下面列出了怎么用javax.ws.rs.container.ResourceInfo的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 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));
}
}
}
}
}
/**
* Constructor for view engine contexts.
*
* @param view Name of view.
* @param models Instance of models.
* @param request HTTP servlet request.
* @param response HTTP servlet response.
* @param responseHeaders The response responseHeaders
* @param outputStream The response stream
* @param mediaType The media type
* @param uriInfo URI info about the request.
* @param resourceInfo Resource matched info.
* @param configuration the configuration.
* @param locale the request locale
*/
public ViewEngineContextImpl(String view, Models models, Object request, Object response,
MultivaluedMap<String, Object> responseHeaders, OutputStream outputStream,
MediaType mediaType, UriInfo uriInfo, ResourceInfo resourceInfo,
Configuration configuration, Locale locale) {
this.view = view;
this.models = models;
this.request = request;
this.response = response;
this.responseHeaders = responseHeaders;
this.outputStream = outputStream;
this.mediaType = mediaType;
this.uriInfo = uriInfo;
this.resourceInfo = resourceInfo;
this.configuration = configuration;
this.locale = locale;
}
public Response processAuthorization(HttpHeaders headers, ResourceInfo resourceInfo){
if (isEnabled()) {
try {
return processUmaAuthorization(headers.getHeaderString("Authorization"), resourceInfo);
}
catch (Exception e){
log.error(e.getMessage(), e);
return getErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage());
}
}
else{
log.info("UMA passport authentication is disabled");
return getErrorResponse(Response.Status.SERVICE_UNAVAILABLE, "Passport configuration was disabled");
}
}
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;
}
@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);
}
}
@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);
}
}
@Override
public Response processAuthorization(HttpHeaders headers, ResourceInfo resourceInfo) {
Response authorizationResponse = null;
String authorization = headers.getHeaderString("Authorization");
log.info("==== API Service call intercepted ====");
log.info("Authorization header {} found", StringUtils.isEmpty(authorization) ? "not" : "");
try {
if (appConfiguration.isOxTrustApiTestMode()) {
log.info("API Test Mode is ACTIVE");
authorizationResponse = processTestModeAuthorization(authorization);
} else if (isEnabled()) {
log.info("API is protected by UMA");
authorizationResponse = processUmaAuthorization(authorization, resourceInfo);
} else {
log.info(
"Please activate UMA or test mode to protect your API endpoints. Read the Gluu API docs to learn more");
authorizationResponse = getErrorResponse(Response.Status.UNAUTHORIZED, "API not protected");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
authorizationResponse = getErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage());
}
return authorizationResponse;
}
@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 void configure(ResourceInfo resourceInfo, FeatureContext context) {
Class<?> resourceClass = resourceInfo.getResourceClass();
Method resourceMethod = resourceInfo.getResourceMethod();
context.register(MCRCacheFilter.class);
if (isStaticContent(resourceClass, resourceMethod)) {
// class or method is annotated with MCRStaticContent
// -> do only register session lock filter
context.register(MCRSessionLockFilter.class);
return;
}
String packageName = resourceClass.getPackage().getName();
if (getPackages().contains(packageName)) {
registerTransactionFilter(context);
registerSessionHookFilter(context);
registerAccessFilter(context, resourceClass, resourceMethod);
}
}
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;
}
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext featureContext) {
CacheControl cacheControl = null;
Method resourceMethod = resourceInfo.getResourceMethod();
if (resourceMethod != null) {
cacheControl = resourceMethod.getAnnotation(CacheControl.class);
} else {
Class<?> resourceClass = resourceInfo.getResourceClass();
if (resourceClass != null) {
cacheControl = resourceClass.getAnnotation(CacheControl.class);
}
}
if (cacheControl == null) {
featureContext.register(NO_CACHE_FILTER);
} else {
featureContext.register(new CacheResponseFilter(cacheControl.value()));
}
}
@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);
}
}
@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
protected void configure() {
jerseyToGuiceGlobal(MultivaluedParameterExtractorProvider.class);
jerseyToGuiceGlobal(Application.class);
jerseyToGuiceGlobal(Providers.class);
// request scoped objects
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);
}
}
public AccessType getAccessType(ResourceInfo resourceInfo)
{
for (ResourceAccessTypeLoader resourceAccessTypeLoader : resourceAccessTypeLoaders) {
// check if the method has an access type declared
Optional<AccessType> accessType = resourceAccessTypeLoader.getAccessType(resourceInfo.getResourceMethod());
if (accessType.isPresent()) {
return accessType.get();
}
// check if the resource class has an access type declared for all methods
accessType = resourceAccessTypeLoader.getAccessType(resourceInfo.getResourceClass());
if (accessType.isPresent()) {
verifyNotPrestoResource(resourceInfo);
return accessType.get();
}
// in some cases there the resource is a nested class, so check the parent class
// we currently only check one level, but we could handle multiple nesting levels if necessary
if (resourceInfo.getResourceClass().getDeclaringClass() != null) {
accessType = resourceAccessTypeLoader.getAccessType(resourceInfo.getResourceClass().getDeclaringClass());
if (accessType.isPresent()) {
verifyNotPrestoResource(resourceInfo);
return accessType.get();
}
}
}
// Presto resources are required to have a declared access control
verifyNotPrestoResource(resourceInfo);
return MANAGEMENT_READ;
}
private static void verifyNotPrestoResource(ResourceInfo resourceInfo)
{
Method resourceMethod = resourceInfo.getResourceMethod();
if (resourceMethod != null && resourceMethod.getDeclaringClass().getPackageName().startsWith("io.prestosql.")) {
throw new IllegalArgumentException("Presto resource is not annotated with @" + ResourceSecurity.class.getSimpleName() + ": " + resourceInfo.getResourceMethod());
}
}
private boolean hasSecurityAnnotations(ResourceInfo resource) {
// resource methods are inherited (see JAX-RS spec, chapter 3.6)
// resource methods must be `public` (see JAX-RS spec, chapter 3.3.1)
// hence `resourceClass.getMethods` -- returns public methods, including inherited ones
return Stream.of(resource.getResourceClass().getMethods())
.filter(this::isResourceMethod)
.anyMatch(this::hasSecurityAnnotations);
}
/**
* Test getResourceInfo method.
*/
@Test
public void testGetResourceInfo() {
ViewEngineContextImpl context = new ViewEngineContextImpl(null, null, null, null, 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, null, null, null, resourceInfo, null, null);
assertNotNull(context.getResourceInfo());
verify(resourceInfo);
}
@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);
}
}
@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 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);
}
}
@Override
public void configure(final ResourceInfo resourceInfo, final FeatureContext context) {
if (resourceInfo.getResourceMethod().isAnnotationPresent(Deprecated.class)
|| resourceInfo.getResourceClass().isAnnotationPresent(Deprecated.class)) {
context
.register((ContainerResponseFilter) (requestContext, responseContext) -> responseContext
.getHeaders()
.putSingle("X-Talend-Warning",
"This endpoint is deprecated and will be removed without notice soon."));
}
}
private void addMethodScopes(ResourceInfo resourceInfo, List<String> scopes) {
Method resourceMethod = resourceInfo.getResourceMethod();
ProtectedApi methodAnnotation = resourceMethod.getAnnotation(ProtectedApi.class);
if (methodAnnotation != null) {
scopes.addAll(Stream.of(methodAnnotation.scopes()).collect(Collectors.toList()));
}
}
/**
* This method checks whether the authorization header is present and valid before scim service methods can be actually
* called.
* @param headers An object holding HTTP headers
* @param uriInfo An object that allows access to request URI information
* @return A null value if the authorization was successful, otherwise a Response object is returned signaling an
* authorization error
*/
public Response processAuthorization(HttpHeaders headers, ResourceInfo resourceInfo){
//Comment this method body if you want to skip the authorization check and proceed straight to use your SCIM service.
//This is useful under certain circumstances while doing development
//log.warn("Bypassing protection TEMPORARILY");
Response authorizationResponse = null;
String authorization = headers.getHeaderString("Authorization");
log.info("==== SCIM Service call intercepted ====");
log.info("Authorization header {} found", StringUtils.isEmpty(authorization) ? "not" : "");
try {
//Test mode may be removed in upcoming versions of Gluu Server...
if (jsonConfigurationService.getOxTrustappConfiguration().isScimTestMode()) {
log.info("SCIM Test Mode is ACTIVE");
authorizationResponse = processTestModeAuthorization(authorization);
}
else
if (isEnabled()){
log.info("SCIM is protected by UMA");
authorizationResponse = processUmaAuthorization(authorization, resourceInfo);
}
else{
log.info("Please activate UMA or test mode to protect your SCIM endpoints. Read the Gluu SCIM docs to learn more");
authorizationResponse= getErrorResponse(Response.Status.UNAUTHORIZED, "SCIM API not protected");
}
}
catch (Exception e){
log.error(e.getMessage(), e);
authorizationResponse=getErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage());
}
return authorizationResponse;
}
@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");
}
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()));
}
}
/**
* <p>checkQuery.</p>
*
* @param query a {@link io.ebean.Query} object.
* @param whitelist a {@link java.util.Set} object.
* @param blacklist a {@link java.util.Set} object.
* @param manager a {@link InjectionManager} object.
*/
public static void checkQuery(Query<?> query, Set<String> whitelist,
Set<String> blacklist, InjectionManager manager) {
ResourceInfo resource = manager.getInstance(ResourceInfo.class);
Class<?> rc = resource.getResourceClass();
Set<String> wl = null, bl = null;
if (rc != null) {
Filter filter = rc.getAnnotation(Filter.class);
if (filter != null) {
if (filter.whitelist().length > 0) {
wl = Sets.newLinkedHashSet();
Collections.addAll(wl, filter.whitelist());
}
if (filter.blacklist().length > 0) {
bl = Sets.newLinkedHashSet();
Collections.addAll(bl, filter.blacklist());
}
}
}
if (whitelist != null) {
if (wl == null) {
wl = Sets.newLinkedHashSet();
}
wl.addAll(whitelist);
}
if (blacklist != null) {
if (bl == null) {
bl = Sets.newLinkedHashSet();
}
bl.addAll(blacklist);
}
checkQuery((SpiQuery) query, wl, bl, manager.getInstance(Application.Mode.class).isProd());
}
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
boolean classAnnotation = resourceInfo.getResourceClass().isAnnotationPresent(OAuth20.class);
boolean methodAnnotation = resourceInfo.getResourceMethod().isAnnotationPresent(OAuth20.class);
if (classAnnotation || methodAnnotation)
{
AllowedScopes scopes = methodAnnotation?resourceInfo.getResourceMethod().getAnnotation(AllowedScopes.class):
resourceInfo.getResourceClass().getAnnotation(AllowedScopes.class);
OAuth2RequestFilter filter = new OAuth2RequestFilter(scopes.scopes(), config, tokenVerifier, requestFactory);
context.register(filter);
}
}
@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");
}