Search in sources :

Example 1 with ServerResourceContext

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);
}
Also used : FilterRequestContextInternalImpl(com.linkedin.restli.internal.server.filter.FilterRequestContextInternalImpl) RestResponse(com.linkedin.r2.message.rest.RestResponse) RestLiArgumentBuilder(com.linkedin.restli.internal.server.methods.arguments.RestLiArgumentBuilder) MultiPartIllegalFormatException(com.linkedin.multipart.exceptions.MultiPartIllegalFormatException) ParseException(javax.mail.internet.ParseException) RestException(com.linkedin.r2.message.rest.RestException) RestLiAttachmentReaderException(com.linkedin.restli.common.attachments.RestLiAttachmentReaderException) RestLiFilterChain(com.linkedin.restli.internal.server.filter.RestLiFilterChain) RoutingResult(com.linkedin.restli.internal.server.RoutingResult) FilterChainCallback(com.linkedin.restli.internal.server.filter.FilterChainCallback) RestLiFilterResponseContextFactory(com.linkedin.restli.internal.server.filter.RestLiFilterResponseContextFactory) FilterRequestContextInternal(com.linkedin.restli.internal.server.filter.FilterRequestContextInternal) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) FilterChainCallbackImpl(com.linkedin.restli.internal.server.filter.FilterChainCallbackImpl)

Example 2 with ServerResourceContext

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;
}
Also used : AnyRecord(com.linkedin.restli.internal.server.methods.AnyRecord) HttpStatus(com.linkedin.restli.common.HttpStatus) HashMap(java.util.HashMap) BatchResult(com.linkedin.restli.server.BatchResult) DataMap(com.linkedin.data.DataMap) BatchResponseEntry(com.linkedin.restli.internal.server.response.BatchResponseEnvelope.BatchResponseEntry) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) RecordTemplate(com.linkedin.data.template.RecordTemplate) HashMap(java.util.HashMap) DataMap(com.linkedin.data.DataMap) Map(java.util.Map)

Example 3 with ServerResourceContext

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);
}
Also used : ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) ProtocolVersion(com.linkedin.restli.common.ProtocolVersion) TreeMap(java.util.TreeMap) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) RestLiInternalException(com.linkedin.restli.internal.server.RestLiInternalException) HttpCookie(java.net.HttpCookie)

Example 4 with ServerResourceContext

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();
}
Also used : ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) DataMap(com.linkedin.data.DataMap)

Example 5 with ServerResourceContext

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;
}
Also used : ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext)

Aggregations

ServerResourceContext (com.linkedin.restli.internal.server.ServerResourceContext)55 Test (org.testng.annotations.Test)28 RoutingResult (com.linkedin.restli.internal.server.RoutingResult)18 Parameter (com.linkedin.restli.internal.server.model.Parameter)15 ResourceContextImpl (com.linkedin.restli.internal.server.ResourceContextImpl)14 DataMap (com.linkedin.data.DataMap)13 RestLiServiceException (com.linkedin.restli.server.RestLiServiceException)12 HashMap (java.util.HashMap)11 RequestContext (com.linkedin.r2.message.RequestContext)10 PathKeysImpl (com.linkedin.restli.internal.server.PathKeysImpl)10 ResourceMethodDescriptor (com.linkedin.restli.internal.server.model.ResourceMethodDescriptor)9 RestRequest (com.linkedin.r2.message.rest.RestRequest)8 RestLiAttachmentReader (com.linkedin.restli.common.attachments.RestLiAttachmentReader)7 URI (java.net.URI)7 ByteString (com.linkedin.data.ByteString)6 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)6 RestResponse (com.linkedin.r2.message.rest.RestResponse)6 RoutingException (com.linkedin.restli.server.RoutingException)6 MaskTree (com.linkedin.data.transform.filter.request.MaskTree)5 ResourceModel (com.linkedin.restli.internal.server.model.ResourceModel)5