下面列出了怎么用javax.ws.rs.core.FeatureContext的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void configure(final ResourceInfo resourceInfo, final FeatureContext configuration) {
AnnotatedMethod am = new AnnotatedMethod(resourceInfo.getResourceMethod());
// RolesAllowed on the method takes precedence over PermitAll
RolesAllowed ra = am.getAnnotation(RolesAllowed.class);
if (ra != null) {
configuration.register(AuthCheckFilter.INSTANCE);
return;
}
// PermitAll takes precedence over RolesAllowed on the class
// This avoids putting AuthCheckFilter in the request flow for all path's which
// are defined under PermitAll annotation. That is requests for "/", "/login", "/mainLogin" and "/spnegoLogin"
// path's doesn't go through AuthCheckFilter.
if (am.isAnnotationPresent(PermitAll.class)) {
// Do nothing.
return;
}
// RolesAllowed on the class takes precedence over PermitAll
ra = resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);
if (ra != null) {
configuration.register(AuthCheckFilter.INSTANCE);
}
}
@Override
public boolean configure(FeatureContext context) {
boolean enabled = mpJwtEnabled();
if (enabled) {
context.register(JWTAuthorizationFilterRegistrar.class);
if (!SmallRyeJWTAuthCDIExtension.isHttpAuthMechanismEnabled()) {
context.register(JWTAuthenticationFilter.class);
JAXRSLogging.log.eeSecurityNotInUseButRegistered(JWTAuthenticationFilter.class.getSimpleName());
}
JAXRSLogging.log.mpJWTLoginConfigPresent(getClass().getSimpleName());
} else {
JAXRSLogging.log.mpJWTLoginConfigNotFound(getClass().getSimpleName());
}
return enabled;
}
@Override
public boolean configure(FeatureContext context) {
context.register(new AbstractBinder() {
@Override
public void configure() {
bind(TokenAuthenticator.class)
.in(Singleton.class);
bind(TokenFactory.class)
.in(Singleton.class);
bind(TokenFactoryProvider.class)
.to(ValueFactoryProvider.class)
.in(Singleton.class);
bind(TokenParamInjectionResolver.class)
.to(new TypeLiteral<InjectionResolver<RobeAuth>>() {
})
.in(Singleton.class);
}
});
return true;
}
private void register(FeatureContext context, Class<?> providerClass) {
boolean isCxf = context.getClass().getName().startsWith("org.apache.cxf");
/*
* With CXF there is no CDI injection if JAX-RS providers are registered via
* context.register(Class). So we try to lookup provider instances from CDI
* and register them instead.
* See: https://issues.apache.org/jira/browse/CXF-7501
*/
if (isCxf) {
List<?> providerInstances = CdiUtils.getApplicationBeans(providerClass);
if (!providerInstances.isEmpty()) {
context.register(providerInstances.get(0));
} else {
context.register(providerClass);
}
}
// will work for all other containers
else {
context.register(providerClass);
}
}
@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 boolean configure(final FeatureContext context) {
final Configuration config = context.getConfiguration();
final String jsonFeature = CommonProperties.getValue(config.getProperties(), config.getRuntimeType(), InternalProperties.JSON_FEATURE, JSON_FEATURE,
String.class);
// Other JSON providers registered.
if (!JSON_FEATURE.equalsIgnoreCase(jsonFeature)) {
return false;
}
// Disable other JSON providers.
context.property(PropertiesHelper.getPropertyNameForRuntime(InternalProperties.JSON_FEATURE, config.getRuntimeType()), JSON_FEATURE);
// Register FastJson.
if (!config.isRegistered(FastJsonProvider.class)) {
context.register(FastJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
}
return true;
}
private void testSecurityRegistration(boolean enabled) {
CrnkFeature feature = new CrnkFeature();
feature.setSecurityEnabled(enabled);
feature.securityContext = Mockito.mock(SecurityContext.class);
FeatureContext context = Mockito.mock(FeatureContext.class);
Mockito.when(context.getConfiguration()).thenReturn(Mockito.mock(Configuration.class));
feature.configure(context);
CrnkBoot boot = feature.getBoot();
if (enabled) {
SecurityProvider securityProvider = boot.getModuleRegistry().getSecurityProvider();
Assert.assertNotNull(securityProvider);
} else {
Assert.assertEquals(0, boot.getModuleRegistry().getSecurityProviders().size());
}
}
private FeatureContext createServerFeatureContext() {
final FeatureContextImpl featureContext = new FeatureContextImpl();
final ServerConfigurableFactory factory = getBus().getExtension(ServerConfigurableFactory.class);
final Configurable<FeatureContext> configImpl = (factory == null)
? new ServerFeatureContextConfigurable(featureContext)
: factory.create(featureContext);
featureContext.setConfigurable(configImpl);
if (application != null) {
Map<String, Object> appProps = application.getProvider().getProperties();
for (Map.Entry<String, Object> entry : appProps.entrySet()) {
configImpl.property(entry.getKey(), entry.getValue());
}
}
return featureContext;
}
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
List<Annotation> authzSpecs = new ArrayList<>();
for (Class<? extends Annotation> annotationClass : shiroAnnotations) {
// XXX What is the performance of getAnnotation vs getAnnotations?
Annotation classAuthzSpec = resourceInfo.getResourceClass().getAnnotation(annotationClass);
Annotation methodAuthzSpec = resourceInfo.getResourceMethod().getAnnotation(annotationClass);
if (classAuthzSpec != null) authzSpecs.add(classAuthzSpec);
if (methodAuthzSpec != null) authzSpecs.add(methodAuthzSpec);
}
if (!authzSpecs.isEmpty()) {
context.register(new AuthorizationFilter(authzSpecs), Priorities.AUTHORIZATION);
}
}
@Override
public boolean configure(FeatureContext context) {
final Configuration config = context.getConfiguration();
final String jsonFeature = CommonProperties.getValue(config.getProperties(), config.getRuntimeType(),
InternalProperties.JSON_FEATURE, JSON_FEATURE_CLASSNAME, String.class);
// Other JSON providers registered.
if (!JSON_FEATURE_CLASSNAME.equalsIgnoreCase(jsonFeature)) {
LOGGER.error("Another JSON provider has been registered: {}", jsonFeature);
return false;
}
// Disable other JSON providers.
context.property(PropertiesHelper.getPropertyNameForRuntime(InternalProperties.JSON_FEATURE, config.getRuntimeType()),
JSON_FEATURE_CLASSNAME);
context.register(DACJacksonJaxbJsonProvider.class);
return true;
}
@Override
public boolean configure(FeatureContext context) {
Configuration configuration = context.getConfiguration();
Boolean enabled = PropertyHelper.getProperty(configuration, RestServerV2.TEST_API_ENABLE);
// Default is not enabled
if (enabled == null || !enabled) {
return false;
}
for (Class<?> resource : scanResult.getAnnotatedClasses(RestResourceUsedForTesting.class)) {
context.register(resource);
}
return true;
}
@Override
public boolean configure(FeatureContext context) {
final Configuration configuration = context.getConfiguration();
Boolean disabled = PropertyHelper.getProperty(configuration, RestServerV2.DAC_AUTH_FILTER_DISABLE);
// Default is not disabled
if (disabled != null && disabled) {
return false;
}
context.register(DACAuthFilter.class);
if (!configuration.isRegistered(RolesAllowedDynamicFeature.class)) {
context.register(RolesAllowedDynamicFeature.class);
}
return true;
}
@Override
public void configure(FeatureContext context) {
final int priorityInc = 3000;
// Jersey MOXY provider have higher priority(7000), so we need set higher than it
int priority = Priorities.USER + priorityInc;
Configuration config = context.getConfiguration();
if (!config.isRegistered(ParsecValidationExceptionMapper.class)) {
context.register(ParsecValidationExceptionMapper.class, priority);
}
if (!config.isRegistered(ValidationConfigurationContextResolver.class)) {
context.register(ValidationConfigurationContextResolver.class, priority);
}
if (!config.isRegistered(ParsecMoxyFeature.class)) {
context.register(ParsecMoxyFeature.class, priority);
}
if (!config.isRegistered(JaxbExceptionMapper.class)) {
context.register(JaxbExceptionMapper.class, priority);
}
}
private void applyInternalCommonConfig(FeatureContext context, InternalCommonConfig internalCommonConfig)
{
for ( Class<?> clazz : internalCommonConfig.getClasses() )
{
log.info(String.format("Registering %s as a component", clazz));
context.register(clazz);
}
for ( Object obj : internalCommonConfig.getInstances() )
{
log.info(String.format("Registering instance of %s as a component", obj.getClass()));
context.register(obj);
}
for ( Map.Entry<String, Object> entry : internalCommonConfig.getProperties().entrySet() )
{
String key = entry.getKey();
Object value = entry.getValue();
log.info(String.format("Registering property key: %s\tvalue: %s", key, value));
context.property(key, value);
}
}
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
final AnnotatedMethod am = new AnnotatedMethod(resourceInfo.getResourceMethod());
final Annotation[][] parameterAnnotations = am.getParameterAnnotations();
if (am.isAnnotationPresent(RolesAllowed.class) || am.isAnnotationPresent(DenyAll.class) ||
am.isAnnotationPresent(PermitAll.class)) {
context.register(authFilter);
} else {
for (Annotation[] annotations : parameterAnnotations) {
for (Annotation annotation : annotations) {
if (annotation instanceof Auth) {
context.register(authFilter);
return;
}
}
}
}
}
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
AnnotatedMethod annotatedMethod = new AnnotatedMethod(resourceInfo.getResourceMethod());
Annotation[][] parameterAnnotations = annotatedMethod.getParameterAnnotations();
Class<?>[] parameterTypes = annotatedMethod.getParameterTypes ();
Type[] parameterGenericTypes = annotatedMethod.getGenericParameterTypes();
verifyAuthAnnotations(parameterAnnotations);
for (int i=0;i<parameterAnnotations.length;i++) {
for (Annotation annotation : parameterAnnotations[i]) {
if (annotation instanceof Auth) {
Type parameterType = parameterTypes[i];
if (parameterType == Optional.class) {
parameterType = ((ParameterizedType)parameterGenericTypes[i]).getActualTypeArguments()[0];
context.register(new WebApplicationExceptionCatchingFilter(getFilterFor(parameterType)));
} else {
context.register(getFilterFor(parameterType));
}
}
}
}
}
@Override
public boolean configure(FeatureContext context) {
if (COMPONENT_SERVICE_LOCATOR != null) {
ExtrasUtilities.bridgeServiceLocator(this.servletServiceLocator, COMPONENT_SERVICE_LOCATOR);
}
return true;
}
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context)
{
AccessType accessType = resourceAccessType.getAccessType(resourceInfo);
switch (accessType) {
case PUBLIC:
// no authentication or authorization
break;
case WEB_UI:
context.register(webUiAuthenticationFilter);
context.register(new DisposeIdentityResponseFilter());
break;
case AUTHENTICATED_USER:
context.register(authenticationFilter);
context.register(new DisposeIdentityResponseFilter());
break;
case MANAGEMENT_READ:
case MANAGEMENT_WRITE:
context.register(new ManagementAuthenticationFilter(fixedManagementUser, fixedManagementUserForHttps, authenticationFilter));
context.register(new ManagementAuthorizationFilter(accessControl, groupProvider, accessType == MANAGEMENT_READ));
context.register(new DisposeIdentityResponseFilter());
break;
case INTERNAL_ONLY:
context.register(new InternalOnlyRequestFilter(internalAuthenticationManager));
break;
default:
throw new IllegalArgumentException("Unknown mode: " + accessType);
}
}
@Override
public boolean configure(FeatureContext context) {
if (context.getConfiguration().isEnabled(BlockingAsyncFeature.class)) {
return false;
}
context.register(new BlockingAsyncBinder());
return true;
}
@Override
public boolean configure(FeatureContext context) {
if (client == null) {
client = createClient();
}
client.register(RxBodyReader.class);
context.register(new Binder());
return true;
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("unchecked")
public boolean configure(FeatureContext context) {
context.register(new WebSocketBinder());
if (serverContainer == null) {
logger.warn(Messages.get("web.socket.server.unsupported"));
}
for (Class endpointClass : endpointClasses) {
WebSocket webSocket = getAnnotation(WebSocket.class, endpointClass);
if (webSocket == null) continue;
Class<? extends Annotation> scope = getScope(endpointClass);
final Binding binding = Bindings.service(endpointClass).to(endpointClass).in(scope);
Providers.getProviderContracts(endpointClass).forEach(binding::to);
injectionManager.register(binding);
DefaultServerEndpointConfig endpointConfig = new DefaultServerEndpointConfig(
injectionManager,
endpointClass,
webSocket
);
if (serverContainer != null) {
try {
serverContainer.addEndpoint(endpointConfig);
} catch (DeploymentException e) {
throw new WebSocketException(e);
}
}
if (webSocket.withSockJS()) {
// create resource use modelProcessor
}
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean configure(FeatureContext context) {
if (!context.getConfiguration().isRegistered(TextMessageBodyWriter.class)) {
context.register(TextMessageBodyWriter.class);
}
if (!context.getConfiguration().isRegistered(CaptchaWriterInterceptor.class)) {
context.register(CaptchaWriterInterceptor.class);
}
if (!context.getConfiguration().isRegistered(PathMessageBodyWriter.class)) {
context.register(PathMessageBodyWriter.class);
}
if (!context.getConfiguration().isRegistered(ContentLengthWriterInterceptor.class)) {
context.register(ContentLengthWriterInterceptor.class);
}
if (!context.getConfiguration().isRegistered(StreamingWriterInterceptor.class)) {
context.register(StreamingWriterInterceptor.class);
// streaming process
context.register(BlobStreamingProcess.class);
context.register(BytesStreamingProcess.class);
context.register(ClobStreamingProcess.class);
context.register(FileStreamingProcess.class);
context.register(InputStreamingProcess.class);
context.register(PathStreamingProcess.class);
}
return false;
}
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
// ignore any other method signatures - in those cases we assume
// response status is set by the user on their own..
if (AgResponse.class.isAssignableFrom(resourceInfo.getResourceMethod().getReturnType())) {
context.register(ResponseStatusFilter.class);
}
}
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
context.register(new ContainerRequestFilter() {
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if (requestContext.getUriInfo().getPath().endsWith("filtered")) {
throw new ForbiddenException();
}
}
}, Priorities.AUTHORIZATION);
}
/**
* All repositories with JAX-RS action need to be registered with JAX-RS as singletons.
*
* @param context of jaxrs
* @param boot of katharsis
*/
private void registerActionRepositories(FeatureContext context, KatharsisBoot boot) {
ResourceRegistry resourceRegistry = boot.getResourceRegistry();
Collection<RegistryEntry> registryEntries = resourceRegistry.getResources();
for(RegistryEntry registryEntry : registryEntries){
ResourceRepositoryInformation repositoryInformation = registryEntry.getRepositoryInformation();
if(!repositoryInformation.getActions().isEmpty()){
ResourceRepositoryAdapter<?, Serializable> repositoryAdapter = registryEntry.getResourceRepository(null);
Object resourceRepository = repositoryAdapter.getResourceRepository();
context.register(resourceRepository);
}
}
}
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
Method method = resourceInfo.getResourceMethod();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (Annotation[] annotations : parameterAnnotations) {
for (Annotation annotation : annotations) {
if (annotation.annotationType().equals(Session.class) && !method.getName().startsWith("log")) {
context.register(NiPingAuthFilter.class);
}
}
}
}
@Override
public boolean configure(final FeatureContext context) {
if (!context.getConfiguration().isRegistered(JacksonJaxbJsonProvider.class)) {
context.register(JsonParseExceptionMapper.class);
context.register(JsonMappingExceptionMapper.class);
context.register(new JaxRSClientJacksonJaxbJsonProvider(reg, cl));
}
return true;
}
@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));
}
@Before
public void setup() {
FeatureContext featureContext = Mockito.mock(FeatureContext.class);
Mockito.when(featureContext.getConfiguration()).thenReturn(Mockito.mock(Configuration.class));
feature = new CrnkFeature();
feature.configure(featureContext);
uriInfo = Mockito.mock(UriInfo.class);
Mockito.when(uriInfo.getQueryParameters()).thenReturn(Mockito.mock(MultivaluedMap.class));
requestContext = Mockito.mock(ContainerRequestContext.class);
Mockito.when(requestContext.getUriInfo()).thenReturn(uriInfo);
context = new JaxrsRequestContext(requestContext, feature);
}
/**
* {@inheritDoc}
*/
@Override
public boolean configure(FeatureContext context) {
Configuration cfg = context.getConfiguration();
if (!cfg.isRegistered(CommonExprTransformer.class))
context.register(CommonExprTransformer.class);
if (!cfg.isRegistered(CommonExprArgTransformer.class))
context.register(CommonExprArgTransformer.class);
if (!cfg.isRegistered(QuerySyntaxExceptionMapper.class))
context.register(QuerySyntaxExceptionMapper.class);
return true;
}