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-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/wrapper/StubProxyFactoryWrapperTest.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.rpc.proxy.wrapper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.support.DemoService;
import org.apache.dubbo.rpc.support.DemoServiceStub;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.STUB_EVENT_KEY;
import static org.apache.dubbo.rpc.Constants.STUB_KEY;
/**
* {@link StubProxyFactoryWrapper }
*/
class StubProxyFactoryWrapperTest {
@Test
void test() {
ProxyFactory proxyFactory = Mockito.mock(ProxyFactory.class);
Protocol protocol = Mockito.mock(Protocol.class);
StubProxyFactoryWrapper stubProxyFactoryWrapper = new StubProxyFactoryWrapper(proxyFactory);
stubProxyFactoryWrapper.setProtocol(protocol);
URL url = URL.valueOf("test://127.0.0.1/test?stub=true");
url = url.addParameter(STUB_KEY, "true");
url = url.addParameter(STUB_EVENT_KEY, "true");
Invoker<DemoService> invoker = Mockito.mock(Invoker.class);
Mockito.when(invoker.getInterface()).thenReturn(DemoService.class);
Mockito.when(invoker.getUrl()).thenReturn(url);
DemoService proxy = stubProxyFactoryWrapper.getProxy(invoker, false);
Assertions.assertTrue(proxy instanceof DemoServiceStub);
Mockito.verify(protocol, Mockito.times(1)).export(Mockito.any());
}
}
| 5,900 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/proxy/jdk/JdkProxyFactoryTest.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.rpc.proxy.jdk;
import org.apache.dubbo.rpc.proxy.AbstractProxyTest;
class JdkProxyFactoryTest extends AbstractProxyTest {
static {
factory = new JdkProxyFactory();
}
}
| 5,901 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/ProtocolListenerWrapperTest.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.rpc.protocol;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.listener.ListenerInvokerWrapper;
import org.apache.dubbo.rpc.proxy.DemoService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INVOKER_LISTENER_KEY;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ProtocolListenerWrapperTest {
@Test
void testLoadingListenerForLocalReference() {
// verify that no listener is loaded by default
URL urlWithoutListener =
URL.valueOf("injvm://127.0.0.1/DemoService").addParameter(INTERFACE_KEY, DemoService.class.getName());
AbstractInvoker<DemoService> invokerWithoutListener =
new AbstractInvoker<DemoService>(DemoService.class, urlWithoutListener) {
@Override
protected Result doInvoke(Invocation invocation) throws Throwable {
return null;
}
};
Protocol protocolWithoutListener = mock(Protocol.class);
when(protocolWithoutListener.refer(DemoService.class, urlWithoutListener))
.thenReturn(invokerWithoutListener);
ProtocolListenerWrapper protocolListenerWrapperWithoutListener =
new ProtocolListenerWrapper(protocolWithoutListener);
Invoker<?> invoker = protocolListenerWrapperWithoutListener.refer(DemoService.class, urlWithoutListener);
Assertions.assertTrue(invoker instanceof ListenerInvokerWrapper);
Assertions.assertEquals(
0, ((ListenerInvokerWrapper<?>) invoker).getListeners().size());
// verify that if the invoker.listener is configured, then load the specified listener
URL urlWithListener = URL.valueOf("injvm://127.0.0.1/DemoService")
.addParameter(INTERFACE_KEY, DemoService.class.getName())
.addParameter(INVOKER_LISTENER_KEY, "count");
AbstractInvoker<DemoService> invokerWithListener =
new AbstractInvoker<DemoService>(DemoService.class, urlWithListener) {
@Override
protected Result doInvoke(Invocation invocation) throws Throwable {
return null;
}
};
Protocol protocol = mock(Protocol.class);
when(protocol.refer(DemoService.class, urlWithListener)).thenReturn(invokerWithListener);
ProtocolListenerWrapper protocolListenerWrapper = new ProtocolListenerWrapper(protocol);
invoker = protocolListenerWrapper.refer(DemoService.class, urlWithListener);
Assertions.assertTrue(invoker instanceof ListenerInvokerWrapper);
Assertions.assertEquals(1, CountInvokerListener.getCounter());
}
@Test
void testLoadingListenerForRemoteReference() {
// verify that no listener is loaded by default
URL urlWithoutListener = URL.valueOf("dubbo://127.0.0.1:20880/DemoService")
.addParameter(INTERFACE_KEY, DemoService.class.getName());
AbstractInvoker<DemoService> invokerWithoutListener =
new AbstractInvoker<DemoService>(DemoService.class, urlWithoutListener) {
@Override
protected Result doInvoke(Invocation invocation) throws Throwable {
return null;
}
};
Protocol protocolWithoutListener = mock(Protocol.class);
when(protocolWithoutListener.refer(DemoService.class, urlWithoutListener))
.thenReturn(invokerWithoutListener);
ProtocolListenerWrapper protocolListenerWrapperWithoutListener =
new ProtocolListenerWrapper(protocolWithoutListener);
Invoker<?> invoker = protocolListenerWrapperWithoutListener.refer(DemoService.class, urlWithoutListener);
Assertions.assertTrue(invoker instanceof ListenerInvokerWrapper);
Assertions.assertEquals(
0, ((ListenerInvokerWrapper<?>) invoker).getListeners().size());
// verify that if the invoker.listener is configured, then load the specified listener
URL urlWithListener = URL.valueOf("dubbo://127.0.0.1:20880/DemoService")
.addParameter(INTERFACE_KEY, DemoService.class.getName())
.addParameter(INVOKER_LISTENER_KEY, "count");
AbstractInvoker<DemoService> invokerWithListener =
new AbstractInvoker<DemoService>(DemoService.class, urlWithListener) {
@Override
protected Result doInvoke(Invocation invocation) throws Throwable {
return null;
}
};
Protocol protocol = mock(Protocol.class);
when(protocol.refer(DemoService.class, urlWithListener)).thenReturn(invokerWithListener);
ProtocolListenerWrapper protocolListenerWrapper = new ProtocolListenerWrapper(protocol);
invoker = protocolListenerWrapper.refer(DemoService.class, urlWithListener);
Assertions.assertTrue(invoker instanceof ListenerInvokerWrapper);
Assertions.assertEquals(1, CountInvokerListener.getCounter());
}
}
| 5,902 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/protocol/CountInvokerListener.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.rpc.protocol;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.InvokerListener;
import org.apache.dubbo.rpc.RpcException;
import java.util.concurrent.atomic.AtomicInteger;
public class CountInvokerListener implements InvokerListener {
private static final AtomicInteger counter = new AtomicInteger(0);
@Override
public void referred(Invoker<?> invoker) throws RpcException {
counter.set(0);
counter.incrementAndGet();
}
@Override
public void destroyed(Invoker<?> invoker) {}
public static int getCounter() {
return counter.get();
}
}
| 5,903 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/PenetrateAttachmentSelectorMock.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.rpc.support;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.PenetrateAttachmentSelector;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcContextAttachment;
import java.util.Map;
public class PenetrateAttachmentSelectorMock implements PenetrateAttachmentSelector {
@Override
public Map<String, Object> select(
Invocation invocation, RpcContextAttachment clientAttachment, RpcContextAttachment serverAttachment) {
Map<String, Object> objectAttachments = RpcContext.getServerAttachment().getObjectAttachments();
objectAttachments.put("testKey", "testVal");
return objectAttachments;
}
@Override
public Map<String, Object> selectReverse(
Invocation invocation,
RpcContextAttachment clientResponseContext,
RpcContextAttachment serverResponseContext) {
Map<String, Object> objectAttachments =
RpcContext.getServerResponseContext().getObjectAttachments();
objectAttachments.put("reverseKey", "reverseVal");
return objectAttachments;
}
}
| 5,904 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceB.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.rpc.support;
public interface DemoServiceB {
String methodB();
}
| 5,905 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/BlockMyInvoker.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.rpc.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
public class BlockMyInvoker<T> extends MyInvoker<T> {
private long blockTime = 100;
public BlockMyInvoker(URL url, long blockTime) {
super(url);
this.blockTime = blockTime;
}
public BlockMyInvoker(URL url, boolean hasException, long blockTime) {
super(url, hasException);
this.blockTime = blockTime;
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
AppResponse result = new AppResponse();
if (!hasException) {
try {
Thread.sleep(blockTime);
} catch (InterruptedException e) {
}
result.setValue("Dubbo");
} else {
result.setException(new RuntimeException("mocked exception"));
}
return AsyncRpcResult.newDefaultAsyncResult(result, invocation);
}
public long getBlockTime() {
return blockTime;
}
public void setBlockTime(long blockTime) {
this.blockTime = blockTime;
}
}
| 5,906 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceStub.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.rpc.support;
public class DemoServiceStub extends DemoServiceImpl {
private DemoService demoService;
public DemoServiceStub(DemoService demoService) {
this.demoService = demoService;
}
public DemoService getDemoService() {
return demoService;
}
}
| 5,907 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/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.rpc.support;
public enum Type {
High,
Normal,
Lower
}
| 5,908 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvocation.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.rpc.support;
import org.apache.dubbo.rpc.AttachmentsAdapter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.model.ServiceModel;
import java.util.HashMap;
import java.util.Map;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
/**
* MockInvocation.java
*/
public class MockInvocation extends RpcInvocation {
private Map<String, Object> attachments;
public MockInvocation() {
attachments = new HashMap<>();
attachments.put(PATH_KEY, "dubbo");
attachments.put(GROUP_KEY, "dubbo");
attachments.put(VERSION_KEY, "1.0.0");
attachments.put(DUBBO_VERSION_KEY, "1.0.0");
attachments.put(TOKEN_KEY, "sfag");
attachments.put(TIMEOUT_KEY, "1000");
}
@Override
public String getTargetServiceUniqueName() {
return null;
}
@Override
public String getProtocolServiceKey() {
return null;
}
public String getMethodName() {
return "echo";
}
@Override
public String getServiceName() {
return "DemoService";
}
public Class<?>[] getParameterTypes() {
return new Class[] {String.class};
}
public Object[] getArguments() {
return new Object[] {"aa"};
}
public Map<String, String> getAttachments() {
return new AttachmentsAdapter.ObjectToStringMap(attachments);
}
@Override
public Map<String, Object> getObjectAttachments() {
return attachments;
}
@Override
public void setAttachment(String key, String value) {
setObjectAttachment(key, value);
}
@Override
public void setAttachment(String key, Object value) {
setObjectAttachment(key, value);
}
@Override
public void setObjectAttachment(String key, Object value) {
attachments.put(key, value);
}
@Override
public void setAttachmentIfAbsent(String key, String value) {
setObjectAttachmentIfAbsent(key, value);
}
@Override
public void setAttachmentIfAbsent(String key, Object value) {
setObjectAttachmentIfAbsent(key, value);
}
@Override
public void setObjectAttachmentIfAbsent(String key, Object value) {
attachments.put(key, value);
}
public Invoker<?> getInvoker() {
return null;
}
@Override
public void setServiceModel(ServiceModel serviceModel) {}
@Override
public ServiceModel getServiceModel() {
return null;
}
@Override
public Object put(Object key, Object value) {
return null;
}
@Override
public Object get(Object key) {
return null;
}
@Override
public Map<Object, Object> getAttributes() {
return null;
}
public String getAttachment(String key) {
return (String) getObjectAttachments().get(key);
}
@Override
public Object getObjectAttachment(String key) {
return attachments.get(key);
}
public String getAttachment(String key, String defaultValue) {
return (String) getObjectAttachments().get(key);
}
@Override
public Object getObjectAttachment(String key, Object defaultValue) {
Object result = attachments.get(key);
if (result == null) {
return defaultValue;
}
return result;
}
}
| 5,909 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceBMock.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.rpc.support;
/**
* default mock service for DemoServiceA
*/
public class DemoServiceBMock implements DemoServiceB {
public static final String MOCK_VALUE = "mockB";
@Override
public String methodB() {
return MOCK_VALUE;
}
}
| 5,910 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MockInvokerTest.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.rpc.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.rpc.Constants.MOCK_KEY;
class MockInvokerTest {
@Test
void testParseMockValue() throws Exception {
Assertions.assertNull(MockInvoker.parseMockValue("null"));
Assertions.assertNull(MockInvoker.parseMockValue("empty"));
Assertions.assertTrue((Boolean) MockInvoker.parseMockValue("true"));
Assertions.assertFalse((Boolean) MockInvoker.parseMockValue("false"));
Assertions.assertEquals(123, MockInvoker.parseMockValue("123"));
Assertions.assertEquals("foo", MockInvoker.parseMockValue("foo"));
Assertions.assertEquals("foo", MockInvoker.parseMockValue("\"foo\""));
Assertions.assertEquals("foo", MockInvoker.parseMockValue("\'foo\'"));
Assertions.assertEquals(new HashMap<>(), MockInvoker.parseMockValue("{}"));
Assertions.assertEquals(new ArrayList<>(), MockInvoker.parseMockValue("[]"));
Assertions.assertEquals("foo", MockInvoker.parseMockValue("foo", new Type[] {String.class}));
}
@Test
void testInvoke() {
URL url = URL.valueOf("remote://1.2.3.4/" + String.class.getName());
url = url.addParameter(MOCK_KEY, "return ");
MockInvoker mockInvoker = new MockInvoker(url, String.class);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Assertions.assertEquals(new HashMap<>(), mockInvoker.invoke(invocation).getObjectAttachments());
}
@Test
void testGetDefaultObject() {
// test methodA in DemoServiceAMock
final Class<DemoServiceA> demoServiceAClass = DemoServiceA.class;
URL url = URL.valueOf("remote://1.2.3.4/" + demoServiceAClass.getName());
url = url.addParameter(MOCK_KEY, "force:true");
MockInvoker mockInvoker = new MockInvoker(url, demoServiceAClass);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("methodA");
Assertions.assertEquals(new HashMap<>(), mockInvoker.invoke(invocation).getObjectAttachments());
// test methodB in DemoServiceBMock
final Class<DemoServiceB> demoServiceBClass = DemoServiceB.class;
url = URL.valueOf("remote://1.2.3.4/" + demoServiceBClass.getName());
url = url.addParameter(MOCK_KEY, "force:true");
mockInvoker = new MockInvoker(url, demoServiceBClass);
invocation = new RpcInvocation();
invocation.setMethodName("methodB");
Assertions.assertEquals(new HashMap<>(), mockInvoker.invoke(invocation).getObjectAttachments());
}
@Test
void testInvokeThrowsRpcException1() {
URL url = URL.valueOf("remote://1.2.3.4/" + String.class.getName());
MockInvoker mockInvoker = new MockInvoker(url, null);
Assertions.assertThrows(RpcException.class, () -> mockInvoker.invoke(new RpcInvocation()));
}
@Test
void testInvokeThrowsRpcException2() {
URL url = URL.valueOf("remote://1.2.3.4/" + String.class.getName());
url = url.addParameter(MOCK_KEY, "fail");
MockInvoker mockInvoker = new MockInvoker(url, String.class);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Assertions.assertThrows(RpcException.class, () -> mockInvoker.invoke(invocation));
}
@Test
void testInvokeThrowsRpcException3() {
URL url = URL.valueOf("remote://1.2.3.4/" + String.class.getName());
url = url.addParameter(MOCK_KEY, "throw");
MockInvoker mockInvoker = new MockInvoker(url, String.class);
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName("getSomething");
Assertions.assertThrows(RpcException.class, () -> mockInvoker.invoke(invocation));
}
@Test
void testGetThrowable() {
Assertions.assertThrows(RpcException.class, () -> MockInvoker.getThrowable("Exception.class"));
}
@Test
void testGetMockObject() {
Assertions.assertEquals(
"",
MockInvoker.getMockObject(
ApplicationModel.defaultModel().getExtensionDirector(), "java.lang.String", String.class));
Assertions.assertThrows(
IllegalStateException.class,
() -> MockInvoker.getMockObject(
ApplicationModel.defaultModel().getExtensionDirector(), "true", String.class));
Assertions.assertThrows(
IllegalStateException.class,
() -> MockInvoker.getMockObject(
ApplicationModel.defaultModel().getExtensionDirector(), "default", String.class));
Assertions.assertThrows(
IllegalStateException.class,
() -> MockInvoker.getMockObject(
ApplicationModel.defaultModel().getExtensionDirector(), "java.lang.String", Integer.class));
Assertions.assertThrows(
IllegalStateException.class,
() -> MockInvoker.getMockObject(
ApplicationModel.defaultModel().getExtensionDirector(),
"java.io.Serializable",
Serializable.class));
}
@Test
void testNormalizeMock() {
Assertions.assertNull(MockInvoker.normalizeMock(null));
Assertions.assertEquals("", MockInvoker.normalizeMock(""));
Assertions.assertEquals("", MockInvoker.normalizeMock("fail:"));
Assertions.assertEquals("", MockInvoker.normalizeMock("force:"));
Assertions.assertEquals("throw", MockInvoker.normalizeMock("throw"));
Assertions.assertEquals("default", MockInvoker.normalizeMock("fail"));
Assertions.assertEquals("default", MockInvoker.normalizeMock("force"));
Assertions.assertEquals("default", MockInvoker.normalizeMock("true"));
Assertions.assertEquals("default", MockInvoker.normalizeMock("default"));
Assertions.assertEquals("return null", MockInvoker.normalizeMock("return"));
Assertions.assertEquals("return null", MockInvoker.normalizeMock("return null"));
}
}
| 5,911 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/LocalException.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.rpc.support;
public class LocalException extends RuntimeException {
public LocalException(String message) {
super(message);
}
}
| 5,912 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RpcUtilsTest.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.rpc.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.InvokeMode;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleServiceRepository;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE;
import static org.apache.dubbo.rpc.Constants.AUTO_ATTACH_INVOCATIONID_KEY;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
class RpcUtilsTest {
/**
* regular scenario: async invocation in URL
* verify: 1. whether invocationId is set correctly, 2. idempotent or not
*/
Invoker createMockInvoker(URL url) {
Invoker invoker = createMockInvoker();
given(invoker.getUrl()).willReturn(url);
return invoker;
}
Invoker createMockInvoker() {
return mock(Invoker.class);
}
@Test
void testAttachInvocationIdIfAsync_normal() {
URL url = URL.valueOf("dubbo://localhost/?test.async=true");
Map<String, Object> attachments = new HashMap<>();
attachments.put("aa", "bb");
Invocation inv = new RpcInvocation("test", "DemoService", "", new Class[] {}, new String[] {}, attachments);
RpcUtils.attachInvocationIdIfAsync(url, inv);
long id1 = RpcUtils.getInvocationId(inv);
RpcUtils.attachInvocationIdIfAsync(url, inv);
long id2 = RpcUtils.getInvocationId(inv);
assertEquals(id1, id2); // verify if it's idempotent
assertTrue(id1 >= 0);
assertEquals("bb", attachments.get("aa"));
}
/**
* scenario: sync invocation, no attachment added by default
* verify: no id attribute added in attachment
*/
@Test
void testAttachInvocationIdIfAsync_sync() {
URL url = URL.valueOf("dubbo://localhost/");
Invocation inv = new RpcInvocation("test", "DemoService", "", new Class[] {}, new String[] {});
RpcUtils.attachInvocationIdIfAsync(url, inv);
assertNull(RpcUtils.getInvocationId(inv));
}
/**
* scenario: async invocation, add attachment by default
* verify: no error report when the original attachment is null
*/
@Test
void testAttachInvocationIdIfAsync_nullAttachments() {
URL url = URL.valueOf("dubbo://localhost/?test.async=true");
Invocation inv = new RpcInvocation("test", "DemoService", "", new Class[] {}, new String[] {});
RpcUtils.attachInvocationIdIfAsync(url, inv);
assertTrue(RpcUtils.getInvocationId(inv) >= 0L);
}
/**
* scenario: explicitly configure to not add attachment
* verify: no id attribute added in attachment
*/
@Test
void testAttachInvocationIdIfAsync_forceNotAttache() {
URL url = URL.valueOf("dubbo://localhost/?test.async=true&" + AUTO_ATTACH_INVOCATIONID_KEY + "=false");
Invocation inv = new RpcInvocation("test", "DemoService", "", new Class[] {}, new String[] {});
RpcUtils.attachInvocationIdIfAsync(url, inv);
assertNull(RpcUtils.getInvocationId(inv));
}
/**
* scenario: explicitly configure to add attachment
* verify: id attribute added in attachment
*/
@Test
void testAttachInvocationIdIfAsync_forceAttache() {
URL url = URL.valueOf("dubbo://localhost/?" + AUTO_ATTACH_INVOCATIONID_KEY + "=true");
Invocation inv = new RpcInvocation("test", "DemoService", "", new Class[] {}, new String[] {});
RpcUtils.attachInvocationIdIfAsync(url, inv);
assertNotNull(RpcUtils.getInvocationId(inv));
}
@Test
void testGetReturnType() {
Class<?> demoServiceClass = DemoService.class;
String serviceName = demoServiceClass.getName();
Invoker invoker = createMockInvoker(
URL.valueOf(
"test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService"));
// void sayHello(String name);
RpcInvocation inv = new RpcInvocation(
"sayHello", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
Class<?> returnType = RpcUtils.getReturnType(inv);
Assertions.assertNull(returnType);
// String echo(String text);
RpcInvocation inv1 =
new RpcInvocation("echo", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
Class<?> returnType1 = RpcUtils.getReturnType(inv1);
Assertions.assertNotNull(returnType1);
Assertions.assertEquals(String.class, returnType1);
// int getSize(String[] strs);
RpcInvocation inv2 = new RpcInvocation(
"getSize", serviceName, "", new Class<?>[] {String[].class}, null, null, invoker, null);
Class<?> returnType2 = RpcUtils.getReturnType(inv2);
Assertions.assertNotNull(returnType2);
Assertions.assertEquals(int.class, returnType2);
// Person getPerson(Person person);
RpcInvocation inv3 = new RpcInvocation(
"getPerson", serviceName, "", new Class<?>[] {Person.class}, null, null, invoker, null);
Class<?> returnType3 = RpcUtils.getReturnType(inv3);
Assertions.assertNotNull(returnType3);
Assertions.assertEquals(Person.class, returnType3);
// List<String> testReturnType1(String str);
RpcInvocation inv4 = new RpcInvocation(
"testReturnType1", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
Class<?> returnType4 = RpcUtils.getReturnType(inv4);
Assertions.assertNotNull(returnType4);
Assertions.assertEquals(List.class, returnType4);
}
@Test
void testGetReturnTypesUseCache() throws Exception {
Class<?> demoServiceClass = DemoService.class;
String serviceName = demoServiceClass.getName();
Invoker invoker = createMockInvoker(
URL.valueOf(
"test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService"));
RpcInvocation inv = new RpcInvocation(
"testReturnType", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
Type[] types = RpcUtils.getReturnTypes(inv);
Assertions.assertNotNull(types);
Assertions.assertEquals(2, types.length);
Assertions.assertEquals(String.class, types[0]);
Assertions.assertEquals(String.class, types[1]);
Assertions.assertArrayEquals(types, inv.getReturnTypes());
RpcInvocation inv1 = new RpcInvocation(
"testReturnType1", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
java.lang.reflect.Type[] types1 = RpcUtils.getReturnTypes(inv1);
Assertions.assertNotNull(types1);
Assertions.assertEquals(2, types1.length);
Assertions.assertEquals(List.class, types1[0]);
Assertions.assertEquals(
demoServiceClass.getMethod("testReturnType1", String.class).getGenericReturnType(), types1[1]);
Assertions.assertArrayEquals(types1, inv1.getReturnTypes());
RpcInvocation inv2 = new RpcInvocation(
"testReturnType2", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
java.lang.reflect.Type[] types2 = RpcUtils.getReturnTypes(inv2);
Assertions.assertNotNull(types2);
Assertions.assertEquals(2, types2.length);
Assertions.assertEquals(String.class, types2[0]);
Assertions.assertEquals(String.class, types2[1]);
Assertions.assertArrayEquals(types2, inv2.getReturnTypes());
RpcInvocation inv3 = new RpcInvocation(
"testReturnType3", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
java.lang.reflect.Type[] types3 = RpcUtils.getReturnTypes(inv3);
Assertions.assertNotNull(types3);
Assertions.assertEquals(2, types3.length);
Assertions.assertEquals(List.class, types3[0]);
java.lang.reflect.Type genericReturnType3 =
demoServiceClass.getMethod("testReturnType3", String.class).getGenericReturnType();
Assertions.assertEquals(((ParameterizedType) genericReturnType3).getActualTypeArguments()[0], types3[1]);
Assertions.assertArrayEquals(types3, inv3.getReturnTypes());
RpcInvocation inv4 = new RpcInvocation(
"testReturnType4", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
java.lang.reflect.Type[] types4 = RpcUtils.getReturnTypes(inv4);
Assertions.assertNotNull(types4);
Assertions.assertEquals(2, types4.length);
Assertions.assertNull(types4[0]);
Assertions.assertNull(types4[1]);
Assertions.assertArrayEquals(types4, inv4.getReturnTypes());
RpcInvocation inv5 = new RpcInvocation(
"testReturnType5", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
java.lang.reflect.Type[] types5 = RpcUtils.getReturnTypes(inv5);
Assertions.assertNotNull(types5);
Assertions.assertEquals(2, types5.length);
Assertions.assertEquals(Map.class, types5[0]);
java.lang.reflect.Type genericReturnType5 =
demoServiceClass.getMethod("testReturnType5", String.class).getGenericReturnType();
Assertions.assertEquals(((ParameterizedType) genericReturnType5).getActualTypeArguments()[0], types5[1]);
Assertions.assertArrayEquals(types5, inv5.getReturnTypes());
}
@Test
void testGetReturnTypesWithoutCache() throws Exception {
Class<?> demoServiceClass = DemoService.class;
String serviceName = demoServiceClass.getName();
Invoker invoker = createMockInvoker(
URL.valueOf(
"test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService"));
RpcInvocation inv = new RpcInvocation(
"testReturnType", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
inv.setReturnTypes(null);
Type[] types = RpcUtils.getReturnTypes(inv);
Assertions.assertNotNull(types);
Assertions.assertEquals(2, types.length);
Assertions.assertEquals(String.class, types[0]);
Assertions.assertEquals(String.class, types[1]);
RpcInvocation inv1 = new RpcInvocation(
"testReturnType1", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
inv1.setReturnTypes(null);
java.lang.reflect.Type[] types1 = RpcUtils.getReturnTypes(inv1);
Assertions.assertNotNull(types1);
Assertions.assertEquals(2, types1.length);
Assertions.assertEquals(List.class, types1[0]);
Assertions.assertEquals(
demoServiceClass.getMethod("testReturnType1", String.class).getGenericReturnType(), types1[1]);
RpcInvocation inv2 = new RpcInvocation(
"testReturnType2", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
inv2.setReturnTypes(null);
java.lang.reflect.Type[] types2 = RpcUtils.getReturnTypes(inv2);
Assertions.assertNotNull(types2);
Assertions.assertEquals(2, types2.length);
Assertions.assertEquals(String.class, types2[0]);
Assertions.assertEquals(String.class, types2[1]);
RpcInvocation inv3 = new RpcInvocation(
"testReturnType3", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
inv3.setReturnTypes(null);
java.lang.reflect.Type[] types3 = RpcUtils.getReturnTypes(inv3);
Assertions.assertNotNull(types3);
Assertions.assertEquals(2, types3.length);
Assertions.assertEquals(List.class, types3[0]);
java.lang.reflect.Type genericReturnType3 =
demoServiceClass.getMethod("testReturnType3", String.class).getGenericReturnType();
Assertions.assertEquals(((ParameterizedType) genericReturnType3).getActualTypeArguments()[0], types3[1]);
RpcInvocation inv4 = new RpcInvocation(
"testReturnType4", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
inv4.setReturnTypes(null);
java.lang.reflect.Type[] types4 = RpcUtils.getReturnTypes(inv4);
Assertions.assertNotNull(types4);
Assertions.assertEquals(2, types4.length);
Assertions.assertNull(types4[0]);
Assertions.assertNull(types4[1]);
RpcInvocation inv5 = new RpcInvocation(
"testReturnType5", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
inv5.setReturnTypes(null);
java.lang.reflect.Type[] types5 = RpcUtils.getReturnTypes(inv5);
Assertions.assertNotNull(types5);
Assertions.assertEquals(2, types5.length);
Assertions.assertEquals(Map.class, types5[0]);
java.lang.reflect.Type genericReturnType5 =
demoServiceClass.getMethod("testReturnType5", String.class).getGenericReturnType();
Assertions.assertEquals(((ParameterizedType) genericReturnType5).getActualTypeArguments()[0], types5[1]);
}
@Test
void testGetReturnTypesWhenGeneric() throws Exception {
Class<?> demoServiceClass = DemoService.class;
String serviceName = demoServiceClass.getName();
Invoker invoker = createMockInvoker(
URL.valueOf(
"test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService"));
RpcInvocation inv = new RpcInvocation(
"testReturnType", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
inv.setMethodName($INVOKE);
Type[] types = RpcUtils.getReturnTypes(inv);
Assertions.assertNull(types);
RpcInvocation inv1 = new RpcInvocation(
"testReturnType1", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
inv1.setMethodName($INVOKE);
java.lang.reflect.Type[] types1 = RpcUtils.getReturnTypes(inv1);
Assertions.assertNull(types1);
RpcInvocation inv2 = new RpcInvocation(
"testReturnType2", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
inv2.setMethodName($INVOKE);
java.lang.reflect.Type[] types2 = RpcUtils.getReturnTypes(inv2);
Assertions.assertNull(types2);
RpcInvocation inv3 = new RpcInvocation(
"testReturnType3", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
inv3.setMethodName($INVOKE);
java.lang.reflect.Type[] types3 = RpcUtils.getReturnTypes(inv3);
Assertions.assertNull(types3);
RpcInvocation inv4 = new RpcInvocation(
"testReturnType4", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
inv4.setMethodName($INVOKE);
java.lang.reflect.Type[] types4 = RpcUtils.getReturnTypes(inv4);
Assertions.assertNull(types4);
RpcInvocation inv5 = new RpcInvocation(
"testReturnType5", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
inv5.setMethodName($INVOKE);
java.lang.reflect.Type[] types5 = RpcUtils.getReturnTypes(inv5);
Assertions.assertNull(types5);
}
@Test
void testGetParameterTypes() {
Class<?> demoServiceClass = DemoService.class;
String serviceName = demoServiceClass.getName();
Invoker invoker = createMockInvoker();
// void sayHello(String name);
RpcInvocation inv1 = new RpcInvocation(
"sayHello", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
Class<?>[] parameterTypes1 = RpcUtils.getParameterTypes(inv1);
Assertions.assertNotNull(parameterTypes1);
Assertions.assertEquals(1, parameterTypes1.length);
Assertions.assertEquals(String.class, parameterTypes1[0]);
// long timestamp();
RpcInvocation inv2 = new RpcInvocation("timestamp", serviceName, "", null, null, null, invoker, null);
Class<?>[] parameterTypes2 = RpcUtils.getParameterTypes(inv2);
Assertions.assertEquals(0, parameterTypes2.length);
// Type enumlength(Type... types);
RpcInvocation inv3 = new RpcInvocation(
"enumlength", serviceName, "", new Class<?>[] {Type.class, Type.class}, null, null, invoker, null);
Class<?>[] parameterTypes3 = RpcUtils.getParameterTypes(inv3);
Assertions.assertNotNull(parameterTypes3);
Assertions.assertEquals(2, parameterTypes3.length);
Assertions.assertEquals(Type.class, parameterTypes3[0]);
Assertions.assertEquals(Type.class, parameterTypes3[1]);
// byte getbyte(byte arg);
RpcInvocation inv4 =
new RpcInvocation("getbyte", serviceName, "", new Class<?>[] {byte.class}, null, null, invoker, null);
Class<?>[] parameterTypes4 = RpcUtils.getParameterTypes(inv4);
Assertions.assertNotNull(parameterTypes4);
Assertions.assertEquals(1, parameterTypes4.length);
Assertions.assertEquals(byte.class, parameterTypes4[0]);
// void $invoke(String s1, String s2);
RpcInvocation inv5 = new RpcInvocation(
"$invoke",
serviceName,
"",
new Class<?>[] {String.class, String[].class},
new Object[] {"method", new String[] {"java.lang.String", "void", "java.lang.Object"}},
null,
invoker,
null);
Class<?>[] parameterTypes5 = RpcUtils.getParameterTypes(inv5);
Assertions.assertNotNull(parameterTypes5);
Assertions.assertEquals(3, parameterTypes5.length);
Assertions.assertEquals(String.class, parameterTypes5[0]);
Assertions.assertEquals(void.class, parameterTypes5[1]);
Assertions.assertEquals(Object.class, parameterTypes5[2]);
}
@Test
void testGet_$invokeAsync_ParameterTypes() {
Object[] args = new Object[] {"hello", true, 520};
Class<?> demoServiceClass = DemoService.class;
String serviceName = demoServiceClass.getName();
Invoker invoker = createMockInvoker();
RpcInvocation inv = new RpcInvocation(
"$invokeAsync",
serviceName,
"",
new Class<?>[] {String.class, String[].class, Object[].class},
new Object[] {
"method", new String[] {"java.lang.String", "java.lang.Boolean", "java.lang.Integer"}, args
},
null,
invoker,
null);
Class<?>[] parameterTypes = RpcUtils.getParameterTypes(inv);
for (int i = 0; i < args.length; i++) {
Assertions.assertNotNull(parameterTypes[i]);
Assertions.assertEquals(args[i].getClass(), parameterTypes[i]);
}
}
@ParameterizedTest
@CsvSource({"echo", "stringLength", "testReturnType"})
public void testGetMethodName(String methodName) {
Class<?> demoServiceClass = DemoService.class;
String serviceName = demoServiceClass.getName();
Invoker invoker = createMockInvoker();
RpcInvocation inv1 = new RpcInvocation(
methodName, serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
String actual = RpcUtils.getMethodName(inv1);
Assertions.assertNotNull(actual);
Assertions.assertEquals(methodName, actual);
}
@ParameterizedTest
@CsvSource({"hello", "apache", "dubbo"})
public void testGet_$invoke_MethodName(String method) {
Class<?> demoServiceClass = DemoService.class;
String serviceName = demoServiceClass.getName();
Invoker invoker = createMockInvoker();
RpcInvocation inv = new RpcInvocation(
"$invoke",
serviceName,
"",
new Class<?>[] {String.class, String[].class},
new Object[] {method, new String[] {"java.lang.String", "void", "java.lang.Object"}},
null,
invoker,
null);
String actual = RpcUtils.getMethodName(inv);
Assertions.assertNotNull(actual);
Assertions.assertEquals(method, actual);
}
@ParameterizedTest
@CsvSource({"hello", "apache", "dubbo"})
public void testGet_$invokeAsync_MethodName(String method) {
Class<?> demoServiceClass = DemoService.class;
String serviceName = demoServiceClass.getName();
Invoker invoker = createMockInvoker();
RpcInvocation inv = new RpcInvocation(
"$invokeAsync",
serviceName,
"",
new Class<?>[] {String.class, String[].class},
new Object[] {method, new String[] {"java.lang.String", "void", "java.lang.Object"}},
null,
invoker,
null);
String actual = RpcUtils.getMethodName(inv);
Assertions.assertNotNull(actual);
Assertions.assertEquals(method, actual);
}
@Test
void testGet_$invoke_Arguments() {
Object[] args = new Object[] {"hello", "dubbo", 520};
Class<?> demoServiceClass = DemoService.class;
String serviceName = demoServiceClass.getName();
Invoker invoker = createMockInvoker();
RpcInvocation inv = new RpcInvocation(
"$invoke",
serviceName,
"",
new Class<?>[] {String.class, String[].class, Object[].class},
new Object[] {"method", new String[] {}, args},
null,
invoker,
null);
Object[] arguments = RpcUtils.getArguments(inv);
for (int i = 0; i < args.length; i++) {
Assertions.assertNotNull(arguments[i]);
Assertions.assertEquals(
args[i].getClass().getName(), arguments[i].getClass().getName());
Assertions.assertEquals(args[i], arguments[i]);
}
}
@Test
void testGet_$invokeAsync_Arguments() {
Object[] args = new Object[] {"hello", "dubbo", 520};
Class<?> demoServiceClass = DemoService.class;
String serviceName = demoServiceClass.getName();
Invoker invoker = createMockInvoker();
RpcInvocation inv = new RpcInvocation(
"$invokeAsync",
serviceName,
"",
new Class<?>[] {String.class, String[].class, Object[].class},
new Object[] {"method", new String[] {}, args},
null,
invoker,
null);
Object[] arguments = RpcUtils.getArguments(inv);
for (int i = 0; i < args.length; i++) {
Assertions.assertNotNull(arguments[i]);
Assertions.assertEquals(
args[i].getClass().getName(), arguments[i].getClass().getName());
Assertions.assertEquals(args[i], arguments[i]);
}
}
@Test
void testIsAsync() {
Object[] args = new Object[] {"hello", "dubbo", 520};
Class<?> demoServiceClass = DemoService.class;
String serviceName = demoServiceClass.getName();
Invoker invoker = createMockInvoker();
URL url = URL.valueOf(
"test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService");
RpcInvocation inv = new RpcInvocation(
"test",
serviceName,
"",
new Class<?>[] {String.class, String[].class, Object[].class},
new Object[] {"method", new String[] {}, args},
null,
invoker,
null);
Assertions.assertFalse(RpcUtils.isAsync(url, inv));
inv.setInvokeMode(InvokeMode.ASYNC);
Assertions.assertTrue(RpcUtils.isAsync(url, inv));
}
@Test
void testIsGenericCall() {
Assertions.assertTrue(
RpcUtils.isGenericCall("Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/Object;", "$invoke"));
Assertions.assertTrue(
RpcUtils.isGenericCall("Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/Object;", "$invokeAsync"));
Assertions.assertFalse(
RpcUtils.isGenericCall("Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/Object;", "testMethod"));
}
@Test
void testIsEcho() {
Assertions.assertTrue(RpcUtils.isEcho("Ljava/lang/Object;", "$echo"));
Assertions.assertFalse(RpcUtils.isEcho("Ljava/lang/Object;", "testMethod"));
Assertions.assertFalse(RpcUtils.isEcho("Ljava/lang/String;", "$echo"));
}
@Test
void testIsReturnTypeFuture() {
Class<?> demoServiceClass = DemoService.class;
String serviceName = demoServiceClass.getName();
Invoker invoker = createMockInvoker(
URL.valueOf(
"test://127.0.0.1:1/org.apache.dubbo.rpc.support.DemoService?interface=org.apache.dubbo.rpc.support.DemoService"));
RpcInvocation inv = new RpcInvocation(
"testReturnType", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
Assertions.assertFalse(RpcUtils.isReturnTypeFuture(inv));
ModuleServiceRepository repository =
ApplicationModel.defaultModel().getDefaultModule().getServiceRepository();
repository.registerService(demoServiceClass);
inv = new RpcInvocation(
"testReturnType4", serviceName, "", new Class<?>[] {String.class}, null, null, invoker, null);
Assertions.assertTrue(RpcUtils.isReturnTypeFuture(inv));
}
}
| 5,913 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/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.rpc.support;
import org.apache.dubbo.rpc.CustomArgument;
import org.apache.dubbo.rpc.RpcContext;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
/**
* 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 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 enumlength(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 getPerson(Person person) {
return person;
}
@Override
public String testReturnType(String str) {
return null;
}
@Override
public List<String> testReturnType1(String str) {
return null;
}
@Override
public CompletableFuture<String> testReturnType2(String str) {
return null;
}
@Override
public CompletableFuture<List<String>> testReturnType3(String str) {
return null;
}
@Override
public CompletableFuture testReturnType4(String str) {
return CompletableFuture.completedFuture("");
}
@Override
public CompletableFuture<Map<String, String>> testReturnType5(String str) {
return null;
}
@Override
public void $invoke(String s1, String s2) {}
}
| 5,914 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/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.rpc.support;
import java.io.Serializable;
/**
* Person.java
*/
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Person() {}
public Person(String name, int age) {
this.name = name;
this.age = 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;
}
}
| 5,915 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/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.rpc.support;
import org.apache.dubbo.rpc.CustomArgument;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
public interface DemoService {
void sayHello(String name);
String echo(String text);
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 enumlength(Type type);
String get(CustomArgument arg1);
byte getbyte(byte arg);
Person getPerson(Person person);
String testReturnType(String str);
List<String> testReturnType1(String str);
CompletableFuture<String> testReturnType2(String str);
CompletableFuture<List<String>> testReturnType3(String str);
CompletableFuture testReturnType4(String str);
CompletableFuture<Map<String, String>> testReturnType5(String str);
void $invoke(String s1, String s2);
}
| 5,916 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/RuntimeExceptionInvoker.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.rpc.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
public class RuntimeExceptionInvoker extends MyInvoker {
public RuntimeExceptionInvoker(URL url) {
super(url);
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
throw new RuntimeException("Runtime exception");
}
}
| 5,917 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceA.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.rpc.support;
public interface DemoServiceA {
String methodA();
}
| 5,918 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/IEcho.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.rpc.support;
public interface IEcho {
String echo(String e);
}
| 5,919 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/MyInvoker.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.rpc.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import java.util.concurrent.CompletableFuture;
/**
* MockInvoker.java
*/
public class MyInvoker<T> implements Invoker<T> {
URL url;
Class<T> type;
boolean hasException = false;
boolean destroyed = false;
public MyInvoker(URL url) {
this.url = url;
type = (Class<T>) DemoService.class;
}
public MyInvoker(URL url, boolean hasException) {
this.url = url;
type = (Class<T>) DemoService.class;
this.hasException = hasException;
}
@Override
public Class<T> getInterface() {
return type;
}
public URL getUrl() {
return url;
}
@Override
public boolean isAvailable() {
return false;
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
AppResponse result = new AppResponse();
if (!hasException) {
result.setValue("alibaba");
} else {
result.setException(new RuntimeException("mocked exception"));
}
return new AsyncRpcResult(CompletableFuture.completedFuture(result), invocation);
}
@Override
public void destroy() {
destroyed = true;
}
public boolean isDestroyed() {
return destroyed;
}
@Override
public String toString() {
return "MyInvoker.toString()";
}
}
| 5,920 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/support/DemoServiceAMock.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.rpc.support;
/**
* default mock service for DemoServiceA
*/
public class DemoServiceAMock implements DemoServiceA {
public static final String MOCK_VALUE = "mockA";
@Override
public String methodA() {
return MOCK_VALUE;
}
}
| 5,921 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubSuppliersTest.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.rpc.stub;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.fail;
class StubSuppliersTest {
private final String serviceName = "service";
@Test
void addDescriptor() {
ServiceDescriptor descriptor = Mockito.mock(ServiceDescriptor.class);
StubSuppliers.addDescriptor(serviceName, descriptor);
Assertions.assertEquals(descriptor, StubSuppliers.getServiceDescriptor(serviceName));
}
@Test
void addSupplier() {
Invoker<?> invoker = Mockito.mock(Invoker.class);
ServiceDescriptor descriptor = Mockito.mock(ServiceDescriptor.class);
StubSuppliers.addSupplier(serviceName, i -> invoker);
Assertions.assertEquals(invoker, StubSuppliers.createStub(serviceName, invoker));
}
@Test
void createStub() {
Invoker<?> invoker = Mockito.mock(Invoker.class);
try {
StubSuppliers.createStub(serviceName + 1, invoker);
fail();
} catch (IllegalStateException e) {
// pass
}
}
@Test
void getServiceDescriptor() {
try {
StubSuppliers.getServiceDescriptor(serviceName + 1);
fail();
} catch (IllegalStateException e) {
// pass
}
}
}
| 5,922 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/BiStreamMethodHandlerTest.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.rpc.stub;
import org.apache.dubbo.common.stream.StreamObserver;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class BiStreamMethodHandlerTest {
@Test
void invoke() throws ExecutionException, InterruptedException, TimeoutException {
StreamObserver<String> responseObserver = Mockito.mock(StreamObserver.class);
BiStreamMethodHandler<String, String> handler = new BiStreamMethodHandler<>(o -> responseObserver);
CompletableFuture<StreamObserver<String>> future = handler.invoke(new Object[] {responseObserver});
Assertions.assertEquals(responseObserver, future.get(1, TimeUnit.SECONDS));
}
}
| 5,923 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubInvokerTest.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.rpc.stub;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.stream.StreamObserver;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.support.DemoService;
import org.apache.dubbo.rpc.support.DemoServiceImpl;
import java.util.Collections;
import java.util.Map;
import java.util.function.BiConsumer;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class StubInvokerTest {
private final URL url = URL.valueOf("tri://0.0.0.0:50051/" + DemoService.class.getName());
private final String methodName = "sayHello";
private final BiConsumer<String, StreamObserver<String>> func = (a, o) -> {
o.onNext("hello," + a);
o.onCompleted();
};
private final Map<String, StubMethodHandler<?, ?>> methodMap =
Collections.singletonMap(methodName, new UnaryStubMethodHandler<>(func));
private final StubInvoker<DemoService> invoker =
new StubInvoker<>(new DemoServiceImpl(), url, DemoService.class, methodMap);
@Test
void getUrl() {
Assertions.assertEquals(url, invoker.getUrl());
}
@Test
void isAvailable() {
Assertions.assertTrue(invoker.isAvailable());
}
@Test
void destroy() {
invoker.destroy();
}
@Test
void getInterface() {
Assertions.assertEquals(DemoService.class, invoker.getInterface());
}
@Test
void invoke() {
RpcInvocation invocation = new RpcInvocation();
invocation.setMethodName(methodName);
invocation.setArguments(new Object[] {"test"});
Result result = invoker.invoke(invocation);
Object value = result.getValue();
Assertions.assertEquals("hello,test", value);
}
}
| 5,924 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/StubProxyFactoryTest.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.rpc.stub;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.ServerService;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.mockito.Mockito.when;
class StubProxyFactoryTest {
private final StubProxyFactory factory = new StubProxyFactory();
private final Invoker<MockInterface> invoker2 = Mockito.mock(Invoker.class);
@Test
void getProxy() {
Invoker<?> invoker = Mockito.mock(Invoker.class);
URL url = Mockito.mock(URL.class);
when(invoker.getUrl()).thenReturn(url);
String service = "SERV_PROX";
when(url.getServiceInterface()).thenReturn(service);
StubSuppliers.addSupplier(service, i -> invoker);
Assertions.assertEquals(invoker, factory.getProxy(invoker));
Assertions.assertEquals(invoker, factory.getProxy(invoker, false));
}
private interface MockInterface {}
private class MockStub implements ServerService<MockInterface>, MockInterface {
@Override
public Invoker<MockInterface> getInvoker(URL url) {
return invoker2;
}
@Override
public ServiceDescriptor getServiceDescriptor() {
return null;
}
}
@Test
void getInvoker() {
URL url = Mockito.mock(URL.class);
Assertions.assertEquals(invoker2, factory.getInvoker(new MockStub(), MockInterface.class, url));
}
}
| 5,925 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/FutureToObserverAdaptorTest.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.rpc.stub;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.fail;
class FutureToObserverAdaptorTest {
@Test
void testAdapt() throws ExecutionException, InterruptedException, TimeoutException {
CompletableFuture<String> done = CompletableFuture.completedFuture("a");
FutureToObserverAdaptor<String> adaptor = new FutureToObserverAdaptor<>(done);
try {
adaptor.onNext("teet");
fail();
} catch (IllegalStateException e) {
// pass
}
CompletableFuture<String> cancel = new CompletableFuture<>();
cancel.cancel(true);
FutureToObserverAdaptor<String> adaptor1 = new FutureToObserverAdaptor<>(cancel);
try {
adaptor1.onNext("teet");
fail();
} catch (IllegalStateException e) {
// pass
}
CompletableFuture<String> exc = new CompletableFuture<>();
exc.completeExceptionally(new IllegalStateException("Test"));
FutureToObserverAdaptor<String> adaptor2 = new FutureToObserverAdaptor<>(exc);
try {
adaptor2.onNext("teet");
fail();
} catch (IllegalStateException e) {
// pass
}
CompletableFuture<String> success = new CompletableFuture<>();
FutureToObserverAdaptor<String> adaptor3 = new FutureToObserverAdaptor<>(success);
adaptor3.onNext("test");
adaptor3.onCompleted();
Assertions.assertEquals("test", success.get(1, TimeUnit.SECONDS));
CompletableFuture<String> exc2 = new CompletableFuture<>();
FutureToObserverAdaptor<String> adaptor4 = new FutureToObserverAdaptor<>(exc2);
adaptor4.onError(new IllegalStateException("test"));
try {
exc2.get();
fail();
} catch (ExecutionException e) {
Assertions.assertTrue(e.getCause() instanceof IllegalStateException);
}
CompletableFuture<String> complete = new CompletableFuture<>();
FutureToObserverAdaptor<String> adaptor5 = new FutureToObserverAdaptor<>(complete);
try {
adaptor5.onCompleted();
fail();
} catch (IllegalStateException e) {
// pass
}
}
}
| 5,926 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/stub/ServerStreamMethodHandlerTest.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.rpc.stub;
import org.apache.dubbo.common.stream.StreamObserver;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
class ServerStreamMethodHandlerTest {
@Test
void invoke() {
AtomicInteger nextCounter = new AtomicInteger();
AtomicInteger completeCounter = new AtomicInteger();
AtomicInteger errorCounter = new AtomicInteger();
StreamObserver<String> responseObserver = Mockito.mock(StreamObserver.class);
doAnswer(o -> nextCounter.incrementAndGet()).when(responseObserver).onNext(anyString());
doAnswer(o -> completeCounter.incrementAndGet()).when(responseObserver).onCompleted();
doAnswer(o -> errorCounter.incrementAndGet()).when(responseObserver).onError(any(Throwable.class));
BiConsumer<String, StreamObserver<String>> consumer = (s, stringStreamObserver) -> {
for (int i = 0; i < 10; i++) {
stringStreamObserver.onNext(s + i);
}
stringStreamObserver.onCompleted();
};
ServerStreamMethodHandler<String, String> handler = new ServerStreamMethodHandler<>(consumer);
CompletableFuture<?> future = handler.invoke(new Object[] {"test", responseObserver});
Assertions.assertTrue(future.isDone());
Assertions.assertEquals(10, nextCounter.get());
Assertions.assertEquals(0, errorCounter.get());
Assertions.assertEquals(1, completeCounter.get());
}
}
| 5,927 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/AccessLogFilterTest.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.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.logger.log4j.Log4jLogger;
import org.apache.dubbo.common.logger.support.FailsafeLogger;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.support.AccessLogData;
import org.apache.dubbo.rpc.support.MockInvocation;
import org.apache.dubbo.rpc.support.MyInvoker;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Queue;
import org.apache.log4j.Appender;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* AccessLogFilterTest.java
*/
class AccessLogFilterTest {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger("mock.dubbo.access.log");
private static org.apache.log4j.Logger realLogger;
@BeforeAll
public static void setupLogger() {
FailsafeLogger failsafeLogger = (FailsafeLogger) logger;
Log4jLogger log4j2Logger = (Log4jLogger) failsafeLogger.getLogger();
realLogger = log4j2Logger.getLogger();
}
AccessLogFilter accessLogFilter = new AccessLogFilter();
// TODO how to assert thread action
@Test
@SuppressWarnings("unchecked")
public void testDefault() throws NoSuchFieldException, IllegalAccessException {
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1");
Invoker<AccessLogFilterTest> invoker = new MyInvoker<AccessLogFilterTest>(url);
Invocation invocation = new MockInvocation();
Field field = AccessLogFilter.class.getDeclaredField("logEntries");
field.setAccessible(true);
assertTrue(((Map) field.get(accessLogFilter)).isEmpty());
accessLogFilter.invoke(invoker, invocation);
Map<String, Queue<AccessLogData>> logs = (Map<String, Queue<AccessLogData>>) field.get(accessLogFilter);
assertFalse(logs.isEmpty());
assertFalse(logs.get("true").isEmpty());
AccessLogData log = logs.get("true").iterator().next();
assertEquals("org.apache.dubbo.rpc.support.DemoService", log.getServiceName());
}
@Test
void testCustom() {
ErrorTypeAwareLogger originalLogger = AccessLogFilter.logger;
long originalInterval = AccessLogFilter.getInterval();
Appender appender = mock(Appender.class);
AccessLogFilter.setInterval(500);
AccessLogFilter.logger = logger;
AccessLogFilter customAccessLogFilter = new AccessLogFilter();
try {
realLogger.addAppender(appender);
URL url = URL.valueOf("test://test:11/test?accesslog=custom-access.log");
Invoker<AccessLogFilterTest> invoker = new MyInvoker<>(url);
Invocation invocation = new MockInvocation();
customAccessLogFilter.invoke(invoker, invocation);
sleep();
ArgumentCaptor<LoggingEvent> argument = ArgumentCaptor.forClass(LoggingEvent.class);
verify(appender, times(2)).doAppend(argument.capture());
assertEquals(Level.WARN, argument.getAllValues().get(1).getLevel());
assertTrue(argument.getAllValues()
.get(1)
.getRenderedMessage()
.contains("Change of accesslog file path not allowed"));
} finally {
customAccessLogFilter.destroy();
realLogger.removeAppender(appender);
AccessLogFilter.logger = originalLogger;
AccessLogFilter.setInterval(originalInterval);
}
Appender appender2 = mock(Appender.class);
AccessLogFilter.setInterval(500);
AccessLogFilter.logger = logger;
AccessLogFilter customAccessLogFilter2 = new AccessLogFilter();
try {
realLogger.addAppender(appender2);
URL url2 = URL.valueOf("test://test:11/test?accesslog=custom-access.log&accesslog.fixed.path=false");
Invoker<AccessLogFilterTest> invoker = new MyInvoker<>(url2);
Invocation invocation = new MockInvocation();
customAccessLogFilter2.invoke(invoker, invocation);
sleep();
ArgumentCaptor<LoggingEvent> argument = ArgumentCaptor.forClass(LoggingEvent.class);
verify(appender2, times(2)).doAppend(argument.capture());
assertEquals(Level.WARN, argument.getAllValues().get(1).getLevel());
assertTrue(argument.getAllValues().get(1).getRenderedMessage().contains("Accesslog file path changed to"));
} finally {
customAccessLogFilter2.destroy();
realLogger.removeAppender(appender2);
AccessLogFilter.logger = originalLogger;
AccessLogFilter.setInterval(originalInterval);
}
}
private void sleep() {
try {
Thread.sleep(600);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 5,928 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ClassLoaderFilterTest.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.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ServiceModel;
import org.apache.dubbo.rpc.support.DemoService;
import org.apache.dubbo.rpc.support.MyInvoker;
import java.net.URLClassLoader;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
class ClassLoaderFilterTest {
private ClassLoaderFilter classLoaderFilter = new ClassLoaderFilter();
@Test
void testInvoke() throws Exception {
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1");
String path = DemoService.class.getResource("/").getPath();
final URLClassLoader cl = new URLClassLoader(new java.net.URL[] {new java.net.URL("file:" + path)}) {
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
try {
return findClass(name);
} catch (ClassNotFoundException e) {
return super.loadClass(name);
}
}
};
final Class<?> clazz = cl.loadClass(DemoService.class.getCanonicalName());
Invoker invoker = new MyInvoker(url) {
@Override
public Class getInterface() {
return clazz;
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
Assertions.assertEquals(cl, Thread.currentThread().getContextClassLoader());
return null;
}
};
Invocation invocation = Mockito.mock(Invocation.class);
ServiceModel serviceModel = Mockito.mock(ServiceModel.class);
Mockito.when(serviceModel.getClassLoader()).thenReturn(cl);
Mockito.when(invocation.getServiceModel()).thenReturn(serviceModel);
classLoaderFilter.invoke(invoker, invocation);
}
}
| 5,929 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ContextFilterTest.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.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.support.DemoService;
import org.apache.dubbo.rpc.support.MockInvocation;
import org.apache.dubbo.rpc.support.MyInvoker;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* ContextFilterTest.java
* TODO need to enhance assertion
*/
class ContextFilterTest {
Filter contextFilter = new ContextFilter(ApplicationModel.defaultModel());
Invoker<DemoService> invoker;
Invocation invocation;
@SuppressWarnings("unchecked")
@Test
void testSetContext() {
invocation = mock(Invocation.class);
given(invocation.getMethodName()).willReturn("$enumlength");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {Enum.class});
given(invocation.getArguments()).willReturn(new Object[] {"hello"});
given(invocation.getObjectAttachments()).willReturn(null);
invoker = mock(Invoker.class);
given(invoker.isAvailable()).willReturn(true);
given(invoker.getInterface()).willReturn(DemoService.class);
AppResponse result = new AppResponse();
result.setValue("High");
given(invoker.invoke(invocation)).willReturn(result);
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
given(invoker.getUrl()).willReturn(url);
contextFilter.invoke(invoker, invocation);
assertNotNull(RpcContext.getServiceContext().getInvoker());
}
@Test
void testWithAttachments() {
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
Invoker<DemoService> invoker = new MyInvoker<DemoService>(url);
Invocation invocation = new MockInvocation();
Result result = contextFilter.invoke(invoker, invocation);
assertNotNull(RpcContext.getServiceContext().getInvoker());
}
}
| 5,930 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ActiveLimitFilterTest.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.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcStatus;
import org.apache.dubbo.rpc.support.BlockMyInvoker;
import org.apache.dubbo.rpc.support.MockInvocation;
import org.apache.dubbo.rpc.support.MyInvoker;
import org.apache.dubbo.rpc.support.RuntimeExceptionInvoker;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.fail;
/**
* ActiveLimitFilterTest.java
*/
class ActiveLimitFilterTest {
ActiveLimitFilter activeLimitFilter = new ActiveLimitFilter();
@Test
void testInvokeNoActives() {
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=0");
Invoker<ActiveLimitFilterTest> invoker = new MyInvoker<ActiveLimitFilterTest>(url);
Invocation invocation = new MockInvocation();
activeLimitFilter.invoke(invoker, invocation);
}
@Test
void testInvokeLessActives() {
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=10");
Invoker<ActiveLimitFilterTest> invoker = new MyInvoker<ActiveLimitFilterTest>(url);
Invocation invocation = new MockInvocation();
activeLimitFilter.invoke(invoker, invocation);
}
@Test
void testInvokeGreaterActives() {
AtomicInteger count = new AtomicInteger(0);
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=1&timeout=1");
final Invoker<ActiveLimitFilterTest> invoker = new BlockMyInvoker<ActiveLimitFilterTest>(url, 100);
final Invocation invocation = new MockInvocation();
final CountDownLatch latch = new CountDownLatch(1);
for (int i = 0; i < 100; i++) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 100; i++) {
try {
activeLimitFilter.invoke(invoker, invocation);
} catch (RpcException expected) {
count.incrementAndGet();
}
}
}
});
thread.start();
}
latch.countDown();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
assertNotSame(0, count.intValue());
}
@Test
void testInvokeTimeOut() {
int totalThread = 100;
int maxActives = 10;
long timeout = 1;
long blockTime = 100;
AtomicInteger count = new AtomicInteger(0);
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch latchBlocking = new CountDownLatch(totalThread);
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=" + maxActives
+ "&timeout=" + timeout);
final Invoker<ActiveLimitFilterTest> invoker = new BlockMyInvoker<ActiveLimitFilterTest>(url, blockTime);
final Invocation invocation = new MockInvocation();
RpcStatus.removeStatus(url);
RpcStatus.removeStatus(url, invocation.getMethodName());
for (int i = 0; i < totalThread; i++) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Result asyncResult = activeLimitFilter.invoke(invoker, invocation);
Result result = asyncResult.get();
activeLimitFilter.onResponse(result, invoker, invocation);
} catch (RpcException expected) {
count.incrementAndGet();
} catch (Exception e) {
fail();
}
} finally {
latchBlocking.countDown();
}
}
});
thread.start();
}
latch.countDown();
try {
latchBlocking.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
assertEquals(90, count.intValue());
}
@Test
void testInvokeNotTimeOut() {
int totalThread = 100;
int maxActives = 10;
long timeout = 100000;
long blockTime = 0;
AtomicInteger count = new AtomicInteger(0);
final CountDownLatch latch = new CountDownLatch(1);
final CountDownLatch latchBlocking = new CountDownLatch(totalThread);
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=" + maxActives
+ "&timeout=" + timeout);
final Invoker<ActiveLimitFilterTest> invoker = new BlockMyInvoker<ActiveLimitFilterTest>(url, blockTime);
final Invocation invocation = new MockInvocation();
for (int i = 0; i < totalThread; i++) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Result asyncResult = activeLimitFilter.invoke(invoker, invocation);
Result result = asyncResult.get();
activeLimitFilter.onResponse(result, invoker, invocation);
} catch (RpcException expected) {
count.incrementAndGet();
activeLimitFilter.onError(expected, invoker, invocation);
} catch (Exception e) {
fail();
}
} finally {
latchBlocking.countDown();
}
}
});
thread.start();
}
latch.countDown();
try {
latchBlocking.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
assertEquals(0, count.intValue());
}
@Test
void testInvokeRuntimeException() {
Assertions.assertThrows(RuntimeException.class, () -> {
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=0");
Invoker<ActiveLimitFilterTest> invoker = new RuntimeExceptionInvoker(url);
Invocation invocation = new MockInvocation();
RpcStatus count = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName());
int beforeExceptionActiveCount = count.getActive();
activeLimitFilter.invoke(invoker, invocation);
int afterExceptionActiveCount = count.getActive();
assertEquals(
beforeExceptionActiveCount,
afterExceptionActiveCount,
"After exception active count should be same");
});
}
@Test
void testInvokeRuntimeExceptionWithActiveCountMatch() {
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&actives=0");
Invoker<ActiveLimitFilterTest> invoker = new RuntimeExceptionInvoker(url);
Invocation invocation = new MockInvocation();
RpcStatus count = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName());
int beforeExceptionActiveCount = count.getActive();
try {
activeLimitFilter.invoke(invoker, invocation);
} catch (RuntimeException ex) {
activeLimitFilter.onError(ex, invoker, invocation);
int afterExceptionActiveCount = count.getActive();
assertEquals(
beforeExceptionActiveCount,
afterExceptionActiveCount,
"After exception active count should be same");
}
}
}
| 5,931 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExceptionFilterTest.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.rpc.filter;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.support.FailsafeErrorTypeAwareLogger;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.support.DemoService;
import org.apache.dubbo.rpc.support.LocalException;
import com.alibaba.com.caucho.hessian.HessianException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* ExceptionFilterTest
*/
class ExceptionFilterTest {
@SuppressWarnings("unchecked")
@Test
void testRpcException() {
Logger failLogger = mock(Logger.class);
FailsafeErrorTypeAwareLogger failsafeLogger = new FailsafeErrorTypeAwareLogger(failLogger);
RpcContext.getServiceContext().setRemoteAddress("127.0.0.1", 1234);
RpcException exception = new RpcException("TestRpcException");
ExceptionFilter exceptionFilter = new ExceptionFilter();
RpcInvocation invocation = new RpcInvocation(
"sayHello", DemoService.class.getName(), "", new Class<?>[] {String.class}, new Object[] {"world"});
Invoker<DemoService> invoker = mock(Invoker.class);
given(invoker.getInterface()).willReturn(DemoService.class);
given(invoker.invoke(eq(invocation))).willThrow(exception);
try {
exceptionFilter.invoke(invoker, invocation);
} catch (RpcException e) {
assertEquals("TestRpcException", e.getMessage());
exceptionFilter.setLogger(failsafeLogger);
exceptionFilter.onError(e, invoker, invocation);
}
failsafeLogger.error(
CONFIG_FILTER_VALIDATION_EXCEPTION,
"",
"",
eq("Got unchecked and undeclared exception which called by 127.0.0.1. service: "
+ DemoService.class.getName() + ", method: sayHello, exception: "
+ RpcException.class.getName() + ": TestRpcException"),
eq(exception));
RpcContext.removeContext();
}
@SuppressWarnings("unchecked")
@Test
void testJavaException() {
ExceptionFilter exceptionFilter = new ExceptionFilter();
RpcInvocation invocation = new RpcInvocation(
"sayHello", DemoService.class.getName(), "", new Class<?>[] {String.class}, new Object[] {"world"});
AppResponse appResponse = new AppResponse();
appResponse.setException(new IllegalArgumentException("java"));
Invoker<DemoService> invoker = mock(Invoker.class);
when(invoker.invoke(invocation)).thenReturn(appResponse);
when(invoker.getInterface()).thenReturn(DemoService.class);
Result newResult = exceptionFilter.invoke(invoker, invocation);
Assertions.assertEquals(appResponse.getException(), newResult.getException());
}
@SuppressWarnings("unchecked")
@Test
void testRuntimeException() {
ExceptionFilter exceptionFilter = new ExceptionFilter();
RpcInvocation invocation = new RpcInvocation(
"sayHello", DemoService.class.getName(), "", new Class<?>[] {String.class}, new Object[] {"world"});
AppResponse appResponse = new AppResponse();
appResponse.setException(new LocalException("localException"));
Invoker<DemoService> invoker = mock(Invoker.class);
when(invoker.invoke(invocation)).thenReturn(appResponse);
when(invoker.getInterface()).thenReturn(DemoService.class);
Result newResult = exceptionFilter.invoke(invoker, invocation);
Assertions.assertEquals(appResponse.getException(), newResult.getException());
}
@SuppressWarnings("unchecked")
@Test
void testConvertToRunTimeException() throws Exception {
ExceptionFilter exceptionFilter = new ExceptionFilter();
RpcInvocation invocation = new RpcInvocation(
"sayHello", DemoService.class.getName(), "", new Class<?>[] {String.class}, new Object[] {"world"});
AppResponse mockRpcResult = new AppResponse();
mockRpcResult.setException(new HessianException("hessian"));
Result mockAsyncResult = AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation);
Invoker<DemoService> invoker = mock(Invoker.class);
when(invoker.invoke(invocation)).thenReturn(mockAsyncResult);
when(invoker.getInterface()).thenReturn(DemoService.class);
Result asyncResult = exceptionFilter.invoke(invoker, invocation);
AppResponse appResponse = (AppResponse) asyncResult.get();
exceptionFilter.onResponse(appResponse, invoker, invocation);
Assertions.assertFalse(appResponse.getException() instanceof HessianException);
Assertions.assertEquals(appResponse.getException().getClass(), RuntimeException.class);
}
}
| 5,932 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericImplFilterTest.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.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.service.GenericException;
import org.apache.dubbo.rpc.service.GenericService;
import org.apache.dubbo.rpc.support.DemoService;
import org.apache.dubbo.rpc.support.Person;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE;
import static org.apache.dubbo.rpc.Constants.GENERIC_KEY;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.when;
class GenericImplFilterTest {
private GenericImplFilter genericImplFilter =
new GenericImplFilter(ApplicationModel.defaultModel().getDefaultModule());
@Test
void testInvoke() throws Exception {
RpcInvocation invocation = new RpcInvocation(
"getPerson",
"org.apache.dubbo.rpc.support.DemoService",
"org.apache.dubbo.rpc.support.DemoService:dubbo",
new Class[] {Person.class},
new Object[] {new Person("dubbo", 10)});
URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?"
+ "accesslog=true&group=dubbo&version=1.1&generic=true");
Invoker invoker = Mockito.mock(Invoker.class);
Map<String, Object> person = new HashMap<String, Object>();
person.put("name", "dubbo");
person.put("age", 10);
AppResponse mockRpcResult = new AppResponse(person);
when(invoker.invoke(any(Invocation.class)))
.thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation));
when(invoker.getUrl()).thenReturn(url);
when(invoker.getInterface()).thenReturn(DemoService.class);
Result asyncResult = genericImplFilter.invoke(invoker, invocation);
Result result = asyncResult.get();
genericImplFilter.onResponse(result, invoker, invocation);
Assertions.assertEquals(Person.class, result.getValue().getClass());
Assertions.assertEquals(10, ((Person) result.getValue()).getAge());
}
@Test
@Disabled("Apache Generic Exception not support cast exception now")
void testInvokeWithException1() throws Exception {
RpcInvocation invocation = new RpcInvocation(
"getPerson",
"org.apache.dubbo.rpc.support.DemoService",
"org.apache.dubbo.rpc.support.DemoService:dubbo",
new Class[] {Person.class},
new Object[] {new Person("dubbo", 10)});
URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?"
+ "accesslog=true&group=dubbo&version=1.1&generic=true");
Invoker invoker = Mockito.mock(Invoker.class);
AppResponse mockRpcResult = new AppResponse(new GenericException(new RuntimeException("failed")));
when(invoker.invoke(any(Invocation.class)))
.thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation));
when(invoker.getUrl()).thenReturn(url);
when(invoker.getInterface()).thenReturn(DemoService.class);
Result asyncResult = genericImplFilter.invoke(invoker, invocation);
Result result = asyncResult.get();
genericImplFilter.onResponse(result, invoker, invocation);
Assertions.assertEquals(RuntimeException.class, result.getException().getClass());
}
@Test
void testInvokeWithException2() throws Exception {
RpcInvocation invocation = new RpcInvocation(
"getPerson",
"org.apache.dubbo.rpc.support.DemoService",
"org.apache.dubbo.rpc.support.DemoService:dubbo",
new Class[] {Person.class},
new Object[] {new Person("dubbo", 10)});
URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?"
+ "accesslog=true&group=dubbo&version=1.1&generic=true");
Invoker invoker = Mockito.mock(Invoker.class);
AppResponse mockRpcResult = new AppResponse(new GenericException(new RuntimeException("failed")));
when(invoker.invoke(any(Invocation.class)))
.thenReturn(AsyncRpcResult.newDefaultAsyncResult(mockRpcResult, invocation));
when(invoker.getUrl()).thenReturn(url);
when(invoker.getInterface()).thenReturn(DemoService.class);
Result asyncResult = genericImplFilter.invoke(invoker, invocation);
Result result = asyncResult.get();
genericImplFilter.onResponse(result, invoker, invocation);
Assertions.assertEquals(GenericException.class, result.getException().getClass());
}
@Test
void testInvokeWith$Invoke() throws Exception {
Method genericInvoke = GenericService.class.getMethods()[0];
Map<String, Object> person = new HashMap<String, Object>();
person.put("name", "dubbo");
person.put("age", 10);
RpcInvocation invocation = new RpcInvocation(
$INVOKE,
GenericService.class.getName(),
"org.apache.dubbo.rpc.support.DemoService:dubbo",
genericInvoke.getParameterTypes(),
new Object[] {"getPerson", new String[] {Person.class.getCanonicalName()}, new Object[] {person}});
URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?"
+ "accesslog=true&group=dubbo&version=1.1&generic=true");
Invoker invoker = Mockito.mock(Invoker.class);
when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse(new Person("person", 10)));
when(invoker.getUrl()).thenReturn(url);
genericImplFilter.invoke(invoker, invocation);
Assertions.assertEquals("true", invocation.getAttachment(GENERIC_KEY));
}
}
| 5,933 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/GenericFilterTest.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.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.service.GenericService;
import org.apache.dubbo.rpc.support.DemoService;
import org.apache.dubbo.rpc.support.Person;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE;
import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA;
import static org.apache.dubbo.rpc.Constants.GENERIC_KEY;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
class GenericFilterTest {
GenericFilter genericFilter = new GenericFilter();
@Test
void testInvokeWithDefault() throws Exception {
Method genericInvoke = GenericService.class.getMethods()[0];
Map<String, Object> person = new HashMap<String, Object>();
person.put("name", "dubbo");
person.put("age", 10);
RpcInvocation invocation = new RpcInvocation(
$INVOKE, GenericService.class.getName(), "", genericInvoke.getParameterTypes(), new Object[] {
"getPerson", new String[] {Person.class.getCanonicalName()}, new Object[] {person}
});
URL url = URL.valueOf(
"test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1");
Invoker invoker = Mockito.mock(Invoker.class);
when(invoker.invoke(any(Invocation.class)))
.thenReturn(AsyncRpcResult.newDefaultAsyncResult(new Person("person", 10), invocation));
when(invoker.getUrl()).thenReturn(url);
when(invoker.getInterface()).thenReturn(DemoService.class);
Result asyncResult = genericFilter.invoke(invoker, invocation);
AppResponse appResponse = (AppResponse) asyncResult.get();
genericFilter.onResponse(appResponse, invoker, invocation);
Assertions.assertEquals(HashMap.class, appResponse.getValue().getClass());
Assertions.assertEquals(10, ((HashMap) appResponse.getValue()).get("age"));
}
@Test
void testInvokeWithJavaException() throws Exception {
// temporary enable native java generic serialize
System.setProperty(ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE, "true");
Assertions.assertThrows(RpcException.class, () -> {
Method genericInvoke = GenericService.class.getMethods()[0];
Map<String, Object> person = new HashMap<String, Object>();
person.put("name", "dubbo");
person.put("age", 10);
RpcInvocation invocation = new RpcInvocation(
$INVOKE, GenericService.class.getName(), "", genericInvoke.getParameterTypes(), new Object[] {
"getPerson", new String[] {Person.class.getCanonicalName()}, new Object[] {person}
});
invocation.setAttachment(GENERIC_KEY, GENERIC_SERIALIZATION_NATIVE_JAVA);
URL url = URL.valueOf("test://test:11/org.apache.dubbo.rpc.support.DemoService?"
+ "accesslog=true&group=dubbo&version=1.1");
Invoker invoker = Mockito.mock(Invoker.class);
when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse(new Person("person", 10)));
when(invoker.getUrl()).thenReturn(url);
when(invoker.getInterface()).thenReturn(DemoService.class);
genericFilter.invoke(invoker, invocation);
});
System.clearProperty(ENABLE_NATIVE_JAVA_GENERIC_SERIALIZE);
}
@Test
void testInvokeWithMethodNamtNot$Invoke() {
Method genericInvoke = GenericService.class.getMethods()[0];
Map<String, Object> person = new HashMap<String, Object>();
person.put("name", "dubbo");
person.put("age", 10);
RpcInvocation invocation = new RpcInvocation(
"sayHi", GenericService.class.getName(), "", genericInvoke.getParameterTypes(), new Object[] {
"getPerson", new String[] {Person.class.getCanonicalName()}, new Object[] {person}
});
URL url = URL.valueOf(
"test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1");
Invoker invoker = Mockito.mock(Invoker.class);
when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse(new Person("person", 10)));
when(invoker.getUrl()).thenReturn(url);
when(invoker.getInterface()).thenReturn(DemoService.class);
Result result = genericFilter.invoke(invoker, invocation);
Assertions.assertEquals(Person.class, result.getValue().getClass());
Assertions.assertEquals(10, ((Person) (result.getValue())).getAge());
}
@Test
void testInvokeWithMethodArgumentSizeIsNot3() {
Method genericInvoke = GenericService.class.getMethods()[0];
Map<String, Object> person = new HashMap<String, Object>();
person.put("name", "dubbo");
person.put("age", 10);
RpcInvocation invocation = new RpcInvocation(
$INVOKE, GenericService.class.getName(), "", genericInvoke.getParameterTypes(), new Object[] {
"getPerson", new String[] {Person.class.getCanonicalName()}
});
URL url = URL.valueOf(
"test://test:11/org.apache.dubbo.rpc.support.DemoService?" + "accesslog=true&group=dubbo&version=1.1");
Invoker invoker = Mockito.mock(Invoker.class);
when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse(new Person("person", 10)));
when(invoker.getUrl()).thenReturn(url);
when(invoker.getInterface()).thenReturn(DemoService.class);
Result result = genericFilter.invoke(invoker, invocation);
Assertions.assertEquals(Person.class, result.getValue().getClass());
Assertions.assertEquals(10, ((Person) (result.getValue())).getAge());
}
}
| 5,934 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/CompatibleFilterFilterTest.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.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.support.DemoService;
import org.apache.dubbo.rpc.support.Type;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* CompatibleFilterTest.java
*/
class CompatibleFilterFilterTest {
private CompatibleFilter compatibleFilter = new CompatibleFilter();
private Invocation invocation;
private Invoker invoker;
@AfterEach
public void tearDown() {
Mockito.reset(invocation, invoker);
}
@Test
void testInvokerGeneric() {
invocation = mock(RpcInvocation.class);
given(invocation.getMethodName()).willReturn("$enumlength");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {Enum.class});
given(invocation.getArguments()).willReturn(new Object[] {"hello"});
invoker = mock(Invoker.class);
given(invoker.isAvailable()).willReturn(true);
given(invoker.getInterface()).willReturn(DemoService.class);
AppResponse result = new AppResponse();
result.setValue("High");
given(invoker.invoke(invocation)).willReturn(result);
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
given(invoker.getUrl()).willReturn(url);
Result filterResult = compatibleFilter.invoke(invoker, invocation);
assertEquals(filterResult, result);
}
@Test
void testResultHasException() {
invocation = mock(RpcInvocation.class);
given(invocation.getMethodName()).willReturn("enumlength");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {Enum.class});
given(invocation.getArguments()).willReturn(new Object[] {"hello"});
invoker = mock(Invoker.class);
given(invoker.isAvailable()).willReturn(true);
given(invoker.getInterface()).willReturn(DemoService.class);
AppResponse result = new AppResponse();
result.setException(new RuntimeException());
result.setValue("High");
given(invoker.invoke(invocation)).willReturn(result);
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
given(invoker.getUrl()).willReturn(url);
Result filterResult = compatibleFilter.invoke(invoker, invocation);
assertEquals(filterResult, result);
}
@Test
void testInvokerJsonPojoSerialization() throws Exception {
invocation = mock(RpcInvocation.class);
given(invocation.getMethodName()).willReturn("enumlength");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {Type[].class});
given(invocation.getArguments()).willReturn(new Object[] {"hello"});
invoker = mock(Invoker.class);
given(invoker.isAvailable()).willReturn(true);
given(invoker.getInterface()).willReturn(DemoService.class);
AppResponse result = new AppResponse();
result.setValue("High");
AsyncRpcResult defaultAsyncResult = AsyncRpcResult.newDefaultAsyncResult(result, invocation);
given(invoker.invoke(invocation)).willReturn(defaultAsyncResult);
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&serialization=json");
given(invoker.getUrl()).willReturn(url);
Result asyncResult = compatibleFilter.invoke(invoker, invocation);
AppResponse appResponse = (AppResponse) asyncResult.get();
compatibleFilter.onResponse(appResponse, invoker, invocation);
assertEquals(Type.High, appResponse.getValue());
}
@Test
void testInvokerNonJsonEnumSerialization() throws Exception {
invocation = mock(RpcInvocation.class);
given(invocation.getMethodName()).willReturn("enumlength");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {Type[].class});
given(invocation.getArguments()).willReturn(new Object[] {"hello"});
invoker = mock(Invoker.class);
given(invoker.isAvailable()).willReturn(true);
given(invoker.getInterface()).willReturn(DemoService.class);
AppResponse result = new AppResponse();
result.setValue("High");
AsyncRpcResult defaultAsyncResult = AsyncRpcResult.newDefaultAsyncResult(result, invocation);
given(invoker.invoke(invocation)).willReturn(defaultAsyncResult);
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
given(invoker.getUrl()).willReturn(url);
Result asyncResult = compatibleFilter.invoke(invoker, invocation);
AppResponse appResponse = (AppResponse) asyncResult.get();
compatibleFilter.onResponse(appResponse, invoker, invocation);
assertEquals(Type.High, appResponse.getValue());
}
@Test
void testInvokerNonJsonNonPojoSerialization() {
invocation = mock(RpcInvocation.class);
given(invocation.getMethodName()).willReturn("echo");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class});
given(invocation.getArguments()).willReturn(new Object[] {"hello"});
invoker = mock(Invoker.class);
given(invoker.isAvailable()).willReturn(true);
given(invoker.getInterface()).willReturn(DemoService.class);
AppResponse result = new AppResponse();
result.setValue(new String[] {"High"});
given(invoker.invoke(invocation)).willReturn(result);
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
given(invoker.getUrl()).willReturn(url);
Result filterResult = compatibleFilter.invoke(invoker, invocation);
assertArrayEquals(new String[] {"High"}, (String[]) filterResult.getValue());
}
@Test
void testInvokerNonJsonPojoSerialization() {
invocation = mock(RpcInvocation.class);
given(invocation.getMethodName()).willReturn("echo");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class});
given(invocation.getArguments()).willReturn(new Object[] {"hello"});
invoker = mock(Invoker.class);
given(invoker.isAvailable()).willReturn(true);
given(invoker.getInterface()).willReturn(DemoService.class);
AppResponse result = new AppResponse();
result.setValue("hello");
given(invoker.invoke(invocation)).willReturn(result);
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
given(invoker.getUrl()).willReturn(url);
Result filterResult = compatibleFilter.invoke(invoker, invocation);
assertEquals("hello", filterResult.getValue());
}
}
| 5,935 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TokenFilterTest.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.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
class TokenFilterTest {
private TokenFilter tokenFilter = new TokenFilter();
@Test
void testInvokeWithToken() throws Exception {
String token = "token";
Invoker invoker = Mockito.mock(Invoker.class);
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&token=" + token);
when(invoker.getUrl()).thenReturn(url);
when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result"));
Invocation invocation = Mockito.mock(Invocation.class);
when(invocation.getObjectAttachmentWithoutConvert(TOKEN_KEY)).thenReturn(token);
Result result = tokenFilter.invoke(invoker, invocation);
Assertions.assertEquals("result", result.getValue());
}
@Test
void testInvokeWithWrongToken() throws Exception {
Assertions.assertThrows(RpcException.class, () -> {
String token = "token";
Invoker invoker = Mockito.mock(Invoker.class);
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&token=" + token);
when(invoker.getUrl()).thenReturn(url);
when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result"));
Map<String, Object> attachments = new HashMap<>();
attachments.put(TOKEN_KEY, "wrongToken");
Invocation invocation = Mockito.mock(Invocation.class);
when(invocation.getObjectAttachments()).thenReturn(attachments);
tokenFilter.invoke(invoker, invocation);
});
}
@Test
void testInvokeWithoutToken() throws Exception {
Assertions.assertThrows(RpcException.class, () -> {
String token = "token";
Invoker invoker = Mockito.mock(Invoker.class);
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&token=" + token);
when(invoker.getUrl()).thenReturn(url);
when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result"));
Invocation invocation = Mockito.mock(Invocation.class);
tokenFilter.invoke(invoker, invocation);
});
}
}
| 5,936 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/EchoFilterTest.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.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.support.DemoService;
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;
class EchoFilterTest {
Filter echoFilter = new EchoFilter();
@SuppressWarnings("unchecked")
@Test
void testEcho() {
Invocation invocation = createMockRpcInvocation();
Invoker<DemoService> invoker = createMockInvoker(invocation);
given(invocation.getMethodName()).willReturn("$echo");
Result filterResult = echoFilter.invoke(invoker, invocation);
assertEquals("hello", filterResult.getValue());
}
@SuppressWarnings("unchecked")
@Test
void testNonEcho() {
Invocation invocation = createMockRpcInvocation();
Invoker<DemoService> invoker = createMockInvoker(invocation);
given(invocation.getMethodName()).willReturn("echo");
Result filterResult = echoFilter.invoke(invoker, invocation);
assertEquals("High", filterResult.getValue());
}
Invocation createMockRpcInvocation() {
Invocation invocation = mock(RpcInvocation.class);
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {Enum.class});
given(invocation.getArguments()).willReturn(new Object[] {"hello"});
given(invocation.getObjectAttachments()).willReturn(null);
return invocation;
}
Invoker<DemoService> createMockInvoker(Invocation invocation) {
Invoker<DemoService> invoker = mock(Invoker.class);
given(invoker.isAvailable()).willReturn(true);
given(invoker.getInterface()).willReturn(DemoService.class);
AppResponse result = new AppResponse();
result.setValue("High");
given(invoker.invoke(invocation)).willReturn(result);
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1");
given(invoker.getUrl()).willReturn(url);
return invoker;
}
}
| 5,937 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/ExecuteLimitFilterTest.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.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.RpcStatus;
import org.apache.dubbo.rpc.support.BlockMyInvoker;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
class ExecuteLimitFilterTest {
private ExecuteLimitFilter executeLimitFilter = new ExecuteLimitFilter();
@Test
void testNoExecuteLimitInvoke() {
Invoker invoker = Mockito.mock(Invoker.class);
when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result"));
when(invoker.getUrl()).thenReturn(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1"));
Invocation invocation = Mockito.mock(Invocation.class);
when(invocation.getMethodName()).thenReturn("testNoExecuteLimitInvoke");
Result result = executeLimitFilter.invoke(invoker, invocation);
Assertions.assertEquals("result", result.getValue());
}
@Test
void testExecuteLimitInvoke() {
Invoker invoker = Mockito.mock(Invoker.class);
when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result"));
when(invoker.getUrl())
.thenReturn(URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&executes=10"));
Invocation invocation = Mockito.mock(Invocation.class);
when(invocation.getMethodName()).thenReturn("testExecuteLimitInvoke");
Result result = executeLimitFilter.invoke(invoker, invocation);
Assertions.assertEquals("result", result.getValue());
}
@Test
void testExecuteLimitInvokeWithException() {
Invoker invoker = Mockito.mock(Invoker.class);
doThrow(new RpcException()).when(invoker).invoke(any(Invocation.class));
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&executes=10");
when(invoker.getUrl()).thenReturn(url);
Invocation invocation = Mockito.mock(Invocation.class);
when(invocation.getMethodName()).thenReturn("testExecuteLimitInvokeWitException");
try {
executeLimitFilter.invoke(invoker, invocation);
} catch (Exception e) {
Assertions.assertTrue(e instanceof RpcException);
executeLimitFilter.onError(e, invoker, invocation);
}
Assertions.assertEquals(
1, RpcStatus.getStatus(url, invocation.getMethodName()).getFailed());
RpcStatus.removeStatus(url, invocation.getMethodName());
}
@Test
void testMoreThanExecuteLimitInvoke() {
int maxExecute = 10;
int totalExecute = 20;
final AtomicInteger failed = new AtomicInteger(0);
final Invocation invocation = Mockito.mock(RpcInvocation.class);
when(invocation.getMethodName()).thenReturn("testMoreThanExecuteLimitInvoke");
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&executes=" + maxExecute);
final Invoker<ExecuteLimitFilter> invoker = new BlockMyInvoker<>(url, 1000);
final CountDownLatch latchThatWaitsAllThreadStarted = new CountDownLatch(1);
final CountDownLatch latchThatWaitsAllThreadFinished = new CountDownLatch(totalExecute);
for (int i = 0; i < totalExecute; i++) {
Thread thread = new Thread(() -> {
try {
latchThatWaitsAllThreadStarted.await();
executeLimitFilter.invoke(invoker, invocation);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (RpcException expected) {
failed.incrementAndGet();
} finally {
latchThatWaitsAllThreadFinished.countDown();
}
});
thread.start();
}
latchThatWaitsAllThreadStarted.countDown();
try {
latchThatWaitsAllThreadFinished.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
Assertions.assertEquals(totalExecute - maxExecute, failed.get());
}
}
| 5,938 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/DeprecatedFilterTest.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.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.LogUtil;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.support.DemoService;
import org.apache.dubbo.rpc.support.MockInvocation;
import org.apache.dubbo.rpc.support.MyInvoker;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* DeprecatedFilterTest.java
*/
class DeprecatedFilterTest {
Filter deprecatedFilter = new DeprecatedFilter();
@Test
void testDeprecatedFilter() {
URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&echo." + DEPRECATED_KEY + "=true");
LogUtil.start();
deprecatedFilter.invoke(new MyInvoker<DemoService>(url), new MockInvocation());
assertEquals(
1,
LogUtil.findMessage(
"The service method org.apache.dubbo.rpc.support.DemoService.echo(String) is DEPRECATED"));
LogUtil.stop();
}
}
| 5,939 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/TimeoutFilterTest.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.rpc.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.support.BlockMyInvoker;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.when;
class TimeoutFilterTest {
private TimeoutFilter timeoutFilter = new TimeoutFilter();
@Test
void testInvokeWithoutTimeout() {
int timeout = 3000;
Invoker invoker = Mockito.mock(Invoker.class);
when(invoker.invoke(any(Invocation.class))).thenReturn(new AppResponse("result"));
when(invoker.getUrl())
.thenReturn(
URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&timeout=" + timeout));
Invocation invocation = Mockito.mock(Invocation.class);
when(invocation.getMethodName()).thenReturn("testInvokeWithoutTimeout");
Result result = timeoutFilter.invoke(invoker, invocation);
Assertions.assertEquals("result", result.getValue());
}
@Test
void testInvokeWithTimeout() {
int timeout = 100;
URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1&timeout=" + timeout);
Invoker invoker = new BlockMyInvoker(url, (timeout + 100));
Invocation invocation = Mockito.mock(RpcInvocation.class);
when(invocation.getMethodName()).thenReturn("testInvokeWithTimeout");
Result result = timeoutFilter.invoke(invoker, invocation);
Assertions.assertEquals("Dubbo", result.getValue());
}
}
| 5,940 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/StatItemTest.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.rpc.filter.tps;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class StatItemTest {
private StatItem statItem;
@AfterEach
public void tearDown() throws Exception {
statItem = null;
}
@Test
void testIsAllowable() throws Exception {
statItem = new StatItem("test", 5, 1000L);
long lastResetTime = statItem.getLastResetTime();
assertTrue(statItem.isAllowable());
Thread.sleep(1100L);
assertTrue(statItem.isAllowable());
assertTrue(lastResetTime != statItem.getLastResetTime());
assertEquals(4, statItem.getToken());
}
@Test
void testAccuracy() throws Exception {
final int EXPECTED_RATE = 5;
statItem = new StatItem("test", EXPECTED_RATE, 60_000L);
for (int i = 1; i <= EXPECTED_RATE; i++) {
assertTrue(statItem.isAllowable());
}
// Must block the 6th item
assertFalse(statItem.isAllowable());
}
@Test
void testConcurrency() throws Exception {
statItem = new StatItem("test", 100, 100000);
List<Task> taskList = new ArrayList<>();
int threadNum = 50;
CountDownLatch stopLatch = new CountDownLatch(threadNum);
CountDownLatch startLatch = new CountDownLatch(1);
for (int i = 0; i < threadNum; i++) {
taskList.add(new Task(statItem, startLatch, stopLatch));
}
startLatch.countDown();
stopLatch.await();
Assertions.assertEquals(
taskList.stream().map(Task::getCount).reduce(Integer::sum).get(), 100);
}
static class Task implements Runnable {
private final StatItem statItem;
private final CountDownLatch startLatch;
private final CountDownLatch stopLatch;
private int count;
public Task(StatItem statItem, CountDownLatch startLatch, CountDownLatch stopLatch) {
this.statItem = statItem;
this.startLatch = startLatch;
this.stopLatch = stopLatch;
new Thread(this).start();
}
@Override
public void run() {
try {
startLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 10000; j++) {
count = statItem.isAllowable() ? count + 1 : count;
}
stopLatch.countDown();
}
public int getCount() {
return count;
}
}
}
| 5,941 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/DefaultTPSLimiterTest.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.rpc.filter.tps;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.support.MockInvocation;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_INTERVAL_KEY;
import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_RATE_KEY;
class DefaultTPSLimiterTest {
private static final int TEST_LIMIT_RATE = 2;
private final DefaultTPSLimiter defaultTPSLimiter = new DefaultTPSLimiter();
@Test
void testIsAllowable() {
Invocation invocation = new MockInvocation();
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, TEST_LIMIT_RATE);
url = url.addParameter(TPS_LIMIT_INTERVAL_KEY, 1000);
for (int i = 1; i <= TEST_LIMIT_RATE; i++) {
Assertions.assertTrue(defaultTPSLimiter.isAllowable(url, invocation));
}
}
@Test
void testIsNotAllowable() {
Invocation invocation = new MockInvocation();
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, TEST_LIMIT_RATE);
url = url.addParameter(TPS_LIMIT_INTERVAL_KEY, 1000);
for (int i = 1; i <= TEST_LIMIT_RATE + 1; i++) {
if (i == TEST_LIMIT_RATE + 1) {
Assertions.assertFalse(defaultTPSLimiter.isAllowable(url, invocation));
} else {
Assertions.assertTrue(defaultTPSLimiter.isAllowable(url, invocation));
}
}
}
@Test
void testTPSLimiterForMethodLevelConfig() {
Invocation invocation = new MockInvocation();
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, TEST_LIMIT_RATE);
int tpsConfigForMethodLevel = 3;
url = url.addParameter("echo.tps", tpsConfigForMethodLevel);
url = url.addParameter(TPS_LIMIT_INTERVAL_KEY, 1000);
for (int i = 1; i <= tpsConfigForMethodLevel + 1; i++) {
if (i == tpsConfigForMethodLevel + 1) {
Assertions.assertFalse(defaultTPSLimiter.isAllowable(url, invocation));
} else {
Assertions.assertTrue(defaultTPSLimiter.isAllowable(url, invocation));
}
}
}
@Test
void testConfigChange() {
Invocation invocation = new MockInvocation();
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, TEST_LIMIT_RATE);
url = url.addParameter(TPS_LIMIT_INTERVAL_KEY, 1000);
for (int i = 1; i <= TEST_LIMIT_RATE; i++) {
Assertions.assertTrue(defaultTPSLimiter.isAllowable(url, invocation));
}
final int tenTimesLimitRate = TEST_LIMIT_RATE * 10;
url = url.addParameter(TPS_LIMIT_RATE_KEY, tenTimesLimitRate);
for (int i = 1; i <= tenTimesLimitRate; i++) {
Assertions.assertTrue(defaultTPSLimiter.isAllowable(url, invocation));
}
Assertions.assertFalse(defaultTPSLimiter.isAllowable(url, invocation));
}
@Test
void testMultiThread() throws InterruptedException {
Invocation invocation = new MockInvocation();
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, 100);
url = url.addParameter(TPS_LIMIT_INTERVAL_KEY, 100000);
List<Task> taskList = new ArrayList<>();
int threadNum = 50;
CountDownLatch stopLatch = new CountDownLatch(threadNum);
CountDownLatch startLatch = new CountDownLatch(1);
for (int i = 0; i < threadNum; i++) {
taskList.add(new Task(defaultTPSLimiter, url, invocation, startLatch, stopLatch));
}
startLatch.countDown();
stopLatch.await();
Assertions.assertEquals(
taskList.stream().map(Task::getCount).reduce(Integer::sum).get(), 100);
}
static class Task implements Runnable {
private final DefaultTPSLimiter defaultTPSLimiter;
private final URL url;
private final Invocation invocation;
private final CountDownLatch startLatch;
private final CountDownLatch stopLatch;
private int count;
public Task(
DefaultTPSLimiter defaultTPSLimiter,
URL url,
Invocation invocation,
CountDownLatch startLatch,
CountDownLatch stopLatch) {
this.defaultTPSLimiter = defaultTPSLimiter;
this.url = url;
this.invocation = invocation;
this.startLatch = startLatch;
this.stopLatch = stopLatch;
new Thread(this).start();
}
@Override
public void run() {
try {
startLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 10000; j++) {
count = defaultTPSLimiter.isAllowable(url, invocation) ? count + 1 : count;
}
stopLatch.countDown();
}
public int getCount() {
return count;
}
}
}
| 5,942 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/tps/TpsLimitFilterTest.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.rpc.filter.tps;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.filter.TpsLimitFilter;
import org.apache.dubbo.rpc.support.MockInvocation;
import org.apache.dubbo.rpc.support.MyInvoker;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.rpc.Constants.TPS_LIMIT_RATE_KEY;
import static org.junit.jupiter.api.Assertions.assertTrue;
class TpsLimitFilterTest {
private TpsLimitFilter filter = new TpsLimitFilter();
@Test
void testWithoutCount() throws Exception {
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, 5);
Invoker<TpsLimitFilterTest> invoker = new MyInvoker<TpsLimitFilterTest>(url);
Invocation invocation = new MockInvocation();
filter.invoke(invoker, invocation);
}
@Test
void testFail() throws Exception {
Assertions.assertThrows(RpcException.class, () -> {
URL url = URL.valueOf("test://test");
url = url.addParameter(INTERFACE_KEY, "org.apache.dubbo.rpc.file.TpsService");
url = url.addParameter(TPS_LIMIT_RATE_KEY, 5);
Invoker<TpsLimitFilterTest> invoker = new MyInvoker<TpsLimitFilterTest>(url);
Invocation invocation = new MockInvocation();
for (int i = 0; i < 10; i++) {
Result re = filter.invoke(invoker, invocation);
if (i >= 5) {
assertTrue(re.hasException());
throw re.getException();
}
}
});
}
}
| 5,943 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvocationProfilerUtils.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.rpc;
import org.apache.dubbo.common.profiler.Profiler;
import org.apache.dubbo.common.profiler.ProfilerEntry;
import org.apache.dubbo.common.profiler.ProfilerSwitch;
import java.util.concurrent.Callable;
public class InvocationProfilerUtils {
public static void enterSimpleProfiler(Invocation invocation, Callable<String> messageCallable) {
if (ProfilerSwitch.isEnableSimpleProfiler()) {
enterProfiler(invocation, messageCallable);
}
}
public static void releaseSimpleProfiler(Invocation invocation) {
if (ProfilerSwitch.isEnableSimpleProfiler()) {
releaseProfiler(invocation);
}
}
public static void enterDetailProfiler(Invocation invocation, Callable<String> messageCallable) {
if (ProfilerSwitch.isEnableDetailProfiler()) {
enterProfiler(invocation, messageCallable);
}
}
public static void releaseDetailProfiler(Invocation invocation) {
if (ProfilerSwitch.isEnableDetailProfiler()) {
releaseProfiler(invocation);
}
}
public static void enterProfiler(Invocation invocation, String message) {
Object fromInvocation = invocation.get(Profiler.PROFILER_KEY);
if (fromInvocation instanceof ProfilerEntry) {
invocation.put(Profiler.PROFILER_KEY, Profiler.enter((ProfilerEntry) fromInvocation, message));
}
}
public static void enterProfiler(Invocation invocation, Callable<String> messageCallable) {
Object fromInvocation = invocation.get(Profiler.PROFILER_KEY);
if (fromInvocation instanceof ProfilerEntry) {
String message = "";
try {
message = messageCallable.call();
} catch (Exception ignore) {
}
invocation.put(Profiler.PROFILER_KEY, Profiler.enter((ProfilerEntry) fromInvocation, message));
}
}
public static void releaseProfiler(Invocation invocation) {
Object fromInvocation = invocation.get(Profiler.PROFILER_KEY);
if (fromInvocation instanceof ProfilerEntry) {
invocation.put(Profiler.PROFILER_KEY, Profiler.release((ProfilerEntry) fromInvocation));
}
}
}
| 5,944 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/CancellationListener.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.rpc;
/**
* A listener notified on context cancellation.
*/
public interface CancellationListener {
/**
* Notifies that a context was cancelled.
*
* @param context the newly cancelled context.
*/
void cancelled(RpcServiceContext context);
}
| 5,945 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncContextImpl.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.rpc;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
public class AsyncContextImpl implements AsyncContext {
private final AtomicBoolean started = new AtomicBoolean(false);
private final AtomicBoolean stopped = new AtomicBoolean(false);
private CompletableFuture<Object> future;
private final RpcContext.RestoreContext restoreContext;
private final ClassLoader restoreClassLoader;
private ClassLoader stagedClassLoader;
public AsyncContextImpl() {
restoreContext = RpcContext.storeContext();
restoreClassLoader = Thread.currentThread().getContextClassLoader();
}
@Override
public void write(Object value) {
if (isAsyncStarted() && stop()) {
if (value instanceof Throwable) {
Throwable bizExe = (Throwable) value;
future.completeExceptionally(bizExe);
} else {
future.complete(value);
}
} else {
throw new IllegalStateException(
"The async response has probably been wrote back by another thread, or the asyncContext has been closed.");
}
}
@Override
public boolean isAsyncStarted() {
return started.get();
}
@Override
public boolean stop() {
return stopped.compareAndSet(false, true);
}
@Override
public void start() {
if (this.started.compareAndSet(false, true)) {
this.future = new CompletableFuture<>();
}
}
@Override
public void signalContextSwitch() {
RpcContext.restoreContext(restoreContext);
if (restoreClassLoader != null) {
stagedClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(restoreClassLoader);
}
}
@Override
public void resetContext() {
RpcContext.removeContext();
if (stagedClassLoader != null) {
Thread.currentThread().setContextClassLoader(restoreClassLoader);
}
}
public CompletableFuture<Object> getInternalFuture() {
return future;
}
}
| 5,946 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncRpcResult.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.rpc;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.ThreadlessExecutor;
import org.apache.dubbo.rpc.model.ConsumerMethodModel;
import org.apache.dubbo.rpc.protocol.dubbo.FutureAdapter;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiConsumer;
import java.util.function.Function;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_ASYNC_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_ERROR_ASYNC_RESPONSE;
import static org.apache.dubbo.common.utils.ReflectUtils.defaultReturn;
/**
* This class represents an unfinished RPC call, it will hold some context information for this call, for example RpcContext and Invocation,
* so that when the call finishes and the result returns, it can guarantee all the contexts being recovered as the same as when the call was made
* before any callback is invoked.
* <p>
* TODO if it's reasonable or even right to keep a reference to Invocation?
* <p>
* As {@link Result} implements CompletionStage, {@link AsyncRpcResult} allows you to easily build a async filter chain whose status will be
* driven entirely by the state of the underlying RPC call.
* <p>
* AsyncRpcResult does not contain any concrete value (except the underlying value bring by CompletableFuture), consider it as a status transfer node.
* {@link #getValue()} and {@link #getException()} are all inherited from {@link Result} interface, implementing them are mainly
* for compatibility consideration. Because many legacy {@link Filter} implementation are most possibly to call getValue directly.
*/
public class AsyncRpcResult implements Result {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AsyncRpcResult.class);
/**
* RpcContext may already have been changed when callback happens, it happens when the same thread is used to execute another RPC call.
* So we should keep the copy of current RpcContext instance and restore it before callback being executed.
*/
private RpcContext.RestoreContext storedContext;
private Executor executor;
private final Invocation invocation;
private final boolean async;
private CompletableFuture<AppResponse> responseFuture;
/**
* Whether set future to Thread Local when invocation mode is sync
*/
private static final boolean setFutureWhenSync =
Boolean.parseBoolean(System.getProperty(CommonConstants.SET_FUTURE_IN_SYNC_MODE, "true"));
public AsyncRpcResult(CompletableFuture<AppResponse> future, Invocation invocation) {
this.responseFuture = future;
this.invocation = invocation;
RpcInvocation rpcInvocation = (RpcInvocation) invocation;
if ((rpcInvocation.get(PROVIDER_ASYNC_KEY) != null || InvokeMode.SYNC != rpcInvocation.getInvokeMode())
&& !future.isDone()) {
async = true;
this.storedContext = RpcContext.clearAndStoreContext();
} else {
async = false;
}
}
/**
* Notice the return type of {@link #getValue} is the actual type of the RPC method, not {@link AppResponse}
*
* @return
*/
@Override
public Object getValue() {
return getAppResponse().getValue();
}
/**
* CompletableFuture can only be completed once, so try to update the result of one completed CompletableFuture will
* have no effect. To avoid this problem, we check the complete status of this future before update its value.
* <p>
* But notice that trying to give an uncompleted CompletableFuture a new specified value may face a race condition,
* because the background thread watching the real result will also change the status of this CompletableFuture.
* The result is you may lose the value you expected to set.
*
* @param value
*/
@Override
public void setValue(Object value) {
try {
if (responseFuture.isDone()) {
responseFuture.get().setValue(value);
} else {
AppResponse appResponse = new AppResponse(invocation);
appResponse.setValue(value);
responseFuture.complete(appResponse);
}
} catch (Exception e) {
// This should not happen in normal request process;
logger.error(
PROXY_ERROR_ASYNC_RESPONSE,
"",
"",
"Got exception when trying to fetch the underlying result from AsyncRpcResult.");
throw new RpcException(e);
}
}
@Override
public Throwable getException() {
return getAppResponse().getException();
}
@Override
public void setException(Throwable t) {
try {
if (responseFuture.isDone()) {
responseFuture.get().setException(t);
} else {
AppResponse appResponse = new AppResponse(invocation);
appResponse.setException(t);
responseFuture.complete(appResponse);
}
} catch (Exception e) {
// This should not happen in normal request process;
logger.error(
PROXY_ERROR_ASYNC_RESPONSE,
"",
"",
"Got exception when trying to fetch the underlying result from AsyncRpcResult.");
throw new RpcException(e);
}
}
@Override
public boolean hasException() {
return getAppResponse().hasException();
}
public CompletableFuture<AppResponse> getResponseFuture() {
return responseFuture;
}
public void setResponseFuture(CompletableFuture<AppResponse> responseFuture) {
this.responseFuture = responseFuture;
}
public Result getAppResponse() {
try {
if (responseFuture.isDone()) {
return responseFuture.get();
}
} catch (Exception e) {
// This should not happen in normal request process;
logger.error(
PROXY_ERROR_ASYNC_RESPONSE,
"",
"",
"Got exception when trying to fetch the underlying result from AsyncRpcResult.");
throw new RpcException(e);
}
return createDefaultValue(invocation);
}
/**
* This method will always return after a maximum 'timeout' waiting:
* 1. if value returns before timeout, return normally.
* 2. if no value returns after timeout, throw TimeoutException.
*
* @return
* @throws InterruptedException
* @throws ExecutionException
*/
@Override
public Result get() throws InterruptedException, ExecutionException {
if (executor instanceof ThreadlessExecutor) {
ThreadlessExecutor threadlessExecutor = (ThreadlessExecutor) executor;
try {
while (!responseFuture.isDone() && !threadlessExecutor.isShutdown()) {
threadlessExecutor.waitAndDrain(Long.MAX_VALUE);
}
} finally {
threadlessExecutor.shutdown();
}
}
return responseFuture.get();
}
@Override
public Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
long deadline = System.nanoTime() + unit.toNanos(timeout);
if (executor instanceof ThreadlessExecutor) {
ThreadlessExecutor threadlessExecutor = (ThreadlessExecutor) executor;
try {
while (!responseFuture.isDone() && !threadlessExecutor.isShutdown()) {
long restTime = deadline - System.nanoTime();
if (restTime > 0) {
threadlessExecutor.waitAndDrain(deadline);
} else {
throw new TimeoutException(
"Timeout after " + unit.toMillis(timeout) + "ms waiting for result.");
}
}
} finally {
threadlessExecutor.shutdown();
}
}
long restTime = deadline - System.nanoTime();
if (!responseFuture.isDone() && restTime < 0) {
throw new TimeoutException("Timeout after " + unit.toMillis(timeout) + "ms waiting for result.");
}
return responseFuture.get(restTime, TimeUnit.NANOSECONDS);
}
@Override
public Object recreate() throws Throwable {
RpcInvocation rpcInvocation = (RpcInvocation) invocation;
if (InvokeMode.FUTURE == rpcInvocation.getInvokeMode()) {
return RpcContext.getClientAttachment().getFuture();
} else if (InvokeMode.ASYNC == rpcInvocation.getInvokeMode()) {
return createDefaultValue(invocation).recreate();
}
return getAppResponse().recreate();
}
public Result whenCompleteWithContext(BiConsumer<Result, Throwable> fn) {
this.responseFuture = this.responseFuture.whenComplete((v, t) -> {
if (async) {
RpcContext.restoreContext(storedContext);
}
fn.accept(v, t);
});
if (setFutureWhenSync || ((RpcInvocation) invocation).getInvokeMode() != InvokeMode.SYNC) {
// Necessary! update future in context, see https://github.com/apache/dubbo/issues/9461
RpcContext.getServiceContext().setFuture(new FutureAdapter<>(this.responseFuture));
}
return this;
}
@Override
public <U> CompletableFuture<U> thenApply(Function<Result, ? extends U> fn) {
return this.responseFuture.thenApply(fn);
}
@Override
@Deprecated
public Map<String, String> getAttachments() {
return getAppResponse().getAttachments();
}
@Override
public Map<String, Object> getObjectAttachments() {
return getAppResponse().getObjectAttachments();
}
@Override
public void setAttachments(Map<String, String> map) {
getAppResponse().setAttachments(map);
}
@Override
public void setObjectAttachments(Map<String, Object> map) {
getAppResponse().setObjectAttachments(map);
}
@Deprecated
@Override
public void addAttachments(Map<String, String> map) {
getAppResponse().addAttachments(map);
}
@Override
public void addObjectAttachments(Map<String, Object> map) {
getAppResponse().addObjectAttachments(map);
}
@Override
public String getAttachment(String key) {
return getAppResponse().getAttachment(key);
}
@Override
public Object getObjectAttachment(String key) {
return getAppResponse().getObjectAttachment(key);
}
@Override
public String getAttachment(String key, String defaultValue) {
return getAppResponse().getAttachment(key, defaultValue);
}
@Override
public Object getObjectAttachment(String key, Object defaultValue) {
return getAppResponse().getObjectAttachment(key, defaultValue);
}
@Override
public void setAttachment(String key, String value) {
setObjectAttachment(key, value);
}
@Override
public void setAttachment(String key, Object value) {
setObjectAttachment(key, value);
}
@Override
public void setObjectAttachment(String key, Object value) {
getAppResponse().setAttachment(key, value);
}
public Executor getExecutor() {
return executor;
}
public void setExecutor(Executor executor) {
this.executor = executor;
}
/**
* Some utility methods used to quickly generate default AsyncRpcResult instance.
*/
public static AsyncRpcResult newDefaultAsyncResult(AppResponse appResponse, Invocation invocation) {
return new AsyncRpcResult(CompletableFuture.completedFuture(appResponse), invocation);
}
public static AsyncRpcResult newDefaultAsyncResult(Invocation invocation) {
return newDefaultAsyncResult(null, null, invocation);
}
public static AsyncRpcResult newDefaultAsyncResult(Object value, Invocation invocation) {
return newDefaultAsyncResult(value, null, invocation);
}
public static AsyncRpcResult newDefaultAsyncResult(Throwable t, Invocation invocation) {
return newDefaultAsyncResult(null, t, invocation);
}
public static AsyncRpcResult newDefaultAsyncResult(Object value, Throwable t, Invocation invocation) {
CompletableFuture<AppResponse> future = new CompletableFuture<>();
AppResponse result = new AppResponse(invocation);
if (t != null) {
result.setException(t);
} else {
result.setValue(value);
}
future.complete(result);
return new AsyncRpcResult(future, invocation);
}
private static Result createDefaultValue(Invocation invocation) {
ConsumerMethodModel method = (ConsumerMethodModel) invocation.get(Constants.METHOD_MODEL);
return method != null ? new AppResponse(defaultReturn(method.getReturnClass())) : new AppResponse();
}
}
| 5,947 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProxyFactory.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.rpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
import static org.apache.dubbo.common.extension.ExtensionScope.FRAMEWORK;
import static org.apache.dubbo.rpc.Constants.PROXY_KEY;
/**
* ProxyFactory. (API/SPI, Singleton, ThreadSafe)
*/
@SPI(value = "javassist", scope = FRAMEWORK)
public interface ProxyFactory {
/**
* create proxy.
*
* @param invoker
* @return proxy
*/
@Adaptive({PROXY_KEY})
<T> T getProxy(Invoker<T> invoker) throws RpcException;
/**
* create proxy.
*
* @param invoker
* @return proxy
*/
@Adaptive({PROXY_KEY})
<T> T getProxy(Invoker<T> invoker, boolean generic) throws RpcException;
/**
* create invoker.
*
* @param <T>
* @param proxy
* @param type
* @param url
* @return invoker
*/
@Adaptive({PROXY_KEY})
<T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) throws RpcException;
}
| 5,948 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContext.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.rpc;
import org.apache.dubbo.common.Experimental;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadlocal.InternalThreadLocal;
import org.apache.dubbo.common.utils.StringUtils;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
/**
* Thread local context. (API, ThreadLocal, ThreadSafe)
* <p>
* Note: RpcContext is a temporary state holder. States in RpcContext changes every time when request is sent or received.
* <p/>
* There are four kinds of RpcContext, which are ServerContext, ClientAttachment, ServerAttachment and ServiceContext.
* <p/>
* ServiceContext: Using to pass environment parameters in the whole invocation. For example, `remotingApplicationName`,
* `remoteAddress`, etc. {@link RpcServiceContext}
* ClientAttachment, ServerAttachment and ServiceContext are using to transfer attachments.
* Imaging a situation like this, A is calling B, and B will call C, after that, B wants to return some attachments back to A.
* ClientAttachment is using to pass attachments to next hop as a consumer. ( A --> B , in A side)
* ServerAttachment is using to fetch attachments from previous hop as a provider. ( A --> B , in B side)
* ServerContext is using to return some attachments back to client as a provider. ( A <-- B , in B side)
* The reason why using `ServiceContext` is to make API compatible with previous.
*
* @export
* @see org.apache.dubbo.rpc.filter.ContextFilter
*/
public class RpcContext {
private static final RpcContext AGENT = new RpcContext();
/**
* use internal thread local to improve performance
*/
private static final InternalThreadLocal<RpcContextAttachment> CLIENT_RESPONSE_LOCAL =
new InternalThreadLocal<RpcContextAttachment>() {
@Override
protected RpcContextAttachment initialValue() {
return new RpcContextAttachment();
}
};
private static final InternalThreadLocal<RpcContextAttachment> SERVER_RESPONSE_LOCAL =
new InternalThreadLocal<RpcContextAttachment>() {
@Override
protected RpcContextAttachment initialValue() {
return new RpcContextAttachment();
}
};
private static final InternalThreadLocal<RpcContextAttachment> CLIENT_ATTACHMENT =
new InternalThreadLocal<RpcContextAttachment>() {
@Override
protected RpcContextAttachment initialValue() {
return new RpcContextAttachment();
}
};
private static final InternalThreadLocal<RpcContextAttachment> SERVER_ATTACHMENT =
new InternalThreadLocal<RpcContextAttachment>() {
@Override
protected RpcContextAttachment initialValue() {
return new RpcContextAttachment();
}
};
private static final InternalThreadLocal<RpcServiceContext> SERVICE_CONTEXT =
new InternalThreadLocal<RpcServiceContext>() {
@Override
protected RpcServiceContext initialValue() {
return new RpcServiceContext();
}
};
/**
* use by cancel call
*/
private static final InternalThreadLocal<CancellationContext> CANCELLATION_CONTEXT =
new InternalThreadLocal<CancellationContext>() {
@Override
protected CancellationContext initialValue() {
return new CancellationContext();
}
};
public static CancellationContext getCancellationContext() {
return CANCELLATION_CONTEXT.get();
}
public static void removeCancellationContext() {
CANCELLATION_CONTEXT.remove();
}
public static void restoreCancellationContext(CancellationContext oldContext) {
CANCELLATION_CONTEXT.set(oldContext);
}
private boolean remove = true;
protected RpcContext() {}
/**
* get server side context. ( A <-- B , in B side)
*
* @return server context
*/
public static RpcContextAttachment getServerContext() {
return new RpcServerContextAttachment();
}
/**
* remove server side context.
*
* @see org.apache.dubbo.rpc.filter.ContextFilter
*/
public static RpcContextAttachment getClientResponseContext() {
return CLIENT_RESPONSE_LOCAL.get();
}
public static RpcContextAttachment getServerResponseContext() {
return SERVER_RESPONSE_LOCAL.get();
}
public static void removeClientResponseContext() {
CLIENT_RESPONSE_LOCAL.remove();
}
public static void removeServerResponseContext() {
SERVER_RESPONSE_LOCAL.remove();
}
/**
* get context.
*
* @return context
*/
@Deprecated
public static RpcContext getContext() {
return AGENT;
}
/**
* get consumer side attachment ( A --> B , in A side)
*
* @return context
*/
public static RpcContextAttachment getClientAttachment() {
return CLIENT_ATTACHMENT.get();
}
/**
* get provider side attachment from consumer ( A --> B , in B side)
*
* @return context
*/
public static RpcContextAttachment getServerAttachment() {
return SERVER_ATTACHMENT.get();
}
public static void removeServerContext() {
RpcContextAttachment rpcContextAttachment = RpcContext.getServerContext();
for (String key : rpcContextAttachment.attachments.keySet()) {
rpcContextAttachment.remove(key);
}
}
public boolean canRemove() {
return remove;
}
public void clearAfterEachInvoke(boolean remove) {
this.remove = remove;
}
/**
* Using to pass environment parameters in the whole invocation. For example, `remotingApplicationName`,
* `remoteAddress`, etc. {@link RpcServiceContext}
*
* @return context
*/
public static RpcServiceContext getServiceContext() {
return SERVICE_CONTEXT.get();
}
public static RpcServiceContext getCurrentServiceContext() {
return SERVICE_CONTEXT.getWithoutInitialize();
}
public static void removeServiceContext() {
SERVICE_CONTEXT.remove();
}
public static void removeClientAttachment() {
if (CLIENT_ATTACHMENT.get().canRemove()) {
CLIENT_ATTACHMENT.remove();
}
}
public static void removeServerAttachment() {
if (SERVER_ATTACHMENT.get().canRemove()) {
SERVER_ATTACHMENT.remove();
}
}
/**
* customized for internal use.
*/
public static void removeContext() {
if (CLIENT_ATTACHMENT.get().canRemove()) {
CLIENT_ATTACHMENT.remove();
}
if (SERVER_ATTACHMENT.get().canRemove()) {
SERVER_ATTACHMENT.remove();
}
CLIENT_RESPONSE_LOCAL.remove();
SERVER_RESPONSE_LOCAL.remove();
SERVICE_CONTEXT.remove();
CANCELLATION_CONTEXT.remove();
}
/**
* Get the request object of the underlying RPC protocol, e.g. HttpServletRequest
*
* @return null if the underlying protocol doesn't provide support for getting request
*/
public Object getRequest() {
return SERVICE_CONTEXT.get().getRequest();
}
public void setRequest(Object request) {
SERVICE_CONTEXT.get().setRequest(request);
}
/**
* Get the request object of the underlying RPC protocol, e.g. HttpServletRequest
*
* @return null if the underlying protocol doesn't provide support for getting request or the request is not of the specified type
*/
@SuppressWarnings("unchecked")
public <T> T getRequest(Class<T> clazz) {
return SERVICE_CONTEXT.get().getRequest(clazz);
}
/**
* Get the response object of the underlying RPC protocol, e.g. HttpServletResponse
*
* @return null if the underlying protocol doesn't provide support for getting response
*/
public Object getResponse() {
return SERVICE_CONTEXT.get().getResponse();
}
public void setResponse(Object response) {
SERVICE_CONTEXT.get().setResponse(response);
}
/**
* Get the response object of the underlying RPC protocol, e.g. HttpServletResponse
*
* @return null if the underlying protocol doesn't provide support for getting response or the response is not of the specified type
*/
@SuppressWarnings("unchecked")
public <T> T getResponse(Class<T> clazz) {
return SERVICE_CONTEXT.get().getResponse(clazz);
}
/**
* is provider side.
*
* @return provider side.
*/
public boolean isProviderSide() {
return SERVICE_CONTEXT.get().isProviderSide();
}
/**
* is consumer side.
*
* @return consumer side.
*/
public boolean isConsumerSide() {
return SERVICE_CONTEXT.get().isConsumerSide();
}
/**
* get CompletableFuture.
*
* @param <T>
* @return future
*/
@SuppressWarnings("unchecked")
public <T> CompletableFuture<T> getCompletableFuture() {
return SERVICE_CONTEXT.get().getCompletableFuture();
}
/**
* get future.
*
* @param <T>
* @return future
*/
@SuppressWarnings("unchecked")
public <T> Future<T> getFuture() {
return SERVICE_CONTEXT.get().getFuture();
}
/**
* set future.
*
* @param future
*/
public void setFuture(CompletableFuture<?> future) {
SERVICE_CONTEXT.get().setFuture(future);
}
public List<URL> getUrls() {
return SERVICE_CONTEXT.get().getUrls();
}
public void setUrls(List<URL> urls) {
SERVICE_CONTEXT.get().setUrls(urls);
}
public URL getUrl() {
return SERVICE_CONTEXT.get().getUrl();
}
public void setUrl(URL url) {
SERVICE_CONTEXT.get().setUrl(url);
}
/**
* get method name.
*
* @return method name.
*/
public String getMethodName() {
return SERVICE_CONTEXT.get().getMethodName();
}
public void setMethodName(String methodName) {
SERVICE_CONTEXT.get().setMethodName(methodName);
}
/**
* get parameter types.
*
* @serial
*/
public Class<?>[] getParameterTypes() {
return SERVICE_CONTEXT.get().getParameterTypes();
}
public void setParameterTypes(Class<?>[] parameterTypes) {
SERVICE_CONTEXT.get().setParameterTypes(parameterTypes);
}
/**
* get arguments.
*
* @return arguments.
*/
public Object[] getArguments() {
return SERVICE_CONTEXT.get().getArguments();
}
public void setArguments(Object[] arguments) {
SERVICE_CONTEXT.get().setArguments(arguments);
}
/**
* set local address.
*
* @param host
* @param port
* @return context
*/
public RpcContext setLocalAddress(String host, int port) {
return SERVICE_CONTEXT.get().setLocalAddress(host, port);
}
/**
* get local address.
*
* @return local address
*/
public InetSocketAddress getLocalAddress() {
return SERVICE_CONTEXT.get().getLocalAddress();
}
/**
* set local address.
*
* @param address
* @return context
*/
public RpcContext setLocalAddress(InetSocketAddress address) {
return SERVICE_CONTEXT.get().setLocalAddress(address);
}
public String getLocalAddressString() {
return SERVICE_CONTEXT.get().getLocalAddressString();
}
/**
* get local host name.
*
* @return local host name
*/
public String getLocalHostName() {
return SERVICE_CONTEXT.get().getLocalHostName();
}
/**
* set remote address.
*
* @param host
* @param port
* @return context
*/
public RpcContext setRemoteAddress(String host, int port) {
return SERVICE_CONTEXT.get().setRemoteAddress(host, port);
}
/**
* get remote address.
*
* @return remote address
*/
public InetSocketAddress getRemoteAddress() {
return SERVICE_CONTEXT.get().getRemoteAddress();
}
/**
* set remote address.
*
* @param address
* @return context
*/
public RpcContext setRemoteAddress(InetSocketAddress address) {
return SERVICE_CONTEXT.get().setRemoteAddress(address);
}
public String getRemoteApplicationName() {
return SERVICE_CONTEXT.get().getRemoteApplicationName();
}
public RpcContext setRemoteApplicationName(String remoteApplicationName) {
return SERVICE_CONTEXT.get().setRemoteApplicationName(remoteApplicationName);
}
/**
* get remote address string.
*
* @return remote address string.
*/
public String getRemoteAddressString() {
return SERVICE_CONTEXT.get().getRemoteAddressString();
}
/**
* get remote host name.
*
* @return remote host name
*/
public String getRemoteHostName() {
return SERVICE_CONTEXT.get().getRemoteHostName();
}
/**
* get local host.
*
* @return local host
*/
public String getLocalHost() {
return SERVICE_CONTEXT.get().getLocalHost();
}
/**
* get local port.
*
* @return port
*/
public int getLocalPort() {
return SERVICE_CONTEXT.get().getLocalPort();
}
/**
* get remote host.
*
* @return remote host
*/
public String getRemoteHost() {
return SERVICE_CONTEXT.get().getRemoteHost();
}
/**
* get remote port.
*
* @return remote port
*/
public int getRemotePort() {
return SERVICE_CONTEXT.get().getRemotePort();
}
/**
* also see {@link #getObjectAttachment(String)}.
*
* @param key
* @return attachment
*/
public String getAttachment(String key) {
String client = CLIENT_ATTACHMENT.get().getAttachment(key);
if (StringUtils.isEmpty(client)) {
return SERVER_ATTACHMENT.get().getAttachment(key);
}
return client;
}
/**
* get attachment.
*
* @param key
* @return attachment
*/
@Experimental("Experiment api for supporting Object transmission")
public Object getObjectAttachment(String key) {
Object client = CLIENT_ATTACHMENT.get().getObjectAttachment(key);
if (client == null) {
return SERVER_ATTACHMENT.get().getObjectAttachment(key);
}
return client;
}
/**
* set attachment.
*
* @param key
* @param value
* @return context
*/
public RpcContext setAttachment(String key, String value) {
return setObjectAttachment(key, value);
}
public RpcContext setAttachment(String key, Object value) {
return setObjectAttachment(key, value);
}
@Experimental("Experiment api for supporting Object transmission")
public RpcContext setObjectAttachment(String key, Object value) {
// TODO compatible with previous
CLIENT_ATTACHMENT.get().setObjectAttachment(key, value);
return this;
}
/**
* remove attachment.
*
* @param key
* @return context
*/
public RpcContext removeAttachment(String key) {
CLIENT_ATTACHMENT.get().removeAttachment(key);
return this;
}
/**
* get attachments.
*
* @return attachments
*/
@Deprecated
public Map<String, String> getAttachments() {
return new AttachmentsAdapter.ObjectToStringMap(this.getObjectAttachments());
}
/**
* get attachments.
*
* @return attachments
*/
@Experimental("Experiment api for supporting Object transmission")
public Map<String, Object> getObjectAttachments() {
Map<String, Object> result =
new HashMap<>((int) ((CLIENT_ATTACHMENT.get().attachments.size()
+ SERVER_ATTACHMENT.get().attachments.size())
/ .75)
+ 1);
result.putAll(SERVER_ATTACHMENT.get().attachments);
result.putAll(CLIENT_ATTACHMENT.get().attachments);
return result;
}
/**
* set attachments
*
* @param attachment
* @return context
*/
public RpcContext setAttachments(Map<String, String> attachment) {
CLIENT_ATTACHMENT.get().attachments.clear();
if (attachment != null && attachment.size() > 0) {
CLIENT_ATTACHMENT.get().attachments.putAll(attachment);
}
return this;
}
/**
* set attachments
*
* @param attachment
* @return context
*/
@Experimental("Experiment api for supporting Object transmission")
public RpcContext setObjectAttachments(Map<String, Object> attachment) {
CLIENT_ATTACHMENT.get().attachments.clear();
if (attachment != null && attachment.size() > 0) {
CLIENT_ATTACHMENT.get().attachments.putAll(attachment);
}
return this;
}
public void clearAttachments() {
CLIENT_ATTACHMENT.get().attachments.clear();
}
/**
* get values.
*
* @return values
*/
@Deprecated
public Map<String, Object> get() {
return CLIENT_ATTACHMENT.get().get();
}
/**
* set value.
*
* @param key
* @param value
* @return context
*/
@Deprecated
public RpcContext set(String key, Object value) {
CLIENT_ATTACHMENT.get().set(key, value);
return this;
}
/**
* remove value.
*
* @param key
* @return value
*/
@Deprecated
public RpcContext remove(String key) {
CLIENT_ATTACHMENT.get().remove(key);
return this;
}
/**
* get value.
*
* @param key
* @return value
*/
@Deprecated
public Object get(String key) {
return CLIENT_ATTACHMENT.get().get(key);
}
/**
* @deprecated Replace to isProviderSide()
*/
@Deprecated
public boolean isServerSide() {
return SERVICE_CONTEXT.get().isServerSide();
}
/**
* @deprecated Replace to isConsumerSide()
*/
@Deprecated
public boolean isClientSide() {
return SERVICE_CONTEXT.get().isClientSide();
}
/**
* @deprecated Replace to getUrls()
*/
@Deprecated
@SuppressWarnings({"unchecked", "rawtypes"})
public List<Invoker<?>> getInvokers() {
return SERVICE_CONTEXT.get().getInvokers();
}
public RpcContext setInvokers(List<Invoker<?>> invokers) {
return SERVICE_CONTEXT.get().setInvokers(invokers);
}
/**
* @deprecated Replace to getUrl()
*/
@Deprecated
public Invoker<?> getInvoker() {
return SERVICE_CONTEXT.get().getInvoker();
}
public RpcContext setInvoker(Invoker<?> invoker) {
return SERVICE_CONTEXT.get().setInvoker(invoker);
}
/**
* @deprecated Replace to getMethodName(), getParameterTypes(), getArguments()
*/
@Deprecated
public Invocation getInvocation() {
return SERVICE_CONTEXT.get().getInvocation();
}
public RpcContext setInvocation(Invocation invocation) {
return SERVICE_CONTEXT.get().setInvocation(invocation);
}
/**
* Async invocation. Timeout will be handled even if <code>Future.get()</code> is not called.
*
* @param callable
* @return get the return result from <code>future.get()</code>
*/
@SuppressWarnings("unchecked")
public <T> CompletableFuture<T> asyncCall(Callable<T> callable) {
return SERVICE_CONTEXT.get().asyncCall(callable);
}
/**
* one way async call, send request only, and result is not required
*
* @param runnable
*/
public void asyncCall(Runnable runnable) {
SERVICE_CONTEXT.get().asyncCall(runnable);
}
/**
* @return
* @throws IllegalStateException
*/
@SuppressWarnings("unchecked")
public static AsyncContext startAsync() throws IllegalStateException {
return RpcContextAttachment.startAsync();
}
protected void setAsyncContext(AsyncContext asyncContext) {
SERVER_ATTACHMENT.get().setAsyncContext(asyncContext);
}
public boolean isAsyncStarted() {
return SERVER_ATTACHMENT.get().isAsyncStarted();
}
public boolean stopAsync() {
return SERVER_ATTACHMENT.get().stopAsync();
}
public AsyncContext getAsyncContext() {
return SERVER_ATTACHMENT.get().getAsyncContext();
}
public String getGroup() {
return SERVICE_CONTEXT.get().getGroup();
}
public String getVersion() {
return SERVICE_CONTEXT.get().getVersion();
}
public String getInterfaceName() {
return SERVICE_CONTEXT.get().getInterfaceName();
}
public String getProtocol() {
return SERVICE_CONTEXT.get().getProtocol();
}
public String getServiceKey() {
return SERVICE_CONTEXT.get().getServiceKey();
}
public String getProtocolServiceKey() {
return SERVICE_CONTEXT.get().getProtocolServiceKey();
}
public URL getConsumerUrl() {
return SERVICE_CONTEXT.get().getConsumerUrl();
}
public void setConsumerUrl(URL consumerUrl) {
SERVICE_CONTEXT.get().setConsumerUrl(consumerUrl);
}
@Deprecated
public static void setRpcContext(URL url) {
RpcServiceContext.getServiceContext().setConsumerUrl(url);
}
protected static RestoreContext clearAndStoreContext() {
RestoreContext restoreContext = new RestoreContext();
RpcContext.removeContext();
return restoreContext;
}
protected static RestoreContext storeContext() {
return new RestoreContext();
}
public static RestoreServiceContext storeServiceContext() {
return new RestoreServiceContext();
}
public static void restoreServiceContext(RestoreServiceContext restoreServiceContext) {
if (restoreServiceContext != null) {
restoreServiceContext.restore();
}
}
protected static void restoreContext(RestoreContext restoreContext) {
if (restoreContext != null) {
restoreContext.restore();
}
}
/**
* Used to temporarily store and restore all kinds of contexts of current thread.
*/
public static class RestoreContext {
private final RpcServiceContext serviceContext;
private final RpcContextAttachment clientAttachment;
private final RpcContextAttachment serverAttachment;
private final RpcContextAttachment clientResponseLocal;
private final RpcContextAttachment serverResponseLocal;
public RestoreContext() {
serviceContext = getServiceContext().copyOf(false);
clientAttachment = getClientAttachment().copyOf(false);
serverAttachment = getServerAttachment().copyOf(false);
clientResponseLocal = getClientResponseContext().copyOf(false);
serverResponseLocal = getServerResponseContext().copyOf(false);
}
public void restore() {
if (serviceContext != null) {
SERVICE_CONTEXT.set(serviceContext);
} else {
removeServiceContext();
}
if (clientAttachment != null) {
CLIENT_ATTACHMENT.set(clientAttachment);
} else {
removeClientAttachment();
}
if (serverAttachment != null) {
SERVER_ATTACHMENT.set(serverAttachment);
} else {
removeServerAttachment();
}
if (clientResponseLocal != null) {
CLIENT_RESPONSE_LOCAL.set(clientResponseLocal);
} else {
removeClientResponseContext();
}
if (serverResponseLocal != null) {
SERVER_RESPONSE_LOCAL.set(serverResponseLocal);
} else {
removeServerResponseContext();
}
}
}
public static class RestoreServiceContext {
private final RpcServiceContext serviceContext;
public RestoreServiceContext() {
RpcServiceContext originContext = getCurrentServiceContext();
if (originContext == null) {
this.serviceContext = null;
} else {
this.serviceContext = originContext.copyOf(true);
}
}
protected void restore() {
if (serviceContext != null) {
SERVICE_CONTEXT.set(serviceContext);
} else {
removeServiceContext();
}
}
}
}
| 5,949 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invocation.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.rpc;
import org.apache.dubbo.common.Experimental;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import org.apache.dubbo.rpc.model.ServiceModel;
import java.beans.Transient;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Stream;
/**
* Invocation. (API, Prototype, NonThreadSafe)
*
* @serial Don't change the class name and package name.
* @see org.apache.dubbo.rpc.Invoker#invoke(Invocation)
* @see org.apache.dubbo.rpc.RpcInvocation
*/
public interface Invocation {
String getTargetServiceUniqueName();
String getProtocolServiceKey();
/**
* get method name.
*
* @return method name.
* @serial
*/
String getMethodName();
/**
* get the interface name
*
* @return
*/
String getServiceName();
/**
* get parameter types.
*
* @return parameter types.
* @serial
*/
Class<?>[] getParameterTypes();
/**
* get parameter's signature, string representation of parameter types.
*
* @return parameter's signature
*/
default String[] getCompatibleParamSignatures() {
return Stream.of(getParameterTypes()).map(Class::getName).toArray(String[]::new);
}
/**
* get arguments.
*
* @return arguments.
* @serial
*/
Object[] getArguments();
/**
* get attachments.
*
* @return attachments.
* @serial
*/
Map<String, String> getAttachments();
@Experimental("Experiment api for supporting Object transmission")
Map<String, Object> getObjectAttachments();
@Experimental("Experiment api for supporting Object transmission")
Map<String, Object> copyObjectAttachments();
@Experimental("Experiment api for supporting Object transmission")
void foreachAttachment(Consumer<Map.Entry<String, Object>> consumer);
void setAttachment(String key, String value);
@Experimental("Experiment api for supporting Object transmission")
void setAttachment(String key, Object value);
@Experimental("Experiment api for supporting Object transmission")
void setObjectAttachment(String key, Object value);
void setAttachmentIfAbsent(String key, String value);
@Experimental("Experiment api for supporting Object transmission")
void setAttachmentIfAbsent(String key, Object value);
@Experimental("Experiment api for supporting Object transmission")
void setObjectAttachmentIfAbsent(String key, Object value);
/**
* get attachment by key.
*
* @return attachment value.
* @serial
*/
String getAttachment(String key);
@Experimental("Experiment api for supporting Object transmission")
Object getObjectAttachment(String key);
@Experimental("Experiment api for supporting Object transmission")
default Object getObjectAttachmentWithoutConvert(String key) {
return getObjectAttachment(key);
}
/**
* get attachment by key with default value.
*
* @return attachment value.
* @serial
*/
String getAttachment(String key, String defaultValue);
@Experimental("Experiment api for supporting Object transmission")
Object getObjectAttachment(String key, Object defaultValue);
/**
* get the invoker in current context.
*
* @return invoker.
* @transient
*/
@Transient
Invoker<?> getInvoker();
void setServiceModel(ServiceModel serviceModel);
ServiceModel getServiceModel();
default ModuleModel getModuleModel() {
return ScopeModelUtil.getModuleModel(
getServiceModel() == null ? null : getServiceModel().getModuleModel());
}
Object put(Object key, Object value);
Object get(Object key);
Map<Object, Object> getAttributes();
/**
* To add invoked invokers into invocation. Can be used in ClusterFilter or Filter for tracing or debugging purpose.
* Currently, only support in consumer side.
*
* @param invoker invoked invokers
*/
void addInvokedInvoker(Invoker<?> invoker);
/**
* Get all invoked invokers in current invocation.
* NOTICE: A curtain invoker could be invoked for twice or more if retries.
*
* @return invokers
*/
List<Invoker<?>> getInvokedInvokers();
}
| 5,950 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AttachmentsAdapter.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.rpc;
import java.util.HashMap;
import java.util.Map;
/**
* This class provides map adapters to support attachments in RpcContext, Invocation and Result switch from
* <String, String> to <String, Object>
*/
public class AttachmentsAdapter {
public static class ObjectToStringMap extends HashMap<String, String> {
private final Map<String, Object> attachments;
public ObjectToStringMap(Map<String, Object> attachments) {
for (Entry<String, Object> entry : attachments.entrySet()) {
String convertResult = convert(entry.getValue());
if (convertResult != null) {
super.put(entry.getKey(), convertResult);
}
}
this.attachments = attachments;
}
@Override
public String put(String key, String value) {
attachments.put(key, value);
return super.put(key, value);
}
@Override
public String remove(Object key) {
attachments.remove(key);
return super.remove(key);
}
private String convert(Object obj) {
if (obj instanceof String) {
return (String) obj;
}
return null; // or JSON.toString(obj);
}
@Override
public void clear() {
attachments.clear();
super.clear();
}
@Override
public void putAll(Map<? extends String, ? extends String> map) {
attachments.putAll(map);
super.putAll(map);
}
}
}
| 5,951 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcException.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.rpc;
import javax.naming.LimitExceededException;
/**
* RPC Exception. (API, Prototype, ThreadSafe)
*
* @serial Don't change the class name and properties.
* @see org.apache.dubbo.rpc.Invoker#invoke(Invocation)
* @since 1.0
*/
public class RpcException extends RuntimeException {
public static final int UNKNOWN_EXCEPTION = 0;
public static final int NETWORK_EXCEPTION = 1;
public static final int TIMEOUT_EXCEPTION = 2;
public static final int BIZ_EXCEPTION = 3;
public static final int FORBIDDEN_EXCEPTION = 4;
public static final int SERIALIZATION_EXCEPTION = 5;
public static final int NO_INVOKER_AVAILABLE_AFTER_FILTER = 6;
public static final int LIMIT_EXCEEDED_EXCEPTION = 7;
public static final int TIMEOUT_TERMINATE = 8;
public static final int REGISTRY_EXCEPTION = 9;
public static final int ROUTER_CACHE_NOT_BUILD = 10;
public static final int METHOD_NOT_FOUND = 11;
public static final int VALIDATION_EXCEPTION = 12;
public static final int AUTHORIZATION_EXCEPTION = 13;
private static final long serialVersionUID = 7815426752583648734L;
/**
* RpcException cannot be extended, use error code for exception type to keep compatibility
*/
private int code;
public RpcException() {
super();
}
public RpcException(String message, Throwable cause) {
super(message, cause);
}
public RpcException(String message) {
super(message);
}
public RpcException(Throwable cause) {
super(cause);
}
public RpcException(int code) {
super();
this.code = code;
}
public RpcException(int code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
public RpcException(int code, String message) {
super(message);
this.code = code;
}
public RpcException(int code, Throwable cause) {
super(cause);
this.code = code;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public boolean isBiz() {
return code == BIZ_EXCEPTION;
}
public boolean isForbidden() {
return code == FORBIDDEN_EXCEPTION;
}
public boolean isTimeout() {
return code == TIMEOUT_EXCEPTION;
}
public boolean isNetwork() {
return code == NETWORK_EXCEPTION;
}
public boolean isSerialization() {
return code == SERIALIZATION_EXCEPTION;
}
public boolean isAuthorization() {
return code == AUTHORIZATION_EXCEPTION;
}
public boolean isNoInvokerAvailableAfterFilter() {
return code == NO_INVOKER_AVAILABLE_AFTER_FILTER;
}
public boolean isLimitExceed() {
return code == LIMIT_EXCEEDED_EXCEPTION || getCause() instanceof LimitExceededException;
}
public boolean isValidation() {
return code == VALIDATION_EXCEPTION;
}
}
| 5,952 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcStatus.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.rpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
* URL statistics. (API, Cached, ThreadSafe)
*
* @see org.apache.dubbo.rpc.filter.ActiveLimitFilter
* @see org.apache.dubbo.rpc.filter.ExecuteLimitFilter
* @see org.apache.dubbo.rpc.cluster.loadbalance.LeastActiveLoadBalance
*/
public class RpcStatus {
private static final ConcurrentMap<String, RpcStatus> SERVICE_STATISTICS =
new ConcurrentHashMap<String, RpcStatus>();
private static final ConcurrentMap<String, ConcurrentMap<String, RpcStatus>> METHOD_STATISTICS =
new ConcurrentHashMap<String, ConcurrentMap<String, RpcStatus>>();
private final ConcurrentMap<String, Object> values = new ConcurrentHashMap<String, Object>();
private final AtomicInteger active = new AtomicInteger();
private final AtomicLong total = new AtomicLong();
private final AtomicInteger failed = new AtomicInteger();
private final AtomicLong totalElapsed = new AtomicLong();
private final AtomicLong failedElapsed = new AtomicLong();
private final AtomicLong maxElapsed = new AtomicLong();
private final AtomicLong failedMaxElapsed = new AtomicLong();
private final AtomicLong succeededMaxElapsed = new AtomicLong();
private RpcStatus() {}
/**
* @param url
* @return status
*/
public static RpcStatus getStatus(URL url) {
String uri = url.toIdentityString();
return ConcurrentHashMapUtils.computeIfAbsent(SERVICE_STATISTICS, uri, key -> new RpcStatus());
}
/**
* @param url
*/
public static void removeStatus(URL url) {
String uri = url.toIdentityString();
SERVICE_STATISTICS.remove(uri);
}
/**
* @param url
* @param methodName
* @return status
*/
public static RpcStatus getStatus(URL url, String methodName) {
String uri = url.toIdentityString();
ConcurrentMap<String, RpcStatus> map =
ConcurrentHashMapUtils.computeIfAbsent(METHOD_STATISTICS, uri, k -> new ConcurrentHashMap<>());
return ConcurrentHashMapUtils.computeIfAbsent(map, methodName, k -> new RpcStatus());
}
/**
* @param url
*/
public static void removeStatus(URL url, String methodName) {
String uri = url.toIdentityString();
ConcurrentMap<String, RpcStatus> map = METHOD_STATISTICS.get(uri);
if (map != null) {
map.remove(methodName);
}
}
public static void beginCount(URL url, String methodName) {
beginCount(url, methodName, Integer.MAX_VALUE);
}
/**
* @param url
*/
public static boolean beginCount(URL url, String methodName, int max) {
max = (max <= 0) ? Integer.MAX_VALUE : max;
RpcStatus appStatus = getStatus(url);
RpcStatus methodStatus = getStatus(url, methodName);
if (methodStatus.active.get() == Integer.MAX_VALUE) {
return false;
}
for (int i; ; ) {
i = methodStatus.active.get();
if (i == Integer.MAX_VALUE || i + 1 > max) {
return false;
}
if (methodStatus.active.compareAndSet(i, i + 1)) {
break;
}
}
appStatus.active.incrementAndGet();
return true;
}
/**
* @param url
* @param elapsed
* @param succeeded
*/
public static void endCount(URL url, String methodName, long elapsed, boolean succeeded) {
endCount(getStatus(url), elapsed, succeeded);
endCount(getStatus(url, methodName), elapsed, succeeded);
}
private static void endCount(RpcStatus status, long elapsed, boolean succeeded) {
status.active.decrementAndGet();
status.total.incrementAndGet();
status.totalElapsed.addAndGet(elapsed);
if (status.maxElapsed.get() < elapsed) {
status.maxElapsed.set(elapsed);
}
if (succeeded) {
if (status.succeededMaxElapsed.get() < elapsed) {
status.succeededMaxElapsed.set(elapsed);
}
} else {
status.failed.incrementAndGet();
status.failedElapsed.addAndGet(elapsed);
if (status.failedMaxElapsed.get() < elapsed) {
status.failedMaxElapsed.set(elapsed);
}
}
}
/**
* set value.
*
* @param key
* @param value
*/
public void set(String key, Object value) {
values.put(key, value);
}
/**
* get value.
*
* @param key
* @return value
*/
public Object get(String key) {
return values.get(key);
}
/**
* get active.
*
* @return active
*/
public int getActive() {
return active.get();
}
/**
* get total.
*
* @return total
*/
public long getTotal() {
return total.longValue();
}
/**
* get total elapsed.
*
* @return total elapsed
*/
public long getTotalElapsed() {
return totalElapsed.get();
}
/**
* get average elapsed.
*
* @return average elapsed
*/
public long getAverageElapsed() {
long total = getTotal();
if (total == 0) {
return 0;
}
return getTotalElapsed() / total;
}
/**
* get max elapsed.
*
* @return max elapsed
*/
public long getMaxElapsed() {
return maxElapsed.get();
}
/**
* get failed.
*
* @return failed
*/
public int getFailed() {
return failed.get();
}
/**
* get failed elapsed.
*
* @return failed elapsed
*/
public long getFailedElapsed() {
return failedElapsed.get();
}
/**
* get failed average elapsed.
*
* @return failed average elapsed
*/
public long getFailedAverageElapsed() {
long failed = getFailed();
if (failed == 0) {
return 0;
}
return getFailedElapsed() / failed;
}
/**
* get failed max elapsed.
*
* @return failed max elapsed
*/
public long getFailedMaxElapsed() {
return failedMaxElapsed.get();
}
/**
* get succeeded.
*
* @return succeeded
*/
public long getSucceeded() {
return getTotal() - getFailed();
}
/**
* get succeeded elapsed.
*
* @return succeeded elapsed
*/
public long getSucceededElapsed() {
return getTotalElapsed() - getFailedElapsed();
}
/**
* get succeeded average elapsed.
*
* @return succeeded average elapsed
*/
public long getSucceededAverageElapsed() {
long succeeded = getSucceeded();
if (succeeded == 0) {
return 0;
}
return getSucceededElapsed() / succeeded;
}
/**
* get succeeded max elapsed.
*
* @return succeeded max elapsed.
*/
public long getSucceededMaxElapsed() {
return succeededMaxElapsed.get();
}
/**
* Calculate average TPS (Transaction per second).
*
* @return tps
*/
public long getAverageTps() {
if (getTotalElapsed() >= 1000L) {
return getTotal() / (getTotalElapsed() / 1000L);
}
return getTotal();
}
}
| 5,953 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ListenableFilter.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.rpc;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* It's recommended to implement Filter.Listener directly for callback registration, check the default implementation,
* see {@link org.apache.dubbo.rpc.filter.ExceptionFilter}, for example.
* <p>
* If you do not want to share Listener instance between RPC calls. ListenableFilter can be used
* to keep a 'one Listener each RPC call' model.
*/
@Deprecated
public abstract class ListenableFilter implements Filter {
protected Listener listener = null;
protected final ConcurrentMap<Invocation, Listener> listeners = new ConcurrentHashMap<>();
public Listener listener() {
return listener;
}
public Listener listener(Invocation invocation) {
Listener invListener = listeners.get(invocation);
if (invListener == null) {
invListener = listener;
}
return invListener;
}
public void addListener(Invocation invocation, Listener listener) {
listeners.putIfAbsent(invocation, listener);
}
public void removeListener(Invocation invocation) {
listeners.remove(invocation);
}
}
| 5,954 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AsyncContext.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.rpc;
/**
* AsyncContext works like {@see javax.servlet.AsyncContext} in the Servlet 3.0.
* An AsyncContext is stated by a call to {@link RpcContext#startAsync()}.
* <p>
* The demo is {@see com.alibaba.dubbo.examples.async.AsyncConsumer}
* and {@see com.alibaba.dubbo.examples.async.AsyncProvider}
*/
public interface AsyncContext {
/**
* write value and complete the async context.
*
* @param value invoke result
*/
void write(Object value);
/**
* @return true if the async context is started
*/
boolean isAsyncStarted();
/**
* change the context state to stop
*/
boolean stop();
/**
* change the context state to start
*/
void start();
/**
* Signal RpcContext switch.
* Use this method to switch RpcContext from a Dubbo thread to a new thread created by the user.
*
* Note that you should use it in a new thread like this:
* <code>
* public class AsyncServiceImpl implements AsyncService {
* public String sayHello(String name) {
* final AsyncContext asyncContext = RpcContext.startAsync();
* new Thread(() -> {
*
* // right place to use this method
* asyncContext.signalContextSwitch();
*
* try {
* Thread.sleep(500);
* } catch (InterruptedException e) {
* e.printStackTrace();
* }
* asyncContext.write("Hello " + name + ", response from provider.");
* }).start();
* return null;
* }
* }
* </code>
*/
void signalContextSwitch();
/**
* Reset Context is not necessary. Only reset context after result was write back if it is necessary.
*
* <code>
* public class AsyncServiceImpl implements AsyncService {
* public String sayHello(String name) {
* final AsyncContext asyncContext = RpcContext.startAsync();
* new Thread(() -> {
* <p>
* // the right place to use this method
* asyncContext.signalContextSwitch();
* <p>
* try {
* Thread.sleep(500);
* } catch (InterruptedException e) {
* e.printStackTrace();
* }
* asyncContext.write("Hello " + name + ", response from provider.");
* // only reset after asyncContext.write()
* asyncContext.resetContext();
* }).start();
* return null;
* }
* }
* </code>
*
* <code>
* public class AsyncServiceImpl implements AsyncService {
* public CompletableFuture sayHello(String name) {
* CompletableFuture future = new CompletableFuture();
* final AsyncContext asyncContext = RpcContext.startAsync();
* new Thread(() -> {
* // the right place to use this method
* asyncContext.signalContextSwitch();
* // some operations...
* future.complete();
* // only reset after future.complete()
* asyncContext.resetContext();
* }).start();
* return future;
* }
* }
* </code>
*/
void resetContext();
}
| 5,955 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/CancellationContext.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.rpc;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
public class CancellationContext implements Closeable {
private volatile ArrayList<ExecutableListener> listeners;
private Throwable cancellationCause;
private boolean cancelled;
public void addListener(final CancellationListener cancellationListener, final Executor executor) {
addListener(cancellationListener, executor, null);
}
public void addListener(final CancellationListener cancellationListener) {
addListener(cancellationListener, Runnable::run, null);
}
public void addListener(final CancellationListener cancellationListener, final RpcServiceContext context) {
addListener(cancellationListener, Runnable::run, context);
}
public void addListener(
final CancellationListener cancellationListener, final Executor executor, final RpcServiceContext context) {
addListenerInternal(new ExecutableListener(executor, cancellationListener, context));
}
public synchronized void addListenerInternal(ExecutableListener executableListener) {
if (isCancelled()) {
executableListener.deliver();
} else {
if (listeners == null) {
listeners = new ArrayList<>();
}
listeners.add(executableListener);
}
}
public boolean cancel(Throwable cause) {
boolean triggeredCancel = false;
synchronized (this) {
if (!cancelled) {
cancelled = true;
this.cancellationCause = cause;
triggeredCancel = true;
}
}
if (triggeredCancel) {
notifyAndClearListeners();
}
return triggeredCancel;
}
private void notifyAndClearListeners() {
ArrayList<ExecutableListener> tmpListeners;
synchronized (this) {
if (listeners == null) {
return;
}
tmpListeners = listeners;
listeners = null;
}
for (ExecutableListener tmpListener : tmpListeners) {
tmpListener.deliver();
}
}
public synchronized boolean isCancelled() {
return cancelled;
}
public List<ExecutableListener> getListeners() {
return listeners;
}
public Throwable getCancellationCause() {
return cancellationCause;
}
@Override
public void close() throws IOException {
cancel(null);
}
}
| 5,956 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/FutureContext.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.rpc;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.threadlocal.InternalThreadLocal;
import org.apache.dubbo.rpc.protocol.dubbo.FutureAdapter;
import java.util.concurrent.CompletableFuture;
/**
* Used for async call scenario. But if the method you are calling has a {@link CompletableFuture<?>} signature
* you do not need to use this class since you will get a Future response directly.
* <p>
* Remember to save the Future reference before making another call using the same thread, otherwise,
* the current Future will be override by the new one, which means you will lose the chance get the return value.
*/
public class FutureContext {
private static final InternalThreadLocal<FutureContext> futureTL = new InternalThreadLocal<FutureContext>() {
@Override
protected FutureContext initialValue() {
return new FutureContext();
}
};
public static FutureContext getContext() {
return futureTL.get();
}
private CompletableFuture<?> future;
private CompletableFuture<?> compatibleFuture;
/**
* Whether clear future once get
*/
private static final boolean clearFutureAfterGet =
Boolean.parseBoolean(System.getProperty(CommonConstants.CLEAR_FUTURE_AFTER_GET, "false"));
/**
* get future.
*
* @param <T>
* @return future
*/
@SuppressWarnings("unchecked")
public <T> CompletableFuture<T> getCompletableFuture() {
try {
return (CompletableFuture<T>) future;
} finally {
if (clearFutureAfterGet) {
this.future = null;
}
}
}
/**
* set future.
*
* @param future
*/
public void setFuture(CompletableFuture<?> future) {
this.future = future;
}
@Deprecated
@SuppressWarnings("unchecked")
public <T> CompletableFuture<T> getCompatibleCompletableFuture() {
try {
return (CompletableFuture<T>) compatibleFuture;
} finally {
if (clearFutureAfterGet) {
this.compatibleFuture = null;
}
}
}
/**
* Guarantee 'using org.apache.dubbo.rpc.RpcContext.getFuture() before proxy returns' can work, a typical scenario is:
* <pre>{@code
* public final class TracingFilter implements Filter {
* public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
* Result result = invoker.invoke(invocation);
* Future<Object> future = rpcContext.getFuture();
* if (future instanceof FutureAdapter) {
* ((FutureAdapter) future).getFuture().setCallback(new FinishSpanCallback(span));
* }
* ......
* }
* }
* }</pre>
*
* Start from 2.7.3, you don't have to get Future from RpcContext, we recommend using Result directly:
* <pre>{@code
* public final class TracingFilter implements Filter {
* public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
* Result result = invoker.invoke(invocation);
* result.getResponseFuture().whenComplete(new FinishSpanCallback(span));
* ......
* }
* }
* }</pre>
*
*/
@Deprecated
public void setCompatibleFuture(CompletableFuture<?> compatibleFuture) {
this.compatibleFuture = compatibleFuture;
if (compatibleFuture != null) {
this.setFuture(new FutureAdapter(compatibleFuture));
}
}
}
| 5,957 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExecutableListener.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.rpc;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import java.util.concurrent.Executor;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_NOTIFY_EVENT;
public class ExecutableListener implements Runnable {
private static final ErrorTypeAwareLogger log = LoggerFactory.getErrorTypeAwareLogger(ExecutableListener.class);
private final Executor executor;
private final CancellationListener listener;
private final RpcServiceContext context;
public ExecutableListener(Executor executor, CancellationListener listener, RpcServiceContext context) {
this.executor = executor;
this.listener = listener;
this.context = context;
}
public ExecutableListener(Executor executor, CancellationListener listener) {
this(executor, listener, null);
}
public void deliver() {
try {
executor.execute(this);
} catch (Throwable t) {
log.warn(COMMON_FAILED_NOTIFY_EVENT, "", "", "Exception notifying context listener", t);
}
}
public Executor getExecutor() {
return executor;
}
public CancellationListener getListener() {
return listener;
}
public RpcServiceContext getContext() {
return context;
}
@Override
public void run() {
listener.cancelled(context);
}
}
| 5,958 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokeMode.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.rpc;
public enum InvokeMode {
SYNC,
ASYNC,
FUTURE;
}
| 5,959 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/InvokerListener.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.rpc;
import org.apache.dubbo.common.extension.SPI;
/**
* InvokerListener. (SPI, Singleton, ThreadSafe)
*/
@SPI
public interface InvokerListener {
/**
* The invoker referred
*
* @param invoker
* @throws RpcException
* @see org.apache.dubbo.rpc.Protocol#refer(Class, org.apache.dubbo.common.URL)
*/
void referred(Invoker<?> invoker) throws RpcException;
/**
* The invoker destroyed.
*
* @param invoker
* @see org.apache.dubbo.rpc.Invoker#destroy()
*/
void destroyed(Invoker<?> invoker);
}
| 5,960 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ServerService.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.rpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
public interface ServerService<T> {
Invoker<T> getInvoker(URL url);
ServiceDescriptor getServiceDescriptor();
}
| 5,961 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Protocol.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.rpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import java.util.Collections;
import java.util.List;
/**
* RPC Protocol extension interface, which encapsulates the details of remote invocation. <br /><br />
*
* <p>Conventions:
*
* <li>
* When user invokes the 'invoke()' method in object that the method 'refer()' returns,
* the protocol needs to execute the 'invoke()' method of Invoker object that received by 'export()' method,
* which should have the same URL.
* </li>
*
* <li>
* Invoker that returned by 'refer()' is implemented by the protocol. The remote invocation request should be sent by that Invoker.
* </li>
*
* <li>
* The invoker that 'export()' receives will be implemented by framework. Protocol implementation should not care with that.
* </li>
*
* <p>Attentions:
*
* <li>
* The Protocol implementation does not care the transparent proxy. The invoker will be converted to business interface by other layer.
* </li>
*
* <li>
* The protocol doesn't need to be backed by TCP connection. It can also be backed by file sharing or inter-process communication.
* </li>
*
* (API/SPI, Singleton, ThreadSafe)
*/
@SPI(value = "dubbo", scope = ExtensionScope.FRAMEWORK)
public interface Protocol {
/**
* Get default port when user doesn't config the port.
*
* @return default port
*/
int getDefaultPort();
/**
* Export service for remote invocation: <br>
* 1. Protocol should record request source address after receive a request:
* RpcContext.getServerAttachment().setRemoteAddress();<br>
* 2. export() must be idempotent, that is, there's no difference between invoking once and invoking twice when
* export the same URL<br>
* 3. Invoker instance is passed in by the framework, protocol needs not to care <br>
*
* @param <T> Service type
* @param invoker Service invoker
* @return exporter reference for exported service, useful for unexport the service later
* @throws RpcException thrown when error occurs during export the service, for example: port is occupied
*/
@Adaptive
<T> Exporter<T> export(Invoker<T> invoker) throws RpcException;
/**
* Refer a remote service: <br>
* 1. When user calls `invoke()` method of `Invoker` object which's returned from `refer()` call, the protocol
* needs to correspondingly execute `invoke()` method of `Invoker` object <br>
* 2. It's protocol's responsibility to implement `Invoker` which's returned from `refer()`. Generally speaking,
* protocol sends remote request in the `Invoker` implementation. <br>
* 3. When there's check=false set in URL, the implementation must not throw exception but try to recover when
* connection fails.
*
* @param <T> Service type
* @param type Service class
* @param url URL address for the remote service
* @return invoker service's local proxy
* @throws RpcException when there's any error while connecting to the service provider
*/
@Adaptive
<T> Invoker<T> refer(Class<T> type, URL url) throws RpcException;
/**
* Destroy protocol: <br>
* 1. Cancel all services this protocol exports and refers <br>
* 2. Release all occupied resources, for example: connection, port, etc. <br>
* 3. Protocol can continue to export and refer new service even after it's destroyed.
*/
void destroy();
/**
* Get all servers serving this protocol
*
* @return
*/
default List<ProtocolServer> getServers() {
return Collections.emptyList();
}
}
| 5,962 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/HeaderFilter.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.rpc;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface HeaderFilter {
RpcInvocation invoke(Invoker<?> invoker, RpcInvocation invocation) throws RpcException;
}
| 5,963 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/TimeoutCountDown.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.rpc;
import java.util.concurrent.TimeUnit;
public final class TimeoutCountDown implements Comparable<TimeoutCountDown> {
public static TimeoutCountDown newCountDown(long timeout, TimeUnit unit) {
return new TimeoutCountDown(timeout, unit);
}
private final long timeoutInMillis;
private final long deadlineInNanos;
private volatile boolean expired;
private TimeoutCountDown(long timeout, TimeUnit unit) {
timeoutInMillis = TimeUnit.MILLISECONDS.convert(timeout, unit);
deadlineInNanos = System.nanoTime() + TimeUnit.NANOSECONDS.convert(timeout, unit);
}
public long getTimeoutInMilli() {
return timeoutInMillis;
}
public boolean isExpired() {
if (!expired) {
if (deadlineInNanos - System.nanoTime() <= 0) {
expired = true;
} else {
return false;
}
}
return true;
}
public long timeRemaining(TimeUnit unit) {
final long currentNanos = System.nanoTime();
if (!expired && deadlineInNanos - currentNanos <= 0) {
expired = true;
}
return unit.convert(deadlineInNanos - currentNanos, TimeUnit.NANOSECONDS);
}
public long elapsedMillis() {
if (isExpired()) {
return timeoutInMillis
+ TimeUnit.MILLISECONDS.convert(System.nanoTime() - deadlineInNanos, TimeUnit.NANOSECONDS);
} else {
return timeoutInMillis
- TimeUnit.MILLISECONDS.convert(deadlineInNanos - System.nanoTime(), TimeUnit.NANOSECONDS);
}
}
@Override
public String toString() {
long timeoutMillis = TimeUnit.MILLISECONDS.convert(deadlineInNanos, TimeUnit.NANOSECONDS);
long remainingMillis = timeRemaining(TimeUnit.MILLISECONDS);
StringBuilder buf = new StringBuilder();
buf.append("Total timeout value - ");
buf.append(timeoutMillis);
buf.append(", times remaining - ");
buf.append(remainingMillis);
return buf.toString();
}
@Override
public int compareTo(TimeoutCountDown another) {
long delta = this.deadlineInNanos - another.deadlineInNanos;
if (delta < 0) {
return -1;
} else if (delta > 0) {
return 1;
}
return 0;
}
}
| 5,964 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/BaseFilter.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.rpc;
public interface BaseFilter {
/**
* Always call invoker.invoke() in the implementation to hand over the request to the next filter node.
*/
Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException;
/**
* This callback listener applies to both synchronous and asynchronous calls, please put logics that need to be executed
* on return of rpc result in onResponse or onError respectively based on it is normal return or exception return.
* <p>
* There's something that needs to pay attention on legacy synchronous style filer refactor, the thing is, try to move logics
* previously defined in the 'finally block' to both onResponse and onError.
*/
interface Listener {
/**
* This method will only be called on successful remote rpc execution, that means, the service in on remote received
* the request and the result (normal or exceptional) returned successfully.
*
* @param appResponse, the rpc call result, it can represent both normal result and exceptional result
* @param invoker, context
* @param invocation, context
*/
void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation);
/**
* This method will be called on detection of framework exceptions, for example, TimeoutException, NetworkException
* Exception raised in Filters, etc.
*
* @param t, framework exception
* @param invoker, context
* @param invocation, context
*/
void onError(Throwable t, Invoker<?> invoker, Invocation invocation);
}
}
| 5,965 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/PenetrateAttachmentSelector.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.rpc;
import org.apache.dubbo.common.extension.SPI;
import java.util.Map;
@SPI
public interface PenetrateAttachmentSelector {
/**
* Select some attachments to pass to next hop.
* These attachments can fetch from {@link RpcContext#getServerAttachment()} or user defined.
*
* @return attachment pass to next hop
*/
Map<String, Object> select(
Invocation invocation, RpcContextAttachment clientAttachment, RpcContextAttachment serverAttachment);
Map<String, Object> selectReverse(
Invocation invocation,
RpcContextAttachment clientResponseContext,
RpcContextAttachment serverResponseContext);
}
| 5,966 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AppResponse.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.rpc;
import org.apache.dubbo.common.compact.Dubbo2CompactUtils;
import org.apache.dubbo.rpc.support.Dubbo2RpcExceptionUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiConsumer;
import java.util.function.Function;
import static org.apache.dubbo.rpc.Constants.INVOCATION_KEY;
/**
* {@link AsyncRpcResult} is introduced in 3.0.0 to replace RpcResult, and RpcResult is replaced with {@link AppResponse}:
* <ul>
* <li>AsyncRpcResult is the object that is actually passed in the call chain</li>
* <li>AppResponse only simply represents the business result</li>
* </ul>
* <p>
* The relationship between them can be described as follow, an abstraction of the definition of AsyncRpcResult:
* <pre>
* {@code
* Public class AsyncRpcResult implements CompletionStage<AppResponse> {
* ......
* }
* </pre>
* AsyncRpcResult is a future representing an unfinished RPC call, while AppResponse is the actual return type of this call.
* In theory, AppResponse doesn't have to implement the {@link Result} interface, this is done mainly for compatibility purpose.
*
* @serial Do not change the class name and properties.
*/
public class AppResponse implements Result {
private static final long serialVersionUID = -6925924956850004727L;
private Object result;
private Throwable exception;
private Map<String, Object> attachments = new HashMap<>();
private final Map<String, Object> attributes = new HashMap<>();
public AppResponse() {}
public AppResponse(Invocation invocation) {
this.setAttribute(INVOCATION_KEY, invocation);
}
public AppResponse(Object result) {
this.result = result;
}
public AppResponse(Throwable exception) {
this.exception = exception;
}
@Override
public Object recreate() throws Throwable {
if (exception != null) {
// fix issue#619
try {
Object stackTrace = exception.getStackTrace();
if (stackTrace == null) {
exception.setStackTrace(new StackTraceElement[0]);
}
} catch (Exception e) {
// ignore
}
if (Dubbo2CompactUtils.isEnabled()
&& Dubbo2RpcExceptionUtils.isRpcExceptionClassLoaded()
&& (exception instanceof RpcException)
&& !Dubbo2RpcExceptionUtils.getRpcExceptionClass().isAssignableFrom(exception.getClass())) {
RpcException recreated = Dubbo2RpcExceptionUtils.newRpcException(
((RpcException) exception).getCode(), exception.getMessage(), exception.getCause());
if (recreated != null) {
recreated.setStackTrace(exception.getStackTrace());
throw recreated;
}
}
throw exception;
}
return result;
}
@Override
public Object getValue() {
return result;
}
@Override
public void setValue(Object value) {
this.result = value;
}
@Override
public Throwable getException() {
return exception;
}
@Override
public void setException(Throwable e) {
this.exception = e;
}
@Override
public boolean hasException() {
return exception != null;
}
@Override
@Deprecated
public Map<String, String> getAttachments() {
return new AttachmentsAdapter.ObjectToStringMap(attachments);
}
@Override
public Map<String, Object> getObjectAttachments() {
return attachments;
}
/**
* Append all items from the map into the attachment, if map is empty then nothing happens
*
* @param map contains all key-value pairs to append
*/
public void setAttachments(Map<String, String> map) {
this.attachments = map == null ? new HashMap<>() : new HashMap<>(map);
}
@Override
public void setObjectAttachments(Map<String, Object> map) {
this.attachments = map == null ? new HashMap<>() : map;
}
public void addAttachments(Map<String, String> map) {
if (map == null) {
return;
}
if (this.attachments == null) {
this.attachments = new HashMap<>(map.size());
}
this.attachments.putAll(map);
}
@Override
public void addObjectAttachments(Map<String, Object> map) {
if (map == null) {
return;
}
if (this.attachments == null) {
this.attachments = new HashMap<>(map.size());
}
this.attachments.putAll(map);
}
@Override
public String getAttachment(String key) {
Object value = attachments.get(key);
if (value instanceof String) {
return (String) value;
}
return null;
}
@Override
public Object getObjectAttachment(String key) {
return attachments.get(key);
}
@Override
public String getAttachment(String key, String defaultValue) {
Object result = attachments.get(key);
if (result == null) {
return defaultValue;
}
if (result instanceof String) {
return (String) result;
}
return defaultValue;
}
@Override
public Object getObjectAttachment(String key, Object defaultValue) {
Object result = attachments.get(key);
if (result == null) {
result = defaultValue;
}
return result;
}
@Override
public void setAttachment(String key, String value) {
setObjectAttachment(key, value);
}
@Override
public void setAttachment(String key, Object value) {
setObjectAttachment(key, value);
}
@Override
public void setObjectAttachment(String key, Object value) {
attachments.put(key, value);
}
public Object getAttribute(String key) {
return attributes.get(key);
}
public void setAttribute(String key, Object value) {
attributes.put(key, value);
}
@Override
public Result whenCompleteWithContext(BiConsumer<Result, Throwable> fn) {
throw new UnsupportedOperationException(
"AppResponse represents an concrete business response, there will be no status changes, you should get internal values directly.");
}
@Override
public <U> CompletableFuture<U> thenApply(Function<Result, ? extends U> fn) {
throw new UnsupportedOperationException(
"AppResponse represents an concrete business response, there will be no status changes, you should get internal values directly.");
}
@Override
public Result get() throws InterruptedException, ExecutionException {
throw new UnsupportedOperationException(
"AppResponse represents an concrete business response, there will be no status changes, you should get internal values directly.");
}
@Override
public Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
throw new UnsupportedOperationException(
"AppResponse represents an concrete business response, there will be no status changes, you should get internal values directly.");
}
public void clear() {
this.result = null;
this.exception = null;
this.attachments.clear();
}
@Override
public String toString() {
return "AppResponse [value=" + result + ", exception=" + exception + "]";
}
}
| 5,967 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/AdaptiveMetrics.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.rpc;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.StringUtils;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
/**
* adaptive Metrics statistics.
*/
public class AdaptiveMetrics {
private final ConcurrentMap<String, AdaptiveMetrics> metricsStatistics = new ConcurrentHashMap<>();
private long currentProviderTime = 0;
private double providerCPULoad = 0;
private long lastLatency = 0;
private long currentTime = 0;
// Allow some time disorder
private long pickTime = System.currentTimeMillis();
private double beta = 0.5;
private final AtomicLong consumerReq = new AtomicLong();
private final AtomicLong consumerSuccess = new AtomicLong();
private final AtomicLong errorReq = new AtomicLong();
private double ewma = 0;
public double getLoad(String idKey, int weight, int timeout) {
AdaptiveMetrics metrics = getStatus(idKey);
// If the time more than 2 times, mandatory selected
if (System.currentTimeMillis() - metrics.pickTime > timeout * 2) {
return 0;
}
if (metrics.currentTime > 0) {
long multiple = (System.currentTimeMillis() - metrics.currentTime) / timeout + 1;
if (multiple > 0) {
if (metrics.currentProviderTime == metrics.currentTime) {
// penalty value
metrics.lastLatency = timeout * 2L;
} else {
metrics.lastLatency = metrics.lastLatency >> multiple;
}
metrics.ewma = metrics.beta * metrics.ewma + (1 - metrics.beta) * metrics.lastLatency;
metrics.currentTime = System.currentTimeMillis();
}
}
long inflight = metrics.consumerReq.get() - metrics.consumerSuccess.get() - metrics.errorReq.get();
return metrics.providerCPULoad
* (Math.sqrt(metrics.ewma) + 1)
* (inflight + 1)
/ ((((double) metrics.consumerSuccess.get() / (double) (metrics.consumerReq.get() + 1)) * weight) + 1);
}
public AdaptiveMetrics getStatus(String idKey) {
return ConcurrentHashMapUtils.computeIfAbsent(metricsStatistics, idKey, k -> new AdaptiveMetrics());
}
public void addConsumerReq(String idKey) {
AdaptiveMetrics metrics = getStatus(idKey);
metrics.consumerReq.incrementAndGet();
}
public void addConsumerSuccess(String idKey) {
AdaptiveMetrics metrics = getStatus(idKey);
metrics.consumerSuccess.incrementAndGet();
}
public void addErrorReq(String idKey) {
AdaptiveMetrics metrics = getStatus(idKey);
metrics.errorReq.incrementAndGet();
}
public void setPickTime(String idKey, long time) {
AdaptiveMetrics metrics = getStatus(idKey);
metrics.pickTime = time;
}
public void setProviderMetrics(String idKey, Map<String, String> metricsMap) {
AdaptiveMetrics metrics = getStatus(idKey);
long serviceTime = Long.parseLong(Optional.ofNullable(metricsMap.get("curTime"))
.filter(v -> StringUtils.isNumeric(v, false))
.orElse("0"));
// If server time is less than the current time, discard
if (metrics.currentProviderTime > serviceTime) {
return;
}
metrics.currentProviderTime = serviceTime;
metrics.currentTime = serviceTime;
metrics.providerCPULoad = Double.parseDouble(Optional.ofNullable(metricsMap.get("load"))
.filter(v -> StringUtils.isNumeric(v, true))
.orElse("0"));
metrics.lastLatency = Long.parseLong((Optional.ofNullable(metricsMap.get("rt"))
.filter(v -> StringUtils.isNumeric(v, false))
.orElse("0")));
metrics.beta = 0.5;
// Vt = β * Vt-1 + (1 - β ) * θt
metrics.ewma = metrics.beta * metrics.ewma + (1 - metrics.beta) * metrics.lastLatency;
}
}
| 5,968 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcContextAttachment.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.rpc;
import org.apache.dubbo.common.Experimental;
import org.apache.dubbo.common.utils.CollectionUtils;
import java.util.HashMap;
import java.util.Map;
public class RpcContextAttachment extends RpcContext {
protected volatile Map<String, Object> attachments = new HashMap<>();
// only useful on provider side.
protected AsyncContext asyncContext;
protected RpcContextAttachment() {}
/**
* @return
* @throws IllegalStateException
*/
@SuppressWarnings("unchecked")
public static AsyncContext startAsync() throws IllegalStateException {
RpcContextAttachment currentContext = getServerAttachment();
if (currentContext.asyncContext == null) {
currentContext.asyncContext = new AsyncContextImpl();
}
currentContext.asyncContext.start();
return currentContext.asyncContext;
}
@Override
protected void setAsyncContext(AsyncContext asyncContext) {
this.asyncContext = asyncContext;
}
@Override
public boolean isAsyncStarted() {
if (this.asyncContext == null) {
return false;
}
return asyncContext.isAsyncStarted();
}
@Override
public boolean stopAsync() {
return asyncContext.stop();
}
@Override
public AsyncContext getAsyncContext() {
return asyncContext;
}
/**
* also see {@link #getObjectAttachment(String)}.
*
* @param key
* @return attachment
*/
@Override
public String getAttachment(String key) {
Object value = attachments.get(key);
if (value instanceof String) {
return (String) value;
}
return null; // or JSON.toString(value);
}
/**
* get attachment.
*
* @param key
* @return attachment
*/
@Override
@Experimental("Experiment api for supporting Object transmission")
public Object getObjectAttachment(String key) {
return attachments.get(key);
}
/**
* set attachment.
*
* @param key
* @param value
* @return context
*/
@Override
public RpcContextAttachment setAttachment(String key, String value) {
return setObjectAttachment(key, (Object) value);
}
@Override
public RpcContextAttachment setAttachment(String key, Object value) {
return setObjectAttachment(key, value);
}
@Override
@Experimental("Experiment api for supporting Object transmission")
public RpcContextAttachment setObjectAttachment(String key, Object value) {
if (value == null) {
attachments.remove(key);
} else {
attachments.put(key, value);
}
return this;
}
/**
* remove attachment.
*
* @param key
* @return context
*/
@Override
public RpcContextAttachment removeAttachment(String key) {
attachments.remove(key);
return this;
}
/**
* get attachments.
*
* @return attachments
*/
@Override
@Deprecated
public Map<String, String> getAttachments() {
return new AttachmentsAdapter.ObjectToStringMap(this.getObjectAttachments());
}
/**
* get attachments.
*
* @return attachments
*/
@Override
@Experimental("Experiment api for supporting Object transmission")
public Map<String, Object> getObjectAttachments() {
return attachments;
}
/**
* set attachments
*
* @param attachment
* @return context
*/
@Override
public RpcContextAttachment setAttachments(Map<String, String> attachment) {
this.attachments.clear();
if (attachment != null && attachment.size() > 0) {
this.attachments.putAll(attachment);
}
return this;
}
/**
* set attachments
*
* @param attachment
* @return context
*/
@Override
@Experimental("Experiment api for supporting Object transmission")
public RpcContextAttachment setObjectAttachments(Map<String, Object> attachment) {
this.attachments.clear();
if (CollectionUtils.isNotEmptyMap(attachment)) {
this.attachments = attachment;
}
return this;
}
@Override
public void clearAttachments() {
this.attachments.clear();
}
/**
* get values.
*
* @return values
*/
@Override
@Deprecated
public Map<String, Object> get() {
return getObjectAttachments();
}
/**
* set value.
*
* @param key
* @param value
* @return context
*/
@Override
@Deprecated
public RpcContextAttachment set(String key, Object value) {
return setAttachment(key, value);
}
/**
* remove value.
*
* @param key
* @return value
*/
@Override
@Deprecated
public RpcContextAttachment remove(String key) {
return removeAttachment(key);
}
/**
* get value.
*
* @param key
* @return value
*/
@Override
@Deprecated
public Object get(String key) {
return getAttachment(key);
}
/**
* Also see {@link RpcServiceContext#copyOf(boolean)}
*
* @return a copy of RpcContextAttachment with deep copied attachments
*/
public RpcContextAttachment copyOf(boolean needCopy) {
if (!isValid()) {
return null;
}
if (needCopy) {
RpcContextAttachment copy = new RpcContextAttachment();
if (CollectionUtils.isNotEmptyMap(attachments)) {
copy.attachments.putAll(this.attachments);
}
if (asyncContext != null) {
copy.asyncContext = this.asyncContext;
}
return copy;
} else {
return this;
}
}
protected boolean isValid() {
return CollectionUtils.isNotEmptyMap(attachments);
}
}
| 5,969 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServiceContext.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.rpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.common.utils.StringUtils;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE;
import static org.apache.dubbo.rpc.Constants.ASYNC_KEY;
import static org.apache.dubbo.rpc.Constants.RETURN_KEY;
public class RpcServiceContext extends RpcContext {
protected RpcServiceContext() {}
// RPC service context updated before each service call.
private URL consumerUrl;
private List<URL> urls;
private URL url;
private String methodName;
private Class<?>[] parameterTypes;
private Object[] arguments;
private InetSocketAddress localAddress;
private InetSocketAddress remoteAddress;
private String remoteApplicationName;
private Boolean localInvoke;
@Deprecated
private List<Invoker<?>> invokers;
@Deprecated
private Invoker<?> invoker;
@Deprecated
private Invocation invocation;
// now we don't use the 'values' map to hold these objects
// we want these objects to be as generic as possible
private Object request;
private Object response;
private boolean needPrintRouterSnapshot;
/**
* Get the request object of the underlying RPC protocol, e.g. HttpServletRequest
*
* @return null if the underlying protocol doesn't provide support for getting request
*/
@Override
public Object getRequest() {
return request;
}
@Override
public void setRequest(Object request) {
this.request = request;
}
/**
* Get the request object of the underlying RPC protocol, e.g. HttpServletRequest
*
* @return null if the underlying protocol doesn't provide support for getting request or the request is not of the specified type
*/
@Override
@SuppressWarnings("unchecked")
public <T> T getRequest(Class<T> clazz) {
return (request != null && clazz.isAssignableFrom(request.getClass())) ? (T) request : null;
}
/**
* Get the response object of the underlying RPC protocol, e.g. HttpServletResponse
*
* @return null if the underlying protocol doesn't provide support for getting response
*/
@Override
public Object getResponse() {
return response;
}
@Override
public void setResponse(Object response) {
this.response = response;
}
/**
* Get the response object of the underlying RPC protocol, e.g. HttpServletResponse
*
* @return null if the underlying protocol doesn't provide support for getting response or the response is not of the specified type
*/
@Override
@SuppressWarnings("unchecked")
public <T> T getResponse(Class<T> clazz) {
return (response != null && clazz.isAssignableFrom(response.getClass())) ? (T) response : null;
}
/**
* is provider side.
*
* @return provider side.
*/
@Override
public boolean isProviderSide() {
return !isConsumerSide();
}
/**
* is consumer side.
*
* @return consumer side.
*/
@Override
public boolean isConsumerSide() {
return getUrl().getSide(PROVIDER_SIDE).equals(CONSUMER_SIDE);
}
/**
* get CompletableFuture.
*
* @param <T>
* @return future
*/
@Override
@SuppressWarnings("unchecked")
public <T> CompletableFuture<T> getCompletableFuture() {
return FutureContext.getContext().getCompletableFuture();
}
/**
* get future.
*
* @param <T>
* @return future
*/
@Override
@SuppressWarnings("unchecked")
public <T> Future<T> getFuture() {
return FutureContext.getContext().getCompletableFuture();
}
/**
* set future.
*
* @param future
*/
@Override
public void setFuture(CompletableFuture<?> future) {
FutureContext.getContext().setFuture(future);
}
@Override
public List<URL> getUrls() {
return urls == null && url != null ? Arrays.asList(url) : urls;
}
@Override
public void setUrls(List<URL> urls) {
this.urls = urls;
if (!urls.isEmpty()) {
this.url = urls.get(0);
}
}
@Override
public URL getUrl() {
return url;
}
@Override
public void setUrl(URL url) {
this.url = url;
}
/**
* get method name.
*
* @return method name.
*/
@Override
public String getMethodName() {
return methodName;
}
@Override
public void setMethodName(String methodName) {
this.methodName = methodName;
}
/**
* get parameter types.
*
* @serial
*/
@Override
public Class<?>[] getParameterTypes() {
return parameterTypes;
}
@Override
public void setParameterTypes(Class<?>[] parameterTypes) {
this.parameterTypes = parameterTypes;
}
/**
* get arguments.
*
* @return arguments.
*/
@Override
public Object[] getArguments() {
return arguments;
}
@Override
public void setArguments(Object[] arguments) {
this.arguments = arguments;
}
/**
* set local address.
*
* @param host
* @param port
* @return context
*/
@Override
public RpcServiceContext setLocalAddress(String host, int port) {
if (port < 0) {
port = 0;
}
this.localAddress = InetSocketAddress.createUnresolved(host, port);
return this;
}
/**
* get local address.
*
* @return local address
*/
@Override
public InetSocketAddress getLocalAddress() {
return localAddress;
}
/**
* set local address.
*
* @param address
* @return context
*/
@Override
public RpcServiceContext setLocalAddress(InetSocketAddress address) {
this.localAddress = address;
return this;
}
@Override
public String getLocalAddressString() {
return getLocalHost() + ":" + getLocalPort();
}
/**
* get local host name.
*
* @return local host name
*/
@Override
public String getLocalHostName() {
String host = localAddress == null ? null : localAddress.getHostName();
if (StringUtils.isEmpty(host)) {
return getLocalHost();
}
return host;
}
/**
* set remote address.
*
* @param host
* @param port
* @return context
*/
@Override
public RpcServiceContext setRemoteAddress(String host, int port) {
if (port < 0) {
port = 0;
}
this.remoteAddress = InetSocketAddress.createUnresolved(host, port);
return this;
}
/**
* get remote address.
*
* @return remote address
*/
@Override
public InetSocketAddress getRemoteAddress() {
return remoteAddress;
}
/**
* set remote address.
*
* @param address
* @return context
*/
@Override
public RpcServiceContext setRemoteAddress(InetSocketAddress address) {
this.remoteAddress = address;
return this;
}
@Override
public String getRemoteApplicationName() {
return remoteApplicationName;
}
@Override
public RpcServiceContext setRemoteApplicationName(String remoteApplicationName) {
this.remoteApplicationName = remoteApplicationName;
return this;
}
/**
* get remote address string.
*
* @return remote address string.
*/
@Override
public String getRemoteAddressString() {
return getRemoteHost() + ":" + getRemotePort();
}
/**
* get remote host name.
*
* @return remote host name
*/
@Override
public String getRemoteHostName() {
return remoteAddress == null ? null : remoteAddress.getHostName();
}
/**
* get local host.
*
* @return local host
*/
@Override
public String getLocalHost() {
String host = localAddress == null
? null
: localAddress.getAddress() == null
? localAddress.getHostName()
: NetUtils.filterLocalHost(localAddress.getAddress().getHostAddress());
if (host == null || host.length() == 0) {
return NetUtils.getLocalHost();
}
return host;
}
/**
* get local port.
*
* @return port
*/
@Override
public int getLocalPort() {
return localAddress == null ? 0 : localAddress.getPort();
}
/**
* get remote host.
*
* @return remote host
*/
@Override
public String getRemoteHost() {
return remoteAddress == null
? null
: remoteAddress.getAddress() == null
? remoteAddress.getHostName()
: NetUtils.filterLocalHost(remoteAddress.getAddress().getHostAddress());
}
/**
* get remote port.
*
* @return remote port
*/
@Override
public int getRemotePort() {
return remoteAddress == null ? 0 : remoteAddress.getPort();
}
/**
* @deprecated Replace to isProviderSide()
*/
@Override
@Deprecated
public boolean isServerSide() {
return isProviderSide();
}
/**
* @deprecated Replace to isConsumerSide()
*/
@Override
@Deprecated
public boolean isClientSide() {
return isConsumerSide();
}
/**
* @deprecated Replace to getUrls()
*/
@Override
@Deprecated
@SuppressWarnings({"unchecked", "rawtypes"})
public List<Invoker<?>> getInvokers() {
return invokers == null && invoker != null ? (List) Arrays.asList(invoker) : invokers;
}
@Override
public RpcServiceContext setInvokers(List<Invoker<?>> invokers) {
this.invokers = invokers;
if (CollectionUtils.isNotEmpty(invokers)) {
List<URL> urls = new ArrayList<URL>(invokers.size());
for (Invoker<?> invoker : invokers) {
urls.add(invoker.getUrl());
}
setUrls(urls);
}
return this;
}
/**
* @deprecated Replace to getUrl()
*/
@Override
@Deprecated
public Invoker<?> getInvoker() {
return invoker;
}
@Override
public RpcServiceContext setInvoker(Invoker<?> invoker) {
this.invoker = invoker;
if (invoker != null) {
setUrl(invoker.getUrl());
}
return this;
}
/**
* @deprecated Replace to getMethodName(), getParameterTypes(), getArguments()
*/
@Override
@Deprecated
public Invocation getInvocation() {
return invocation;
}
@Override
public RpcServiceContext setInvocation(Invocation invocation) {
this.invocation = invocation;
if (invocation != null) {
setMethodName(invocation.getMethodName());
setParameterTypes(invocation.getParameterTypes());
setArguments(invocation.getArguments());
}
return this;
}
/**
* Async invocation. Timeout will be handled even if <code>Future.get()</code> is not called.
*
* @param callable
* @return get the return result from <code>future.get()</code>
*/
@Override
@SuppressWarnings("unchecked")
public <T> CompletableFuture<T> asyncCall(Callable<T> callable) {
try {
try {
setAttachment(ASYNC_KEY, Boolean.TRUE.toString());
final T o = callable.call();
// local invoke will return directly
if (o != null) {
if (o instanceof CompletableFuture) {
return (CompletableFuture<T>) o;
}
return CompletableFuture.completedFuture(o);
} else {
// The service has a normal sync method signature, should get future from RpcContext.
}
} catch (Exception e) {
throw new RpcException(e);
} finally {
removeAttachment(ASYNC_KEY);
}
} catch (final RpcException e) {
CompletableFuture<T> exceptionFuture = new CompletableFuture<>();
exceptionFuture.completeExceptionally(e);
return exceptionFuture;
}
return ((CompletableFuture<T>) getServiceContext().getFuture());
}
/**
* one way async call, send request only, and result is not required
*
* @param runnable
*/
@Override
public void asyncCall(Runnable runnable) {
try {
setAttachment(RETURN_KEY, Boolean.FALSE.toString());
runnable.run();
} catch (Throwable e) {
// FIXME should put exception in future?
throw new RpcException("oneway call error ." + e.getMessage(), e);
} finally {
removeAttachment(RETURN_KEY);
}
}
@Override
public String getGroup() {
if (consumerUrl == null) {
return null;
}
return consumerUrl.getGroup();
}
@Override
public String getVersion() {
if (consumerUrl == null) {
return null;
}
return consumerUrl.getVersion();
}
@Override
public String getInterfaceName() {
if (consumerUrl == null) {
return null;
}
return consumerUrl.getServiceInterface();
}
@Override
public String getProtocol() {
if (consumerUrl == null) {
return null;
}
return consumerUrl.getProtocol();
}
@Override
public String getServiceKey() {
if (consumerUrl == null) {
return null;
}
return consumerUrl.getServiceKey();
}
@Override
public String getProtocolServiceKey() {
if (consumerUrl == null) {
return null;
}
return consumerUrl.getProtocolServiceKey();
}
@Override
public URL getConsumerUrl() {
return consumerUrl;
}
@Override
public void setConsumerUrl(URL consumerUrl) {
this.consumerUrl = consumerUrl;
}
public boolean isNeedPrintRouterSnapshot() {
return needPrintRouterSnapshot;
}
public void setNeedPrintRouterSnapshot(boolean needPrintRouterSnapshot) {
this.needPrintRouterSnapshot = needPrintRouterSnapshot;
}
public RpcServiceContext setLocalInvoke(boolean localInvoke) {
this.localInvoke = localInvoke;
return this;
}
public Boolean getLocalInvoke() {
return this.localInvoke;
}
/**
* Only part of the properties are copied, the others are either not used currently or can be got from invocation.
* Also see {@link RpcContextAttachment#copyOf(boolean)}
*
* @param needCopy
* @return a shallow copy of RpcServiceContext
*/
public RpcServiceContext copyOf(boolean needCopy) {
if (needCopy) {
RpcServiceContext copy = new RpcServiceContext();
copy.arguments = this.arguments;
copy.consumerUrl = this.consumerUrl;
copy.invocation = this.invocation;
copy.invokers = this.invokers;
copy.invoker = this.invoker;
copy.localAddress = this.localAddress;
copy.methodName = this.methodName;
copy.needPrintRouterSnapshot = this.needPrintRouterSnapshot;
copy.parameterTypes = this.parameterTypes;
copy.remoteAddress = this.remoteAddress;
copy.remoteApplicationName = this.remoteApplicationName;
copy.request = this.request;
copy.response = this.response;
copy.url = this.url;
copy.urls = this.urls;
return copy;
} else {
return this;
}
}
}
| 5,970 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ExporterListener.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.rpc;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* ExporterListener. (SPI, Singleton, ThreadSafe)
*/
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface ExporterListener {
/**
* The exporter exported.
*
* @param exporter
* @throws RpcException
* @see org.apache.dubbo.rpc.Protocol#export(Invoker)
*/
void exported(Exporter<?> exporter) throws RpcException;
/**
* The exporter unexported.
*
* @param exporter
* @throws RpcException
* @see org.apache.dubbo.rpc.Exporter#unexport()
*/
void unexported(Exporter<?> exporter);
}
| 5,971 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Result.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.rpc;
import org.apache.dubbo.common.Experimental;
import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiConsumer;
import java.util.function.Function;
/**
* (API, Prototype, NonThreadSafe)
*
* An RPC {@link Result}.
*
* Known implementations are:
* 1. {@link AsyncRpcResult}, it's a {@link CompletionStage} whose underlying value signifies the return value of an RPC call.
* 2. {@link AppResponse}, it inevitably inherits {@link CompletionStage} and {@link Future}, but you should never treat AppResponse as a type of Future,
* instead, it is a normal concrete type.
*
* @serial Don't change the class name and package name.
* @see org.apache.dubbo.rpc.Invoker#invoke(Invocation)
* @see AppResponse
*/
public interface Result extends Serializable {
/**
* Get invoke result.
*
* @return result. if no result return null.
*/
Object getValue();
void setValue(Object value);
/**
* Get exception.
*
* @return exception. if no exception return null.
*/
Throwable getException();
void setException(Throwable t);
/**
* Has exception.
*
* @return has exception.
*/
boolean hasException();
/**
* Recreate.
* <p>
* <code>
* if (hasException()) {
* throw getException();
* } else {
* return getValue();
* }
* </code>
*
* @return result.
* @throws if has exception throw it.
*/
Object recreate() throws Throwable;
/**
* get attachments.
*
* @return attachments.
*/
Map<String, String> getAttachments();
/**
* get attachments.
*
* @return attachments.
*/
@Experimental("Experiment api for supporting Object transmission")
Map<String, Object> getObjectAttachments();
/**
* Add the specified map to existing attachments in this instance.
*
* @param map
*/
void addAttachments(Map<String, String> map);
/**
* Add the specified map to existing attachments in this instance.
*
* @param map
*/
@Experimental("Experiment api for supporting Object transmission")
void addObjectAttachments(Map<String, Object> map);
/**
* Replace the existing attachments with the specified param.
*
* @param map
*/
void setAttachments(Map<String, String> map);
/**
* Replace the existing attachments with the specified param.
*
* @param map
*/
@Experimental("Experiment api for supporting Object transmission")
void setObjectAttachments(Map<String, Object> map);
/**
* get attachment by key.
*
* @return attachment value.
*/
String getAttachment(String key);
/**
* get attachment by key.
*
* @return attachment value.
*/
@Experimental("Experiment api for supporting Object transmission")
Object getObjectAttachment(String key);
/**
* get attachment by key with default value.
*
* @return attachment value.
*/
String getAttachment(String key, String defaultValue);
/**
* get attachment by key with default value.
*
* @return attachment value.
*/
@Experimental("Experiment api for supporting Object transmission")
Object getObjectAttachment(String key, Object defaultValue);
void setAttachment(String key, String value);
@Experimental("Experiment api for supporting Object transmission")
void setAttachment(String key, Object value);
@Experimental("Experiment api for supporting Object transmission")
void setObjectAttachment(String key, Object value);
/**
* Add a callback which can be triggered when the RPC call finishes.
* <p>
* Just as the method name implies, this method will guarantee the callback being triggered under the same context as when the call was started,
* see implementation in {@link Result#whenCompleteWithContext(BiConsumer)}
*
* @param fn
* @return
*/
Result whenCompleteWithContext(BiConsumer<Result, Throwable> fn);
<U> CompletableFuture<U> thenApply(Function<Result, ? extends U> fn);
Result get() throws InterruptedException, ExecutionException;
Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
}
| 5,972 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcScopeModelInitializer.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.rpc;
import org.apache.dubbo.common.beans.factory.ScopeBeanFactory;
import org.apache.dubbo.rpc.listener.InjvmExporterListener;
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;
import org.apache.dubbo.rpc.protocol.PermittedSerializationKeeper;
public class RpcScopeModelInitializer implements ScopeModelInitializer {
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {
ScopeBeanFactory beanFactory = frameworkModel.getBeanFactory();
beanFactory.registerBean(InjvmExporterListener.class);
beanFactory.registerBean(PermittedSerializationKeeper.class);
}
@Override
public void initializeApplicationModel(ApplicationModel applicationModel) {}
@Override
public void initializeModuleModel(ModuleModel moduleModel) {}
}
| 5,973 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcServerContextAttachment.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.rpc;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class RpcServerContextAttachment extends RpcContextAttachment {
@Override
public RpcContextAttachment copyOf(boolean needCopy) {
throw new RuntimeException("copyOf internal method, should not be invoke");
}
@Override
protected boolean isValid() {
throw new RuntimeException("isValid of is internal method, should not be invoke");
}
@Override
public RpcContextAttachment setObjectAttachment(String key, Object value) {
RpcContext.getServerResponseContext().setObjectAttachment(key, value);
return this;
}
@Override
protected void setAsyncContext(AsyncContext asyncContext) {
RpcContext.getServerResponseContext().setAsyncContext(asyncContext);
}
@Override
public boolean isAsyncStarted() {
return RpcContext.getServerResponseContext().isAsyncStarted();
}
@Override
public boolean stopAsync() {
return RpcContext.getServerResponseContext().stopAsync();
}
@Override
public AsyncContext getAsyncContext() {
return RpcContext.getServerResponseContext().getAsyncContext();
}
@Override
public String getAttachment(String key) {
Object attachment = getObjectAttachment(key);
if (attachment instanceof String) {
return (String) attachment;
}
return null;
}
@Override
public Object getObjectAttachment(String key) {
Object fromServerResponse = RpcContext.getServerResponseContext().getObjectAttachment(key);
if (fromServerResponse == null) {
fromServerResponse = RpcContext.getClientResponseContext().getObjectAttachment(key);
}
return fromServerResponse;
}
@Override
public RpcContextAttachment setAttachment(String key, String value) {
return RpcContext.getServerResponseContext().setAttachment(key, value);
}
@Override
public RpcContextAttachment setAttachment(String key, Object value) {
return RpcContext.getServerResponseContext().setAttachment(key, value);
}
@Override
public RpcContextAttachment removeAttachment(String key) {
RpcContext.getServerResponseContext().removeAttachment(key);
RpcContext.getClientResponseContext().removeAttachment(key);
return this;
}
@Override
public Map<String, String> getAttachments() {
return new AttachmentsAdapter.ObjectToStringMap(new ObjectAttachmentMap(this));
}
@Override
public Map<String, Object> getObjectAttachments() {
return new ObjectAttachmentMap(this);
}
@Override
public RpcContextAttachment setAttachments(Map<String, String> attachment) {
RpcContext.getServerResponseContext().setAttachments(attachment);
RpcContext.getClientResponseContext().clearAttachments();
return this;
}
@Override
public RpcContextAttachment setObjectAttachments(Map<String, Object> attachment) {
RpcContext.getServerResponseContext().setObjectAttachments(attachment);
RpcContext.getClientResponseContext().clearAttachments();
return this;
}
@Override
public void clearAttachments() {
RpcContext.getServerResponseContext().clearAttachments();
RpcContext.getClientResponseContext().clearAttachments();
}
@Override
public Map<String, Object> get() {
return getObjectAttachments();
}
@Override
public RpcContextAttachment set(String key, Object value) {
return setAttachment(key, value);
}
@Override
public RpcContextAttachment remove(String key) {
return removeAttachment(key);
}
@Override
public Object get(String key) {
return getAttachment(key);
}
static class ObjectAttachmentMap implements Map<String, Object> {
private final RpcServerContextAttachment adapter;
public ObjectAttachmentMap(RpcServerContextAttachment adapter) {
this.adapter = adapter;
}
private Map<String, Object> getAttachments() {
Map<String, Object> clientResponse =
RpcContext.getClientResponseContext().getObjectAttachments();
Map<String, Object> serverResponse =
RpcContext.getServerResponseContext().getObjectAttachments();
Map<String, Object> result =
new HashMap<>((int) (clientResponse.size() + serverResponse.size() / 0.75) + 1);
result.putAll(clientResponse);
result.putAll(serverResponse);
return result;
}
@Override
public int size() {
return getAttachments().size();
}
@Override
public boolean isEmpty() {
return RpcContext.getClientResponseContext().getObjectAttachments().isEmpty()
&& RpcContext.getServerResponseContext()
.getObjectAttachments()
.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return RpcContext.getClientResponseContext().getObjectAttachments().containsKey(key)
|| RpcContext.getServerResponseContext()
.getObjectAttachments()
.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return RpcContext.getClientResponseContext().getObjectAttachments().containsValue(value)
|| RpcContext.getServerResponseContext()
.getObjectAttachments()
.containsValue(value);
}
@Override
public Object get(Object key) {
if (key instanceof String) {
return adapter.getObjectAttachment((String) key);
} else {
return null;
}
}
@Override
public Object put(String key, Object value) {
return adapter.setObjectAttachment(key, value);
}
@Override
public Object remove(Object key) {
if (key instanceof String) {
return adapter.removeAttachment((String) key);
} else {
return null;
}
}
@Override
public void putAll(Map<? extends String, ?> m) {
for (Entry<? extends String, ?> entry : m.entrySet()) {
adapter.setObjectAttachment(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
adapter.clearAttachments();
}
@Override
public Set<String> keySet() {
return getAttachments().keySet();
}
@Override
public Collection<Object> values() {
return getAttachments().values();
}
@Override
public Set<Entry<String, Object>> entrySet() {
return getAttachments().entrySet();
}
}
}
| 5,974 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ProtocolServer.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.rpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.RemotingServer;
import java.util.Map;
/**
* Distinct from {@link RemotingServer}, each protocol holds one or more ProtocolServers(the number usually decides by port numbers),
* while each ProtocolServer holds zero or one RemotingServer.
*/
public interface ProtocolServer {
default RemotingServer getRemotingServer() {
return null;
}
default void setRemotingServers(RemotingServer server) {}
String getAddress();
void setAddress(String address);
default URL getUrl() {
return null;
}
default void reset(URL url) {}
void close();
Map<String, Object> getAttributes();
}
| 5,975 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcConstants.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.rpc;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.constants.FilterConstants;
import org.apache.dubbo.common.constants.QosConstants;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.constants.RemotingConstants;
/**
* RpcConstants
*
* @deprecated Replace to org.apache.dubbo.common.Constants
*/
@Deprecated
public final class RpcConstants
implements CommonConstants, QosConstants, FilterConstants, RegistryConstants, RemotingConstants {
private RpcConstants() {}
}
| 5,976 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/RpcInvocation.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.rpc;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.model.ServiceModel;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.stream.Stream;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;
/**
* RPC Invocation.
*
* @serial Don't change the class name and properties.
*/
public class RpcInvocation implements Invocation, Serializable {
private static final long serialVersionUID = -4355285085441097045L;
private String targetServiceUniqueName;
private String protocolServiceKey;
private ServiceModel serviceModel;
private String methodName;
private String interfaceName;
private transient Class<?>[] parameterTypes;
private String parameterTypesDesc;
private String[] compatibleParamSignatures;
private Object[] arguments;
/**
* Passed to the remote server during RPC call
*/
private Map<String, Object> attachments;
private final transient Lock attachmentLock = new ReentrantLock();
/**
* Only used on the caller side, will not appear on the wire.
*/
private transient Map<Object, Object> attributes = Collections.synchronizedMap(new HashMap<>());
private transient Invoker<?> invoker;
private transient Class<?> returnType;
private transient Type[] returnTypes;
private transient InvokeMode invokeMode;
private transient List<Invoker<?>> invokedInvokers = new LinkedList<>();
/**
* @deprecated only for test
*/
@Deprecated
public RpcInvocation() {}
/**
* Deep clone of an invocation
*
* @param invocation original invocation
*/
public RpcInvocation(Invocation invocation) {
this(invocation, null);
}
/**
* Deep clone of an invocation & put some service params into attachment from invoker (will not change the invoker in invocation)
*
* @param invocation original invocation
* @param invoker target invoker
*/
public RpcInvocation(Invocation invocation, Invoker<?> invoker) {
this(
invocation.getTargetServiceUniqueName(),
invocation.getServiceModel(),
invocation.getMethodName(),
invocation.getServiceName(),
invocation.getProtocolServiceKey(),
invocation.getParameterTypes(),
invocation.getArguments(),
invocation.copyObjectAttachments(),
invocation.getInvoker(),
invocation.getAttributes(),
invocation instanceof RpcInvocation ? ((RpcInvocation) invocation).getInvokeMode() : null);
if (invoker != null) {
URL url = invoker.getUrl();
setAttachment(PATH_KEY, url.getPath());
if (url.hasParameter(INTERFACE_KEY)) {
setAttachment(INTERFACE_KEY, url.getParameter(INTERFACE_KEY));
}
if (url.hasParameter(GROUP_KEY)) {
setAttachment(GROUP_KEY, url.getGroup());
}
if (url.hasParameter(VERSION_KEY)) {
setAttachment(VERSION_KEY, url.getVersion("0.0.0"));
}
if (url.hasParameter(TIMEOUT_KEY)) {
setAttachment(TIMEOUT_KEY, url.getParameter(TIMEOUT_KEY));
}
if (url.hasParameter(TOKEN_KEY)) {
setAttachment(TOKEN_KEY, url.getParameter(TOKEN_KEY));
}
if (url.hasParameter(APPLICATION_KEY)) {
setAttachment(APPLICATION_KEY, url.getApplication());
}
}
}
/**
* To create a brand-new invocation
*/
public RpcInvocation(
ServiceModel serviceModel,
String methodName,
String interfaceName,
String protocolServiceKey,
Class<?>[] parameterTypes,
Object[] arguments) {
this(
null,
serviceModel,
methodName,
interfaceName,
protocolServiceKey,
parameterTypes,
arguments,
null,
null,
null,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
ServiceModel serviceModel,
Method method,
String interfaceName,
String protocolServiceKey,
Object[] arguments) {
this(
null,
serviceModel,
method.getName(),
interfaceName,
protocolServiceKey,
method.getParameterTypes(),
arguments,
null,
null,
null,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(Method method, String interfaceName, String protocolServiceKey, Object[] arguments) {
this(
null,
null,
method.getName(),
interfaceName,
protocolServiceKey,
method.getParameterTypes(),
arguments,
null,
null,
null,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
ServiceModel serviceModel,
Method method,
String interfaceName,
String protocolServiceKey,
Object[] arguments,
Map<String, Object> attachment,
Map<Object, Object> attributes) {
this(
null,
serviceModel,
method.getName(),
interfaceName,
protocolServiceKey,
method.getParameterTypes(),
arguments,
attachment,
null,
attributes,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
Method method,
String interfaceName,
String protocolServiceKey,
Object[] arguments,
Map<String, Object> attachment,
Map<Object, Object> attributes) {
this(
null,
null,
method.getName(),
interfaceName,
protocolServiceKey,
method.getParameterTypes(),
arguments,
attachment,
null,
attributes,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
String methodName,
String interfaceName,
String protocolServiceKey,
Class<?>[] parameterTypes,
Object[] arguments) {
this(
null,
null,
methodName,
interfaceName,
protocolServiceKey,
parameterTypes,
arguments,
null,
null,
null,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
ServiceModel serviceModel,
String methodName,
String interfaceName,
String protocolServiceKey,
Class<?>[] parameterTypes,
Object[] arguments,
Map<String, Object> attachments) {
this(
null,
serviceModel,
methodName,
interfaceName,
protocolServiceKey,
parameterTypes,
arguments,
attachments,
null,
null,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
String methodName,
String interfaceName,
String protocolServiceKey,
Class<?>[] parameterTypes,
Object[] arguments,
Map<String, Object> attachments) {
this(
null,
null,
methodName,
interfaceName,
protocolServiceKey,
parameterTypes,
arguments,
attachments,
null,
null,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
String methodName,
String interfaceName,
String protocolServiceKey,
Class<?>[] parameterTypes,
Object[] arguments,
Map<String, Object> attachments,
Invoker<?> invoker,
Map<Object, Object> attributes) {
this(
null,
null,
methodName,
interfaceName,
protocolServiceKey,
parameterTypes,
arguments,
attachments,
invoker,
attributes,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
ServiceModel serviceModel,
String methodName,
String interfaceName,
String protocolServiceKey,
Class<?>[] parameterTypes,
Object[] arguments,
Map<String, Object> attachments,
Invoker<?> invoker,
Map<Object, Object> attributes) {
this(
null,
serviceModel,
methodName,
interfaceName,
protocolServiceKey,
parameterTypes,
arguments,
attachments,
invoker,
attributes,
null);
}
/**
* @deprecated deprecated, will be removed in 3.1.x
*/
@Deprecated
public RpcInvocation(
ServiceModel serviceModel,
String methodName,
String interfaceName,
String protocolServiceKey,
Class<?>[] parameterTypes,
Object[] arguments,
Map<String, Object> attachments,
Invoker<?> invoker,
Map<Object, Object> attributes,
InvokeMode invokeMode) {
this(
null,
serviceModel,
methodName,
interfaceName,
protocolServiceKey,
parameterTypes,
arguments,
attachments,
invoker,
attributes,
invokeMode);
}
/**
* To create a brand-new invocation
*/
public RpcInvocation(
String targetServiceUniqueName,
ServiceModel serviceModel,
String methodName,
String interfaceName,
String protocolServiceKey,
Class<?>[] parameterTypes,
Object[] arguments,
Map<String, Object> attachments,
Invoker<?> invoker,
Map<Object, Object> attributes,
InvokeMode invokeMode) {
this.targetServiceUniqueName = targetServiceUniqueName;
this.serviceModel = serviceModel;
this.methodName = methodName;
this.interfaceName = interfaceName;
this.protocolServiceKey = protocolServiceKey;
this.parameterTypes = parameterTypes == null ? new Class<?>[0] : parameterTypes;
this.arguments = arguments == null ? new Object[0] : arguments;
this.attachments = attachments == null ? new HashMap<>() : attachments;
this.attributes = attributes == null ? Collections.synchronizedMap(new HashMap<>()) : attributes;
this.invoker = invoker;
initParameterDesc();
this.invokeMode = invokeMode;
}
private void initParameterDesc() {
AtomicReference<ServiceDescriptor> serviceDescriptor = new AtomicReference<>();
if (serviceModel != null) {
serviceDescriptor.set(serviceModel.getServiceModel());
} else if (StringUtils.isNotEmpty(interfaceName)) {
// TODO: Multi Instance compatible mode
FrameworkModel.defaultModel().getServiceRepository().allProviderModels().stream()
.map(ProviderModel::getServiceModel)
.filter(s -> interfaceName.equals(s.getInterfaceName()))
.findFirst()
.ifPresent(serviceDescriptor::set);
}
if (serviceDescriptor.get() != null) {
MethodDescriptor methodDescriptor = serviceDescriptor.get().getMethod(methodName, parameterTypes);
if (methodDescriptor != null) {
this.parameterTypesDesc = methodDescriptor.getParamDesc();
this.compatibleParamSignatures = methodDescriptor.getCompatibleParamSignatures();
this.returnTypes = methodDescriptor.getReturnTypes();
this.returnType = methodDescriptor.getReturnClass();
}
}
if (parameterTypesDesc == null) {
this.parameterTypesDesc = ReflectUtils.getDesc(this.getParameterTypes());
this.compatibleParamSignatures =
Stream.of(this.parameterTypes).map(Class::getName).toArray(String[]::new);
this.returnTypes = RpcUtils.getReturnTypes(this);
this.returnType = RpcUtils.getReturnType(this);
}
}
@Override
public Invoker<?> getInvoker() {
return invoker;
}
public void setInvoker(Invoker<?> invoker) {
this.invoker = invoker;
}
@Override
public Object put(Object key, Object value) {
return attributes.put(key, value);
}
@Override
public Object get(Object key) {
return attributes.get(key);
}
@Override
public Map<Object, Object> getAttributes() {
return attributes;
}
@Override
public void addInvokedInvoker(Invoker<?> invoker) {
this.invokedInvokers.add(invoker);
}
@Override
public List<Invoker<?>> getInvokedInvokers() {
return this.invokedInvokers;
}
@Override
public String getTargetServiceUniqueName() {
return targetServiceUniqueName;
}
public void setTargetServiceUniqueName(String targetServiceUniqueName) {
this.targetServiceUniqueName = targetServiceUniqueName;
}
@Override
public String getProtocolServiceKey() {
return protocolServiceKey;
}
@Override
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
@Override
public String getServiceName() {
return interfaceName;
}
public void setServiceName(String interfaceName) {
this.interfaceName = interfaceName;
}
@Override
public Class<?>[] getParameterTypes() {
return parameterTypes;
}
public void setParameterTypes(Class<?>[] parameterTypes) {
this.parameterTypes = parameterTypes == null ? new Class<?>[0] : parameterTypes;
}
public String getParameterTypesDesc() {
return parameterTypesDesc;
}
public void setParameterTypesDesc(String parameterTypesDesc) {
this.parameterTypesDesc = parameterTypesDesc;
}
@Override
public String[] getCompatibleParamSignatures() {
return compatibleParamSignatures;
}
// parameter signatures can be set independently, it is useful when the service type is not found on caller side and
// the invocation is not generic invocation either.
public void setCompatibleParamSignatures(String[] compatibleParamSignatures) {
this.compatibleParamSignatures = compatibleParamSignatures;
}
@Override
public Object[] getArguments() {
return arguments;
}
public void setArguments(Object[] arguments) {
this.arguments = arguments == null ? new Object[0] : arguments;
}
@Override
public Map<String, Object> getObjectAttachments() {
try {
attachmentLock.lock();
if (attachments == null) {
attachments = new HashMap<>();
}
return attachments;
} finally {
attachmentLock.unlock();
}
}
@Override
public Map<String, Object> copyObjectAttachments() {
try {
attachmentLock.lock();
if (attachments == null) {
return new HashMap<>();
}
return new HashMap<>(attachments);
} finally {
attachmentLock.unlock();
}
}
@Override
public void foreachAttachment(Consumer<Map.Entry<String, Object>> consumer) {
try {
attachmentLock.lock();
if (attachments != null) {
attachments.entrySet().forEach(consumer);
}
} finally {
attachmentLock.unlock();
}
}
public void setObjectAttachments(Map<String, Object> attachments) {
try {
attachmentLock.lock();
this.attachments = attachments == null ? new HashMap<>() : attachments;
} finally {
attachmentLock.unlock();
}
}
@Override
public void setAttachment(String key, String value) {
setObjectAttachment(key, value);
}
@Deprecated
@Override
public Map<String, String> getAttachments() {
try {
attachmentLock.lock();
if (attachments == null) {
attachments = new HashMap<>();
}
return new AttachmentsAdapter.ObjectToStringMap(attachments);
} finally {
attachmentLock.unlock();
}
}
@Deprecated
public void setAttachments(Map<String, String> attachments) {
try {
attachmentLock.lock();
this.attachments = attachments == null ? new HashMap<>() : new HashMap<>(attachments);
} finally {
attachmentLock.unlock();
}
}
@Override
public void setAttachment(String key, Object value) {
setObjectAttachment(key, value);
}
@Override
public void setObjectAttachment(String key, Object value) {
try {
attachmentLock.lock();
if (attachments == null) {
attachments = new HashMap<>();
}
attachments.put(key, value);
} finally {
attachmentLock.unlock();
}
}
@Override
public void setAttachmentIfAbsent(String key, String value) {
setObjectAttachmentIfAbsent(key, value);
}
@Override
public void setAttachmentIfAbsent(String key, Object value) {
setObjectAttachmentIfAbsent(key, value);
}
@Override
public void setObjectAttachmentIfAbsent(String key, Object value) {
try {
attachmentLock.lock();
if (attachments == null) {
attachments = new HashMap<>();
}
if (!attachments.containsKey(key)) {
attachments.put(key, value);
}
} finally {
attachmentLock.unlock();
}
}
@Deprecated
public void addAttachments(Map<String, String> attachments) {
try {
attachmentLock.lock();
if (attachments == null) {
return;
}
if (this.attachments == null) {
this.attachments = new HashMap<>();
}
this.attachments.putAll(attachments);
} finally {
attachmentLock.unlock();
}
}
public void addObjectAttachments(Map<String, Object> attachments) {
try {
attachmentLock.lock();
if (attachments == null) {
return;
}
if (this.attachments == null) {
this.attachments = new HashMap<>();
}
this.attachments.putAll(attachments);
} finally {
attachmentLock.unlock();
}
}
@Deprecated
public void addAttachmentsIfAbsent(Map<String, String> attachments) {
if (attachments == null) {
return;
}
for (Map.Entry<String, String> entry : attachments.entrySet()) {
setAttachmentIfAbsent(entry.getKey(), entry.getValue());
}
}
public void addObjectAttachmentsIfAbsent(Map<String, Object> attachments) {
if (attachments == null) {
return;
}
for (Map.Entry<String, Object> entry : attachments.entrySet()) {
setAttachmentIfAbsent(entry.getKey(), entry.getValue());
}
}
@Override
@Deprecated
public String getAttachment(String key) {
try {
attachmentLock.lock();
if (attachments == null) {
return null;
}
Object value = attachments.get(key);
if (value instanceof String) {
return (String) value;
}
return null;
} finally {
attachmentLock.unlock();
}
}
@Override
public Object getObjectAttachment(String key) {
try {
attachmentLock.lock();
if (attachments == null) {
return null;
}
final Object val = attachments.get(key);
if (val != null) {
return val;
}
return attachments.get(key.toLowerCase(Locale.ROOT));
} finally {
attachmentLock.unlock();
}
}
@Override
@Deprecated
public String getAttachment(String key, String defaultValue) {
try {
attachmentLock.lock();
if (attachments == null) {
return defaultValue;
}
Object value = attachments.get(key);
if (value instanceof String) {
String strValue = (String) value;
if (StringUtils.isEmpty(strValue)) {
return defaultValue;
} else {
return strValue;
}
}
return defaultValue;
} finally {
attachmentLock.unlock();
}
}
@Deprecated
@Override
public Object getObjectAttachment(String key, Object defaultValue) {
try {
attachmentLock.lock();
if (attachments == null) {
return defaultValue;
}
Object value = attachments.get(key);
if (value == null) {
return defaultValue;
}
return value;
} finally {
attachmentLock.unlock();
}
}
@Override
public Object getObjectAttachmentWithoutConvert(String key) {
try {
attachmentLock.lock();
if (attachments == null) {
return null;
}
return attachments.get(key);
} finally {
attachmentLock.unlock();
}
}
public Class<?> getReturnType() {
return returnType;
}
public void setReturnType(Class<?> returnType) {
this.returnType = returnType;
}
public Type[] getReturnTypes() {
return returnTypes;
}
public void setReturnTypes(Type[] returnTypes) {
this.returnTypes = returnTypes;
}
public InvokeMode getInvokeMode() {
return invokeMode;
}
public void setInvokeMode(InvokeMode invokeMode) {
this.invokeMode = invokeMode;
}
@Override
public void setServiceModel(ServiceModel serviceModel) {
this.serviceModel = serviceModel;
}
@Override
public ServiceModel getServiceModel() {
return serviceModel;
}
@Override
public String toString() {
return "RpcInvocation [methodName=" + methodName + ", parameterTypes=" + Arrays.toString(parameterTypes) + "]";
}
}
| 5,977 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/GracefulShutdown.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.rpc;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.List;
public interface GracefulShutdown {
void readonly();
void writeable();
static List<GracefulShutdown> getGracefulShutdowns(FrameworkModel frameworkModel) {
return frameworkModel.getBeanFactory().getBeansOfType(GracefulShutdown.class);
}
}
| 5,978 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Invoker.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.rpc;
import org.apache.dubbo.common.Node;
/**
* Invoker. (API/SPI, Prototype, ThreadSafe)
*
* @see org.apache.dubbo.rpc.Protocol#refer(Class, org.apache.dubbo.common.URL)
* @see org.apache.dubbo.rpc.InvokerListener
* @see org.apache.dubbo.rpc.protocol.AbstractInvoker
*/
public interface Invoker<T> extends Node {
/**
* get service interface.
*
* @return service interface.
*/
Class<T> getInterface();
/**
* invoke.
*
* @param invocation
* @return result
* @throws RpcException
*/
Result invoke(Invocation invocation) throws RpcException;
}
| 5,979 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/ZoneDetector.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.rpc;
import org.apache.dubbo.common.extension.SPI;
/**
* Extend and provide your own implementation if you want to distribute traffic around registries.
* Please, name it as 'default'
*/
@SPI
public interface ZoneDetector {
String getZoneOfCurrentRequest(Invocation invocation);
String isZoneForcingEnabled(Invocation invocation, String zone);
}
| 5,980 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/PathResolver.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.rpc;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* PathResolver maintains a mapping between request path and Invoker for multiple protocols.
*/
@SPI(value = CommonConstants.TRIPLE, scope = ExtensionScope.FRAMEWORK)
public interface PathResolver {
Invoker<?> add(String path, Invoker<?> invoker);
Invoker<?> addIfAbsent(String path, Invoker<?> invoker);
Invoker<?> resolve(String path);
boolean hasNativeStub(String path);
void addNativeStub(String path);
void remove(String path);
void destroy();
}
| 5,981 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Filter.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.rpc;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* Extension for intercepting the invocation for both service provider and consumer, furthermore, most of
* functions in dubbo are implemented base on the same mechanism. Since every time when remote method is
* invoked, the filter extensions will be executed too, the corresponding penalty should be considered before
* more filters are added.
* <pre>
* They way filter work from sequence point of view is
* <b>
* ...code before filter ...
* invoker.invoke(invocation) //filter work in a filter implementation class
* ...code after filter ...
* </b>
* Caching is implemented in dubbo using filter approach. If cache is configured for invocation then before
* remote call configured caching type's (e.g. Thread Local, JCache etc) implementation invoke method gets called.
* </pre>
*
* Starting from 3.0, Filter on consumer side has been refactored. There are two different kinds of Filters working at different stages
* of an RPC request.
* 1. Filter. Works at the instance level, each Filter is bond to one specific Provider instance(invoker).
* 2. ClusterFilter. Newly introduced in 3.0, intercepts request before Loadbalancer picks one specific Filter(Invoker).
*
* Filter Chain in 3.x
*
* -> Filter -> Invoker
*
* Proxy -> ClusterFilter -> ClusterInvoker -> Filter -> Invoker
*
* -> Filter -> Invoker
*
*
* Filter Chain in 2.x
*
* Filter -> Invoker
*
* Proxy -> ClusterInvoker -> Filter -> Invoker
*
* Filter -> Invoker
*
*
* Filter. (SPI, Singleton, ThreadSafe)
*
* @see org.apache.dubbo.rpc.filter.GenericFilter
* @see org.apache.dubbo.rpc.filter.EchoFilter
* @see org.apache.dubbo.rpc.filter.TokenFilter
* @see org.apache.dubbo.rpc.filter.TpsLimitFilter
*/
@SPI(scope = ExtensionScope.MODULE)
public interface Filter extends BaseFilter {}
| 5,982 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Exporter.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.rpc;
/**
* Exporter. (API/SPI, Prototype, ThreadSafe)
*
* @see org.apache.dubbo.rpc.Protocol#export(Invoker)
* @see org.apache.dubbo.rpc.ExporterListener
* @see org.apache.dubbo.rpc.protocol.AbstractExporter
*/
public interface Exporter<T> {
/**
* get invoker.
*
* @return invoker
*/
Invoker<T> getInvoker();
/**
* unexport.
* <p>
* <code>
* getInvoker().destroy();
* </code>
*/
void unexport();
/**
* register to registry
*/
void register();
/**
* unregister from registry
*/
void unregister();
}
| 5,983 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/Constants.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.rpc;
public interface Constants {
String LOCAL_KEY = "local";
String STUB_KEY = "stub";
String MOCK_KEY = "mock";
String DEPRECATED_KEY = "deprecated";
String $ECHO = "$echo";
String $ECHO_PARAMETER_DESC = "Ljava/lang/Object;";
String RETURN_PREFIX = "return ";
String THROW_PREFIX = "throw";
String FAIL_PREFIX = "fail:";
String FORCE_PREFIX = "force:";
String MERGER_KEY = "merger";
String IS_SERVER_KEY = "isserver";
String FORCE_USE_TAG = "dubbo.force.tag";
String TPS_LIMIT_RATE_KEY = "tps";
String TPS_LIMIT_INTERVAL_KEY = "tps.interval";
long DEFAULT_TPS_LIMIT_INTERVAL = 60 * 1000;
String AUTO_ATTACH_INVOCATIONID_KEY = "invocationid.autoattach";
boolean DEFAULT_STUB_EVENT = false;
String STUB_EVENT_METHODS_KEY = "dubbo.stub.event.methods";
String COMPRESSOR_KEY = "dubbo.rpc.tri.compressor";
String PROXY_KEY = "proxy";
String EXECUTES_KEY = "executes";
String ACCESS_LOG_KEY = "accesslog";
String ACCESS_LOG_FIXED_PATH_KEY = "accesslog.fixed.path";
String ACTIVES_KEY = "actives";
String ID_KEY = "id";
String ASYNC_KEY = "async";
String RETURN_KEY = "return";
String TOKEN_KEY = "token";
String INTERFACE = "interface";
String INTERFACES = "interfaces";
String GENERIC_KEY = "generic";
String LOCAL_PROTOCOL = "injvm";
String DEFAULT_REMOTING_SERVER = "netty";
String SCOPE_KEY = "scope";
String SCOPE_LOCAL = "local";
String SCOPE_REMOTE = "remote";
String INPUT_KEY = "input";
String OUTPUT_KEY = "output";
String CONSUMER_MODEL = "consumerModel";
String METHOD_MODEL = "methodModel";
String SERIALIZATION_SECURITY_CHECK_KEY = "serialization.security.check";
String INVOCATION_KEY = "invocation";
String SERIALIZATION_ID_KEY = "serialization_id";
String H2_SETTINGS_HEADER_TABLE_SIZE_KEY = "dubbo.rpc.tri.header-table-size";
String H2_SETTINGS_ENABLE_PUSH_KEY = "dubbo.rpc.tri.enable-push";
String H2_SETTINGS_MAX_CONCURRENT_STREAMS_KEY = "dubbo.rpc.tri.max-concurrent-streams";
String H2_SETTINGS_INITIAL_WINDOW_SIZE_KEY = "dubbo.rpc.tri.initial-window-size";
String H2_SETTINGS_MAX_FRAME_SIZE_KEY = "dubbo.rpc.tri.max-frame-size";
String H2_SETTINGS_MAX_HEADER_LIST_SIZE_KEY = "dubbo.rpc.tri.max-header-list-size";
String ADAPTIVE_LOADBALANCE_ATTACHMENT_KEY = "lb_adaptive";
String ADAPTIVE_LOADBALANCE_START_TIME = "adaptive_startTime";
String H2_SUPPORT_NO_LOWER_HEADER_KEY = "dubbo.rpc.tri.support-no-lower-header";
String TRI_BUILTIN_SERVICE_INIT = "dubbo.tri.builtin.service.init";
String H2_IGNORE_1_0_0_KEY = "dubbo.rpc.tri.ignore-1.0.0-version";
String H2_RESOLVE_FALLBACK_TO_DEFAULT_KEY = "dubbo.rpc.tri.resolve-fallback-to-default";
}
| 5,984 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerInvokerWrapper.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.rpc.listener;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.InvokerListener;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import java.util.List;
import java.util.function.Consumer;
/**
* ListenerInvoker
*/
public class ListenerInvokerWrapper<T> implements Invoker<T> {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ListenerInvokerWrapper.class);
private final Invoker<T> invoker;
private final List<InvokerListener> listeners;
public ListenerInvokerWrapper(Invoker<T> invoker, List<InvokerListener> listeners) {
if (invoker == null) {
throw new IllegalArgumentException("invoker == null");
}
this.invoker = invoker;
this.listeners = listeners;
listenerEvent(listener -> listener.referred(invoker));
}
@Override
public Class<T> getInterface() {
return invoker.getInterface();
}
@Override
public URL getUrl() {
return invoker.getUrl();
}
@Override
public boolean isAvailable() {
return invoker.isAvailable();
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
}
@Override
public String toString() {
return getInterface() + " -> " + (getUrl() == null ? " " : getUrl().toString());
}
@Override
public void destroy() {
try {
invoker.destroy();
} finally {
listenerEvent(listener -> listener.destroyed(invoker));
}
}
public Invoker<T> getInvoker() {
return invoker;
}
public List<InvokerListener> getListeners() {
return listeners;
}
private void listenerEvent(Consumer<InvokerListener> consumer) {
if (CollectionUtils.isNotEmpty(listeners)) {
RuntimeException exception = null;
for (InvokerListener listener : listeners) {
if (listener != null) {
try {
consumer.accept(listener);
} catch (RuntimeException t) {
logger.error(
LoggerCodeConstants.INTERNAL_ERROR,
"wrapped listener internal error",
"",
t.getMessage(),
t);
exception = t;
}
}
}
if (exception != null) {
throw exception;
}
}
}
}
| 5,985 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/InvokerListenerAdapter.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.rpc.listener;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.InvokerListener;
import org.apache.dubbo.rpc.RpcException;
/**
* InvokerListenerAdapter
*/
public abstract class InvokerListenerAdapter implements InvokerListener {
@Override
public void referred(Invoker<?> invoker) throws RpcException {}
@Override
public void destroyed(Invoker<?> invoker) {}
}
| 5,986 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ExporterListenerAdapter.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.rpc.listener;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.ExporterListener;
import org.apache.dubbo.rpc.RpcException;
/**
* ExporterListenerAdapter
*/
public abstract class ExporterListenerAdapter implements ExporterListener {
@Override
public void exported(Exporter<?> exporter) throws RpcException {}
@Override
public void unexported(Exporter<?> exporter) throws RpcException {}
}
| 5,987 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/DeprecatedInvokerListener.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.rpc.listener;
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.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_UNSUPPORTED_INVOKER;
import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY;
/**
* DeprecatedProtocolFilter
*/
@Activate(DEPRECATED_KEY)
public class DeprecatedInvokerListener extends InvokerListenerAdapter {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(DeprecatedInvokerListener.class);
@Override
public void referred(Invoker<?> invoker) throws RpcException {
if (invoker.getUrl().getParameter(DEPRECATED_KEY, false)) {
LOGGER.error(
PROXY_UNSUPPORTED_INVOKER,
"",
"",
"The service " + invoker.getInterface().getName() + " is DEPRECATED! Declare from "
+ invoker.getUrl());
}
}
}
| 5,988 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ExporterChangeListener.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.rpc.listener;
import org.apache.dubbo.rpc.Exporter;
/**
* An interface for listening to changes in the export state of an Exporter object.
*/
public interface ExporterChangeListener {
/**
* This method is called when an Exporter object is exported.
*
* @param exporter The Exporter object that has been exported.
*/
void onExporterChangeExport(Exporter<?> exporter);
/**
* This method is called when an Exporter object is unexported.
*
* @param exporter The Exporter object that has been unexported.
*/
void onExporterChangeUnExport(Exporter<?> exporter);
}
| 5,989 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/ListenerExporterWrapper.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.rpc.listener;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.ExporterListener;
import org.apache.dubbo.rpc.Invoker;
import java.util.List;
import java.util.function.Consumer;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_FAILED_NOTIFY_EVENT;
/**
* ListenerExporter
*/
public class ListenerExporterWrapper<T> implements Exporter<T> {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ListenerExporterWrapper.class);
private final Exporter<T> exporter;
private final List<ExporterListener> listeners;
public ListenerExporterWrapper(Exporter<T> exporter, List<ExporterListener> listeners) {
if (exporter == null) {
throw new IllegalArgumentException("exporter == null");
}
this.exporter = exporter;
this.listeners = listeners;
listenerEvent(listener -> listener.exported(this));
}
@Override
public Invoker<T> getInvoker() {
return exporter.getInvoker();
}
@Override
public void unexport() {
try {
exporter.unexport();
} finally {
listenerEvent(listener -> listener.unexported(this));
}
}
@Override
public void register() {
exporter.register();
}
@Override
public void unregister() {
exporter.unregister();
}
private void listenerEvent(Consumer<ExporterListener> consumer) {
if (CollectionUtils.isNotEmpty(listeners)) {
RuntimeException exception = null;
for (ExporterListener listener : listeners) {
if (listener != null) {
try {
consumer.accept(listener);
} catch (RuntimeException t) {
logger.error(COMMON_FAILED_NOTIFY_EVENT, "", "", t.getMessage(), t);
exception = t;
}
}
}
if (exception != null) {
throw exception;
}
}
}
}
| 5,990 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/listener/InjvmExporterListener.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.rpc.listener;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.RpcException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* The InjvmExporterListener class is an implementation of the ExporterListenerAdapter abstract class,
* <p>
* which is used to listen for changes to the InjvmExporter instances.
* <p>
* It maintains two ConcurrentHashMaps, one to keep track of the ExporterChangeListeners registered for each service,
* <p>
* and another to keep track of the currently exported services and their associated Exporter instances.
* <p>
* It overrides the exported and unexported methods to add or remove the corresponding Exporter instances to/from
* <p>
* the exporters ConcurrentHashMap, and to notify all registered ExporterChangeListeners of the change.
* <p>
* It also provides methods to add or remove ExporterChangeListeners for a specific service, and to retrieve the
* <p>
* currently exported Exporter instance for a given service.
*/
public class InjvmExporterListener extends ExporterListenerAdapter {
/*
* A ConcurrentHashMap to keep track of the ExporterChangeListeners registered for each service.
*/
private final Map<String, Set<ExporterChangeListener>> exporterChangeListeners = new ConcurrentHashMap<>();
/*
* A ConcurrentHashMap to keep track of the currently exported services and their associated Exporter instances
*/
private final Map<String, Exporter<?>> exporters = new ConcurrentHashMap<>();
/**
* Overrides the exported method to add the given exporter to the exporters ConcurrentHashMap,
* <p>
* and to notify all registered ExporterChangeListeners of the export event.
*
* @param exporter The Exporter instance that has been exported.
* @throws RpcException If there is an error during the export process.
*/
@Override
public void exported(Exporter<?> exporter) throws RpcException {
String serviceKey = exporter.getInvoker().getUrl().getServiceKey();
exporters.putIfAbsent(serviceKey, exporter);
Set<ExporterChangeListener> listeners = exporterChangeListeners.get(serviceKey);
if (!CollectionUtils.isEmpty(listeners)) {
for (ExporterChangeListener listener : listeners) {
listener.onExporterChangeExport(exporter);
}
}
super.exported(exporter);
}
/**
* Overrides the unexported method to remove the given exporter from the exporters ConcurrentHashMap,
* <p>
* and to notify all registered ExporterChangeListeners of the unexport event.
*
* @param exporter The Exporter instance that has been unexported.
* @throws RpcException If there is an error during the unexport process.
*/
@Override
public void unexported(Exporter<?> exporter) throws RpcException {
String serviceKey = exporter.getInvoker().getUrl().getServiceKey();
exporters.remove(serviceKey, exporter);
Set<ExporterChangeListener> listeners = exporterChangeListeners.get(serviceKey);
if (!CollectionUtils.isEmpty(listeners)) {
for (ExporterChangeListener listener : listeners) {
listener.onExporterChangeUnExport(exporter);
}
}
super.unexported(exporter);
}
/**
* Adds an ExporterChangeListener for a specific service, and notifies the listener of the current Exporter instance
* <p>
* if it exists.
*
* @param listener The ExporterChangeListener to add.
* @param serviceKey The service key for the service to listen for changes on.
*/
public synchronized void addExporterChangeListener(ExporterChangeListener listener, String serviceKey) {
exporterChangeListeners.putIfAbsent(serviceKey, new ConcurrentHashSet<>());
exporterChangeListeners.get(serviceKey).add(listener);
if (exporters.get(serviceKey) != null) {
Exporter<?> exporter = exporters.get(serviceKey);
listener.onExporterChangeExport(exporter);
}
}
/**
* Removes an ExporterChangeListener for a specific service.
*
* @param listener The ExporterChangeListener to remove.
* @param listenerKey The service key for the service to remove the listener from.
*/
public synchronized void removeExporterChangeListener(ExporterChangeListener listener, String listenerKey) {
Set<ExporterChangeListener> listeners = exporterChangeListeners.get(listenerKey);
if (CollectionUtils.isEmpty(listeners)) {
return;
}
listeners.remove(listener);
if (CollectionUtils.isEmpty(listeners)) {
exporterChangeListeners.remove(listenerKey);
}
}
}
| 5,991 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractFallbackJdkProxyFactory.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.rpc.proxy;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.proxy.jdk.JdkProxyFactory;
import java.util.Arrays;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED;
public abstract class AbstractFallbackJdkProxyFactory extends AbstractProxyFactory {
protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(this.getClass());
private final JdkProxyFactory jdkProxyFactory = new JdkProxyFactory();
@Override
public <T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) throws RpcException {
try {
return doGetInvoker(proxy, type, url);
} catch (Throwable throwable) {
// try fall back to JDK proxy factory
String factoryName = getClass().getSimpleName();
try {
Invoker<T> invoker = jdkProxyFactory.getInvoker(proxy, type, url);
logger.error(
PROXY_FAILED,
"",
"",
"Failed to generate invoker by " + factoryName + " failed. Fallback to use JDK proxy success. "
+ "Interfaces: " + type,
throwable);
// log out error
return invoker;
} catch (Throwable fromJdk) {
logger.error(
PROXY_FAILED,
"",
"",
"Failed to generate invoker by " + factoryName
+ " failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + type
+ " Javassist Error.",
throwable);
logger.error(
PROXY_FAILED,
"",
"",
"Failed to generate invoker by " + factoryName
+ " failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + type
+ " JDK Error.",
fromJdk);
throw throwable;
}
}
}
@Override
public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) {
try {
return doGetProxy(invoker, interfaces);
} catch (Throwable throwable) {
// try fall back to JDK proxy factory
String factoryName = getClass().getSimpleName();
try {
T proxy = jdkProxyFactory.getProxy(invoker, interfaces);
logger.error(
PROXY_FAILED,
"",
"",
"Failed to generate proxy by " + factoryName + " failed. Fallback to use JDK proxy success. "
+ "Interfaces: " + Arrays.toString(interfaces),
throwable);
return proxy;
} catch (Throwable fromJdk) {
logger.error(
PROXY_FAILED,
"",
"",
"Failed to generate proxy by " + factoryName
+ " failed. Fallback to use JDK proxy is also failed. " + "Interfaces: "
+ Arrays.toString(interfaces) + " Javassist Error.",
throwable);
logger.error(
PROXY_FAILED,
"",
"",
"Failed to generate proxy by " + factoryName
+ " failed. Fallback to use JDK proxy is also failed. " + "Interfaces: "
+ Arrays.toString(interfaces) + " JDK Error.",
fromJdk);
throw throwable;
}
}
}
protected abstract <T> Invoker<T> doGetInvoker(T proxy, Class<T> type, URL url);
protected abstract <T> T doGetProxy(Invoker<T> invoker, Class<?>[] types);
}
| 5,992 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyFactory.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.rpc.proxy;
import org.apache.dubbo.common.compact.Dubbo2CompactUtils;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.Constants;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ServiceModel;
import org.apache.dubbo.rpc.service.Destroyable;
import org.apache.dubbo.rpc.service.EchoService;
import org.apache.dubbo.rpc.service.GenericService;
import java.util.Arrays;
import java.util.LinkedHashSet;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_UNSUPPORTED_INVOKER;
import static org.apache.dubbo.rpc.Constants.INTERFACES;
/**
* AbstractProxyFactory
*/
public abstract class AbstractProxyFactory implements ProxyFactory {
private static final Class<?>[] INTERNAL_INTERFACES = new Class<?>[] {EchoService.class, Destroyable.class};
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AbstractProxyFactory.class);
@Override
public <T> T getProxy(Invoker<T> invoker) throws RpcException {
return getProxy(invoker, false);
}
@Override
public <T> T getProxy(Invoker<T> invoker, boolean generic) throws RpcException {
// when compiling with native image, ensure that the order of the interfaces remains unchanged
LinkedHashSet<Class<?>> interfaces = new LinkedHashSet<>();
ClassLoader classLoader = getClassLoader(invoker);
String config = invoker.getUrl().getParameter(INTERFACES);
if (StringUtils.isNotEmpty(config)) {
String[] types = COMMA_SPLIT_PATTERN.split(config);
for (String type : types) {
try {
interfaces.add(ReflectUtils.forName(classLoader, type));
} catch (Throwable e) {
// ignore
}
}
}
Class<?> realInterfaceClass = null;
if (generic) {
try {
// find the real interface from url
String realInterface = invoker.getUrl().getParameter(Constants.INTERFACE);
realInterfaceClass = ReflectUtils.forName(classLoader, realInterface);
interfaces.add(realInterfaceClass);
} catch (Throwable e) {
// ignore
}
if (GenericService.class.isAssignableFrom(invoker.getInterface())
&& Dubbo2CompactUtils.isEnabled()
&& Dubbo2CompactUtils.isGenericServiceClassLoaded()) {
interfaces.add(Dubbo2CompactUtils.getGenericServiceClass());
}
if (!GenericService.class.isAssignableFrom(invoker.getInterface())) {
if (Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isGenericServiceClassLoaded()) {
interfaces.add(Dubbo2CompactUtils.getGenericServiceClass());
} else {
interfaces.add(org.apache.dubbo.rpc.service.GenericService.class);
}
}
}
interfaces.add(invoker.getInterface());
interfaces.addAll(Arrays.asList(INTERNAL_INTERFACES));
try {
return getProxy(invoker, interfaces.toArray(new Class<?>[0]));
} catch (Throwable t) {
if (generic) {
if (realInterfaceClass != null) {
interfaces.remove(realInterfaceClass);
}
interfaces.remove(invoker.getInterface());
logger.error(
PROXY_UNSUPPORTED_INVOKER,
"",
"",
"Error occur when creating proxy. Invoker is in generic mode. Trying to create proxy without real interface class.",
t);
return getProxy(invoker, interfaces.toArray(new Class<?>[0]));
} else {
throw t;
}
}
}
private <T> ClassLoader getClassLoader(Invoker<T> invoker) {
ServiceModel serviceModel = invoker.getUrl().getServiceModel();
ClassLoader classLoader = null;
if (serviceModel != null && serviceModel.getInterfaceClassLoader() != null) {
classLoader = serviceModel.getInterfaceClassLoader();
}
if (classLoader == null) {
classLoader = ClassUtils.getClassLoader();
}
return classLoader;
}
public static Class<?>[] getInternalInterfaces() {
return INTERNAL_INTERFACES.clone();
}
public abstract <T> T getProxy(Invoker<T> invoker, Class<?>[] types);
}
| 5,993 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvocationUtil.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.rpc.proxy;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.profiler.Profiler;
import org.apache.dubbo.common.profiler.ProfilerEntry;
import org.apache.dubbo.common.profiler.ProfilerSwitch;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.RpcServiceContext;
import org.apache.dubbo.rpc.support.RpcUtils;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_TIMEOUT_REQUEST;
public class InvocationUtil {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(InvokerInvocationHandler.class);
public static Object invoke(Invoker<?> invoker, RpcInvocation rpcInvocation) throws Throwable {
RpcContext.RestoreServiceContext originServiceContext = RpcContext.storeServiceContext();
try {
URL url = invoker.getUrl();
String serviceKey = url.getServiceKey();
rpcInvocation.setTargetServiceUniqueName(serviceKey);
// invoker.getUrl() returns consumer url.
RpcServiceContext.getServiceContext().setConsumerUrl(url);
if (ProfilerSwitch.isEnableSimpleProfiler()) {
ProfilerEntry parentProfiler = Profiler.getBizProfiler();
ProfilerEntry bizProfiler;
if (parentProfiler != null) {
bizProfiler = Profiler.enter(
parentProfiler,
"Receive request. Client invoke begin. ServiceKey: " + serviceKey + " MethodName:"
+ rpcInvocation.getMethodName());
} else {
bizProfiler = Profiler.start("Receive request. Client invoke begin. ServiceKey: " + serviceKey + " "
+ "MethodName:" + rpcInvocation.getMethodName());
}
rpcInvocation.put(Profiler.PROFILER_KEY, bizProfiler);
try {
return invoker.invoke(rpcInvocation).recreate();
} finally {
Profiler.release(bizProfiler);
Long timeout =
RpcUtils.convertToNumber(rpcInvocation.getObjectAttachmentWithoutConvert(TIMEOUT_KEY));
if (timeout == null) {
timeout = (long) url.getMethodPositiveParameter(
rpcInvocation.getMethodName(), TIMEOUT_KEY, DEFAULT_TIMEOUT);
}
long usage = bizProfiler.getEndTime() - bizProfiler.getStartTime();
if ((usage / (1000_000L * ProfilerSwitch.getWarnPercent())) > timeout) {
StringBuilder attachment = new StringBuilder();
rpcInvocation.foreachAttachment((entry) -> {
attachment
.append(entry.getKey())
.append("=")
.append(entry.getValue())
.append(";\n");
});
logger.warn(
PROXY_TIMEOUT_REQUEST,
"",
"",
String.format(
"[Dubbo-Consumer] execute service %s#%s cost %d.%06d ms, this invocation almost (maybe already) timeout. Timeout: %dms\n"
+ "invocation context:\n%s" + "thread info: \n%s",
rpcInvocation.getProtocolServiceKey(),
rpcInvocation.getMethodName(),
usage / 1000_000,
usage % 1000_000,
timeout,
attachment,
Profiler.buildDetail(bizProfiler)));
}
}
}
return invoker.invoke(rpcInvocation).recreate();
} finally {
RpcContext.restoreServiceContext(originServiceContext);
}
}
}
| 5,994 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/InvokerInvocationHandler.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.rpc.proxy;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.Constants;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.ServiceModel;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* InvokerHandler
*/
public class InvokerInvocationHandler implements InvocationHandler {
private static final Logger logger = LoggerFactory.getLogger(InvokerInvocationHandler.class);
private final Invoker<?> invoker;
private final ServiceModel serviceModel;
private final String protocolServiceKey;
public InvokerInvocationHandler(Invoker<?> handler) {
this.invoker = handler;
URL url = invoker.getUrl();
this.protocolServiceKey = url.getProtocolServiceKey();
this.serviceModel = url.getServiceModel();
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getDeclaringClass() == Object.class) {
return method.invoke(invoker, args);
}
String methodName = method.getName();
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 0) {
if ("toString".equals(methodName)) {
return invoker.toString();
} else if ("$destroy".equals(methodName)) {
invoker.destroy();
return null;
} else if ("hashCode".equals(methodName)) {
return invoker.hashCode();
}
} else if (parameterTypes.length == 1 && "equals".equals(methodName)) {
return invoker.equals(args[0]);
}
RpcInvocation rpcInvocation = new RpcInvocation(
serviceModel,
method.getName(),
invoker.getInterface().getName(),
protocolServiceKey,
method.getParameterTypes(),
args);
if (serviceModel instanceof ConsumerModel) {
rpcInvocation.put(Constants.CONSUMER_MODEL, serviceModel);
rpcInvocation.put(Constants.METHOD_MODEL, ((ConsumerModel) serviceModel).getMethodModel(method));
}
return InvocationUtil.invoke(invoker, rpcInvocation);
}
}
| 5,995 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/MethodInvoker.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.rpc.proxy;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public interface MethodInvoker {
Object invoke(Object instance, String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Throwable;
/**
* no overload method invoker
*/
class SingleMethodInvoker implements MethodInvoker {
private final Method method;
SingleMethodInvoker(Method method) {
this.method = method;
}
@Override
public Object invoke(Object instance, String methodName, Class<?>[] parameterTypes, Object[] arguments)
throws Throwable {
return method.invoke(instance, arguments);
}
}
/**
* overload method invoker
*/
class OverloadMethodInvoker implements MethodInvoker {
private final MethodMeta[] methods;
OverloadMethodInvoker(List<Method> methods) {
this.methods = methods.stream().map(MethodMeta::new).toArray(MethodMeta[]::new);
}
@Override
public Object invoke(Object instance, String methodName, Class<?>[] parameterTypes, Object[] arguments)
throws Throwable {
for (MethodMeta meta : methods) {
if (Arrays.equals(meta.getParametersType(), parameterTypes)) {
return meta.getMethod().invoke(instance, arguments);
}
}
throw new NoSuchMethodException(
instance.getClass().getName() + "." + methodName + Arrays.toString(parameterTypes));
}
private static class MethodMeta {
private final Method method;
private final Class<?>[] parametersType;
private MethodMeta(Method method) {
this.method = method;
this.parametersType = method.getParameterTypes();
}
public Method getMethod() {
return method;
}
public Class<?>[] getParametersType() {
return parametersType;
}
}
}
class CompositeMethodInvoker implements MethodInvoker {
private final Map<String, MethodInvoker> invokers;
public CompositeMethodInvoker(Map<String, MethodInvoker> invokers) {
this.invokers = invokers;
}
/**
* for test
*
* @return all MethodInvoker
*/
Map<String, MethodInvoker> getInvokers() {
return invokers;
}
@Override
public Object invoke(Object instance, String methodName, Class<?>[] parameterTypes, Object[] arguments)
throws Throwable {
MethodInvoker invoker = invokers.get(methodName);
if (invoker == null) {
throw new NoSuchMethodException(
instance.getClass().getName() + "." + methodName + Arrays.toString(parameterTypes));
}
return invoker.invoke(instance, methodName, parameterTypes, arguments);
}
}
static MethodInvoker newInstance(Class<?> clazz) {
Method[] methods = clazz.getMethods();
Map<String, MethodInvoker> invokers = new HashMap<>();
Map<String, List<Method>> map = new HashMap<>();
for (Method method : methods) {
map.computeIfAbsent(method.getName(), name -> new ArrayList<>()).add(method);
}
Set<Map.Entry<String, List<Method>>> entries = map.entrySet();
for (Map.Entry<String, List<Method>> entry : entries) {
String methodName = entry.getKey();
List<Method> ms = entry.getValue();
if (ms.size() == 1) {
invokers.put(methodName, new SingleMethodInvoker(ms.get(0)));
continue;
}
invokers.put(methodName, new OverloadMethodInvoker(ms));
}
return new CompositeMethodInvoker(invokers);
}
}
| 5,996 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.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.rpc.proxy;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.profiler.Profiler;
import org.apache.dubbo.common.profiler.ProfilerEntry;
import org.apache.dubbo.common.profiler.ProfilerSwitch;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.AsyncContextImpl;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_ASYNC_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_ERROR_ASYNC_RESPONSE;
/**
* This Invoker works on provider side, delegates RPC to interface implementation.
*/
public abstract class AbstractProxyInvoker<T> implements Invoker<T> {
ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractProxyInvoker.class);
private final T proxy;
private final Class<T> type;
private final URL url;
public AbstractProxyInvoker(T proxy, Class<T> type, URL url) {
if (proxy == null) {
throw new IllegalArgumentException("proxy == null");
}
if (type == null) {
throw new IllegalArgumentException("interface == null");
}
if (!type.isInstance(proxy)) {
throw new IllegalArgumentException(proxy.getClass().getName() + " not implement interface " + type);
}
this.proxy = proxy;
this.type = type;
this.url = url;
}
@Override
public Class<T> getInterface() {
return type;
}
@Override
public URL getUrl() {
return url;
}
@Override
public boolean isAvailable() {
return true;
}
@Override
public void destroy() {}
@Override
public Result invoke(Invocation invocation) throws RpcException {
ProfilerEntry originEntry = null;
try {
if (ProfilerSwitch.isEnableSimpleProfiler()) {
Object fromInvocation = invocation.get(Profiler.PROFILER_KEY);
if (fromInvocation instanceof ProfilerEntry) {
ProfilerEntry profiler = Profiler.enter(
(ProfilerEntry) fromInvocation, "Receive request. Server biz impl invoke begin.");
invocation.put(Profiler.PROFILER_KEY, profiler);
originEntry = Profiler.setToBizProfiler(profiler);
}
}
Object value = doInvoke(
proxy, invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments());
CompletableFuture<Object> future = wrapWithFuture(value, invocation);
CompletableFuture<AppResponse> appResponseFuture = future.handle((obj, t) -> {
AppResponse result = new AppResponse(invocation);
if (t != null) {
if (t instanceof CompletionException) {
result.setException(t.getCause());
} else {
result.setException(t);
}
} else {
result.setValue(obj);
}
return result;
});
return new AsyncRpcResult(appResponseFuture, invocation);
} catch (InvocationTargetException e) {
if (RpcContext.getServiceContext().isAsyncStarted()
&& !RpcContext.getServiceContext().stopAsync()) {
logger.error(
PROXY_ERROR_ASYNC_RESPONSE,
"",
"",
"Provider async started, but got an exception from the original method, cannot write the exception back to consumer because an async result may have returned the new thread.",
e);
}
return AsyncRpcResult.newDefaultAsyncResult(null, e.getTargetException(), invocation);
} catch (Throwable e) {
throw new RpcException(
"Failed to invoke remote proxy method " + invocation.getMethodName() + " to " + getUrl()
+ ", cause: " + e.getMessage(),
e);
} finally {
if (ProfilerSwitch.isEnableSimpleProfiler()) {
Object fromInvocation = invocation.get(Profiler.PROFILER_KEY);
if (fromInvocation instanceof ProfilerEntry) {
ProfilerEntry profiler = Profiler.release((ProfilerEntry) fromInvocation);
invocation.put(Profiler.PROFILER_KEY, profiler);
}
}
Profiler.removeBizProfiler();
if (originEntry != null) {
Profiler.setToBizProfiler(originEntry);
}
}
}
private CompletableFuture<Object> wrapWithFuture(Object value, Invocation invocation) {
if (value instanceof CompletableFuture) {
invocation.put(PROVIDER_ASYNC_KEY, Boolean.TRUE);
return (CompletableFuture<Object>) value;
} else if (RpcContext.getServerAttachment().isAsyncStarted()) {
invocation.put(PROVIDER_ASYNC_KEY, Boolean.TRUE);
return ((AsyncContextImpl) (RpcContext.getServerAttachment().getAsyncContext())).getInternalFuture();
}
return CompletableFuture.completedFuture(value);
}
protected abstract Object doInvoke(T proxy, String methodName, Class<?>[] parameterTypes, Object[] arguments)
throws Throwable;
@Override
public String toString() {
return getInterface() + " -> " + (getUrl() == null ? " " : getUrl().toString());
}
}
| 5,997 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/javassist/JavassistProxyFactory.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.rpc.proxy.javassist;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.bytecode.Proxy;
import org.apache.dubbo.common.bytecode.Wrapper;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.proxy.AbstractProxyFactory;
import org.apache.dubbo.rpc.proxy.AbstractProxyInvoker;
import org.apache.dubbo.rpc.proxy.InvokerInvocationHandler;
import org.apache.dubbo.rpc.proxy.jdk.JdkProxyFactory;
import java.util.Arrays;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED;
/**
* JavassistRpcProxyFactory
*/
public class JavassistProxyFactory extends AbstractProxyFactory {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(JavassistProxyFactory.class);
private final JdkProxyFactory jdkProxyFactory = new JdkProxyFactory();
@Override
@SuppressWarnings("unchecked")
public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) {
try {
return (T) Proxy.getProxy(interfaces).newInstance(new InvokerInvocationHandler(invoker));
} catch (Throwable fromJavassist) {
// try fall back to JDK proxy factory
try {
T proxy = jdkProxyFactory.getProxy(invoker, interfaces);
logger.error(
PROXY_FAILED,
"",
"",
"Failed to generate proxy by Javassist failed. Fallback to use JDK proxy success. "
+ "Interfaces: " + Arrays.toString(interfaces),
fromJavassist);
return proxy;
} catch (Throwable fromJdk) {
logger.error(
PROXY_FAILED,
"",
"",
"Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. "
+ "Interfaces: " + Arrays.toString(interfaces) + " Javassist Error.",
fromJavassist);
logger.error(
PROXY_FAILED,
"",
"",
"Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. "
+ "Interfaces: " + Arrays.toString(interfaces) + " JDK Error.",
fromJdk);
throw fromJavassist;
}
}
}
@Override
public <T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) {
try {
// TODO Wrapper cannot handle this scenario correctly: the classname contains '$'
final Wrapper wrapper =
Wrapper.getWrapper(proxy.getClass().getName().indexOf('$') < 0 ? proxy.getClass() : type);
return new AbstractProxyInvoker<T>(proxy, type, url) {
@Override
protected Object doInvoke(T proxy, String methodName, Class<?>[] parameterTypes, Object[] arguments)
throws Throwable {
return wrapper.invokeMethod(proxy, methodName, parameterTypes, arguments);
}
};
} catch (Throwable fromJavassist) {
// try fall back to JDK proxy factory
try {
Invoker<T> invoker = jdkProxyFactory.getInvoker(proxy, type, url);
logger.error(
PROXY_FAILED,
"",
"",
"Failed to generate invoker by Javassist failed. Fallback to use JDK proxy success. "
+ "Interfaces: " + type,
fromJavassist);
// log out error
return invoker;
} catch (Throwable fromJdk) {
logger.error(
PROXY_FAILED,
"",
"",
"Failed to generate invoker by Javassist failed. Fallback to use JDK proxy is also failed. "
+ "Interfaces: " + type + " Javassist Error.",
fromJavassist);
logger.error(
PROXY_FAILED,
"",
"",
"Failed to generate invoker by Javassist failed. Fallback to use JDK proxy is also failed. "
+ "Interfaces: " + type + " JDK Error.",
fromJdk);
throw fromJavassist;
}
}
}
}
| 5,998 |
0 | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy | Create_ds/dubbo/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/bytebuddy/ByteBuddyProxyInvoker.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.rpc.proxy.bytebuddy;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.proxy.AbstractProxyInvoker;
import org.apache.dubbo.rpc.proxy.MethodInvoker;
class ByteBuddyProxyInvoker<T> extends AbstractProxyInvoker<T> {
private final MethodInvoker methodInvoker;
private ByteBuddyProxyInvoker(T proxy, Class<T> type, URL url, MethodInvoker methodInvoker) {
super(proxy, type, url);
this.methodInvoker = methodInvoker;
}
@Override
protected Object doInvoke(T instance, String methodName, Class<?>[] parameterTypes, Object[] arguments)
throws Throwable {
if ("getClass".equals(methodName)) {
return instance.getClass();
}
if ("hashCode".equals(methodName)) {
return instance.hashCode();
}
if ("toString".equals(methodName)) {
return instance.toString();
}
if ("equals".equals(methodName)) {
if (arguments.length == 1) {
return instance.equals(arguments[0]);
}
throw new IllegalArgumentException("Invoke method [" + methodName + "] argument number error.");
}
return methodInvoker.invoke(instance, methodName, parameterTypes, arguments);
}
static <T> ByteBuddyProxyInvoker<T> newInstance(T proxy, Class<T> type, URL url) {
return new ByteBuddyProxyInvoker<>(proxy, type, url, MethodInvoker.newInstance(proxy.getClass()));
}
}
| 5,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.