com.alipay.sofa.rpc.filter.Filter Java Examples

The following examples show how to use com.alipay.sofa.rpc.filter.Filter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RpcFilterContainer.java    From sofa-rpc-boot-projects with Apache License 2.0 6 votes vote down vote up
/**
 * 获取所有的 Filter 实例
 *
 * @param applicationContext Spring 上下文
 * @return 所有的 Filter 实例
 */
public List<Filter> getFilters(ApplicationContext applicationContext) {
    if (applicationContext != null) {
        if (!alreadyLoad) {
            synchronized (LOAD_LOCK) {
                if (!alreadyLoad) {
                    loadFilters(applicationContext);
                    alreadyLoad = true;
                }
            }
        }

        return filters;

    } else {
        throw new SofaBootRpcRuntimeException("The applicationContext should not be null");
    }
}
 
Example #2
Source File: CustomFilterServerMain.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        Filter customEchoFilter2 = new CustomEchoFilter2();

        ApplicationConfig application = new ApplicationConfig().setAppName("test-server");

        ServerConfig serverConfig = new ServerConfig()
            .setPort(22000)
            .setDaemon(false);

        ProviderConfig<HelloService> providerConfig = new ProviderConfig<HelloService>()
            .setInterfaceId(HelloService.class.getName())
            .setApplication(application)
            .setRef(new HelloServiceImpl())
            .setServer(serverConfig)
            .setFilter(Arrays.asList("customEcho"))
            .setFilterRef(Arrays.asList(customEchoFilter2))
            .setRegister(false);

        providerConfig.export();

        LOGGER.error("started at pid {}", RpcRuntimeContext.PID);
    }
 
Example #3
Source File: HystrixFilterAsyncTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testHystrixLockNotRelease() {
    // 通过 filter mock 锁超时的情况
    providerConfig = defaultServer(2000);
    providerConfig.export();

    consumerConfig = defaultClient()
        .setFilterRef(Collections.<Filter> singletonList(new MockTimeoutFilter(4000)))
        .setTimeout(10000);
    HystrixService HystrixService = consumerConfig.refer();

    try {
        //wait server ok
        Thread.sleep(2000);
        HystrixService.sayHello("abc", 24);
        Assert.fail();
    } catch (Exception e) {
        Assert.assertTrue(e instanceof SofaTimeOutException);
        Assert
            .assertEquals(
                "Asynchronous execution timed out, please check Hystrix configuration. Events: [SofaAsyncHystrixEvent#EMIT]",
                e.getMessage());
    }

}
 
Example #4
Source File: HystrixFilterSyncTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testHystrixFallback() {
    providerConfig = defaultServer(2000);
    providerConfig.export();

    consumerConfig = defaultClient()
        .setTimeout(10000)
        .setFilterRef(Collections.<Filter> singletonList(new HystrixFilter()));

    SofaHystrixConfig.registerFallback(consumerConfig, new HystrixServiceFallback());

    HystrixService helloService = consumerConfig.refer();

    String result = helloService.sayHello("abc", 24);
    Assert.assertEquals("fallback abc from server! age: 24", result);
}
 
Example #5
Source File: ExtensionLoaderTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddListener(){
    ExtensionLoader<Filter> extensionLoader = ExtensionLoaderFactory.getExtensionLoader(Filter.class);
    extensionLoader.loadExtension(DynamicFilter.class);
    ConcurrentMap<String, ExtensionClass<Filter>> all = extensionLoader.all;
    String alias = "dynamic0";
    Assert.assertTrue(all.containsKey(alias));


    List<String> filters = new ArrayList<>();
    extensionLoader = ExtensionLoaderFactory.getExtensionLoader(Filter.class);
    extensionLoader.addListener( new  ExtensionLoaderListener<Filter>() {
        @Override
        public void onLoad(ExtensionClass<Filter> extensionClass) {
            filters.add(extensionClass.getAlias());
        }
    });

    Assert.assertTrue(filters.contains(alias));

}
 
Example #6
Source File: ExtensionLoaderTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadFromFile() throws Exception {
    ExtensionLoader loader = new ExtensionLoader<Filter>(Filter.class, false, null);
    loader.loadFromFile("META-INF/ext1/");
    Assert.assertTrue(loader.getAllExtensions().isEmpty());

    // test right extension
    loader = new ExtensionLoader<Filter>(Filter.class, false, null);
    loader.loadFromFile("META-INF/ext2/");
    Assert.assertFalse(loader.getAllExtensions().isEmpty());
    ExtensionClass extensionClass = loader.getExtensionClass("rightxx0");
    Assert.assertNotNull(extensionClass);
    Assert.assertTrue(extensionClass.getOrder() == 123);

    loader = new ExtensionLoader<Filter>(Filter.class, false, new TestErrorLoadListener());
    loader.loadFromFile("META-INF/ext3/");
    Assert.assertFalse(loader.getAllExtensions().isEmpty());
    extensionClass = loader.getExtensionClass("rightxx0");
    Assert.assertNotNull(extensionClass);
    extensionClass = loader.getExtensionClass("rightxx1");
    Assert.assertNotNull(extensionClass);
    Assert.assertTrue(extensionClass.getOrder() == 128);

    loader = new ExtensionLoader<Filter>(Filter.class, false, new TestLoadListener());
    loader.loadFromFile("META-INF/ext4/");
    Assert.assertFalse(loader.getAllExtensions().isEmpty());
    extensionClass = loader.getExtensionClass("rightxx0");
    Assert.assertNotNull(extensionClass);
    Assert.assertTrue(extensionClass.getOrder() == 123);
    extensionClass = loader.getExtensionClass("rightxx1");
    Assert.assertNotNull(extensionClass);
    Assert.assertTrue(extensionClass.getOrder() == 128);

}
 
Example #7
Source File: ExtensionLoaderTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseAliasAndClassName() throws Exception {
    ExtensionLoader loader = new ExtensionLoader<Filter>(Filter.class);

    Assert.assertNull(loader.parseAliasAndClassName(null));
    Assert.assertNull(loader.parseAliasAndClassName(""));
    Assert.assertNull(loader.parseAliasAndClassName("    "));
    Assert.assertNull(loader.parseAliasAndClassName("\t"));
    Assert.assertNull(loader.parseAliasAndClassName("\r\n"));

    Assert.assertNull(loader.parseAliasAndClassName("    # xxxx"));
    Assert.assertNull(loader.parseAliasAndClassName("# xxxx"));
    Assert.assertNull(loader.parseAliasAndClassName("xxx="));

    Assert.assertArrayEquals(loader.parseAliasAndClassName("1111"), new String[] { null, "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("  1111"), new String[] { null, "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("  1111   "), new String[] { null, "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("1111   "), new String[] { null, "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("1111#aa"), new String[] { null, "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("  1111#aa"), new String[] { null, "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("1111#aa   "), new String[] { null, "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("  1111#aa  "), new String[] { null, "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("1111 #aa"), new String[] { null, "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("  1111 #aa"), new String[] { null, "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("1111 #aa   "), new String[] { null, "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("  1111 #aa  "), new String[] { null, "1111" });

    Assert.assertArrayEquals(loader.parseAliasAndClassName("aa=1111"), new String[] { "aa", "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("  aa=1111"), new String[] { "aa", "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("aa=1111  "), new String[] { "aa", "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("  aa=1111  "), new String[] { "aa", "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("aa=1111#aa"), new String[] { "aa", "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("  aa=1111#aa"), new String[] { "aa", "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("aa=1111#aa  "), new String[] { "aa", "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("  aa=1111#aa  "), new String[] { "aa", "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("aa=1111  #aa"), new String[] { "aa", "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("  aa=1111  #aa"), new String[] { "aa", "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("aa=1111  #aa  "), new String[] { "aa", "1111" });
    Assert.assertArrayEquals(loader.parseAliasAndClassName("  aa=1111  #aa  "), new String[] { "aa", "1111" });
}
 
Example #8
Source File: ExtensionLoaderTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testDynamicLoadExtension() {
    ExtensionLoader<Filter> extensionLoader = ExtensionLoaderFactory.getExtensionLoader(Filter.class);
    extensionLoader.loadExtension(DynamicFilter.class);
    Filter dynamic0 = extensionLoader.getExtension("dynamic0");
    Assert.assertTrue(dynamic0 instanceof DynamicFilter);
}
 
Example #9
Source File: RpcBindingConverter.java    From sofa-rpc-boot-projects with Apache License 2.0 4 votes vote down vote up
private void parseFilter(Element element, RpcBindingParam param, BindingConverterContext bindingConverterContext) {
    List<Filter> filters = new ArrayList<Filter>(RpcFilterContainer.getInstance().getFilters(
        bindingConverterContext.getApplicationContext()));

    if (element != null) {
        List<String> filterNames = new ArrayList<String>();

        String filterStrs = element.getAttribute(RpcBindingXmlConstants.TAG_FILTER);
        if (StringUtils.hasText(filterStrs)) {

            String[] subFilter = filterStrs.split(FILTER_SEPERATOR_SYMBOL);
            for (String subfilterName : subFilter) {
                if (StringUtils.hasText(subfilterName)) {

                    if (subfilterName.charAt(0) == EXCLUDE_FILTER_BEGIN_SYMBOL) {
                        String realFilterName = subfilterName.substring(1);
                        if (StringUtils.hasText(realFilterName)) {

                            filters.add(new ExcludeFilter(realFilterName));
                        }
                    } else {
                        filterNames.add(subfilterName);
                    }
                }
            }
        }

        if (!CollectionUtils.isEmpty(filterNames)) {
            for (String filterName : filterNames) {
                Object filter = bindingConverterContext.getApplicationContext().getBean(filterName);
                if (filter instanceof Filter) {
                    filters.add((Filter) filter);
                } else {
                    throw new SofaBootRpcRuntimeException("filter name[" + filterName + "] is not ref a Filter.");
                }
            }
        }
    }

    param.setFilters(filters);
}
 
Example #10
Source File: RpcBindingConverter.java    From sofa-rpc-boot-projects with Apache License 2.0 4 votes vote down vote up
/**
 * convert props to RpcBindingParam
 *
 * @param bindingParam
 * @param sofaServiceAnnotation
 * @param sofaServiceBindingAnnotation
 * @param bindingConverterContext
 */
protected void convertServiceAnnotation(RpcBindingParam bindingParam, SofaService sofaServiceAnnotation,
                                        SofaServiceBinding sofaServiceBindingAnnotation,
                                        BindingConverterContext bindingConverterContext) {
    bindingParam.setTimeout(sofaServiceBindingAnnotation.timeout());

    //TODO need a magic number
    if (sofaServiceBindingAnnotation.weight() != 0) {
        bindingParam.setWeight(sofaServiceBindingAnnotation.weight());
    }
    if (sofaServiceBindingAnnotation.warmUpTime() != 0) {
        bindingParam.setWarmUpTime(sofaServiceBindingAnnotation.warmUpTime());
    }
    if (sofaServiceBindingAnnotation.warmUpWeight() != 0) {
        bindingParam.setWarmUpWeight(sofaServiceBindingAnnotation.warmUpWeight());
    }
    if (StringUtils.hasText(sofaServiceBindingAnnotation.serializeType())) {
        bindingParam.setSerialization(sofaServiceBindingAnnotation.serializeType());
    }

    ApplicationContext applicationContext = bindingConverterContext.getApplicationContext();
    List<Filter> filters = new ArrayList<Filter>(RpcFilterContainer.getInstance().getFilters(
        applicationContext));

    String[] filterNames = sofaServiceBindingAnnotation.filters();
    if (filterNames.length > 0) {
        for (String filterName : filterNames) {
            Object filter = applicationContext.getBean(filterName);
            if (filter instanceof Filter) {
                filters.add((Filter) filter);
            } else {
                throw new SofaBootRpcRuntimeException("filter name[" + filterName + "] is not ref a Filter.");
            }
        }
    }

    if (!CollectionUtils.isEmpty(filters)) {
        bindingParam.setFilters(filters);
    }
    String threadPool = sofaServiceBindingAnnotation.userThreadPool();
    if (StringUtils.hasText(threadPool)) {

        UserThreadPool threadPoolObj = (UserThreadPool) applicationContext.getBean(threadPool);

        String interfaceName = sofaServiceAnnotation.interfaceType().getCanonicalName();
        String uniqId = sofaServiceAnnotation.uniqueId();
        String uniqueName = interfaceName
            + ":1.0"
            + (StringUtils.isEmpty(uniqId) ? "" : ":" + uniqId);

        UserThreadPoolManager.registerUserThread(uniqueName,
            threadPoolObj);
    }

    String registryAlias = sofaServiceBindingAnnotation.registry();
    if (StringUtils.hasText(registryAlias)) {
        String[] registrys = registryAlias.split(",");
        bindingParam.setRegistrys(Arrays.asList(registrys));
    }

    SofaParameter[] parameters = sofaServiceBindingAnnotation.parameters();
    if (parameters.length > 0) {
        bindingParam.setParameters(parseSofaParameters(parameters));
    }

    SofaMethod[] sofaMethods = sofaServiceBindingAnnotation.methodInfos();
    if (sofaMethods.length > 0) {
        bindingParam.setMethodInfos(parseSofaMethods(sofaMethods));
    }
}
 
Example #11
Source File: RpcBindingConverter.java    From sofa-rpc-boot-projects with Apache License 2.0 4 votes vote down vote up
/**
 * convert props to RpcBindingParam
 *
 * @param bindingParam
 * @param sofaReferenceBindingAnnotation
 * @param bindingConverterContext
 */
protected void convertReferenceAnnotation(RpcBindingParam bindingParam,
                                          SofaReferenceBinding sofaReferenceBindingAnnotation,
                                          BindingConverterContext bindingConverterContext) {
    if (sofaReferenceBindingAnnotation.addressWaitTime() != 0) {
        bindingParam.setAddressWaitTime(sofaReferenceBindingAnnotation.addressWaitTime());
    }
    if (StringUtils.hasText(sofaReferenceBindingAnnotation.directUrl())) {
        bindingParam.setTargetUrl(sofaReferenceBindingAnnotation.directUrl());
    }
    if (sofaReferenceBindingAnnotation.timeout() != 0) {
        bindingParam.setTimeout(sofaReferenceBindingAnnotation.timeout());
    }
    if (StringUtils.hasText(sofaReferenceBindingAnnotation.serializeType())) {
        bindingParam.setSerialization(sofaReferenceBindingAnnotation.serializeType());
    }
    if (StringUtils.hasText(sofaReferenceBindingAnnotation.loadBalancer())) {
        bindingParam.setLoadBalancer(sofaReferenceBindingAnnotation.loadBalancer());
    }
    bindingParam.setType(sofaReferenceBindingAnnotation.invokeType());

    ApplicationContext applicationContext = bindingConverterContext.getApplicationContext();
    List<Filter> filters = new ArrayList<Filter>(RpcFilterContainer.getInstance().getFilters(
        applicationContext));

    String[] filterNames = sofaReferenceBindingAnnotation.filters();

    if (filterNames.length > 0) {
        for (String filterName : filterNames) {
            Object filter = applicationContext.getBean(filterName);
            if (filter instanceof Filter) {
                filters.add((Filter) filter);
            } else {
                throw new SofaBootRpcRuntimeException("filter name[" + filterName + "] is not ref a Filter.");
            }
        }
    }

    if (!CollectionUtils.isEmpty(filters)) {
        bindingParam.setFilters(filters);
    }

    bindingParam.setRetries(sofaReferenceBindingAnnotation.retries());

    String callbackRef = sofaReferenceBindingAnnotation.callbackHandler();
    if (StringUtils.hasText(callbackRef)) {
        bindingParam.setCallbackHandler(applicationContext.getBean(callbackRef));
    }
    bindingParam.setLazy(sofaReferenceBindingAnnotation.lazy());

    String registryAlias = sofaReferenceBindingAnnotation.registry();
    if (StringUtils.hasText(registryAlias)) {
        String[] registrys = registryAlias.split(",");
        bindingParam.setRegistrys(Arrays.asList(registrys));
    }

    SofaParameter[] parameters = sofaReferenceBindingAnnotation.parameters();
    if (parameters.length > 0) {
        bindingParam.setParameters(parseSofaParameters(parameters));
    }

    SofaMethod[] sofaMethods = sofaReferenceBindingAnnotation.methodInfos();
    if (sofaMethods.length > 0) {
        bindingParam.setMethodInfos(parseSofaMethods(sofaMethods));
    }
}
 
Example #12
Source File: CustomizeFilterTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    customizeContainerRequestTestFilter = new CustomizeContainerRequestTestFilter();
    customizeContainerResponseTestFilter = new CustomizeContainerResponseTestFilter();
    customizeClientRequestTestFilter = new CustomizeClientRequestTestFilter();
    customizeClientResponseTestFilter = new CustomizeClientResponseTestFilter();

    JAXRSProviderManager.registerCustomProviderInstance(customizeContainerRequestTestFilter);
    JAXRSProviderManager.registerCustomProviderInstance(customizeContainerResponseTestFilter);
    JAXRSProviderManager.registerCustomProviderInstance(customizeClientRequestTestFilter);
    JAXRSProviderManager.registerCustomProviderInstance(customizeClientResponseTestFilter);

    providerFilter = new CustomizeTestFilter();
    List<Filter> providerFilters = new ArrayList<Filter>(2);
    providerFilters.add(providerFilter);

    ServerConfig restServer = new ServerConfig()
        .setPort(8583)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_REST);

    List<ServerConfig> servers = new ArrayList<ServerConfig>(2);
    servers.add(restServer);
    providerConfig = new ProviderConfig<RestService>()
        .setInterfaceId(RestService.class.getName())
        .setRef(new RestServiceImpl())
        .setRegister(false)
        .setServer(servers)
        .setFilterRef(providerFilters);

    providerConfig.export();

    //rest服务
    clientFilter = new CustomizeTestFilter();
    List<Filter> clientFilters = new ArrayList<Filter>(2);
    clientFilters.add(clientFilter);

    ConsumerConfig<RestService> consumerConfigRest = new ConsumerConfig<RestService>()
        .setInterfaceId(RestService.class.getName())
        .setProtocol(RpcConstants.PROTOCOL_TYPE_REST)
        .setDirectUrl("rest://127.0.0.1:8583")
        .setTimeout(1000)
        .setFilterRef(clientFilters)
        .setApplication(new ApplicationConfig().setAppName("TestClientRest"));
    filterRestService = consumerConfigRest.refer();
}
 
Example #13
Source File: RpcBindingParam.java    From sofa-rpc-boot-projects with Apache License 2.0 2 votes vote down vote up
/**
 * Getter method for property <tt>filters</tt>.
 *
 * @return property value of filters
 */
public List<Filter> getFilters() {
    return filters;
}
 
Example #14
Source File: RpcBindingParam.java    From sofa-rpc-boot-projects with Apache License 2.0 2 votes vote down vote up
/**
 * Setter method for property <tt>filters</tt>.
 *
 * @param filters value to be assigned to property filters
 */
public void setFilters(List<Filter> filters) {
    this.filters = filters;
}
 
Example #15
Source File: AbstractInterfaceConfig.java    From sofa-rpc with Apache License 2.0 2 votes vote down vote up
/**
 * Gets filter ref.
 *
 * @return the filter ref
 */
public List<Filter> getFilterRef() {
    return filterRef;
}
 
Example #16
Source File: AbstractInterfaceConfig.java    From sofa-rpc with Apache License 2.0 2 votes vote down vote up
/**
 * Sets filter ref.
 *
 * @param filterRef the filter ref
 * @return the filter ref
 */
public S setFilterRef(List<Filter> filterRef) {
    this.filterRef = filterRef;
    return castThis();
}