use of org.glassfish.jersey.server.ContainerRequest in project jersey by jersey.
the class RoutingStage method apply.
/**
* {@inheritDoc}
* <p/>
* Routing stage navigates through the nested {@link Router routing hierarchy}
* using a depth-first transformation strategy until a request-to-response
* inflector is {@link org.glassfish.jersey.process.internal.Inflecting found on
* a leaf stage node}, in which case the request routing is terminated and an
* {@link org.glassfish.jersey.process.Inflector inflector} (if found) is pushed
* to the {@link RoutingContext routing context}.
*/
@Override
public Continuation<RequestProcessingContext> apply(final RequestProcessingContext context) {
final ContainerRequest request = context.request();
context.triggerEvent(RequestEvent.Type.MATCHING_START);
final TracingLogger tracingLogger = TracingLogger.getInstance(request);
final long timestamp = tracingLogger.timestamp(ServerTraceEvent.MATCH_SUMMARY);
try {
final RoutingResult result = _apply(context, routingRoot);
Stage<RequestProcessingContext> nextStage = null;
if (result.endpoint != null) {
context.routingContext().setEndpoint(result.endpoint);
nextStage = getDefaultNext();
}
return Continuation.of(result.context, nextStage);
} finally {
tracingLogger.logDuration(ServerTraceEvent.MATCH_SUMMARY, timestamp);
}
}
use of org.glassfish.jersey.server.ContainerRequest in project jersey by jersey.
the class MethodSelectingRouter method getMethodRouter.
private List<Router> getMethodRouter(final RequestProcessingContext context) {
final ContainerRequest request = context.request();
final List<ConsumesProducesAcceptor> acceptors = consumesProducesAcceptors.get(request.getMethod());
if (acceptors == null) {
throw new NotAllowedException(Response.status(Status.METHOD_NOT_ALLOWED).allow(consumesProducesAcceptors.keySet()).build());
}
final List<ConsumesProducesAcceptor> satisfyingAcceptors = new LinkedList<>();
final Set<ResourceMethod> differentInvokableMethods = Collections.newSetFromMap(new IdentityHashMap<>());
for (ConsumesProducesAcceptor cpi : acceptors) {
if (cpi.isConsumable(request)) {
satisfyingAcceptors.add(cpi);
differentInvokableMethods.add(cpi.methodRouting.method);
}
}
if (satisfyingAcceptors.isEmpty()) {
throw new NotSupportedException();
}
final List<AcceptableMediaType> acceptableMediaTypes = request.getQualifiedAcceptableMediaTypes();
final MediaType requestContentType = request.getMediaType();
final MediaType effectiveContentType = requestContentType == null ? MediaType.WILDCARD_TYPE : requestContentType;
final MethodSelector methodSelector = selectMethod(acceptableMediaTypes, satisfyingAcceptors, effectiveContentType, differentInvokableMethods.size() == 1);
if (methodSelector.selected != null) {
final RequestSpecificConsumesProducesAcceptor selected = methodSelector.selected;
if (methodSelector.sameFitnessAcceptors != null) {
reportMethodSelectionAmbiguity(acceptableMediaTypes, methodSelector.selected, methodSelector.sameFitnessAcceptors);
}
context.push(new Function<ContainerResponse, ContainerResponse>() {
@Override
public ContainerResponse apply(final ContainerResponse responseContext) {
// - either there is an entity, or we are responding to a HEAD request
if (responseContext.getMediaType() == null && ((responseContext.hasEntity() || HttpMethod.HEAD.equals(request.getMethod())))) {
MediaType effectiveResponseType = determineResponseMediaType(responseContext.getEntityClass(), responseContext.getEntityType(), methodSelector.selected, acceptableMediaTypes);
if (MediaTypes.isWildcard(effectiveResponseType)) {
if (effectiveResponseType.isWildcardType() || "application".equalsIgnoreCase(effectiveResponseType.getType())) {
effectiveResponseType = MediaType.APPLICATION_OCTET_STREAM_TYPE;
} else {
throw new NotAcceptableException();
}
}
responseContext.setMediaType(effectiveResponseType);
}
return responseContext;
}
});
return selected.methodRouting.routers;
}
throw new NotAcceptableException();
}
use of org.glassfish.jersey.server.ContainerRequest in project jersey by jersey.
the class InMemoryConnector method apply.
/**
* {@inheritDoc}
* <p/>
* Transforms client-side request to server-side and invokes it on provided application ({@link ApplicationHandler}
* instance).
*
* @param clientRequest client side request to be invoked.
*/
@Override
public ClientResponse apply(final ClientRequest clientRequest) {
PropertiesDelegate propertiesDelegate = new MapPropertiesDelegate();
final ContainerRequest containerRequest = new ContainerRequest(baseUri, clientRequest.getUri(), clientRequest.getMethod(), null, propertiesDelegate);
containerRequest.getHeaders().putAll(clientRequest.getStringHeaders());
final ByteArrayOutputStream clientOutput = new ByteArrayOutputStream();
if (clientRequest.getEntity() != null) {
clientRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {
@Override
public OutputStream getOutputStream(int contentLength) throws IOException {
final MultivaluedMap<String, Object> clientHeaders = clientRequest.getHeaders();
if (contentLength != -1 && !clientHeaders.containsKey(HttpHeaders.CONTENT_LENGTH)) {
containerRequest.getHeaders().putSingle(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength));
}
return clientOutput;
}
});
clientRequest.enableBuffering();
try {
clientRequest.writeEntity();
} catch (IOException e) {
final String msg = "Error while writing entity to the output stream.";
LOGGER.log(Level.SEVERE, msg, e);
throw new ProcessingException(msg, e);
}
}
containerRequest.setEntityStream(new ByteArrayInputStream(clientOutput.toByteArray()));
boolean followRedirects = ClientProperties.getValue(clientRequest.getConfiguration().getProperties(), ClientProperties.FOLLOW_REDIRECTS, true);
final InMemoryResponseWriter inMemoryResponseWriter = new InMemoryResponseWriter();
containerRequest.setWriter(inMemoryResponseWriter);
containerRequest.setSecurityContext(new SecurityContext() {
@Override
public Principal getUserPrincipal() {
return null;
}
@Override
public boolean isUserInRole(String role) {
return false;
}
@Override
public boolean isSecure() {
return false;
}
@Override
public String getAuthenticationScheme() {
return null;
}
});
appHandler.handle(containerRequest);
return tryFollowRedirects(followRedirects, createClientResponse(clientRequest, inMemoryResponseWriter), new ClientRequest(clientRequest));
}
use of org.glassfish.jersey.server.ContainerRequest in project jersey by jersey.
the class ResourceMethodInvoker method apply.
@Override
@SuppressWarnings("unchecked")
public ContainerResponse apply(final RequestProcessingContext processingContext) {
final ContainerRequest request = processingContext.request();
final Object resource = processingContext.routingContext().peekMatchedResource();
if (method.isSuspendDeclared() || method.isManagedAsyncDeclared()) {
if (!processingContext.asyncContext().suspend()) {
throw new ProcessingException(LocalizationMessages.ERROR_SUSPENDING_ASYNC_REQUEST());
}
}
if (method.isManagedAsyncDeclared()) {
processingContext.asyncContext().invokeManaged(new Producer<Response>() {
@Override
public Response call() {
final Response response = invoke(processingContext, resource);
if (method.isSuspendDeclared()) {
// we ignore any response returned from a method that injects AsyncResponse
return null;
}
return response;
}
});
// return null on current thread
return null;
} else {
// TODO replace with processing context factory method.
return new ContainerResponse(request, invoke(processingContext, resource));
}
}
use of org.glassfish.jersey.server.ContainerRequest in project jersey by jersey.
the class JsonProcessingAutoDiscoverableServerTest method _test.
private void _test(final String response, final Boolean globalDisable, final Boolean serverDisable) throws Exception {
final ResourceConfig resourceConfig = new ResourceConfig(Resource.class, Filter.class);
if (globalDisable != null) {
resourceConfig.property(CommonProperties.JSON_PROCESSING_FEATURE_DISABLE, globalDisable);
}
if (serverDisable != null) {
resourceConfig.property(ServerProperties.JSON_PROCESSING_FEATURE_DISABLE, serverDisable);
}
final ApplicationHandler app = new ApplicationHandler(resourceConfig);
final URI baseUri = URI.create("/");
assertEquals(response, app.apply(new ContainerRequest(baseUri, baseUri, "GET", null, new MapPropertiesDelegate())).get().getEntity());
}
Aggregations