Search in sources :

Example 11 with ProtocolVersion

use of com.linkedin.restli.common.ProtocolVersion in project rest.li by linkedin.

the class ExampleRequestResponseGenerator method buildRequest.

private RestRequest buildRequest(Request<?> request) {
    ProtocolVersion protocolVersion;
    switch(_requestOptions.getProtocolVersionOption()) {
        case FORCE_USE_LATEST:
            protocolVersion = AllProtocolVersions.LATEST_PROTOCOL_VERSION;
            break;
        case USE_LATEST_IF_AVAILABLE:
            protocolVersion = AllProtocolVersions.BASELINE_PROTOCOL_VERSION;
            break;
        case FORCE_USE_NEXT:
            protocolVersion = AllProtocolVersions.NEXT_PROTOCOL_VERSION;
            break;
        case FORCE_USE_PREVIOUS:
            protocolVersion = AllProtocolVersions.PREVIOUS_PROTOCOL_VERSION;
            break;
        default:
            throw new IllegalArgumentException("Unsupported enum value: " + _requestOptions.getProtocolVersionOption());
    }
    URI uri = RestliUriBuilderUtil.createUriBuilder(request, "", protocolVersion).build();
    RestRequestBuilder requestBuilder = new RestRequestBuilder(uri);
    requestBuilder.setMethod(request.getMethod().getHttpMethod().name());
    // unfortunately some headers get set in RestClient, and since we're not using rest client, we
    // replicate that behavior here
    requestBuilder.setHeader(RestConstants.HEADER_ACCEPT, RestConstants.HEADER_VALUE_APPLICATION_JSON);
    requestBuilder.setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, protocolVersion.toString());
    if (request.getMethod().getHttpMethod() == HttpMethod.POST) {
        requestBuilder.setHeader(RestConstants.HEADER_RESTLI_REQUEST_METHOD, request.getMethod().toString());
    }
    if (request.getInputRecord() != null) {
        requestBuilder.setHeader(RestConstants.HEADER_CONTENT_TYPE, RestConstants.HEADER_VALUE_APPLICATION_JSON);
        writeEntity(request, protocolVersion, requestBuilder);
    }
    return requestBuilder.build();
}
Also used : RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) ProtocolVersion(com.linkedin.restli.common.ProtocolVersion) URI(java.net.URI)

Example 12 with ProtocolVersion

use of com.linkedin.restli.common.ProtocolVersion in project rest.li by linkedin.

the class TestFilterRequestContextInternalImpl method testFilterRequestContextAdapter.

@Test
public void testFilterRequestContextAdapter() throws Exception {
    final String resourceName = "resourceName";
    final String resourceNamespace = "resourceNamespace";
    final ResourceMethod methodType = ResourceMethod.GET;
    final DataMap customAnnotations = new DataMap();
    customAnnotations.put("foo", "Bar");
    final ProjectionMode projectionMode = ProjectionMode.AUTOMATIC;
    final MaskTree maskTree = new MaskTree();
    final MutablePathKeys pathKeys = new PathKeysImpl();
    final Map<String, String> requestHeaders = new HashMap<String, String>();
    requestHeaders.put("Key1", "Value1");
    final URI requestUri = new URI("foo.bar.com");
    final ProtocolVersion protoVersion = AllProtocolVersions.BASELINE_PROTOCOL_VERSION;
    final DataMap queryParams = new DataMap();
    queryParams.put("Param1", "Val1");
    final Map<String, Object> localAttrs = new HashMap<>();
    localAttrs.put("Key1", "Val1");
    final RequestContext r2RequestContext = new RequestContext();
    r2RequestContext.putLocalAttr("Key1", "Val1");
    final String finderName = UUID.randomUUID().toString();
    final String actionName = UUID.randomUUID().toString();
    when(resourceModel.getName()).thenReturn(resourceName);
    when(resourceModel.getNamespace()).thenReturn(resourceNamespace);
    when(resourceMethod.getResourceModel()).thenReturn(resourceModel);
    when(resourceMethod.getMethodType()).thenReturn(methodType);
    when(resourceMethod.getFinderName()).thenReturn(finderName);
    when(resourceMethod.getActionName()).thenReturn(actionName);
    when(resourceMethod.getCustomAnnotationData()).thenReturn(customAnnotations);
    when(resourceMethod.getMethod()).thenReturn(null);
    when(context.getProjectionMode()).thenReturn(projectionMode);
    when(context.getProjectionMask()).thenReturn(maskTree);
    when(context.getPathKeys()).thenReturn(pathKeys);
    when(context.getRequestHeaders()).thenReturn(requestHeaders);
    when(context.getRequestURI()).thenReturn(requestUri);
    when(context.getRestliProtocolVersion()).thenReturn(protoVersion);
    when(context.getParameters()).thenReturn(queryParams);
    when(context.getRawRequestContext()).thenReturn(r2RequestContext);
    FilterRequestContextInternalImpl filterContext = new FilterRequestContextInternalImpl(context, resourceMethod);
    Object spValue = new Object();
    String spKey = UUID.randomUUID().toString();
    filterContext.getFilterScratchpad().put(spKey, spValue);
    assertEquals(filterContext.getFilterResourceModel().getResourceName(), resourceName);
    assertEquals(filterContext.getFilterResourceModel().getResourceNamespace(), resourceNamespace);
    assertEquals(filterContext.getMethodType(), methodType);
    assertEquals(filterContext.getCustomAnnotations(), customAnnotations);
    assertEquals(filterContext.getProjectionMode(), projectionMode);
    assertEquals(filterContext.getProjectionMask(), maskTree);
    assertEquals(filterContext.getPathKeys(), pathKeys);
    assertEquals(filterContext.getRequestHeaders(), requestHeaders);
    assertEquals(filterContext.getRequestURI(), requestUri);
    assertEquals(filterContext.getRestliProtocolVersion(), protoVersion);
    assertEquals(filterContext.getQueryParameters(), queryParams);
    assertEquals(filterContext.getActionName(), actionName);
    assertEquals(filterContext.getFinderName(), finderName);
    assertEquals(filterContext.getRequestContextLocalAttrs(), localAttrs);
    assertNull(filterContext.getMethod());
    assertTrue(filterContext.getFilterScratchpad().get(spKey) == spValue);
    filterContext.getRequestHeaders().put("header2", "value2");
    assertEquals(requestHeaders.get("header2"), "value2");
    verify(resourceModel).getName();
    verify(resourceModel).getNamespace();
    verify(resourceMethod).getMethodType();
    verify(resourceMethod).getResourceModel();
    verify(resourceMethod).getCustomAnnotationData();
    verify(resourceMethod).getFinderName();
    verify(resourceMethod).getActionName();
    verify(resourceMethod).getMethod();
    verify(context).getProjectionMode();
    verify(context).getProjectionMask();
    verify(context).getPathKeys();
    verify(context, times(2)).getRequestHeaders();
    verify(context).getRequestURI();
    verify(context).getRestliProtocolVersion();
    verify(context).getParameters();
    verify(context).getRawRequestContext();
    verify(resourceMethod).getFinderMetadataType();
    verifyNoMoreInteractions(context, resourceMethod, resourceModel);
}
Also used : MutablePathKeys(com.linkedin.restli.internal.server.MutablePathKeys) HashMap(java.util.HashMap) PathKeysImpl(com.linkedin.restli.internal.server.PathKeysImpl) ProtocolVersion(com.linkedin.restli.common.ProtocolVersion) URI(java.net.URI) DataMap(com.linkedin.data.DataMap) MaskTree(com.linkedin.data.transform.filter.request.MaskTree) ProjectionMode(com.linkedin.restli.server.ProjectionMode) RequestContext(com.linkedin.r2.message.RequestContext) ResourceMethod(com.linkedin.restli.common.ResourceMethod) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Example 13 with ProtocolVersion

use of com.linkedin.restli.common.ProtocolVersion 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 14 with ProtocolVersion

use of com.linkedin.restli.common.ProtocolVersion in project rest.li by linkedin.

the class ResponseImpl method getId.

/**
   * Specific getter for the 'X-LinkedIn-Id' header
   *
   * @throws UnsupportedOperationException if the entity returned is a {@link CreateResponse} or {@link IdResponse}
   * and the key is a {@link ComplexResourceKey} or {@link CompoundKey}.
   *
   * @deprecated
   * @see {@link com.linkedin.restli.client.Response#getId()}
   */
@Override
@Deprecated
public String getId() {
    if (_entity instanceof CreateResponse<?> || _entity instanceof IdResponse<?> || _entity instanceof IdEntityResponse<?, ?>) {
        final Object id = checkAndReturnId();
        final ProtocolVersion protocolVersion = ProtocolVersionUtil.extractProtocolVersion(_headers);
        return URIParamUtils.encodeKeyForHeader(id, protocolVersion);
    } else {
        return null;
    }
}
Also used : IdResponse(com.linkedin.restli.common.IdResponse) CreateResponse(com.linkedin.restli.client.response.CreateResponse) ProtocolVersion(com.linkedin.restli.common.ProtocolVersion)

Example 15 with ProtocolVersion

use of com.linkedin.restli.common.ProtocolVersion in project rest.li by linkedin.

the class RestliRequestUriSignature method dump.

/**
   * Return a {@link String} representation of the signature. The difference to {@link #toString()} is that
   * this method always returns stable result across different Map capacity and Java versions, ideal for storing and caching.
   * This is done by visiting the Map {@link Map}s by the order of its keys.
   *
   * This method is more costly tha toString(). If there is no requirement for stability, prefer to use toString().
   */
public String dump() {
    final ProtocolVersion protocolVersion = AllProtocolVersions.LATEST_PROTOCOL_VERSION;
    final DataMap pathKeysMap = new DataMap(URIParamUtils.encodePathKeysForUri(_pathKeys, protocolVersion));
    final DataMap queryParamsMap = QueryParamsUtil.convertToDataMap(_queryParams, _queryParamClasses, protocolVersion);
    final ToStringBuilder builder = new ToStringBuilder(null, ToStringStyle.SHORT_PREFIX_STYLE).append("baseUriTemplate", _baseUriTemplate).append("pathKeys", Data.dump("", pathKeysMap, "")).append("id", _id).append("queryParams", Data.dump("", queryParamsMap, ""));
    return builder.toString();
}
Also used : ToStringBuilder(org.apache.commons.lang.builder.ToStringBuilder) ProtocolVersion(com.linkedin.restli.common.ProtocolVersion) DataMap(com.linkedin.data.DataMap)

Aggregations

ProtocolVersion (com.linkedin.restli.common.ProtocolVersion)35 DataMap (com.linkedin.data.DataMap)12 Test (org.testng.annotations.Test)8 CompoundKey (com.linkedin.restli.common.CompoundKey)7 RestLiServiceException (com.linkedin.restli.server.RestLiServiceException)7 URI (java.net.URI)7 ServerResourceContext (com.linkedin.restli.internal.server.ServerResourceContext)5 HashMap (java.util.HashMap)5 ComplexResourceKey (com.linkedin.restli.common.ComplexResourceKey)4 ResourceMethod (com.linkedin.restli.common.ResourceMethod)4 ByteString (com.linkedin.data.ByteString)3 BatchKVResponse (com.linkedin.restli.client.response.BatchKVResponse)3 ErrorResponse (com.linkedin.restli.common.ErrorResponse)3 IdResponse (com.linkedin.restli.common.IdResponse)3 AnyRecord (com.linkedin.restli.internal.server.methods.AnyRecord)3 HttpCookie (java.net.HttpCookie)3 HashSet (java.util.HashSet)3 RecordTemplate (com.linkedin.data.template.RecordTemplate)2 MaskTree (com.linkedin.data.transform.filter.request.MaskTree)2 Foo (com.linkedin.pegasus.generator.examples.Foo)2