blob: 4be33af3d4fcee642757563a270e29b10bc8a9da [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-4-navigation">Part 4: Navigation<a class="headerlink" href="#part-4-navigation" 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 will learn how to implement navigation between 2 Entity Types in an OData V4 service.</p>
<p><strong>Note</strong></p>
<p>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\p4_navigation</em></p>
<p><strong>Disclaimer</strong></p>
<p>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&rsquo;t be reused for advanced scenarios.</p>
<p><strong>Background</strong></p>
<p>Say, we have an electronics shop and we have a lot of products which we&rsquo;re selling and these products can be notebooks or monitors or organizers, which are the categories.
We would have 3 requirements:</p>
<ol>
<li>We want to show a list of all our categories, then select one and display a list of all products that belong to this category, e.g. all monitors
In terms of OData, this is called navigation</li>
<li>From the list of our products, we want to choose one and display its category</li>
<li>We want to navigate from a category to its products and perform a READ operation on one of them.</li>
</ol>
<p><strong>Example for navigating in a service</strong></p>
<p>We open the Categories collection: <a href="http://localhost:8080/DemoService/DemoService.svc/Categories">http://localhost:8080/DemoService/DemoService.svc/Categories</a></p>
<p><img alt="CategoryCollection" src="browser_categories.JPG" title="The Category collection"/></p>
<p>We open the details of the first Category, the &ldquo;Notebooks&rdquo;-category:
<a href="http://localhost:8080/DemoService/DemoService.svc/Categories(1)">http://localhost:8080/DemoService/DemoService.svc/Categories(1)</a></p>
<p><img alt="CategoryEntity" src="browser_categories1.jpg" title="Read single Category entity"/></p>
<p>In order to display all products that are notebooks, we can navigate from the selected category to its products:
<a href="http://localhost:8080/DemoService/DemoService.svc/Categories(1)/Products">http://localhost:8080/DemoService/DemoService.svc/Categories(1)/Products</a></p>
<p><img alt="ProductsOfCategory" src="browser_categories1_products.jpg" title="After navigating from a Category to the related Products"/></p>
<p>In the above example we&rsquo;ve executed a one-to-many navigation.</p>
<p>As mentioned in the Background section, it is also required to navigate from a selected product to its category, which is a to-one relation, like:
<a href="http://localhost:8080/DemoService/DemoService.svc/Products(1)/Category">http://localhost:8080/DemoService/DemoService.svc/Products(1)/Category</a></p>
<p>And finally, it is possible to navigate to a list of products and directly access one of them, e.g.
<a href="http://localhost:8080/DemoService/DemoService.svc/Categories(1)/Products(1)">http://localhost:8080/DemoService/DemoService.svc/Categories(1)/Products(1)</a></p>
<p>All three cases are covered by the present tutorial.</p>
<p><strong>Table of Contents</strong></p>
<ol>
<li>Prerequisites</li>
<li>Preparation</li>
<li>Implementating the navigation
<ol>
<li>Declare the Metadata</li>
<li>Implement the to-many navigation</li>
<li>Implement the to-one navigation</li>
<li>Implement the to-many navigation with key access</li>
</ol>
</li>
<li>Run the implemented service</li>
<li>Summary</li>
<li>Links</li>
<li>Appendix: code snippets</li>
</ol>
<hr/>
<h1 id="1-prerequisites">1. Prerequisites<a class="headerlink" href="#1-prerequisites" title="Permalink">&para;</a></h1>
<p>Same prerequisites as in <a href="/doc/odata4/tutorials/read/tutorial_read.html">Tutorial Part 1: Read Entity Collection</a> and <a href="/doc/odata4/tutorials/readep/tutorial_readep.html">Tutorial Part 2: Read Entity</a> as well as basic knowledge about the concepts presented in both tutorials.</p>
<hr/>
<h1 id="2-preparation">2. Preparation<a class="headerlink" href="#2-preparation" title="Permalink">&para;</a></h1>
<p>Follow <a href="/doc/odata4/tutorials/read/tutorial_read.html">Tutorial Part 1: Read Entity Collection</a> and <a href="/doc/odata4/tutorials/readep/tutorial_readep.html">Tutorial Part 2: Read Entity</a> or as shortcut import <em>Part 2: Read Entity, Read Property</em> into your Eclipse workspace.</p>
<p>Afterwards do a Deploy and run: it should be working.</p>
<hr/>
<h1 id="3-implementing-the-navigation">3. Implementing the navigation<a class="headerlink" href="#3-implementing-the-navigation" title="Permalink">&para;</a></h1>
<p>In our sample scenario, we want to navigate from a product to its category and from a category to a list of products.
In order to achieve this, we need to create a second Entity Type, "Category", and we need to specify <em>Navigation Properties</em> in both Entity Types.
Our model looks as follows:</p>
<p><img alt="ODataModelNavigation" src="model.JPG" title="Our OData Model with link between 2 Entity Types"/></p>
<p><strong>Note</strong>
When designing the OData model, we could think of specifying a property &ldquo;ProductCategory&rdquo; in the entity type &ldquo;Product&rdquo;.
E.g. a product with name &ldquo;Brilliant flat and wide&rdquo; would have the category &ldquo;Monitors&rdquo;.
But this is not necessary, because that information can be obtained by navigating to the respective &ldquo;Category&rdquo;-entity using the navigation property.
That way, we can keep the entity types lightweight, which is one of the intentions of OData.</p>
<h2 id="31-declare-the-metadata">3.1. Declare the metadata<a class="headerlink" href="#31-declare-the-metadata" title="Permalink">&para;</a></h2>
<p>In order to declare the metadata of our OData service, we open the class myservice.mynamespace.service.DemoEdmProvider_</p>
<h3 id="311-extend-the-entity-type-product">3.1.1. Extend the Entity Type &ldquo;Product&rdquo;<a class="headerlink" href="#311-extend-the-entity-type-product" title="Permalink">&para;</a></h3>
<p>In the previous tutorial we&rsquo;ve already created the metadata for the &ldquo;Product&rdquo; entity type:</p>
<pre><code class="language-xml"> &lt;EntityType Name="Product"&gt;
&lt;Key&gt;
&lt;PropertyRef Name="ID" /&gt;
&lt;/Key&gt;
&lt;Property Name="ID" Type="Edm.Int32" Nullable="false" /&gt;
&lt;Property Name="Name" Type="Edm.String" Nullable="false" /&gt;
&lt;Property Name="Description" Type="Edm.String" Nullable="false" /&gt;
&lt;/EntityType&gt;
</code></pre>
<p>Now we have to add a navigation property.
That navigation property element has the following attributes:</p>
<p><strong>Name</strong>
The name of the navigation property is used as segment in the URI
e.g. for the following URL: <a href="http://localhost:8080/DemoService/DemoService.svc/Products(1)/Category">http://localhost:8080/DemoService/DemoService.svc/Products(1)/Category</a>
The segment &ldquo;Category&rdquo; is the name of the navigation property</p>
<p><strong>Type</strong>
Here we specify the Entity Type to which we&rsquo;re navigating.
e.g. for the following URL: <a href="http://localhost:8080/DemoService/DemoService.svc/Products(1)/Category">http://localhost:8080/DemoService/DemoService.svc/Products(1)/Category</a>
we&rsquo;re navigating to an entity which has the entity type &ldquo;OData.Demo.Category&rdquo;
(we still have to create this entity type in this tutorial)
Note that the fully qualified name has to be specified.
Note that here we don&rsquo;t specify a collection, so we have a to-one relationship.</p>
<p><strong>Nullable</strong>
Specifies if the navigation target is required.
If we don&rsquo;t specify it, then the default is assumed to be &ldquo;true&rdquo;.
In our example we want to declare that every product must have a category, so we have to set it to &ldquo;false&rdquo;</p>
<p><strong>Partner</strong>
An optional attribute, used to define a bi-directional relationship.
Specifies a path from the entity type (specified here) to the navigation property (defined there).
In our example, we can navigate from product to category and from category to product</p>
<p>In our example, the metadata of our &ldquo;Product&rdquo; entity type looks as follows:</p>
<pre><code class="language-xml"> &lt;EntityType Name="Product"&gt;
&lt;Key&gt;
&lt;PropertyRef Name="ID"/&gt;
&lt;/Key&gt;
&lt;Property Name="ID" Type="Edm.Int32"/&gt;
&lt;Property Name="Name" Type="Edm.String"/&gt;
&lt;Property Name="Description" Type="Edm.String"/&gt;
&lt;NavigationProperty Name="Category" Type="OData.Demo.Category" Nullable="false" Partner="Products"/&gt;
&lt;/EntityType&gt;
</code></pre>
<p>Implementation-wise we have to create and configure an object of type <code>CsdlNavigationProperty</code>:</p>
<pre><code class="language-java"> CsdlNavigationProperty navProp = new CsdlNavigationProperty()
.setName("Category")
.setType(ET_CATEGORY_FQN)
.setNullable(false)
.setPartner("Products");
</code></pre>
<p>Since an entity type can have multiple navigation properties, we have to put it into a list:</p>
<pre><code class="language-java"> List&lt;CsdlNavigationProperty&gt; navPropList = new ArrayList&lt;CsdlNavigationProperty&gt;();
navPropList.add(navProp);
</code></pre>
<p>That list becomes relevant for the entity type that has been created earlier:</p>
<pre><code class="language-java"> entityType.setNavigationProperties(navPropList);
</code></pre>
<p>There&rsquo;s one more step to consider with respect to the navigation: the entity set.
At runtime, we need to know how to implement the navigation, when an entity set is invoked.
For this purpose, the OData specifies the <code>NavigationPropertyBinding</code> element, which is a child element of the entity set and should be defined for each navigation property.
That <code>NavigationPropertyBinding</code> has the following attributes:</p>
<p><strong>Path</strong>
Here we specify the name of the corresponding navigation property.
In our example, the navigation property that we&rsquo;ve defined above is named &ldquo;Category&rdquo;</p>
<p><strong>Target</strong>
Here we specify the entity set where we&rsquo;re navigating to.
In our example it is the entity set &ldquo;Categories&rdquo; (which we will create below)</p>
<p>In our example, the definition of our &ldquo;Products&rdquo; entity set looks as follows:</p>
<pre><code class="language-xml"> &lt;EntitySet Name="Products" EntityType="OData.Demo.Product"&gt;
&lt;NavigationPropertyBinding Path="Category" Target="Categories"/&gt;
&lt;/EntitySet&gt;
</code></pre>
<p>Code-wise, the getEntitySet method is extended as follows:</p>
<pre><code class="language-java"> CsdlNavigationPropertyBinding navPropBinding = new CsdlNavigationPropertyBinding();
navPropBinding.setPath("Category"); // the path from entity type to navigation property
navPropBinding.setTarget("Categories"); //target entitySet, where the nav prop points to
List&lt;CsdlNavigationPropertyBinding&gt; navPropBindingList = new ArrayList&lt;CsdlNavigationPropertyBinding&gt;();
navPropBindingList.add(navPropBinding);
entitySet.setNavigationPropertyBindings(navPropBindingList);
</code></pre>
<h3 id="312-create-the-entity-type-category">3.1.2. Create the Entity Type &ldquo;Category&rdquo;<a class="headerlink" href="#312-create-the-entity-type-category" title="Permalink">&para;</a></h3>
<p>Now we have to create the second entity type, the &ldquo;Category&rdquo;.
In order to keep our sample as simple as possible, we define only 2 properties, the &ldquo;ID&rdquo; and a &ldquo;Name&rdquo;.
Since we want to be able to navigate from one given category (e.g. &ldquo;Monitors&rdquo;) to a list of products (e.g. all products that are monitors), we have to specify a navigation property in this entity type as well.
Here, the navigation property has the following attributes:</p>
<p><strong>Name</strong>
In our example, we specify &ldquo;Products&rdquo;, in plural because we want to get multiple entities.</p>
<p><strong>Type</strong>
The &ldquo;Type&rdquo; attribute can be either an &ldquo;entity type&rdquo; or a &ldquo;collection of entity types&rdquo;
In our example this time, we specify a &ldquo;collection&rdquo; of &ldquo;OData.Demo.Product&rdquo;</p>
<p><strong>Nullable</strong>
According to the OData specification (see odata.org), this attribute is not allowed for a collection
A collection can be empty, but never null.</p>
<p><strong>Partner</strong>
In our example, we&rsquo;re defining a bi-directional navigation, so here we specify &ldquo;Category&rdquo;, the name of the navigation property defined above.</p>
<p>In our example, the metadata of our &ldquo;Category&rdquo; entity type looks as follows:</p>
<pre><code class="language-xml"> &lt;EntityType Name="Category"&gt;
&lt;Key&gt;
&lt;PropertyRef Name="ID"/&gt;
&lt;/Key&gt;
&lt;Property Name="ID" Type="Edm.Int32"/&gt;
&lt;Property Name="Name" Type="Edm.String"/&gt;
&lt;NavigationProperty Name="Products" Type="Collection(OData.Demo.Product)" Partner="Category"/&gt;
&lt;/EntityType&gt;
</code></pre>
<p>The code for the &ldquo;Category&rdquo; entity type:</p>
<pre><code class="language-java"> if (entityTypeName.equals(ET_CATEGORY_FQN)){
//create EntityType properties
CsdlProperty id = new CsdlProperty()
.setName("ID")
.setType(EdmPrimitiveTypeKind.Int32.getFullQualifiedName());
CsdlProperty name = new CsdlProperty()
.setName("Name")
.setType(EdmPrimitiveTypeKind.String.getFullQualifiedName());
// create PropertyRef for Key element
CsdlPropertyRef propertyRef = new CsdlPropertyRef();
propertyRef.setName("ID");
// navigation property: one-to-many
CsdlNavigationProperty navProp = new CsdlNavigationProperty()
.setName("Products")
.setType(ET_PRODUCT_FQN)
.setCollection(true)
.setPartner("Category");
List&lt;CsdlNavigationProperty&gt; navPropList = new ArrayList&lt;CsdlNavigationProperty&gt;();
navPropList.add(navProp);
// configure EntityType
entityType = new CsdlEntityType();
entityType.setName(ET_CATEGORY_NAME);
entityType.setProperties(Arrays.asList(id, name));
entityType.setKey(Arrays.asList(propertyRef));
entityType.setNavigationProperties(navPropList);
}
</code></pre>
<p>The <code>NavigationPropertyBinding</code> element and its attributes for the entity set &ldquo;Categories&rdquo;:</p>
<p><strong>Path</strong>
In our example, the navigation property that we&rsquo;ve defined above is named &ldquo;Products&rdquo;</p>
<p><strong>Target</strong>
In our example it is the entity set &ldquo;Products&rdquo;</p>
<p>In our example, the definition of our &ldquo;Categories&rdquo; entity set looks as follows:</p>
<pre><code class="language-xml"> &lt;EntitySet Name="Categories" EntityType="OData.Demo.Category"&gt;
&lt;NavigationPropertyBinding Path="Products" Target="Products"/&gt;
&lt;/EntitySet&gt;
</code></pre>
<p>And the implementation in the <code>getEntitySet</code> method:</p>
<pre><code class="language-java"> CsdlNavigationPropertyBinding navPropBinding = new CsdlNavigationPropertyBinding();
navPropBinding.setTarget("Products");//target entitySet, where the nav prop points to
navPropBinding.setPath("Products"); // the path from entity type to navigation property
List&lt;CsdlNavigationPropertyBinding&gt; navPropBindingList = new ArrayList&lt;CsdlNavigationPropertyBinding&gt;();
navPropBindingList.add(navPropBinding);
entitySet.setNavigationPropertyBindings(navPropBindingList);
</code></pre>
<hr/>
<h2 id="32-implement-the-to-many-navigation">3.2. Implement the to-many navigation<a class="headerlink" href="#32-implement-the-to-many-navigation" title="Permalink">&para;</a></h2>
<p>Let&rsquo;s again have a look at our example, as described in the introduction section above.
The user of our service invokes the &ldquo;Categories&rdquo; collection and chooses one &ldquo;Category&rdquo;.
This is done with e.g. the following URL: <a href="http://localhost:8080/DemoService/DemoService.svc/Categories(1)">http://localhost:8080/DemoService/DemoService.svc/Categories(1)</a></p>
<p>The returned response payload doesn&rsquo;t contain any information about possible navigation.
So the user has to check the metadata document, where he can see that the entity type &ldquo;Category&rdquo; defines one navigation property:</p>
<p><img alt="CategoryMetadata" src="browser_metadataCategory.JPG" title="The definition of a Navigation Property in the $metadata document"/></p>
<p>This means, that he can append the navigation property name to his URL, which takes him to the set of &ldquo;Products&rdquo; that belong to the chosen &ldquo;Category&rdquo;: <a href="http://localhost:8080/DemoService/DemoService.svc/Categories(1)/Products">http://localhost:8080/DemoService/DemoService.svc/Categories(1)/Products</a></p>
<p>From the metadata we can see that the &ldquo;Type&rdquo; attribute defines a collection.
This means that the implementation has to be done in the <code>EntityCollectionProcessor</code>, since we have to provide a collection of entities.</p>
<p>Open the class <code>myservice.mynamespace.service.DemoEntityCollectionProcessor.java</code></p>
<p>There, the implementation for a &ldquo;normal&rdquo; read operation is already in place and we have to add the case when an entity collection is expected after navigation.
Note that we want to keep our tutorial and our code simple, so we decide that only one step navigation is to be supported by our service.
This means that we can navigate only once from one entity to another one.
For example:
Categories(1)/Products
We don&rsquo;t support navigation from one entity to an entity and then to another entity and so on
For example:
Categories(1)/Products(1)/Category</p>
<p>Based on this assumption, in our <code>EntityCollectionProcessor</code>, we can rely on the fact that the URI can have either one or two segments.
This means: we can be called for the following kind of URLs:</p>
<p>Example URL for one sement: <a href="http://localhost:8080/DemoService/DemoService.svc/Categories">http://localhost:8080/DemoService/DemoService.svc/Categories</a></p>
<p>Example URL for two segments: <a href="http://localhost:8080/DemoService/DemoService.svc/Categories(1)/Products">http://localhost:8080/DemoService/DemoService.svc/Categories(1)/Products</a></p>
<p>As such, in our code we distinguish these 2 cases:</p>
<pre><code class="language-java"> if(segmentCount == 1){
// here the &ldquo;normal&rdquo; entity set is requested
}else if (segmentCount == 2){
// this is reached in case of navigation: DemoService.svc/Categories(1)/Products
}else{
// in our example, we don&rsquo;t support URIs like Products(1)/Category/Products
throw new ODataApplicationException("Not supported", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(),Locale.ENGLISH);
}
</code></pre>
<p>The segments of the URI are retrieved from the uriInfo parameter:</p>
<pre><code class="language-java"> List&lt;UriResource&gt; resourceParts = uriInfo.getUriResourceParts();
int segmentCount = resourceParts.size();
</code></pre>
<p>In both cases, we have to retrieve the list of entities to be returned.
For the first case, we have only one entitySet, so the implementation is straight forward:</p>
<pre><code class="language-java"> EdmEntitySet startEdmEntitySet = uriResourceEntitySet.getEntitySet();
if(segmentCount == 1) {
// 2nd: fetch the data from backend for this requested EntitySetName
responseEntityCollection = storage.readEntitySetData(responseEdmEntitySet);
responseEdmEntitySet = startEdmEntitySet; //there&rsquo;s only one entity set
}
</code></pre>
<p>Now let&rsquo;s focus on the second case, the navigation.</p>
<p>Our tasks are:</p>
<ol>
<li>depending on the chosen key of the first segment, we have to compute which and how many entities exactly have to be returned. With other words, find the right data in the backend
e.g. for the category &ldquo;monitors&rdquo;, we have to find the right products that are monitors</li>
<li>find out, which entity set has to be returned (can be products, categories, etc)
This <code>EdmEntitySet</code> is required in order to properly build the context URL</li>
</ol>
<p>The following sections explain how to do that.</p>
<h3 id="321-get-the-data-for-the-response">3.2.1. Get the data for the response<a class="headerlink" href="#321-get-the-data-for-the-response" title="Permalink">&para;</a></h3>
<p>Getting the data for the response is reylized in 2 steps:</p>
<p><strong>A)</strong> get the data for the first URI segment
in our example, we have to perform a read operation for retrieving the Category with ID 3, which is "Monitors"</p>
<p><strong>B)</strong> get the data for the navigation
in our example, we have to find the products that are monitors.</p>
<p>With respect to data, remember that we're using sample data that we create in our <code>Storage</code> class which represents our kind of database-mock.<br/>
On startup of our service, we initialize some sample products and categories.
During initialization, there&rsquo;s no assignment of products to its categories.
In our sample code, we&rsquo;re doing this when requested in a hard-coded method in our <code>Storage</code> class.</p>
<p><strong>A) get the data for the first URI segment</strong></p>
<p>In our example, the URL would be: <a href="http://localhost:8080/DemoService/DemoService.svc/Categories(3)/Products">http://localhost:8080/DemoService/DemoService.svc/Categories(3)/Products</a></p>
<p>For this example, we would have to retrieve the Category with <em>ID=3</em>.<br/>
The code looks like a normal <code>READ</code> operation:</p>
<pre><code class="language-java"> List&lt;UriParameter&gt; keyPredicates = uriResourceEntitySet.getKeyPredicates();
Entity sourceEntity = storage.readEntityData(startEdmEntitySet, keyPredicates);
</code></pre>
<p>In our example, the result is an entity that represents the &ldquo;Monitors&rdquo; &ndash; category.</p>
<p><strong>B) get the data for the navigation</strong></p>
<p>Now we have to follow the navigation, based on the retrieved entity.<br/>
In our example, we have to retrieve all products that are monitors.</p>
<p>This is backend logic, so we can directly call a helper method in our Storage class:</p>
<pre><code class="language-java"> responseEntityCollection = storage.getRelatedEntityCollection(sourceEntity, targetEntityType);
</code></pre>
<p>This helper method requires the source entity and returns the target collection.
Additionally, the method needs the <code>EdmEntityType</code> that corresponds to the requested target.
In our example, we pass the &ldquo;Category&rdquo; (i.e. "Monitors") as source entity and the navigation target entity type, which is &ldquo;Product&rdquo;.
As a result, we get the desired &ldquo;Products&rdquo; collection, all products that are monitors.</p>
<p>After this step, we&rsquo;re almost done, because we have the entity collection that our OData service returns in the response body.
We only need to do some more hand work: the response entity collection has to be serialized and the serializer which is in charge of doing that has to be configured properly.
For that we need the <code>EdmEntitySet</code> that corresponds to the response.
Since it is different in case of navigation and non-navigation, we still need to retrieve it for the case of navigation.</p>
<h3 id="322-retrieve-the-edmentityset-for-the-response">3.2.2. Retrieve the EdmEntitySet for the response<a class="headerlink" href="#322-retrieve-the-edmentityset-for-the-response" title="Permalink">&para;</a></h3>
<p>First, we have to analyze the URI, and find out if the URI segment is used for navigation.
As mentioned, in our simple example we assume that the second segment is used for navigation (in advanced services, a segment could as well be an action or function import, etc).
The navigation URI segment can then be asked for the corresponding <code>EdmNavigationProperty</code></p>
<pre><code class="language-java"> UriResource lastSegment = resourceParts.get(1);
if(lastSegment instanceof UriResourceNavigation){
UriResourceNavigation uriResourceNavigation = (UriResourceNavigation)lastSegment;
EdmNavigationProperty edmNavigationProperty = uriResourceNavigation.getProperty();
</code></pre>
<p>The bad news is that the <code>EdmNavigationProperty</code> doesn&rsquo;t know about the target <code>EdmEntitySet</code>.
This is as per design, just check the metadata:</p>
<pre><code class="language-xml"> &lt;EntityType Name="Category"&gt;
...
&lt;NavigationProperty Name="Products" Type="Collection(OData.Demo.Product)" Partner="Category"/&gt;
&lt;/EntityType&gt;
</code></pre>
<p>The navigation property is defined on entity-type-level and as such, it does know the target entity type.
The target entity set is defined in the navigation property binding element on entity-set-level:</p>
<pre><code class="language-xml"> &lt;EntitySet Name="Categories" EntityType="OData.Demo.Category"&gt;
&lt;NavigationPropertyBinding Path="Products" Target="Products"/&gt;
&lt;/EntitySet&gt;
</code></pre>
<p>This is where we get the information that we need.</p>
<p>For our implementation, this means:</p>
<ol>
<li>we need the <code>EdmEntitySet</code> that corresponds to the first segment of the URI
in our example: Categories</li>
<li>we need the navigation property that corresponds to the second segment of the URI
in our example: Products</li>
</ol>
<p>As shown below, from the source <code>EdmEntitySet</code> we get the binding target, based on the navigation property.</p>
<pre><code class="language-java"> EdmBindingTarget edmBindingTarget = startEdmEntitySet.getRelatedBindingTarget(navPropName);
if(edmBindingTarget instanceof EdmEntitySet){
navigationTargetEntitySet = (EdmEntitySet)edmBindingTarget;
</code></pre>
<p>This target is the entity set that we need.</p>
<p>We move the code into the utility method <code>Util.getNavigationTargetEntitySet(startEdmEntitySet, edmNavigationProperty)</code>
Reason is that we'll need it again, later in this tutorial.</p>
<h3 id="323-remaining-tasks">3.2.3 Remaining tasks<a class="headerlink" href="#323-remaining-tasks" title="Permalink">&para;</a></h3>
<p>In the previous tutorials we&rsquo;ve already learned what else has to be done: transform the retrieve data into an <code>InputStream</code> i.e. serialize the content.
Furthermore, configure the response object, i.e. set the response body, the content type and the header.</p>
<p>The following snippet shows the implementation of the <code>readEntityCollection(&hellip;)</code> method.</p>
<pre><code class="language-java"> public void readEntityCollection(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat)
throws ODataApplicationException, SerializerException {
EdmEntitySet responseEdmEntitySet = null; // for building ContextURL
EntityCollection responseEntityCollection = null; // for the response body
// 1st retrieve the requested EntitySet from the uriInfo
List&lt;UriResource&gt; resourceParts = uriInfo.getUriResourceParts();
int segmentCount = resourceParts.size();
UriResource uriResource = resourceParts.get(0); // the first segment is the EntitySet
if (! (uriResource instanceof UriResourceEntitySet)) {
throw new ODataApplicationException("Only EntitySet is supported", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(),Locale.ROOT);
}
UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) uriResource;
EdmEntitySet startEdmEntitySet = uriResourceEntitySet.getEntitySet();
if(segmentCount == 1){ // this is the case for: DemoService/DemoService.svc/Categories
responseEdmEntitySet = startEdmEntitySet; // first (and only) entitySet
// 2nd: fetch the data from backend for this requested EntitySetName
responseEntityCollection = storage.readEntitySetData(startEdmEntitySet);
}else if (segmentCount == 2){ //navigation: e.g. DemoService.svc/Categories(3)/Products
UriResource lastSegment = resourceParts.get(1); // don't support more complex URIs
if(lastSegment instanceof UriResourceNavigation){
UriResourceNavigation uriResourceNavigation = (UriResourceNavigation)lastSegment;
EdmNavigationProperty edmNavigationProperty = uriResourceNavigation.getProperty();
EdmEntityType targetEntityType = edmNavigationProperty.getType();
responseEdmEntitySet = Util.getNavigationTargetEntitySet(startEdmEntitySet, edmNavigationProperty);
// 2nd: fetch the data from backend
// first fetch the entity where the first segment of the URI points to
// e.g. Categories(3)/Products first find the single entity: Category(3)
List&lt;UriParameter&gt; keyPredicates = uriResourceEntitySet.getKeyPredicates();
Entity sourceEntity = storage.readEntityData(startEdmEntitySet, keyPredicates);
// error handling for e.g. DemoService.svc/Categories(99)/Products
if(sourceEntity == null) {
throw new ODataApplicationException("Entity not found.", HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ROOT);
}
// then fetch the entity collection where the entity navigates to
responseEntityCollection = storage.getRelatedEntityCollection(sourceEntity, targetEntityType);
}
}else{ // this would be the case for e.g. Products(1)/Category/Products
throw new ODataApplicationException("Not supported", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(),Locale.ROOT);
}
// 3rd: create and configure a serializer
ContextURL contextUrl = ContextURL.with().entitySet(responseEdmEntitySet).build();
final String id = request.getRawBaseUri() + "/" + responseEdmEntitySet.getName();
EntityCollectionSerializerOptions opts = EntityCollectionSerializerOptions.with().contextURL(contextUrl).id(id).build();
EdmEntityType edmEntityType = responseEdmEntitySet.getEntityType();
ODataSerializer serializer = odata.createSerializer(responseFormat);
SerializerResult serializerResult = serializer.entityCollection(this.srvMetadata, edmEntityType, responseEntityCollection, opts);
// 4th: configure the response object: set the body, headers and status code
response.setContent(serializerResult.getContent());
response.setStatusCode(HttpStatusCode.OK.getStatusCode());
response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
</code></pre>
<h2 id="33-implement-the-to-one-navigation">3.3. Implement the to-one navigation<a class="headerlink" href="#33-implement-the-to-one-navigation" title="Permalink">&para;</a></h2>
<p>As for the to-one navigation, it is the case if the navigation target is a single entity, not a collection.
In our example, the following URL represents a to-one navigation: <a href="http://localhost:8080/DemoService/DemoService.svc/Products(1)/Category">http://localhost:8080/DemoService/DemoService.svc/Products(1)/Category</a></p>
<p>The user of our service has chosen a product and wants to know to which category it belongs. He can find it out by following the navigation property.
As per design, a product can only belong to <strong>one</strong> category (obviously, a product can only be a Notebook or a Monitor, not both). Therefore in our service, we&rsquo;ve defined a navigation property that is not of type collection:</p>
<pre><code class="language-xml"> &lt;NavigationProperty
Name="Category"
Type="OData.Demo.Category"
Nullable="false"
Partner="Products"/&gt;
</code></pre>
<p>So when the user follows the navigation property in order to display the product category, he expects a response that contains only one entry.
This means that we have to do the implementation in the <code>EntityProcessor</code>.</p>
<p>Open the class <code>myservice.mynamespace.service.DemoEntityProcessor.java</code></p>
<p>As usual, we first have to analyze the URI.
Just like we did in the <code>EntityCollectionProcessor</code>, we have to distinguish between navigation and &ldquo;normal&rdquo; read of an entity:</p>
<pre><code class="language-java"> if(segmentCount == 1){
// in case of directly adressing of an entity
}else if (segmentCount == 2){
// this is reached in case of navigation
}
</code></pre>
<p>In the following section, we will focus on the navigation case only.
In our example, our task is to find the category of a chosen product.
Again, we have to first fetch the chosen product (first URI segment) from our database-mock and in a second step, we have to ask our database-mock for the corresponding category.
This final entity is then serialized and set as response body for the <code>readEntity()</code> method, which we&rsquo;re implementing.</p>
<p><strong>A) get the data for the first URI segment</strong></p>
<p>In our example, we have to perform a read operation for retrieving the product with ID 1: <a href="http://localhost:8080/DemoService/DemoService.svc/Products(1)/Category">http://localhost:8080/DemoService/DemoService.svc/Products(1)/Category</a></p>
<p>The code is the same like in the previous chapter (to-many navigation):</p>
<pre><code class="language-java"> List&lt;UriParameter&gt; keyPredicates = uriResourceEntitySet.getKeyPredicates();
Entity sourceEntity = storage.readEntityData(startEdmEntitySet, keyPredicates);
</code></pre>
<p><strong>B) get the data for the navigation</strong></p>
<p>Now we have to follow the navigation, based on the retrieved entity.
In our example, we have to find the category corresponding to the chosen product.
Therefore, we invoke our helper method and pass the source Entity (Product) and the required target entity type (Category). The method will find the category which is related to the chosen product.</p>
<pre><code class="language-java"> responseEntity = storage.getRelatedEntity(sourceEntity, responseEdmEntityType);
</code></pre>
<p>Before we can serialize the <code>responseEntity</code>, we have to retrieve the <code>EdmEntitySet</code> that corresponds to the response entity, because we need it for building the ContextURL.</p>
<p>The procedure is the same like in the chapter above, where we treated the to-many navigation:</p>
<pre><code class="language-java"> EdmNavigationProperty edmNavigationProperty = uriResourceNavigation.getProperty();
responseEdmEntityType = edmNavigationProperty.getType();
responseEdmEntitySet = Util.getNavigationTargetEntitySet(startEdmEntitySet, edmNavigationProperty);
</code></pre>
<p>In our example, the value of the variable <code>responseEdmEntitySet</code> will be &ldquo;Categories&rdquo; and it will be used for building the contextURL, which will look as follows:</p>
<pre><code class="language-xml"> "$metadata#Categories/$entity"
</code></pre>
<h2 id="34-implement-the-to-many-navigation-with-key-access">3.4. Implement the to-many navigation with key access<a class="headerlink" href="#34-implement-the-to-many-navigation-with-key-access" title="Permalink">&para;</a></h2>
<p>"Navigation with key access" means that we have a to-many navigation, like navigating from a chosen category to the list of corresponding products: <a href="http://localhost:8080/DemoService/DemoService.svc/Categories(3)/Products">http://localhost:8080/DemoService/DemoService.svc/Categories(3)/Products</a></p>
<p>but in addition, we want to read only one of the collected products, which is directly addressed by its key: <a href="http://localhost:8080/DemoService/DemoService.svc/Categories(3)/Products(5)">http://localhost:8080/DemoService/DemoService.svc/Categories(3)/Products(5)</a></p>
<p>From this URL, we can assume that the <code>EntityProcessor</code> is the relevant place to handle this request in our code.</p>
<p>The steps to find the requested entity are:</p>
<ol>
<li>Do a read operation for the first segment (same as in the previous chapter)
In our example, this would be read entity for: <em>/Categories(3)</em></li>
<li>Follow the navigation to get the collection of the second segment
In our example, this would be get the entity collection for: <em>/Categories(3)/Products</em></li>
<li>Pick the requested entity from the collection
In our example, retrieve the product with ID=5, which is contained in the collection <em>/Categories(3)/Products(5)</em></li>
</ol>
<p>We can assume, that our database-mock is able to perform step 2 and 3 together.</p>
<p>In our class <code>myservice.mynamespace.service.DemoEntityProcessor.java</code>, we&rsquo;ve already added the navigation capability for to-one navigation.
How can we find out that we aren&rsquo;t called for a to-one navigation, but instead, we&rsquo;re responding to a to-many navigation with key access?
The difference is the &ldquo;key predicate&rdquo;.
The necessary info about it can be obtained from the URI segment.
In the first chapter, we&rsquo;ve already learned that there&rsquo;s a special interface responsible for navigation segments, the <code>org.apache.olingo.server.api.uri.UriResourceNavigation</code>
It also provides a method <code>getKeyPredicates()</code>
We can make use of it in order to distinguish between &ldquo;to-one navigation&rdquo; and &ldquo;navigation with key access&rdquo;.
If the call to</p>
<pre><code class="language-java"> List&lt;UriParmeter&gt; navKeyPredicates = uriResourceNavigation.getKeyPredicates();
</code></pre>
<p>returns an empty list, then we can assume that our OData service has been called for a &ldquo;to-one navigation&rdquo;.
This to-one navigation has been explained in the chapter 3.3. above.
If the service request is like
/Categories(3)/Products(5)
then the method <code>getKeyPredicates()</code> will return a list of with one element that contains ID=5</p>
<p>In our implementation of the <code>EntityProcessor</code>, we add the following code:</p>
<pre><code class="language-java"> List&lt;UriParameter&gt; navKeyPredicates = uriResourceNavigation.getKeyPredicates();
if(navKeyPredicates.isEmpty()){
responseEntity = storage.getRelatedEntity(sourceEntity, responseEdmEntityType);
}else{
responseEntity = storage.getRelatedEntity(sourceEntity, responseEdmEntityType, navKeyPredicates);
}
</code></pre>
<p>We get the key predicates for the navigation segment.
Then we check if returned list is empty.
If yes, we use the line that we implemented in chapter 3.3.
If not, we have to create a new helper method that uses the key predicates for retrieving the desired entity.
The new helper method</p>
<pre><code class="language-java"> responseEntity = storage.getRelatedEntity(sourceEntity, responseEdmEntityType, navKeyPredicates);
</code></pre>
<p>will take care of getting the collection of products (<code>responseEntityType</code>) that are in scope of the chosen category (<code>sourceEntity</code>) and will then pick the requested product, based on the given key (<code>navKeyPredicates</code>).</p>
<p>One last thing to consider:<br/>
As we mentioned above, the user of our service is expected to specify a key of a product that is contained in the collection of products (e.g. <em>/Categories(3)/Products</em>) that is addressed by e.g. <em>/Categories(3)/Products(5)</em>.</p>
<p>But he might specify a product ID that is existing, but not valid for the addressed navigation e.g. <em>/Categories(3)/Products(1)</em>.</p>
<p>With other words: it is not valid to navigate from category "Monitors" to a product like "Notebook Basic 15"</p>
<p>If this is the case, we have to throw an appropriate exception.
However, in our simple example we&rsquo;re satisfied with simply checking if an entity was found at all:</p>
<pre><code class="language-java"> if(responseEntity == null) {
throw new ODataApplicationException("Nothing found.", HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ROOT);
}
</code></pre>
<p><strong>Note</strong>
When implementing this navigation for the first time, our first intention might have been:
Let&rsquo;s just ignore the first segment and simply do a read operation for /Products(5)
Which would mean, from the list of all products, pick the one with ID=5
Why not?
The answer is that we cannot assume that the requested Product is automatically belonging to the specified Category.
E.g. in our example, the following URI should throw an error:
Categories(3)/Products(1)
As we know, Categories(3) is &ldquo;Monitors&rdquo; and Product(1) is a &ldquo;Notebook&rdquo;</p>
<p>That&rsquo;s it.
We don&rsquo;t need to do an additional effort to retrieve the <code>EdmEntitySet</code> for the ContextURL, because this has already been implemented in our <code>DemoEntityProcessor</code> in the context of the previous chapter 3.3.</p>
<p>So now we can finally have a look at the full implementation of the <code>readEntity()</code> method, the covers both the cases of chapter 3.3. and 3.4.</p>
<pre><code class="language-java"> public void readEntity(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat)
throws ODataApplicationException, SerializerException {
EdmEntityType responseEdmEntityType = null; // we'll need this to build the ContextURL
Entity responseEntity = null; // required for serialization of the response body
EdmEntitySet responseEdmEntitySet = null; // we need this for building the contextUrl
// 1st step: retrieve the requested Entity:
// can be "normal" read operation, or navigation (to-one)
List&lt;UriResource&gt; resourceParts = uriInfo.getUriResourceParts();
int segmentCount = resourceParts.size();
UriResource uriResource = resourceParts.get(0);
if (! (uriResource instanceof UriResourceEntitySet)) {
throw new ODataApplicationException("Only EntitySet is supported", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(),
Locale.ROOT);
}
UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) uriResource;
EdmEntitySet startEdmEntitySet = uriResourceEntitySet.getEntitySet();
// Analyze the URI segments
if(segmentCount == 1){ // no navigation
responseEdmEntityType = startEdmEntitySet.getEntityType();
responseEdmEntitySet = startEdmEntitySet; // since we have only one segment
// 2. step: retrieve the data from backend
List&lt;UriParameter&gt; keyPredicates = uriResourceEntitySet.getKeyPredicates();
responseEntity = storage.readEntityData(startEdmEntitySet, keyPredicates);
} else if (segmentCount == 2){ //navigation
UriResource navSegment = resourceParts.get(1);
if(navSegment instanceof UriResourceNavigation){
UriResourceNavigation uriResourceNavigation = (UriResourceNavigation) navSegment;
EdmNavigationProperty edmNavigationProperty = uriResourceNavigation.getProperty();
responseEdmEntityType = edmNavigationProperty.getType();
responseEdmEntitySet = Util.getNavigationTargetEntitySet(startEdmEntitySet, edmNavigationProperty);
// 2nd: fetch the data from backend.
// for: Products(1)/Category we have to find the correct Category entity
List&lt;UriParameter&gt; keyPredicates = uriResourceEntitySet.getKeyPredicates();
// e.g. for Products(1)/Category we have to find first the Products(1)
Entity sourceEntity = storage.readEntityData(startEdmEntitySet, keyPredicates);
// now we have to check if the navigation is
// a) to-one: e.g. Products(1)/Category
// b) to-many with key: e.g. Categories(3)/Products(5)
List&lt;UriParameter&gt; navKeyPredicates = uriResourceNavigation.getKeyPredicates();
if(navKeyPredicates.isEmpty()){
// e.g. DemoService.svc/Products(1)/Category
responseEntity = storage.getRelatedEntity(sourceEntity, responseEdmEntityType);
}else{ // e.g. DemoService.svc/Categories(3)/Products(5)
responseEntity = storage.getRelatedEntity(sourceEntity, responseEdmEntityType, navKeyPredicates);
}
}
}else{
// this would be the case for e.g. Products(1)/Category/Products(1)/Category
throw new ODataApplicationException("Not supported", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ROOT);
}
if(responseEntity == null) {
// this is the case for e.g. DemoService.svc/Categories(4) or
// DemoService.svc/Categories(3)/Products(999)
throw new ODataApplicationException("Nothing found.", HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ROOT);
}
// 3. serialize
ContextURL contextUrl = ContextURL.with().entitySet(responseEdmEntitySet).suffix(Suffix.ENTITY).build();
EntitySerializerOptions opts = EntitySerializerOptions.with().contextURL(contextUrl).build();
ODataSerializer serializer = this.odata.createSerializer(responseFormat);
SerializerResult serializerResult = serializer.entity(this.srvMetadata, responseEdmEntityType, responseEntity, opts);
//4. configure the response object
response.setContent(serializerResult.getContent());
response.setStatusCode(HttpStatusCode.OK.getStatusCode());
response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
}
</code></pre>
<hr/>
<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 URLs:</p>
<ul>
<li>Metadata and Service documents
<ul>
<li><a href="http://localhost:8080/DemoService/DemoService.svc/$metadata">http://localhost:8080/DemoService/DemoService.svc/$metadata</a></li>
<li><a href="http://localhost:8080/DemoService/DemoService.svc">http://localhost:8080/DemoService/DemoService.svc</a></li>
</ul>
</li>
<li>&ldquo;Normal&rdquo; query of both entity sets
<ul>
<li><a href="http://localhost:8080/DemoService/DemoService.svc/Products">http://localhost:8080/DemoService/DemoService.svc/Products</a></li>
<li><a href="http://localhost:8080/DemoService/DemoService.svc/Categories">http://localhost:8080/DemoService/DemoService.svc/Categories</a></li>
</ul>
</li>
<li>&ldquo;Normal&rdquo; read of both entity types
<ul>
<li><a href="http://localhost:8080/DemoService/DemoService.svc/Products(1)">http://localhost:8080/DemoService/DemoService.svc/Products(1)</a></li>
<li><a href="http://localhost:8080/DemoService/DemoService.svc/Categories(3)">http://localhost:8080/DemoService/DemoService.svc/Categories(3)</a></li>
</ul>
</li>
<li>&ldquo;to-many&rdquo; navigation
<ul>
<li><a href="http://localhost:8080/DemoService/DemoService.svc/Categories(2)/Products">http://localhost:8080/DemoService/DemoService.svc/Categories(2)/Products</a></li>
</ul>
</li>
<li>&ldquo;to-one&rdquo; navigation
<ul>
<li><a href="http://localhost:8080/DemoService/DemoService.svc/Products(1)/Category">http://localhost:8080/DemoService/DemoService.svc/Products(1)/Category</a></li>
</ul>
</li>
<li>&ldquo;to-many&rdquo; navigation with key access
<ul>
<li><a href="http://localhost:8080/DemoService/DemoService.svc/Categories(1)/Products(2)">http://localhost:8080/DemoService/DemoService.svc/Categories(1)/Products(2)</a></li>
</ul>
</li>
<li>&ldquo;to-many&rdquo; navigation with key access of invalid key, throwing an error
<ul>
<li><a href="http://localhost:8080/DemoService/DemoService.svc/Categories(1)/Products(3)">http://localhost:8080/DemoService/DemoService.svc/Categories(1)/Products(3)</a></li>
</ul>
</li>
</ul>
<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 add navigation capabilities to an OData service.
We&rsquo;ve implemented the to-many and to-one relationship and also the READ access to one entity after a to-many navigation.
We&rsquo;ve restricted the navigation to two segments, no more than navigating from one entity to another one.
The modification of relations has not been covered by this tutorial.
Check the <em>Links</em> section for more OData V4 tutorials.</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: <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: Navigation</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>
<hr/>
<h1 id="7-appendix-code-snippets">7. Appendix: code snippets<a class="headerlink" href="#7-appendix-code-snippets" title="Permalink">&para;</a></h1>
<p>When reaching the point where your OData service has to become production ready and support complex scenarions, you&rsquo;ll find the following code snippets useful.</p>
<h2 id="71-find-the-edmentityset-for-the-navigation-target">7.1. Find the EdmEntitySet for the navigation target<a class="headerlink" href="#71-find-the-edmentityset-for-the-navigation-target" title="Permalink">&para;</a></h2>
<pre><code class="language-java"> public static EdmEntitySet getNavigationTargetEntitySet(final UriInfoResource uriInfo) throws ODataApplicationException {
EdmEntitySet entitySet;
final List&lt;UriResource&gt; resourcePaths = uriInfo.getUriResourceParts();
// First must be entity set (hence function imports are not supported here).
if (resourcePaths.get(0) instanceof UriResourceEntitySet) {
entitySet = ((UriResourceEntitySet) resourcePaths.get(0)).getEntitySet();
} else {
throw new ODataApplicationException("Invalid resource type.",
HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ROOT);
}
int navigationCount = 0;
while (entitySet != null
&amp;&amp; ++navigationCount &lt; resourcePaths.size()
&amp;&amp; resourcePaths.get(navigationCount) instanceof UriResourceNavigation) {
final UriResourceNavigation uriResourceNavigation = (UriResourceNavigation) resourcePaths.get(navigationCount);
final EdmBindingTarget target = entitySet.getRelatedBindingTarget(uriResourceNavigation.getProperty().getName());
if (target instanceof EdmEntitySet) {
entitySet = (EdmEntitySet) target;
} else {
throw new ODataApplicationException("Singletons not supported", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(),
Locale.ROOT);
}
}
return entitySet;
}
</code></pre>
<h2 id="72-find-the-last-navigation-segment">7.2. Find the last navigation segment<a class="headerlink" href="#72-find-the-last-navigation-segment" title="Permalink">&para;</a></h2>
<pre><code class="language-java"> public static UriResourceNavigation getLastNavigation(final UriInfoResource uriInfo) {
final List&lt;UriResource&gt; resourcePaths = uriInfo.getUriResourceParts();
int navigationCount = 1;
while (navigationCount &lt; resourcePaths.size()
&amp;&amp; resourcePaths.get(navigationCount) instanceof UriResourceNavigation) {
navigationCount++;
}
return (UriResourceNavigation) resourcePaths.get(--navigationCount);
}
</code></pre>
<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>