下面列出了javax.ws.rs.container.ContainerRequestContext#getProperty ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* <p>applyStreaming.</p>
*
* @param requestContext a {@link javax.ws.rs.container.ContainerRequestContext} object.
* @param context a {@link javax.ws.rs.ext.WriterInterceptorContext} object.
* @throws java.io.IOException if any.
*/
protected void applyStreaming(ContainerRequestContext requestContext, WriterInterceptorContext context)
throws IOException {
Object entity = context.getEntity();
StreamingProcess<Object> process = MessageHelper.getStreamingProcess(context.getEntity(), manager);
if (process != null) {
ContainerResponseContext responseContext =
(ContainerResponseContext) requestContext.getProperty(RESP_PROP_N);
responseContext.setStatusInfo(Response.Status.PARTIAL_CONTENT);
context.getHeaders().putSingle(ACCEPT_RANGES, BYTES_RANGE);
context.setType(StreamingOutput.class);
context.setEntity(new MediaStreaming(
entity,
requestContext.getHeaderString(MediaStreaming.RANGE),
process,
context.getMediaType(),
context.getHeaders()
)
);
}
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
String origin = requestContext.getHeaderString(ORIGIN);
if (origin == null || requestContext.getMethod().equalsIgnoreCase("OPTIONS")
|| requestContext.getProperty("cors.failure") != null) {
// don't do anything if origin is null, its an OPTIONS request, or cors.failure is set
return;
}
responseContext.getHeaders().putSingle(ACCESS_CONTROL_ALLOW_ORIGIN, origin);
if (allowCredentials)
responseContext.getHeaders().putSingle(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
if (exposedHeaders != null) {
responseContext.getHeaders().putSingle(ACCESS_CONTROL_EXPOSE_HEADERS, exposedHeaders);
}
}
@Override
public void filter(ContainerRequestContext requestContext)
throws IOException
{
// Only allow requests on the admin interfaces
Object listenAddressName = requestContext.getProperty(LISTEN_ADDRESS_NAME_ATTRIBUTE);
if (listenAddressName == null || !listenAddressName.equals(ServerConfig.ADMIN_ADDRESS)) {
throw new NotFoundException();
}
// Only allow admin users
Boolean admin = (Boolean) request.getAttribute("admin");
if (admin == null || !admin) {
throw new ForbiddenException();
}
}
@Override
public void filter(ContainerRequestContext req, ContainerResponseContext res) {
int status = res.getStatus();
// We are only interested in recording the response status if it was an error
// (either a 4xx or 5xx). No point in counting the successful responses
if (status >= 400) {
PrometheusExporter.instance().recordResponseError(status, req.getMethod());
}
// Record request duration if timestamp property is present
// and only if it is relevant (skip pictures)
if (req.getProperty(METRICS_REQUEST_TIMESTAMP) != null &&
contentTypeIsRelevant(res)) {
long time = (long) req.getProperty(METRICS_REQUEST_TIMESTAMP);
long dur = System.currentTimeMillis() - time;
LOG.trace("Duration is calculated as " + dur + " ms.");
PrometheusExporter.instance().recordRequestDuration(dur, req.getMethod());
}
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
if (BooleanUtils.isTrue((Boolean) requestContext.getProperty(LOGGING_ENABLED_PROPERTY))) {
RestResponseDetails restResponse = createResponseDetails(responseContext);
if (responseContext.hasEntity()) {
OutputStream stream = new LoggingStream(responseContext.getEntityStream());
responseContext.setEntityStream(stream);
requestContext.setProperty(LOGGINGSTREAM_PROPERTY, stream);
requestContext.setProperty(RESPONSE_DETAILS, restResponse);
} else {
Long requestTime = (Long) requestContext.getProperty(REQUEST_TIME);
RestRequestDetails restRequest = (RestRequestDetails) requestContext.getProperty(REQUEST_DETAILS);
Map<String, String> restParams = (Map<String, String>) requestContext.getProperty(REST_PARAMS);
sendStructuredEvent(restRequest, restResponse, restParams, requestTime, "");
}
}
}
@Override
public void filter(
ContainerRequestContext containerRequestContext,
ContainerResponseContext containerResponseContext) throws IOException {
Long startTime = (Long) containerRequestContext.getProperty(REQUEST_EXECUTION_START);
String took;
if (startTime == null) {
took = "-1";
} else {
took = Long.toString(System.currentTimeMillis() - startTime);
}
try (MDC.MDCCloseable mdcTook = MDC.putCloseable("request.took", took);
MDC.MDCCloseable mdcStatus = MDC
.putCloseable("response.status", Integer.toString(containerResponseContext.getStatus()));) {
logger.debug("Completed {}.", containerRequestContext.getUriInfo().getPath());
}
}
/**
* @param request
* @param create
* @return
*/
protected Session getSession(ContainerRequestContext request, boolean create) {
Session session = (Session) request.getProperty(SESSION);
if (session != null) {
return session;
}
Cookie sessionCookie = request.getCookies().get(AUTH_COOKIE);
if (sessionCookie != null) {
session = configuration.getSessionStore().getSession(sessionCookie.getValue());
}
if (session != null && session.hasExpired(configuration.getSessionExpiryTimeInSecs())) {
session = null;
}
if (session == null && create) {
String sessionId = null;
if (Strings.isNullOrEmpty(sessionId)) {
sessionId = UUID.randomUUID().toString();
}
session = configuration.getSessionStore().createSession(sessionId);
}
return session;
}
@Override
public void filter(
ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
HttpRequestContext context = (HttpRequestContext) requestContext.getProperty(CONTEXT_PROPERTY);
if (context == null) {
// JAX-RS response filters are always invoked - we only want to record something if
// request came through this filter
return;
}
Scope scope = (Scope) requestContext.getProperty(SPAN_PROPERTY);
if (scope != null) {
scope.close();
}
if (responseContext.getLength() > 0) {
handler.handleMessageSent(context, responseContext.getLength());
}
ExtendedContainerRequest extendedRequest = new ExtendedContainerRequest(requestContext, info);
handler.handleEnd(context, extendedRequest, responseContext, null);
}
@Override
public void filter(ContainerRequestContext requestContext,
ContainerResponseContext responseContext) {
Scope scope = (Scope)requestContext.getProperty(TRACING_SCOPE);
if (scope != null) {
scope.close();
}
Span span = (Span) requestContext.getProperty(TRACING_SPAN);
if (span != null) {
span.finish();
}
finishAndCloseActiveSpan();
}
@Override public void filter(ContainerRequestContext context) throws IOException {
X509Certificate[] chain =
(X509Certificate[]) context.getProperty("javax.servlet.request.X509Certificate");
if (chain != null && chain.length > 0) {
String subject = chain[0].getSubjectDN().getName();
CertificateSecurityContext securityContext = new CertificateSecurityContext(subject, chain);
context.setSecurityContext(securityContext);
}
}
@SuppressWarnings("unchecked")
@Override
public void filter(final ContainerRequestContext requestContext,
final ContainerResponseContext responseContext) throws IOException {
super.stopTraceSpan(requestContext.getHeaders(), responseContext.getHeaders(),
responseContext.getStatus(), (TraceScopeHolder<TraceScope>)requestContext.getProperty(TRACE_SPAN));
}
@Override
public void filter(final ContainerRequestContext requestContext) {
validateRequest(requestContext);
HttpServletRequest request =
(HttpServletRequest) requestContext.getProperty(HttpServletRequest.class.getName());
final Optional<P> principal;
try {
principal = authenticator.authenticate(request);
if (principal.isPresent()) {
requestContext.setSecurityContext(new SecurityContext() {
@Override
public Principal getUserPrincipal() {
return principal.get();
}
@Override
public boolean isUserInRole(String role) {
return authorizer.authorize(principal.get(), role);
}
@Override
public boolean isSecure() {
return requestContext.getSecurityContext().isSecure();
}
@Override
public String getAuthenticationScheme() {
return SecurityContext.BASIC_AUTH;
}
});
return;
}
} catch (AuthenticationException e) {
LOGGER.warn("Error authenticating credentials", e);
throw new InternalServerErrorException();
}
// TODO: re-enable / check if 302 has been returned
// throw new WebApplicationException(unauthorizedHandler.buildResponse(prefix, realm));
}
@Override
public void filter(ContainerRequestContext requestContext,
ContainerResponseContext responseContext) throws IOException {
if (responseContext.getMediaType() != null) {
String ct = responseContext.getMediaType().toString();
if (requestContext.getProperty("filterexception") != null) {
if (!"text/plain".equals(ct)) {
throw new RuntimeException();
}
responseContext.getHeaders().putSingle("FilterException",
requestContext.getProperty("filterexception"));
}
Object entity = responseContext.getEntity();
Type entityType = responseContext.getEntityType();
if (entity instanceof GenericHandler && InjectionUtils.getActualType(entityType) == Book.class) {
ct += ";charset=ISO-8859-1";
if ("getGenericBook2".equals(rInfo.getResourceMethod().getName())) {
Annotation[] anns = responseContext.getEntityAnnotations();
if (anns.length == 4 && anns[3].annotationType() == Context.class) {
responseContext.getHeaders().addFirst("Annotations", "OK");
}
} else {
responseContext.setEntity(new Book("book", 124L));
}
} else {
ct += ";charset=";
}
responseContext.getHeaders().putSingle("Content-Type", ct);
responseContext.getHeaders().add("Response", "OK");
}
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
String tokenContext = (String)requestContext.getProperty(SECURITY_CONTEXT_TOKEN);
if (tokenContext != null) {
responseContext.getHeaders().add(HttpHeaders.SET_COOKIE, tokenContext);
}
}
static MCRRequestScopeACL getInstance(ContainerRequestContext requestContext) {
Object property = requestContext.getProperty(MCRRequestScopeACLFilter.ACL_INSTANT_KEY);
Objects.requireNonNull(property, "Please register " + MCRRequestScopeACLFilter.class);
if (property instanceof Supplier) {
@SuppressWarnings("unchecked")
MCRRequestScopeACL requestScopeACL = ((Supplier<MCRRequestScopeACL>) property).get();
requestContext.setProperty(MCRRequestScopeACLFilter.ACL_INSTANT_KEY, requestScopeACL);
property = requestScopeACL;
}
return (MCRRequestScopeACL) property;
}
@Path("/authorizer-principal") @GET
@Produces(MediaType.APPLICATION_JSON)
public SingleValueModel echoAuthorizerPrincipal(@Context ContainerRequestContext context) {
SingleValueModel valueModel = new SingleValueModel();
AwsProxyRequestContext awsProxyRequestContext =
(AwsProxyRequestContext) context.getProperty(RequestReader.API_GATEWAY_CONTEXT_PROPERTY);
valueModel.setValue(awsProxyRequestContext.getAuthorizer().getPrincipalId());
return valueModel;
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
String origin = requestContext.getHeaderString(ORIGIN);
Object originFailureProperty = requestContext.getProperty(CORS_FAILURE_PROPERTY_NAME);
String accessControlRequestMethod = requestContext.getHeaderString(ACCESS_CONTROL_REQUEST_METHOD);
String requestMethod = requestContext.getMethod();
if (origin == null
|| originFailureProperty != null
|| isPreflightRequest(requestMethod, accessControlRequestMethod)
|| sameOriginPolicy.isSameOrigin(requestContext, origin)) {
return; // not CORS or a CORS failure => do not add any CORS headers
}
addCorsResponseHeaders(responseContext.getHeaders(), origin);
}
@Override
public void filter(ContainerRequestContext requestContext) {
ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) requestContext
.getProperty("org.jboss.resteasy.core.ResourceMethodInvoker");
Method method = methodInvoker.getMethod();
// Access allowed for all
if (!method.isAnnotationPresent(PermitAll.class)) {
// Access denied for all
if (method.isAnnotationPresent(DenyAll.class)) {
requestContext.abortWith(ACCESS_FORBIDDEN);
return;
}
// Get request headers
final MultivaluedMap<String, String> headersMap = requestContext.getHeaders();
// Fetch authorization header
final List<String> authorization = headersMap.get(AUTHORIZATION_PROPERTY);
// If no authorization information present; block access
if (authorization == null || authorization.isEmpty()) {
requestContext.abortWith(ACCESS_DENIED);
return;
}
// Get encoded username and password
final String encodedUserPassword = authorization.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", "");
// Decode username and password
String usernameAndPassword = new String(Base64.decodeBase64(encodedUserPassword));
// Split username and password tokens
final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
final String username = tokenizer.nextToken();
final String password = tokenizer.nextToken();
// Verify user access
if (method.isAnnotationPresent(RolesAllowed.class)) {
RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value()));
// Is user valid?
if (!isUserAllowed(username, password, rolesSet)) {
requestContext.abortWith(ACCESS_DENIED);
return;
}
}
}
}
@Override
public void filter(ContainerRequestContext requestContext) {
ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) requestContext
.getProperty(RESOURCE_METHOD_INVOKER);
Method method = methodInvoker.getMethod();
// Access allowed for all
if (!method.isAnnotationPresent(PermitAll.class)) {
// Access denied for all
if (method.isAnnotationPresent(DenyAll.class)) {
requestContext.abortWith(ACCESS_FORBIDDEN);
return;
}
// Get request headers
final MultivaluedMap<String, String> headersMap = requestContext.getHeaders();
// Fetch authorization header
final List<String> authorizationList = headersMap.get(AUTHORIZATION_PROPERTY);
// If no authorization information present; block access
if (authorizationList == null || authorizationList.isEmpty()) {
requestContext.abortWith(ACCESS_DENIED);
return;
}
// Get encoded username and password
final String encodedUserPassword = authorizationList.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", "");
// Decode username and password
String usernameAndPassword = new String(Base64.decodeBase64(encodedUserPassword));
// Split username and password tokens
final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
final String userName = tokenizer.nextToken();
final String password = tokenizer.nextToken();
// Verify user access
if (method.isAnnotationPresent(RolesAllowed.class)) {
RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value()));
// Is user valid?
if (!isUserAllowed(userName, password, rolesSet)) {
requestContext.abortWith(ACCESS_DENIED);
return;
}
}
}
}
@Override public void filter(ContainerRequestContext request) {
SpanCustomizer span = (SpanCustomizer) request.getProperty(SpanCustomizer.class.getName());
if (span != null && resourceInfo != null) {
parser.resourceInfo(resourceInfo, span);
}
}