Search in sources :

Example 36 with ByteString

use of com.linkedin.data.ByteString in project rest.li by linkedin.

the class TestDataMapConverter method testJSONByteStringToDataMapWithUnsupportedContentType.

@Test
public void testJSONByteStringToDataMapWithUnsupportedContentType() throws MimeTypeParseException, IOException {
    // unsupport content type should fallback to JSON
    DataMap expectedDataMap = createTestDataMap();
    ByteString byteString = ByteString.copy(JACKSON_DATA_CODEC.mapToBytes(expectedDataMap));
    Map<String, String> headers = Collections.singletonMap(RestConstants.HEADER_CONTENT_TYPE, "mysuperkool/xson");
    DataMap dataMap = DataMapConverter.bytesToDataMap(headers, byteString);
    Assert.assertEquals(dataMap, expectedDataMap);
}
Also used : ByteString(com.linkedin.data.ByteString) ByteString(com.linkedin.data.ByteString) DataMap(com.linkedin.data.DataMap) Test(org.testng.annotations.Test)

Example 37 with ByteString

use of com.linkedin.data.ByteString in project rest.li by linkedin.

the class IPAddressSimpleCoercer method coerceOutput.

@Override
public InetAddress coerceOutput(Object object) throws TemplateOutputCastException {
    try {
        byte[] addressBytes;
        Class<?> objectType = object.getClass();
        if (objectType == String.class) {
            addressBytes = Data.stringToBytes((String) object, true);
        } else if (objectType == ByteString.class) {
            addressBytes = ((ByteString) object).copyBytes();
        } else {
            throw new TemplateOutputCastException("Invalid type");
        }
        return InetAddress.getByAddress(addressBytes);
    } catch (UnknownHostException e) {
        throw new TemplateOutputCastException("Invalid host", e);
    }
}
Also used : UnknownHostException(java.net.UnknownHostException) ByteString(com.linkedin.data.ByteString) ByteString(com.linkedin.data.ByteString) TemplateOutputCastException(com.linkedin.data.template.TemplateOutputCastException)

Example 38 with ByteString

use of com.linkedin.data.ByteString in project rest.li by linkedin.

the class GreetingUnstructuredDataCollectionResourceReactive method get.

@Override
public void get(String key, @CallbackParam Callback<UnstructuredDataReactiveResult> callback) {
    if (key.equals("callbackError")) {
        callback.onError(new NoPermissionException("missing access permission"));
        return;
    }
    Writer<ByteString> writer = chooseGreetingWriter(key);
    String contentType;
    if (key.equals("goodNullContentType")) {
        contentType = null;
    } else {
        contentType = MIME_TYPE;
    }
    UnstructuredDataReactiveResult result = new UnstructuredDataReactiveResult(EntityStreams.newEntityStream(writer), contentType);
    callback.onSuccess(result);
}
Also used : ByteString(com.linkedin.data.ByteString) UnstructuredDataReactiveResult(com.linkedin.restli.server.UnstructuredDataReactiveResult) NoPermissionException(javax.naming.NoPermissionException) ByteString(com.linkedin.data.ByteString)

Example 39 with ByteString

use of com.linkedin.data.ByteString in project rest.li by linkedin.

the class TestComplexByteKeyResource method testGetMain.

private void testGetMain(RootBuilderWrapper.MethodBuilderWrapper<ComplexResourceKey<TyperefRecord, TwoPartKey>, TyperefRecord, TyperefRecord> requestBuilder) throws RemoteInvocationException {
    final ByteString byteData = ByteString.copy(new byte[] { 0, 32, -95 });
    Request<TyperefRecord> request = requestBuilder.id(getComplexKey(byteData)).build();
    ResponseFuture<TyperefRecord> future = getClient().sendRequest(request);
    Response<TyperefRecord> response = future.getResponse();
    Assert.assertEquals(response.getEntity().getBytes(), byteData);
}
Also used : ByteString(com.linkedin.data.ByteString) TyperefRecord(com.linkedin.restli.examples.typeref.api.TyperefRecord)

Example 40 with ByteString

use of com.linkedin.data.ByteString in project rest.li by linkedin.

the class RestLiSymbolTableRequestHandler method handleRequest.

@Override
public void handleRequest(RestRequest request, RequestContext requestContext, Callback<RestResponse> callback) {
    if (HttpMethod.GET != HttpMethod.valueOf(request.getMethod())) {
        LOGGER.error("GET is expected, but " + request.getMethod() + " received");
        callback.onError(RestException.forError(HttpStatus.S_405_METHOD_NOT_ALLOWED.getCode(), "Invalid method"));
        return;
    }
    // 
    // Determine response content type based on accept header.
    // Assume protobuf2 if no accept header is specified. Note that this is a deviation from the rest of rest.li
    // which assumes JSON as the default, for efficiency reasons.
    // 
    ContentType type;
    String mimeType = Optional.ofNullable(request.getHeader(RestConstants.HEADER_ACCEPT)).orElse(RestConstants.HEADER_VALUE_APPLICATION_PROTOBUF2);
    try {
        type = ContentType.getContentType(mimeType).orElseThrow(() -> new MimeTypeParseException("Invalid accept type: " + mimeType));
    } catch (MimeTypeParseException e) {
        LOGGER.error("Could not handle accept type", e);
        callback.onError(RestException.forError(HttpStatus.S_406_NOT_ACCEPTABLE.getCode(), "Invalid accept type: " + mimeType));
        return;
    }
    final String path = request.getURI().getRawPath();
    final List<UriComponent.PathSegment> pathSegments = UriComponent.decodePath(path, true);
    final SymbolTableProvider provider = SymbolTableProviderHolder.INSTANCE.getSymbolTableProvider();
    SymbolTable symbolTable = null;
    // at this point, `handleRequest` has verified that the incoming request is a symbolTable request.
    // The URL can be one of two options:
    // .../symbolTable/tableName
    // .../symbolTable
    // We check if the last path segments is "symbolTable", and if it is, we call provider.getResponseSymbolTable
    // because we do not know the table name.
    // Otherwise, we call provider.getSymbolTable
    int pathSize = pathSegments.size();
    try {
        if (pathSegments.get(pathSize - 1).getPath().equals(SYMBOL_TABLE_URI_PATH)) {
            symbolTable = provider.getResponseSymbolTable(request.getURI(), request.getHeaders());
        } else if (pathSegments.get(pathSize - 2).getPath().equals(SYMBOL_TABLE_URI_PATH)) {
            symbolTable = provider.getSymbolTable(pathSegments.get(pathSize - 1).getPath());
        } else {
            LOGGER.error("request is malformed for handling symbolTable" + request.getURI());
        }
    } catch (IllegalStateException e) {
        LOGGER.error("Exception retrieving symbol table for URI " + request.getURI());
        symbolTable = null;
    }
    if (symbolTable == null) {
        LOGGER.error("Did not find symbol table for path " + path);
        callback.onError(RestException.forError(HttpStatus.S_404_NOT_FOUND.getCode(), "Did not find symbol table"));
        return;
    }
    try {
        // Cache key is the name of the symbol table concatenated with the type used to serialize the payload.
        String cacheKey = symbolTable.getName() + ":" + type.getHeaderKey();
        ByteString serializedTable = _symbolTableNameToSerializedBytesCache.getIfPresent(cacheKey);
        if (serializedTable == null) {
            serializedTable = SymbolTableSerializer.toByteString(type.getCodec(), symbolTable);
            _symbolTableNameToSerializedBytesCache.put(cacheKey, serializedTable);
        }
        RestResponse restResponse = new RestResponseBuilder().setStatus(HttpStatus.S_200_OK.getCode()).setHeader(RestConstants.HEADER_CONTENT_TYPE, type.getHeaderKey()).setEntity(serializedTable).build();
        callback.onSuccess(restResponse);
    } catch (IOException e) {
        callback.onError(e);
    }
}
Also used : MimeTypeParseException(javax.activation.MimeTypeParseException) SymbolTableProvider(com.linkedin.data.codec.symbol.SymbolTableProvider) DefaultSymbolTableProvider(com.linkedin.data.codec.symbol.DefaultSymbolTableProvider) ContentType(com.linkedin.restli.common.ContentType) ByteString(com.linkedin.data.ByteString) RestResponse(com.linkedin.r2.message.rest.RestResponse) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) SymbolTable(com.linkedin.data.codec.symbol.SymbolTable) ByteString(com.linkedin.data.ByteString) IOException(java.io.IOException)

Aggregations

ByteString (com.linkedin.data.ByteString)152 Test (org.testng.annotations.Test)77 ByteArrayOutputStream (java.io.ByteArrayOutputStream)33 MimeMultipart (javax.mail.internet.MimeMultipart)31 MimeBodyPart (javax.mail.internet.MimeBodyPart)26 DataMap (com.linkedin.data.DataMap)25 RestResponse (com.linkedin.r2.message.rest.RestResponse)25 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)22 FullEntityReader (com.linkedin.r2.message.stream.entitystream.FullEntityReader)22 RestRequest (com.linkedin.r2.message.rest.RestRequest)21 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)21 URI (java.net.URI)21 CountDownLatch (java.util.concurrent.CountDownLatch)20 RequestContext (com.linkedin.r2.message.RequestContext)18 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)18 Callback (com.linkedin.common.callback.Callback)17 StreamRequestBuilder (com.linkedin.r2.message.stream.StreamRequestBuilder)14 RestException (com.linkedin.r2.message.rest.RestException)12 HashMap (java.util.HashMap)12 DataList (com.linkedin.data.DataList)11