javax.ws.rs.container.ContainerResponseFilter Java Examples

The following examples show how to use javax.ws.rs.container.ContainerResponseFilter. 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: AdminApiApplication.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
public AdminApiApplication(ServerInstance instance, AccessControlFactory accessControlFactory) {
  this.serverInstance = instance;
  this.accessControlFactory = accessControlFactory;
  packages(RESOURCE_PACKAGE);
  register(new AbstractBinder() {
    @Override
    protected void configure() {
      bind(serverInstance).to(ServerInstance.class);
      bind(accessControlFactory).to(AccessControlFactory.class);
    }
  });

  register(JacksonFeature.class);

  registerClasses(io.swagger.jaxrs.listing.ApiListingResource.class);
  registerClasses(io.swagger.jaxrs.listing.SwaggerSerializers.class);
  register(new ContainerResponseFilter() {
    @Override
    public void filter(ContainerRequestContext containerRequestContext,
        ContainerResponseContext containerResponseContext)
        throws IOException {
      containerResponseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
    }
  });
}
 
Example #2
Source File: TestHelper.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
protected ServiceRegistration<?> registerExtension(
    String name, Object... keyValues) {

    TestFilter testFilter = new TestFilter();

    Hashtable<String, Object> properties = new Hashtable<>();

    properties.put(JAX_RS_EXTENSION, true);
    properties.put(JAX_RS_NAME, name);
    properties.putIfAbsent(
        JAX_RS_APPLICATION_SELECT, "(osgi.jaxrs.name=*)");

    for (int i = 0; i < keyValues.length; i = i + 2) {
        properties.put(keyValues[i].toString(), keyValues[i + 1]);
    }

    ServiceRegistration<ContainerResponseFilter> serviceRegistration =
        bundleContext.registerService(
            ContainerResponseFilter.class, testFilter, properties);

    _registrations.add(serviceRegistration);

    return serviceRegistration;
}
 
Example #3
Source File: ConfigurationImplTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidContract() {
    TestHandler handler = new TestHandler();
    LogUtils.getL7dLogger(ConfigurationImpl.class).addHandler(handler);

    ConfigurationImpl c = new ConfigurationImpl(RuntimeType.SERVER);
    ContainerResponseFilter filter = new ContainerResponseFilterImpl();
    assertFalse(c.register(filter,
                           Collections.<Class<?>, Integer>singletonMap(MessageBodyReader.class, 1000)));

    for (String message : handler.messages) {
        if (message.startsWith("WARN") && message.contains("does not implement specified contract")) {
            return; // success
        }
    }
    fail("did not log expected message");
}
 
Example #4
Source File: ServerProviderFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public Map<Class<?>, Integer> getContracts(Class<?> cls) {
    Map<Class<?>, Integer> map = new HashMap<>();
    if (isRegistered(cls)) {
        if (ContainerRequestFilter.class.isAssignableFrom(cls)) {
            boolean isPreMatch = cls.getAnnotation(PreMatching.class) != null;
            map.put(ContainerRequestFilter.class,
                    getPriority(isPreMatch ? preMatchContainerRequestFilters
                        : postMatchContainerRequestFilters.values(), cls, ContainerRequestFilter.class));
        }
        if (ContainerResponseFilter.class.isAssignableFrom(cls)) {
            map.put(ContainerResponseFilter.class,
                    getPriority(containerResponseFilters.values(), cls, ContainerResponseFilter.class));
        }
        if (WriterInterceptor.class.isAssignableFrom(cls)) {
            map.put(WriterInterceptor.class,
                    getPriority(writerInterceptors.values(), cls, WriterInterceptor.class));
        }
        if (ReaderInterceptor.class.isAssignableFrom(cls)) {
            map.put(ReaderInterceptor.class,
                    getPriority(readerInterceptors.values(), cls, ReaderInterceptor.class));
        }
    }
    return map;
}
 
Example #5
Source File: BookServer20.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext configurable) {

    configurable.register(new PreMatchDynamicContainerRequestFilter());
    configurable.register(RESPONSE_FILTER);
    Map<Class<?>, Integer> contracts = new HashMap<>();
    contracts.put(ContainerResponseFilter.class, 2);
    configurable.register(new PostMatchDynamicContainerRequestResponseFilter(),
                          contracts);
    Method m = resourceInfo.getResourceMethod();
    if ("echoBookElement".equals(m.getName())) {
        Class<?> paramType = m.getParameterTypes()[0];
        if (paramType == Book.class) {
            configurable.register(new PostMatchDynamicEchoBookFilter(2));
        }
    }
}
 
Example #6
Source File: JAXRSUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static void runContainerResponseFilters(ServerProviderFactory pf,
                                               ResponseImpl r,
                                               Message m,
                                               OperationResourceInfo ori,
                                               Method invoked) throws IOException, Throwable {
    List<ProviderInfo<ContainerResponseFilter>> containerFilters =
        pf.getContainerResponseFilters(ori == null ? null : ori.getNameBindings());
    if (!containerFilters.isEmpty()) {
        ContainerRequestContext requestContext =
            new ContainerRequestContextImpl(m.getExchange().getInMessage(),
                                           false,
                                           true);
        ContainerResponseContext responseContext =
            new ContainerResponseContextImpl(r, m,
                ori == null ? null : ori.getClassResourceInfo().getServiceClass(), invoked);
        for (ProviderInfo<ContainerResponseFilter> filter : containerFilters) {
            InjectionUtils.injectContexts(filter.getProvider(), filter, m);
            filter.getProvider().filter(requestContext, responseContext);
        }
    }
}
 
Example #7
Source File: RESTService.java    From tomee with Apache License 2.0 5 votes vote down vote up
private static <T> boolean isProvider(final Class<T> clazz) {
    return MessageBodyReader.class.isAssignableFrom(clazz) ||
            MessageBodyWriter.class.isAssignableFrom(clazz) ||
            ParamConverter.class.isAssignableFrom(clazz) ||
            ContainerRequestFilter.class.isAssignableFrom(clazz) ||
            ContainerResponseFilter.class.isAssignableFrom(clazz) ||
            ReaderInterceptor.class.isAssignableFrom(clazz) ||
            WriterInterceptor.class.isAssignableFrom(clazz) ||
            ParamConverterProvider.class.isAssignableFrom(clazz) ||
            ContextResolver.class.isAssignableFrom(clazz) ||
            Feature.class.isAssignableFrom(clazz) ||
            new MetaAnnotatedClass<>(clazz).isAnnotationPresent(Provider.class);
}
 
Example #8
Source File: ConfigurationImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testClientFilterContractsOnServerFeatureIsRejected() {
    FeatureContextImpl featureContext = new FeatureContextImpl();
    Configurable<FeatureContext> configurable = new ConfigurableImpl<>(featureContext, RuntimeType.SERVER);
    featureContext.setConfigurable(configurable);
    featureContext.register(TestFilter.class);
    Configuration config = configurable.getConfiguration();
    Map<Class<?>, Integer> contracts = config.getContracts(TestFilter.class);
    assertFalse(contracts.containsKey(ClientRequestFilter.class));
    assertFalse(contracts.containsKey(ClientResponseFilter.class));
    assertTrue(contracts.containsKey(ContainerRequestFilter.class));
    assertTrue(contracts.containsKey(ContainerResponseFilter.class));
}
 
Example #9
Source File: ConfigurationImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testServerFilterContractsOnClientIsRejected() {
    try (ConfigurableImpl<Client> configurable 
            = new ConfigurableImpl<>(createClientProxy(), RuntimeType.CLIENT)) {
        Configuration config = configurable.getConfiguration();
        configurable.register(TestFilter.class);
        Map<Class<?>, Integer> contracts = config.getContracts(TestFilter.class);
        assertTrue(contracts.containsKey(ClientRequestFilter.class));
        assertTrue(contracts.containsKey(ClientResponseFilter.class));
        assertFalse(contracts.containsKey(ContainerRequestFilter.class));
        assertFalse(contracts.containsKey(ContainerResponseFilter.class));
    }
}
 
Example #10
Source File: ConfigurationImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubClassIsRegisteredOnConfigurable() {
    FeatureContextImpl featureContext = new FeatureContextImpl();
    Configurable<FeatureContext> configurable = new ConfigurableImpl<>(featureContext, RuntimeType.SERVER);
    featureContext.setConfigurable(configurable);
    featureContext.register(ContainerResponseFilterSubClassImpl.class);
    Configuration config = configurable.getConfiguration();
    Map<Class<?>, Integer> contracts = config.getContracts(ContainerResponseFilter.class);
    assertEquals(1, contracts.size());
    assertTrue(contracts.containsKey(ContainerResponseFilter.class));
}
 
Example #11
Source File: ConfigurationImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void doTestIsFilterRegistered(Object provider, Class<?> providerClass) throws Exception {
    ConfigurationImpl c = new ConfigurationImpl(RuntimeType.SERVER);
    assertTrue(c.register(provider,
                          Collections.<Class<?>, Integer>singletonMap(ContainerResponseFilter.class, 1000)));
    assertTrue(c.isRegistered(provider));
    assertFalse(c.isRegistered(providerClass.newInstance()));
    assertTrue(c.isRegistered(providerClass));
    assertFalse(c.isRegistered(ContainerResponseFilter.class));
    assertFalse(c.register(provider,
                           Collections.<Class<?>, Integer>singletonMap(ContainerResponseFilter.class, 1000)));
    assertFalse(c.register(providerClass,
                           Collections.<Class<?>, Integer>singletonMap(ContainerResponseFilter.class, 1000)));
}
 
Example #12
Source File: JaxrsTest.java    From aries-jax-rs-whiteboard with Apache License 2.0 5 votes vote down vote up
@Test
public void testExtensionWithoutAName() {
    Dictionary<String, Object> properties = new Hashtable<>();

    properties.put(JAX_RS_EXTENSION, true);

    ServiceRegistration<ContainerResponseFilter> registration =
        bundleContext.registerService(
            ContainerResponseFilter.class, new TestFilter(), properties);

    try {
        RuntimeDTO runtimeDTO = _runtime.getRuntimeDTO();

        assertEquals(
            (long)registration.getReference().getProperty("service.id"),
            runtimeDTO.defaultApplication.extensionDTOs[0].serviceId);
    }
    finally {
        registration.unregister();
    }

}
 
Example #13
Source File: MessageResponseFilter.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(final ResourceInfo resourceInfo, final FeatureContext context) {
    if (resourceInfo.getResourceMethod().isAnnotationPresent(Deprecated.class)
            || resourceInfo.getResourceClass().isAnnotationPresent(Deprecated.class)) {
        context
                .register((ContainerResponseFilter) (requestContext, responseContext) -> responseContext
                        .getHeaders()
                        .putSingle("X-Talend-Warning",
                                "This endpoint is deprecated and will be removed without notice soon."));
    }
}
 
Example #14
Source File: ServerProviderFactory.java    From cxf with Apache License 2.0 4 votes vote down vote up
public List<ProviderInfo<ContainerResponseFilter>> getContainerResponseFilters(Set<String> names) {
    return getBoundFilters(containerResponseFilters, names);
}
 
Example #15
Source File: DPCXFNonSpringJaxrsServlet.java    From JaxRSProviders with Apache License 2.0 4 votes vote down vote up
@Override
protected void createServerFromApplication(ServletConfig servletConfig) throws ServletException {
	Application app = new DPCXFApplication();

	configurable.register(new DPCXFContainerResponseFilter(), ContainerResponseFilter.class);

	List<Class<?>> resourceClasses = new ArrayList<>();
	Map<Class<?>, ResourceProvider> map = new HashMap<>();
	List<Feature> features = new ArrayList<>();

	for (Object o : app.getSingletons()) {
		ResourceProvider rp = new SingletonResourceProvider(o);
		for (Class<?> c : app.getClasses()) {
			resourceClasses.add(c);
			map.put(c, rp);
		}
	}

	JAXRSServerFactoryBean bean = createJAXRSServerFactoryBean();
	bean.setBus(getBus());
	bean.setAddress("/");

	bean.setResourceClasses(resourceClasses);
	bean.setFeatures(features);

	for (Map.Entry<Class<?>, ResourceProvider> entry : map.entrySet()) {
		bean.setResourceProvider(entry.getKey(), entry.getValue());
	}

	Map<String, Object> appProps = app.getProperties();
	if (appProps != null) {
		bean.getProperties(true).putAll(appProps);
	}

	bean.setApplication(app);

	CXFServerConfiguration configuration = (CXFServerConfiguration) this.configurable.getConfiguration();
	bean.setProviders(new ArrayList<Object>(configuration.getExtensions()));

	bean.create();
}
 
Example #16
Source File: JaxrsTest.java    From aries-jax-rs-whiteboard with Apache License 2.0 4 votes vote down vote up
@Test
public void testSSEApplication() throws
        InterruptedException, MalformedURLException, TimeoutException {

    AtomicInteger atomicInteger = new AtomicInteger();

    registerApplication(
        new TestSSEApplication(), JAX_RS_APPLICATION_BASE, "/sse");
    registerAddon(
        new SSEResource(), JAX_RS_APPLICATION_SELECT,
        "(" + JAX_RS_APPLICATION_BASE + "=/sse)");
    registerExtension(
        ContainerResponseFilter.class,
        (req, res) -> atomicInteger.incrementAndGet(), "Filter",
        JAX_RS_APPLICATION_SELECT,
        "(" + JAX_RS_APPLICATION_BASE + "=/sse)");

    SseEventSourceFactory sseFactory = createSseFactory();

    SseEventSource source1 = sseFactory.newSource(
        createDefaultTarget().path("/sse").path("/subscribe"));

    SseEventSource source2 = sseFactory.newSource(
        createDefaultTarget().path("/sse").path("/subscribe"));

    ArrayList<String> source1Events = new ArrayList<>();
    ArrayList<String> source2Events = new ArrayList<>();

    Phaser phaser = new Phaser(2);

    source1.register(
        event -> {source1Events.add(event.readData(String.class));phaser.arrive(); });
    source2.register(
        event -> {source2Events.add(event.readData(String.class));phaser.arrive(); });

    source1.open();
    source2.open();

    phaser.awaitAdvanceInterruptibly(0, 10, TimeUnit.SECONDS);

    //The filter IS invoked on the subscribe method
    assertEquals(2, atomicInteger.get());

    WebTarget broadcast = createDefaultTarget().path("/sse").path(
        "/broadcast");

    broadcast.request().post(
        Entity.entity("message", MediaType.TEXT_PLAIN_TYPE));

    phaser.awaitAdvanceInterruptibly(1, 10, TimeUnit.SECONDS);

    assertEquals(Arrays.asList("welcome", "message"), source1Events);
    assertEquals(Arrays.asList("welcome", "message"), source2Events);

    source2.close();
    phaser.arrive();

    atomicInteger.set(0);

    broadcast.request().post(
        Entity.entity("another message", MediaType.TEXT_PLAIN_TYPE));

    phaser.awaitAdvanceInterruptibly(2, 10, TimeUnit.SECONDS);

    assertEquals(
        Arrays.asList("welcome", "message", "another message"),
        source1Events);
    assertEquals(Arrays.asList("welcome", "message"), source2Events);

    source1.close();

    //The filter IS invoked when broadcasting events
    assertEquals(1, atomicInteger.get());
}
 
Example #17
Source File: WebConfigImpl.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public WebConfig bindResponseFilter(ContainerResponseFilter filter) {
    app.register(filter);
    return this;
}
 
Example #18
Source File: RequestEvent.java    From ameba with MIT License 2 votes vote down vote up
/**
 * <p>getContainerResponseFilters.</p>
 *
 * @return a {@link java.lang.Iterable} object.
 */
public Iterable<ContainerResponseFilter> getContainerResponseFilters() {
    return event.getContainerResponseFilters();
}
 
Example #19
Source File: JerseyConfig.java    From dropwizard-guicey with MIT License 2 votes vote down vote up
/**
 * Show response filters {@link ContainerResponseFilter}.
 *
 * @return config instance for chained calls
 */
public JerseyConfig showResponseFilters() {
    types.add(ContainerResponseFilter.class);
    return this;
}
 
Example #20
Source File: WebConfig.java    From jweb-cms with GNU Affero General Public License v3.0 votes vote down vote up
WebConfig bindResponseFilter(ContainerResponseFilter filter);