Search in sources :

Example 1 with Olingo2BatchResponse

use of org.apache.camel.component.olingo2.api.batch.Olingo2BatchResponse in project camel by apache.

the class Olingo2AppImpl method parseResponse.

private Olingo2BatchResponse parseResponse(Edm edm, Map<String, String> contentIdLocationMap, Olingo2BatchRequest request, BatchSingleResponse response) throws EntityProviderException, ODataApplicationException {
    // validate HTTP status
    final int statusCode = Integer.parseInt(response.getStatusCode());
    final String statusInfo = response.getStatusInfo();
    final BasicHttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, statusCode, statusInfo));
    final Map<String, String> headers = response.getHeaders();
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpResponse.setHeader(entry.getKey(), entry.getValue());
    }
    ByteArrayInputStream content = null;
    try {
        if (response.getBody() != null) {
            final ContentType partContentType = receiveWithCharsetParameter(ContentType.parse(headers.get(HttpHeaders.CONTENT_TYPE)), Consts.UTF_8);
            final String charset = partContentType.getCharset().toString();
            final String body = response.getBody();
            content = body != null ? new ByteArrayInputStream(body.getBytes(charset)) : null;
            httpResponse.setEntity(new StringEntity(body, charset));
        }
        AbstractFutureCallback.checkStatus(httpResponse);
    } catch (ODataApplicationException e) {
        return new Olingo2BatchResponse(statusCode, statusInfo, response.getContentId(), response.getHeaders(), e);
    } catch (UnsupportedEncodingException e) {
        return new Olingo2BatchResponse(statusCode, statusInfo, response.getContentId(), response.getHeaders(), e);
    }
    // resolve resource path and query params and parse batch part uri
    final String resourcePath = request.getResourcePath();
    final String resolvedResourcePath;
    if (resourcePath.startsWith("$") && !(METADATA.equals(resourcePath) || BATCH.equals(resourcePath))) {
        resolvedResourcePath = findLocation(resourcePath, contentIdLocationMap);
    } else {
        final String resourceLocation = response.getHeader(HttpHeaders.LOCATION);
        resolvedResourcePath = resourceLocation != null ? resourceLocation.substring(serviceUri.length()) : resourcePath;
    }
    final Map<String, String> resolvedQueryParams = request instanceof Olingo2BatchQueryRequest ? ((Olingo2BatchQueryRequest) request).getQueryParams() : null;
    final UriInfoWithType uriInfo = parseUri(edm, resolvedResourcePath, resolvedQueryParams);
    // resolve response content
    final Object resolvedContent = content != null ? readContent(uriInfo, content) : null;
    return new Olingo2BatchResponse(statusCode, statusInfo, response.getContentId(), response.getHeaders(), resolvedContent);
}
Also used : ContentType(org.apache.http.entity.ContentType) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ODataApplicationException(org.apache.olingo.odata2.api.exception.ODataApplicationException) BasicStatusLine(org.apache.http.message.BasicStatusLine) Olingo2BatchQueryRequest(org.apache.camel.component.olingo2.api.batch.Olingo2BatchQueryRequest) StringEntity(org.apache.http.entity.StringEntity) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) Olingo2BatchResponse(org.apache.camel.component.olingo2.api.batch.Olingo2BatchResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with Olingo2BatchResponse

use of org.apache.camel.component.olingo2.api.batch.Olingo2BatchResponse in project camel by apache.

the class Olingo2AppImpl method writeContent.

private <T> void writeContent(final Edm edm, HttpEntityEnclosingRequestBase httpEntityRequest, final UriInfoWithType uriInfo, final Object content, final Olingo2ResponseHandler<T> responseHandler) {
    try {
        // process resource by UriType
        final ODataResponse response = writeContent(edm, uriInfo, content);
        // copy all response headers
        for (String header : response.getHeaderNames()) {
            httpEntityRequest.setHeader(header, response.getHeader(header));
        }
        // get (http) entity which is for default Olingo2 implementation an InputStream
        if (response.getEntity() instanceof InputStream) {
            httpEntityRequest.setEntity(new InputStreamEntity((InputStream) response.getEntity()));
        /*
                // avoid sending it without a header field set
                if (!httpEntityRequest.containsHeader(HttpHeaders.CONTENT_TYPE)) {
                    httpEntityRequest.addHeader(HttpHeaders.CONTENT_TYPE, getContentType());
                }
*/
        }
        // execute HTTP request
        final Header requestContentTypeHeader = httpEntityRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE);
        final ContentType requestContentType = requestContentTypeHeader != null ? ContentType.parse(requestContentTypeHeader.getValue()) : contentType;
        execute(httpEntityRequest, requestContentType, new AbstractFutureCallback<T>(responseHandler) {

            @SuppressWarnings("unchecked")
            @Override
            public void onCompleted(HttpResponse result) throws IOException, EntityProviderException, BatchException, ODataApplicationException {
                // if a entity is created (via POST request) the response body contains the new created entity
                HttpStatusCodes statusCode = HttpStatusCodes.fromStatusCode(result.getStatusLine().getStatusCode());
                // look for no content, or no response body!!!
                final boolean noEntity = result.getEntity() == null || result.getEntity().getContentLength() == 0;
                if (statusCode == HttpStatusCodes.NO_CONTENT || noEntity) {
                    responseHandler.onResponse((T) HttpStatusCodes.fromStatusCode(result.getStatusLine().getStatusCode()));
                } else {
                    switch(uriInfo.getUriType()) {
                        case URI9:
                            // $batch
                            final List<BatchSingleResponse> singleResponses = EntityProvider.parseBatchResponse(result.getEntity().getContent(), result.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
                            // parse batch response bodies
                            final List<Olingo2BatchResponse> responses = new ArrayList<Olingo2BatchResponse>();
                            Map<String, String> contentIdLocationMap = new HashMap<String, String>();
                            final List<Olingo2BatchRequest> batchRequests = (List<Olingo2BatchRequest>) content;
                            final Iterator<Olingo2BatchRequest> iterator = batchRequests.iterator();
                            for (BatchSingleResponse response : singleResponses) {
                                final Olingo2BatchRequest request = iterator.next();
                                if (request instanceof Olingo2BatchChangeRequest && ((Olingo2BatchChangeRequest) request).getContentId() != null) {
                                    contentIdLocationMap.put("$" + ((Olingo2BatchChangeRequest) request).getContentId(), response.getHeader(HttpHeaders.LOCATION));
                                }
                                try {
                                    responses.add(parseResponse(edm, contentIdLocationMap, request, response));
                                } catch (Exception e) {
                                    // report any parsing errors as error response
                                    responses.add(new Olingo2BatchResponse(Integer.parseInt(response.getStatusCode()), response.getStatusInfo(), response.getContentId(), response.getHeaders(), new ODataApplicationException("Error parsing response for " + request + ": " + e.getMessage(), Locale.ENGLISH, e)));
                                }
                            }
                            responseHandler.onResponse((T) responses);
                            break;
                        case URI4:
                        case URI5:
                            // simple property
                            // get the response content as Object for $value or Map<String, Object> otherwise
                            final List<EdmProperty> simplePropertyPath = uriInfo.getPropertyPath();
                            final EdmProperty simpleProperty = simplePropertyPath.get(simplePropertyPath.size() - 1);
                            if (uriInfo.isValue()) {
                                responseHandler.onResponse((T) EntityProvider.readPropertyValue(simpleProperty, result.getEntity().getContent()));
                            } else {
                                responseHandler.onResponse((T) EntityProvider.readProperty(getContentType(), simpleProperty, result.getEntity().getContent(), EntityProviderReadProperties.init().build()));
                            }
                            break;
                        case URI3:
                            // complex property
                            // get the response content as Map<String, Object>
                            final List<EdmProperty> complexPropertyPath = uriInfo.getPropertyPath();
                            final EdmProperty complexProperty = complexPropertyPath.get(complexPropertyPath.size() - 1);
                            responseHandler.onResponse((T) EntityProvider.readProperty(getContentType(), complexProperty, result.getEntity().getContent(), EntityProviderReadProperties.init().build()));
                            break;
                        case URI7A:
                            // $links with 0..1 cardinality property
                            // get the response content as String
                            final EdmEntitySet targetLinkEntitySet = uriInfo.getTargetEntitySet();
                            responseHandler.onResponse((T) EntityProvider.readLink(getContentType(), targetLinkEntitySet, result.getEntity().getContent()));
                            break;
                        case URI7B:
                            // $links with * cardinality property
                            // get the response content as java.util.List<String>
                            final EdmEntitySet targetLinksEntitySet = uriInfo.getTargetEntitySet();
                            responseHandler.onResponse((T) EntityProvider.readLinks(getContentType(), targetLinksEntitySet, result.getEntity().getContent()));
                            break;
                        case URI1:
                        case URI2:
                        case URI6A:
                        case URI6B:
                            // Entity
                            // get the response content as an ODataEntry object
                            responseHandler.onResponse((T) EntityProvider.readEntry(response.getContentHeader(), uriInfo.getTargetEntitySet(), result.getEntity().getContent(), EntityProviderReadProperties.init().build()));
                            break;
                        default:
                            throw new ODataApplicationException("Unsupported resource type " + uriInfo.getTargetType(), Locale.ENGLISH);
                    }
                }
            }
        });
    } catch (ODataException e) {
        responseHandler.onException(e);
    } catch (URISyntaxException e) {
        responseHandler.onException(e);
    } catch (UnsupportedEncodingException e) {
        responseHandler.onException(e);
    } catch (IOException e) {
        responseHandler.onException(e);
    }
}
Also used : ContentType(org.apache.http.entity.ContentType) HttpStatusCodes(org.apache.olingo.odata2.api.commons.HttpStatusCodes) Olingo2BatchRequest(org.apache.camel.component.olingo2.api.batch.Olingo2BatchRequest) URISyntaxException(java.net.URISyntaxException) BatchException(org.apache.olingo.odata2.api.batch.BatchException) Olingo2BatchResponse(org.apache.camel.component.olingo2.api.batch.Olingo2BatchResponse) Iterator(java.util.Iterator) Olingo2BatchChangeRequest(org.apache.camel.component.olingo2.api.batch.Olingo2BatchChangeRequest) List(java.util.List) ArrayList(java.util.ArrayList) EdmEntitySet(org.apache.olingo.odata2.api.edm.EdmEntitySet) EdmProperty(org.apache.olingo.odata2.api.edm.EdmProperty) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) BatchSingleResponse(org.apache.olingo.odata2.api.client.batch.BatchSingleResponse) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpResponse(org.apache.http.HttpResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) ODataApplicationException(org.apache.olingo.odata2.api.exception.ODataApplicationException) URISyntaxException(java.net.URISyntaxException) ODataApplicationException(org.apache.olingo.odata2.api.exception.ODataApplicationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) EntityProviderException(org.apache.olingo.odata2.api.ep.EntityProviderException) EdmException(org.apache.olingo.odata2.api.edm.EdmException) ODataException(org.apache.olingo.odata2.api.exception.ODataException) IOException(java.io.IOException) BatchException(org.apache.olingo.odata2.api.batch.BatchException) InputStreamEntity(org.apache.http.entity.InputStreamEntity) EntityProviderException(org.apache.olingo.odata2.api.ep.EntityProviderException) ODataException(org.apache.olingo.odata2.api.exception.ODataException) Header(org.apache.http.Header) ODataResponse(org.apache.olingo.odata2.api.processor.ODataResponse) Map(java.util.Map) HashMap(java.util.HashMap)

Example 3 with Olingo2BatchResponse

use of org.apache.camel.component.olingo2.api.batch.Olingo2BatchResponse in project camel by apache.

the class Olingo2AppAPITest method testBatchRequest.

@Test
public void testBatchRequest() throws Exception {
    final List<Olingo2BatchRequest> batchParts = new ArrayList<Olingo2BatchRequest>();
    // Edm query
    batchParts.add(Olingo2BatchQueryRequest.resourcePath(Olingo2AppImpl.METADATA).build());
    // feed query
    batchParts.add(Olingo2BatchQueryRequest.resourcePath(MANUFACTURERS).build());
    // read
    batchParts.add(Olingo2BatchQueryRequest.resourcePath(TEST_MANUFACTURER).build());
    // read with expand
    final HashMap<String, String> queryParams = new HashMap<String, String>();
    queryParams.put(SystemQueryOption.$expand.toString(), CARS);
    batchParts.add(Olingo2BatchQueryRequest.resourcePath(TEST_MANUFACTURER).queryParams(queryParams).build());
    // create
    final Map<String, Object> data = getEntityData();
    batchParts.add(Olingo2BatchChangeRequest.resourcePath(MANUFACTURERS).contentId(TEST_RESOURCE_CONTENT_ID).operation(Operation.CREATE).body(data).build());
    // update
    final Map<String, Object> updateData = new HashMap<String, Object>(data);
    @SuppressWarnings("unchecked") Map<String, Object> address = (Map<String, Object>) updateData.get(ADDRESS);
    updateData.put("Name", "MyCarManufacturer Renamed");
    address.put("Street", "Main Street");
    batchParts.add(Olingo2BatchChangeRequest.resourcePath(TEST_RESOURCE).operation(Operation.UPDATE).body(updateData).build());
    // delete
    batchParts.add(Olingo2BatchChangeRequest.resourcePath(TEST_RESOURCE).operation(Operation.DELETE).build());
    final TestOlingo2ResponseHandler<List<Olingo2BatchResponse>> responseHandler = new TestOlingo2ResponseHandler<List<Olingo2BatchResponse>>();
    // read to verify delete
    batchParts.add(Olingo2BatchQueryRequest.resourcePath(TEST_CREATE_MANUFACTURER).build());
    olingoApp.batch(edm, batchParts, responseHandler);
    final List<Olingo2BatchResponse> responseParts = responseHandler.await(15, TimeUnit.MINUTES);
    assertEquals("Batch responses expected", 8, responseParts.size());
    assertNotNull(responseParts.get(0).getBody());
    final ODataFeed feed = (ODataFeed) responseParts.get(1).getBody();
    assertNotNull(feed);
    LOG.info("Batch feed:  {}", prettyPrint(feed));
    ODataEntry dataEntry = (ODataEntry) responseParts.get(2).getBody();
    assertNotNull(dataEntry);
    LOG.info("Batch read entry:  {}", prettyPrint(dataEntry));
    dataEntry = (ODataEntry) responseParts.get(3).getBody();
    assertNotNull(dataEntry);
    LOG.info("Batch read entry with expand:  {}", prettyPrint(dataEntry));
    dataEntry = (ODataEntry) responseParts.get(4).getBody();
    assertNotNull(dataEntry);
    LOG.info("Batch create entry:  {}", prettyPrint(dataEntry));
    assertEquals(HttpStatusCodes.NO_CONTENT.getStatusCode(), responseParts.get(5).getStatusCode());
    assertEquals(HttpStatusCodes.NO_CONTENT.getStatusCode(), responseParts.get(6).getStatusCode());
    assertEquals(HttpStatusCodes.NOT_FOUND.getStatusCode(), responseParts.get(7).getStatusCode());
    final Exception exception = (Exception) responseParts.get(7).getBody();
    assertNotNull(exception);
    LOG.info("Batch retrieve deleted entry:  {}", exception);
}
Also used : ODataFeed(org.apache.olingo.odata2.api.ep.feed.ODataFeed) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Olingo2BatchRequest(org.apache.camel.component.olingo2.api.batch.Olingo2BatchRequest) Olingo2BatchResponse(org.apache.camel.component.olingo2.api.batch.Olingo2BatchResponse) ArrayList(java.util.ArrayList) List(java.util.List) ODataEntry(org.apache.olingo.odata2.api.ep.entry.ODataEntry) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Example 4 with Olingo2BatchResponse

use of org.apache.camel.component.olingo2.api.batch.Olingo2BatchResponse in project camel by apache.

the class Olingo2ComponentTest method testBatch.

@Test
public void testBatch() throws Exception {
    final List<Olingo2BatchRequest> batchParts = new ArrayList<Olingo2BatchRequest>();
    // 1. Edm query
    batchParts.add(Olingo2BatchQueryRequest.resourcePath(Olingo2AppImpl.METADATA).build());
    // 2. feed query
    batchParts.add(Olingo2BatchQueryRequest.resourcePath(MANUFACTURERS).build());
    // 3. read
    batchParts.add(Olingo2BatchQueryRequest.resourcePath(TEST_MANUFACTURER).build());
    // 4. read with expand
    final HashMap<String, String> queryParams = new HashMap<String, String>();
    queryParams.put(SystemQueryOption.$expand.toString(), CARS);
    batchParts.add(Olingo2BatchQueryRequest.resourcePath(TEST_MANUFACTURER).queryParams(queryParams).build());
    // 5. create
    final Map<String, Object> data = getEntityData();
    batchParts.add(Olingo2BatchChangeRequest.resourcePath(MANUFACTURERS).contentId(TEST_RESOURCE_CONTENT_ID).operation(Operation.CREATE).body(data).build());
    // 6. update address in created entry
    final Map<String, Object> updateData = new HashMap<String, Object>(data);
    Map<String, Object> address = (Map<String, Object>) updateData.get(ADDRESS);
    address.put("Street", "Main Street");
    batchParts.add(Olingo2BatchChangeRequest.resourcePath(TEST_RESOURCE_ADDRESS).operation(Operation.UPDATE).body(address).build());
    // 7. update
    updateData.put("Name", "MyCarManufacturer Renamed");
    batchParts.add(Olingo2BatchChangeRequest.resourcePath(TEST_RESOURCE).operation(Operation.UPDATE).body(updateData).build());
    // 8. delete
    batchParts.add(Olingo2BatchChangeRequest.resourcePath(TEST_RESOURCE).operation(Operation.DELETE).build());
    // 9. read to verify delete
    batchParts.add(Olingo2BatchQueryRequest.resourcePath(TEST_CREATE_MANUFACTURER).build());
    // execute batch request
    final List<Olingo2BatchResponse> responseParts = requestBody("direct://BATCH", batchParts);
    assertNotNull("Batch response", responseParts);
    assertEquals("Batch responses expected", 9, responseParts.size());
    final Edm edm = (Edm) responseParts.get(0).getBody();
    assertNotNull(edm);
    LOG.info("Edm entity sets: {}", edm.getEntitySets());
    final ODataFeed feed = (ODataFeed) responseParts.get(1).getBody();
    assertNotNull(feed);
    LOG.info("Read feed: {}", feed.getEntries());
    ODataEntry dataEntry = (ODataEntry) responseParts.get(2).getBody();
    assertNotNull(dataEntry);
    LOG.info("Read entry: {}", dataEntry.getProperties());
    dataEntry = (ODataEntry) responseParts.get(3).getBody();
    assertNotNull(dataEntry);
    LOG.info("Read entry with $expand: {}", dataEntry.getProperties());
    dataEntry = (ODataEntry) responseParts.get(4).getBody();
    assertNotNull(dataEntry);
    LOG.info("Created entry: {}", dataEntry.getProperties());
    int statusCode = responseParts.get(5).getStatusCode();
    assertEquals(HttpStatusCodes.NO_CONTENT.getStatusCode(), statusCode);
    LOG.info("Update address status: {}", statusCode);
    statusCode = responseParts.get(6).getStatusCode();
    assertEquals(HttpStatusCodes.NO_CONTENT.getStatusCode(), statusCode);
    LOG.info("Update entry status: {}", statusCode);
    statusCode = responseParts.get(7).getStatusCode();
    assertEquals(HttpStatusCodes.NO_CONTENT.getStatusCode(), statusCode);
    LOG.info("Delete status: {}", statusCode);
    assertEquals(HttpStatusCodes.NOT_FOUND.getStatusCode(), responseParts.get(8).getStatusCode());
    final Exception exception = (Exception) responseParts.get(8).getBody();
    assertNotNull(exception);
    LOG.info("Read deleted entry exception: {}", exception);
}
Also used : ODataFeed(org.apache.olingo.odata2.api.ep.feed.ODataFeed) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Olingo2BatchRequest(org.apache.camel.component.olingo2.api.batch.Olingo2BatchRequest) Edm(org.apache.olingo.odata2.api.edm.Edm) Olingo2BatchResponse(org.apache.camel.component.olingo2.api.batch.Olingo2BatchResponse) ODataEntry(org.apache.olingo.odata2.api.ep.entry.ODataEntry) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Aggregations

HashMap (java.util.HashMap)4 Map (java.util.Map)4 Olingo2BatchResponse (org.apache.camel.component.olingo2.api.batch.Olingo2BatchResponse)4 ArrayList (java.util.ArrayList)3 Olingo2BatchRequest (org.apache.camel.component.olingo2.api.batch.Olingo2BatchRequest)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 List (java.util.List)2 ContentType (org.apache.http.entity.ContentType)2 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)2 ODataEntry (org.apache.olingo.odata2.api.ep.entry.ODataEntry)2 ODataFeed (org.apache.olingo.odata2.api.ep.feed.ODataFeed)2 ODataApplicationException (org.apache.olingo.odata2.api.exception.ODataApplicationException)2 Test (org.junit.Test)2 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 URISyntaxException (java.net.URISyntaxException)1 Iterator (java.util.Iterator)1 Olingo2BatchChangeRequest (org.apache.camel.component.olingo2.api.batch.Olingo2BatchChangeRequest)1 Olingo2BatchQueryRequest (org.apache.camel.component.olingo2.api.batch.Olingo2BatchQueryRequest)1