javax.ws.rs.core.FeatureContext Java Examples

The following examples show how to use javax.ws.rs.core.FeatureContext. 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: ParsecValidationAutoDiscoverable.java    From parsec-libraries with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #2
Source File: TokenFeature.java    From robe with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #3
Source File: SmallRyeJWTAuthJaxRsFeature.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #4
Source File: AuthDynamicFeature.java    From dropwizard-java8 with Apache License 2.0 6 votes vote down vote up
@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;
                }
            }
        }
    }
}
 
Example #5
Source File: AuthDynamicFeature.java    From dropwizard-simpleauth with Apache License 2.0 6 votes vote down vote up
@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));
        }
      }
    }
  }
}
 
Example #6
Source File: AuthDynamicFeature.java    From Bats with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #7
Source File: GuiceBundle.java    From soabase with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #8
Source File: DACAuthFilterFeature.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #9
Source File: TestResourcesFeature.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #10
Source File: DefaultConfigProvider.java    From krazo with Apache License 2.0 6 votes vote down vote up
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);
        }


    }
 
Example #11
Source File: DACJacksonJaxbJsonFeature.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #12
Source File: AuthorizationFilterFeature.java    From shiro-jersey with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #13
Source File: ServerProviderFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #14
Source File: CrnkFeatureTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
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());
	}
}
 
Example #15
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 #16
Source File: FastJsonFeature.java    From fastjson-jaxrs-json-provider with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #17
Source File: ClientTracingFeature.java    From java-jaxrs with Apache License 2.0 5 votes vote down vote up
@Override
public boolean configure(FeatureContext context) {
    if (log.isLoggable(Level.FINE)) {
        log.fine("Registering client OpenTracing, with configuration:" + builder.toString());
    }
    context.register(new ClientTracingFilter(builder.tracer, builder.spanDecorators),
        builder.priority);

    if (builder.traceSerialization) {
        context.register(
            new ClientTracingInterceptor(builder.tracer, builder.serializationSpanDecorators),
            builder.serializationPriority);
    }
    return true;
}
 
Example #18
Source File: MCRGuiceBridgeFeature.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean configure(FeatureContext context) {
    Objects.requireNonNull(scopedLocator, "HK2 ServiceLocator was not injected");
    Injector injector = MCRInjectorConfig.injector();
    GuiceBridge.getGuiceBridge().initializeGuiceBridge(scopedLocator);
    GuiceIntoHK2Bridge guiceBridge = scopedLocator.getService(GuiceIntoHK2Bridge.class);
    guiceBridge.bridgeGuiceInjector(injector);
    LogManager.getLogger().info("Initialize hk2 - guice bridge...done");
    return true;
}
 
Example #19
Source File: SecuredResourceFilterFactory.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext featureContext) {

    Method am = resourceInfo.getResourceMethod();

    if (logger.isTraceEnabled()) {
        logger.trace("configure {} method {}",
            resourceInfo.getResourceClass().getSimpleName(), resourceInfo.getResourceMethod().getName());
    }

    boolean sysadminLocalhostOnly =
            Boolean.parseBoolean(properties.getProperty("usergrid.sysadmin.localhost.only", "false"));

    if (sysadminLocalhostOnly) {
        // priority = PRIORITY_SUPERUSER forces this to run first
        featureContext.register( SysadminLocalhostFilter.class, PRIORITY_SUPERUSER );
    }

    if ( am.isAnnotationPresent( RequireApplicationAccess.class ) ) {
        featureContext.register( ApplicationFilter.class, PRIORITY_DEFAULT);
    }
    else if ( am.isAnnotationPresent( RequireOrganizationAccess.class ) ) {
        featureContext.register( OrganizationFilter.class, PRIORITY_DEFAULT);
    }
    else if ( am.isAnnotationPresent( RequireSystemAccess.class ) ) {
        featureContext.register( SystemFilter.class, PRIORITY_DEFAULT);
    }
    else if ( am.isAnnotationPresent( RequireAdminUserAccess.class ) ) {
        featureContext.register( SystemFilter.AdminUserFilter.class, PRIORITY_DEFAULT);
    }
    else if ( am.isAnnotationPresent( CheckPermissionsForPath.class ) ) {
        featureContext.register( PathPermissionsFilter.class, PRIORITY_DEFAULT);
    }

}
 
Example #20
Source File: RolesAnnotationFilter.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
  final AnnotatedMethod am = new AnnotatedMethod(resourceInfo.getResourceMethod());

  // DenyAll on the method take precedence over RolesAllowed and PermitAll
  if (am.isAnnotationPresent(DenyAll.class)) {
    context.register(new RolesAllowedRequestFilter());
    return;
  }

  // RolesAllowed on the method takes precedence over PermitAll
  RolesAllowed ra = am.getAnnotation(RolesAllowed.class);
  if (ra != null) {
    context.register(new RolesAllowedRequestFilter(ra.value()));
    return;
  }

  // PermitAll takes precedence over RolesAllowed on the class
  if (am.isAnnotationPresent(PermitAll.class)) {
    // Do nothing.
    return;
  }

  // DenyAll can't be attached to classes

  // RolesAllowed on the class takes precedence over PermitAll
  ra = resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);
  if (ra != null) {
    context.register(new RolesAllowedRequestFilter(ra.value()));
  }
}
 
Example #21
Source File: MCRRestFeature.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void registerAccessFilter(FeatureContext context, Class<?> resourceClass, Method resourceMethod) {
    if (resourceClass.getPackageName().contains(".v1")) {
        context.register(org.mycore.restapi.v1.MCRRestAuthorizationFilter.class);
    } else {
        context.register(org.mycore.restapi.v2.MCRRestAuthorizationFilter.class);
    }
    super.registerAccessFilter(context, resourceClass, resourceMethod);
}
 
Example #22
Source File: HelloDynamicBinding.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    LOG.info("Hello dynamic binding");

    if (Greetings.class.equals(resourceInfo.getResourceClass()) && resourceInfo.getResourceMethod()
        .getName()
        .contains("HiGreeting")) {
        context.register(ResponseServerFilter.class);
    }

}
 
Example #23
Source File: JacksonFilteringFeature.java    From ameba with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean configure(final FeatureContext context) {
    final Configuration config = context.getConfiguration();

    if (!config.isRegistered(JacksonFilteringFeature.Binder.class)) {
        context.register(new Binder());
        return true;
    }
    return false;
}
 
Example #24
Source File: EmbeddedServer.java    From java-client with Apache License 2.0 5 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    if (classInterceptor.containsKey(resourceInfo.getResourceClass())
            && resourceInfo.getResourceMethod().getName().contains("post")) {
        context.register(classInterceptor.get(resourceInfo.getResourceClass()));
    }
}
 
Example #25
Source File: QueryDslFeature.java    From ameba with MIT License 5 votes vote down vote up
/**
 * {@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;
}
 
Example #26
Source File: JaxrsRequestContextTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #27
Source File: InjectionBridge.java    From clouditor with Apache License 2.0 5 votes vote down vote up
@Override
public boolean configure(FeatureContext context) {
  if (COMPONENT_SERVICE_LOCATOR != null) {
    ExtrasUtilities.bridgeServiceLocator(this.servletServiceLocator, COMPONENT_SERVICE_LOCATOR);
  }

  return true;
}
 
Example #28
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 #29
Source File: JaxRSClientJacksonFeature.java    From JaxRSProviders with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #30
Source File: MCRJerseyDefaultFeature.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
protected void registerAccessFilter(FeatureContext context, Class<?> resourceClass, Method resourceMethod) {
    MCRRestrictedAccess restrictedAccessMETHOD = resourceMethod.getAnnotation(MCRRestrictedAccess.class);
    MCRRestrictedAccess restrictedAccessTYPE = resourceClass.getAnnotation(MCRRestrictedAccess.class);
    if (restrictedAccessMETHOD != null) {
        LOGGER.info("Access to {} is restricted by {}", resourceMethod,
            restrictedAccessMETHOD.value().getCanonicalName());
        addFilter(context, restrictedAccessMETHOD);
    } else if (restrictedAccessTYPE != null) {
        LOGGER.info("Access to {} is restricted by {}", resourceClass.getName(),
            restrictedAccessTYPE.value().getCanonicalName());
        addFilter(context, restrictedAccessTYPE);
    }
}