Search in sources :

Example 31 with RestException

use of com.linkedin.r2.message.rest.RestException in project voldemort by voldemort.

the class R2Store method getAll.

@Override
public Map<ByteArray, List<Versioned<byte[]>>> getAll(Iterable<ByteArray> keys, Map<ByteArray, byte[]> transforms) throws VoldemortException {
    Map<ByteArray, List<Versioned<byte[]>>> resultMap = new HashMap<ByteArray, List<Versioned<byte[]>>>();
    int numberOfKeys = 0;
    try {
        Iterator<ByteArray> it = keys.iterator();
        StringBuilder keyArgs = null;
        while (it.hasNext()) {
            ByteArray key = it.next();
            String base64Key = RestUtils.encodeVoldemortKey(key.get());
            if (keyArgs == null) {
                keyArgs = new StringBuilder();
                keyArgs.append(base64Key);
            } else {
                keyArgs.append("," + base64Key);
            }
            numberOfKeys++;
        }
        // TODO a common way to handle getAll with any number of keys
        if (numberOfKeys == 1) {
            List<Versioned<byte[]>> resultList = new ArrayList<Versioned<byte[]>>();
            it = keys.iterator();
            ByteArray key = it.next();
            byte[] singleKeyTransforms = null;
            if (transforms != null) {
                singleKeyTransforms = transforms.get(key);
            }
            resultList = this.get(key, singleKeyTransforms);
            resultMap.put(key, resultList);
        } else {
            RestRequestBuilder rb = new RestRequestBuilder(new URI(this.restBootstrapURL + "/" + getName() + "/" + keyArgs.toString()));
            rb.setMethod(GET);
            rb.setHeader("Accept", MULTIPART_CONTENT_TYPE);
            String timeoutStr = Long.toString(this.config.getTimeoutConfig().getOperationTimeout(VoldemortOpCode.GET_ALL_OP_CODE));
            rb.setHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, timeoutStr);
            rb.setHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS, String.valueOf(System.currentTimeMillis()));
            if (this.routingTypeCode != null) {
                rb.setHeader(RestMessageHeaders.X_VOLD_ROUTING_TYPE_CODE, this.routingTypeCode);
            }
            if (this.zoneId != INVALID_ZONE_ID) {
                rb.setHeader(RestMessageHeaders.X_VOLD_ZONE_ID, String.valueOf(this.zoneId));
            }
            RestRequest request = rb.build();
            Future<RestResponse> f = client.restRequest(request);
            // This will block
            RestResponse response = f.get();
            // Parse the response
            final ByteString entity = response.getEntity();
            String contentType = response.getHeader(CONTENT_TYPE);
            if (entity != null) {
                if (contentType.equalsIgnoreCase(MULTIPART_CONTENT_TYPE)) {
                    resultMap = parseGetAllResults(entity);
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Did not receive a multipart response");
                    }
                }
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Did not get any response!");
                }
            }
        }
    } catch (ExecutionException e) {
        if (e.getCause() instanceof RestException) {
            RestException exception = (RestException) e.getCause();
            if (logger.isDebugEnabled()) {
                logger.debug("REST EXCEPTION STATUS : " + exception.getResponse().getStatus());
            }
        } else {
            throw new VoldemortException("Unknown HTTP request execution exception: " + e.getMessage(), e);
        }
    } catch (InterruptedException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Operation interrupted : " + e.getMessage(), e);
        }
        throw new VoldemortException("Operation interrupted exception: " + e.getMessage(), e);
    } catch (URISyntaxException e) {
        throw new VoldemortException("Illegal HTTP URL" + e.getMessage(), e);
    }
    return resultMap;
}
Also used : Versioned(voldemort.versioning.Versioned) HashMap(java.util.HashMap) RestResponse(com.linkedin.r2.message.rest.RestResponse) ByteString(com.linkedin.data.ByteString) ArrayList(java.util.ArrayList) RestException(com.linkedin.r2.message.rest.RestException) ByteString(com.linkedin.data.ByteString) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) VoldemortException(voldemort.VoldemortException) RestRequest(com.linkedin.r2.message.rest.RestRequest) ByteArray(voldemort.utils.ByteArray) List(java.util.List) ArrayList(java.util.ArrayList) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) ExecutionException(java.util.concurrent.ExecutionException)

Example 32 with RestException

use of com.linkedin.r2.message.rest.RestException in project voldemort by voldemort.

the class CoordinatorAdminClient method putStoreClientConfigString.

public boolean putStoreClientConfigString(String storeClientConfigAvro, String coordinatorUrl) {
    String responseMessage = null;
    Boolean success = false;
    try {
        // Create the REST request
        StringBuilder URIStringBuilder = new StringBuilder().append(coordinatorUrl).append(URL_SEPARATOR).append(STORE_CLIENT_CONFIG_OPS).append(URL_SEPARATOR);
        RestRequestBuilder requestBuilder = new RestRequestBuilder(new URI(URIStringBuilder.toString()));
        byte[] payload = storeClientConfigAvro.getBytes("UTF-8");
        // Create a HTTP POST request
        requestBuilder.setMethod(requestType.POST.toString());
        requestBuilder.setEntity(payload);
        requestBuilder.setHeader(CONTENT_TYPE, "binary");
        requestBuilder.setHeader(CONTENT_LENGTH, "" + payload.length);
        String timeoutStr = Long.toString(this.config.getTimeoutConfig().getOperationTimeout(VoldemortOpCode.PUT_OP_CODE));
        requestBuilder.setHeader(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, timeoutStr);
        requestBuilder = setCommonRequestHeader(requestBuilder);
        RestRequest request = requestBuilder.build();
        Future<RestResponse> future = client.restRequest(request);
        // This will block
        RestResponse response = future.get();
        final ByteString entity = response.getEntity();
        if (entity == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Empty response !");
            }
            responseMessage = "Received empty response from " + coordinatorUrl;
        } else {
            responseMessage = entity.asString("UTF-8");
            success = true;
        }
    } catch (Exception e) {
        if (e.getCause() instanceof RestException) {
            responseMessage = ((RestException) e.getCause()).getResponse().getEntity().asString("UTF-8");
        } else {
            responseMessage = "An exception other than RestException happens!";
        }
        handleRequestAndResponseException(e);
    } finally {
        System.out.println(responseMessage);
    }
    return success;
}
Also used : RestRequest(com.linkedin.r2.message.rest.RestRequest) RestResponse(com.linkedin.r2.message.rest.RestResponse) ByteString(com.linkedin.data.ByteString) RestException(com.linkedin.r2.message.rest.RestException) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) ByteString(com.linkedin.data.ByteString) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) RestException(com.linkedin.r2.message.rest.RestException) VoldemortException(voldemort.VoldemortException) ExecutionException(java.util.concurrent.ExecutionException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 33 with RestException

use of com.linkedin.r2.message.rest.RestException in project rest.li by linkedin.

the class RestLiResponseHandler method buildRestException.

public RestException buildRestException(final Throwable e, 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();
        ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
        // partialResponse.getSchema()
        DataMapUtils.write(dataMap, null, baos, true);
        builder.setEntity(baos.toByteArray());
    }
    RestResponse restResponse = builder.build();
    RestException restException = new RestException(restResponse, e);
    return restException;
}
Also used : RestResponse(com.linkedin.r2.message.rest.RestResponse) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) RestException(com.linkedin.r2.message.rest.RestException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DataMap(com.linkedin.data.DataMap)

Example 34 with RestException

use of com.linkedin.r2.message.rest.RestException in project rest.li by linkedin.

the class TestRestCaptureFilter method testCaptureRestException.

@Test
public void testCaptureRestException() {
    final RestRequest req = request();
    final RestResponse res = new RestResponseBuilder().setStatus(RestStatus.NOT_FOUND).build();
    final Exception ex = new RestException(res);
    FilterUtil.fireUntypedRequestError(getFilterChain(), req, ex);
    Assert.assertEquals(res, getDb().replay(req));
}
Also used : RestRequest(com.linkedin.r2.message.rest.RestRequest) RestResponse(com.linkedin.r2.message.rest.RestResponse) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) RestException(com.linkedin.r2.message.rest.RestException) RestException(com.linkedin.r2.message.rest.RestException) Test(org.testng.annotations.Test)

Example 35 with RestException

use of com.linkedin.r2.message.rest.RestException in project rest.li by linkedin.

the class TestRestReplayFilter method testReplayWithRestException.

@Test
public void testReplayWithRestException() {
    final RestRequest req = request();
    final RestResponse res = new RestResponseBuilder().setStatus(RestStatus.NOT_FOUND).build();
    final CaptureLastCallFilter captureFilter = new CaptureLastCallFilter();
    final FilterChain fc = getFilterChain().addFirstRest(captureFilter);
    // Record a response for the request we will fire
    getDb().record(req, res);
    // We should be able to fire just the request - the response should be replayed from the
    // capture we set up above. The response should be a RestException since the status code is 404.
    FilterUtil.fireUntypedRequest(fc, req);
    Assert.assertTrue(captureFilter.getLastErr() instanceof RestException);
    Assert.assertEquals(res, ((RestException) captureFilter.getLastErr()).getResponse());
}
Also used : RestRequest(com.linkedin.r2.message.rest.RestRequest) CaptureLastCallFilter(com.linkedin.r2.testutils.filter.CaptureLastCallFilter) RestResponse(com.linkedin.r2.message.rest.RestResponse) FilterChain(com.linkedin.r2.filter.FilterChain) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) RestException(com.linkedin.r2.message.rest.RestException) Test(org.testng.annotations.Test)

Aggregations

RestException (com.linkedin.r2.message.rest.RestException)62 RestResponse (com.linkedin.r2.message.rest.RestResponse)48 Test (org.testng.annotations.Test)44 RestRequest (com.linkedin.r2.message.rest.RestRequest)33 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)31 URI (java.net.URI)23 BeforeTest (org.testng.annotations.BeforeTest)21 ExecutionException (java.util.concurrent.ExecutionException)20 RestResponseBuilder (com.linkedin.r2.message.rest.RestResponseBuilder)19 FilterRequestContext (com.linkedin.restli.server.filter.FilterRequestContext)19 RequestContext (com.linkedin.r2.message.RequestContext)18 Callback (com.linkedin.common.callback.Callback)16 URISyntaxException (java.net.URISyntaxException)16 ByteString (com.linkedin.data.ByteString)15 AfterTest (org.testng.annotations.AfterTest)12 MultiPartMIMEFullReaderCallback (com.linkedin.multipart.utils.MIMETestUtils.MultiPartMIMEFullReaderCallback)11 SinglePartMIMEFullReaderCallback (com.linkedin.multipart.utils.MIMETestUtils.SinglePartMIMEFullReaderCallback)11 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)11 RequestExecutionReport (com.linkedin.restli.server.RequestExecutionReport)11 RestLiResponseAttachments (com.linkedin.restli.server.RestLiResponseAttachments)11