Java Code Examples for javax.ws.rs.container.ResourceInfo

The following are top voted examples for showing how to use javax.ws.rs.container.ResourceInfo. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: wechat-mall   File: AppkeyServiceFeature.java   Source Code and License 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {

    List<Annotation> authzSpecs = new ArrayList<>();

    Annotation classAuthzSpec =
        resourceInfo.getResourceClass().getAnnotation(AppkeyAnnotation.class);
    Annotation methodAuthzSpec =
        resourceInfo.getResourceMethod().getAnnotation(AppkeyAnnotation.class);

    if (classAuthzSpec != null)
        authzSpecs.add(classAuthzSpec);
    if (methodAuthzSpec != null)
        authzSpecs.add(methodAuthzSpec);

    if (!authzSpecs.isEmpty()) {
        context.register(AppkeyFilter.class);
    }
}
 
Example 2
Project: wechat-mall   File: AuthServiceFeature.java   Source Code and License 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {

    List<Annotation> authzSpecs = new ArrayList<>();

    Annotation classAuthzSpec =
        resourceInfo.getResourceClass().getAnnotation(AuthAnnotation.class);
    Annotation methodAuthzSpec =
        resourceInfo.getResourceMethod().getAnnotation(AuthAnnotation.class);

    if (classAuthzSpec != null)
        authzSpecs.add(classAuthzSpec);
    if (methodAuthzSpec != null)
        authzSpecs.add(methodAuthzSpec);

    if (!authzSpecs.isEmpty()) {
        // 需要拦截的api
        context.register(AuthorizationFilter.class);
    }
}
 
Example 3
Project: syndesis   File: CacheForFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    CacheFor cc = resourceInfo.getResourceClass().getAnnotation(CacheFor.class);
    CacheFor mcc = resourceInfo.getResourceMethod().getAnnotation(CacheFor.class);
    if( mcc!=null ) {
        cc = mcc;
    }
    if (cc!=null) {
        if( cc.value() == 0 ) {
            context.register(NoCacheFilter.class);
        } else if( cc.value() > 0 ) {
            context.register(new CacheFilter("max-age= " + cc.unit().toSeconds(cc.value())));
        }
    } else {
        context.register(NoCacheFilter.class);
    }
}
 
Example 4
Project: oscm   File: VersionFilterTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("boxing")
private MultivaluedMap<String, String> testVersionFilter(String version) throws WebApplicationException, NoSuchMethodException {

    ResourceInfo resourceInfo = mock(ResourceInfo.class);
    ContainerRequestContext request = mock(ContainerRequestContext.class);
    UriInfo uriInfo = mock(UriInfo.class);
    when(request.getUriInfo()).thenReturn(uriInfo);

    Method method = SinceClass.class.getMethod("dummy");

    MultivaluedMap<String, String> prop = new MultivaluedHashMap<>();
    prop.putSingle(CommonParams.PARAM_VERSION, version);
    when(uriInfo.getPathParameters()).thenReturn(prop);

    VersionFilter filter = spy(new VersionFilter());
    when(filter.getResourceInfo()).thenReturn(resourceInfo);
    when(resourceInfo.getResourceMethod()).thenReturn(method);
    filter.filter(request);

    return prop;
}
 
Example 5
Project: azeroth   File: DefaultFilterDynamicFeature.java   Source Code and License 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    // 获取资源方法
    Method resourceMethod = resourceInfo.getResourceMethod();

    if (resourceMethod != null) {

        // 获取FormatJson注解
        ResponseFormat formatJson = resourceMethod.getAnnotation(ResponseFormat.class);

        if (formatJson == null || formatJson.type().equals(FormatType.JSON)) {
            context.register(DefaultWebFilter.class);
        }

    }
}
 
Example 6
Project: mycore   File: MCRJerseyDefaultFeature.java   Source Code and License 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    Class<?> resourceClass = resourceInfo.getResourceClass();
    Method resourceMethod = resourceInfo.getResourceMethod();
    if (isStaticContent(resourceClass, resourceMethod)) {
        // class or method is annotated with MCRStaticContent
        //   -> do not register any filter
        return;
    }
    String packageName = resourceClass.getPackage().getName();
    if (getPackages().contains(packageName)) {
        registerTransactionFilter(context);
        registerSessionHookFilter(context);
        registerAccessFilter(context, resourceClass, resourceMethod);
    }
}
 
Example 7
Project: awplab-core   File: BasicAuthKarafSecurityDynamicFeature.java   Source Code and License 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext featureContext) {

    AnnotatedMethod am = new AnnotatedMethod(resourceInfo.getResourceMethod());

    RequireBasicAuth requireBasicAuth = null;
    if (am.isAnnotationPresent(RequireBasicAuth.class)) {
        requireBasicAuth = am.getAnnotation(RequireBasicAuth.class);
    }
    else {
        requireBasicAuth = resourceInfo.getResourceClass().getAnnotation(RequireBasicAuth.class);
    }

    if (requireBasicAuth != null) {
        featureContext.register(new BasicAuthKarafSecurityRequestFilter(requireBasicAuth.limitToGroups(), requireBasicAuth.limitToRoles(), requireBasicAuth.karafRealm(), requireBasicAuth.requiresSecure(), requireBasicAuth.httpRealm()));
    }
}
 
Example 8
Project: ozark   File: ViewResponseFilter.java   Source Code and License 6 votes vote down vote up
private static MediaType selectVariant(Request request, ResourceInfo resourceInfo) {

        Produces produces = resourceInfo.getResourceMethod().getAnnotation(Produces.class);
        if (produces == null) {
            produces = getAnnotation(resourceInfo.getResourceClass(), Produces.class);
        }

        if (produces != null) {

            List<Variant> variants = Arrays.stream(produces.value())
                .map((String mt) -> Variant.mediaTypes(MediaType.valueOf(mt)).build().get(0))
                .collect(Collectors.toList());

            Variant variant = request.selectVariant(variants);
            if (variant != null) {
                return variant.getMediaType();
            }

        }

        return null;

    }
 
Example 9
Project: openregister-java   File: RegisterAuthDynamicFeature.java   Source Code and License 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();
    //@DenyAll shouldn't be attached to classes
    final boolean annotationOnClass = (resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class) != null) ||
            (resourceInfo.getResourceClass().getAnnotation(PermitAll.class) != null);
    final boolean annotationOnMethod = am.isAnnotationPresent(RolesAllowed.class) || am.isAnnotationPresent(DenyAll.class) ||
            am.isAnnotationPresent(PermitAll.class);

    if (annotationOnClass || annotationOnMethod) {
        context.register(filterClass);
    } else {
        for (Annotation[] annotations : parameterAnnotations) {
            for (Annotation annotation : annotations) {
                if (annotation instanceof Auth) {
                    context.register(filterClass);
                    return;
                }
            }
        }
    }
}
 
Example 10
Project: jeesuite-libs   File: ResponseWrapperHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void processResponse(ContainerRequestContext requestContext, ContainerResponseContext responseContext,
		ResourceInfo resourceInfo) {
	MediaType mediaType = responseContext.getMediaType();
	if (mediaType != null && MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) {
		Object responseData = responseContext.getEntity();
		WrapperResponseEntity jsonResponse;

		if (responseData instanceof WrapperResponseEntity) {
			jsonResponse = (WrapperResponseEntity) responseData;
		} else {
			jsonResponse = new WrapperResponseEntity(ResponseCode.OK);
			jsonResponse.setData(responseData);
		}
		responseContext.setStatus(ResponseCode.OK.getCode());

		responseContext.setEntity(jsonResponse);

	}
}
 
Example 11
Project: jeesuite-libs   File: DefaultFilterDynamicFeature.java   Source Code and License 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
	// 获取资源方法
	Method resourceMethod = resourceInfo.getResourceMethod();

	if (resourceMethod != null) {

		// 获取FormatJson注解
		ResponseFormat formatJson = resourceMethod.getAnnotation(ResponseFormat.class);

		if(formatJson == null || formatJson.type().equals(FormatType.JSON)){
			context.register(DefaultWebFilter.class);
		}

	}
}
 
Example 12
Project: java-jaxrs   File: ServerTracingDynamicFeature.java   Source Code and License 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    // TODO why it is called twice for the same endpoint
    if (!tracingDisabled(resourceInfo) && builder.allTraced) {
        log(resourceInfo);
        context.register(new ServerTracingFilter(
            builder.tracer,
            operationName(resourceInfo),
            builder.spanDecorators,
            builder.operationNameBuilder.build(resourceInfo.getResourceClass(), resourceInfo.getResourceMethod()),
            builder.skipPattern != null ? Pattern.compile(builder.skipPattern) : null),
            builder.priority);

        if (builder.traceSerialization) {
            context.register(new ServerTracingInterceptor(builder.tracer,
                builder.serializationSpanDecorators), builder.serializationPriority);
        }
    }
}
 
Example 13
Project: java-dropwizard   File: ServerTracingFeature.java   Source Code and License 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    Trace annotation = resourceInfo.getResourceMethod().getAnnotation(Trace.class);
    String operationName = this.operationName;
    if (annotation != null) {
        if (!annotation.operationName().equals("")) {
            operationName = annotation.operationName();
        }
        context.register(new ServerRequestTracingFilter(this.tracer, operationName,
            this.tracedAttributes, this.tracedProperties, this.decorator));
        context.register(new ServerResponseTracingFilter(this.tracer));  
    } else {
        if (traceAll) {
            context.register(new ServerRequestTracingFilter(this.tracer, operationName,
                this.tracedAttributes, this.tracedProperties, this.decorator));
            context.register(new ServerResponseTracingFilter(this.tracer));
        } 
    }
}
 
Example 14
Project: syndesis-rest   File: CacheForFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    CacheFor cc = resourceInfo.getResourceClass().getAnnotation(CacheFor.class);
    CacheFor mcc = resourceInfo.getResourceMethod().getAnnotation(CacheFor.class);
    if( mcc!=null ) {
        cc = mcc;
    }
    if (cc!=null) {
        if( cc.value() == 0 ) {
            context.register(NoCacheFilter.class);
        } else if( cc.value() > 0 ) {
            context.register(new CacheFilter("max-age= " + cc.unit().toSeconds(cc.value())));
        }
    } else {
        context.register(NoCacheFilter.class);
    }
}
 
Example 15
Project: drill   File: AuthDynamicFeature.java   Source Code and License 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 16
Project: sealion   File: PermissionProvider.java   Source Code and License 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {

    if (resourceInfo.getResourceClass().getName()
            .startsWith(RootResource.class.getPackage().getName() + ".") == false) {
        return;
    }

    Permissions permissions = resourceInfo.getResourceMethod().getAnnotation(Permissions.class);
    if (permissions == null) {
        permissions = resourceInfo.getResourceClass().getAnnotation(Permissions.class);
    }
    if (permissions == null) {
        //TODO
        Logger.getLogger(PermissionProvider.class.getName())
                .warning(String.format("%s not annotated @Permissions",
                        resourceInfo.getResourceMethod().toGenericString()));
        return;
    }
    context.register(new PermissionTester(permissions));
}
 
Example 17
Project: jee-user-auth   File: AuthenticationFeatureTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldRegisterFilterWhenIsPermitAllReturnsFalse() throws Exception {
    // given
    AuthenticationFeature feature = new AuthenticationFeature() {
        @Override
        boolean isPermitAll(ResourceInfo resourceInfo) {
            return false;
        }
    };

    // when
    FeatureContext context = mock(FeatureContext.class);
    feature.configure(mock(ResourceInfo.class), context);

    // then
    verify(context).register(any(AuthenticationFilter.class));
}
 
Example 18
Project: jee-user-auth   File: AuthenticationFeatureTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldNotRegisterFilterWhenIsPermitAllReturnsTrue() throws Exception {
    // given
    AuthenticationFeature feature = new AuthenticationFeature() {
        @Override
        boolean isPermitAll(ResourceInfo resourceInfo) {
            return true;
        }
    };

    // when
    FeatureContext context = mock(FeatureContext.class);
    feature.configure(mock(ResourceInfo.class), context);

    // then
    verify(context, never()).register(any(AuthenticationFilter.class));
}
 
Example 19
Project: hawkular-commons   File: TenantFeature.java   Source Code and License 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    Class<?> resourceClass = resourceInfo.getResourceClass();
    Method method = resourceInfo.getResourceMethod();

    boolean required = true;
    if (resourceClass.isAnnotationPresent(TenantRequired.class)) {
        required = resourceClass.getAnnotation(TenantRequired.class).value();
    }

    if (method.isAnnotationPresent(TenantRequired.class)) {
        required = method.getAnnotation(TenantRequired.class).value();
    }

    if (required) {
        context.register(TENANT_FILTER);
    }
}
 
Example 20
Project: respiro   File: TimerFeature.java   Source Code and License 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {

    Method resourceMethod = resourceInfo.getResourceMethod();
    Class<?> resourceClass = resourceInfo.getResourceClass();
    if(metricsDisabled(resourceClass)) {
        return;
    }
    Path methodPath = resourceMethod.getAnnotation(Path.class);
    Path classPath  = resourceClass.getAnnotation(Path.class);

    Path path = methodPath != null ? methodPath : classPath;
    if(path != null) {
        UriBuilder builder = methodPath != null
                ? UriBuilder.fromResource(resourceClass).path(resourceClass, resourceMethod.getName())
                : UriBuilder.fromResource(resourceClass);

        String template = builder.toTemplate();
        context.register(new TimerBeforeFilter(template));
        context.register(TimerAfterFilter.class);
    }
}
 
Example 21
Project: shiro-jersey   File: AuthorizationFilterFeature.java   Source Code and License 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 22
Project: module.jaxrs-filter-jsend   File: JSendFeature.java   Source Code and License 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    Jsend jsend = resourceInfo.getResourceMethod().getAnnotation(Jsend.class);
    if (jsend == null) {
        jsend = resourceInfo.getResourceClass().getAnnotation(Jsend.class);
    }
    if (jsend != null) {
        Produces produces = resourceInfo.getResourceMethod().getAnnotation(Produces.class);
        if (produces == null) {
            produces = resourceInfo.getResourceClass().getAnnotation(Produces.class);
        }
        if (produces == null || produces.value().length == 0) {
            context.register(new JsendFilter(jsend));
        } else {
            final Jsend finalJsend = jsend;
            Arrays.asList(produces.value())
                .stream()
                .filter(ct -> MediaType.APPLICATION_JSON_TYPE.isCompatible(MediaType.valueOf(ct)))
                .findFirst()
                .ifPresent(s -> context.register(new JsendFilter(finalJsend)));
        }
    }
}
 
Example 23
Project: dropwizard-guicey   File: GuiceBindingsModule.java   Source Code and License 6 votes vote down vote up
@Override
protected void configure() {
    jerseyToGuice(MultivaluedParameterExtractorProvider.class);
    jerseyToGuice(Application.class);
    jerseyToGuice(Providers.class);

    // request scoped objects, but hk will control their scope
    // must be used in guice only with Provider
    jerseyToGuice(UriInfo.class);
    jerseyToGuice(ResourceInfo.class);
    jerseyToGuice(HttpHeaders.class);
    jerseyToGuice(SecurityContext.class);
    jerseyToGuice(Request.class);
    jerseyToGuice(ContainerRequest.class);
    jerseyToGuice(AsyncContext.class);

    if (!guiceServletSupport) {
        // bind request and response objects when guice servlet module not registered
        // but this will work only for resources
        jerseyToGuice(HttpServletRequest.class);
        jerseyToGuice(HttpServletResponse.class);
    }
}
 
Example 24
Project: Shiro-Jersey2-annotations   File: ShiroDynamicFeature.java   Source Code and License 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext featureContext) {
	// No need to check non-Jax-rs classes
	if (resourceInfo.getResourceClass().getAnnotation(Path.class) != null) {
		if (filterNeeded(RequiresAuthentication.class, RequiresNoAuthentication.class, resourceInfo)) {
			featureContext.register(new RequiresAuthenticationContainerRequestFilter());
		}

		if (filterNeeded(RequiresGuest.class, RequiresNoGuest.class, resourceInfo)) {
			featureContext.register(new RequiresGuestContainerRequestFilter());
		}

		if (filterNeeded(RequiresPermissions.class, RequiresNoPermission.class, resourceInfo)) {
			featureContext.register(new RequiresPermissionContainerRequestFilter(resourceInfo));
		}

		if (filterNeeded(RequiresRoles.class, RequiresNoRoles.class, resourceInfo)) {
			featureContext.register(new RequiresRolesContainerRequestFilter(resourceInfo));
		}

		if (filterNeeded(RequiresUser.class, RequiresNoUser.class, resourceInfo)) {
			featureContext.register(new RequiresUserContainerRequestFilter());
		}
	}
}
 
Example 25
Project: Shiro-Jersey2-annotations   File: RequiresPermissionContainerRequestFilter.java   Source Code and License 6 votes vote down vote up
public RequiresPermissionContainerRequestFilter(ResourceInfo resourceInfo) {
	RequiresPermissions permissions = resourceInfo.getResourceClass().getAnnotation(
			RequiresPermissions.class);
	RequiresPermissions methodPermissions = resourceInfo.getResourceMethod().getAnnotation(
			RequiresPermissions.class);

	if (methodPermissions != null) {
		permissions = methodPermissions;
	}

	Objects.requireNonNull(permissions);
	logical = permissions.logical();
	for (String permission : permissions.value()) {
		requiredPermissions.add(new WildcardPermission(permission));
	}
}
 
Example 26
Project: dropwizard-java8   File: AuthDynamicFeature.java   Source Code and License 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 27
Project: module.jaxrs-filter-security   File: PermissionsFeature.java   Source Code and License 6 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    Method am = resourceInfo.getResourceMethod();
    if (am.isAnnotationPresent(Permissions.class)) {
        Authenticated authenticated = am.getAnnotation(Authenticated.class);
        if (authenticated == null) {
            authenticated = resourceInfo.getResourceClass().getAnnotation(Authenticated.class);
            if (authenticated == null) {
                throw new IllegalStateException("@Permissions found on " + am + " but no @Authenticated found");
            }
        }
        List<String> permissions = Arrays.asList(am.getAnnotation(Permissions.class).value());
        Collection<String> vars = new HashSet<>();
        for (String p : permissions) {
            int s = p.indexOf('{');
            while (s != -1) {
                int e = p.indexOf('}', s + 1);
                vars.add(p.substring(s + 1, e));
                s = p.indexOf('{', e + 1);
            }
        }
        context.register(new PermissionFilter(authenticated.value(), permissions, vars));
    }
}
 
Example 28
Project: baguette   File: Server.java   Source Code and License 6 votes vote down vote up
public Server() {
    register(FreemarkerMvcFeature.class);

    packages("ru.qatools.school.baguette.resources");

    register(new DynamicFeature() {
        @Override
        public void configure(ResourceInfo resourceInfo, FeatureContext context) {
            context.register(DatabaseProvider.class);

            if (resourceInfo.getResourceMethod().isAnnotationPresent(AuthenticationRequired.class)) {
                context.register(AuthenticationFilter.class);
            }
        }
    });
}
 
Example 29
Project: shiro-jersey   File: AuthorizationFilterFeature.java   Source Code and License 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 30
Project: Mastering-Java-EE-Development-with-WildFly   File: MyResourceSingleton.java   Source Code and License 5 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
	Class<?> resourceClass = resourceInfo.getResourceClass();
	Method method = resourceInfo.getResourceMethod();
	logger.info("getResourceClass: " + resourceClass);
	logger.info("getResourceMethod: " + method);
	context.property("new_dynamic_feature", resourceClass + "|" + method);
}
 
Example 31
Project: Alpine   File: AuthorizationFeature.java   Source Code and License 5 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    if (ENFORCE_AUTHENTICATION && ENFORCE_AUTHORIZATION) {
        final Method method = resourceInfo.getResourceMethod();
        if (method.isAnnotationPresent(PermissionRequired.class)) {
            context.register(AuthorizationFilter.class);
        }
    }
}
 
Example 32
Project: Alpine   File: AuthenticationFeature.java   Source Code and License 5 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    if (ENFORCE_AUTHENTICATION) {
        final Method method = resourceInfo.getResourceMethod();
        if (!method.isAnnotationPresent(AuthenticationNotRequired.class)) {
            context.register(AuthenticationFilter.class);
        }
    }
}
 
Example 33
Project: SAPNetworkMonitor   File: AuthFilterDynamicBinding.java   Source Code and License 5 votes vote down vote up
@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);
            }
        }
    }
}
 
Example 34
Project: redpipe   File: AuthorizationFilterFeature.java   Source Code and License 5 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {

    List<Annotation> authzSpecs = new ArrayList<>();
    boolean canRedirect = true;
    for (Class<? extends Annotation> annotationClass : filterAnnotations) {
        // 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(resourceInfo.getResourceClass().isAnnotationPresent(NoAuthRedirect.class)
        		|| resourceInfo.getResourceMethod().isAnnotationPresent(NoAuthRedirect.class))
        	canRedirect = false;
        if(resourceInfo.getResourceClass().isAnnotationPresent(NoAuthFilter.class)
        		|| resourceInfo.getResourceMethod().isAnnotationPresent(NoAuthFilter.class))
        	return;
    }

    if (!authzSpecs.isEmpty()) {
    	if(canRedirect)
    		context.register(new LoginRedirectFilter(), Priorities.AUTHENTICATION + 1);
        context.register(new AuthorizationFilter(authzSpecs), Priorities.AUTHORIZATION);
    }
}
 
Example 35
Project: haystack-client-java   File: ServerFilter.java   Source Code and License 5 votes vote down vote up
/**
* Helper to determine if the filter applies in the current context or not.
*
* @param context Context provided on the request
* @param resourceInfo Resource Info injected via @Context
* @return <code>true</code> if this filter should apply to the current context
*/
 protected boolean shouldFilter(ContainerRequestContext context, ResourceInfo resourceInfo) {
     if (resourceInfo.getResourceMethod().getAnnotation(DisableTracing.class) != null
         || resourceInfo.getResourceClass().getAnnotation(DisableTracing.class) != null) {
         return false;
     }
     return true;
 }
 
Example 36
Project: haystack-client-java   File: ServerFilter.java   Source Code and License 5 votes vote down vote up
/**
 * Extension point used to supply the operation name for tracing.
 *
 * @param context Context provided on the request
 * @param resourceInfo Resource Info injected via @Context
 * @return the name used for this operation
 */
protected String getOperationName(ContainerRequestContext context, ResourceInfo resourceInfo) {
    final Traced methodAnnotation = resourceInfo.getResourceMethod().getAnnotation(Traced.class);
    if (methodAnnotation != null) {
        return methodAnnotation.name();
    }

    final Traced classAnnotation = resourceInfo.getResourceClass().getAnnotation(Traced.class);
    if (classAnnotation != null) {
        return classAnnotation.name();
    }

    return String.format("%s:%s", context.getMethod(), resourceInfo.getResourceClass().getCanonicalName());
}
 
Example 37
Project: apm-client   File: TraceContainerFilterTest.java   Source Code and License 5 votes vote down vote up
public Span test(String clientTraceId, String clientSpanId, int statusCode) throws Exception {

    TracerTestImpl tracer = new TracerTestImpl();

    ResourceInfo resourceInfo  = Mockito.mock(ResourceInfo.class);
    Method method = TraceContainerFilterTest.class.getMethod("testNoClientTrace");
    Mockito.when(resourceInfo.getResourceMethod()).thenReturn(method);
    Mockito.when(resourceInfo.getResourceClass()).thenReturn((Class)method.getDeclaringClass());

    TraceContainerFilter scf = new TraceContainerFilter();
    scf.setTracer(tracer);
    scf.resourceInfo = resourceInfo;

    UriInfo uriInfo  = Mockito.mock(UriInfo.class);
    Mockito.when(uriInfo.getRequestUri()).thenReturn(new URI("https://example.com:7110/some/path"));
    Mockito.when(uriInfo.getPath()).thenReturn("/path");

    ContainerRequestContext requestContext = Mockito.mock(ContainerRequestContext.class);
    Mockito.when(requestContext.getUriInfo()).thenReturn(uriInfo);
    Mockito.when(requestContext.getMethod()).thenReturn("GET");

    Mockito.when(requestContext.getHeaderString(Mockito.eq(TracerImpl.SPAN_ID))).thenReturn(clientSpanId);
    Mockito.when(requestContext.getHeaderString(Mockito.eq(TracerImpl.TRACE_ID))).thenReturn(clientTraceId);

    scf.filter(requestContext);
    Assert.assertNotNull(tracer.getCurrentSpan());

    ContainerResponseContext responseContext = Mockito.mock(ContainerResponseContext.class);
    Mockito.when(responseContext.getEntityAnnotations()).thenReturn(new Annotation[]{});
    Mockito.when(responseContext.getStatus()).thenReturn(statusCode);

    scf.filter(requestContext, responseContext);
    Assert.assertNull(tracer.getCurrentSpan());

    Span span = tracer.getCapturedSpan();
    Assert.assertEquals("service", span.getService());
    Assert.assertEquals("TraceContainerFilterTest", span.getResource());
    Assert.assertEquals("testNoClientTrace", span.getOperation());
    return span;
  }
 
Example 38
Project: app-ms   File: InterceptorTest.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings({
    "unchecked",
    "rawtypes"
})
@Test
public void testInterceptor() throws Exception {

    jwtInterceptor.setClaimsProcessor(new ValidatingProcessor("typ", "https://example.com/register"));

    final JwtClaims jwtClaims = JwtClaims.parse("{\"typ\":\"https://example.com/register\", \"aud\":\"sample\", \"jti\": \"abc\", \"iss\":\"http://accounts.trajano.net\"}");
    final String jwt = cryptoOps.sign(jwtClaims);
    System.out.println(jwt);

    final ResourceInfo resourceInfo = Mockito.mock(ResourceInfo.class);
    Mockito.when(resourceInfo.getResourceMethod()).thenReturn(Hello.class.getMethod("hello2B"));
    Mockito.when(resourceInfo.getResourceClass()).thenReturn((Class) Hello.class);
    jwtInterceptor.setResourceInfo(resourceInfo);

    final ContainerRequestContext containerRequestContext = Mockito.mock(ContainerRequestContext.class);
    final UriInfo uriInfo = Mockito.mock(UriInfo.class);
    Mockito.when(uriInfo.getRequestUri()).thenReturn(URI.create("http://trajano.net/sample"));
    Mockito.when(containerRequestContext.getUriInfo()).thenReturn(uriInfo);
    Mockito.when(containerRequestContext.getHeaderString("X-JWT-Assertion")).thenReturn(jwt);
    Mockito.when(containerRequestContext.getHeaderString("X-JWT-Audience")).thenReturn("sample");
    mdcInterceptor.filter(containerRequestContext);
    jwtInterceptor.filter(containerRequestContext);
    //        final Request request = mock(Request.class);
    //        when(request.getHeader("X-JWT-Assertion")).thenReturn(jwt);
    //        final Response responder = mock(Response.class);
    //        final ServiceMethodInfo serviceMethodInfo = mock(ServiceMethodInfo.class);
    //        assertTrue(interceptor.preCall(request, responder, serviceMethodInfo));
}
 
Example 39
Project: holon-jaxrs   File: AuthenticationDynamicFeature.java   Source Code and License 5 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
	// check method
	if (!registerAuthenticationFilters(context, resourceInfo.getResourceMethod())) {
		// check class
		registerAuthenticationFilters(context, resourceInfo.getResourceClass());
	}
}
 
Example 40
Project: azeroth   File: ResponseWrapperHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void processResponse(ContainerRequestContext requestContext,
                            ContainerResponseContext responseContext,
                            ResourceInfo resourceInfo) {
    MediaType mediaType = responseContext.getMediaType();
    if (mediaType != null && MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) {
        Object responseData = responseContext.getEntity();
        WrapperResponseEntity jsonResponse;

        if (responseData instanceof WrapperResponseEntity) {
            jsonResponse = (WrapperResponseEntity) responseData;
        } else {
            jsonResponse = new WrapperResponseEntity(ResponseCode.OK);
            jsonResponse.setData(responseData);
        }
        responseContext.setStatus(ResponseCode.OK.getCode());

        responseContext.setEntity(jsonResponse);

    }
}
 
Example 41
Project: azeroth   File: CorsHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void processResponse(ContainerRequestContext requestContext,
                            ContainerResponseContext responseContext,
                            ResourceInfo resourceInfo) {
    responseContext.getHeaders().add(RestConst.ACCESS_CONTROL_ALLOW_ORIGIN,
        FilterConfig.getCorsAllowOrgin());
    responseContext.getHeaders().add(RestConst.ACCESS_CONTROL_ALLOW_METHODS_TITLE,
        RestConst.ACCESS_CONTROL_ALLOW_METHODS);
    responseContext.getHeaders().add(RestConst.ACCESS_CONTROL_ALLOW_HEADERS,
        RestConst.ALLOW_HEADERS);
    responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
}
 
Example 42
Project: ratelimitj   File: RateLimited429EnforcerFeature.java   Source Code and License 5 votes vote down vote up
@Override
public void configure(final ResourceInfo resourceInfo,
                      final FeatureContext context) {

    final AnnotatedMethod method = new AnnotatedMethod(resourceInfo.getResourceMethod());
    final RateLimited rateLimited = method.getAnnotation(RateLimited.class);

    if (null != rateLimited) {
        context.register(RateLimit429EnforcerFilter.class);
    }
}
 
Example 43
Project: elo-api   File: AuthFeature.java   Source Code and License 5 votes vote down vote up
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
    Method method = resourceInfo.getResourceMethod();
    if (!method.isAnnotationPresent(PermitAll.class)
            && !resourceInfo.getResourceClass().equals(io.swagger.jaxrs.listing.ApiListingResource.class)) {
        AuthenticationFilter authenticationFilter = new AuthenticationFilter(authorizationService);
        context.register(authenticationFilter);
    }
}
 
Example 44
Project: ozark   File: ViewEngineContextImplTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test getResourceInfo method.
 */
@Test
public void testGetResourceInfo() {
    ViewEngineContextImpl context = new ViewEngineContextImpl(null, null, null, null, null, null, null);
    assertNull(context.getResourceInfo());
    ResourceInfo resourceInfo = EasyMock.createMock(ResourceInfo.class);
    replay(resourceInfo);
    context = new ViewEngineContextImpl(null, null, null, null, null, resourceInfo, null);
    assertNotNull(context.getResourceInfo());
    verify(resourceInfo);
}
 
Example 45
Project: orientdb-microservices   File: MetricsFeature.java   Source Code and License 5 votes vote down vote up
private String chooseName(String explicitName, boolean absolute, ResourceInfo resourceInfo) {
    if (explicitName != null && !explicitName.isEmpty()) {
        if (absolute) {
            return explicitName;
        }
        return name(getName(resourceInfo), explicitName);
    }

    return getName(resourceInfo);
}
 
Example 46
Project: orientdb-microservices   File: MetricsFeature.java   Source Code and License 5 votes vote down vote up
private String getPath(ResourceInfo resourceInfo) {
    String rootPath = null;
    String methodPath = null;

    if (resourceInfo.getResourceClass().isAnnotationPresent(Path.class)) {
        rootPath = resourceInfo.getResourceClass().getAnnotation(Path.class).value();
    }

    if (resourceInfo.getResourceMethod().isAnnotationPresent(Path.class)) {
        methodPath = resourceInfo.getResourceMethod().getAnnotation(Path.class).value();
    }

    return new StringJoiner("/").add(rootPath).add(methodPath).toString();
}
 
Example 47
Project: dropwizard-hk2   File: ResourceMethodMetricNameFilter.java   Source Code and License 5 votes vote down vote up
@Override
public MetricName buildRequestScopedName(MetricName metricName, AnnotatedElement injectionSite, Type metricType) {
    checkState(resourceInfoProvider != null, "resourceInfo must be set");
    ResourceInfo resourceInfo = resourceInfoProvider.get();
    if (resourceInfo == null || resourceInfo.getResourceMethod() == null) {
        return metricName;
    }
    return metricName.addTag(tagName, resourceInfo.getResourceMethod().getName());
}
 
Example 48
Project: dropwizard-hk2   File: ResourceClassMetricNameFilter.java   Source Code and License 5 votes vote down vote up
@Override
public MetricName buildRequestScopedName(MetricName metricName, AnnotatedElement injectionSite, Type metricType) {
    checkState(resourceInfoProvider != null, "resourceInfo must be set");
    ResourceInfo resourceInfo = resourceInfoProvider.get();
    if (resourceInfo == null || resourceInfo.getResourceClass() == null) {
        return metricName;
    }
    return metricName.addTag(tagName, resourceInfo.getResourceClass().getSimpleName());
}
 
Example 49
Project: jeesuite-libs   File: CorsHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void processResponse(ContainerRequestContext requestContext, ContainerResponseContext responseContext,
		ResourceInfo resourceInfo) {
	responseContext.getHeaders().add(RestConst.ACCESS_CONTROL_ALLOW_ORIGIN, FilterConfig.getCorsAllowOrgin());
	responseContext.getHeaders().add(RestConst.ACCESS_CONTROL_ALLOW_METHODS_TITLE, RestConst.ACCESS_CONTROL_ALLOW_METHODS);
	responseContext.getHeaders().add(RestConst.ACCESS_CONTROL_ALLOW_HEADERS, RestConst.ALLOW_HEADERS);
	responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");	
}
 
Example 50
Project: hawkcd   File: HttpSecurityContext.java   Source Code and License 5 votes vote down vote up
public HttpSecurityContext(User user, ResourceInfo resourceInfo) throws NoSuchFieldException {
    this.principalUser = new PrincipalUser(user);
    this.resourceInfo = resourceInfo;
    this.methodName = resourceInfo.getResourceMethod().getName();
    servicePackageNameField = resourceInfo.getResourceClass().getDeclaredField("SERVICE_PACKAGE_NAME");
    serviceClassNameField = resourceInfo.getResourceClass().getDeclaredField("SERVICE_CLASS_NAME");
}
 
Example 51
Project: java-jaxrs   File: InstrumentedRestApplication.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 52
Project: java-jaxrs   File: ServerTracingDynamicFeature.java   Source Code and License 5 votes vote down vote up
private void log(ResourceInfo resourceInfo) {
    if (log.isLoggable(Level.FINE)) {
        log.fine(String.format("Registering tracing on %s#%s...",
                resourceInfo.getResourceClass().getCanonicalName(),
                resourceInfo.getResourceMethod().getName()));
    } else if (!logged) {
        log.info("Registering tracing on deployed resources...");
    }

    logged = true;
}
 
Example 53
Project: java-jaxrs   File: ServerTracingDynamicFeature.java   Source Code and License 5 votes vote down vote up
protected Traced closestTracedAnnotation(ResourceInfo resourceInfo) {
    Traced tracedAnnotation = resourceInfo.getResourceMethod().getAnnotation(Traced.class);
    if (tracedAnnotation == null) {
        tracedAnnotation = resourceInfo.getResourceClass().getAnnotation(Traced.class);
    }

    return tracedAnnotation;
}
 
Example 54
Project: microbule   File: MetricsFeature.java   Source Code and License 5 votes vote down vote up
@Override
protected void configure(Timed annotation, ResourceInfo resourceInfo, FeatureContext featureContext) {
    final Method method = resourceInfo.getResourceMethod();
    final String name = MetricRegistry.name(descriptor.serviceInterface().getSimpleName(), StringUtils.defaultIfBlank(annotation.name(), method.getName()));
    final Timer timer = metricsService.createTimer(name, annotation.strategy(), config);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Adding \"{}\" timer using strategy \"{}\" filter to method {}.{}({})...", name, annotation.strategy(), descriptor.serviceInterface().getSimpleName(), method.getName(), Arrays.stream(method.getParameterTypes()).map(Class::getSimpleName).collect(Collectors.joining(", ")));
    }
    featureContext.register(new MetricsFilter(timer));
}
 
Example 55
Project: microbule   File: CacheDynamicFeature.java   Source Code and License 5 votes vote down vote up
@Override
protected void configure(Cacheable annotation, ResourceInfo resourceInfo, FeatureContext featureContext) {
    final Method method = resourceInfo.getResourceMethod();
    getAnnotation(method, GET.class).ifPresent(get -> {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Adding cache filter to method {}({})...", resourceInfo.getResourceMethod().getName(), Arrays.stream(method.getParameterTypes()).map(Class::getSimpleName).collect(Collectors.joining(", ")));
        }
        featureContext.register(new ContainerCacheFilter(annotation));
    });
}
 
Example 56
Project: jaxrs-versioning   File: VersionMediaTypeParameterFeature.java   Source Code and License 5 votes vote down vote up
@Override
public void configure(ResourceInfo resource, FeatureContext context) {
  VersionMediaTypeParameter versionParameter = resource.getResourceMethod().getAnnotation(VersionMediaTypeParameter.class);
  if (versionParameter == null) {
    versionParameter = resource.getResourceClass().getAnnotation(VersionMediaTypeParameter.class);
  }
  
  if (versionParameter != null) {
    context.register(new VersionMediaTypeParameterFilter(versionParameter.value()));
  }
}
 
Example 57
Project: jaxrs-versioning   File: VersionHeaderFeature.java   Source Code and License 5 votes vote down vote up
@Override
public void configure(ResourceInfo resource, FeatureContext context) {
  VersionHeader versionHeader = resource.getResourceMethod().getAnnotation(VersionHeader.class);
  if (versionHeader == null) {
    versionHeader = resource.getResourceClass().getAnnotation(VersionHeader.class);
  }
  
  if (versionHeader != null) {
    context.register(new VersionHeaderFilter(versionHeader.value()));
  }
}
 
Example 58
Project: jaxrs-versioning   File: VersionedMediaTypeFeature.java   Source Code and License 5 votes vote down vote up
@Override
public void configure(ResourceInfo resource, FeatureContext context) {
  VersionedMediaType versionedContentType = resource.getResourceMethod().getAnnotation(VersionedMediaType.class);
  if (versionedContentType == null) {
    versionedContentType = resource.getResourceClass().getAnnotation(VersionedMediaType.class);
  }
  
  if (versionedContentType != null) {
    VersionedMediaTypeFilter.register(versionedContentType.value(), MediaType.valueOf(versionedContentType.mapsTo()));
  }
}
 
Example 59
Project: jaxrs-versioning   File: VersionQueryParameterFeature.java   Source Code and License 5 votes vote down vote up
@Override
public void configure(ResourceInfo resource, FeatureContext context) {
  VersionQueryParameter versionParameter = resource.getResourceMethod().getAnnotation(VersionQueryParameter.class);
  if (versionParameter == null) {
    versionParameter = resource.getResourceClass().getAnnotation(VersionQueryParameter.class);
  }
  
  if (versionParameter != null) {
    context.register(new VersionQueryParameterFilter(versionParameter.value()));
  }
}
 
Example 60
Project: sealion   File: UIResponseProvider.java   Source Code and License 5 votes vote down vote up
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {

    Method resourceMethod = resourceInfo.getResourceMethod();
    if (resourceMethod.getReturnType() != Optional.class) {
        return;
    }

    Type returnType = resourceMethod.getGenericReturnType();
    if ((returnType instanceof ParameterizedType) == false) {
        return;
    }

    ParameterizedType pt = (ParameterizedType) returnType;
    if (pt.getActualTypeArguments()[0] != UIResponse.class) {
        return;
    }

    context.register(new ContainerResponseFilter() {

        @Override
        public void filter(ContainerRequestContext requestContext,
                ContainerResponseContext responseContext) throws IOException {
            if (responseContext.hasEntity() == false) {
                return;
            }
            Optional<?> opt = (Optional<?>) responseContext.getEntity();
            responseContext.setEntity(opt.orElse(null));
            responseContext.setStatusInfo(
                    opt.map(a -> responseContext.getStatusInfo()).orElse(Status.NOT_FOUND));
        }
    });
}