use of com.linkedin.restli.internal.server.ServerResourceContext in project rest.li by linkedin.
the class RestLiServer method handleResourceRequest.
private void handleResourceRequest(final RestRequest request, final RequestContext requestContext, final RequestExecutionCallback<RestResponse> callback, final RestLiAttachmentReader attachmentReader, final boolean isDebugMode) {
try {
ensureRequestUsesValidRestliProtocol(request);
} catch (RestLiServiceException e) {
respondWithPreRoutingError(e, request, attachmentReader, callback);
return;
}
final RoutingResult method;
try {
method = _router.process(request, requestContext, attachmentReader);
} catch (Exception e) {
respondWithPreRoutingError(e, request, attachmentReader, callback);
return;
}
final RequestExecutionCallback<RestResponse> wrappedCallback = notifyInvokeAwares(method, callback);
RequestExecutionReportBuilder requestExecutionReportBuilder = null;
if (isDebugMode) {
requestExecutionReportBuilder = new RequestExecutionReportBuilder();
}
final FilterRequestContextInternal filterContext = new FilterRequestContextInternalImpl((ServerResourceContext) method.getContext(), method.getResourceMethod());
RestLiArgumentBuilder adapter;
try {
RestUtils.validateRequestHeadersAndUpdateResourceContext(request.getHeaders(), (ServerResourceContext) method.getContext());
adapter = buildRestLiArgumentBuilder(method, _errorResponseBuilder);
filterContext.setRequestData(adapter.extractRequestData(method, request));
} catch (Exception e) {
// would not trigger response filters because request filters haven't run yet
wrappedCallback.onError(e, requestExecutionReportBuilder == null ? null : requestExecutionReportBuilder.build(), ((ServerResourceContext) method.getContext()).getRequestAttachmentReader(), null);
return;
}
RestLiFilterResponseContextFactory<Object> filterResponseContextFactory = new RestLiFilterResponseContextFactory<Object>(request, method, _responseHandler);
FilterChainCallback filterChainCallback = new FilterChainCallbackImpl(method, _methodInvoker, adapter, requestExecutionReportBuilder, attachmentReader, _responseHandler, wrappedCallback);
RestLiFilterChain filterChain = new RestLiFilterChain(_filters, filterChainCallback);
filterChain.onRequest(filterContext, filterResponseContextFactory);
}
use of com.linkedin.restli.internal.server.ServerResourceContext in project rest.li by linkedin.
the class BatchGetResponseBuilder method buildRestLiResponseData.
@Override
public RestLiResponseData buildRestLiResponseData(RestRequest request, RoutingResult routingResult, Object result, Map<String, String> headers, List<HttpCookie> cookies) {
@SuppressWarnings({ "unchecked" }) final Map<Object, RecordTemplate> /** constrained by signature of {@link com.linkedin.restli.server.resources.CollectionResource#batchGet(java.util.Set)} */
entities = (Map<Object, RecordTemplate>) result;
Map<Object, HttpStatus> statuses = Collections.emptyMap();
Map<Object, RestLiServiceException> serviceErrors = Collections.emptyMap();
if (result instanceof BatchResult) {
@SuppressWarnings({ "unchecked" }) final BatchResult<Object, RecordTemplate> /** constrained by signature of {@link com.linkedin.restli.server.resources.CollectionResource#batchGet(java.util.Set)} */
batchResult = (BatchResult<Object, RecordTemplate>) result;
statuses = batchResult.getStatuses();
serviceErrors = batchResult.getErrors();
}
try {
if (statuses.containsKey(null)) {
throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null key inside of a Map returned by the resource method: " + routingResult.getResourceMethod());
}
} catch (NullPointerException e) {
// Some map implementations will throw an NPE if they do not support null keys.
// In this case it is OK to swallow this exception and proceed.
}
Map<Object, BatchResponseEntry> batchResult = new HashMap<Object, BatchResponseEntry>(entities.size() + serviceErrors.size());
for (Map.Entry<Object, RecordTemplate> entity : entities.entrySet()) {
if (entity.getKey() == null) {
throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null key inside of a Map returned by the resource method: " + routingResult.getResourceMethod());
}
Object finalKey = ResponseUtils.translateCanonicalKeyToAlternativeKeyIfNeeded(entity.getKey(), routingResult);
final DataMap projectedData = RestUtils.projectFields(entity.getValue().data(), routingResult.getContext().getProjectionMode(), routingResult.getContext().getProjectionMask());
AnyRecord anyRecord = new AnyRecord(projectedData);
batchResult.put(finalKey, new BatchResponseEntry(statuses.get(entity.getKey()), anyRecord));
}
for (Map.Entry<Object, RestLiServiceException> entity : serviceErrors.entrySet()) {
if (entity.getKey() == null || entity.getValue() == null) {
throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null key inside of a Map returned by the resource method: " + routingResult.getResourceMethod());
}
Object finalKey = ResponseUtils.translateCanonicalKeyToAlternativeKeyIfNeeded(entity.getKey(), routingResult);
batchResult.put(finalKey, new BatchResponseEntry(statuses.get(entity.getKey()), entity.getValue()));
}
final Map<Object, RestLiServiceException> contextErrors = ((ServerResourceContext) routingResult.getContext()).getBatchKeyErrors();
for (Map.Entry<Object, RestLiServiceException> entry : contextErrors.entrySet()) {
Object finalKey = ResponseUtils.translateCanonicalKeyToAlternativeKeyIfNeeded(entry.getKey(), routingResult);
batchResult.put(finalKey, new BatchResponseEntry(statuses.get(entry.getKey()), entry.getValue()));
}
RestLiResponseDataImpl responseData = new RestLiResponseDataImpl(HttpStatus.S_200_OK, headers, cookies);
responseData.setResponseEnvelope(new BatchGetResponseEnvelope(batchResult, responseData));
return responseData;
}
use of com.linkedin.restli.internal.server.ServerResourceContext in project rest.li by linkedin.
the class RestLiResponseHandler method buildRestLiResponseData.
/**
* Build a RestLiResponseDataInternal from response object, incoming RestRequest and RoutingResult.
*
* @param request
* {@link RestRequest}
* @param routingResult
* {@link RoutingResult}
* @param responseObject
* response value
* @return {@link RestLiResponseEnvelope}
* @throws IOException
* if cannot build response
*/
public RestLiResponseData buildRestLiResponseData(final RestRequest request, final RoutingResult routingResult, final Object responseObject) throws IOException {
ServerResourceContext context = (ServerResourceContext) routingResult.getContext();
final ProtocolVersion protocolVersion = context.getRestliProtocolVersion();
Map<String, String> responseHeaders = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
responseHeaders.putAll(context.getResponseHeaders());
responseHeaders.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, protocolVersion.toString());
List<HttpCookie> responseCookies = context.getResponseCookies();
if (responseObject == null) {
//If we have a null result, we have to assign the correct response status
if (routingResult.getResourceMethod().getType().equals(ResourceMethod.ACTION)) {
RestLiResponseDataImpl responseData = new RestLiResponseDataImpl(HttpStatus.S_200_OK, responseHeaders, responseCookies);
responseData.setResponseEnvelope(new ActionResponseEnvelope(null, responseData));
return responseData;
} else if (routingResult.getResourceMethod().getType().equals(ResourceMethod.GET)) {
throw new RestLiServiceException(HttpStatus.S_404_NOT_FOUND, "Requested entity not found: " + routingResult.getResourceMethod());
} else {
//All other cases do not permit null to be returned
throw new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Unexpected null encountered. Null returned by the resource method: " + routingResult.getResourceMethod());
}
}
RestLiResponseBuilder responseBuilder = chooseResponseBuilder(responseObject, routingResult);
if (responseBuilder == null) {
// this should not happen if valid return types are specified
ResourceMethodDescriptor resourceMethod = routingResult.getResourceMethod();
String fqMethodName = resourceMethod.getResourceModel().getResourceClass().getName() + '#' + routingResult.getResourceMethod().getMethod().getName();
throw new RestLiInternalException("Invalid return type '" + responseObject.getClass() + " from method '" + fqMethodName + '\'');
}
return responseBuilder.buildRestLiResponseData(request, routingResult, responseObject, responseHeaders, responseCookies);
}
use of com.linkedin.restli.internal.server.ServerResourceContext in project rest.li by linkedin.
the class RestLiResponseHandler method buildResponse.
/**
* Build a RestResponse from PartialRestResponse and RoutingResult.
*
* @param routingResult
* {@link RoutingResult}
* @param partialResponse
* {@link PartialRestResponse}
* @return
*/
public RestResponse buildResponse(final RoutingResult routingResult, PartialRestResponse partialResponse) {
List<String> cookies = CookieUtil.encodeSetCookies(partialResponse.getCookies());
RestResponseBuilder builder = new RestResponseBuilder().setHeaders(partialResponse.getHeaders()).setCookies(cookies).setStatus(partialResponse.getStatus().getCode());
if (partialResponse.hasData()) {
DataMap dataMap = partialResponse.getDataMap();
String mimeType = ((ServerResourceContext) routingResult.getContext()).getResponseMimeType();
builder = encodeResult(mimeType, builder, dataMap);
}
return builder.build();
}
use of com.linkedin.restli.internal.server.ServerResourceContext in project rest.li by linkedin.
the class RestLiArgumentBuilderTestHelper method getMockResourceContextWithStructuredParameter.
public static ServerResourceContext getMockResourceContextWithStructuredParameter(String parameterKey, String parameterValue, Object structuredParameter, boolean attachmentReaderGetExpected) {
ServerResourceContext context = createMock(ServerResourceContext.class);
expect(context.getParameter(parameterKey)).andReturn(parameterValue);
expect(context.getStructuredParameter(parameterKey)).andReturn(structuredParameter);
if (attachmentReaderGetExpected) {
expect(context.getRequestAttachmentReader()).andReturn(null);
}
replay(context);
return context;
}
Aggregations