本文整理匯總了Java中javax.ws.rs.container.ContainerRequestContext類的典型用法代碼示例。如果您正苦於以下問題:Java ContainerRequestContext類的具體用法?Java ContainerRequestContext怎麽用?Java ContainerRequestContext使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
ContainerRequestContext類屬於javax.ws.rs.container包,在下文中一共展示了ContainerRequestContext類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: extractRequestEntity
import javax.ws.rs.container.ContainerRequestContext; //導入依賴的package包/類
static String extractRequestEntity(ContainerRequestContext request) {
if (request.hasEntity()) {
InputStream inputStreamOriginal = request.getEntityStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamOriginal, MAX_ENTITY_READ);
bufferedInputStream.mark(MAX_ENTITY_READ);
byte[] bytes = new byte[MAX_ENTITY_READ];
int read;
try {
read = bufferedInputStream.read(bytes, 0, MAX_ENTITY_READ);
bufferedInputStream.reset();
} catch (IOException e) {
throw new RuntimeException(e);
}
request.setEntityStream(bufferedInputStream);
return new String(bytes, Charsets.UTF_8);
}
return null;
}
示例2: filter
import javax.ws.rs.container.ContainerRequestContext; //導入依賴的package包/類
@Override
public void filter(
ContainerRequestContext containerRequestContext,
ContainerResponseContext containerResponseContext) throws IOException {
MultivaluedMap<String, Object> headers = containerResponseContext.getHeaders();
headers.add(
"Access-Control-Allow-Origin",
"*");
headers.add(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS");
headers.add(
"Access-Control-Allow-Headers",
"Cache-Control, X-Requested-With, Origin, Content-Type, Accept, Authorization");
}
示例3: extractBodyParameter
import javax.ws.rs.container.ContainerRequestContext; //導入依賴的package包/類
/**
* Extracts the body from the supplied request.
*/
private static void extractBodyParameter(final RequestParameters requestParameters,
final ContainerRequestContext ctx, final Optional<Parameter> parameter) throws IOException {
String body = extractBody(ctx);
if (body == null) {
return;
}
requestParameters.setRawBody(body);
if (!parameter.isPresent()) {
return;
}
if (ctx.getHeaders().get(HttpHeaders.CONTENT_TYPE).stream().filter(
header -> ContentType.APPLICATION_JSON.toString().startsWith(header)).findAny().orElse(
null) == null) {
return;
}
ObjectMapper objectMapper = new ObjectMapper();
Map json = objectMapper.readValue(body, Map.class);
if (json.keySet().size() == 1) {
requestParameters.putAll(json);
}
}
示例4: filter
import javax.ws.rs.container.ContainerRequestContext; //導入依賴的package包/類
@Override
public void filter(final ContainerRequestContext ctx) throws IOException {
final List<String> exts = ctx.getUriInfo().getQueryParameters().getOrDefault("ext", emptyList());
if (exts.contains(UPLOADS)) {
if (INVALID_EXT_METHODS.contains(ctx.getMethod())) {
ctx.abortWith(status(METHOD_NOT_ALLOWED).build());
}
if (ctx.getMethod().equals("POST")) {
final String path = ctx.getUriInfo().getPath();
final String urlBase = nonNull(baseUrl) ? baseUrl : ctx.getUriInfo().getBaseUri().toString();
final String contentType = ofNullable(ctx.getMediaType()).map(MediaType::toString)
.orElse(APPLICATION_OCTET_STREAM);
final String identifier = ofNullable(ctx.getHeaderString("Slug"))
.orElseGet(resourceService.getIdentifierSupplier());
final String uploadId = binaryService.initiateUpload(rdf.createIRI(TRELLIS_PREFIX + path + identifier),
contentType);
if (isNull(uploadId)) {
throw new WebApplicationException("Cannot initiate multipart upload", BAD_REQUEST);
}
ctx.abortWith(status(CREATED).location(create(urlBase + UPLOAD_PREFIX + uploadId)).build());
}
}
}
示例5: filter
import javax.ws.rs.container.ContainerRequestContext; //導入依賴的package包/類
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Get the Authorization header from the request
String authorizationHeader
= requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
// Validate the Authorization header
if (!isTokenBasedAuthentication(authorizationHeader)) {
abortWithUnauthorized(requestContext);
}
// Extract the token from the Authorization header
String token = authorizationHeader
.substring(AUTHENTICATION_SCHEME.length()).trim();
try {
// Validate the token
verifyToken(token);
} catch (Exception e) {
abortWithUnauthorized(requestContext);
}
}
示例6: setHeader
import javax.ws.rs.container.ContainerRequestContext; //導入依賴的package包/類
private void setHeader(String format, ContainerRequestContext containerRequestContext) {
ArrayList<String> mediaTypes = new ArrayList<>();
switch (format) {
case ("json"):
mediaTypes.add(MediaType.APPLICATION_JSON);
mediaTypes.add(MediaTypes.LDJSON);
break;
case ("xml"):
mediaTypes.add(MediaType.APPLICATION_XML);
mediaTypes.add(MediaTypes.RDFXML);
break;
case ("ttl"):
mediaTypes.add(MediaTypes.TURTLE);
break;
default:
LOG.error("Format parameter {} not supported -> ignored", format);
break;
}
if (!mediaTypes.isEmpty()) {
LOG.debug("Format parameter {} set, expand Accept header with {}", format, mediaTypes);
containerRequestContext.getHeaders().put(HttpHeaders.ACCEPT, mediaTypes);
}
}
示例7: filter
import javax.ws.rs.container.ContainerRequestContext; //導入依賴的package包/類
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) {
String path = request.getUriInfo().getRequestUri().getPath();
LOG.fine(String.format("Received request : crossdomain for %s", path));
// TODO : disable for production
// *** ONLY FOR DEMO ***
// response.getHeaders().add("Access-Control-Allow-Origin", "http://localhost:3002");
response.getHeaders().add("Access-Control-Allow-Origin", "*");
response.getHeaders().add("Access-Control-Allow-Headers", "Content-Range, Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
response.getHeaders().add("Access-Control-Expose-Headers", "Content-Range, Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// response.getHeaders().add("Access-Control-Allow-Credentials", "http://localhost:3002");
response.getHeaders().add("Access-Control-Allow-Credentials", "*");
response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH");
response.getHeaders().add("Access-Control-Max-Age", "*");
}
示例8: filter
import javax.ws.rs.container.ContainerRequestContext; //導入依賴的package包/類
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
if (alwaysAccept(requestContext)) {
return;
}
String apptokenid = requestContext.getHeaderString(APPTOKENID_HEADER);
if (apptokenid == null || apptokenid.trim().isEmpty()) {
handleErrorNoAppToken(requestContext);
} else {
ApplicationToken token = tokenServiceClient.getApptokenById(apptokenid);
TokenCheckResult result = applicationTokenAccessValidator.checkApplicationToken(token);
if (result != TokenCheckResult.AUTHORIZED) {
handleErrorUnauthorized(requestContext, apptokenid, result);
} else if (! isAllowedToCallEndpoint(token)) {
handleErrorUnauthorizedForEndpoint(requestContext, apptokenid, result);
}
}
}
示例9: filter404NoParameter
import javax.ws.rs.container.ContainerRequestContext; //導入依賴的package包/類
@SuppressWarnings("rawtypes")
@Test
public void filter404NoParameter() {
final ContainerRequestContext requestContext = Mockito.mock(ContainerRequestContext.class);
final ContainerResponseContext responseContext = Mockito.mock(ContainerResponseContext.class);
Mockito.when(responseContext.getStatus()).thenReturn(204);
final Annotation anno1 = Mockito.mock(Annotation.class);
final Annotation anno2 = Mockito.mock(Annotation.class);
final Annotation[] annotations = new Annotation[] { anno1, anno2 };
Mockito.when((Class) anno2.annotationType()).thenReturn(OnNullReturn404.class);
Mockito.when(responseContext.getEntityAnnotations()).thenReturn(annotations);
final UriInfo uriInfo = Mockito.mock(UriInfo.class);
final MultivaluedMap<String, String> parameters = new MultivaluedHashMap<>();
Mockito.when(uriInfo.getPathParameters()).thenReturn(parameters);
Mockito.when(requestContext.getUriInfo()).thenReturn(uriInfo);
filter.filter(requestContext, responseContext);
Mockito.verify(responseContext, VerificationModeFactory.atLeastOnce()).setStatus(404);
Mockito.verify(responseContext, VerificationModeFactory.atLeastOnce())
.setEntity("{\"code\":\"data\",\"message\":null,\"parameters\":null,\"cause\":null}", annotations, MediaType.APPLICATION_JSON_TYPE);
}
示例10: filter
import javax.ws.rs.container.ContainerRequestContext; //導入依賴的package包/類
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
String usertokenId = requestContext.getHeaderString(Constants.USERTOKENID_HEADER);
if (Strings.isNullOrEmpty(usertokenId)) {
return;
}
UserToken userToken;
try {
userToken = tokenServiceClient.getUserTokenById(usertokenId);
} catch (TokenServiceClientException e) {
throw new NotAuthorizedException("UsertokenId: '" + usertokenId + "' not valid", e);
}
UibBrukerPrincipal brukerPrincipal = UibBrukerPrincipal.ofUserToken(userToken);
ImmutableSet<String> tilganger = extractRolesAllowed(userToken, brukerPrincipal.uibBruker);
requestContext.setSecurityContext(new AutentiseringsContext(brukerPrincipal, tilganger));
if (authenticatedHandler != null) {
authenticatedHandler.handle(requestContext);
}
}
示例11: filter
import javax.ws.rs.container.ContainerRequestContext; //導入依賴的package包/類
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
Single<Boolean> ret = null;
for (Map.Entry<AuthorizingAnnotationHandler, Annotation> authzCheck : authzChecks.entrySet()) {
AuthorizingAnnotationHandler handler = authzCheck.getKey();
Annotation authzSpec = authzCheck.getValue();
Single<Boolean> check = handler.assertAuthorized(authzSpec);
if(ret == null)
ret = check;
else
ret = ret.zipWith(check, (a, b) -> a && b);
}
if(ret != null) {
PreMatchContainerRequestContext context = (PreMatchContainerRequestContext)requestContext;
context.suspend();
ret.subscribe(result -> {
if (result)
context.resume();
else
context.resume(new AuthorizationException("Authorization failed"));
}, error -> {
context.resume(error);
});
}
}
示例12: filter
import javax.ws.rs.container.ContainerRequestContext; //導入依賴的package包/類
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
System.out.println("Response = " + requestContext + " " + responseContext);
Long start = concurrentRequests.get(requestContext);
concurrentRequests.remove(requestContext);
long duration = (System.nanoTime() - start);
System.out.println("Duration: " + duration);
UriInfo uriInfo = requestContext.getUriInfo();
String ipv4 = extractIpAddress(uriInfo);
System.out.println("ipv4 = " + ipv4);
String serviceName = extractServiceName(uriInfo);
System.out.println("serviceName = " + serviceName);
String spanName = extractSpanName(uriInfo);
System.out.println("spanName = " + spanName);
Optional<String> traceId = extractTraceId(requestContext);
String spanId = traceId.map(id -> this.tracee.saveChildSpan(id, spanName, serviceName, ipv4, 0)).
orElseGet(() -> this.tracee.saveParentSpan(spanName, serviceName, ipv4, duration));
System.out.println("Storing span id: " + spanId);
storeSpandId(responseContext, spanId);
}
示例13: filter
import javax.ws.rs.container.ContainerRequestContext; //導入依賴的package包/類
@Override
public void filter(ContainerRequestContext containerRequestContext,
ContainerResponseContext containerResponseContext) throws IOException {
MultivaluedMap<String, Object> headers = containerResponseContext.getHeaders();
headers.add(ACCESS_CONTROL_ALLOW_HEADERS, "orgin");
headers.add(ACCESS_CONTROL_ALLOW_HEADERS, "content-type");
headers.add(ACCESS_CONTROL_ALLOW_HEADERS, "accept");
headers.add(ACCESS_CONTROL_ALLOW_HEADERS, "authorization");
customHeaders.forEach(s -> headers.add(ACCESS_CONTROL_ALLOW_HEADERS, s));
// make sure there's only one header with this name
String headerString = (String) headers.get(ACCESS_CONTROL_ALLOW_HEADERS).stream()
.reduce((a, b) -> a.toString() + ", " + b.toString()).get();
headers.putSingle(ACCESS_CONTROL_ALLOW_HEADERS, headerString);
headers.putSingle("Access-Control-Allow-Credentials", "true");
headers.putSingle("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
}
示例14: filter
import javax.ws.rs.container.ContainerRequestContext; //導入依賴的package包/類
public void filter(ContainerRequestContext requestContext) throws IOException {
HttpServletRequest request = ResteasyProviderFactory.getContextData(HttpServletRequest.class);
RpcContext.getContext().setRequest(request);
// this only works for servlet containers
if (request != null && RpcContext.getContext().getRemoteAddress() == null) {
RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort());
}
RpcContext.getContext().setResponse(ResteasyProviderFactory.getContextData(HttpServletResponse.class));
String headers = requestContext.getHeaderString(DUBBO_ATTACHMENT_HEADER);
if (headers != null) {
for (String header : headers.split(",")) {
int index = header.indexOf("=");
if (index > 0) {
String key = header.substring(0, index);
String value = header.substring(index + 1);
if (!StringUtils.isEmpty(key)) {
RpcContext.getContext().setAttachment(key.trim(), value.trim());
}
}
}
}
}
示例15: testVersionFilterVersionNotExisting
import javax.ws.rs.container.ContainerRequestContext; //導入依賴的package包/類
@SuppressWarnings("boxing")
@Test
public void testVersionFilterVersionNotExisting() {
try {
UriInfo info = mock(UriInfo.class);
MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
ContainerRequestContext request = mock(
ContainerRequestContext.class);
when(info.getPathParameters()).thenReturn(map);
when(request.getUriInfo()).thenReturn(info);
VersionFilter filter = new VersionFilter();
filter.filter(request);
} catch (WebApplicationException e) {
assertEquals(Status.NOT_FOUND.getStatusCode(),
e.getResponse().getStatus());
}
}