blob: e004c3395d6593f4d1d3d5b2a0d979885c43ed53 [file] [log] [blame]
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Apache Olingo provides libraries which enable developers to implement OData producers and OData consumers. The available OData Java library implements OData version 2.0. In future on goal is to provide an OData 4.0 compliant library once the OData standard is published at OASIS. The focus within the community is currently on the Java technology but it is up to the community to discuss if other environments find interest.">
<meta name="author" content="">
<link rel="icon" href="/favicon.ico">
<title>Apache Olingo Library</title>
<!-- Bootstrap core CSS -->
<link href="/css/bootstrap.css" rel="stylesheet" type="text/css"><!-- Custom styles for this template -->
<link href="/css/navbar.css" rel="stylesheet" type="text/css"><!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<link href="/css/offcanvas.css" rel="stylesheet" type="text/css"><!-- Custom styles for this template -->
<link rel="stylesheet" href="/css/main.css">
<!--[if lt IE 9]><script src="/js/ie8-responsive-file-warning.js"></script><![endif]-->
<style>
.headerlink {
visibility: hidden;
}
dt:hover > .headerlink, p:hover > .headerlink, td:hover > .headerlink, h1:hover > .headerlink, h2:hover > .headerlink, h3:hover > .headerlink, h4:hover > .headerlink, h5:hover > .headerlink, h6:hover > .headerlink {
visibility: visible
} </style>
<script src="/js/ie-emulation-modes-warning.js" type="text/javascript">
</script><!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="/js/ie10-viewport-bug-workaround.js" type="text/javascript">
</script><!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="/js/html5shiv.min.js"></script>
<script src="/js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<!-- Static navbar -->
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<img class="navbar-brand" src="/img/OlingoOrangeTM.png" style="width:62px;" >
<a class="navbar-brand" href="/">Apache Olingo™</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">ASF <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="http://www.apache.org/foundation/">ASF Home</a></li>
<li><a href="http://projects.apache.org/">Projects</a></li>
<li><a href="http://people.apache.org/">People</a></li>
<li><a href="http://www.apache.org/foundation/getinvolved.html">Get Involved</a></li>
<li><a href="http://www.apache.org/dyn/closer.cgi">Download</a></li>
<li><a href="http://www.apache.org/security/">Security</a></li>
<li><a href="http://www.apache.org/foundation/sponsorship.html">Support Apache</a></li>
</ul>
</li>
<li><a href="http://www.apache.org/licenses/">License</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Download <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="/doc/odata2/download.html">Download OData 2.0 Java</a></li>
<li><a href="/doc/odata4/download.html">Download OData 4.0 Java</a></li>
<li><a href="/doc/javascript/download.html">Download OData 4.0 JavaScript</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Documentation <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="/doc/odata2/index.html">Documentation OData 2.0 Java</a></li>
<li><a href="/doc/odata4/index.html">Documentation OData 4.0 Java</a></li>
<li><a href="/doc/javascript/index.html">Documentation OData 4.0 JavaScript</a></li>
</ul>
</li>
<li><a href="/support.html">Support</a></li>
<li><a href="/contribute.html">Contribute</a></li>
</ul>
<a class="navbar-right" href="http://www.apache.org/foundation/" target="_blank">
<img class="navbar-right" height="50px" src="/img/asf_logo_url.svg" alt="Apache Software Foundation">
</a>
</div><!--/.nav-collapse -->
</div><!--/.container-fluid -->
</div><!-- Main component for a primary marketing message or call to action -->
<h1 id="how-to-build-an-odata-service-with-olingo-v4">How to build an OData Service with Olingo V4<a class="headerlink" href="#how-to-build-an-odata-service-with-olingo-v4" title="Permalink">&para;</a></h1>
<h1 id="part-8-batch-request-support">Part 8: Batch Request Support<a class="headerlink" href="#part-8-batch-request-support" title="Permalink">&para;</a></h1>
<h2 id="introduction">Introduction<a class="headerlink" href="#introduction" title="Permalink">&para;</a></h2>
<p>In the present tutorial, we&rsquo;ll implement batch requests.</p>
<p><strong>Note:</strong>
The final source code can be found in the project <a href="https://gitbox.apache.org/repos/asf/olingo-odata4">git repository</a>.
A detailed description how to checkout the tutorials can be found <a href="/doc/odata4/tutorials/prerequisites/prerequisites.html">here</a>.<br/>
This tutorial can be found in subdirectory /samples/tutorials/p11_batch</p>
<p><strong>Table of Contents</strong></p>
<ol>
<li>Introduction</li>
<li>Preparation</li>
<li>Implementation</li>
<li>Run the implemented service</li>
<li>Links</li>
</ol>
<h1 id="1-introduction">1. Introduction<a class="headerlink" href="#1-introduction" title="Permalink">&para;</a></h1>
<p>Batch requests <a href="http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.html#_Toc406398359">(OData Version 4.0 Part 1: Protocol Plus Errata 02)</a> allow grouping multiple operations into a single HTTP request payload. A batch request is represented as a Multipart MIME v1.0 message <a href="https://www.ietf.org/rfc/rfc2046.txt">(RFC2046)</a>.
Each part of a Multipart MINE message can have a different content type. For example you can mix OData requests with Content-Type <code>application/json</code> and Media Ressource Requests with Content Type <code>image/png</code>.</p>
<p>The content of batch requests can consist of a series of individual requests and Change Sets, each represented as a distinct MIME part. In difference to OData V2 an individual request can be a Data Request, Data Modification Request, Action invocation request or a Function invocation request. So all kinds of OData requests are allowed at top level. The order of individual requests and Change Set sets in significant. Within a Change Set you can use Data Modification requests and Action invocation requests. Due to the fact that all requests within a Change Set are unordered, GET requests must not be used within a Change Set. All operations in a change set represent a single change unit so a service must successfully process and apply all the requests in the change set or else apply none of them.</p>
<p><strong>Example</strong></p>
<p>The request below consists of an individual request (upper red box), actually a GET request(the upper blue box) to the Entity Set <code>Products</code> and a Change Set (lower red box). The Change Set contains a single POST request (lower blue box) to create a new <code>Product</code>. Please note that the <em>boundary delimiter</em> <code>abc123</code> is used in the request below. The whole content must be wrapped in a single POST request issued against the resource <code>/$batch</code>. The Content-Type of the POST request is consequently <code>Content-Type: multipart/mixed;boundary=abc123</code></p>
<p><img alt="Test" src="request.png"/></p>
<h1 id="2-preparation">2. Preparation<a class="headerlink" href="#2-preparation" title="Permalink">&para;</a></h1>
<p>You should read the previous tutorials first to have an idea how to read and write entities. In addition the following code is based on the write tutorial.</p>
<p>As a shortcut you should checkout the prepared tutorial project in the git repository in folder /samples/tutorials/p3_write.</p>
<p>The main idea of the following implementation is to reuse the existing processors.
To do so, we will implement a new processor, which takes a batch request and dispatches the single requests to the responsible processors.</p>
<p>The following steps have to be performed:</p>
<ul>
<li>Modify the data store</li>
<li>Implement the interface <code>BatchProcessor</code></li>
</ul>
<h2 id="add-transactional-behavior-to-the-data-store">Add transactional behavior to the data store<a class="headerlink" href="#add-transactional-behavior-to-the-data-store" title="Permalink">&para;</a></h2>
<p>Before we start with the actual processor implementation the data store has to be modified to provide transactional behavior. In real world service the underlying database may supports transactional handling. This tutorial is not based on a database so we have implement a simple transaction handling by ourselves.</p>
<p>Add the following methods to the class <code>myservice.mynamespace.data.Storage</code>. When a new transaction has been begun the data of the service is copied and stored in an instance variable. If <code>rollbackTransaction</code> has been called the current data is replaced with the previous copied one.</p>
<pre><code class="language-java"> private List&lt;Entity&gt; productListBeforeTransaction;
public void beginTransaction() {
if(productListBeforeTransaction == null) {
productListBeforeTransaction = cloneEntityCollection(productList);
}
}
public void commitTransaction() {
if(productListBeforeTransaction != null) {
productListBeforeTransaction = null;
}
}
public void rollbackTranscation() {
if(productListBeforeTransaction != null) {
productList = productListBeforeTransaction;
productListBeforeTransaction = null;
}
}
private List&lt;Entity&gt; cloneEntityCollection(final List&lt;Entity&gt; entities) {
final List&lt;Entity&gt; clonedEntities = new ArrayList&lt;Entity&gt;();
for(final Entity entity : entities) {
final Entity clonedEntity = new Entity();
clonedEntity.setId(entity.getId());
for(final Property property : entity.getProperties()) {
clonedEntity.addProperty(new Property(property.getType(),
property.getName(),
property.getValueType(),
property.getValue()));
}
clonedEntities.add(clonedEntity);
}
return clonedEntities;
}
</code></pre>
<h2 id="implement-the-interface-batchprocessor">Implement the interface <code>BatchProcessor</code><a class="headerlink" href="#implement-the-interface-batchprocessor" title="Permalink">&para;</a></h2>
<p>Create a new class <code>myservice.mynamespace.service.DemoBatchProcessor</code>. The class should implement the interface <code>org.apache.olingo.server.api.processor.BatchProcessor</code>.</p>
<p>Create a constructor and pass the data store to the processor.</p>
<pre><code class="language-java"> public class DemoBatchProcessor implements BatchProcessor {
private OData odata;
private Storage storage;
public DemoBatchProcessor(final Storage storage) {
this.storage = storage;
}
@Override
public void init(final OData odata, final ServiceMetadata serviceMetadata) {
this.odata = odata;
}
...
</code></pre>
<h3 id="implement-batch-handling">Implement batch handling<a class="headerlink" href="#implement-batch-handling" title="Permalink">&para;</a></h3>
<p>Batch requests will be dispatched to the method <code>processBatch</code>. First, the boundary have to be extract from the Content-Type of the POST request.</p>
<pre><code class="language-java"> @Override
public void processBatch(final BatchFacade facade, final ODataRequest request, final ODataResponse response)
throws ODataApplicationException, ODataLibraryException {
// 1. Extract the boundary
final String boundary = facade.extractBoundaryFromContentType(request.getHeader(HttpHeader.CONTENT_TYPE));
</code></pre>
<p>After that we are able to parse the multipart mixed body. The parser needs to know what the base URI and the service resolution paths are. The result of the parser is a list of BatchRequestParts. Each of these parts represents either a single request or a Change Set (Collection of one or more requests).</p>
<pre><code class="language-java"> // 2. Prepare the batch options
final BatchOptions options = BatchOptions.with().rawBaseUri(request.getRawBaseUri())
.rawServiceResolutionUri(request.getRawServiceResolutionUri())
.build();
// 3. Deserialize the batch request
final List&lt;BatchRequestPart&gt; requestParts = odata.createFixedFormatDeserializer()
.parseBatchRequest(request.getBody(), boundary, options);
</code></pre>
<p>Now the requests have to be executed by our service. If you like, you can do it by our own or simply call the method <code>handleBatchRequest</code>. This method dispatches individual requests directly to the responsible processor. If a Change Set is passed to <code>handleBatchRequest</code> the implementation dispatches the request to the method <code>processChangeSet</code> of our <code>DemoBatchProcessor</code>.</p>
<pre><code class="language-java"> // 4. Execute the batch request parts
final List&lt;ODataResponsePart&gt; responseParts = new ArrayList&lt;ODataResponsePart&gt;();
for (final BatchRequestPart part : requestParts) {
responseParts.add(facade.handleBatchRequest(part));
}
</code></pre>
<p>The last steps are to serialize the responses and setup the response of the batch request.</p>
<pre><code class="language-java"> // 5. Create a new boundary for the response
final String responseBoundary = "batch_" + UUID.randomUUID().toString();
// 6. Serialize the response content
final InputStream responseContent = odata.createFixedFormatSerializer().batchResponse(responseParts, responseBoundary);
// 7. Setup response
response.setHeader(HttpHeader.CONTENT_TYPE, ContentType.MULTIPART_MIXED + ";boundary=" + responseBoundary);
response.setContent(responseContent);
response.setStatusCode(HttpStatusCode.ACCEPTED.getStatusCode());
}
</code></pre>
<h3 id="implement-change-set-handling">Implement Change Set handling<a class="headerlink" href="#implement-change-set-handling" title="Permalink">&para;</a></h3>
<p>As mentioned above Change Sets are dispatched to the method <code>processChangeSet</code>.
In this tutorial the implementation is quite simple. First we begin a new transaction. After that we try to execute all requests of the Change Set. If one of the requests fail all changes have to be rolled back.
The comments in the source code give a detailed explanation about the steps done in this method.</p>
<pre><code class="language-java"> @Override
public ODataResponsePart processChangeSet(final BatchFacade facade, final List&lt;ODataRequest&gt; requests)
throws ODataApplicationException, ODataLibraryException {
/*
* OData Version 4.0 Part 1: Protocol Plus Errata 02
* 11.7.4 Responding to a Batch Request
*
* All operations in a change set represent a single change unit so a service MUST successfully process and
* apply all the requests in the change set or else apply none of them. It is up to the service implementation
* to define rollback semantics to undo any requests within a change set that may have been applied before
* another request in that same change set failed and thereby apply this all-or-nothing requirement.
* The service MAY execute the requests within a change set in any order and MAY return the responses to the
* individual requests in any order. The service MUST include the Content-ID header in each response with the
* same value that the client specified in the corresponding request, so clients can correlate requests
* and responses.
*
* To keep things simple, we dispatch the requests within the Change Set to the other processor interfaces.
*/
final List&lt;ODataResponse&gt; responses = new ArrayList&lt;ODataResponse&gt;();
try {
storage.beginTransaction();
for(final ODataRequest request : requests) {
// Actual request dispatching to the other processor interfaces.
final ODataResponse response = facade.handleODataRequest(request);
// Determine if an error occurred while executing the request.
// Exceptions thrown by the processors get caught and result in a proper OData response.
final int statusCode = response.getStatusCode();
if(statusCode &lt; 400) {
// The request has been executed successfully. Return the response as a part of the change set
responses.add(response);
} else {
// Something went wrong. Undo all previous requests in this Change Set
storage.rollbackTranscation();
/*
* In addition the response must be provided as follows:
*
* OData Version 4.0 Part 1: Protocol Plus Errata 02
* 11.7.4 Responding to a Batch Request
*
* When a request within a change set fails, the change set response is not represented using
* the multipart/mixed media type. Instead, a single response, using the application/http media type
* and a Content-Transfer-Encoding header with a value of binary, is returned that
* applies to all requests in the change set and MUST be formatted according to the Error Handling
* defined for the particular response format.
*
* This can be simply done by passing the response of the failed ODataRequest to a new instance of
* ODataResponsePart and setting the second parameter "isChangeSet" to false.
*/
return new ODataResponsePart(response, false);
}
}
// Everything went well, so commit the changes.
storage.commitTransaction();
return new ODataResponsePart(responses, true);
} catch(ODataApplicationException e) {
// See below
storage.rollbackTranscation();
throw e;
} catch(ODataLibraryException e) {
// The batch request is malformed or the processor implementation is not correct.
// Throwing an exception will stop the whole batch request not only the Change Set!
storage.rollbackTranscation();
throw e;
}
}
</code></pre>
<h1 id="4-run-the-implemented-service">4. Run the implemented service<a class="headerlink" href="#4-run-the-implemented-service" title="Permalink">&para;</a></h1>
<p>After building and deploying your service to your server, you can try the following requests:</p>
<p>All requests are issued againest <a href="http://localhost:8080/DemoService-Action/DemoService.svc/$batch">http://localhost:8080/DemoService-Action/DemoService.svc/$batch</a>
Set the Content-Type header to <code>Content-Type: multipart/mixed;boundary=abc123</code></p>
<p><strong>Example 1</strong><br/>
Please note that the second request in the Change Set references the first request of the Change Set.
This is done by prefixing the Content-Id of the referenced request with a $. e.g. <code>$abc</code></p>
<pre><code>--abc123
Content-Type: application/http
Content-Transfer-Encoding: binary
GET Products HTTP/1.1
Content-Type: application/json
--abc123
Content-Type: multipart/mixed;boundary=changeset_abc
--changeset_abc
Content-Type: application/http
Content-Transfer-Encoding:binary
Content-Id: 1
POST Products HTTP/1.1
Content-Type: application/json
{"Name": "Test Product", "Description": "This is a test product"}
--changeset_abc
Content-Type: application/http
Content-Transfer-Encoding:binary
Content-ID: 2
PATCH $1 HTTP/1.1
Content-Type: application/json
Accept: application/json
{"Description": "With a changed Description"}
--changeset_abc--
--abc123
Content-Type: application/http
Content-Transfer-Encoding: binary
GET Products HTTP/1.1
Content-Type: application/json
--abc123--
</code></pre>
<p>Now have a look at the response. As you can see a new product has been created and the description has been updated to 'With a changed Description'</p>
<pre><code>{
"@odata.context": "$metadata#Products",
"value": [
...
{
"ID": 4,
"Name": "Test Product",
"Description": "With a changed Description"
}
]
}
</code></pre>
<p><strong>Example 2</strong><br/>
Let us try what is happing if we send a invalid request within an Change Set. Use the same URI and Content-Type as before and use the following body:</p>
<pre><code>--abc123
Content-Type: multipart/mixed;boundary=changeset_abc
--changeset_abc
Content-Type: application/http
Content-Transfer-Encoding:binary
Content-Id: 1
POST Products HTTP/1.1
Content-Type: application/json
{"Name": "Test Product2", "Description": "This is a test product"}
--changeset_abc
Content-Type: application/http
Content-Transfer-Encoding:binary
Content-ID: 2
PATCH $1 HTTP/1.1
Content-Type: application/json
Accept: application/json
{"Description": "Invalid....
--changeset_abc--
--abc123--
</code></pre>
<p>As you can see the response contains a single request response instead of a Change Set response. The error message in stored in the response body.</p>
<h1 id="5-links">5. Links<a class="headerlink" href="#5-links" title="Permalink">&para;</a></h1>
<h3 id="tutorials">Tutorials<a class="headerlink" href="#tutorials" title="Permalink">&para;</a></h3>
<p>Further topics to be covered by follow-up tutorials:</p>
<ul>
<li>Tutorial OData V4 service part 1: <a href="/doc/odata4/tutorials/read/tutorial_read.html">Read Entity Collection</a></li>
<li>Tutorial OData V4 service part 2: <a href="/doc/odata4/tutorials/readep/tutorial_readep.html">Read Entity, Read Property</a></li>
<li>Tutorial OData V4 service part 3: <a href="/doc/odata4/tutorials/write/tutorial_write.html">Write (Create, Update, Delete Entity)</a></li>
<li>Tutorial OData V4 service, part 4: <a href="/doc/odata4/tutorials/navigation/tutorial_navigation.html">Navigation</a></li>
<li>Tutorial OData V4 service, part 5.1: <a href="/doc/odata4/tutorials/sqo_tcs/tutorial_sqo_tcs.html">System Query Options $top, $skip, $count (this page)</a></li>
<li>Tutorial OData V4 service, part 5.2: <a href="/doc/odata4/tutorials/sqo_es/tutorial_sqo_es.html">System Query Options $select, $expand</a></li>
<li>Tutorial OData V4 service, part 5.3: <a href="/doc/odata4/tutorials/sqo_o/tutorial_sqo_o.html">System Query Options $orderby</a></li>
<li>Tutorial OData V4 service, part 5.4: <a href="/doc/odata4/tutorials/sqo_f/tutorial_sqo_f.html">System Query Options $filter</a></li>
<li>Tutorial OData V4 service, part 6: <a href="/doc/odata4/tutorials/action/tutorial_action.html">Action and Function Imports</a></li>
<li>Tutorial OData V4 service, part 7: <a href="/doc/odata4/tutorials/media/tutorial_media.html">Add Media entities to the service</a></li>
<li>Tutorial OData V4 service, part 8: Batch request support</li>
<li>Tutorial OData V4 service, part 9: <a href="/doc/odata4/tutorials/deep_insert/tutorial_deep_insert.html">Handling "Deep Insert" requests</a></li>
</ul>
<h3 id="code-and-repository">Code and Repository<a class="headerlink" href="#code-and-repository" title="Permalink">&para;</a></h3>
<ul>
<li><a href="https://gitbox.apache.org/repos/asf/olingo-odata4">Git Repository</a></li>
<li><a href="/doc/odata4/tutorials/prerequisites/prerequisites.html">Guide - To fetch the tutorial sources</a></li>
<li><a href="http://www.apache.org/dyn/closer.lua/olingo/odata4/4.0.0/DemoService_Tutorial.zip">Demo Service source code as zip file (contains all tutorials)</a></li>
</ul>
<h3 id="further-reading">Further reading<a class="headerlink" href="#further-reading" title="Permalink">&para;</a></h3>
<ul>
<li><a href="http://odata.org/">Official OData Homepage</a></li>
<li><a href="http://www.odata.org/documentation/">OData documentation</a></li>
<li><a href="/javadoc/odata4/index.html">Olingo Javadoc</a></li>
</ul>
<div align="center">
<p>Copyright © 2013-2022, The Apache Software Foundation<br>
Apache Olingo, Olingo, Apache, the Apache feather, and
the Apache Olingo project logo are trademarks of the Apache Software
Foundation.</p>
<small><a href="/doc/odata2/privacy.html">Privacy</a></small>
</div>
</div><!-- /container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="/js/jquery.js" type="text/javascript">
</script>
<script src="/js/bootstrap.js" type="text/javascript">
</script>
<script src="/js/offcanvas.js" type="text/javascript">
</script>
<link rel="stylesheet" href="/css/docco.css">
<script src="//cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.0.1/build/highlight.min.js"></script>
<script>hljs.highlightAll();</script>
</body>
</html>