javax.ws.rs.core.Feature Java Examples

The following examples show how to use javax.ws.rs.core.Feature. 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: JaxrsTest.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
@Test
public void testFeatureExtension() {
    WebTarget webTarget = createDefaultTarget().path("/test-application");

    registerApplication(new TestApplication());

    registerExtension(
        Feature.class,
        context -> {
            context.register(new TestFilter());

            return true;
        },
        "Feature",
        JAX_RS_APPLICATION_SELECT,
        "(" + JAX_RS_APPLICATION_BASE + "=/test-application)");

    Response response = webTarget.request().get();

    assertEquals("Hello application", response.readEntity(String.class));

    assertEquals("true", response.getHeaders().getFirst("Filtered"));
}
 
Example #2
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testRegisterMbrMbwProviderAsMbwOnly() {
    ServerProviderFactory pf = ServerProviderFactory.getInstance();
    JAXBElementProvider<Book> customProvider = new JAXBElementProvider<>();
    pf.registerUserProvider((Feature) context -> {
        context.register(customProvider, MessageBodyWriter.class);
        return true;
    });
    MessageBodyWriter<Book> writer = pf.createMessageBodyWriter(Book.class, null, null,
                                                                MediaType.TEXT_XML_TYPE, new MessageImpl());
    assertSame(writer, customProvider);

    MessageBodyReader<Book> reader = pf.createMessageBodyReader(Book.class, null, null,
                                                                MediaType.TEXT_XML_TYPE, new MessageImpl());
    assertTrue(reader instanceof JAXBElementProvider);
    assertNotSame(reader, customProvider);
}
 
Example #3
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testRegisterMbrMbwProviderAsMbrOnly() {
    ServerProviderFactory pf = ServerProviderFactory.getInstance();
    JAXBElementProvider<Book> customProvider = new JAXBElementProvider<>();
    pf.registerUserProvider((Feature) context -> {
        context.register(customProvider, MessageBodyReader.class);
        return true;
    });
    MessageBodyReader<Book> reader = pf.createMessageBodyReader(Book.class, null, null,
                                                                MediaType.TEXT_XML_TYPE, new MessageImpl());
    assertSame(reader, customProvider);

    MessageBodyWriter<Book> writer = pf.createMessageBodyWriter(Book.class, null, null,
                                                                MediaType.TEXT_XML_TYPE, new MessageImpl());
    assertTrue(writer instanceof JAXBElementProvider);
    assertNotSame(writer, customProvider);
}
 
Example #4
Source File: JerseyClientUtil.java    From datacollector with Apache License 2.0 6 votes vote down vote up
public static AccessToken configureOAuth1(
  String consumerKey,
  String consumerSecret,
  String token,
  String tokenSecret,
  ClientBuilder clientBuilder
) {
  ConsumerCredentials consumerCredentials = new ConsumerCredentials(consumerKey, consumerSecret);

  AccessToken accessToken = new AccessToken(token, tokenSecret);
  Feature feature = OAuth1ClientSupport.builder(consumerCredentials)
      .feature()
      .accessToken(accessToken)
      .build();
  clientBuilder.register(feature);

  return accessToken;
}
 
Example #5
Source File: AgRuntime.java    From agrest with Apache License 2.0 6 votes vote down vote up
@Override
public boolean configure(FeatureContext context) {

    // this gives everyone access to the Agrest services
    context.property(AgRuntime.AGREST_CONTAINER_PROPERTY, injector);

    @SuppressWarnings("unchecked")
    Map<String, Class> bodyWriters =
            injector.getInstance(Key.getMapOf(String.class, Class.class, AgRuntime.BODY_WRITERS_MAP));

    for (Class<?> type : bodyWriters.values()) {
        context.register(type);
    }

    context.register(ResponseStatusDynamicFeature.class);

    context.register(EntityUpdateReader.class);
    context.register(EntityUpdateCollectionReader.class);

    for (Feature f : extraFeatures) {
        f.configure(context);
    }

    return true;
}
 
Example #6
Source File: SoaBundle.java    From soabase with Apache License 2.0 6 votes vote down vote up
private void checkAdminGuiceFeature(final Environment environment, final JerseyEnvironment jerseyEnvironment)
{
    try
    {
        Feature feature = new Feature()
        {
            @Override
            public boolean configure(FeatureContext context)
            {
                for ( Object obj : environment.jersey().getResourceConfig().getSingletons() )
                {
                    if ( obj instanceof InternalFeatureRegistrations )
                    {
                        ((InternalFeatureRegistrations)obj).apply(context);
                    }
                }
                return true;
            }
        };
        jerseyEnvironment.register(feature);
    }
    catch ( Exception ignore )
    {
        // ignore - GuiceBundle not added
    }
}
 
Example #7
Source File: JaxrsTest.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
@Test
public void testErroredExtensionInverseRegistrationOrder() {
    ServiceRegistration<Feature> serviceRegistration = registerExtension(
        Feature.class,
        context -> {
                throw new RuntimeException();
            },
        "ErrorFeature",
        JAX_RS_APPLICATION_SELECT,
        "(" + JAX_RS_APPLICATION_BASE + "=/test-application)");

    registerApplication(new TestApplication());

    RuntimeDTO runtimeDTO = _runtime.getRuntimeDTO();

    assertEquals(0, runtimeDTO.failedApplicationDTOs.length);
    assertEquals(1, runtimeDTO.failedExtensionDTOs.length);
    assertEquals(
        serviceRegistration.getReference().getProperty("service.id"),
        runtimeDTO.failedExtensionDTOs[0].serviceId);
    assertEquals(
        DTOConstants.FAILURE_REASON_UNKNOWN,
        runtimeDTO.failedExtensionDTOs[0].failureReason);
}
 
Example #8
Source File: JaxrsTest.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
@Test
public void testErroredExtension() {
    registerApplication(new TestApplication());

    ServiceRegistration<Feature> serviceRegistration = registerExtension(
        Feature.class,
        context -> {
            throw new RuntimeException();
        },
        "ErrorFeature",
        JAX_RS_APPLICATION_SELECT,
        "(" + JAX_RS_APPLICATION_BASE + "=/test-application)");

    RuntimeDTO runtimeDTO = _runtime.getRuntimeDTO();

    assertEquals(1, runtimeDTO.failedExtensionDTOs.length);
    assertEquals(
        serviceRegistration.getReference().getProperty("service.id"),
        runtimeDTO.failedExtensionDTOs[0].serviceId);
    assertEquals(
        DTOConstants.FAILURE_REASON_UNKNOWN,
        runtimeDTO.failedExtensionDTOs[0].failureReason);
}
 
Example #9
Source File: JaxrsTest.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultServiceReferencePropertiesAreAvailableInFeatures() {
    AtomicBoolean executed = new AtomicBoolean();
    AtomicReference<Object> propertyvalue = new AtomicReference<>();

    registerExtension(
        Feature.class, featureContext -> {
            executed.set(true);

            @SuppressWarnings("unchecked")
            Map<String, Object> properties =
                (Map<String, Object>)
                    featureContext.getConfiguration().getProperty(
                        "osgi.jaxrs.application.serviceProperties");
            propertyvalue.set(properties.get(JAX_RS_NAME));

            return false;
        }, "Feature", JAX_RS_APPLICATION_SELECT,
        "("+ JAX_RS_NAME + "=" + JAX_RS_DEFAULT_APPLICATION + ")");

    assertTrue(executed.get());
    assertEquals(JAX_RS_DEFAULT_APPLICATION, propertyvalue.get());
}
 
Example #10
Source File: ConfigurationImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
public ConfigurationImpl(Configuration parent) {
    if (parent != null) {
        this.props.putAll(parent.getProperties());
        this.runtimeType = parent.getRuntimeType();

        Set<Class<?>> providerClasses = new HashSet<>(parent.getClasses());
        for (Object o : parent.getInstances()) {
            if (!(o instanceof Feature)) {
                registerParentProvider(o, parent);
            } else {
                Feature f = (Feature)o;
                features.put(f, parent.isEnabled(f));
            }
            providerClasses.remove(o.getClass());
        }
        for (Class<?> cls : providerClasses) {
            registerParentProvider(createProvider(cls), parent);
        }

    }
}
 
Example #11
Source File: ShiroAuthorizationActivator.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
@Override
public void start(BundleContext context) throws Exception {

    _LOG.debug("Starting the Shiro JAX-RS Authorization Feature");

    _registration = coalesce(
            configuration("org.apache.aries.jax.rs.shiro.authorization"),
            just(() -> {

                _LOG.debug("Using the default configuration for the Shiro JAX-RS Authorization Feature");

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

                properties.put(
                    Constants.SERVICE_PID,
                    "org.apache.aries.jax.rs.shiro.authorization");

                return properties;
            })
    ).map(this::filter)
     .flatMap(p -> register(Feature.class, new ShiroAuthorizationFeature(), p))
     .run(context);
}
 
Example #12
Source File: ShiroAuthenticationActivator.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
OSGi<?> setupRealms(Map<String, Object> properties) {

        Object filter = properties.get("realms.target");

        OSGi<List<Realm>> realms;
        if(filter == null) {
            _LOG.debug("The Shiro JAX-RS Authentication Feature is accepting all realms");
            realms = accumulate(service(serviceReferences(Realm.class)));
        } else {
            _LOG.debug("The Shiro JAX-RS Authentication Feature is filtering realms using the filter {}", filter);
            realms = accumulate(service(serviceReferences(Realm.class, String.valueOf(filter))));
        }

        return realms.map(ShiroAuthenticationFeatureProvider::new)
                .flatMap(f -> register(Feature.class, f,  properties)
                        .effects(x -> {}, x -> f.close()));
    }
 
Example #13
Source File: SenchaFeatureProvider.java    From agrest with Apache License 2.0 5 votes vote down vote up
@Override
public Feature feature(Injector injector) {
    return context -> {
        context.register(SenchaDeletePayloadParser.class);
        return true;
    };
}
 
Example #14
Source File: JaxrsTest.java    From aries-jax-rs-whiteboard with Apache License 2.0 5 votes vote down vote up
@Test
public void testServiceReferencePropertiesAreAvailableInStaticFeatures() {
    AtomicBoolean executed = new AtomicBoolean();
    AtomicReference<Object> propertyvalue = new AtomicReference<>();

    registerApplication(
        new Application() {
            @Override
            public Set<Object> getSingletons() {
                return new HashSet<>(Arrays.asList(
                    (Feature)featureContext -> {
                        executed.set(true);

                        @SuppressWarnings("unchecked")
                        Map<String, Object> properties =
                            (Map<String, Object>)
                                featureContext.
                                    getConfiguration().
                                    getProperty(
                                    "osgi.jaxrs.application." +
                                        "serviceProperties");
                        propertyvalue.set(properties.get("property"));

                        return false;
                    },
                    new Object() {

                        @GET
                        public String hello() {
                            return "hello";
                        }
                    }
                    ));
            }
        }, JAX_RS_NAME, "test", "property", true);

    assertTrue(executed.get());
    assertEquals(true, propertyvalue.get());
}
 
Example #15
Source File: JaxrsTest.java    From aries-jax-rs-whiteboard with Apache License 2.0 5 votes vote down vote up
@Test
public void testServiceReferencePropertiesAreAvailableInFeatures() {
    AtomicBoolean executed = new AtomicBoolean();
    AtomicReference<Object> propertyvalue = new AtomicReference<>();

    registerExtension(
        Feature.class, featureContext -> {
            executed.set(true);

            @SuppressWarnings("unchecked")
            Map<String, Object> properties =
                (Map<String, Object>)
                    featureContext.getConfiguration().getProperty(
                        "osgi.jaxrs.application.serviceProperties");
            propertyvalue.set(properties.get("property"));

            return false;
        }, "Feature", JAX_RS_APPLICATION_SELECT, "(property=true)");

    registerApplication(
        new Application() {
        @Override
        public Set<Object> getSingletons() {
            return Collections.singleton(
                new Object() {

                    @GET
                    public String hello() {
                        return "hello";
                    }
                });
        }
    }, JAX_RS_NAME, "test", "property", true);

    assertTrue(executed.get());
    assertEquals(true, propertyvalue.get());
}
 
Example #16
Source File: JerseyClientHeaders.java    From tutorials with MIT License 5 votes vote down vote up
public static Response bearerAuthenticationWithOAuth1AtClientLevel(String token, String consumerKey) {
    ConsumerCredentials consumerCredential = new ConsumerCredentials(consumerKey, BEARER_CONSUMER_SECRET);
    AccessToken accessToken = new AccessToken(token, BEARER_ACCESS_TOKEN_SECRET);
    Feature feature = OAuth1ClientSupport
            .builder(consumerCredential)
            .feature()
            .accessToken(accessToken)
            .build();

    Client client = ClientBuilder.newBuilder().register(feature).build();
    return client.target(TARGET)
            .path(MAIN_RESOURCE)
            .request()
            .get();
}
 
Example #17
Source File: JerseyClientHeaders.java    From tutorials with MIT License 5 votes vote down vote up
public static Response bearerAuthenticationWithOAuth2AtClientLevel(String token) {
    Feature feature = OAuth2ClientSupport.feature(token);

    Client client = ClientBuilder.newBuilder().register(feature).build();
    return client.target(TARGET)
            .path(MAIN_RESOURCE)
            .request()
            .get();
}
 
Example #18
Source File: ProviderFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegisterInFeature() {
    ServerProviderFactory pf = ServerProviderFactory.getInstance();
    final Object provider = new WebApplicationExceptionMapper();
    pf.registerUserProvider((Feature) context -> {
        context.register(provider);
        return true;
    });
    ExceptionMapper<WebApplicationException> em =
        pf.createExceptionMapper(WebApplicationException.class, new MessageImpl());
    assertSame(provider, em);
}
 
Example #19
Source File: JerseyClientHeaders.java    From tutorials with MIT License 5 votes vote down vote up
public static Response bearerAuthenticationWithOAuth1AtRequestLevel(String token, String consumerKey) {
    ConsumerCredentials consumerCredential = new ConsumerCredentials(consumerKey, BEARER_CONSUMER_SECRET);
    AccessToken accessToken = new AccessToken(token, BEARER_ACCESS_TOKEN_SECRET);
    Feature feature = OAuth1ClientSupport
            .builder(consumerCredential)
            .feature()
            .build();

    Client client = ClientBuilder.newBuilder().register(feature).build();
    return client.target(TARGET)
            .path(MAIN_RESOURCE)
            .request()
            .property(OAuth1ClientSupport.OAUTH_PROPERTY_ACCESS_TOKEN, accessToken)
            .get();
}
 
Example #20
Source File: ConfigurationImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testFeatureDisabledInstance() {
    FeatureContextImpl featureContext = new FeatureContextImpl();
    Configurable<FeatureContext> configurable = new ConfigurableImpl<>(featureContext, RuntimeType.SERVER);
    featureContext.setConfigurable(configurable);
    Feature feature = new DisablableFeature();
    featureContext.register(feature);

    Configuration config = configurable.getConfiguration();
    assertFalse(config.isEnabled(feature));
}
 
Example #21
Source File: AgBuilder.java    From agrest with Apache License 2.0 5 votes vote down vote up
private void loadExceptionMapperFeature(Collection<Feature> collector, Injector i) {

        i.getInstance(Key.getMapOf(String.class, ExceptionMapper.class))
                .values()
                .forEach(em -> collector.add(c -> {
                    c.register(em);
                    return true;
                }));
    }
 
Example #22
Source File: ConfigurableImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
private C doRegister(Object provider, Map<Class<?>, Integer> contracts) {
    if (!checkConstraints(provider)) {
        return configurable;
    }
    if (provider instanceof Feature) {
        Feature feature = (Feature)provider;
        boolean enabled = feature.configure(new FeatureContextImpl(this));
        config.setFeature(feature, enabled);

        return configurable;
    }
    config.register(provider, contracts);
    return configurable;
}
 
Example #23
Source File: ConfigurationImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isEnabled(Class<? extends Feature> f) {
    for (Entry<Feature, Boolean> entry : features.entrySet()) {
        Feature feature = entry.getKey();
        Boolean enabled = entry.getValue();
        if (f.isAssignableFrom(feature.getClass()) && enabled.booleanValue()) {
            return true;
        }
    }
    return false;
}
 
Example #24
Source File: JerseyClientHeaders.java    From tutorials with MIT License 5 votes vote down vote up
public static Response bearerAuthenticationWithOAuth2AtRequestLevel(String token, String otherToken) {
    Feature feature = OAuth2ClientSupport.feature(token);

    Client client = ClientBuilder.newBuilder().register(feature).build();
    return client.target(TARGET)
            .path(MAIN_RESOURCE)
            .request()
            .property(OAuth2ClientSupport.OAUTH2_PROPERTY_ACCESS_TOKEN, otherToken)
            .get();
}
 
Example #25
Source File: JWT_Client_IT.java    From agrest with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startTestRuntime() {
    Feature f = c -> {
        c.register(JWTAuthFilter.class);
        return true;
    };
    startTestRuntime(ab -> ab.feature(f), Resource.class);
}
 
Example #26
Source File: ConfigurationImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public Map<Class<?>, Integer> getContracts(Class<?> cls) {
    for (Object o : getInstances()) {
        if (cls.isAssignableFrom(o.getClass())) {
            if (o instanceof Feature) {
                return Collections.emptyMap();
            } else {
                return providers.get(o);
            }
        }
    }
    return Collections.emptyMap();
}
 
Example #27
Source File: LocalResourceAddon.java    From ameba with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void setup(final Application application) {

    final Set<ClassInfo> classInfoSet = Sets.newLinkedHashSet();
    subscribeSystemEvent(ClassFoundEvent.class, event -> event.accept(info -> {
        if (info.containsAnnotations(Service.class)) {
            classInfoSet.add(info);
            return true;
        }
        return false;
    }));

    final Feature localResource = new Feature() {

        @Inject
        private ServiceLocator locator;

        @Override
        public boolean configure(FeatureContext context) {
            for (ClassInfo classInfo : classInfoSet) {
                ServiceLocatorUtilities.addClasses(locator, classInfo.toClass());
            }
            classInfoSet.clear();
            return true;
        }
    };

    application.register(localResource);
}
 
Example #28
Source File: ServerProviderFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isEnabled(Class<? extends Feature> featureCls) {
    for (DynamicFeature f : dynamicFeatures) {
        if (featureCls.isAssignableFrom(f.getClass())) {
            return true;
        }
    }
    return false;
}
 
Example #29
Source File: ServerProviderFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void injectApplicationIntoFeature(Feature feature) {
    if (application != null) {
        AbstractResourceInfo info = new AbstractResourceInfo(feature.getClass(),
                                                             ClassHelper.getRealClass(feature),
                                                             true,
                                                             true,
                                                             getBus()) {
            @Override
            public boolean isSingleton() {
                return false;
            }
        };
        Method contextMethod = info.getContextMethods().get(Application.class);
        if (contextMethod != null) {
            InjectionUtils.injectThroughMethod(feature, contextMethod, application.getProvider());
            return;
        }
        for (Field contextField : info.getContextFields()) {
            if (Application.class == contextField.getType()) {
                InjectionUtils.injectContextField(info, contextField, feature, application.getProvider());
                break;
            }
        }
        
    }
    
}
 
Example #30
Source File: BookServer20.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void run() {
    Bus bus = BusFactory.getDefaultBus();
    setBus(bus);
    JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
    sf.setBus(bus);
    sf.setResourceClasses(BookStore.class);

    List<Object> providers = new ArrayList<>();

    providers.add(new PreMatchContainerRequestFilter2());
    providers.add(new PreMatchContainerRequestFilter());
    providers.add(new PostMatchContainerResponseFilter());
    providers.add((Feature) context -> {
        context.register(new PostMatchContainerResponseFilter3());

        return true;
    });
    providers.add(new PostMatchContainerResponseFilter2());
    providers.add(new CustomReaderBoundInterceptor());
    providers.add(new CustomReaderInterceptor());
    providers.add(new CustomWriterInterceptor());
    providers.add(new CustomDynamicFeature());
    providers.add(new PostMatchContainerRequestFilter());
    providers.add(new FaultyContainerRequestFilter());
    providers.add(new PreMatchReplaceStreamOrAddress());
    providers.add(new ServerTestFeature());
    providers.add(new JacksonJaxbJsonProvider());
    providers.add(new IOExceptionMapper());
    sf.setApplication(new Application());
    sf.setProviders(providers);
    sf.setResourceProvider(BookStore.class,
                           new SingletonResourceProvider(new BookStore(), true));
    sf.setAddress("http://localhost:" + PORT + "/");
    server = sf.create();
    BusFactory.setDefaultBus(null);
    BusFactory.setThreadDefaultBus(null);
}