blob: c07bdc4f33d815cb69ccdddc5dc8a80cba549e25 [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>
<h2 id="part-2-read-scenario-continued">Part 2: Read scenario continued<a class="headerlink" href="#part-2-read-scenario-continued" title="Permalink">&para;</a></h2>
<h3 id="introduction">Introduction<a class="headerlink" href="#introduction" title="Permalink">&para;</a></h3>
<p>In the first tutorial, we&rsquo;ve learned how to build a very simple OData service.
That service exposes its metadata and allows reading a list of products.
It doesn&rsquo;t support accessing the URL for a single product.
And it also doesn&rsquo;t support reading a single property of a product.
These 2 topics will be covered in the present tutorial.</p>
<p>Note that this tutorial doesn&rsquo;t cover modifying operations like create, update and delete.
Such operations will be the focus of the Olingo V4 tutorial no. 3</p>
<p><strong>Note</strong><br/>
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 <em>\samples\tutorials\p2_readep</em></p>
<p><strong>Disclaimer</strong><br/>
Again, in the present tutorial, We will focus only on the relevant implementation, in order to keep the code small and simple.
The sample code shouldn't be reused for advanced scenarios.</p>
<p><strong>Table of Contents</strong></p>
<ol>
<li>Prerequisites</li>
<li>Preparation
<ol>
<li>Create data class</li>
<li>Adapt the servlet class</li>
<li>Modify the DemoEntityCollectionProcessor</li>
<li>Create utility class</li>
</ol>
</li>
<li>Implementation of Read Single Entity
<ol>
<li>Implement the EntityProcessor interface</li>
<li>Adapt the DemoServlet class</li>
<li>Run the service</li>
</ol>
</li>
<li>Implementation of Read Single Property
<ol>
<li>Implement the PrimitiveProcessor interface</li>
<li>Adapt the DemoServlet class</li>
<li>Run the service</li>
</ol>
</li>
<li>Summary</li>
<li>Links</li>
<li>Appendix: PrimitiveValueProcessor</li>
</ol>
<h1 id="1-prerequisites">1. Prerequisites<a class="headerlink" href="#1-prerequisites" title="Permalink">&para;</a></h1>
<p>Follow <a href="/doc/odata4/tutorials/read/tutorial_read.html">Tutorial Part 1: Read Entity Collection</a>, which also covers setting up the environment and running the service.</p>
<h1 id="2-preparation">2. Preparation<a class="headerlink" href="#2-preparation" title="Permalink">&para;</a></h1>
<p>Follow the <a href="/doc/odata4/tutorials/read/tutorial_read.html">Tutorial Part 1: Read Entity Collection</a> or import the the tutorial form subdirectory <a href="/doc/odata4/tutorials/prerequisites/prerequisites.html"><em>\samples\tutorials\p1_read</em></a> into your Eclipse workspace.<br/>
Afterwards do a <em>Deploy and run</em>: it should be working.<br/>
Before we start with the actual tutorial, we need to adapt the existing code to meet the requirements of the present tutorial.</p>
<h2 id="21-create-a-new-data-class">2.1. Create a new data-class<a class="headerlink" href="#21-create-a-new-data-class" title="Permalink">&para;</a></h2>
<p>In the first tutorial, we had created a single method called <code>getData()</code> to provide sample data for the list of products.
Handling the sample data will get a bit more advanced from now on, so we move the code into a separate class.</p>
<p>Create a new package <em>myservice.mynamespace.data</em><br/>
Within this package, create a new class <em>Storage.java</em> to simulate the data layer (in a real scenario, this would be e.g. a database or any other data storage)</p>
<p>Here&rsquo;s the full implementation of this class:</p>
<pre><code class="language-java"> package myservice.mynamespace.data;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import myservice.mynamespace.service.DemoEdmProvider;
import myservice.mynamespace.util.Util;
import org.apache.olingo.commons.api.data.Entity;
import org.apache.olingo.commons.api.data.EntityCollection;
import org.apache.olingo.commons.api.data.Property;
import org.apache.olingo.commons.api.data.ValueType;
import org.apache.olingo.commons.api.edm.EdmEntitySet;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
public class Storage {
private List&lt;Entity&gt; productList;
public Storage() {
productList = new ArrayList&lt;Entity&gt;();
initSampleData();
}
/* PUBLIC FACADE */
public EntityCollection readEntitySetData(EdmEntitySet edmEntitySet)throws ODataApplicationException{
// actually, this is only required if we have more than one Entity Sets
if(edmEntitySet.getName().equals(DemoEdmProvider.ES_PRODUCTS_NAME)){
return getProducts();
}
return null;
}
public Entity readEntityData(EdmEntitySet edmEntitySet, List&lt;UriParameter&gt; keyParams) throws ODataApplicationException{
EdmEntityType edmEntityType = edmEntitySet.getEntityType();
// actually, this is only required if we have more than one Entity Type
if(edmEntityType.getName().equals(DemoEdmProvider.ET_PRODUCT_NAME)){
return getProduct(edmEntityType, keyParams);
}
return null;
}
/* INTERNAL */
private EntityCollection getProducts(){
EntityCollection retEntitySet = new EntityCollection();
for(Entity productEntity : this.productList){
retEntitySet.getEntities().add(productEntity);
}
return retEntitySet;
}
private Entity getProduct(EdmEntityType edmEntityType, List&lt;UriParameter&gt; keyParams) throws ODataApplicationException{
// the list of entities at runtime
EntityCollection entitySet = getProducts();
/* generic approach to find the requested entity */
Entity requestedEntity = Util.findEntity(edmEntityType, entitySet, keyParams);
if(requestedEntity == null){
// this variable is null if our data doesn't contain an entity for the requested key
// Throw suitable exception
throw new ODataApplicationException("Entity for requested key doesn't exist",
HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
}
return requestedEntity;
}
/* HELPER */
private void initSampleData(){
// add some sample product entities
final Entity e1 = new Entity()
.addProperty(new Property(null, "ID", ValueType.PRIMITIVE, 1))
.addProperty(new Property(null, "Name", ValueType.PRIMITIVE, "Notebook Basic 15"))
.addProperty(new Property(null, "Description", ValueType.PRIMITIVE,
"Notebook Basic, 1.7GHz - 15 XGA - 1024MB DDR2 SDRAM - 40GB"));
e1.setId(createId("Products", 1));
productList.add(e1);
final Entity e2 = new Entity()
.addProperty(new Property(null, "ID", ValueType.PRIMITIVE, 2))
.addProperty(new Property(null, "Name", ValueType.PRIMITIVE, "1UMTS PDA"))
.addProperty(new Property(null, "Description", ValueType.PRIMITIVE,
"Ultrafast 3G UMTS/HSDPA Pocket PC, supports GSM network"));
e2.setId(createId("Products", 1));
productList.add(e2);
final Entity e3 = new Entity()
.addProperty(new Property(null, "ID", ValueType.PRIMITIVE, 3))
.addProperty(new Property(null, "Name", ValueType.PRIMITIVE, "Ergo Screen"))
.addProperty(new Property(null, "Description", ValueType.PRIMITIVE,
"19 Optimum Resolution 1024 x 768 @ 85Hz, resolution 1280 x 960"));
e3.setId(createId("Products", 1));
productList.add(e3);
}
private URI createId(String entitySetName, Object id) {
try {
return new URI(entitySetName + "(" + String.valueOf(id) + ")");
} catch (URISyntaxException e) {
throw new ODataRuntimeException("Unable to create id for entity: " + entitySetName, e);
}
}
}
</code></pre>
<p>The <em>Public Fa&ccedil;ade</em> contains the methods that are called from outside.<br/>
They are data-layer-agnostic; their parameters are objects from the OData world.<br/>
The implementation of these methods simply delegates the logic to the internal methods.</p>
<p>The <em>internal</em> methods do know about the names of tables or columns and these methods know how to e.g. find a single product.</p>
<h2 id="22-adapt-the-servlet-class">2.2. Adapt the servlet class<a class="headerlink" href="#22-adapt-the-servlet-class" title="Permalink">&para;</a></h2>
<p>The <code>Data-Storage</code> class will be instantiated in the <code>DemoServlet</code> class and attached to the HTTP-session.<br/>
This has the advantage that our final OData service can be tested and the sample data can be changed and the changes will remain active until the session is closed.</p>
<p>Open the class <code>myservice.mynamespace.web.DemoServlet</code></p>
<p>Change the code such that it looks as follows:</p>
<pre><code class="language-java"> protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
HttpSession session = req.getSession(true);
Storage storage = (Storage) session.getAttribute(Storage.class.getName());
if (storage == null) {
storage = new Storage();
session.setAttribute(Storage.class.getName(), storage);
}
// create odata handler and configure it with EdmProvider and Processor
OData odata = OData.newInstance();
ServiceMetadata edm = odata.createServiceMetadata(new DemoEdmProvider(), new ArrayList&lt;EdmxReference&gt;());
ODataHttpHandler handler = odata.createHandler(edm);
handler.register(new DemoEntityCollectionProcessor(storage));
} /* more code */
}
</code></pre>
<p>Note that we pass the instance of the <code>Storage</code> object to the constructor of our existing <code>DemoEntityCollectionProcessor</code>.</p>
<p>So the next step is to adapt the <code>DemoEntityCollectionProcessor</code> class.</p>
<h2 id="23-modify-the-demoentitycollectionprocessor">2.3. Modify the DemoEntityCollectionProcessor<a class="headerlink" href="#23-modify-the-demoentitycollectionprocessor" title="Permalink">&para;</a></h2>
<p>In the <code>DemoEntityCollectionProcessor</code> class that we created in the first tutorial, we have to make 3 changes:</p>
<h3 id="231-create-constructor">2.3.1 Create Constructor<a class="headerlink" href="#231-create-constructor" title="Permalink">&para;</a></h3>
<p>We have to create a Constructor that takes the <code>Storage</code> instance and stores it as a member variable:</p>
<pre><code class="language-java"> public class DemoEntityCollectionProcessor implements EntityCollectionProcessor {
private OData odata;
private ServiceMetadata serviceMetadata;
private Storage storage;
public DemoEntityCollectionProcessor(Storage storage) {
this.storage = storage;
}
}
</code></pre>
<h3 id="232-delete-the-getdata-method">2.3.2. Delete the getData() method<a class="headerlink" href="#232-delete-the-getdata-method" title="Permalink">&para;</a></h3>
<p>The code that we had written in this method has been moved to the <code>init()</code> method of the Storage class.
So we can delete this <code>getData()</code> method.</p>
<h3 id="233-adapt-the-usage-of-the-getdata-method">2.3.3. Adapt the usage of the getData() method<a class="headerlink" href="#233-adapt-the-usage-of-the-getdata-method" title="Permalink">&para;</a></h3>
<p>After deleting the <code>getData()</code> method, we get a compile error in the line where this method is used.
We replace this method invocation with a call to our <code>Storage</code> object:</p>
<pre><code class="language-java"> EntitySet entitySet = storage.readEntitySetData(edmEntitySet);
</code></pre>
<p>The new code looks as follows:</p>
<pre><code class="language-java"> public void readEntityCollection(ODataRequest request, ODataResponse response,
UriInfo uriInfo, ContentType responseFormat)
throws ODataApplicationException, SerializerException {
// 1st retrieve the requested EntitySet from the uriInfo (representation of the parsed URI)
List&lt;UriResource&gt; resourcePaths = uriInfo.getUriResourceParts();
// in our example, the first segment is the EntitySet
UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0);
EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();
// 2nd: fetch the data from backend for this requested EntitySetName and deliver as EntitySet
EntityCollection entityCollection = storage.readEntitySetData(edmEntitySet);
}
</code></pre>
<h2 id="24-create-utility-class">2.4. Create utility class<a class="headerlink" href="#24-create-utility-class" title="Permalink">&para;</a></h2>
<p>Furthermore, we create one more class, to host a few helper methods.<br/>
Create package <code>myservice.mynamespace.util</code>
Within this package, create a class <code>Util.java</code></p>
<p>Copy the following code into this class:</p>
<pre><code class="language-java"> package myservice.mynamespace.util;
import java.util.List;
import java.util.Locale;
import org.apache.olingo.commons.api.data.Entity;
import org.apache.olingo.commons.api.data.EntityCollection;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriParameter;
public class Util {
public static EdmEntitySet getEdmEntitySet(UriInfoResource uriInfo) throws ODataApplicationException {
List&lt;UriResource&gt; resourcePaths = uriInfo.getUriResourceParts();
// To get the entity set we have to interpret all URI segments
if (!(resourcePaths.get(0) instanceof UriResourceEntitySet)) {
throw new ODataApplicationException("Invalid resource type for first segment.",
HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(),Locale.ENGLISH);
}
UriResourceEntitySet uriResource = (UriResourceEntitySet) resourcePaths.get(0);
return uriResource.getEntitySet();
}
public static Entity findEntity(EdmEntityType edmEntityType,
EntityCollection rt_entitySet, List&lt;UriParameter&gt; keyParams)
throws ODataApplicationException {
List&lt;Entity&gt; entityList = rt_entitySet.getEntities();
// loop over all entities in order to find that one that matches all keys in request
// an example could be e.g. contacts(ContactID=1, CompanyID=1)
for(Entity rt_entity : entityList){
boolean foundEntity = entityMatchesAllKeys(edmEntityType, rt_entity, keyParams);
if(foundEntity){
return rt_entity;
}
}
return null;
}
public static boolean entityMatchesAllKeys(EdmEntityType edmEntityType, Entity rt_entity, List&lt;UriParameter&gt; keyParams)
throws ODataApplicationException {
// loop over all keys
for (final UriParameter key : keyParams) {
// key
String keyName = key.getName();
String keyText = key.getText();
// Edm: we need this info for the comparison below
EdmProperty edmKeyProperty = (EdmProperty )edmEntityType.getProperty(keyName);
Boolean isNullable = edmKeyProperty.isNullable();
Integer maxLength = edmKeyProperty.getMaxLength();
Integer precision = edmKeyProperty.getPrecision();
Boolean isUnicode = edmKeyProperty.isUnicode();
Integer scale = edmKeyProperty.getScale();
// get the EdmType in order to compare
EdmType edmType = edmKeyProperty.getType();
// Key properties must be instance of primitive type
EdmPrimitiveType edmPrimitiveType = (EdmPrimitiveType)edmType;
// Runtime data: the value of the current entity
Object valueObject = rt_entity.getProperty(keyName).getValue(); // null-check is done in FWK
// now need to compare the valueObject with the keyText String
// this is done using the type.valueToString //
String valueAsString = null;
try {
valueAsString = edmPrimitiveType.valueToString(valueObject, isNullable, maxLength,
precision, scale, isUnicode);
} catch (EdmPrimitiveTypeException e) {
throw new ODataApplicationException("Failed to retrieve String value",
HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode(),Locale.ENGLISH, e);
}
if (valueAsString == null){
return false;
}
boolean matches = valueAsString.equals(keyText);
if(!matches){
// if any of the key properties is not found in the entity, we don't need to search further
return false;
}
}
return true;
}
}
</code></pre>
<p>These helper methods are going to be used within the implementation of the Processor implementations.</p>
<hr/>
<h1 id="3-implementation-of-read-single-entity">3. Implementation of Read Single Entity<a class="headerlink" href="#3-implementation-of-read-single-entity" title="Permalink">&para;</a></h1>
<p>The user of our sample OData service is enabled to invoke the list of products via the following URL:</p>
<pre><code>http://localhost:8080/DemoService/DemoService.svc/Products
</code></pre>
<p>In a next step, he wants to read the details of a single product entity.
This is done via the following URL:</p>
<pre><code>http://localhost:8080/DemoService/DemoService.svc/Products(3)
</code></pre>
<p>From the above URL we can see that the user requests the product which has an ID with value 3<br/>
Whenever such a URL is requested, the Olingo library will delegate the request to an implementation of the Interface <code>EntityProcessor</code>.</p>
<p>This means, we have to create a new Java class that implements the mentioned interface and we have to register it in the <code>DemoServlet</code> class (remember that all Processor-implementations have to be registered there).</p>
<h2 id="31-implement-the-entityprocessor-interface">3.1. Implement the EntityProcessor interface<a class="headerlink" href="#31-implement-the-entityprocessor-interface" title="Permalink">&para;</a></h2>
<p>The interface <code>org.apache.olingo.server.api.processor.EntityProcessor</code> has 5 methods to implement:</p>
<ul>
<li>
<p><em>init(...)</em><br/>
Here we are initialized by the Framework to pass the context objects to us</p>
</li>
<li>
<p><em>readEntity(&hellip;)</em><br/>
This method is relevant for reading a single entity</p>
</li>
<li>
<p><em>createEntity(&hellip;)</em><br/>
We will ignore this method in the present tutorial</p>
</li>
<li>
<p><em>updateEntity(&hellip;)</em><br/>
We will ignore this method in the present tutorial</p>
</li>
<li>
<p><em>deleteEntity(&hellip;)</em><br/>
We will ignore this method in the present tutorial</p>
</li>
</ul>
<p>Let&rsquo;s have a look at the implementation.</p>
<p>Create the class <code>DemoEntityProcessor</code> in package <code>myservice.mynamespace.service</code> which implements the interface <code>EntityProcessor</code>.<br/>
First we need to implement the <code>init()</code> method, in order to store the <code>OData</code> object.
Second, as described in the preparation-section, we need to create a constructor that takes and stores our <code>Storage</code> instance</p>
<pre><code class="language-java"> public class DemoEntityProcessor implements EntityProcessor {
private OData odata;
private ServiceMetadata serviceMetadata;
private Storage storage;
public DemoEntityProcessor(Storage storage) {
this.storage = storage;
}
public void init(OData odata, ServiceMetadata serviceMetadata) {
this.odata = odata;
this.serviceMetadata = serviceMetadata;
}
}
</code></pre>
<p><strong>readEntity(...)</strong></p>
<p>When going through the implementation, let&rsquo;s keep in mind that the user invokes e.g. the following URL</p>
<pre><code>http://localhost:8080/DemoService/DemoService.svc/Products(3)
</code></pre>
<p>and he receives the following response in the browser:</p>
<pre><code class="language-json"> {
@odata.context: "$metadata#Products",
ID: 3,
Name: "Ergo Screen",
Description: "19 Optimum Resolution 1024 x 768 @ 85Hz, resolution 1280 x 960"
}
</code></pre>
<p><strong>Steps</strong><br/>
The steps to be followed in the implementation of the <code>readEntity(...)</code> method are the same that we followed in the previous tutorial, when we implemented the <code>readEntityCollection(...)</code> method:</p>
<ol>
<li>
<p><strong>Which data is requested?</strong><br/>
Check the UriInfo instance for information about which <em>EntityCollection</em> has been requested.<br/>
Note that in the code, we directly access the first segment of the URI and cast it to <code>UriResourceEntitySet</code></p>
<pre><code class="language-java"> UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0);
</code></pre>
<p>This is only possible, because in our current sample scenario we only support simple URIs. In a real production environment OData service, which supports navigation and other OData V4 features, the code would be more complex.</p>
</li>
<li>
<p><strong>Fetch the data from backend</strong><br/>
In the backend, which in our sample is represented by the <code>Storage</code> class, we have a list with products.
From this list we have to pick that one that is requested by the user.
The information, which one is requested, is contained in the so-called <em>KeyPredicates</em>.
In our OData model, we have only one property that is marked as &ldquo;key&rdquo;, it is the property with name <em>ID</em>
In other models, the key could also be composed by multiple properties. In such a case, all key-properties are mentioned in the URI.
That&rsquo;s why the <em>KeyPredicate</em> information is provided as a list:</p>
<pre><code class="language-java"> List&lt;UriParameter&gt; keyPredicates = uriResourceEntitySet.getKeyPredicates();
</code></pre>
<p>Now our task is to loop over all product entities that we have in our backend and to find that one that matches all keys. Which means that we have to loop over all key params.
In our sample code, we have moved this logic to the <em>Util</em> class that has a <em>findEntity()</em> method, which loops over all existing product entities, and a <em>entityMatchesAllKeys()</em> method that checks if the given entity is the right one.</p>
</li>
<li>
<p><strong>Transform the data</strong><br/>
After fetching the Entity object from the backend, we have to convert it to an <code>InputStream</code>, using the proper <code>ODataSerializer</code> method:</p>
<pre><code class="language-java"> ODataSerializer serializer = odata.createSerializer(responseFormat);
SerializerResult serializerResult = serializer.entity(serviceMetadata, entityType, entity, options);
InputStream entityStream = serializerResult.getContent();
</code></pre>
<p><strong>Note:</strong>
The <code>ODataSerializer</code> object has to be configured with a <code>ContextURL</code> (in case that it is requested) and with <code>EntitySerializerOptions</code>. In our sample we keep the code simple, since we know that we don&rsquo;t support advanced operations.</p>
</li>
<li>
<p><strong>Configure the response</strong><br/>
As usual, we have to set the body, the content type and the HTTP status code, as required by the specification.</p>
</li>
</ol>
<p>The following snippet shows the implementation of the <code>readEntity(...)</code> method.</p>
<pre><code class="language-java"> public void readEntity(ODataRequest request, ODataResponse response,
UriInfo uriInfo, ContentType responseFormat)
throws ODataApplicationException, SerializerException {
// 1. retrieve the Entity Type
List&lt;UriResource&gt; resourcePaths = uriInfo.getUriResourceParts();
// Note: only in our example we can assume that the first segment is the EntitySet
UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) resourcePaths.get(0);
EdmEntitySet edmEntitySet = uriResourceEntitySet.getEntitySet();
// 2. retrieve the data from backend
List&lt;UriParameter&gt; keyPredicates = uriResourceEntitySet.getKeyPredicates();
Entity entity = storage.readEntityData(edmEntitySet, keyPredicates);
// 3. serialize
EdmEntityType entityType = edmEntitySet.getEntityType();
ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).build();
// expand and select currently not supported
EntitySerializerOptions options = EntitySerializerOptions.with().contextURL(contextUrl).build();
ODataSerializer serializer = odata.createSerializer(responseFormat);
SerializerResult serializerResult = serializer.entity(serviceMetadata, entityType, entity, options);
InputStream entityStream = serializerResult.getContent();
//4. configure the response object
response.setContent(entityStream);
response.setStatusCode(HttpStatusCode.OK.getStatusCode());
response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
</code></pre>
<h2 id="32-adapt-the-demoservlet-class">3.2. Adapt the DemoServlet class<a class="headerlink" href="#32-adapt-the-demoservlet-class" title="Permalink">&para;</a></h2>
<p>As we&rsquo;ve learned in our first tutorial, the Processor implementations have to be registered on the <code>ODataHttpHandler</code> instance in the servlet class.
Open the <code>DemoServlet</code> class and add the line that registers the <code>DemoEntityProcessor</code> instance:</p>
<pre><code class="language-java"> // create odata handler and configure it with EdmProvider and Processor
OData odata = OData.newInstance();
ServiceMetadata edm = odata.createServiceMetadata(new DemoEdmProvider(),
new ArrayList&lt;EdmxReference&gt;());
ODataHttpHandler handler = odata.createHandler(edm);
handler.register(new DemoEntityCollectionProcessor(storage));
handler.register(new DemoEntityProcessor(storage));
</code></pre>
<h2 id="33-run-the-service">3.3. Run the service<a class="headerlink" href="#33-run-the-service" title="Permalink">&para;</a></h2>
<p>We have provided the implementation for the <code>readEntity(...)</code>, we have registered the processor and in the preparation section, we&rsquo;ve created the <code>Storage</code> class and the <code>Util</code> class.
After building and deploying the project, we can invoke e.g. the following URL:</p>
<pre><code>http://localhost:8080/DemoService/DemoService.svc/Products(3)
</code></pre>
<p>and get the expected result:</p>
<pre><code class="language-json"> {
@odata.context: "$metadata#Products",
ID: 3,
Name: "Ergo Screen",
Description: "19 Optimum Resolution 1024 x 768 @ 85Hz, resolution 1280 x 960"
}
</code></pre>
<hr/>
<h1 id="4-implementation-of-read-single-property">4. Implementation of Read Single Property<a class="headerlink" href="#4-implementation-of-read-single-property" title="Permalink">&para;</a></h1>
<p>In the following section, We will add the capabilities to our service that allows the user to invoke e.g. the following URL:</p>
<pre><code>http://localhost:8080/DemoService/DemoService.svc/Products(1)/Description
</code></pre>
<p>Remember:
As described in our first tutorial, &ldquo;Description&rdquo; is the name of a property in our OData model.</p>
<p><img alt="datamodel" src="model1.png" title="The OData model"/></p>
<p>When a user invokes this URL, he doesn&rsquo;t want to receive the full payload of the entity (since usually there are more properties than in our example), but instead, only the value of the property he is interested in.</p>
<p>Example result:</p>
<pre><code class="language-json"> {
@odata.context: "$metadata#Products/Description",
value: "Notebook Basic, 1.7GHz - 15 XGA - 1024MB DDR2 SDRAM - 40GB"
}
</code></pre>
<p><strong>Advantages:</strong><br/>
Allows more performant implementation in the backend, (e.g. SQL statement).<br/>
Sends less data through the network to the client (e.g. mobile phone).</p>
<p><strong>Note:</strong><br/>
Don&rsquo;t mix the above mentioned call with this one:</p>
<pre><code>http://localhost:8080/DemoService/DemoService.svc/Products(1)/Description/$value
</code></pre>
<p>Here, the response body contains only the pure value of the property, in plain text.
This can be realized by implementing the interface <code>PropertyValueProcessor</code> (see Appendix)</p>
<h2 id="41-implement-the-primitiveprocessor-interface">4.1. Implement the PrimitiveProcessor interface<a class="headerlink" href="#41-implement-the-primitiveprocessor-interface" title="Permalink">&para;</a></h2>
<p>The interface <code>org.apache.olingo.server.api.processor.PrimitiveProcessor</code> has 4 methods to implement:</p>
<ul>
<li>
<p><code>init()</code><br/>
Here we are initialized by the Framework to pass the context objects to us</p>
</li>
<li>
<p><code>readPrimitive</code><br/>
This one is relevant for reading a single property of a single entity</p>
</li>
<li>
<p><code>updatePrimitive</code><br/>
We will ignore this method in the present tutorial</p>
</li>
<li>
<p><code>deletePrimitive</code><br/>
We will ignore this method in the present tutorial</p>
</li>
</ul>
<p>Create the class <code>DemoPrimitiveProcessor</code> in package <code>myservice.mynamespace.service</code> which implements the interface <code>PrimitiveProcessor</code></p>
<p>We have to create a Constructor that takes the <code>Storage</code> instance and stores it as a member variable:</p>
<pre><code class="language-java"> public class DemoPrimitiveProcessor implements PrimitiveProcessor {
private OData odata;
private Storage storage;
private ServiceMetadata serviceMetadata;
public DemoPrimitiveProcessor(Storage storage) {
this.storage = storage;
}
public void init(OData odata, ServiceMetadata serviceMetadata) {
this.odata = odata;
this.serviceMetadata = serviceMetadata;
}
</code></pre>
<p><strong>readPrimitive</strong></p>
<p>Again, we have the following 4 steps to follow:</p>
<ol>
<li>
<p>Which data is requested?<br/>
From the <code>UriInfo</code> object, we not only have to retrieve the information about the <code>EntitySet</code> that is requested, but as well the desired property.</p>
</li>
<li>
<p>Fetch the data from backend<br/>
Based on this information, we can retrieve the backend-data for the entity, just like we did in the <code>readEntity()</code> method, described above.
The property value can then be extracted from it.</p>
</li>
<li>
<p>Transform the data<br/>
The third step is to serialize the backend data into an <code>InputStream</code> object.<br/>
For the current use case, the <code>ODataSerializer</code> instance offers a method called <code>primitive(...)</code></p>
</li>
<li>
<p>Configure the response<br/>
When reading a property, we have to consider that the value of the property can be empty.<br/>
If this is the case, when configuring the response object, we don&rsquo;t provide response body and header.</p>
<pre><code class="language-java"> public void readPrimitive(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat)
throws ODataApplicationException, SerializerException {
// 1. Retrieve info from URI
// 1.1. retrieve the info about the requested entity set
List&lt;UriResource&gt; resourceParts = uriInfo.getUriResourceParts();
// Note: only in our example we can rely that the first segment is the EntitySet
UriResourceEntitySet uriEntityset = (UriResourceEntitySet) resourceParts.get(0);
EdmEntitySet edmEntitySet = uriEntityset.getEntitySet();
// the key for the entity
List&lt;UriParameter&gt; keyPredicates = uriEntityset.getKeyPredicates();
// 1.2. retrieve the requested (Edm) property
// the last segment is the Property
UriResourceProperty uriProperty = (UriResourceProperty) resourceParts.get(resourceParts.size() -1);
EdmProperty edmProperty = uriProperty.getProperty();
String edmPropertyName = edmProperty.getName();
// in our example, we know we have only primitive types in our model
EdmPrimitiveType edmPropertyType = (EdmPrimitiveType) edmProperty.getType();
// 2. retrieve data from backend
// 2.1. retrieve the entity data, for which the property has to be read
Entity entity = storage.readEntityData(edmEntitySet, keyPredicates);
if (entity == null) { // Bad request
throw new ODataApplicationException("Entity not found",
HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
}
// 2.2. retrieve the property data from the entity
Property property = entity.getProperty(edmPropertyName);
if (property == null) {
throw new ODataApplicationException("Property not found",
HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ENGLISH);
}
// 3. serialize
Object value = property.getValue();
if (value != null) {
// 3.1. configure the serializer
ODataSerializer serializer = odata.createSerializer(responseFormat);
ContextURL contextUrl = ContextURL.with().entitySet(edmEntitySet).navOrPropertyPath(edmPropertyName).build();
PrimitiveSerializerOptions options = PrimitiveSerializerOptions.with().contextURL(contextUrl).build();
// 3.2. serialize
SerializerResult serializerResult = serializer.primitive(serviceMetadata, edmPropertyType, property, options);
InputStream propertyStream = serializerResult.getContent();
//4. configure the response object
response.setContent(propertyStream);
response.setStatusCode(HttpStatusCode.OK.getStatusCode());
response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}else{
// in case there's no value for the property, we can skip the serialization
response.setStatusCode(HttpStatusCode.NO_CONTENT.getStatusCode());
}
}
</code></pre>
</li>
</ol>
<h2 id="42-adapt-the-demoservlet-class">4.2. Adapt the DemoServlet class<a class="headerlink" href="#42-adapt-the-demoservlet-class" title="Permalink">&para;</a></h2>
<p>The DemoServlet has to register a third processor:</p>
<pre><code class="language-java"> // create odata handler and configure it with EdmProvider and Processor
OData odata = OData.newInstance();
ServiceMetadata edm = odata.createServiceMetadata(new DemoEdmProvider(),
new ArrayList&lt;EdmxReference&gt;());
ODataHttpHandler handler = odata.createHandler(edm);
handler.register(new DemoEntityCollectionProcessor(storage));
handler.register(new DemoEntityProcessor(storage));
handler.register(new DemoPrimitiveProcessor(storage));
</code></pre>
<h2 id="43-run-the-service">4.3. Run the service<a class="headerlink" href="#43-run-the-service" title="Permalink">&para;</a></h2>
<p>We have provided the implementation for the <code>readPrimitive</code>, we have registered the processor and in the preparation section, we&rsquo;ve created the <code>Storage</code> class and the <code>Util</code> class.
After building and deploying the project, we can invoke e.g. the following URL</p>
<pre><code>http://localhost:8080/DemoService/DemoService.svc/Products(ID=3)/Description
</code></pre>
<p>and get the expected result:</p>
<pre><code class="language-json"> {
@odata.context: "$metadata#Products/Description",
value: "19 Optimum Resolution 1024 x 768 @ 85Hz, resolution 1280 x 960"
}
</code></pre>
<p>Of course, all other properties can be accessed in the same way:</p>
<pre><code>http://localhost:8080/DemoService/DemoService.svc/Products(ID=3)/Name
http://localhost:8080/DemoService/DemoService.svc/Products(ID=3)/ID
</code></pre>
<hr/>
<h1 id="5-summary">5. Summary<a class="headerlink" href="#5-summary" title="Permalink">&para;</a></h1>
<p>In this tutorial we have learned how to implement the read operation for single entity and single property.
It has been based on a simple OData model, focusing on simple sample code and sample data.</p>
<p>In the next tutorial (<a href="/doc/odata4/tutorials/write/tutorial_write.html">Part 3: Write</a>) we will learn how to implement write operations, i.e. create, update and delete of an entity.</p>
<hr/>
<h1 id="6-links">6. Links<a class="headerlink" href="#6-links" title="Permalink">&para;</a></h1>
<h3 id="tutorials">Tutorials<a class="headerlink" href="#tutorials" title="Permalink">&para;</a></h3>
<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: Read Entity, Read Property</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">Media Entities</a></li>
<li>Tutorial OData V4 service, part 8: <a href="/doc/odata4/tutorials/batch/tutorial_batch.html">Batch Request support</a></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>