下面列出了怎么用javax.ws.rs.core.Feature的API类实例代码及写法,或者点击链接到github查看源代码。
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()));
}
@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);
}
@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());
}
@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);
}
@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);
}
@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"));
}
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
}
}
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;
}
@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;
}
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);
}
}
}
@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);
}
@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);
}
@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());
}
@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());
}
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;
}));
}
@Override
public Feature feature(Injector injector) {
return context -> {
context.register(SenchaDeletePayloadParser.class);
return true;
};
}
@BeforeClass
public static void startTestRuntime() {
Feature f = c -> {
c.register(JWTAuthFilter.class);
return true;
};
startTestRuntime(ab -> ab.feature(f), Resource.class);
}
/**
* {@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);
}
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);
}
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;
}
}
}
}
@Override
public boolean isEnabled(Class<? extends Feature> featureCls) {
for (DynamicFeature f : dynamicFeatures) {
if (featureCls.isAssignableFrom(f.getClass())) {
return true;
}
}
return false;
}
@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();
}
@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;
}
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;
}
@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);
}
@Test
public void testRegisterFeatureInFeature() {
ServerProviderFactory pf = ServerProviderFactory.getInstance();
final Object provider = new WebApplicationExceptionMapper();
pf.registerUserProvider((Feature) context -> {
context.register((Feature) context2-> {
context2.register(provider);
return true;
});
return true;
});
ExceptionMapper<WebApplicationException> em =
pf.createExceptionMapper(WebApplicationException.class, new MessageImpl());
assertSame(provider, em);
}
@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));
}
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);
}
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();
}
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();
}