index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/AbstractTripleReactorPublisher.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.reactive; import org.apache.dubbo.rpc.protocol.tri.CancelableStreamObserver; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; /** * The middle layer between {@link org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver} and Reactive API. <p> * 1. passing the data received by CallStreamObserver to Reactive consumer <br> * 2. passing the request of Reactive API to CallStreamObserver */ public abstract class AbstractTripleReactorPublisher<T> extends CancelableStreamObserver<T> implements Publisher<T>, Subscription { private boolean canRequest; private long requested; // weather publisher has been subscribed private final AtomicBoolean SUBSCRIBED = new AtomicBoolean(); private volatile Subscriber<? super T> downstream; protected volatile CallStreamObserver<?> subscription; private final AtomicBoolean HAS_SUBSCRIPTION = new AtomicBoolean(); // cancel status private volatile boolean isCancelled; // complete status private volatile boolean isDone; // to help bind TripleSubscriber private volatile Consumer<CallStreamObserver<?>> onSubscribe; private volatile Runnable shutdownHook; private final AtomicBoolean CALLED_SHUT_DOWN_HOOK = new AtomicBoolean(); public AbstractTripleReactorPublisher() {} public AbstractTripleReactorPublisher(Consumer<CallStreamObserver<?>> onSubscribe, Runnable shutdownHook) { this.onSubscribe = onSubscribe; this.shutdownHook = shutdownHook; } protected void onSubscribe(final CallStreamObserver<?> subscription) { if (subscription != null && this.subscription == null && HAS_SUBSCRIPTION.compareAndSet(false, true)) { this.subscription = subscription; subscription.disableAutoFlowControl(); if (onSubscribe != null) { onSubscribe.accept(subscription); } return; } throw new IllegalStateException(getClass().getSimpleName() + " supports only a single subscription"); } @Override public void onNext(T data) { if (isDone || isCancelled) { return; } downstream.onNext(data); } @Override public void onError(Throwable throwable) { if (isDone || isCancelled) { return; } isDone = true; downstream.onError(throwable); doPostShutdown(); } @Override public void onCompleted() { if (isDone || isCancelled) { return; } isDone = true; downstream.onComplete(); doPostShutdown(); } private void doPostShutdown() { Runnable r = shutdownHook; // CAS to confirm shutdownHook will be run only once. if (r != null && CALLED_SHUT_DOWN_HOOK.compareAndSet(false, true)) { shutdownHook = null; r.run(); } } @Override public void subscribe(Subscriber<? super T> subscriber) { if (subscriber == null) { throw new NullPointerException(); } if (SUBSCRIBED.compareAndSet(false, true)) { subscriber.onSubscribe(this); this.downstream = subscriber; if (isCancelled) { this.downstream = null; } } } @Override public void request(long l) { synchronized (this) { if (SUBSCRIBED.get() && canRequest) { subscription.request(l >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) l); } else { requested += l; } } } @Override public void startRequest() { synchronized (this) { if (!canRequest) { canRequest = true; long count = requested; subscription.request(count >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) count); } } } @Override public void cancel() { if (isCancelled) { return; } isCancelled = true; doPostShutdown(); } public boolean isCancelled() { return isCancelled; } }
8,200
0
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorClientCalls.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.reactive.calls; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.reactive.ClientTripleReactorPublisher; import org.apache.dubbo.reactive.ClientTripleReactorSubscriber; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.StubMethodDescriptor; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import org.apache.dubbo.rpc.stub.StubInvocationUtil; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** * A collection of methods to convert client-side Reactor calls to stream calls. */ public final class ReactorClientCalls { private ReactorClientCalls() {} /** * Implements a unary -> unary call as Mono -> Mono * * @param invoker invoker * @param monoRequest the mono with request * @param methodDescriptor the method descriptor * @return the mono with response */ public static <TRequest, TResponse, TInvoker> Mono<TResponse> oneToOne( Invoker<TInvoker> invoker, Mono<TRequest> monoRequest, StubMethodDescriptor methodDescriptor) { try { return Mono.create(emitter -> monoRequest.subscribe( request -> StubInvocationUtil.unaryCall( invoker, methodDescriptor, request, new StreamObserver<TResponse>() { @Override public void onNext(TResponse tResponse) { emitter.success(tResponse); } @Override public void onError(Throwable throwable) { emitter.error(throwable); } @Override public void onCompleted() { // Do nothing } }), emitter::error)); } catch (Throwable throwable) { return Mono.error(throwable); } } /** * Implements a unary -> stream call as Mono -> Flux * * @param invoker invoker * @param monoRequest the mono with request * @param methodDescriptor the method descriptor * @return the flux with response */ public static <TRequest, TResponse, TInvoker> Flux<TResponse> oneToMany( Invoker<TInvoker> invoker, Mono<TRequest> monoRequest, StubMethodDescriptor methodDescriptor) { try { return monoRequest.flatMapMany(request -> { ClientTripleReactorPublisher<TResponse> clientPublisher = new ClientTripleReactorPublisher<>(); StubInvocationUtil.serverStreamCall(invoker, methodDescriptor, request, clientPublisher); return clientPublisher; }); } catch (Throwable throwable) { return Flux.error(throwable); } } /** * Implements a stream -> unary call as Flux -> Mono * * @param invoker invoker * @param requestFlux the flux with request * @param methodDescriptor the method descriptor * @return the mono with response */ public static <TRequest, TResponse, TInvoker> Mono<TResponse> manyToOne( Invoker<TInvoker> invoker, Flux<TRequest> requestFlux, StubMethodDescriptor methodDescriptor) { try { ClientTripleReactorSubscriber<TRequest> clientSubscriber = requestFlux.subscribeWith(new ClientTripleReactorSubscriber<>()); ClientTripleReactorPublisher<TResponse> clientPublisher = new ClientTripleReactorPublisher<>( s -> clientSubscriber.subscribe((CallStreamObserver<TRequest>) s), clientSubscriber::cancel); return Mono.from(clientPublisher) .doOnSubscribe(dummy -> StubInvocationUtil.biOrClientStreamCall(invoker, methodDescriptor, clientPublisher)); } catch (Throwable throwable) { return Mono.error(throwable); } } /** * Implements a stream -> stream call as Flux -> Flux * * @param invoker invoker * @param requestFlux the flux with request * @param methodDescriptor the method descriptor * @return the flux with response */ public static <TRequest, TResponse, TInvoker> Flux<TResponse> manyToMany( Invoker<TInvoker> invoker, Flux<TRequest> requestFlux, StubMethodDescriptor methodDescriptor) { try { ClientTripleReactorSubscriber<TRequest> clientSubscriber = requestFlux.subscribeWith(new ClientTripleReactorSubscriber<>()); ClientTripleReactorPublisher<TResponse> clientPublisher = new ClientTripleReactorPublisher<>( s -> clientSubscriber.subscribe((CallStreamObserver<TRequest>) s), clientSubscriber::cancel); return Flux.from(clientPublisher) .doOnSubscribe(dummy -> StubInvocationUtil.biOrClientStreamCall(invoker, methodDescriptor, clientPublisher)); } catch (Throwable throwable) { return Flux.error(throwable); } } }
8,201
0
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/calls/ReactorServerCalls.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.reactive.calls; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.reactive.ServerTripleReactorPublisher; import org.apache.dubbo.reactive.ServerTripleReactorSubscriber; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import org.apache.dubbo.rpc.protocol.tri.observer.ServerCallToObserverAdapter; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** * A collection of methods to convert server-side stream calls to Reactor calls. */ public final class ReactorServerCalls { private ReactorServerCalls() {} /** * Implements a unary -> unary call as Mono -> Mono * * @param request request * @param responseObserver response StreamObserver * @param func service implementation */ public static <T, R> void oneToOne(T request, StreamObserver<R> responseObserver, Function<Mono<T>, Mono<R>> func) { func.apply(Mono.just(request)).subscribe(res -> { CompletableFuture.completedFuture(res).whenComplete((r, t) -> { if (t != null) { responseObserver.onError(t); } else { responseObserver.onNext(r); responseObserver.onCompleted(); } }); }); } /** * Implements a unary -> stream call as Mono -> Flux * * @param request request * @param responseObserver response StreamObserver * @param func service implementation */ public static <T, R> void oneToMany( T request, StreamObserver<R> responseObserver, Function<Mono<T>, Flux<R>> func) { try { Flux<R> response = func.apply(Mono.just(request)); ServerTripleReactorSubscriber<R> subscriber = response.subscribeWith(new ServerTripleReactorSubscriber<>()); subscriber.subscribe((ServerCallToObserverAdapter<R>) responseObserver); } catch (Throwable throwable) { responseObserver.onError(throwable); } } /** * Implements a stream -> unary call as Flux -> Mono * * @param responseObserver response StreamObserver * @param func service implementation * @return request StreamObserver */ public static <T, R> StreamObserver<T> manyToOne( StreamObserver<R> responseObserver, Function<Flux<T>, Mono<R>> func) { ServerTripleReactorPublisher<T> serverPublisher = new ServerTripleReactorPublisher<T>((CallStreamObserver<R>) responseObserver); try { Mono<R> responseMono = func.apply(Flux.from(serverPublisher)); responseMono.subscribe( value -> { // Don't try to respond if the server has already canceled the request if (!serverPublisher.isCancelled()) { responseObserver.onNext(value); } }, throwable -> { // Don't try to respond if the server has already canceled the request if (!serverPublisher.isCancelled()) { responseObserver.onError(throwable); } }, responseObserver::onCompleted); serverPublisher.startRequest(); } catch (Throwable throwable) { responseObserver.onError(throwable); } return serverPublisher; } /** * Implements a stream -> stream call as Flux -> Flux * * @param responseObserver response StreamObserver * @param func service implementation * @return request StreamObserver */ public static <T, R> StreamObserver<T> manyToMany( StreamObserver<R> responseObserver, Function<Flux<T>, Flux<R>> func) { // responseObserver is also a subscription of publisher, we can use it to request more data ServerTripleReactorPublisher<T> serverPublisher = new ServerTripleReactorPublisher<T>((CallStreamObserver<R>) responseObserver); try { Flux<R> responseFlux = func.apply(Flux.from(serverPublisher)); ServerTripleReactorSubscriber<R> serverSubscriber = responseFlux.subscribeWith(new ServerTripleReactorSubscriber<>()); serverSubscriber.subscribe((CallStreamObserver<R>) responseObserver); serverPublisher.startRequest(); } catch (Throwable throwable) { responseObserver.onError(throwable); } return serverPublisher; } }
8,202
0
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/ManyToOneMethodHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.reactive.handler; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.reactive.calls.ReactorServerCalls; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import org.apache.dubbo.rpc.stub.StubMethodHandler; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** * The handler of ManyToOne() method for stub invocation. */ public class ManyToOneMethodHandler<T, R> implements StubMethodHandler<T, R> { private final Function<Flux<T>, Mono<R>> func; public ManyToOneMethodHandler(Function<Flux<T>, Mono<R>> func) { this.func = func; } @SuppressWarnings("unchecked") @Override public CompletableFuture<StreamObserver<T>> invoke(Object[] arguments) { CallStreamObserver<R> responseObserver = (CallStreamObserver<R>) arguments[0]; StreamObserver<T> requestObserver = ReactorServerCalls.manyToOne(responseObserver, func); return CompletableFuture.completedFuture(requestObserver); } }
8,203
0
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToManyMethodHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.reactive.handler; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.reactive.calls.ReactorServerCalls; import org.apache.dubbo.rpc.stub.StubMethodHandler; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** * The handler of OneToMany() method for stub invocation. */ public class OneToManyMethodHandler<T, R> implements StubMethodHandler<T, R> { private final Function<Mono<T>, Flux<R>> func; public OneToManyMethodHandler(Function<Mono<T>, Flux<R>> func) { this.func = func; } @SuppressWarnings("unchecked") @Override public CompletableFuture<?> invoke(Object[] arguments) { T request = (T) arguments[0]; StreamObserver<R> responseObserver = (StreamObserver<R>) arguments[1]; ReactorServerCalls.oneToMany(request, responseObserver, func); return CompletableFuture.completedFuture(null); } }
8,204
0
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/OneToOneMethodHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.reactive.handler; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.reactive.calls.ReactorServerCalls; import org.apache.dubbo.rpc.stub.FutureToObserverAdaptor; import org.apache.dubbo.rpc.stub.StubMethodHandler; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import reactor.core.publisher.Mono; /** * The handler of OneToOne() method for stub invocation. */ public class OneToOneMethodHandler<T, R> implements StubMethodHandler<T, R> { private final Function<Mono<T>, Mono<R>> func; public OneToOneMethodHandler(Function<Mono<T>, Mono<R>> func) { this.func = func; } @SuppressWarnings("unchecked") @Override public CompletableFuture<R> invoke(Object[] arguments) { T request = (T) arguments[0]; CompletableFuture<R> future = new CompletableFuture<>(); StreamObserver<R> responseObserver = new FutureToObserverAdaptor<>(future); ReactorServerCalls.oneToOne(request, responseObserver, func); return future; } }
8,205
0
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive
Create_ds/dubbo/dubbo-plugin/dubbo-reactive/src/main/java/org/apache/dubbo/reactive/handler/ManyToManyMethodHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.reactive.handler; import org.apache.dubbo.common.stream.StreamObserver; import org.apache.dubbo.reactive.calls.ReactorServerCalls; import org.apache.dubbo.rpc.protocol.tri.observer.CallStreamObserver; import org.apache.dubbo.rpc.stub.StubMethodHandler; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import reactor.core.publisher.Flux; /** * The handler of ManyToMany() method for stub invocation. */ public class ManyToManyMethodHandler<T, R> implements StubMethodHandler<T, R> { private final Function<Flux<T>, Flux<R>> func; public ManyToManyMethodHandler(Function<Flux<T>, Flux<R>> func) { this.func = func; } @SuppressWarnings("unchecked") @Override public CompletableFuture<StreamObserver<T>> invoke(Object[] arguments) { CallStreamObserver<R> responseObserver = (CallStreamObserver<R>) arguments[0]; StreamObserver<T> requestObserver = ReactorServerCalls.manyToMany(responseObserver, func); return CompletableFuture.completedFuture(requestObserver); } }
8,206
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/DemoServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos; public class DemoServiceImpl implements DemoService { @Override public String echo(String str) { return "hello world"; } }
8,207
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/DemoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos; public interface DemoService { String echo(String str); }
8,208
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TTableTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.textui; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; class TTableTest { @Test void test1() throws Exception { TTable table = new TTable(4); table.addRow(1, "one", "uno", "un"); table.addRow(2, "two", "dos", "deux"); String result = table.rendering(); String expected = "+-+---+---+----+" + System.lineSeparator() + "|1|one|uno|un |" + System.lineSeparator() + "+-+---+---+----+" + System.lineSeparator() + "|2|two|dos|deux|" + System.lineSeparator() + "+-+---+---+----+" + System.lineSeparator(); assertThat(result, equalTo(expected)); System.out.println(result); } @Test void test2() throws Exception { TTable table = new TTable(new TTable.ColumnDefine[] { new TTable.ColumnDefine(5, true, TTable.Align.LEFT), new TTable.ColumnDefine(10, false, TTable.Align.MIDDLE), new TTable.ColumnDefine(10, false, TTable.Align.RIGHT) }); table.addRow(1, "abcde", "ABCDE"); String result = table.rendering(); String expected = "+-+----------+----------+" + System.lineSeparator() + "|1| abcde | ABCDE|" + System.lineSeparator() + "+-+----------+----------+" + System.lineSeparator(); assertThat(result, equalTo(expected)); System.out.println(result); } }
8,209
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TTreeTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.textui; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; class TTreeTest { @Test void test() throws Exception { TTree tree = new TTree(false, "root"); tree.begin("one").begin("ONE").end().end(); tree.begin("two").begin("TWO").end().begin("2").end().end(); tree.begin("three").end(); String result = tree.rendering(); String expected = "`---+root\n" + " +---+one\n" + " | `---ONE\n" + " +---+two\n" + " | +---TWO\n" + " | `---2\n" + " `---three\n"; assertThat(result, equalTo(expected)); System.out.println(result); } }
8,210
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TLadderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.textui; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; class TLadderTest { @Test void testRendering() throws Exception { TLadder ladder = new TLadder(); ladder.addItem("1"); ladder.addItem("2"); ladder.addItem("3"); ladder.addItem("4"); String result = ladder.rendering(); String expected = "1" + System.lineSeparator() + " `-2" + System.lineSeparator() + " `-3" + System.lineSeparator() + " `-4" + System.lineSeparator(); assertThat(result, equalTo(expected)); System.out.println(result); } }
8,211
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/textui/TKvTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.textui; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; class TKvTest { @Test void test1() { TKv tKv = new TKv( new TTable.ColumnDefine(TTable.Align.RIGHT), new TTable.ColumnDefine(10, false, TTable.Align.LEFT)); tKv.add("KEY-1", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); tKv.add("KEY-2", "1234567890"); tKv.add("KEY-3", "1234567890"); TTable tTable = new TTable(new TTable.ColumnDefine[] { new TTable.ColumnDefine(), new TTable.ColumnDefine(20, false, TTable.Align.LEFT) }); String kv = tKv.rendering(); assertThat(kv, containsString("ABCDEFGHIJ" + System.lineSeparator())); assertThat(kv, containsString("KLMNOPQRST" + System.lineSeparator())); assertThat(kv, containsString("UVWXYZ" + System.lineSeparator())); tTable.addRow("OPTIONS", kv); String table = tTable.rendering(); assertThat(table, containsString("|OPTIONS|")); assertThat(table, containsString("|KEY-3")); System.out.println(table); } @Test void test2() throws Exception { TKv tKv = new TKv(); tKv.add("KEY-1", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); tKv.add("KEY-2", "1234567890"); tKv.add("KEY-3", "1234567890"); String kv = tKv.rendering(); assertThat(kv, containsString("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); System.out.println(kv); } }
8,212
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.qos.legacy.service.DemoService; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.telnet.TelnetHandler; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; /** * ChangeTelnetHandlerTest.java */ class ChangeTelnetHandlerTest { private static TelnetHandler change = new ChangeTelnetHandler(); private Channel mockChannel; private Invoker<DemoService> mockInvoker; @AfterAll public static void tearDown() {} @SuppressWarnings("unchecked") @BeforeEach public void setUp() { mockChannel = mock(Channel.class); mockInvoker = mock(Invoker.class); given(mockChannel.getAttribute("telnet.service")) .willReturn("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); mockChannel.setAttribute("telnet.service", "DemoService"); givenLastCall(); mockChannel.setAttribute("telnet.service", "org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); givenLastCall(); mockChannel.setAttribute("telnet.service", "demo"); givenLastCall(); mockChannel.removeAttribute("telnet.service"); givenLastCall(); given(mockInvoker.getInterface()).willReturn(DemoService.class); given(mockInvoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:20884/demo")); } private void givenLastCall() {} @AfterEach public void after() { FrameworkModel.destroyAll(); reset(mockChannel, mockInvoker); } @Test void testChangeSimpleName() throws RemotingException { ExtensionLoader.getExtensionLoader(Protocol.class) .getExtension(DubboProtocol.NAME) .export(mockInvoker); String result = change.telnet(mockChannel, "DemoService"); assertEquals("Used the DemoService as default.\r\nYou can cancel default service by command: cd /", result); } @Test void testChangeName() throws RemotingException { ExtensionLoader.getExtensionLoader(Protocol.class) .getExtension(DubboProtocol.NAME) .export(mockInvoker); String result = change.telnet(mockChannel, "org.apache.dubbo.qos.legacy.service.DemoService"); assertEquals( "Used the org.apache.dubbo.qos.legacy.service.DemoService as default.\r\nYou can cancel default service by command: cd /", result); } @Test void testChangePath() throws RemotingException { ExtensionLoader.getExtensionLoader(Protocol.class) .getExtension(DubboProtocol.NAME) .export(mockInvoker); String result = change.telnet(mockChannel, "demo"); assertEquals("Used the demo as default.\r\nYou can cancel default service by command: cd /", result); } @Test void testChangeMessageNull() throws RemotingException { String result = change.telnet(mockChannel, null); assertEquals("Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService", result); } @Test void testChangeServiceNotExport() throws RemotingException { String result = change.telnet(mockChannel, "demo"); assertEquals("No such service demo", result); } @Test void testChangeCancel() throws RemotingException { String result = change.telnet(mockChannel, ".."); assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result); } @Test void testChangeCancel2() throws RemotingException { String result = change.telnet(mockChannel, "/"); assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result); } }
8,213
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/ProtocolUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; /** * TODO Comment of ProtocolUtils */ public class ProtocolUtils { public static <T> T refer(Class<T> type, String url) { return refer(type, URL.valueOf(url)); } public static <T> T refer(Class<T> type, URL url) { Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); return proxy.getProxy(protocol.refer(type, url)); } public static <T> Exporter<T> export(T instance, Class<T> type, String url) { return export(instance, type, URL.valueOf(url)); } public static <T> Exporter<T> export(T instance, Class<T> type, URL url) { Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); return protocol.export(proxy.getInvoker(instance, type, url)); } public static void closeAll() { DubboProtocol.getDubboProtocol().destroy(); ExtensionLoader.getExtensionLoader(Protocol.class).destroy(); FrameworkModel.destroyAll(); } }
8,214
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/LogTelnetHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.telnet.TelnetHandler; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; /** * LogTelnetHandlerTest.java */ class LogTelnetHandlerTest { private static TelnetHandler log = new LogTelnetHandler(); private Channel mockChannel; @Test void testChangeLogLevel() throws RemotingException { mockChannel = mock(Channel.class); String result = log.telnet(mockChannel, "error"); assertTrue(result.contains("\r\nCURRENT LOG LEVEL:ERROR")); String result2 = log.telnet(mockChannel, "warn"); assertTrue(result2.contains("\r\nCURRENT LOG LEVEL:WARN")); } @Test void testPrintLog() throws RemotingException { mockChannel = mock(Channel.class); String result = log.telnet(mockChannel, "100"); assertTrue(result.contains("CURRENT LOG APPENDER")); } }
8,215
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/TraceTelnetHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.qos.legacy.service.DemoService; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.telnet.TelnetHandler; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; import org.apache.dubbo.rpc.protocol.dubbo.filter.TraceFilter; import java.lang.reflect.Field; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; class TraceTelnetHandlerTest { private TelnetHandler handler; private Channel mockChannel; private Invoker<DemoService> mockInvoker; private URL url = URL.valueOf("dubbo://127.0.0.1:20884/demo"); @BeforeEach public void setUp() { handler = new TraceTelnetHandler(); mockChannel = mock(Channel.class); mockInvoker = mock(Invoker.class); given(mockInvoker.getInterface()).willReturn(DemoService.class); given(mockInvoker.getUrl()).willReturn(url); } @AfterEach public void tearDown() { reset(mockChannel, mockInvoker); FrameworkModel.destroyAll(); } @Test void testTraceTelnetAddTracer() throws Exception { String method = "sayHello"; String message = "org.apache.dubbo.qos.legacy.service.DemoService sayHello 1"; Class<?> type = DemoService.class; ExtensionLoader.getExtensionLoader(Protocol.class) .getExtension(DubboProtocol.NAME) .export(mockInvoker); handler.telnet(mockChannel, message); String key = type.getName() + "." + method; Field tracers = TraceFilter.class.getDeclaredField("TRACERS"); tracers.setAccessible(true); ConcurrentHashMap<String, Set<Channel>> map = (ConcurrentHashMap<String, Set<Channel>>) tracers.get(new ConcurrentHashMap<String, Set<Channel>>()); Set<Channel> channels = map.getOrDefault(key, null); Assertions.assertNotNull(channels); Assertions.assertTrue(channels.contains(mockChannel)); } }
8,216
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/channel/MockChannel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy.channel; import org.apache.dubbo.common.URL; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.ChannelHandler; import org.apache.dubbo.remoting.RemotingException; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; public class MockChannel implements Channel { public static final String ERROR_WHEN_SEND = "error_when_send"; InetSocketAddress localAddress; InetSocketAddress remoteAddress; private URL remoteUrl; private ChannelHandler handler; private boolean isClosed; private volatile boolean closing; private Map<String, Object> attributes = new HashMap<String, Object>(1); private List<Object> receivedObjects = new LinkedList<>(); private CountDownLatch latch; public MockChannel() {} public MockChannel(URL remoteUrl) { this.remoteUrl = remoteUrl; } public MockChannel(URL remoteUrl, CountDownLatch latch) { this.remoteUrl = remoteUrl; this.latch = latch; } public MockChannel(ChannelHandler handler) { this.handler = handler; } @Override public URL getUrl() { return remoteUrl; } @Override public ChannelHandler getChannelHandler() { return handler; } @Override public InetSocketAddress getLocalAddress() { return localAddress; } @Override public void send(Object message) throws RemotingException { if (remoteUrl.getParameter(ERROR_WHEN_SEND, Boolean.FALSE)) { throw new RemotingException(localAddress, remoteAddress, "mock error"); } else { receivedObjects.add(message); if (latch != null) { latch.countDown(); } } } @Override public void send(Object message, boolean sent) throws RemotingException { send(message); } @Override public void close() { close(0); } @Override public void close(int timeout) { isClosed = true; } @Override public void startClose() { closing = true; } @Override public boolean isClosed() { return isClosed; } @Override public InetSocketAddress getRemoteAddress() { return remoteAddress; } @Override public boolean isConnected() { return isClosed; } @Override public boolean hasAttribute(String key) { return attributes.containsKey(key); } @Override public Object getAttribute(String key) { return attributes.get(key); } @Override public void setAttribute(String key, Object value) { attributes.put(key, value); } @Override public void removeAttribute(String key) { attributes.remove(key); } public List<Object> getReceivedObjects() { return receivedObjects; } }
8,217
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/Type.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy.service; public enum Type { High, Normal, Lower }
8,218
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/CustomArgument.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy.service; import java.io.Serializable; @SuppressWarnings("serial") public class CustomArgument implements Serializable { Type type; String name; public CustomArgument() {} public CustomArgument(Type type, String name) { super(); this.type = type; this.name = name; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
8,219
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/Man.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy.service; import java.io.Serializable; /** * Man.java */ public class Man implements Serializable { private static final long serialVersionUID = 1L; private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
8,220
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/DemoServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy.service; import org.apache.dubbo.rpc.RpcContext; import java.util.Map; import java.util.Set; /** * DemoServiceImpl */ public class DemoServiceImpl implements DemoService { public DemoServiceImpl() { super(); } public void sayHello(String name) { System.out.println("hello " + name); } public String echo(String text) { return text; } public Map echo(Map map) { return map; } public long timestamp() { return System.currentTimeMillis(); } public String getThreadName() { return Thread.currentThread().getName(); } public int getSize(String[] strs) { if (strs == null) return -1; return strs.length; } public int getSize(Object[] os) { if (os == null) return -1; return os.length; } public Object invoke(String service, String method) throws Exception { System.out.println("RpcContext.getServerAttachment().getRemoteHost()=" + RpcContext.getServiceContext().getRemoteHost()); return service + ":" + method; } public Type enumlength(Type... types) { if (types.length == 0) return Type.Lower; return types[0]; } public Type getType(Type type) { return type; } public int stringLength(String str) { return str.length(); } public String get(CustomArgument arg1) { return arg1.toString(); } public byte getbyte(byte arg) { return arg; } public Person gerPerson(Person person) { return person; } public Set<String> keys(Map<String, String> map) { return map == null ? null : map.keySet(); } public void nonSerializedParameter(NonSerialized ns) {} public NonSerialized returnNonSerialized() { return new NonSerialized(); } public long add(int a, long b) { return a + b; } @Override public int getPerson(Person person) { return person.getAge(); } @Override public int getPerson(Person person1, Person person2) { return person1.getAge() + person2.getAge(); } @Override public String getPerson(Man man) { return man.getName(); } @Override public String getRemoteApplicationName() { return RpcContext.getServiceContext().getRemoteApplicationName(); } @Override public Map<Integer, Object> getMap(Map<Integer, Object> map) { return map; } }
8,221
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/Person.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy.service; import java.io.Serializable; /** * Person.java */ public class Person implements Serializable { private static final long serialVersionUID = 1L; private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
8,222
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/NonSerialized.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy.service; /** * NonSerialized */ public class NonSerialized {}
8,223
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/DemoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy.service; import java.util.Map; import java.util.Set; /** * <code>TestService</code> */ public interface DemoService { void sayHello(String name); Set<String> keys(Map<String, String> map); String echo(String text); Map echo(Map map); long timestamp(); String getThreadName(); int getSize(String[] strs); int getSize(Object[] os); Object invoke(String service, String method) throws Exception; int stringLength(String str); Type enumlength(Type... types); Type getType(Type type); String get(CustomArgument arg1); byte getbyte(byte arg); void nonSerializedParameter(NonSerialized ns); NonSerialized returnNonSerialized(); long add(int a, long b); int getPerson(Person person); int getPerson(Person person1, Person perso2); String getPerson(Man man); String getRemoteApplicationName(); Map<Integer, Object> getMap(Map<Integer, Object> map); }
8,224
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy.service.generic; /** * DemoException */ public class DemoException extends Exception { private static final long serialVersionUID = -8213943026163641747L; public DemoException() { super(); } public DemoException(String message, Throwable cause) { super(message, cause); } public DemoException(String message) { super(message); } public DemoException(Throwable cause) { super(cause); } }
8,225
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/User.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy.service.generic; import java.io.Serializable; /** * User */ public class User implements Serializable { private static final long serialVersionUID = 1L; private String name; public User() {} public User(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { return name == null ? -1 : name.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof User)) { return false; } User other = (User) obj; if (this == other) { return true; } if (name != null && other.name != null) { return name.equals(other.name); } return false; } }
8,226
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/GenericServiceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy.service.generic; import org.apache.dubbo.common.beanutil.JavaBeanAccessor; import org.apache.dubbo.common.beanutil.JavaBeanDescriptor; import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.rpc.service.GenericException; import org.apache.dubbo.rpc.service.GenericService; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; /** * GenericServiceTest */ @Disabled("Keeps failing on Travis, but can not be reproduced locally.") class GenericServiceTest { @Test void testGenericServiceException() { ServiceConfig<GenericService> service = new ServiceConfig<GenericService>(); service.setInterface(DemoService.class.getName()); service.setRef(new GenericService() { public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException { if ("sayName".equals(method)) { return "Generic " + args[0]; } if ("throwDemoException".equals(method)) { throw new GenericException(DemoException.class.getName(), "Generic"); } if ("getUsers".equals(method)) { return args[0]; } return null; } }); ReferenceConfig<DemoService> reference = new ReferenceConfig<DemoService>(); reference.setInterface(DemoService.class); reference.setUrl("dubbo://127.0.0.1:29581?generic=true&timeout=3000"); DubboBootstrap bootstrap = DubboBootstrap.getInstance() .application(new ApplicationConfig("generic-test")) .registry(new RegistryConfig("N/A")) .protocol(new ProtocolConfig("dubbo", 29581)) .service(service) .reference(reference); bootstrap.start(); try { DemoService demoService = bootstrap.getCache().get(reference); // say name Assertions.assertEquals("Generic Haha", demoService.sayName("Haha")); // get users List<User> users = new ArrayList<User>(); users.add(new User("Aaa")); users = demoService.getUsers(users); Assertions.assertEquals("Aaa", users.get(0).getName()); // throw demo exception try { demoService.throwDemoException(); Assertions.fail(); } catch (DemoException e) { Assertions.assertEquals("Generic", e.getMessage()); } } finally { bootstrap.stop(); } } @SuppressWarnings("unchecked") @Test void testGenericReferenceException() { ServiceConfig<DemoService> service = new ServiceConfig<DemoService>(); service.setInterface(DemoService.class.getName()); service.setRef(new DemoServiceImpl()); ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>(); reference.setInterface(DemoService.class); reference.setUrl("dubbo://127.0.0.1:29581?scope=remote&timeout=3000"); reference.setGeneric(true); DubboBootstrap bootstrap = DubboBootstrap.getInstance() .application(new ApplicationConfig("generic-test")) .registry(new RegistryConfig("N/A")) .protocol(new ProtocolConfig("dubbo", 29581)) .service(service) .reference(reference); bootstrap.start(); try { GenericService genericService = bootstrap.getCache().get(reference); List<Map<String, Object>> users = new ArrayList<Map<String, Object>>(); Map<String, Object> user = new HashMap<String, Object>(); user.put("class", "org.apache.dubbo.config.api.User"); user.put("name", "actual.provider"); users.add(user); users = (List<Map<String, Object>>) genericService.$invoke("getUsers", new String[] {List.class.getName()}, new Object[] {users}); Assertions.assertEquals(1, users.size()); Assertions.assertEquals("actual.provider", users.get(0).get("name")); } finally { bootstrap.stop(); } } @Test void testGenericSerializationJava() throws Exception { ServiceConfig<DemoService> service = new ServiceConfig<DemoService>(); service.setInterface(DemoService.class.getName()); DemoServiceImpl ref = new DemoServiceImpl(); service.setRef(ref); ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>(); reference.setInterface(DemoService.class); reference.setUrl("dubbo://127.0.0.1:29581?scope=remote&timeout=3000"); reference.setGeneric(GENERIC_SERIALIZATION_NATIVE_JAVA); DubboBootstrap bootstrap = DubboBootstrap.getInstance() .application(new ApplicationConfig("generic-test")) .registry(new RegistryConfig("N/A")) .protocol(new ProtocolConfig("dubbo", 29581)) .service(service) .reference(reference); bootstrap.start(); try { GenericService genericService = bootstrap.getCache().get(reference); String name = "kimi"; ByteArrayOutputStream bos = new ByteArrayOutputStream(512); ExtensionLoader.getExtensionLoader(Serialization.class) .getExtension("nativejava") .serialize(null, bos) .writeObject(name); byte[] arg = bos.toByteArray(); Object obj = genericService.$invoke("sayName", new String[] {String.class.getName()}, new Object[] {arg}); Assertions.assertTrue(obj instanceof byte[]); byte[] result = (byte[]) obj; Assertions.assertEquals( ref.sayName(name), ExtensionLoader.getExtensionLoader(Serialization.class) .getExtension("nativejava") .deserialize(null, new ByteArrayInputStream(result)) .readObject() .toString()); // getUsers List<User> users = new ArrayList<User>(); User user = new User(); user.setName(name); users.add(user); bos = new ByteArrayOutputStream(512); ExtensionLoader.getExtensionLoader(Serialization.class) .getExtension("nativejava") .serialize(null, bos) .writeObject(users); obj = genericService.$invoke( "getUsers", new String[] {List.class.getName()}, new Object[] {bos.toByteArray()}); Assertions.assertTrue(obj instanceof byte[]); result = (byte[]) obj; Assertions.assertEquals( users, ExtensionLoader.getExtensionLoader(Serialization.class) .getExtension("nativejava") .deserialize(null, new ByteArrayInputStream(result)) .readObject()); // echo(int) bos = new ByteArrayOutputStream(512); ExtensionLoader.getExtensionLoader(Serialization.class) .getExtension("nativejava") .serialize(null, bos) .writeObject(Integer.MAX_VALUE); obj = genericService.$invoke("echo", new String[] {int.class.getName()}, new Object[] {bos.toByteArray()}); Assertions.assertTrue(obj instanceof byte[]); Assertions.assertEquals( Integer.MAX_VALUE, ExtensionLoader.getExtensionLoader(Serialization.class) .getExtension("nativejava") .deserialize(null, new ByteArrayInputStream((byte[]) obj)) .readObject()); } finally { bootstrap.stop(); } } @Test void testGenericInvokeWithBeanSerialization() { ServiceConfig<DemoService> service = new ServiceConfig<DemoService>(); service.setInterface(DemoService.class); DemoServiceImpl impl = new DemoServiceImpl(); service.setRef(impl); ReferenceConfig<GenericService> reference = new ReferenceConfig<GenericService>(); reference.setInterface(DemoService.class); reference.setUrl("dubbo://127.0.0.1:29581?scope=remote&timeout=3000"); reference.setGeneric(GENERIC_SERIALIZATION_BEAN); DubboBootstrap bootstrap = DubboBootstrap.getInstance() .application(new ApplicationConfig("generic-test")) .registry(new RegistryConfig("N/A")) .protocol(new ProtocolConfig("dubbo", 29581)) .service(service) .reference(reference); bootstrap.start(); try { GenericService genericService = bootstrap.getCache().get(reference); User user = new User(); user.setName("zhangsan"); List<User> users = new ArrayList<User>(); users.add(user); Object result = genericService.$invoke("getUsers", new String[] {ReflectUtils.getName(List.class)}, new Object[] { JavaBeanSerializeUtil.serialize(users, JavaBeanAccessor.METHOD) }); Assertions.assertTrue(result instanceof JavaBeanDescriptor); JavaBeanDescriptor descriptor = (JavaBeanDescriptor) result; Assertions.assertTrue(descriptor.isCollectionType()); Assertions.assertEquals(1, descriptor.propertySize()); descriptor = (JavaBeanDescriptor) descriptor.getProperty(0); Assertions.assertTrue(descriptor.isBeanType()); Assertions.assertEquals( user.getName(), ((JavaBeanDescriptor) descriptor.getProperty("name")).getPrimitiveProperty()); } finally { bootstrap.stop(); } } @Test void testGenericImplementationWithBeanSerialization() { final AtomicReference reference = new AtomicReference(); ServiceConfig<GenericService> service = new ServiceConfig<GenericService>(); service.setInterface(DemoService.class.getName()); service.setRef(new GenericService() { public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException { if ("getUsers".equals(method)) { GenericParameter arg = new GenericParameter(); arg.method = method; arg.parameterTypes = parameterTypes; arg.arguments = args; reference.set(arg); return args[0]; } if ("sayName".equals(method)) { return null; } return args; } }); ReferenceConfig<DemoService> ref = null; ref = new ReferenceConfig<DemoService>(); ref.setInterface(DemoService.class); ref.setUrl("dubbo://127.0.0.1:29581?scope=remote&generic=bean&timeout=3000"); DubboBootstrap bootstrap = DubboBootstrap.getInstance() .application(new ApplicationConfig("generic-test")) .registry(new RegistryConfig("N/A")) .protocol(new ProtocolConfig("dubbo", 29581)) .service(service) .reference(ref); bootstrap.start(); try { DemoService demoService = bootstrap.getCache().get(ref); User user = new User(); user.setName("zhangsan"); List<User> users = new ArrayList<User>(); users.add(user); List<User> result = demoService.getUsers(users); Assertions.assertEquals(users.size(), result.size()); Assertions.assertEquals(user.getName(), result.get(0).getName()); GenericParameter gp = (GenericParameter) reference.get(); Assertions.assertEquals("getUsers", gp.method); Assertions.assertEquals(1, gp.parameterTypes.length); Assertions.assertEquals(ReflectUtils.getName(List.class), gp.parameterTypes[0]); Assertions.assertEquals(1, gp.arguments.length); Assertions.assertTrue(gp.arguments[0] instanceof JavaBeanDescriptor); JavaBeanDescriptor descriptor = (JavaBeanDescriptor) gp.arguments[0]; Assertions.assertTrue(descriptor.isCollectionType()); Assertions.assertEquals(ArrayList.class.getName(), descriptor.getClassName()); Assertions.assertEquals(1, descriptor.propertySize()); descriptor = (JavaBeanDescriptor) descriptor.getProperty(0); Assertions.assertTrue(descriptor.isBeanType()); Assertions.assertEquals(User.class.getName(), descriptor.getClassName()); Assertions.assertEquals( user.getName(), ((JavaBeanDescriptor) descriptor.getProperty("name")).getPrimitiveProperty()); Assertions.assertNull(demoService.sayName("zhangsan")); } finally { bootstrap.stop(); } } protected static class GenericParameter { String method; String[] parameterTypes; Object[] arguments; } }
8,227
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy.service.generic; import java.util.List; /** * DemoServiceImpl */ public class DemoServiceImpl implements DemoService { public String sayName(String name) { return "say:" + name; } public void throwDemoException() throws DemoException { throw new DemoException("DemoServiceImpl"); } public List<User> getUsers(List<User> users) { return users; } public int echo(int i) { return i; } }
8,228
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/legacy/service/generic/DemoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy.service.generic; import java.util.List; /** * DemoService */ public interface DemoService { String sayName(String name); void throwDemoException() throws DemoException; List<User> getUsers(List<User> users); int echo(int i); }
8,229
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/ForeignHostPermitHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server.handler; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.qos.api.QosConfiguration; import java.net.InetAddress; import java.net.InetSocketAddress; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class ForeignHostPermitHandlerTest { @Test void shouldShowIpNotPermittedMsg_GivenAcceptForeignIpFalseAndEmptyWhiteList() throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); Channel channel = mock(Channel.class); when(context.channel()).thenReturn(channel); InetAddress addr = mock(InetAddress.class); when(addr.isLoopbackAddress()).thenReturn(false); InetSocketAddress address = new InetSocketAddress(addr, 12345); when(channel.remoteAddress()).thenReturn(address); ChannelFuture future = mock(ChannelFuture.class); when(context.writeAndFlush(any(ByteBuf.class))).thenReturn(future); ForeignHostPermitHandler handler = new ForeignHostPermitHandler(QosConfiguration.builder() .acceptForeignIp(false) .acceptForeignIpWhitelist(StringUtils.EMPTY_STRING) .anonymousAccessPermissionLevel(PermissionLevel.NONE.name()) .build()); handler.handlerAdded(context); ArgumentCaptor<ByteBuf> captor = ArgumentCaptor.forClass(ByteBuf.class); verify(context).writeAndFlush(captor.capture()); assertThat( new String(captor.getValue().array()), containsString("Foreign Ip Not Permitted, Consider Config It In Whitelist")); verify(future).addListener(ChannelFutureListener.CLOSE); } @Test void shouldShowIpNotPermittedMsg_GivenAcceptForeignIpFalseAndNotMatchWhiteList() throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); Channel channel = mock(Channel.class); when(context.channel()).thenReturn(channel); InetAddress addr = mock(InetAddress.class); when(addr.isLoopbackAddress()).thenReturn(false); when(addr.getHostAddress()).thenReturn("179.23.44.1"); InetSocketAddress address = new InetSocketAddress(addr, 12345); when(channel.remoteAddress()).thenReturn(address); ChannelFuture future = mock(ChannelFuture.class); when(context.writeAndFlush(any(ByteBuf.class))).thenReturn(future); ForeignHostPermitHandler handler = new ForeignHostPermitHandler(QosConfiguration.builder() .acceptForeignIp(false) .acceptForeignIpWhitelist("175.23.44.1 , 192.168.1.192/26") .anonymousAccessPermissionLevel(PermissionLevel.NONE.name()) .build()); handler.handlerAdded(context); ArgumentCaptor<ByteBuf> captor = ArgumentCaptor.forClass(ByteBuf.class); verify(context).writeAndFlush(captor.capture()); assertThat( new String(captor.getValue().array()), containsString("Foreign Ip Not Permitted, Consider Config It In Whitelist")); verify(future).addListener(ChannelFutureListener.CLOSE); } @Test void shouldNotShowIpNotPermittedMsg_GivenAcceptForeignIpFalseAndMatchWhiteList() throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); Channel channel = mock(Channel.class); when(context.channel()).thenReturn(channel); InetAddress addr = mock(InetAddress.class); when(addr.isLoopbackAddress()).thenReturn(false); when(addr.getHostAddress()).thenReturn("175.23.44.1"); InetSocketAddress address = new InetSocketAddress(addr, 12345); when(channel.remoteAddress()).thenReturn(address); ForeignHostPermitHandler handler = new ForeignHostPermitHandler(QosConfiguration.builder() .acceptForeignIp(false) .acceptForeignIpWhitelist("175.23.44.1, 192.168.1.192/26 ") .build()); handler.handlerAdded(context); verify(context, never()).writeAndFlush(any()); } @Test void shouldNotShowIpNotPermittedMsg_GivenAcceptForeignIpFalseAndMatchWhiteListRange() throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); Channel channel = mock(Channel.class); when(context.channel()).thenReturn(channel); InetAddress addr = mock(InetAddress.class); when(addr.isLoopbackAddress()).thenReturn(false); when(addr.getHostAddress()).thenReturn("192.168.1.199"); InetSocketAddress address = new InetSocketAddress(addr, 12345); when(channel.remoteAddress()).thenReturn(address); ForeignHostPermitHandler handler = new ForeignHostPermitHandler(QosConfiguration.builder() .acceptForeignIp(false) .acceptForeignIpWhitelist("175.23.44.1, 192.168.1.192/26") .build()); handler.handlerAdded(context); verify(context, never()).writeAndFlush(any()); } @Test void shouldNotShowIpNotPermittedMsg_GivenAcceptForeignIpFalseAndNotMatchWhiteListAndPermissionConfig() throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); Channel channel = mock(Channel.class); when(context.channel()).thenReturn(channel); ChannelFuture future = mock(ChannelFuture.class); when(context.writeAndFlush(any(ByteBuf.class))).thenReturn(future); ForeignHostPermitHandler handler = new ForeignHostPermitHandler(QosConfiguration.builder() .acceptForeignIp(false) .acceptForeignIpWhitelist("175.23.44.1 , 192.168.1.192/26") .anonymousAccessPermissionLevel(PermissionLevel.PROTECTED.name()) .build()); handler.handlerAdded(context); verify(future, never()).addListener(ChannelFutureListener.CLOSE); } }
8,230
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/HttpProcessHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server.handler; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.rpc.model.FrameworkModel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class HttpProcessHandlerTest { @Test void test1() throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); ChannelFuture future = mock(ChannelFuture.class); when(context.writeAndFlush(any(FullHttpResponse.class))).thenReturn(future); HttpRequest message = Mockito.mock(HttpRequest.class); when(message.uri()).thenReturn("test"); HttpProcessHandler handler = new HttpProcessHandler( FrameworkModel.defaultModel(), QosConfiguration.builder().build()); handler.channelRead0(context, message); verify(future).addListener(ChannelFutureListener.CLOSE); ArgumentCaptor<FullHttpResponse> captor = ArgumentCaptor.forClass(FullHttpResponse.class); verify(context).writeAndFlush(captor.capture()); FullHttpResponse response = captor.getValue(); assertThat(response.status().code(), equalTo(404)); } @Test void test2() throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); ChannelFuture future = mock(ChannelFuture.class); when(context.writeAndFlush(any(FullHttpResponse.class))).thenReturn(future); HttpRequest message = Mockito.mock(HttpRequest.class); when(message.uri()).thenReturn("localhost:80/greeting"); when(message.method()).thenReturn(HttpMethod.GET); HttpProcessHandler handler = new HttpProcessHandler( FrameworkModel.defaultModel(), QosConfiguration.builder() .anonymousAccessPermissionLevel(PermissionLevel.NONE.name()) .build()); handler.channelRead0(context, message); verify(future).addListener(ChannelFutureListener.CLOSE); ArgumentCaptor<FullHttpResponse> captor = ArgumentCaptor.forClass(FullHttpResponse.class); verify(context).writeAndFlush(captor.capture()); FullHttpResponse response = captor.getValue(); assertThat(response.status().code(), equalTo(200)); } @Test void test3() throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); ChannelFuture future = mock(ChannelFuture.class); when(context.writeAndFlush(any(FullHttpResponse.class))).thenReturn(future); HttpRequest message = Mockito.mock(HttpRequest.class); when(message.uri()).thenReturn("localhost:80/test"); when(message.method()).thenReturn(HttpMethod.GET); HttpProcessHandler handler = new HttpProcessHandler( FrameworkModel.defaultModel(), QosConfiguration.builder() .anonymousAccessPermissionLevel(PermissionLevel.NONE.name()) .build()); handler.channelRead0(context, message); verify(future).addListener(ChannelFutureListener.CLOSE); ArgumentCaptor<FullHttpResponse> captor = ArgumentCaptor.forClass(FullHttpResponse.class); verify(context).writeAndFlush(captor.capture()); FullHttpResponse response = captor.getValue(); assertThat(response.status().code(), equalTo(404)); } }
8,231
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/QosProcessHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server.handler; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.Collections; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; class QosProcessHandlerTest { @Test void testDecodeHttp() throws Exception { ByteBuf buf = Unpooled.wrappedBuffer(new byte[] {'G'}); ChannelHandlerContext context = Mockito.mock(ChannelHandlerContext.class); ChannelPipeline pipeline = Mockito.mock(ChannelPipeline.class); Mockito.when(context.pipeline()).thenReturn(pipeline); QosProcessHandler handler = new QosProcessHandler( FrameworkModel.defaultModel(), QosConfiguration.builder() .welcome("welcome") .acceptForeignIp(false) .acceptForeignIpWhitelist(StringUtils.EMPTY_STRING) .build()); handler.decode(context, buf, Collections.emptyList()); verify(pipeline).addLast(any(HttpServerCodec.class)); verify(pipeline).addLast(any(HttpObjectAggregator.class)); verify(pipeline).addLast(any(HttpProcessHandler.class)); verify(pipeline).remove(handler); } @Test void testDecodeTelnet() throws Exception { ByteBuf buf = Unpooled.wrappedBuffer(new byte[] {'A'}); ChannelHandlerContext context = Mockito.mock(ChannelHandlerContext.class); ChannelPipeline pipeline = Mockito.mock(ChannelPipeline.class); Mockito.when(context.pipeline()).thenReturn(pipeline); QosProcessHandler handler = new QosProcessHandler( FrameworkModel.defaultModel(), QosConfiguration.builder() .welcome("welcome") .acceptForeignIp(false) .acceptForeignIpWhitelist(StringUtils.EMPTY_STRING) .build()); handler.decode(context, buf, Collections.emptyList()); verify(pipeline).addLast(any(LineBasedFrameDecoder.class)); verify(pipeline).addLast(any(StringDecoder.class)); verify(pipeline).addLast(any(StringEncoder.class)); verify(pipeline).addLast(any(TelnetProcessHandler.class)); verify(pipeline).remove(handler); } }
8,232
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server.handler; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.rpc.model.FrameworkModel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class TelnetProcessHandlerTest { @Test void testPrompt() throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); TelnetProcessHandler handler = new TelnetProcessHandler( FrameworkModel.defaultModel(), QosConfiguration.builder() .anonymousAccessPermissionLevel(PermissionLevel.NONE.name()) .build()); handler.channelRead0(context, ""); verify(context).writeAndFlush(QosProcessHandler.PROMPT); } @Test void testBye() throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); TelnetProcessHandler handler = new TelnetProcessHandler( FrameworkModel.defaultModel(), QosConfiguration.builder().build()); ChannelFuture future = mock(ChannelFuture.class); when(context.writeAndFlush("BYE!\n")).thenReturn(future); handler.channelRead0(context, "quit"); verify(future).addListener(ChannelFutureListener.CLOSE); } @Test void testUnknownCommand() throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); TelnetProcessHandler handler = new TelnetProcessHandler( FrameworkModel.defaultModel(), QosConfiguration.builder().build()); handler.channelRead0(context, "unknown"); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); verify(context, Mockito.atLeastOnce()).writeAndFlush(captor.capture()); assertThat(captor.getAllValues(), contains("unknown :no such command", "\r\ndubbo>")); } @Test void testGreeting() throws Exception { ChannelHandlerContext context = mock(ChannelHandlerContext.class); TelnetProcessHandler handler = new TelnetProcessHandler( FrameworkModel.defaultModel(), QosConfiguration.builder() .anonymousAccessPermissionLevel(PermissionLevel.NONE.name()) .build()); handler.channelRead0(context, "greeting"); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); verify(context).writeAndFlush(captor.capture()); assertThat(captor.getValue(), containsString("greeting")); assertThat(captor.getValue(), containsString("dubbo>")); } }
8,233
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/protocol/QosProtocolWrapperTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.server.Server; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP; import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE; import static org.apache.dubbo.common.constants.QosConstants.QOS_HOST; import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class QosProtocolWrapperTest { private URL url = Mockito.mock(URL.class); private Invoker invoker = mock(Invoker.class); private Protocol protocol = mock(Protocol.class); private QosProtocolWrapper wrapper; private URL triUrl = Mockito.mock(URL.class); private Invoker triInvoker = mock(Invoker.class); private Protocol triProtocol = mock(Protocol.class); private QosProtocolWrapper triWrapper; private Server server; @BeforeEach public void setUp() throws Exception { when(url.getParameter(QOS_ENABLE, true)).thenReturn(true); when(url.getParameter(QOS_HOST)).thenReturn("localhost"); when(url.getParameter(QOS_PORT, 22222)).thenReturn(12345); when(url.getParameter(ACCEPT_FOREIGN_IP, "false")).thenReturn("false"); when(url.getProtocol()).thenReturn(REGISTRY_PROTOCOL); when(invoker.getUrl()).thenReturn(url); wrapper = new QosProtocolWrapper(protocol); wrapper.setFrameworkModel(FrameworkModel.defaultModel()); // url2 use tri protocol and qos.accept.foreign.ip=true when(triUrl.getParameter(QOS_ENABLE, true)).thenReturn(true); when(triUrl.getParameter(QOS_HOST)).thenReturn("localhost"); when(triUrl.getParameter(QOS_PORT, 22222)).thenReturn(12345); when(triUrl.getParameter(ACCEPT_FOREIGN_IP, "false")).thenReturn("true"); when(triUrl.getProtocol()).thenReturn(CommonConstants.TRIPLE); when(triInvoker.getUrl()).thenReturn(triUrl); triWrapper = new QosProtocolWrapper(triProtocol); triWrapper.setFrameworkModel(FrameworkModel.defaultModel()); server = FrameworkModel.defaultModel().getBeanFactory().getBean(Server.class); } @AfterEach public void tearDown() throws Exception { if (server.isStarted()) { server.stop(); } FrameworkModel.defaultModel().destroy(); } @Test void testExport() throws Exception { wrapper.export(invoker); assertThat(server.isStarted(), is(true)); assertThat(server.getHost(), is("localhost")); assertThat(server.getPort(), is(12345)); assertThat(server.isAcceptForeignIp(), is(false)); verify(protocol).export(invoker); } @Test void testRefer() throws Exception { wrapper.refer(BaseCommand.class, url); assertThat(server.isStarted(), is(true)); assertThat(server.getHost(), is("localhost")); assertThat(server.getPort(), is(12345)); assertThat(server.isAcceptForeignIp(), is(false)); verify(protocol).refer(BaseCommand.class, url); } @Test void testMultiProtocol() throws Exception { // tri protocol start first, acceptForeignIp = true triWrapper.export(triInvoker); assertThat(server.isStarted(), is(true)); assertThat(server.getHost(), is("localhost")); assertThat(server.getPort(), is(12345)); assertThat(server.isAcceptForeignIp(), is(true)); verify(triProtocol).export(triInvoker); // next registry protocol server still acceptForeignIp=true even though wrapper invoker url set false wrapper.export(invoker); assertThat(server.isStarted(), is(true)); assertThat(server.getHost(), is("localhost")); assertThat(server.getPort(), is(12345)); assertThat(server.isAcceptForeignIp(), is(true)); verify(protocol).export(invoker); } }
8,234
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/CommandContextTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command; import org.apache.dubbo.qos.api.CommandContext; import io.netty.channel.Channel; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class CommandContextTest { @Test void test() { CommandContext context = new CommandContext("test", new String[] {"hello"}, true); Object request = new Object(); context.setOriginRequest(request); Channel channel = Mockito.mock(Channel.class); context.setRemote(channel); assertThat(context.getCommandName(), equalTo("test")); assertThat(context.getArgs(), arrayContaining("hello")); assertThat(context.getOriginRequest(), is(request)); assertTrue(context.isHttp()); assertThat(context.getRemote(), is(channel)); context = new CommandContext("command"); context.setRemote(channel); context.setOriginRequest(request); context.setArgs(new String[] {"world"}); context.setHttp(false); assertThat(context.getCommandName(), equalTo("command")); assertThat(context.getArgs(), arrayContaining("world")); assertThat(context.getOriginRequest(), is(request)); assertFalse(context.isHttp()); assertThat(context.getRemote(), is(channel)); } }
8,235
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/CommandContextFactoryTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command; import org.apache.dubbo.qos.api.CommandContext; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertTrue; class CommandContextFactoryTest { @Test void testNewInstance() { CommandContext context = CommandContextFactory.newInstance("test"); assertThat(context.getCommandName(), equalTo("test")); context = CommandContextFactory.newInstance("command", new String[] {"hello"}, true); assertThat(context.getCommandName(), equalTo("command")); assertThat(context.getArgs(), Matchers.arrayContaining("hello")); assertTrue(context.isHttp()); } }
8,236
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/GreetingCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.qos.api.CommandContext; @Cmd( name = "greeting", summary = "greeting message", example = { "greeting dubbo", }) public class GreetingCommand implements BaseCommand { @Override public String execute(CommandContext commandContext, String[] args) { return ArrayUtils.isNotEmpty(args) ? "greeting " + args[0] : "greeting"; } }
8,237
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/DefaultCommandExecutorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.qos.command.exception.NoSuchCommandException; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; class DefaultCommandExecutorTest { @Test void testExecute1() { Assertions.assertThrows(NoSuchCommandException.class, () -> { DefaultCommandExecutor executor = new DefaultCommandExecutor(FrameworkModel.defaultModel()); executor.execute(CommandContextFactory.newInstance("not-exit")); }); } @Test void testExecute2() throws Exception { DefaultCommandExecutor executor = new DefaultCommandExecutor(FrameworkModel.defaultModel()); final CommandContext commandContext = CommandContextFactory.newInstance("greeting", new String[] {"dubbo"}, false); commandContext.setQosConfiguration(QosConfiguration.builder() .anonymousAccessPermissionLevel(PermissionLevel.PROTECTED.name()) .build()); String result = executor.execute(commandContext); assertThat(result, equalTo("greeting dubbo")); } @Test void shouldNotThrowPermissionDenyException_GivenPermissionConfigAndMatchDefaultPUBLICCmdPermissionLevel() { DefaultCommandExecutor executor = new DefaultCommandExecutor(FrameworkModel.defaultModel()); final CommandContext commandContext = CommandContextFactory.newInstance("live", new String[] {"dubbo"}, false); commandContext.setQosConfiguration(QosConfiguration.builder().build()); Assertions.assertDoesNotThrow(() -> executor.execute(commandContext)); } @Test void shouldNotThrowPermissionDenyException_GivenPermissionConfigAndNotMatchCmdPermissionLevel() { DefaultCommandExecutor executor = new DefaultCommandExecutor(FrameworkModel.defaultModel()); final CommandContext commandContext = CommandContextFactory.newInstance("live", new String[] {"dubbo"}, false); // 1 PROTECTED commandContext.setQosConfiguration( QosConfiguration.builder().anonymousAccessPermissionLevel("1").build()); Assertions.assertDoesNotThrow(() -> executor.execute(commandContext)); } }
8,238
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/TestRegistryFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; public class TestRegistryFactory implements RegistryFactory { static Registry registry; @Override public Registry getRegistry(URL url) { return registry; } }
8,239
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LiveTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class LiveTest { private FrameworkModel frameworkModel; @BeforeEach public void setUp() { frameworkModel = new FrameworkModel(); } @AfterEach public void reset() { frameworkModel.destroy(); } @Test void testExecute() { Live live = new Live(frameworkModel); CommandContext commandContext = new CommandContext("live"); String result = live.execute(commandContext, new String[0]); Assertions.assertEquals(result, "false"); Assertions.assertEquals(commandContext.getHttpCode(), 503); MockLivenessProbe.setCheckReturnValue(true); result = live.execute(commandContext, new String[0]); Assertions.assertEquals(result, "true"); Assertions.assertEquals(commandContext.getHttpCode(), 200); } }
8,240
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/QuitTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.common.QosConstants; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; class QuitTest { @Test void testExecute() throws Exception { Quit quit = new Quit(); String output = quit.execute(Mockito.mock(CommandContext.class), null); assertThat(output, equalTo(QosConstants.CLOSE)); } }
8,241
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/CountTelnetTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.command.impl.channel.MockNettyChannel; import org.apache.dubbo.qos.legacy.service.DemoService; import org.apache.dubbo.remoting.telnet.support.TelnetUtils; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.RpcStatus; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CountDownLatch; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; class CountTelnetTest { private BaseCommand count; private MockNettyChannel mockChannel; private Invoker<DemoService> mockInvoker; private CommandContext mockCommandContext; private CountDownLatch latch; private final URL url = URL.valueOf("dubbo://127.0.0.1:20884/demo"); @BeforeEach public void setUp() { count = new CountTelnet(FrameworkModel.defaultModel()); latch = new CountDownLatch(2); mockInvoker = mock(Invoker.class); mockCommandContext = mock(CommandContext.class); mockChannel = new MockNettyChannel(url, latch); given(mockCommandContext.getRemote()).willReturn(mockChannel); given(mockInvoker.getInterface()).willReturn(DemoService.class); given(mockInvoker.getUrl()).willReturn(url); } @AfterEach public void tearDown() { FrameworkModel.destroyAll(); mockChannel.close(); reset(mockInvoker, mockCommandContext); } @Test void test() throws Exception { String methodName = "sayHello"; String[] args = new String[] {"org.apache.dubbo.qos.legacy.service.DemoService", "sayHello", "1"}; ExtensionLoader.getExtensionLoader(Protocol.class) .getExtension(DubboProtocol.NAME) .export(mockInvoker); RpcStatus.beginCount(url, methodName); RpcStatus.endCount(url, methodName, 10L, true); count.execute(mockCommandContext, args); latch.await(); StringBuilder sb = new StringBuilder(); for (Object o : mockChannel.getReceivedObjects()) { sb.append(o.toString()); } assertThat(sb.toString(), containsString(buildTable(methodName, 10, 10, "1", "0", "0"))); } public static String buildTable( String methodName, long averageElapsed, long maxElapsed, String total, String failed, String active) { List<String> header = new LinkedList<>(); header.add("method"); header.add("total"); header.add("failed"); header.add("active"); header.add("average"); header.add("max"); List<List<String>> table = new LinkedList<>(); List<String> row = new LinkedList<String>(); row.add(methodName); row.add(total); row.add(failed); row.add(active); row.add(averageElapsed + "ms"); row.add(maxElapsed + "ms"); table.add(row); return TelnetUtils.toTable(header, table); } }
8,242
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SelectTelnetTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.legacy.service.DemoService; import org.apache.dubbo.qos.legacy.service.DemoServiceImpl; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ServiceDescriptor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import io.netty.channel.Channel; import io.netty.util.DefaultAttributeMap; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; class SelectTelnetTest { private BaseCommand select; private Channel mockChannel; private CommandContext mockCommandContext; private ModuleServiceRepository repository; private final DefaultAttributeMap defaultAttributeMap = new DefaultAttributeMap(); private List<Method> methods; @BeforeEach public void setup() { repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); select = new SelectTelnet(FrameworkModel.defaultModel()); String methodName = "getPerson"; methods = new ArrayList<>(); for (Method method : DemoService.class.getMethods()) { if (method.getName().equals(methodName)) { methods.add(method); } } DubboBootstrap.reset(); mockChannel = mock(Channel.class); mockCommandContext = mock(CommandContext.class); given(mockCommandContext.getRemote()).willReturn(mockChannel); } @AfterEach public void after() { FrameworkModel.destroyAll(); reset(mockChannel, mockCommandContext); } @Test void testInvokeWithoutMethodList() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).set(null); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)) .willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String result = select.execute(mockCommandContext, new String[] {"1"}); assertTrue(result.contains("Please use the invoke command first.")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).remove(); } @Test void testInvokeWithIllegalMessage() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).set(methods); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)) .willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String result = select.execute(mockCommandContext, new String[] {"index"}); assertTrue(result.contains("Illegal index ,please input select 1")); result = select.execute(mockCommandContext, new String[] {"0"}); assertTrue(result.contains("Illegal index ,please input select 1")); result = select.execute(mockCommandContext, new String[] {"1000"}); assertTrue(result.contains("Illegal index ,please input select 1")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).remove(); } @Test void testInvokeWithNull() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).set(methods); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)) .willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String result = select.execute(mockCommandContext, new String[0]); assertTrue(result.contains("Please input the index of the method you want to invoke")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).remove(); } private void registerProvider(String key, Object impl, Class<?> interfaceClass) { ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); repository.registerProvider(key, impl, serviceDescriptor, null, null); } }
8,243
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ReadyTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.deploy.ModuleDeployer; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.probe.ReadinessProbe; import org.apache.dubbo.qos.probe.impl.DeployerReadinessProbe; import org.apache.dubbo.qos.probe.impl.ProviderReadinessProbe; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.FrameworkServiceRepository; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class ReadyTest { private FrameworkModel frameworkModel; private ModuleDeployer moduleDeployer; private FrameworkServiceRepository frameworkServiceRepository; @BeforeEach public void setUp() { frameworkModel = Mockito.mock(FrameworkModel.class); frameworkServiceRepository = Mockito.mock(FrameworkServiceRepository.class); ConfigManager manager = Mockito.mock(ConfigManager.class); Mockito.when(manager.getApplication()).thenReturn(Optional.of(new ApplicationConfig("ReadyTest"))); ApplicationModel applicationModel = Mockito.mock(ApplicationModel.class); ModuleModel moduleModel = Mockito.mock(ModuleModel.class); moduleDeployer = Mockito.mock(ModuleDeployer.class); Mockito.when(frameworkServiceRepository.allProviderModels()).thenReturn(Collections.emptyList()); Mockito.when(frameworkModel.newApplication()).thenReturn(applicationModel); Mockito.when(frameworkModel.getApplicationModels()).thenReturn(Arrays.asList(applicationModel)); Mockito.when(frameworkModel.getServiceRepository()).thenReturn(frameworkServiceRepository); Mockito.when(applicationModel.getModuleModels()).thenReturn(Arrays.asList(moduleModel)); Mockito.when(applicationModel.getApplicationConfigManager()).thenReturn(manager); Mockito.when(moduleModel.getDeployer()).thenReturn(moduleDeployer); Mockito.when(moduleDeployer.isStarted()).thenReturn(true); ExtensionLoader loader = Mockito.mock(ExtensionLoader.class); Mockito.when(frameworkModel.getExtensionLoader(ReadinessProbe.class)).thenReturn(loader); URL url = URL.valueOf("application://").addParameter(CommonConstants.QOS_READY_PROBE_EXTENSION, ""); List<ReadinessProbe> readinessProbes = Arrays.asList(new DeployerReadinessProbe(frameworkModel), new ProviderReadinessProbe(frameworkModel)); Mockito.when(loader.getActivateExtension(url, CommonConstants.QOS_READY_PROBE_EXTENSION)) .thenReturn(readinessProbes); } @Test void testExecute() { Ready ready = new Ready(frameworkModel); CommandContext commandContext = new CommandContext("ready"); String result = ready.execute(commandContext, new String[0]); Assertions.assertEquals("true", result); Assertions.assertEquals(commandContext.getHttpCode(), 200); Mockito.when(moduleDeployer.isStarted()).thenReturn(false); result = ready.execute(commandContext, new String[0]); Assertions.assertEquals("false", result); Assertions.assertEquals(commandContext.getHttpCode(), 503); } }
8,244
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OnlineTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.qos.DemoService; import org.apache.dubbo.qos.DemoServiceImpl; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.registry.RegistryService; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceMetadata; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE; import static org.mockito.Mockito.mock; /** * {@link BaseOnline} * {@link Online} * {@link OnlineApp} * {@link OnlineInterface} */ class OnlineTest { private FrameworkModel frameworkModel; private ModuleServiceRepository repository; private ProviderModel.RegisterStatedURL registerStatedURL; @BeforeEach public void setUp() { frameworkModel = new FrameworkModel(); repository = frameworkModel.newApplication().getDefaultModule().getServiceRepository(); registerProvider(); } @AfterEach public void reset() { frameworkModel.destroy(); } @Test void testExecute() { Online online = new Online(frameworkModel); String result = online.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()}); Assertions.assertEquals(result, "OK"); Assertions.assertTrue(registerStatedURL.isRegistered()); OnlineInterface onlineInterface = new OnlineInterface(frameworkModel); registerStatedURL.setRegistered(false); result = onlineInterface.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()}); Assertions.assertEquals(result, "OK"); Assertions.assertTrue(registerStatedURL.isRegistered()); registerStatedURL.setRegistered(false); registerStatedURL.setRegistryUrl(URL.valueOf("test://127.0.0.1:2181/" + RegistryService.class.getName()) .addParameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE)); OnlineApp onlineApp = new OnlineApp(frameworkModel); result = onlineApp.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()}); Assertions.assertEquals(result, "OK"); Assertions.assertTrue(registerStatedURL.isRegistered()); } private void registerProvider() { ServiceDescriptor serviceDescriptor = repository.registerService(DemoService.class); ServiceMetadata serviceMetadata = new ServiceMetadata(); serviceMetadata.setServiceKey(DemoService.class.getName()); ProviderModel providerModel = new ProviderModel( DemoService.class.getName(), new DemoServiceImpl(), serviceDescriptor, serviceMetadata, ClassUtils.getClassLoader(DemoService.class)); registerStatedURL = new ProviderModel.RegisterStatedURL( URL.valueOf("dubbo://127.0.0.1:20880/" + DemoService.class.getName()), URL.valueOf("test://127.0.0.1:2181/" + RegistryService.class.getName()), false); providerModel.addStatedUrl(registerStatedURL); repository.registerProvider(providerModel); } }
8,245
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SerializeWarnedClassesTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.utils.SerializeSecurityManager; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class SerializeWarnedClassesTest { @Test void test() { FrameworkModel frameworkModel = new FrameworkModel(); SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeWarnedClasses serializeWarnedClasses = new SerializeWarnedClasses(frameworkModel); CommandContext commandContext1 = Mockito.mock(CommandContext.class); Mockito.when(commandContext1.isHttp()).thenReturn(false); CommandContext commandContext2 = Mockito.mock(CommandContext.class); Mockito.when(commandContext2.isHttp()).thenReturn(true); Assertions.assertFalse( serializeWarnedClasses.execute(commandContext1, null).contains("Test1234")); Assertions.assertFalse( serializeWarnedClasses.execute(commandContext2, null).contains("Test1234")); ssm.getWarnedClasses().add("Test1234"); Assertions.assertTrue( serializeWarnedClasses.execute(commandContext1, null).contains("Test1234")); Assertions.assertTrue( serializeWarnedClasses.execute(commandContext2, null).contains("Test1234")); Assertions.assertFalse( serializeWarnedClasses.execute(commandContext1, null).contains("Test4321")); Assertions.assertFalse( serializeWarnedClasses.execute(commandContext2, null).contains("Test4321")); ssm.getWarnedClasses().add("Test4321"); Assertions.assertTrue( serializeWarnedClasses.execute(commandContext1, null).contains("Test4321")); Assertions.assertTrue( serializeWarnedClasses.execute(commandContext2, null).contains("Test4321")); frameworkModel.destroy(); } }
8,246
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/TestInterface.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; public interface TestInterface { String sayHello(); }
8,247
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PortTelnetTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.legacy.service.DemoService; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.remoting.exchange.ExchangeClient; import org.apache.dubbo.remoting.exchange.Exchangers; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; class PortTelnetTest { private BaseCommand port; private Invoker<DemoService> mockInvoker; private CommandContext mockCommandContext; private static final int availablePort = NetUtils.getAvailablePort(); @SuppressWarnings("unchecked") @BeforeEach public void before() { FrameworkModel frameworkModel = FrameworkModel.defaultModel(); port = new PortTelnet(frameworkModel); mockCommandContext = mock(CommandContext.class); mockInvoker = mock(Invoker.class); given(mockInvoker.getInterface()).willReturn(DemoService.class); given(mockInvoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:" + availablePort + "/demo")); frameworkModel .getExtensionLoader(Protocol.class) .getExtension(DubboProtocol.NAME) .export(mockInvoker); } @AfterEach public void afterEach() { FrameworkModel.destroyAll(); reset(mockInvoker, mockCommandContext); } /** * In NAT network scenario, server's channel.getRemoteAddress() possibly get the address of network gateway, or * the address converted by NAT. In this case, check port only. */ @Test void testListClient() throws Exception { ExchangeClient client1 = Exchangers.connect("dubbo://127.0.0.1:" + availablePort + "/demo"); ExchangeClient client2 = Exchangers.connect("dubbo://127.0.0.1:" + availablePort + "/demo"); Thread.sleep(100); String result = port.execute(mockCommandContext, new String[] {"-l", availablePort + ""}); String client1Addr = client1.getLocalAddress().toString(); String client2Addr = client2.getLocalAddress().toString(); System.out.printf("Result: %s %n", result); System.out.printf("Client 1 Address %s %n", client1Addr); System.out.printf("Client 2 Address %s %n", client2Addr); assertTrue(result.contains(String.valueOf(client1.getLocalAddress().getPort()))); assertTrue(result.contains(String.valueOf(client2.getLocalAddress().getPort()))); } @Test void testListDetail() throws RemotingException { String result = port.execute(mockCommandContext, new String[] {"-l"}); assertEquals("dubbo://127.0.0.1:" + availablePort + "", result); } @Test void testListAllPort() throws RemotingException { String result = port.execute(mockCommandContext, new String[0]); assertEquals("" + availablePort + "", result); } @Test void testErrorMessage() throws RemotingException { String result = port.execute(mockCommandContext, new String[] {"a"}); assertEquals("Illegal port a, must be integer.", result); } @Test void testNoPort() throws RemotingException { String result = port.execute(mockCommandContext, new String[] {"-l", "20880"}); assertEquals("No such port 20880", result); } }
8,248
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/HelpTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; class HelpTest { @Test void testMainHelp() { Help help = new Help(FrameworkModel.defaultModel()); String output = help.execute(Mockito.mock(CommandContext.class), null); assertThat(output, containsString("greeting")); assertThat(output, containsString("help")); assertThat(output, containsString("ls")); assertThat(output, containsString("online")); assertThat(output, containsString("offline")); assertThat(output, containsString("quit")); } @Test void testGreeting() { Help help = new Help(FrameworkModel.defaultModel()); String output = help.execute(Mockito.mock(CommandContext.class), new String[] {"greeting"}); assertThat(output, containsString("COMMAND NAME")); assertThat(output, containsString("greeting")); assertThat(output, containsString("EXAMPLE")); assertThat(output, containsString("greeting dubbo")); } }
8,249
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/StartupTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.deploy.ModuleDeployer; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.probe.StartupProbe; import org.apache.dubbo.qos.probe.impl.DeployerStartupProbe; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.Arrays; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class StartupTest { private FrameworkModel frameworkModel; private ModuleDeployer moduleDeployer; @BeforeEach public void setUp() { frameworkModel = Mockito.mock(FrameworkModel.class); ApplicationModel applicationModel = Mockito.mock(ApplicationModel.class); ModuleModel moduleModel = Mockito.mock(ModuleModel.class); ConfigManager manager = Mockito.mock(ConfigManager.class); Mockito.when(manager.getApplication()).thenReturn(Optional.of(new ApplicationConfig("ReadyTest"))); moduleDeployer = Mockito.mock(ModuleDeployer.class); Mockito.when(frameworkModel.newApplication()).thenReturn(applicationModel); Mockito.when(frameworkModel.getApplicationModels()).thenReturn(Arrays.asList(applicationModel)); Mockito.when(applicationModel.getModuleModels()).thenReturn(Arrays.asList(moduleModel)); Mockito.when(applicationModel.getApplicationConfigManager()).thenReturn(manager); Mockito.when(moduleModel.getDeployer()).thenReturn(moduleDeployer); Mockito.when(moduleDeployer.isRunning()).thenReturn(true); ExtensionLoader loader = Mockito.mock(ExtensionLoader.class); Mockito.when(frameworkModel.getExtensionLoader(StartupProbe.class)).thenReturn(loader); URL url = URL.valueOf("application://").addParameter(CommonConstants.QOS_STARTUP_PROBE_EXTENSION, ""); List<StartupProbe> readinessProbes = Arrays.asList(new DeployerStartupProbe(frameworkModel)); Mockito.when(loader.getActivateExtension(url, CommonConstants.QOS_STARTUP_PROBE_EXTENSION)) .thenReturn(readinessProbes); } @Test void testExecute() { Startup startup = new Startup(frameworkModel); CommandContext commandContext = new CommandContext("startup"); String result = startup.execute(commandContext, new String[0]); Assertions.assertEquals("true", result); Assertions.assertEquals(commandContext.getHttpCode(), 200); Mockito.when(moduleDeployer.isRunning()).thenReturn(false); result = startup.execute(commandContext, new String[0]); Assertions.assertEquals("false", result); Assertions.assertEquals(commandContext.getHttpCode(), 503); } }
8,250
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/GetConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.SslConfig; import org.apache.dubbo.metadata.MetadataService; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class GetConfigTest { @Test void testAll() { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel1 = frameworkModel.newApplication(); applicationModel1.getApplicationConfigManager().setApplication(new ApplicationConfig("app1")); applicationModel1.getApplicationConfigManager().addProtocol(new ProtocolConfig("dubbo", 12345)); applicationModel1.getApplicationConfigManager().addRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181")); applicationModel1 .getApplicationConfigManager() .addMetadataReport(new MetadataReportConfig("zookeeper://127.0.0.1:2181")); ConfigCenterConfig configCenterConfig = new ConfigCenterConfig(); configCenterConfig.setAddress("zookeeper://127.0.0.1:2181"); applicationModel1.getApplicationConfigManager().addConfigCenter(configCenterConfig); applicationModel1.getApplicationConfigManager().setMetrics(new MetricsConfig()); applicationModel1.getApplicationConfigManager().setMonitor(new MonitorConfig()); applicationModel1.getApplicationConfigManager().setSsl(new SslConfig()); ModuleModel moduleModel = applicationModel1.newModule(); moduleModel.getConfigManager().setModule(new ModuleConfig()); moduleModel.getConfigManager().addConsumer(new ConsumerConfig()); moduleModel.getConfigManager().addProvider(new ProviderConfig()); ReferenceConfig<Object> referenceConfig = new ReferenceConfig<>(); referenceConfig.setInterface(MetadataService.class); moduleModel.getConfigManager().addReference(referenceConfig); ServiceConfig<Object> serviceConfig = new ServiceConfig<>(); serviceConfig.setInterface(MetadataService.class); moduleModel.getConfigManager().addService(serviceConfig); CommandContext commandContext = new CommandContext("getConfig"); commandContext.setHttp(true); Assertions.assertNotNull(new GetConfig(frameworkModel).execute(commandContext, null)); } @Test void testFilter1() { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel1 = frameworkModel.newApplication(); applicationModel1.getApplicationConfigManager().setApplication(new ApplicationConfig("app1")); applicationModel1.getApplicationConfigManager().addProtocol(new ProtocolConfig("dubbo", 12345)); applicationModel1.getApplicationConfigManager().addRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181")); applicationModel1 .getApplicationConfigManager() .addMetadataReport(new MetadataReportConfig("zookeeper://127.0.0.1:2181")); ConfigCenterConfig configCenterConfig = new ConfigCenterConfig(); configCenterConfig.setAddress("zookeeper://127.0.0.1:2181"); applicationModel1.getApplicationConfigManager().addConfigCenter(configCenterConfig); applicationModel1.getApplicationConfigManager().setMetrics(new MetricsConfig()); applicationModel1.getApplicationConfigManager().setMonitor(new MonitorConfig()); applicationModel1.getApplicationConfigManager().setSsl(new SslConfig()); ModuleModel moduleModel = applicationModel1.newModule(); moduleModel.getConfigManager().setModule(new ModuleConfig()); moduleModel.getConfigManager().addConsumer(new ConsumerConfig()); moduleModel.getConfigManager().addProvider(new ProviderConfig()); ReferenceConfig<Object> referenceConfig = new ReferenceConfig<>(); referenceConfig.setInterface(MetadataService.class); moduleModel.getConfigManager().addReference(referenceConfig); ServiceConfig<Object> serviceConfig = new ServiceConfig<>(); serviceConfig.setInterface(MetadataService.class); moduleModel.getConfigManager().addService(serviceConfig); CommandContext commandContext = new CommandContext("getConfig"); commandContext.setHttp(true); Assertions.assertNotNull( new GetConfig(frameworkModel).execute(commandContext, new String[] {"ApplicationConfig"})); } @Test void testFilter2() { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel1 = frameworkModel.newApplication(); applicationModel1.getApplicationConfigManager().setApplication(new ApplicationConfig("app1")); applicationModel1.getApplicationConfigManager().addProtocol(new ProtocolConfig("dubbo", 12345)); applicationModel1.getApplicationConfigManager().addRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181")); applicationModel1 .getApplicationConfigManager() .addMetadataReport(new MetadataReportConfig("zookeeper://127.0.0.1:2181")); ConfigCenterConfig configCenterConfig = new ConfigCenterConfig(); configCenterConfig.setAddress("zookeeper://127.0.0.1:2181"); applicationModel1.getApplicationConfigManager().addConfigCenter(configCenterConfig); applicationModel1.getApplicationConfigManager().setMetrics(new MetricsConfig()); applicationModel1.getApplicationConfigManager().setMonitor(new MonitorConfig()); applicationModel1.getApplicationConfigManager().setSsl(new SslConfig()); ModuleModel moduleModel = applicationModel1.newModule(); moduleModel.getConfigManager().setModule(new ModuleConfig()); moduleModel.getConfigManager().addConsumer(new ConsumerConfig()); moduleModel.getConfigManager().addProvider(new ProviderConfig()); ReferenceConfig<Object> referenceConfig = new ReferenceConfig<>(); referenceConfig.setInterface(MetadataService.class); moduleModel.getConfigManager().addReference(referenceConfig); ServiceConfig<Object> serviceConfig = new ServiceConfig<>(); serviceConfig.setInterface(MetadataService.class); moduleModel.getConfigManager().addService(serviceConfig); CommandContext commandContext = new CommandContext("getConfig"); commandContext.setHttp(true); Assertions.assertNotNull( new GetConfig(frameworkModel).execute(commandContext, new String[] {"ProtocolConfig", "dubbo"})); } }
8,251
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PublishMetadataTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class PublishMetadataTest { private FrameworkModel frameworkModel; @BeforeEach public void setUp() throws Exception { frameworkModel = new FrameworkModel(); for (int i = 0; i < 3; i++) { ApplicationModel applicationModel = frameworkModel.newApplication(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("APP_" + i)); } } @AfterEach public void reset() { frameworkModel.destroy(); } @Test void testExecute() { PublishMetadata publishMetadata = new PublishMetadata(frameworkModel); String result = publishMetadata.execute(Mockito.mock(CommandContext.class), new String[0]); String expectResult = "publish metadata succeeded. App:APP_0\n" + "publish metadata succeeded. App:APP_1\n" + "publish metadata succeeded. App:APP_2\n"; Assertions.assertEquals(result, expectResult); // delay 5s result = publishMetadata.execute(Mockito.mock(CommandContext.class), new String[] {"5"}); expectResult = "publish task submitted, will publish in 5 seconds. App:APP_0\n" + "publish task submitted, will publish in 5 seconds. App:APP_1\n" + "publish task submitted, will publish in 5 seconds. App:APP_2\n"; Assertions.assertEquals(result, expectResult); // wrong delay param result = publishMetadata.execute(Mockito.mock(CommandContext.class), new String[] {"A"}); expectResult = "publishMetadata failed! Wrong delay param!"; Assertions.assertEquals(result, expectResult); } }
8,252
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/LsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.qos.DemoService; import org.apache.dubbo.qos.DemoServiceImpl; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.model.AsyncMethodInfo; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceMetadata; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class LsTest { private FrameworkModel frameworkModel; private ModuleServiceRepository repository; @BeforeEach public void setUp() { frameworkModel = new FrameworkModel(); repository = frameworkModel.newApplication().getDefaultModule().getServiceRepository(); registerProvider(); registerConsumer(); } @AfterEach public void reset() { frameworkModel.destroy(); } @Test void testExecute() { Ls ls = new Ls(frameworkModel); String result = ls.execute(Mockito.mock(CommandContext.class), new String[0]); System.out.println(result); /** * As Provider side: * +--------------------------------+---+ * | Provider Service Name |PUB| * +--------------------------------+---+ * |org.apache.dubbo.qos.DemoService| N | * +--------------------------------+---+ * As Consumer side: * +--------------------------------+---+ * | Consumer Service Name |NUM| * +--------------------------------+---+ * |org.apache.dubbo.qos.DemoService| 0 | * +--------------------------------+---+ */ } private void registerProvider() { ServiceDescriptor serviceDescriptor = repository.registerService(DemoService.class); ServiceMetadata serviceMetadata = new ServiceMetadata(); serviceMetadata.setServiceKey(DemoService.class.getName()); ProviderModel providerModel = new ProviderModel( DemoService.class.getName(), new DemoServiceImpl(), serviceDescriptor, null, serviceMetadata, ClassUtils.getClassLoader(DemoService.class)); repository.registerProvider(providerModel); } private void registerConsumer() { ServiceDescriptor serviceDescriptor = repository.registerService(DemoService.class); ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setInterface(DemoService.class); ServiceMetadata serviceMetadata = new ServiceMetadata(); serviceMetadata.setServiceKey(DemoService.class.getName()); Map<String, AsyncMethodInfo> methodConfigs = new HashMap<>(); ConsumerModel consumerModel = new ConsumerModel( serviceMetadata.getServiceKey(), null, serviceDescriptor, serviceMetadata, methodConfigs, referenceConfig.getInterfaceClassLoader()); repository.registerConsumer(consumerModel); } }
8,253
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/MockLivenessProbe.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.qos.probe.LivenessProbe; @Activate public class MockLivenessProbe implements LivenessProbe { private static boolean checkReturnValue = false; @Override public boolean check() { return checkReturnValue; } public static void setCheckReturnValue(boolean checkReturnValue) { MockLivenessProbe.checkReturnValue = checkReturnValue; } }
8,254
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/PwdTelnetTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.rpc.model.FrameworkModel; import io.netty.channel.Channel; import io.netty.util.DefaultAttributeMap; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; class PwdTelnetTest { private static final BaseCommand pwdTelnet = new PwdTelnet(); private Channel mockChannel; private CommandContext mockCommandContext; private final DefaultAttributeMap defaultAttributeMap = new DefaultAttributeMap(); @BeforeEach public void setUp() { mockChannel = mock(Channel.class); mockCommandContext = mock(CommandContext.class); given(mockCommandContext.getRemote()).willReturn(mockChannel); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); } @AfterEach public void tearDown() { FrameworkModel.destroyAll(); mockChannel.close(); reset(mockChannel, mockCommandContext); } @Test void testService() throws RemotingException { defaultAttributeMap .attr(ChangeTelnet.SERVICE_KEY) .set("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); String result = pwdTelnet.execute(mockCommandContext, new String[0]); assertEquals("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService", result); } @Test void testSlash() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(null); String result = pwdTelnet.execute(mockCommandContext, new String[0]); assertEquals("/", result); } @Test void testMessageError() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(null); String result = pwdTelnet.execute(mockCommandContext, new String[] {"test"}); assertEquals("Unsupported parameter [test] for pwd.", result); } }
8,255
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/OfflineTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.qos.DemoService; import org.apache.dubbo.qos.DemoServiceImpl; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.registry.RegistryService; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceMetadata; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE; import static org.mockito.Mockito.mock; /** * {@link BaseOffline} * {@link Offline} * {@link OfflineApp} * {@link OfflineInterface} */ class OfflineTest { private FrameworkModel frameworkModel; private ModuleServiceRepository repository; private ProviderModel.RegisterStatedURL registerStatedURL; @BeforeEach public void setUp() { frameworkModel = new FrameworkModel(); repository = frameworkModel.newApplication().getDefaultModule().getServiceRepository(); registerProvider(); } @AfterEach public void reset() { frameworkModel.destroy(); } @Test void testExecute() { Offline offline = new Offline(frameworkModel); String result = offline.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()}); Assertions.assertEquals(result, "OK"); Assertions.assertFalse(registerStatedURL.isRegistered()); OfflineInterface offlineInterface = new OfflineInterface(frameworkModel); registerStatedURL.setRegistered(true); result = offlineInterface.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()}); Assertions.assertEquals(result, "OK"); Assertions.assertFalse(registerStatedURL.isRegistered()); registerStatedURL.setRegistered(true); registerStatedURL.setRegistryUrl(URL.valueOf("test://127.0.0.1:2181/" + RegistryService.class.getName()) .addParameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE)); OfflineApp offlineApp = new OfflineApp(frameworkModel); result = offlineApp.execute(mock(CommandContext.class), new String[] {DemoService.class.getName()}); Assertions.assertEquals(result, "OK"); Assertions.assertFalse(registerStatedURL.isRegistered()); } private void registerProvider() { ServiceDescriptor serviceDescriptor = repository.registerService(DemoService.class); ServiceMetadata serviceMetadata = new ServiceMetadata(); serviceMetadata.setServiceKey(DemoService.class.getName()); ProviderModel providerModel = new ProviderModel( DemoService.class.getName(), new DemoServiceImpl(), serviceDescriptor, serviceMetadata, ClassUtils.getClassLoader(DemoService.class)); registerStatedURL = new ProviderModel.RegisterStatedURL( URL.valueOf("dubbo://127.0.0.1:20880/" + DemoService.class.getName()), URL.valueOf("test://127.0.0.1:2181/" + RegistryService.class.getName()), true); providerModel.addStatedUrl(registerStatedURL); repository.registerProvider(providerModel); } }
8,256
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/InvokeTelnetTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.legacy.service.DemoService; import org.apache.dubbo.qos.legacy.service.DemoServiceImpl; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ServiceDescriptor; import io.netty.channel.Channel; import io.netty.util.DefaultAttributeMap; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; class InvokeTelnetTest { private FrameworkModel frameworkModel; private BaseCommand invoke; private BaseCommand select; private Channel mockChannel; private CommandContext mockCommandContext; private final DefaultAttributeMap defaultAttributeMap = new DefaultAttributeMap(); private ModuleServiceRepository repository; @BeforeEach public void setup() { DubboBootstrap.reset(); frameworkModel = new FrameworkModel(); invoke = new InvokeTelnet(frameworkModel); select = new SelectTelnet(frameworkModel); mockChannel = mock(Channel.class); mockCommandContext = mock(CommandContext.class); given(mockCommandContext.getRemote()).willReturn(mockChannel); ApplicationModel applicationModel = frameworkModel.newApplication(); repository = applicationModel.getDefaultModule().getServiceRepository(); } @AfterEach public void after() { frameworkModel.destroy(); reset(mockChannel, mockCommandContext); } @Test void testInvokeWithoutServicePrefixAndWithoutDefaultService() throws RemotingException { registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String result = invoke.execute(mockCommandContext, new String[] {"echo(\"ok\")"}); assertTrue(result.contains( "If you want to invoke like [invoke sayHello(\"xxxx\")], please execute cd command first," + " or you can execute it like [invoke IHelloService.sayHello(\"xxxx\")]")); } @Test void testInvokeDefaultService() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String result = invoke.execute(mockCommandContext, new String[] {"echo(\"ok\")"}); assertTrue(result.contains("result: \"ok\"")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove(); } @Test void testInvokeWithSpecifyService() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(null); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String result = invoke.execute(mockCommandContext, new String[] {"DemoService.echo(\"ok\")"}); assertTrue(result.contains("result: \"ok\"")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove(); } @Test void testInvokeByPassingNullValue() { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); try { invoke.execute(mockCommandContext, new String[] {"sayHello(null)"}); } catch (Exception ex) { assertTrue(ex instanceof NullPointerException); } defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove(); } @Test void testInvokeByPassingEnumValue() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String result = invoke.execute(mockCommandContext, new String[] {"getType(\"High\")"}); assertTrue(result.contains("result: \"High\"")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove(); } @Test void testOverriddenMethodWithSpecifyParamType() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String result = invoke.execute(mockCommandContext, new String[] { "getPerson({\"name\":\"zhangsan\",\"age\":12,\"class\":\"org.apache.dubbo.qos.legacy.service.Person\"})" }); assertTrue(result.contains("result: 12")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove(); } @Test void testInvokeOverriddenMethodBySelect() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); defaultAttributeMap.attr(SelectTelnet.SELECT_METHOD_KEY).set(null); defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_PROVIDER_KEY).set(null); defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).set(null); defaultAttributeMap.attr(InvokeTelnet.INVOKE_MESSAGE_KEY).set(null); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_METHOD_KEY)) .willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_METHOD_KEY)); given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_PROVIDER_KEY)) .willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_PROVIDER_KEY)); given(mockChannel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)) .willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY)); given(mockChannel.attr(InvokeTelnet.INVOKE_MESSAGE_KEY)) .willReturn(defaultAttributeMap.attr(InvokeTelnet.INVOKE_MESSAGE_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String param = "{\"name\":\"Dubbo\",\"age\":8}"; String result = invoke.execute(mockCommandContext, new String[] {"getPerson(" + param + ")"}); assertTrue( result.contains("Please use the select command to select the method you want to invoke. eg: select 1")); result = select.execute(mockCommandContext, new String[] {"1"}); // result dependent on method order. assertTrue(result.contains("result: 8") || result.contains("result: \"Dubbo\"")); result = select.execute(mockCommandContext, new String[] {"2"}); assertTrue(result.contains("result: 8") || result.contains("result: \"Dubbo\"")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove(); defaultAttributeMap.attr(SelectTelnet.SELECT_METHOD_KEY).remove(); defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_PROVIDER_KEY).remove(); defaultAttributeMap.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).remove(); defaultAttributeMap.attr(InvokeTelnet.INVOKE_MESSAGE_KEY).remove(); } @Test void testInvokeMethodWithMapParameter() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String param = "{1:\"Dubbo\",2:\"test\"}"; String result = invoke.execute(mockCommandContext, new String[] {"getMap(" + param + ")"}); assertTrue(result.contains("result: {1:\"Dubbo\",2:\"test\"}")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove(); } @Test void testInvokeMultiJsonParamMethod() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(DemoService.class.getName()); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); registerProvider(DemoService.class.getName(), new DemoServiceImpl(), DemoService.class); String param = "{\"name\":\"Dubbo\",\"age\":8},{\"name\":\"Apache\",\"age\":20}"; String result = invoke.execute(mockCommandContext, new String[] {"getPerson(" + param + ")"}); assertTrue(result.contains("result: 28")); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove(); } @Test void testMessageNull() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(null); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); String result = invoke.execute(mockCommandContext, new String[0]); assertEquals( "Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\ninvoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\ninvoke com.xxx.XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})", result); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove(); } @Test void testInvalidMessage() throws RemotingException { defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).set(null); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).set(null); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); given(mockChannel.attr(SelectTelnet.SELECT_KEY)).willReturn(defaultAttributeMap.attr(SelectTelnet.SELECT_KEY)); String result = invoke.execute(mockCommandContext, new String[] {"("}); assertEquals("Invalid parameters, format: service.method(args)", result); defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY).remove(); defaultAttributeMap.attr(SelectTelnet.SELECT_KEY).remove(); } private void registerProvider(String key, Object impl, Class<?> interfaceClass) { ServiceDescriptor serviceDescriptor = repository.registerService(interfaceClass); repository.registerProvider(key, impl, serviceDescriptor, null, null); } }
8,257
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ChangeTelnetTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.legacy.service.DemoService; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; import io.netty.channel.Channel; import io.netty.util.DefaultAttributeMap; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; class ChangeTelnetTest { private final DefaultAttributeMap defaultAttributeMap = new DefaultAttributeMap(); private BaseCommand change; private Channel mockChannel; private CommandContext mockCommandContext; private Invoker<DemoService> mockInvoker; @AfterAll public static void tearDown() { FrameworkModel.destroyAll(); } @BeforeAll public static void setUp() { FrameworkModel.destroyAll(); } @SuppressWarnings("unchecked") @BeforeEach public void beforeEach() { change = new ChangeTelnet(FrameworkModel.defaultModel()); mockCommandContext = mock(CommandContext.class); mockChannel = mock(Channel.class); mockInvoker = mock(Invoker.class); given(mockChannel.attr(ChangeTelnet.SERVICE_KEY)) .willReturn(defaultAttributeMap.attr(ChangeTelnet.SERVICE_KEY)); mockChannel.attr(ChangeTelnet.SERVICE_KEY).set("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); given(mockCommandContext.getRemote()).willReturn(mockChannel); given(mockInvoker.getInterface()).willReturn(DemoService.class); given(mockInvoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:20884/demo")); } @AfterEach public void afterEach() { FrameworkModel.destroyAll(); reset(mockCommandContext, mockChannel, mockInvoker); } @Test void testChangeSimpleName() { ExtensionLoader.getExtensionLoader(Protocol.class) .getExtension(DubboProtocol.NAME) .export(mockInvoker); String result = change.execute(mockCommandContext, new String[] {"DemoService"}); assertEquals("Used the DemoService as default.\r\nYou can cancel default service by command: cd /", result); } @Test void testChangeName() { ExtensionLoader.getExtensionLoader(Protocol.class) .getExtension(DubboProtocol.NAME) .export(mockInvoker); String result = change.execute(mockCommandContext, new String[] {"org.apache.dubbo.qos.legacy.service.DemoService"}); assertEquals( "Used the org.apache.dubbo.qos.legacy.service.DemoService as default.\r\nYou can cancel default service by command: cd /", result); } @Test void testChangePath() { ExtensionLoader.getExtensionLoader(Protocol.class) .getExtension(DubboProtocol.NAME) .export(mockInvoker); String result = change.execute(mockCommandContext, new String[] {"demo"}); assertEquals("Used the demo as default.\r\nYou can cancel default service by command: cd /", result); } @Test void testChangeMessageNull() { String result = change.execute(mockCommandContext, null); assertEquals("Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService", result); } @Test void testChangeServiceNotExport() { String result = change.execute(mockCommandContext, new String[] {"demo"}); assertEquals("No such service demo", result); } @Test void testChangeCancel() { String result = change.execute(mockCommandContext, new String[] {".."}); assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result); } @Test void testChangeCancel2() { String result = change.execute(mockCommandContext, new String[] {"/"}); assertEquals("Cancelled default service org.apache.dubbo.rpc.protocol.dubbo.support.DemoService.", result); } }
8,258
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/ShutdownTelnetTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.remoting.RemotingException; import org.apache.dubbo.rpc.model.FrameworkModel; import io.netty.channel.Channel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; class ShutdownTelnetTest { private BaseCommand shutdown; private Channel mockChannel; private CommandContext mockCommandContext; @BeforeEach public void setUp() { shutdown = new ShutdownTelnet(FrameworkModel.defaultModel()); mockCommandContext = mock(CommandContext.class); mockChannel = mock(Channel.class); given(mockCommandContext.getRemote()).willReturn(mockChannel); } @AfterEach public void after() { FrameworkModel.destroyAll(); reset(mockChannel, mockCommandContext); } @Test void testInvoke() throws RemotingException { String result = shutdown.execute(mockCommandContext, new String[0]); assertTrue(result.contains("Application has shutdown successfully")); } @Test void testInvokeWithTimeParameter() throws RemotingException { int sleepTime = 2000; long start = System.currentTimeMillis(); String result = shutdown.execute(mockCommandContext, new String[] {"-t", "" + sleepTime}); long end = System.currentTimeMillis(); assertTrue(result.contains("Application has shutdown successfully"), result); assertTrue((end - start) >= sleepTime, "sleepTime: " + sleepTime + ", execTime: " + (end - start)); } }
8,259
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SerializeCheckStatusTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.utils.SerializeSecurityManager; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class SerializeCheckStatusTest { @Test void testNotify() { FrameworkModel frameworkModel = new FrameworkModel(); SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeCheckStatus serializeCheckStatus = new SerializeCheckStatus(frameworkModel); CommandContext commandContext1 = Mockito.mock(CommandContext.class); Mockito.when(commandContext1.isHttp()).thenReturn(false); CommandContext commandContext2 = Mockito.mock(CommandContext.class); Mockito.when(commandContext2.isHttp()).thenReturn(true); Assertions.assertFalse( serializeCheckStatus.execute(commandContext1, null).contains("Test1234")); Assertions.assertFalse( serializeCheckStatus.execute(commandContext2, null).contains("Test1234")); ssm.addToAllowed("Test1234"); Assertions.assertTrue( serializeCheckStatus.execute(commandContext1, null).contains("Test1234")); Assertions.assertTrue( serializeCheckStatus.execute(commandContext2, null).contains("Test1234")); Assertions.assertFalse( serializeCheckStatus.execute(commandContext1, null).contains("Test4321")); Assertions.assertFalse( serializeCheckStatus.execute(commandContext2, null).contains("Test4321")); ssm.addToDisAllowed("Test4321"); Assertions.assertTrue( serializeCheckStatus.execute(commandContext1, null).contains("Test4321")); Assertions.assertTrue( serializeCheckStatus.execute(commandContext2, null).contains("Test4321")); Assertions.assertFalse( serializeCheckStatus.execute(commandContext1, null).contains("CheckSerializable: false")); Assertions.assertFalse( serializeCheckStatus.execute(commandContext2, null).contains("\"checkSerializable\":false")); ssm.setCheckSerializable(false); Assertions.assertTrue( serializeCheckStatus.execute(commandContext1, null).contains("CheckSerializable: false")); Assertions.assertTrue( serializeCheckStatus.execute(commandContext2, null).contains("\"checkSerializable\":false")); Assertions.assertFalse( serializeCheckStatus.execute(commandContext1, null).contains("CheckStatus: DISABLE")); Assertions.assertFalse( serializeCheckStatus.execute(commandContext2, null).contains("\"checkStatus\":\"DISABLE\"")); ssm.setCheckStatus(org.apache.dubbo.common.utils.SerializeCheckStatus.DISABLE); Assertions.assertTrue( serializeCheckStatus.execute(commandContext1, null).contains("CheckStatus: DISABLE")); Assertions.assertTrue( serializeCheckStatus.execute(commandContext2, null).contains("\"checkStatus\":\"DISABLE\"")); frameworkModel.destroy(); } }
8,260
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/TestInterface2.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; public interface TestInterface2 { String sayHello(); }
8,261
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/channel/MockNettyChannel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl.channel; import org.apache.dubbo.common.URL; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelConfig; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelId; import io.netty.channel.ChannelMetadata; import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelProgressivePromise; import io.netty.channel.ChannelPromise; import io.netty.channel.EventLoop; import io.netty.util.Attribute; import io.netty.util.AttributeKey; import io.netty.util.AttributeMap; import io.netty.util.DefaultAttributeMap; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; public class MockNettyChannel implements Channel { InetSocketAddress localAddress; InetSocketAddress remoteAddress; private URL remoteUrl; private List<Object> receivedObjects = new LinkedList<>(); public static final String ERROR_WHEN_SEND = "error_when_send"; private CountDownLatch latch; private AttributeMap attributeMap = new DefaultAttributeMap(); public MockNettyChannel(URL remoteUrl, CountDownLatch latch) { this.remoteUrl = remoteUrl; this.latch = latch; } @Override public ChannelFuture writeAndFlush(Object msg) { receivedObjects.add(msg); if (latch != null) { latch.countDown(); } return newPromise(); } @Override public ChannelPromise newPromise() { return new ChannelPromise() { @Override public Channel channel() { return null; } @Override public ChannelPromise setSuccess(Void result) { return null; } @Override public ChannelPromise setSuccess() { return null; } @Override public boolean trySuccess() { return false; } @Override public ChannelPromise setFailure(Throwable cause) { return null; } @Override public ChannelPromise addListener(GenericFutureListener<? extends Future<? super Void>> listener) { return null; } @Override public ChannelPromise addListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) { return null; } @Override public ChannelPromise removeListener(GenericFutureListener<? extends Future<? super Void>> listener) { return null; } @Override public ChannelPromise removeListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) { return null; } @Override public ChannelPromise sync() throws InterruptedException { return null; } @Override public ChannelPromise syncUninterruptibly() { return null; } @Override public ChannelPromise await() throws InterruptedException { return this; } @Override public ChannelPromise awaitUninterruptibly() { return null; } @Override public ChannelPromise unvoid() { return null; } @Override public boolean isVoid() { return false; } @Override public boolean trySuccess(Void result) { return false; } @Override public boolean tryFailure(Throwable cause) { return false; } @Override public boolean setUncancellable() { return false; } @Override public boolean isSuccess() { return false; } @Override public boolean isCancellable() { return false; } @Override public Throwable cause() { return null; } @Override public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return true; } @Override public boolean await(long timeoutMillis) throws InterruptedException { return true; } @Override public boolean awaitUninterruptibly(long timeout, TimeUnit unit) { return true; } @Override public boolean awaitUninterruptibly(long timeoutMillis) { return false; } @Override public Void getNow() { return null; } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return false; } @Override public Void get() throws InterruptedException, ExecutionException { return null; } @Override public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return null; } }; } @Override public ChannelProgressivePromise newProgressivePromise() { return null; } @Override public ChannelFuture newSucceededFuture() { return null; } @Override public ChannelFuture newFailedFuture(Throwable cause) { return null; } @Override public ChannelPromise voidPromise() { return null; } @Override public ChannelId id() { return null; } @Override public EventLoop eventLoop() { return null; } @Override public Channel parent() { return null; } @Override public ChannelConfig config() { return null; } @Override public boolean isOpen() { return false; } @Override public boolean isRegistered() { return false; } @Override public boolean isActive() { return false; } @Override public ChannelMetadata metadata() { return null; } @Override public SocketAddress localAddress() { return null; } @Override public SocketAddress remoteAddress() { return null; } @Override public ChannelFuture closeFuture() { return null; } @Override public boolean isWritable() { return false; } @Override public long bytesBeforeUnwritable() { return 0; } @Override public long bytesBeforeWritable() { return 0; } @Override public Unsafe unsafe() { return null; } @Override public ChannelPipeline pipeline() { return null; } @Override public ByteBufAllocator alloc() { return null; } @Override public ChannelFuture bind(SocketAddress localAddress) { return null; } @Override public ChannelFuture connect(SocketAddress remoteAddress) { return null; } @Override public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { return null; } @Override public ChannelFuture disconnect() { return null; } @Override public ChannelFuture close() { return null; } @Override public ChannelFuture deregister() { return null; } @Override public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) { return null; } @Override public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { return null; } @Override public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { return null; } @Override public ChannelFuture disconnect(ChannelPromise promise) { return null; } @Override public ChannelFuture close(ChannelPromise promise) { return null; } @Override public ChannelFuture deregister(ChannelPromise promise) { return null; } @Override public Channel read() { return null; } @Override public ChannelFuture write(Object msg) { return null; } @Override public ChannelFuture write(Object msg, ChannelPromise promise) { return null; } @Override public Channel flush() { return null; } @Override public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { return null; } @Override public <T> Attribute<T> attr(AttributeKey<T> key) { return attributeMap.attr(key); } @Override public <T> boolean hasAttr(AttributeKey<T> key) { return attributeMap.hasAttr(key); } @Override public int compareTo(Channel o) { return 0; } public List<Object> getReceivedObjects() { return receivedObjects; } }
8,262
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/ServiceCheckUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.util; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.qos.DemoService; import org.apache.dubbo.qos.DemoServiceImpl; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.client.migration.MigrationInvoker; import org.apache.dubbo.registry.client.migration.model.MigrationStep; import org.apache.dubbo.rpc.cluster.ClusterInvoker; import org.apache.dubbo.rpc.cluster.Directory; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ConsumerModel; import org.apache.dubbo.rpc.model.ModuleServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.rpc.model.ServiceMetadata; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for ServiceCheckUtils */ class ServiceCheckUtilsTest { private final ModuleServiceRepository repository = ApplicationModel.defaultModel().getDefaultModule().getServiceRepository(); @Test void testIsRegistered() { DemoService demoServiceImpl = new DemoServiceImpl(); int availablePort = NetUtils.getAvailablePort(); URL url = URL.valueOf("tri://127.0.0.1:" + availablePort + "/" + DemoService.class.getName()); ServiceDescriptor serviceDescriptor = repository.registerService(DemoService.class); ProviderModel providerModel = new ProviderModel( url.getServiceKey(), demoServiceImpl, serviceDescriptor, new ServiceMetadata(), ClassUtils.getClassLoader(DemoService.class)); repository.registerProvider(providerModel); String url1 = "service-discovery-registry://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099&registry=zookeeper&timestamp=1654588337653"; String url2 = "zookeeper://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099&timestamp=1654588337653"; providerModel.getStatedUrl().add(new ProviderModel.RegisterStatedURL(url, URL.valueOf(url1), true)); providerModel.getStatedUrl().add(new ProviderModel.RegisterStatedURL(url, URL.valueOf(url2), false)); Assertions.assertEquals("zookeeper-A(Y)/zookeeper-I(N)", ServiceCheckUtils.getRegisterStatus(providerModel)); } @Test void testGetConsumerAddressNum() { ConsumerModel consumerModel = Mockito.mock(ConsumerModel.class); ServiceMetadata serviceMetadata = Mockito.mock(ServiceMetadata.class); Mockito.when(consumerModel.getServiceMetadata()).thenReturn(serviceMetadata); String registry1 = "service-discovery-registry://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099&registry=zookeeper&timestamp=1654588337653"; String registry2 = "zookeeper://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099&timestamp=1654588337653"; String registry3 = "nacos://127.0.0.1:8848/org.apache.dubbo.registry.RegistryService?application=dubbo-demo-api-provider&dubbo=2.0.2&pid=66099&timestamp=1654588337653"; Map<Registry, MigrationInvoker<?>> invokerMap = new LinkedHashMap<>(); { Registry registry = Mockito.mock(Registry.class); Mockito.when(registry.getUrl()).thenReturn(URL.valueOf(registry1)); MigrationInvoker<?> migrationInvoker = Mockito.mock(MigrationInvoker.class); Mockito.when(migrationInvoker.getMigrationStep()).thenReturn(MigrationStep.FORCE_APPLICATION); ClusterInvoker serviceDiscoveryInvoker = Mockito.mock(ClusterInvoker.class); Mockito.when(migrationInvoker.getServiceDiscoveryInvoker()).thenReturn(serviceDiscoveryInvoker); Directory<?> sdDirectory = Mockito.mock(Directory.class); Mockito.when(serviceDiscoveryInvoker.getDirectory()).thenReturn(sdDirectory); List sdInvokers = Mockito.mock(List.class); Mockito.when(sdDirectory.getAllInvokers()).thenReturn(sdInvokers); Mockito.when(sdInvokers.size()).thenReturn(5); invokerMap.put(registry, migrationInvoker); } { Registry registry = Mockito.mock(Registry.class); Mockito.when(registry.getUrl()).thenReturn(URL.valueOf(registry2)); MigrationInvoker<?> migrationInvoker = Mockito.mock(MigrationInvoker.class); Mockito.when(migrationInvoker.getMigrationStep()).thenReturn(MigrationStep.APPLICATION_FIRST); ClusterInvoker serviceDiscoveryInvoker = Mockito.mock(ClusterInvoker.class); Mockito.when(migrationInvoker.getServiceDiscoveryInvoker()).thenReturn(serviceDiscoveryInvoker); Directory<?> sdDirectory = Mockito.mock(Directory.class); Mockito.when(serviceDiscoveryInvoker.getDirectory()).thenReturn(sdDirectory); List sdInvokers = Mockito.mock(List.class); Mockito.when(sdDirectory.getAllInvokers()).thenReturn(sdInvokers); Mockito.when(sdInvokers.size()).thenReturn(0); ClusterInvoker invoker = Mockito.mock(ClusterInvoker.class); Mockito.when(migrationInvoker.getInvoker()).thenReturn(invoker); Directory<?> directory = Mockito.mock(Directory.class); Mockito.when(invoker.getDirectory()).thenReturn(directory); List invokers = Mockito.mock(List.class); Mockito.when(directory.getAllInvokers()).thenReturn(invokers); Mockito.when(invokers.size()).thenReturn(10); invokerMap.put(registry, migrationInvoker); } { Registry registry = Mockito.mock(Registry.class); Mockito.when(registry.getUrl()).thenReturn(URL.valueOf(registry3)); MigrationInvoker<?> migrationInvoker = Mockito.mock(MigrationInvoker.class); Mockito.when(migrationInvoker.getMigrationStep()).thenReturn(MigrationStep.FORCE_INTERFACE); ClusterInvoker invoker = Mockito.mock(ClusterInvoker.class); Mockito.when(migrationInvoker.getInvoker()).thenReturn(invoker); Directory<?> directory = Mockito.mock(Directory.class); Mockito.when(invoker.getDirectory()).thenReturn(directory); List invokers = Mockito.mock(List.class); Mockito.when(directory.getAllInvokers()).thenReturn(invokers); Mockito.when(invokers.size()).thenReturn(10); invokerMap.put(registry, migrationInvoker); } Mockito.when(serviceMetadata.getAttribute("currentClusterInvoker")).thenReturn(invokerMap); assertEquals( "zookeeper-A(5)/zookeeper-AF(I-10,A-0)/nacos-I(10)", ServiceCheckUtils.getConsumerAddressNum(consumerModel)); } }
8,263
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/SerializeCheckUtilsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.util; import org.apache.dubbo.common.utils.SerializeCheckStatus; import org.apache.dubbo.common.utils.SerializeSecurityManager; import org.apache.dubbo.rpc.model.FrameworkModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class SerializeCheckUtilsTest { @Test void testNotify() { FrameworkModel frameworkModel = new FrameworkModel(); SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeCheckUtils serializeCheckUtils = new SerializeCheckUtils(frameworkModel); ssm.addToAllowed("Test1234"); Assertions.assertTrue(serializeCheckUtils.getAllowedList().contains("Test1234")); ssm.addToDisAllowed("Test4321"); Assertions.assertTrue(serializeCheckUtils.getDisAllowedList().contains("Test4321")); ssm.setCheckSerializable(false); Assertions.assertFalse(serializeCheckUtils.isCheckSerializable()); ssm.setCheckStatus(SerializeCheckStatus.DISABLE); Assertions.assertEquals(SerializeCheckStatus.DISABLE, serializeCheckUtils.getStatus()); frameworkModel.destroy(); } }
8,264
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/util/CommandHelperTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.util; import org.apache.dubbo.qos.command.GreetingCommand; import org.apache.dubbo.qos.command.impl.ChangeTelnet; import org.apache.dubbo.qos.command.impl.CountTelnet; import org.apache.dubbo.qos.command.impl.DefaultMetricsReporterCmd; import org.apache.dubbo.qos.command.impl.DisableDetailProfiler; import org.apache.dubbo.qos.command.impl.DisableRouterSnapshot; import org.apache.dubbo.qos.command.impl.DisableSimpleProfiler; import org.apache.dubbo.qos.command.impl.EnableDetailProfiler; import org.apache.dubbo.qos.command.impl.EnableRouterSnapshot; import org.apache.dubbo.qos.command.impl.EnableSimpleProfiler; import org.apache.dubbo.qos.command.impl.GetAddress; import org.apache.dubbo.qos.command.impl.GetConfig; import org.apache.dubbo.qos.command.impl.GetEnabledRouterSnapshot; import org.apache.dubbo.qos.command.impl.GetRecentRouterSnapshot; import org.apache.dubbo.qos.command.impl.GetRouterSnapshot; import org.apache.dubbo.qos.command.impl.GracefulShutdown; import org.apache.dubbo.qos.command.impl.Help; import org.apache.dubbo.qos.command.impl.InvokeTelnet; import org.apache.dubbo.qos.command.impl.Live; import org.apache.dubbo.qos.command.impl.LoggerInfo; import org.apache.dubbo.qos.command.impl.Ls; import org.apache.dubbo.qos.command.impl.Offline; import org.apache.dubbo.qos.command.impl.OfflineApp; import org.apache.dubbo.qos.command.impl.OfflineInterface; import org.apache.dubbo.qos.command.impl.Online; import org.apache.dubbo.qos.command.impl.OnlineApp; import org.apache.dubbo.qos.command.impl.OnlineInterface; import org.apache.dubbo.qos.command.impl.PortTelnet; import org.apache.dubbo.qos.command.impl.PublishMetadata; import org.apache.dubbo.qos.command.impl.PwdTelnet; import org.apache.dubbo.qos.command.impl.Quit; import org.apache.dubbo.qos.command.impl.Ready; import org.apache.dubbo.qos.command.impl.SelectTelnet; import org.apache.dubbo.qos.command.impl.SerializeCheckStatus; import org.apache.dubbo.qos.command.impl.SerializeWarnedClasses; import org.apache.dubbo.qos.command.impl.SetProfilerWarnPercent; import org.apache.dubbo.qos.command.impl.ShutdownTelnet; import org.apache.dubbo.qos.command.impl.Startup; import org.apache.dubbo.qos.command.impl.SwitchLogLevel; import org.apache.dubbo.qos.command.impl.SwitchLogger; import org.apache.dubbo.qos.command.impl.Version; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.LinkedList; import java.util.List; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; class CommandHelperTest { private CommandHelper commandHelper = new CommandHelper(FrameworkModel.defaultModel()); @Test void testHasCommand() { assertTrue(commandHelper.hasCommand("greeting")); assertFalse(commandHelper.hasCommand("not-exiting")); } @Test void testGetAllCommandClass() { List<Class<?>> classes = commandHelper.getAllCommandClass(); // update this list when introduce a new command List<Class<?>> expectedClasses = new LinkedList<>(); expectedClasses.add(GreetingCommand.class); expectedClasses.add(Help.class); expectedClasses.add(Live.class); expectedClasses.add(Ls.class); expectedClasses.add(Offline.class); expectedClasses.add(OfflineApp.class); expectedClasses.add(OfflineInterface.class); expectedClasses.add(Online.class); expectedClasses.add(OnlineApp.class); expectedClasses.add(OnlineInterface.class); expectedClasses.add(PublishMetadata.class); expectedClasses.add(Quit.class); expectedClasses.add(Ready.class); expectedClasses.add(Startup.class); expectedClasses.add(Version.class); expectedClasses.add(ChangeTelnet.class); expectedClasses.add(CountTelnet.class); expectedClasses.add(InvokeTelnet.class); expectedClasses.add(SelectTelnet.class); expectedClasses.add(PortTelnet.class); expectedClasses.add(PwdTelnet.class); expectedClasses.add(ShutdownTelnet.class); expectedClasses.add(EnableDetailProfiler.class); expectedClasses.add(DisableDetailProfiler.class); expectedClasses.add(EnableSimpleProfiler.class); expectedClasses.add(DisableSimpleProfiler.class); expectedClasses.add(SetProfilerWarnPercent.class); expectedClasses.add(GetRouterSnapshot.class); expectedClasses.add(GetEnabledRouterSnapshot.class); expectedClasses.add(EnableRouterSnapshot.class); expectedClasses.add(DisableRouterSnapshot.class); expectedClasses.add(GetRecentRouterSnapshot.class); expectedClasses.add(LoggerInfo.class); expectedClasses.add(SwitchLogger.class); expectedClasses.add(SwitchLogLevel.class); expectedClasses.add(SerializeCheckStatus.class); expectedClasses.add(SerializeWarnedClasses.class); expectedClasses.add(GetConfig.class); expectedClasses.add(GetAddress.class); expectedClasses.add(GracefulShutdown.class); expectedClasses.add(DefaultMetricsReporterCmd.class); assertThat(classes, containsInAnyOrder(expectedClasses.toArray(new Class<?>[0]))); } @Test void testGetCommandClass() { assertThat(commandHelper.getCommandClass("greeting"), equalTo(GreetingCommand.class)); assertNull(commandHelper.getCommandClass("not-exiting")); } }
8,265
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.decoder; import org.apache.dubbo.qos.api.CommandContext; import java.nio.charset.StandardCharsets; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class HttpCommandDecoderTest { @Test void decodeGet() { HttpRequest request = mock(HttpRequest.class); when(request.uri()).thenReturn("localhost:80/test"); when(request.method()).thenReturn(HttpMethod.GET); CommandContext context = HttpCommandDecoder.decode(request); assertThat(context.getCommandName(), equalTo("test")); assertThat(context.isHttp(), is(true)); when(request.uri()).thenReturn("localhost:80/test?a=b&c=d"); context = HttpCommandDecoder.decode(request); assertThat(context.getArgs(), arrayContaining("b", "d")); } @Test void decodePost() { FullHttpRequest request = mock(FullHttpRequest.class); when(request.uri()).thenReturn("localhost:80/test"); when(request.method()).thenReturn(HttpMethod.POST); when(request.headers()).thenReturn(HttpHeaders.EMPTY_HEADERS); ByteBuf buf = Unpooled.copiedBuffer("a=b&c=d", StandardCharsets.UTF_8); when(request.content()).thenReturn(buf); CommandContext context = HttpCommandDecoder.decode(request); assertThat(context.getCommandName(), equalTo("test")); assertThat(context.isHttp(), is(true)); assertThat(context.getArgs(), arrayContaining("b", "d")); } }
8,266
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/decoder/TelnetCommandDecoderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.decoder; import org.apache.dubbo.qos.api.CommandContext; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; class TelnetCommandDecoderTest { @Test void testDecode() throws Exception { CommandContext context = TelnetCommandDecoder.decode("test a b"); assertThat(context.getCommandName(), equalTo("test")); assertThat(context.isHttp(), is(false)); assertThat(context.getArgs(), arrayContaining("a", "b")); } }
8,267
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/permission/DefaultAnonymousAccessPermissionCheckerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.permission; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.qos.api.QosConfiguration; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import io.netty.channel.Channel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; class DefaultAnonymousAccessPermissionCheckerTest { @Test void testPermission() throws UnknownHostException { InetAddress inetAddress = InetAddress.getByName("127.0.0.1"); InetSocketAddress socketAddress = Mockito.mock(InetSocketAddress.class); Mockito.when(socketAddress.getAddress()).thenReturn(inetAddress); Channel channel = Mockito.mock(Channel.class); Mockito.when(channel.remoteAddress()).thenReturn(socketAddress); CommandContext commandContext = Mockito.mock(CommandContext.class); Mockito.when(commandContext.getRemote()).thenReturn(channel); QosConfiguration qosConfiguration = Mockito.mock(QosConfiguration.class); Mockito.when(qosConfiguration.getAnonymousAccessPermissionLevel()).thenReturn(PermissionLevel.PUBLIC); Mockito.when(qosConfiguration.getAcceptForeignIpWhitelistPredicate()).thenReturn(ip -> false); Mockito.when(commandContext.getQosConfiguration()).thenReturn(qosConfiguration); DefaultAnonymousAccessPermissionChecker checker = new DefaultAnonymousAccessPermissionChecker(); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.NONE)); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PUBLIC)); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PROTECTED)); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PRIVATE)); inetAddress = InetAddress.getByName("1.1.1.1"); Mockito.when(socketAddress.getAddress()).thenReturn(inetAddress); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.NONE)); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PUBLIC)); Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PROTECTED)); Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PRIVATE)); Mockito.when(qosConfiguration.getAnonymousAccessPermissionLevel()).thenReturn(PermissionLevel.PROTECTED); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.NONE)); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PUBLIC)); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PROTECTED)); Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PRIVATE)); Mockito.when(qosConfiguration.getAnonymousAccessPermissionLevel()).thenReturn(PermissionLevel.NONE); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.NONE)); Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PUBLIC)); Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PROTECTED)); Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PRIVATE)); Mockito.when(qosConfiguration.getAcceptForeignIpWhitelistPredicate()).thenReturn(ip -> true); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.NONE)); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PUBLIC)); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PROTECTED)); Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PRIVATE)); Mockito.when(qosConfiguration.getAcceptForeignIpWhitelistPredicate()).thenReturn(ip -> false); Mockito.when(qosConfiguration.getAnonymousAllowCommands()).thenReturn("test1,test2"); Mockito.when(commandContext.getCommandName()).thenReturn("test1"); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.NONE)); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PUBLIC)); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PROTECTED)); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PRIVATE)); Mockito.when(commandContext.getCommandName()).thenReturn("test2"); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.NONE)); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PUBLIC)); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PROTECTED)); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.PRIVATE)); Mockito.when(commandContext.getCommandName()).thenReturn("test"); Assertions.assertTrue(checker.access(commandContext, PermissionLevel.NONE)); Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PUBLIC)); Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PROTECTED)); Assertions.assertFalse(checker.access(commandContext, PermissionLevel.PRIVATE)); } }
8,268
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/QosScopeModelInitializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos; import org.apache.dubbo.common.beans.factory.ScopeBeanFactory; import org.apache.dubbo.qos.command.util.SerializeCheckUtils; import org.apache.dubbo.qos.server.Server; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ScopeModelInitializer; public class QosScopeModelInitializer implements ScopeModelInitializer { @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) { ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory(); beanFactory.registerBean(Server.class); beanFactory.registerBean(SerializeCheckUtils.class); } @Override public void initializeApplicationModel(ApplicationModel applicationModel) {} @Override public void initializeModuleModel(ModuleModel moduleModel) {} }
8,269
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TKv.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.textui; import org.apache.dubbo.common.utils.StringUtils; import java.util.Scanner; /** * KV */ public class TKv implements TComponent { private final TTable tTable; public TKv() { this.tTable = new TTable(new TTable.ColumnDefine[] { new TTable.ColumnDefine(TTable.Align.RIGHT), new TTable.ColumnDefine(TTable.Align.RIGHT), new TTable.ColumnDefine(TTable.Align.LEFT) }) .padding(0); this.tTable.getBorder().set(TTable.Border.BORDER_NON); } public TKv(TTable.ColumnDefine keyColumnDefine, TTable.ColumnDefine valueColumnDefine) { this.tTable = new TTable(new TTable.ColumnDefine[] { keyColumnDefine, new TTable.ColumnDefine(TTable.Align.RIGHT), valueColumnDefine }) .padding(0); this.tTable.getBorder().set(TTable.Border.BORDER_NON); } public TKv add(final Object key, final Object value) { tTable.addRow(key, " : ", value); return this; } @Override public String rendering() { return filterEmptyLine(tTable.rendering()); } private String filterEmptyLine(String content) { final StringBuilder sb = new StringBuilder(); try (Scanner scanner = new Scanner(content)) { while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line != null) { // remove extra space at line's end line = StringUtils.stripEnd(line, " "); if (line.isEmpty()) { line = " "; } } sb.append(line).append(System.lineSeparator()); } } return sb.toString(); } }
8,270
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TComponent.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.textui; /** * render component */ public interface TComponent { /** * render */ String rendering(); }
8,271
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTree.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.textui; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import static java.lang.System.currentTimeMillis; import static org.apache.dubbo.common.utils.StringUtils.EMPTY_STRING; import static org.apache.dubbo.common.utils.StringUtils.length; import static org.apache.dubbo.common.utils.StringUtils.repeat; /** * tree */ public class TTree implements TComponent { private static final String STEP_FIRST_CHAR = "`---"; private static final String STEP_NORMAL_CHAR = "+---"; private static final String STEP_HAS_BOARD = "| "; private static final String STEP_EMPTY_BOARD = " "; // should output cost or not private final boolean isPrintCost; // tree node private final Node root; // current node private Node current; public TTree(boolean isPrintCost, String title) { this.root = new Node(title).markBegin().markEnd(); this.current = root; this.isPrintCost = isPrintCost; } @Override public String rendering() { final StringBuilder treeSB = new StringBuilder(); recursive(0, true, "", root, new Callback() { @Override public void callback(int deep, boolean isLast, String prefix, Node node) { final boolean hasChild = !node.children.isEmpty(); final String stepString = isLast ? STEP_FIRST_CHAR : STEP_NORMAL_CHAR; final int stepStringLength = length(stepString); treeSB.append(prefix).append(stepString); int costPrefixLength = 0; if (hasChild) { treeSB.append('+'); } if (isPrintCost && !node.isRoot()) { final String costPrefix = String.format( "[%s,%sms]", (node.endTimestamp - root.beginTimestamp), (node.endTimestamp - node.beginTimestamp)); costPrefixLength = length(costPrefix); treeSB.append(costPrefix); } try (Scanner scanner = new Scanner(new StringReader(node.data.toString()))) { boolean isFirst = true; while (scanner.hasNextLine()) { if (isFirst) { treeSB.append(scanner.nextLine()).append('\n'); isFirst = false; } else { treeSB.append(prefix) .append(repeat(' ', stepStringLength)) .append(hasChild ? "|" : EMPTY_STRING) .append(repeat(' ', costPrefixLength)) .append(scanner.nextLine()) .append(System.lineSeparator()); } } } } }); return treeSB.toString(); } /** * recursive visit */ private void recursive(int deep, boolean isLast, String prefix, Node node, Callback callback) { callback.callback(deep, isLast, prefix, node); if (!node.isLeaf()) { final int size = node.children.size(); for (int index = 0; index < size; index++) { final boolean isLastFlag = index == size - 1; final String currentPrefix = isLast ? prefix + STEP_EMPTY_BOARD : prefix + STEP_HAS_BOARD; recursive(deep + 1, isLastFlag, currentPrefix, node.children.get(index), callback); } } } public boolean isTop() { return current.isRoot(); } /** * create a branch node * * @param data node data * @return this */ public TTree begin(Object data) { current = new Node(current, data); current.markBegin(); return this; } public TTree begin() { return begin(null); } public Object get() { if (current.isRoot()) { throw new IllegalStateException("current node is root."); } return current.data; } public TTree set(Object data) { if (current.isRoot()) { throw new IllegalStateException("current node is root."); } current.data = data; return this; } /** * end a branch node * * @return this */ public TTree end() { if (current.isRoot()) { throw new IllegalStateException("current node is root."); } current.markEnd(); current = current.parent; return this; } /** * tree node */ private static class Node { /** * parent node */ final Node parent; /** * node data */ Object data; /** * child nodes */ final List<Node> children = new ArrayList<Node>(); /** * begin timestamp */ private long beginTimestamp; /** * end timestamp */ private long endTimestamp; /** * construct root node */ private Node(Object data) { this.parent = null; this.data = data; } /** * construct a regular node * * @param parent parent node * @param data node data */ private Node(Node parent, Object data) { this.parent = parent; this.data = data; parent.children.add(this); } /** * is the current node the root node * * @return true / false */ boolean isRoot() { return null == parent; } /** * if the current node the leaf node * * @return true / false */ boolean isLeaf() { return children.isEmpty(); } Node markBegin() { beginTimestamp = currentTimeMillis(); return this; } Node markEnd() { endTimestamp = currentTimeMillis(); return this; } } /** * callback interface for recursive visit */ private interface Callback { void callback(int deep, boolean isLast, String prefix, Node node); } }
8,272
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TTable.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.textui; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.String.format; import static org.apache.dubbo.common.utils.StringUtils.EMPTY_STRING; import static org.apache.dubbo.common.utils.StringUtils.length; import static org.apache.dubbo.common.utils.StringUtils.repeat; import static org.apache.dubbo.common.utils.StringUtils.replace; /** * Table */ public class TTable implements TComponent { // column definition private final ColumnDefine[] columnDefineArray; // border private final Border border = new Border(); // padding private int padding; public TTable(ColumnDefine[] columnDefineArray) { this.columnDefineArray = null == columnDefineArray ? new ColumnDefine[0] : columnDefineArray; } public TTable(int columnNum) { this.columnDefineArray = new ColumnDefine[columnNum]; for (int index = 0; index < this.columnDefineArray.length; index++) { columnDefineArray[index] = new ColumnDefine(); } } @Override public String rendering() { final StringBuilder tableSB = new StringBuilder(); // process width cache final int[] widthCacheArray = new int[getColumnCount()]; for (int index = 0; index < widthCacheArray.length; index++) { widthCacheArray[index] = abs(columnDefineArray[index].getWidth()); } final int rowCount = getRowCount(); for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) { final boolean isFirstRow = rowIndex == 0; final boolean isLastRow = rowIndex == rowCount - 1; // print first separation line if (isFirstRow && border.has(Border.BORDER_OUTER_TOP)) { tableSB.append(drawSeparationLine(widthCacheArray)).append(System.lineSeparator()); } // print inner separation lines if (!isFirstRow && border.has(Border.BORDER_INNER_H)) { tableSB.append(drawSeparationLine(widthCacheArray)).append(System.lineSeparator()); } // draw one line tableSB.append(drawRow(widthCacheArray, rowIndex)); // print ending separation line if (isLastRow && border.has(Border.BORDER_OUTER_BOTTOM)) { tableSB.append(drawSeparationLine(widthCacheArray)).append(System.lineSeparator()); } } return tableSB.toString(); } private String drawRow(int[] widthCacheArray, int rowIndex) { final StringBuilder rowSB = new StringBuilder(); final Scanner[] scannerArray = new Scanner[getColumnCount()]; try { boolean hasNextLine; do { hasNextLine = false; final StringBuilder segmentSB = new StringBuilder(); for (int colIndex = 0; colIndex < getColumnCount(); colIndex++) { final int width = widthCacheArray[colIndex]; final boolean isFirstColOfRow = colIndex == 0; final boolean isLastColOfRow = colIndex == widthCacheArray.length - 1; final String borderChar; if (isFirstColOfRow && border.has(Border.BORDER_OUTER_LEFT)) { borderChar = "|"; } else if (!isFirstColOfRow && border.has(Border.BORDER_INNER_V)) { borderChar = "|"; } else { borderChar = EMPTY_STRING; } if (null == scannerArray[colIndex]) { scannerArray[colIndex] = new Scanner( new StringReader(wrap(getData(rowIndex, columnDefineArray[colIndex]), width))); } final Scanner scanner = scannerArray[colIndex]; final String data; if (scanner.hasNextLine()) { data = scanner.nextLine(); hasNextLine = true; } else { data = EMPTY_STRING; } if (width > 0) { final ColumnDefine columnDefine = columnDefineArray[colIndex]; final String dataFormat = getDataFormat(columnDefine, width, data); final String paddingChar = repeat(" ", padding); segmentSB.append(format(borderChar + paddingChar + dataFormat + paddingChar, data)); } if (isLastColOfRow) { if (border.has(Border.BORDER_OUTER_RIGHT)) { segmentSB.append('|'); } segmentSB.append(System.lineSeparator()); } } if (hasNextLine) { rowSB.append(segmentSB); } } while (hasNextLine); return rowSB.toString(); } finally { for (Scanner scanner : scannerArray) { if (null != scanner) { scanner.close(); } } } } private String getData(int rowIndex, ColumnDefine columnDefine) { return columnDefine.getRowCount() <= rowIndex ? EMPTY_STRING : columnDefine.rows.get(rowIndex); } private String getDataFormat(ColumnDefine columnDefine, int width, String data) { switch (columnDefine.align) { case MIDDLE: { final int length = length(data); final int diff = width - length; final int left = diff / 2; return repeat(" ", diff - left) + "%s" + repeat(" ", left); } case RIGHT: { return "%" + width + "s"; } case LEFT: default: { return "%-" + width + "s"; } } } /** * get row count */ private int getRowCount() { int rowCount = 0; for (ColumnDefine columnDefine : columnDefineArray) { rowCount = max(rowCount, columnDefine.getRowCount()); } return rowCount; } /** * position to last column */ private int indexLastCol(final int[] widthCacheArray) { for (int colIndex = widthCacheArray.length - 1; colIndex >= 0; colIndex--) { final int width = widthCacheArray[colIndex]; if (width <= 0) { continue; } return colIndex; } return 0; } /** * draw separation line */ private String drawSeparationLine(final int[] widthCacheArray) { final StringBuilder separationLineSB = new StringBuilder(); final int lastCol = indexLastCol(widthCacheArray); final int colCount = widthCacheArray.length; for (int colIndex = 0; colIndex < colCount; colIndex++) { final int width = widthCacheArray[colIndex]; if (width <= 0) { continue; } final boolean isFirstCol = colIndex == 0; final boolean isLastCol = colIndex == lastCol; if (isFirstCol && border.has(Border.BORDER_OUTER_LEFT)) { separationLineSB.append('+'); } if (!isFirstCol && border.has(Border.BORDER_INNER_V)) { separationLineSB.append('+'); } separationLineSB.append(repeat("-", width + 2 * padding)); if (isLastCol && border.has(Border.BORDER_OUTER_RIGHT)) { separationLineSB.append('+'); } } return separationLineSB.toString(); } /** * Add a row */ public TTable addRow(Object... columnDataArray) { if (null != columnDataArray) { for (int index = 0; index < columnDefineArray.length; index++) { final ColumnDefine columnDefine = columnDefineArray[index]; if (index < columnDataArray.length && null != columnDataArray[index]) { columnDefine.rows.add(replaceTab(columnDataArray[index].toString())); } else { columnDefine.rows.add(EMPTY_STRING); } } } return this; } /** * alignment */ public enum Align { /** * left-alignment */ LEFT, /** * right-alignment */ RIGHT, /** * middle-alignment */ MIDDLE } /** * column definition */ public static class ColumnDefine { // column width private final int width; // whether to auto resize private final boolean isAutoResize; // alignment private final Align align; // data rows private final List<String> rows = new ArrayList<String>(); public ColumnDefine(int width, boolean isAutoResize, Align align) { this.width = width; this.isAutoResize = isAutoResize; this.align = align; } public ColumnDefine(Align align) { this(0, true, align); } public ColumnDefine(int width) { this(width, false, Align.LEFT); } public ColumnDefine(int width, Align align) { this(width, false, align); } public ColumnDefine() { this(Align.LEFT); } /** * get current width * * @return width */ public int getWidth() { // if not auto resize, return preset width if (!isAutoResize) { return width; } // if it's auto resize, then calculate the possible max width int maxWidth = 0; for (String data : rows) { maxWidth = max(width(data), maxWidth); } return maxWidth; } /** * get rows for the current column * * @return current column's rows */ public int getRowCount() { return rows.size(); } } /** * set padding * * @param padding padding */ public TTable padding(int padding) { this.padding = padding; return this; } /** * get column count * * @return column count */ public int getColumnCount() { return columnDefineArray.length; } /** * replace tab to four spaces * * @param string the original string * @return the replaced string */ private static String replaceTab(String string) { return replace(string, "\t", " "); } /** * visible width for the given string. * * for example: "abc\n1234"'s width is 4. * * @param string the given string * @return visible width */ private static int width(String string) { int maxWidth = 0; try (Scanner scanner = new Scanner(new StringReader(string))) { while (scanner.hasNextLine()) { maxWidth = max(length(scanner.nextLine()), maxWidth); } } return maxWidth; } /** * get border * * @return table border */ public Border getBorder() { return border; } /** * border style */ public class Border { private int borders = BORDER_OUTER | BORDER_INNER; /** * border outer top */ public static final int BORDER_OUTER_TOP = 1 << 0; /** * border outer right */ public static final int BORDER_OUTER_RIGHT = 1 << 1; /** * border outer bottom */ public static final int BORDER_OUTER_BOTTOM = 1 << 2; /** * border outer left */ public static final int BORDER_OUTER_LEFT = 1 << 3; /** * inner border: horizon */ public static final int BORDER_INNER_H = 1 << 4; /** * inner border: vertical */ public static final int BORDER_INNER_V = 1 << 5; /** * outer border */ public static final int BORDER_OUTER = BORDER_OUTER_TOP | BORDER_OUTER_BOTTOM | BORDER_OUTER_LEFT | BORDER_OUTER_RIGHT; /** * inner border */ public static final int BORDER_INNER = BORDER_INNER_H | BORDER_INNER_V; /** * no border */ public static final int BORDER_NON = 0; /** * whether has one of the specified border styles * * @param borderArray border styles * @return whether has one of the specified border styles */ public boolean has(int... borderArray) { if (null == borderArray) { return false; } for (int b : borderArray) { if ((this.borders & b) == b) { return true; } } return false; } /** * get border style * * @return border style */ public int get() { return borders; } /** * set border style * * @param border border style * @return this */ public Border set(int border) { this.borders = border; return this; } public Border add(int border) { return set(get() | border); } public Border remove(int border) { return set(get() ^ border); } } public static String wrap(String string, int width) { final StringBuilder sb = new StringBuilder(); final char[] buffer = string.toCharArray(); int count = 0; for (char c : buffer) { if (count == width) { count = 0; sb.append('\n'); if (c == '\n') { continue; } } if (c == '\n') { count = 0; } else { count++; } sb.append(c); } return sb.toString(); } }
8,273
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/textui/TLadder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.textui; import java.util.LinkedList; import java.util.List; import static org.apache.dubbo.common.utils.StringUtils.repeat; /** * Ladder */ public class TLadder implements TComponent { // separator private static final String LADDER_CHAR = "`-"; // tab private static final String STEP_CHAR = " "; // indent length private static final int INDENT_STEP = 2; private final List<String> items = new LinkedList<String>(); @Override public String rendering() { final StringBuilder ladderSB = new StringBuilder(); int deep = 0; for (String item : items) { // no separator is required for the first item if (deep == 0) { ladderSB.append(item).append(System.lineSeparator()); } // need separator for others else { ladderSB.append(repeat(STEP_CHAR, deep * INDENT_STEP)) .append(LADDER_CHAR) .append(item) .append(System.lineSeparator()); } deep++; } return ladderSB.toString(); } /** * add one item */ public TLadder addItem(String item) { items.add(item); return this; } }
8,274
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/TraceTelnetHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.telnet.TelnetHandler; import org.apache.dubbo.remoting.telnet.support.Help; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; import org.apache.dubbo.rpc.protocol.dubbo.filter.TraceFilter; import java.lang.reflect.Method; /** * TraceTelnetHandler */ @Activate @Help(parameter = "[service] [method] [times]", summary = "Trace the service.", detail = "Trace the service.") public class TraceTelnetHandler implements TelnetHandler { @Override public String telnet(Channel channel, String message) { String service = (String) channel.getAttribute(ChangeTelnetHandler.SERVICE_KEY); if ((StringUtils.isEmpty(service)) && (StringUtils.isEmpty(message))) { return "Please input service name, eg: \r\ntrace XxxService\r\ntrace XxxService xxxMethod\r\ntrace XxxService xxxMethod 10\r\nor \"cd XxxService\" firstly."; } String[] parts = message.split("\\s+"); String method; String times; // message like : XxxService , XxxService 10 , XxxService xxxMethod , XxxService xxxMethod 10 if (StringUtils.isEmpty(service)) { service = parts.length > 0 ? parts[0] : null; method = parts.length > 1 ? parts[1] : null; times = parts.length > 2 ? parts[2] : "1"; } else { // message like : xxxMethod, xxxMethod 10 method = parts.length > 0 ? parts[0] : null; times = parts.length > 1 ? parts[1] : "1"; } if (StringUtils.isNumber(method)) { times = method; method = null; } if (!StringUtils.isNumber(times)) { return "Illegal times " + times + ", must be integer."; } Invoker<?> invoker = null; for (Exporter<?> exporter : DubboProtocol.getDubboProtocol().getExporters()) { if (service.equals(exporter.getInvoker().getInterface().getSimpleName()) || service.equals(exporter.getInvoker().getInterface().getName()) || service.equals(exporter.getInvoker().getUrl().getPath())) { invoker = exporter.getInvoker(); break; } } if (invoker != null) { if (StringUtils.isNotEmpty(method)) { boolean found = false; for (Method m : invoker.getInterface().getMethods()) { if (m.getName().equals(method)) { found = true; break; } } if (!found) { return "No such method " + method + " in class " + invoker.getInterface().getName(); } } TraceFilter.addTracer(invoker.getInterface(), method, channel, Integer.parseInt(times)); } else { return "No such service " + service; } return null; } }
8,275
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/ChangeTelnetHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.telnet.TelnetHandler; import org.apache.dubbo.remoting.telnet.support.Help; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; /** * ChangeServiceTelnetHandler */ @Activate @Help(parameter = "[service]", summary = "Change default service.", detail = "Change default service.") public class ChangeTelnetHandler implements TelnetHandler { public static final String SERVICE_KEY = "telnet.service"; @Override public String telnet(Channel channel, String message) { if (StringUtils.isEmpty(message)) { return "Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService"; } StringBuilder buf = new StringBuilder(); if ("/".equals(message) || "..".equals(message)) { String service = (String) channel.getAttribute(SERVICE_KEY); channel.removeAttribute(SERVICE_KEY); buf.append("Cancelled default service ").append(service).append('.'); } else { boolean found = false; for (Exporter<?> exporter : DubboProtocol.getDubboProtocol().getExporters()) { if (message.equals(exporter.getInvoker().getInterface().getSimpleName()) || message.equals(exporter.getInvoker().getInterface().getName()) || message.equals(exporter.getInvoker().getUrl().getPath())) { found = true; break; } } if (found) { channel.setAttribute(SERVICE_KEY, message); buf.append("Used the ") .append(message) .append(" as default.\r\nYou can cancel default service by command: cd /"); } else { buf.append("No such service ").append(message); } } return buf.toString(); } }
8,276
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/legacy/LogTelnetHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.legacy; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.remoting.Channel; import org.apache.dubbo.remoting.telnet.TelnetHandler; import org.apache.dubbo.remoting.telnet.support.Help; import java.io.File; import java.io.FileInputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.text.SimpleDateFormat; import java.util.Date; /** * LogTelnetHandler */ @Activate @Help(parameter = "level", summary = "Change log level or show log ", detail = "Change log level or show log") public class LogTelnetHandler implements TelnetHandler { public static final String SERVICE_KEY = "telnet.log"; @Override public String telnet(Channel channel, String message) { long size; File file = LoggerFactory.getFile(); StringBuilder buf = new StringBuilder(); if (message == null || message.trim().length() == 0) { buf.append("EXAMPLE: log error / log 100"); } else { String[] str = message.split(" "); if (!StringUtils.isNumber(str[0])) { LoggerFactory.setLevel(Level.valueOf(message.toUpperCase())); } else { int showLogLength = Integer.parseInt(str[0]); if (file != null && file.exists()) { try (FileInputStream fis = new FileInputStream(file)) { FileChannel filechannel = fis.getChannel(); size = filechannel.size(); ByteBuffer bb; if (size <= showLogLength) { bb = ByteBuffer.allocate((int) size); filechannel.read(bb, 0); } else { int pos = (int) (size - showLogLength); bb = ByteBuffer.allocate(showLogLength); filechannel.read(bb, pos); } bb.flip(); String content = new String(bb.array()) .replace("<", "&lt;") .replace(">", "&gt;") .replace("\n", "<br/><br/>"); buf.append("\r\ncontent:").append(content); buf.append("\r\nmodified:") .append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") .format(new Date(file.lastModified()))); buf.append("\r\nsize:").append(size).append("\r\n"); } catch (Exception e) { buf.append(e.getMessage()); } } else { buf.append("\r\nMESSAGE: log file not exists or log appender is console ."); } } } buf.append("\r\nCURRENT LOG LEVEL:") .append(LoggerFactory.getLevel()) .append("\r\nCURRENT LOG APPENDER:") .append(file == null ? "console" : file.getAbsolutePath()); return buf.toString(); } }
8,277
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/DubboLogo.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server; public class DubboLogo { public static final String DUBBO = " ___ __ __ ___ ___ ____ " + System.lineSeparator() + " / _ \\ / / / // _ ) / _ ) / __ \\ " + System.lineSeparator() + " / // // /_/ // _ |/ _ |/ /_/ / " + System.lineSeparator() + "/____/ \\____//____//____/ \\____/ " + System.lineSeparator(); }
8,278
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/QosBindException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server; /** * Indicate that if Qos Start failed */ public class QosBindException extends RuntimeException { public QosBindException(String message, Throwable cause) { super(message, cause); } }
8,279
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/Server.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.qos.server.handler.QosProcessHandler; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.concurrent.atomic.AtomicBoolean; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.util.concurrent.DefaultThreadFactory; /** * A server serves for both telnet access and http access * <ul> * <li>static initialize server</li> * <li>start server and bind port</li> * <li>close server</li> * </ul> */ public class Server { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(Server.class); private String host; private int port; private boolean acceptForeignIp = true; private String acceptForeignIpWhitelist = StringUtils.EMPTY_STRING; private String anonymousAccessPermissionLevel = PermissionLevel.NONE.name(); private String anonymousAllowCommands = StringUtils.EMPTY_STRING; private EventLoopGroup boss; private EventLoopGroup worker; private FrameworkModel frameworkModel; public Server(FrameworkModel frameworkModel) { this.welcome = DubboLogo.DUBBO; this.frameworkModel = frameworkModel; } private String welcome; private AtomicBoolean started = new AtomicBoolean(); /** * welcome message */ public void setWelcome(String welcome) { this.welcome = welcome; } public int getPort() { return port; } /** * start server, bind port */ public void start() throws Throwable { if (!started.compareAndSet(false, true)) { return; } boss = new NioEventLoopGroup(1, new DefaultThreadFactory("qos-boss", true)); worker = new NioEventLoopGroup(0, new DefaultThreadFactory("qos-worker", true)); ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(boss, worker); serverBootstrap.channel(NioServerSocketChannel.class); serverBootstrap.option(ChannelOption.SO_REUSEADDR, true); serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true); serverBootstrap.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline() .addLast(new QosProcessHandler( frameworkModel, QosConfiguration.builder() .welcome(welcome) .acceptForeignIp(acceptForeignIp) .acceptForeignIpWhitelist(acceptForeignIpWhitelist) .anonymousAccessPermissionLevel(anonymousAccessPermissionLevel) .anonymousAllowCommands(anonymousAllowCommands) .build())); } }); try { if (StringUtils.isBlank(host)) { serverBootstrap.bind(port).sync(); } else { serverBootstrap.bind(host, port).sync(); } logger.info("qos-server bind localhost:" + port); } catch (Throwable throwable) { throw new QosBindException("qos-server can not bind localhost:" + port, throwable); } } /** * close server */ public void stop() { logger.info("qos-server stopped."); if (boss != null) { boss.shutdownGracefully(); } if (worker != null) { worker.shutdownGracefully(); } started.set(false); } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public void setPort(int port) { this.port = port; } public boolean isAcceptForeignIp() { return acceptForeignIp; } public void setAcceptForeignIp(boolean acceptForeignIp) { this.acceptForeignIp = acceptForeignIp; } public void setAcceptForeignIpWhitelist(String acceptForeignIpWhitelist) { this.acceptForeignIpWhitelist = acceptForeignIpWhitelist; } public void setAnonymousAccessPermissionLevel(String anonymousAccessPermissionLevel) { this.anonymousAccessPermissionLevel = anonymousAccessPermissionLevel; } public void setAnonymousAllowCommands(String anonymousAllowCommands) { this.anonymousAllowCommands = anonymousAllowCommands; } public String getWelcome() { return welcome; } public boolean isStarted() { return started.get(); } }
8,280
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/ForeignHostPermitHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server.handler; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.qos.common.QosConstants; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.function.Predicate; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerAdapter; import io.netty.channel.ChannelHandlerContext; public class ForeignHostPermitHandler extends ChannelHandlerAdapter { // true means to accept foreign IP private final boolean acceptForeignIp; // the whitelist of foreign IP when acceptForeignIp = false, the delimiter is colon(,) // support specific ip and an ip range from CIDR specification private final String acceptForeignIpWhitelist; private final Predicate<String> whitelistPredicate; private final QosConfiguration qosConfiguration; public ForeignHostPermitHandler(QosConfiguration qosConfiguration) { this.qosConfiguration = qosConfiguration; this.acceptForeignIp = qosConfiguration.isAcceptForeignIp(); this.acceptForeignIpWhitelist = qosConfiguration.getAcceptForeignIpWhitelist(); this.whitelistPredicate = qosConfiguration.getAcceptForeignIpWhitelistPredicate(); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { if (acceptForeignIp) { return; } // the anonymous access is enabled by default, permission level is PUBLIC // if allow anonymous access, return if (qosConfiguration.isAllowAnonymousAccess()) { return; } final InetAddress inetAddress = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress(); // loopback address, return if (inetAddress.isLoopbackAddress()) { return; } // the ip is in the whitelist, return if (checkForeignIpInWhiteList(inetAddress)) { return; } ByteBuf cb = Unpooled.wrappedBuffer((QosConstants.BR_STR + "Foreign Ip Not Permitted, Consider Config It In Whitelist." + QosConstants.BR_STR) .getBytes()); ctx.writeAndFlush(cb).addListener(ChannelFutureListener.CLOSE); } private boolean checkForeignIpInWhiteList(InetAddress inetAddress) { if (StringUtils.isEmpty(acceptForeignIpWhitelist)) { return false; } final String foreignIp = inetAddress.getHostAddress(); return whitelistPredicate.test(foreignIp); } }
8,281
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetProcessHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server.handler; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.qos.command.CommandExecutor; import org.apache.dubbo.qos.command.DefaultCommandExecutor; import org.apache.dubbo.qos.command.decoder.TelnetCommandDecoder; import org.apache.dubbo.qos.command.exception.NoSuchCommandException; import org.apache.dubbo.qos.command.exception.PermissionDenyException; import org.apache.dubbo.qos.common.QosConstants; import org.apache.dubbo.rpc.model.FrameworkModel; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_COMMAND_NOT_FOUND; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PERMISSION_DENY_EXCEPTION; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_UNEXPECTED_EXCEPTION; /** * Telnet process handler */ public class TelnetProcessHandler extends SimpleChannelInboundHandler<String> { private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(TelnetProcessHandler.class); private final CommandExecutor commandExecutor; private final QosConfiguration qosConfiguration; public TelnetProcessHandler(FrameworkModel frameworkModel, QosConfiguration qosConfiguration) { this.commandExecutor = new DefaultCommandExecutor(frameworkModel); this.qosConfiguration = qosConfiguration; } @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { if (StringUtils.isBlank(msg)) { ctx.writeAndFlush(QosProcessHandler.PROMPT); } else { CommandContext commandContext = TelnetCommandDecoder.decode(msg); commandContext.setQosConfiguration(qosConfiguration); commandContext.setRemote(ctx.channel()); try { String result = commandExecutor.execute(commandContext); if (StringUtils.isEquals(QosConstants.CLOSE, result)) { ctx.writeAndFlush(getByeLabel()).addListener(ChannelFutureListener.CLOSE); } else { ctx.writeAndFlush(result + QosConstants.BR_STR + QosProcessHandler.PROMPT); } } catch (NoSuchCommandException ex) { ctx.writeAndFlush(msg + " :no such command"); ctx.writeAndFlush(QosConstants.BR_STR + QosProcessHandler.PROMPT); log.error(QOS_COMMAND_NOT_FOUND, "", "", "can not found command " + commandContext, ex); } catch (PermissionDenyException ex) { ctx.writeAndFlush(msg + " :permission deny"); ctx.writeAndFlush(QosConstants.BR_STR + QosProcessHandler.PROMPT); log.error( QOS_PERMISSION_DENY_EXCEPTION, "", "", "permission deny to access command " + commandContext, ex); } catch (Exception ex) { ctx.writeAndFlush(msg + " :fail to execute commandContext by " + ex.getMessage()); ctx.writeAndFlush(QosConstants.BR_STR + QosProcessHandler.PROMPT); log.error( QOS_UNEXPECTED_EXCEPTION, "", "", "execute commandContext got exception " + commandContext, ex); } } } private String getByeLabel() { return "BYE!\n"; } }
8,282
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/HttpProcessHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server.handler; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.qos.command.CommandExecutor; import org.apache.dubbo.qos.command.DefaultCommandExecutor; import org.apache.dubbo.qos.command.decoder.HttpCommandDecoder; import org.apache.dubbo.qos.command.exception.NoSuchCommandException; import org.apache.dubbo.qos.command.exception.PermissionDenyException; import org.apache.dubbo.rpc.model.FrameworkModel; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_COMMAND_NOT_FOUND; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PERMISSION_DENY_EXCEPTION; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_UNEXPECTED_EXCEPTION; /** * Parse HttpRequest for uri and parameters * <p> * <ul> * <li>if command not found, return 404</li> * <li>if execution fails, return 500</li> * <li>if succeed, return 200</li> * </ul> * <p> * will disconnect after execution finishes */ public class HttpProcessHandler extends SimpleChannelInboundHandler<HttpRequest> { private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(HttpProcessHandler.class); private final CommandExecutor commandExecutor; private final QosConfiguration qosConfiguration; public HttpProcessHandler(FrameworkModel frameworkModel, QosConfiguration qosConfiguration) { this.commandExecutor = new DefaultCommandExecutor(frameworkModel); this.qosConfiguration = qosConfiguration; } private static FullHttpResponse http(int httpCode, String result) { FullHttpResponse response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(httpCode), Unpooled.wrappedBuffer(result.getBytes())); HttpHeaders httpHeaders = response.headers(); httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, "text/plain"); httpHeaders.set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); return response; } private static FullHttpResponse http(int httpCode) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(httpCode)); HttpHeaders httpHeaders = response.headers(); httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, "text/plain"); httpHeaders.set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); return response; } @Override protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception { CommandContext commandContext = HttpCommandDecoder.decode(msg); // return 404 when fail to construct command context if (commandContext == null) { log.warn(QOS_UNEXPECTED_EXCEPTION, "", "", "can not found commandContext, url: " + msg.uri()); FullHttpResponse response = http(404); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { commandContext.setRemote(ctx.channel()); commandContext.setQosConfiguration(qosConfiguration); try { String result = commandExecutor.execute(commandContext); int httpCode = commandContext.getHttpCode(); FullHttpResponse response = http(httpCode, result); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (NoSuchCommandException ex) { log.error(QOS_COMMAND_NOT_FOUND, "", "", "can not find command: " + commandContext, ex); FullHttpResponse response = http(404); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (PermissionDenyException ex) { log.error( QOS_PERMISSION_DENY_EXCEPTION, "", "", "permission deny to access command: " + commandContext, ex); FullHttpResponse response = http(403); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (Exception qosEx) { log.error( QOS_UNEXPECTED_EXCEPTION, "", "", "execute commandContext: " + commandContext + " got exception", qosEx); FullHttpResponse response = http(500, qosEx.getMessage()); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } } } }
8,283
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/QosProcessHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server.handler; import org.apache.dubbo.common.utils.ExecutorUtil; import org.apache.dubbo.qos.api.QosConfiguration; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.List; import java.util.concurrent.TimeUnit; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.handler.timeout.IdleStateEvent; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.CharsetUtil; import io.netty.util.concurrent.ScheduledFuture; public class QosProcessHandler extends ByteToMessageDecoder { private ScheduledFuture<?> welcomeFuture; private final FrameworkModel frameworkModel; public static final String PROMPT = "dubbo>"; private final QosConfiguration qosConfiguration; public QosProcessHandler(FrameworkModel frameworkModel, QosConfiguration qosConfiguration) { this.frameworkModel = frameworkModel; this.qosConfiguration = qosConfiguration; } @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { welcomeFuture = ctx.executor() .schedule( () -> { final String welcome = qosConfiguration.getWelcome(); if (welcome != null) { ctx.write(Unpooled.wrappedBuffer(welcome.getBytes())); ctx.writeAndFlush(Unpooled.wrappedBuffer(PROMPT.getBytes())); } }, 500, TimeUnit.MILLISECONDS); } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() < 1) { return; } // read one byte to guess protocol final int magic = in.getByte(in.readerIndex()); ChannelPipeline p = ctx.pipeline(); p.addLast(new ForeignHostPermitHandler(qosConfiguration)); if (isHttp(magic)) { // no welcome output for http protocol if (welcomeFuture != null && welcomeFuture.isCancellable()) { welcomeFuture.cancel(false); } p.addLast(new HttpServerCodec()); p.addLast(new HttpObjectAggregator(1048576)); p.addLast(new HttpProcessHandler(frameworkModel, qosConfiguration)); p.remove(this); } else { p.addLast(new LineBasedFrameDecoder(2048)); p.addLast(new StringDecoder(CharsetUtil.UTF_8)); p.addLast(new StringEncoder(CharsetUtil.UTF_8)); p.addLast(new IdleStateHandler(0, 0, 5 * 60)); p.addLast(new TelnetIdleEventHandler()); p.addLast(new TelnetProcessHandler(frameworkModel, qosConfiguration)); p.remove(this); } } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { ExecutorUtil.cancelScheduledFuture(welcomeFuture); ctx.close(); } } // G for GET, and P for POST private static boolean isHttp(int magic) { return magic == 'G' || magic == 'P'; } }
8,284
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/server/handler/TelnetIdleEventHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.server.handler; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.timeout.IdleStateEvent; public class TelnetIdleEventHandler extends ChannelDuplexHandler { private static final Logger log = LoggerFactory.getLogger(TelnetIdleEventHandler.class); @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { // server will close channel when server don't receive any request from client util timeout. if (evt instanceof IdleStateEvent) { Channel channel = ctx.channel(); log.info("IdleStateEvent triggered, close channel " + channel); channel.close(); } else { super.userEventTriggered(ctx, evt); } } }
8,285
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/protocol/QosProtocolWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.protocol; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.qos.common.QosConstants; import org.apache.dubbo.qos.server.Server; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProtocolServer; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeModelAware; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_FAILED_START_SERVER; import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP; import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP_WHITELIST; import static org.apache.dubbo.common.constants.QosConstants.ANONYMOUS_ACCESS_ALLOW_COMMANDS; import static org.apache.dubbo.common.constants.QosConstants.ANONYMOUS_ACCESS_PERMISSION_LEVEL; import static org.apache.dubbo.common.constants.QosConstants.QOS_CHECK; import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE; import static org.apache.dubbo.common.constants.QosConstants.QOS_HOST; import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT; @Activate(order = 200) public class QosProtocolWrapper implements Protocol, ScopeModelAware { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(QosProtocolWrapper.class); private final AtomicBoolean hasStarted = new AtomicBoolean(false); private final Protocol protocol; private FrameworkModel frameworkModel; public QosProtocolWrapper(Protocol protocol) { if (protocol == null) { throw new IllegalArgumentException("protocol == null"); } this.protocol = protocol; } @Override public void setFrameworkModel(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; } @Override public int getDefaultPort() { return protocol.getDefaultPort(); } @Override public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException { startQosServer(invoker.getUrl(), true); return protocol.export(invoker); } @Override public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { startQosServer(url, false); return protocol.refer(type, url); } @Override public void destroy() { protocol.destroy(); stopServer(); } @Override public List<ProtocolServer> getServers() { return protocol.getServers(); } private void startQosServer(URL url, boolean isServer) throws RpcException { boolean qosCheck = url.getParameter(QOS_CHECK, false); try { if (!hasStarted.compareAndSet(false, true)) { return; } boolean qosEnable = url.getParameter(QOS_ENABLE, true); if (!qosEnable) { logger.info("qos won't be started because it is disabled. " + "Please check dubbo.application.qos.enable is configured either in system property, " + "dubbo.properties or XML/spring-boot configuration."); return; } String host = url.getParameter(QOS_HOST); int port = url.getParameter(QOS_PORT, QosConstants.DEFAULT_PORT); boolean acceptForeignIp = Boolean.parseBoolean(url.getParameter(ACCEPT_FOREIGN_IP, "false")); String acceptForeignIpWhitelist = url.getParameter(ACCEPT_FOREIGN_IP_WHITELIST, StringUtils.EMPTY_STRING); String anonymousAccessPermissionLevel = url.getParameter(ANONYMOUS_ACCESS_PERMISSION_LEVEL, PermissionLevel.PUBLIC.name()); String anonymousAllowCommands = url.getParameter(ANONYMOUS_ACCESS_ALLOW_COMMANDS, StringUtils.EMPTY_STRING); Server server = frameworkModel.getBeanFactory().getBean(Server.class); if (server.isStarted()) { return; } server.setHost(host); server.setPort(port); server.setAcceptForeignIp(acceptForeignIp); server.setAcceptForeignIpWhitelist(acceptForeignIpWhitelist); server.setAnonymousAccessPermissionLevel(anonymousAccessPermissionLevel); server.setAnonymousAllowCommands(anonymousAllowCommands); server.start(); } catch (Throwable throwable) { logger.warn(QOS_FAILED_START_SERVER, "", "", "Fail to start qos server: ", throwable); if (qosCheck) { try { // Stop QoS Server to support re-start if Qos-Check is enabled stopServer(); } catch (Throwable stop) { logger.warn(QOS_FAILED_START_SERVER, "", "", "Fail to stop qos server: ", stop); } if (isServer) { // Only throws exception when export services throw new RpcException(throwable); } } } } /*package*/ void stopServer() { if (hasStarted.compareAndSet(true, false)) { Server server = frameworkModel.getBeanFactory().getBean(Server.class); if (server.isStarted()) { server.stop(); } } } }
8,286
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/common/QosConstants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.common; public interface QosConstants { int DEFAULT_PORT = 22222; String BR_STR = "\r\n"; String CLOSE = "close!"; String QOS_PERMISSION_CHECKER = "qosPermissionChecker"; }
8,287
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/DefaultCommandExecutor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.qos.command.exception.NoSuchCommandException; import org.apache.dubbo.qos.command.exception.PermissionDenyException; import org.apache.dubbo.qos.common.QosConstants; import org.apache.dubbo.qos.permission.DefaultAnonymousAccessPermissionChecker; import org.apache.dubbo.qos.permission.PermissionChecker; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.Arrays; import java.util.Objects; import java.util.Optional; import io.netty.channel.Channel; public class DefaultCommandExecutor implements CommandExecutor { private static final Logger logger = LoggerFactory.getLogger(DefaultCommandExecutor.class); private final FrameworkModel frameworkModel; public DefaultCommandExecutor(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; } @Override public String execute(CommandContext commandContext) throws NoSuchCommandException, PermissionDenyException { String remoteAddress = Optional.ofNullable(commandContext.getRemote()) .map(Channel::remoteAddress) .map(Objects::toString) .orElse("unknown"); logger.info("[Dubbo QoS] Command Process start. Command: " + commandContext.getCommandName() + ", Args: " + Arrays.toString(commandContext.getArgs()) + ", Remote Address: " + remoteAddress); BaseCommand command = null; try { command = frameworkModel.getExtensionLoader(BaseCommand.class).getExtension(commandContext.getCommandName()); } catch (Throwable throwable) { // can't find command } if (command == null) { logger.info("[Dubbo QoS] Command Not found. Command: " + commandContext.getCommandName() + ", Remote Address: " + remoteAddress); throw new NoSuchCommandException(commandContext.getCommandName()); } // check permission when configs allow anonymous access if (commandContext.isAllowAnonymousAccess()) { PermissionChecker permissionChecker = DefaultAnonymousAccessPermissionChecker.INSTANCE; try { permissionChecker = frameworkModel .getExtensionLoader(PermissionChecker.class) .getExtension(QosConstants.QOS_PERMISSION_CHECKER); } catch (Throwable throwable) { // can't find valid custom permissionChecker } final Cmd cmd = command.getClass().getAnnotation(Cmd.class); final PermissionLevel cmdRequiredPermissionLevel = cmd.requiredPermissionLevel(); if (!permissionChecker.access(commandContext, cmdRequiredPermissionLevel)) { logger.info( "[Dubbo QoS] Command Deny to access. Command: " + commandContext.getCommandName() + ", Args: " + Arrays.toString(commandContext.getArgs()) + ", Required Permission Level: " + cmdRequiredPermissionLevel + ", Remote Address: " + remoteAddress); throw new PermissionDenyException(commandContext.getCommandName()); } } try { String result = command.execute(commandContext, commandContext.getArgs()); if (command.logResult()) { logger.info("[Dubbo QoS] Command Process success. Command: " + commandContext.getCommandName() + ", Args: " + Arrays.toString(commandContext.getArgs()) + ", Result: " + result + ", Remote Address: " + remoteAddress); } return result; } catch (Throwable t) { logger.info( "[Dubbo QoS] Command Process Failed. Command: " + commandContext.getCommandName() + ", Args: " + Arrays.toString(commandContext.getArgs()) + ", Remote Address: " + remoteAddress, t); throw t; } } }
8,288
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/CommandContextFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command; import org.apache.dubbo.qos.api.CommandContext; public class CommandContextFactory { public static CommandContext newInstance(String commandName) { return new CommandContext(commandName); } public static CommandContext newInstance(String commandName, String[] args, boolean isHttp) { return new CommandContext(commandName, args, isHttp); } }
8,289
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/CommandExecutor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.command.exception.NoSuchCommandException; import org.apache.dubbo.qos.command.exception.PermissionDenyException; public interface CommandExecutor { /** * Execute one command and return the execution result * * @param commandContext command context * @return command execution result * @throws NoSuchCommandException */ String execute(CommandContext commandContext) throws NoSuchCommandException, PermissionDenyException; }
8,290
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.ReferenceConfigBase; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfigBase; import org.apache.dubbo.config.SslConfig; import org.apache.dubbo.config.TracingConfig; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.context.ModuleConfigManager; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; @Cmd( name = "getConfig", summary = "Get current running config.", example = {"getConfig ReferenceConfig com.example.DemoService", "getConfig ApplicationConfig"}, requiredPermissionLevel = PermissionLevel.PRIVATE) public class GetConfig implements BaseCommand { private final FrameworkModel frameworkModel; public GetConfig(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; } @Override public String execute(CommandContext commandContext, String[] args) { boolean http = commandContext.isHttp(); StringBuilder plainOutput = new StringBuilder(); Map<String, Object> frameworkMap = new HashMap<>(); appendFrameworkConfig(args, plainOutput, frameworkMap); if (http) { return JsonUtils.toJson(frameworkMap); } else { return plainOutput.toString(); } } private void appendFrameworkConfig(String[] args, StringBuilder plainOutput, Map<String, Object> frameworkMap) { for (ApplicationModel applicationModel : frameworkModel.getApplicationModels()) { Map<String, Object> applicationMap = new HashMap<>(); frameworkMap.put(applicationModel.getDesc(), applicationMap); plainOutput .append("ApplicationModel: ") .append(applicationModel.getDesc()) .append("\n"); ConfigManager configManager = applicationModel.getApplicationConfigManager(); appendApplicationConfigs(args, plainOutput, applicationModel, applicationMap, configManager); } } private static void appendApplicationConfigs( String[] args, StringBuilder plainOutput, ApplicationModel applicationModel, Map<String, Object> applicationMap, ConfigManager configManager) { Optional<ApplicationConfig> applicationConfig = configManager.getApplication(); applicationConfig.ifPresent(config -> appendConfig("ApplicationConfig", config.getName(), config, plainOutput, applicationMap, args)); for (ProtocolConfig protocol : configManager.getProtocols()) { appendConfigs("ProtocolConfig", protocol.getName(), protocol, plainOutput, applicationMap, args); } for (RegistryConfig registry : configManager.getRegistries()) { appendConfigs("RegistryConfig", registry.getId(), registry, plainOutput, applicationMap, args); } for (MetadataReportConfig metadataConfig : configManager.getMetadataConfigs()) { appendConfigs( "MetadataReportConfig", metadataConfig.getId(), metadataConfig, plainOutput, applicationMap, args); } for (ConfigCenterConfig configCenter : configManager.getConfigCenters()) { appendConfigs("ConfigCenterConfig", configCenter.getId(), configCenter, plainOutput, applicationMap, args); } Optional<MetricsConfig> metricsConfig = configManager.getMetrics(); metricsConfig.ifPresent( config -> appendConfig("MetricsConfig", config.getId(), config, plainOutput, applicationMap, args)); Optional<TracingConfig> tracingConfig = configManager.getTracing(); tracingConfig.ifPresent( config -> appendConfig("TracingConfig", config.getId(), config, plainOutput, applicationMap, args)); Optional<MonitorConfig> monitorConfig = configManager.getMonitor(); monitorConfig.ifPresent( config -> appendConfig("MonitorConfig", config.getId(), config, plainOutput, applicationMap, args)); Optional<SslConfig> sslConfig = configManager.getSsl(); sslConfig.ifPresent( config -> appendConfig("SslConfig", config.getId(), config, plainOutput, applicationMap, args)); for (ModuleModel moduleModel : applicationModel.getModuleModels()) { Map<String, Object> moduleMap = new HashMap<>(); applicationMap.put(moduleModel.getDesc(), moduleMap); plainOutput.append("ModuleModel: ").append(moduleModel.getDesc()).append("\n"); ModuleConfigManager moduleConfigManager = moduleModel.getConfigManager(); appendModuleConfigs(args, plainOutput, moduleMap, moduleConfigManager); } } private static void appendModuleConfigs( String[] args, StringBuilder plainOutput, Map<String, Object> moduleMap, ModuleConfigManager moduleConfigManager) { for (ProviderConfig provider : moduleConfigManager.getProviders()) { appendConfigs("ProviderConfig", provider.getId(), provider, plainOutput, moduleMap, args); } for (ConsumerConfig consumer : moduleConfigManager.getConsumers()) { appendConfigs("ConsumerConfig", consumer.getId(), consumer, plainOutput, moduleMap, args); } Optional<ModuleConfig> moduleConfig = moduleConfigManager.getModule(); moduleConfig.ifPresent( config -> appendConfig("ModuleConfig", config.getId(), config, plainOutput, moduleMap, args)); for (ServiceConfigBase<?> service : moduleConfigManager.getServices()) { appendConfigs("ServiceConfig", service.getUniqueServiceName(), service, plainOutput, moduleMap, args); } for (ReferenceConfigBase<?> reference : moduleConfigManager.getReferences()) { appendConfigs("ReferenceConfig", reference.getUniqueServiceName(), reference, plainOutput, moduleMap, args); } } @SuppressWarnings("unchecked") private static void appendConfigs( String type, String id, Object config, StringBuilder plainOutput, Map<String, Object> map, String[] args) { if (!isMatch(type, id, args)) { return; } plainOutput .append(type) .append(": ") .append(id) .append("\n") .append(config) .append("\n\n"); Map<String, Object> typeMap = (Map<String, Object>) map.computeIfAbsent(type, k -> new HashMap<String, Object>()); typeMap.put(id, config); } private static void appendConfig( String type, String id, Object config, StringBuilder plainOutput, Map<String, Object> map, String[] args) { if (!isMatch(type, id, args)) { return; } plainOutput .append(type) .append(": ") .append(id) .append("\n") .append(config) .append("\n\n"); map.put(type, config); } private static boolean isMatch(String type, String id, String[] args) { if (args == null) { return true; } switch (args.length) { case 1: if (!Objects.equals(args[0], type)) { return false; } break; case 2: if (!Objects.equals(args[0], type) || !Objects.equals(args[1], id)) { return false; } break; default: } return true; } }
8,291
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/BaseOffline.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.NamedThreadFactory; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.FrameworkServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceMetadata; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class BaseOffline implements BaseCommand { private static final Logger logger = LoggerFactory.getLogger(BaseOffline.class); public FrameworkServiceRepository serviceRepository; public BaseOffline(FrameworkModel frameworkModel) { this.serviceRepository = frameworkModel.getServiceRepository(); } @Override public String execute(CommandContext commandContext, String[] args) { logger.info("receive offline command"); String servicePattern = ".*"; if (ArrayUtils.isNotEmpty(args)) { servicePattern = args[0]; } boolean hasService = doExecute(servicePattern); if (hasService) { return "OK"; } else { return "service not found"; } } protected boolean doExecute(String servicePattern) { return this.offline(servicePattern); } public boolean offline(String servicePattern) { boolean hasService = false; ExecutorService executorService = Executors.newFixedThreadPool( Math.min(Runtime.getRuntime().availableProcessors(), 4), new NamedThreadFactory("Dubbo-Offline")); try { List<CompletableFuture<Void>> futures = new LinkedList<>(); Collection<ProviderModel> providerModelList = serviceRepository.allProviderModels(); for (ProviderModel providerModel : providerModelList) { ServiceMetadata metadata = providerModel.getServiceMetadata(); if (metadata.getServiceKey().matches(servicePattern) || metadata.getDisplayServiceKey().matches(servicePattern)) { hasService = true; List<ProviderModel.RegisterStatedURL> statedUrls = providerModel.getStatedUrl(); for (ProviderModel.RegisterStatedURL statedURL : statedUrls) { if (statedURL.isRegistered()) { futures.add(CompletableFuture.runAsync( () -> { doUnexport(statedURL); }, executorService)); } } } } for (CompletableFuture<Void> future : futures) { future.get(); } } catch (ExecutionException | InterruptedException e) { throw new RuntimeException(e); } finally { executorService.shutdown(); } return hasService; } protected void doUnexport(ProviderModel.RegisterStatedURL statedURL) { RegistryFactory registryFactory = statedURL .getRegistryUrl() .getOrDefaultApplicationModel() .getExtensionLoader(RegistryFactory.class) .getAdaptiveExtension(); Registry registry = registryFactory.getRegistry(statedURL.getRegistryUrl()); registry.unregister(statedURL.getProviderUrl()); statedURL.setRegistered(false); } }
8,292
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/LoggerInfo.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.logger.Level; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.qos.api.CommandContext; @Cmd( name = "loggerInfo", summary = "Print logger info", example = {"loggerInfo"}) public class LoggerInfo implements BaseCommand { @Override public String execute(CommandContext commandContext, String[] args) { String availableAdapters = String.join(", ", LoggerFactory.getAvailableAdapter().toArray(new String[0])); String currentAdapter = LoggerFactory.getCurrentAdapter(); Level level = LoggerFactory.getLevel(); return "Available logger adapters: [" + availableAdapters + "]. Current Adapter: [" + currentAdapter + "]. Log level: " + level.name(); } }
8,293
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetRecentRouterSnapshot.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.Arrays; import java.util.Objects; import java.util.stream.Collectors; @Cmd(name = "getRecentRouterSnapshot", summary = "Get recent (32) router snapshot message") public class GetRecentRouterSnapshot implements BaseCommand { private final RouterSnapshotSwitcher routerSnapshotSwitcher; public GetRecentRouterSnapshot(FrameworkModel frameworkModel) { this.routerSnapshotSwitcher = frameworkModel.getBeanFactory().getBean(RouterSnapshotSwitcher.class); } @Override public String execute(CommandContext commandContext, String[] args) { return Arrays.stream(routerSnapshotSwitcher.cloneSnapshot()) .filter(Objects::nonNull) .sorted() .collect(Collectors.joining("\n\n")); } }
8,294
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Offline.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ProviderModel; @Cmd( name = "offline", summary = "offline dubbo", example = {"offline dubbo", "offline xx.xx.xxx.service"}) public class Offline extends BaseOffline { public Offline(FrameworkModel frameworkModel) { super(frameworkModel); } @Override protected void doUnexport(ProviderModel.RegisterStatedURL statedURL) { super.doUnexport(statedURL); } }
8,295
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/BaseOnline.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.FrameworkServiceRepository; import org.apache.dubbo.rpc.model.ProviderModel; import org.apache.dubbo.rpc.model.ServiceMetadata; import java.util.Collection; import java.util.List; public class BaseOnline implements BaseCommand { private static final Logger logger = LoggerFactory.getLogger(BaseOnline.class); public FrameworkServiceRepository serviceRepository; public BaseOnline(FrameworkModel frameworkModel) { this.serviceRepository = frameworkModel.getServiceRepository(); } @Override public String execute(CommandContext commandContext, String[] args) { logger.info("receive online command"); String servicePattern = ".*"; if (ArrayUtils.isNotEmpty(args)) { servicePattern = "" + args[0]; } boolean hasService = doExecute(servicePattern); if (hasService) { return "OK"; } else { return "service not found"; } } public boolean online(String servicePattern) { boolean hasService = false; Collection<ProviderModel> providerModelList = serviceRepository.allProviderModels(); for (ProviderModel providerModel : providerModelList) { ServiceMetadata metadata = providerModel.getServiceMetadata(); if (metadata.getServiceKey().matches(servicePattern) || metadata.getDisplayServiceKey().matches(servicePattern)) { hasService = true; List<ProviderModel.RegisterStatedURL> statedUrls = providerModel.getStatedUrl(); for (ProviderModel.RegisterStatedURL statedURL : statedUrls) { if (!statedURL.isRegistered()) { doExport(statedURL); } } } } return hasService; } protected boolean doExecute(String servicePattern) { return this.online(servicePattern); } protected void doExport(ProviderModel.RegisterStatedURL statedURL) { RegistryFactory registryFactory = statedURL .getRegistryUrl() .getOrDefaultApplicationModel() .getExtensionLoader(RegistryFactory.class) .getAdaptiveExtension(); Registry registry = registryFactory.getRegistry(statedURL.getRegistryUrl()); registry.register(statedURL.getProviderUrl()); statedURL.setRegistered(true); } }
8,296
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableSimpleProfiler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.profiler.ProfilerSwitch; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.qos.api.CommandContext; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_ENABLED; @Cmd(name = "enableSimpleProfiler", summary = "Enable Dubbo Invocation Profiler.") public class EnableSimpleProfiler implements BaseCommand { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(EnableSimpleProfiler.class); @Override public String execute(CommandContext commandContext, String[] args) { ProfilerSwitch.enableSimpleProfiler(); logger.warn(QOS_PROFILER_ENABLED, "", "", "Dubbo Invocation Profiler has been enabled."); return "OK"; } }
8,297
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ready.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.qos.api.CommandContext; import org.apache.dubbo.qos.api.PermissionLevel; import org.apache.dubbo.qos.probe.ReadinessProbe; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; @Cmd(name = "ready", summary = "Judge if service is ready to work? ", requiredPermissionLevel = PermissionLevel.PUBLIC) public class Ready implements BaseCommand { private final FrameworkModel frameworkModel; public Ready(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; } @Override public String execute(CommandContext commandContext, String[] args) { String config = frameworkModel.getApplicationModels().stream() .map(applicationModel -> applicationModel.getApplicationConfigManager().getApplication()) .map(o -> o.orElse(null)) .filter(Objects::nonNull) .map(ApplicationConfig::getReadinessProbe) .filter(Objects::nonNull) .collect(Collectors.joining(",")); URL url = URL.valueOf("application://").addParameter(CommonConstants.QOS_READY_PROBE_EXTENSION, config); List<ReadinessProbe> readinessProbes = frameworkModel .getExtensionLoader(ReadinessProbe.class) .getActivateExtension(url, CommonConstants.QOS_READY_PROBE_EXTENSION); if (!readinessProbes.isEmpty()) { for (ReadinessProbe readinessProbe : readinessProbes) { if (!readinessProbe.check()) { // 503 Service Unavailable commandContext.setHttpCode(503); return "false"; } } } // 200 OK commandContext.setHttpCode(200); return "true"; } }
8,298
0
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableSimpleProfiler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.qos.command.impl; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.profiler.ProfilerSwitch; import org.apache.dubbo.qos.api.BaseCommand; import org.apache.dubbo.qos.api.Cmd; import org.apache.dubbo.qos.api.CommandContext; import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_DISABLED; @Cmd(name = "disableSimpleProfiler", summary = "Disable Dubbo Invocation Profiler.") public class DisableSimpleProfiler implements BaseCommand { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DisableSimpleProfiler.class); @Override public String execute(CommandContext commandContext, String[] args) { ProfilerSwitch.disableSimpleProfiler(); logger.warn(QOS_PROFILER_DISABLED, "", "", "Dubbo Invocation Profiler has been disabled."); return "OK"; } }
8,299