blob: 0ab763db929cbbfb339ff320345357d7d7441776 [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="media-resources">Media Resources<a class="headerlink" href="#media-resources" title="Permalink">&para;</a></h1>
<hr/>
<h3 id="how-to-guide-extend-read-scenario-with-support-for-media-resources">How To Guide - Extend read scenario with support for media resources<a class="headerlink" href="#how-to-guide-extend-read-scenario-with-support-for-media-resources" title="Permalink">&para;</a></h3>
<p>This How To Guide shows how to extend the read scenario (with <code>$expand</code> extension) with support for Media Link Entries and Media Resources.</p>
<p>The tutorial introduces a new resource (Driver), shows how to extend the according <code>readEntitySet(...)</code> and <code>readEntity(...)</code> and introduces the new method <code>readEntityMedia(uriInfo:GetMediaResourceUriInfo, contentType:String):ODataResponse</code> within the <code>MyODataSingleProcessor</code>.</p>
<h3 id="prerequisites">Prerequisites<a class="headerlink" href="#prerequisites" title="Permalink">&para;</a></h3>
<p>Setup of <a href="read_expand">Read Scenario with <code>$expand</code></a> extension
(which has as prerequisite Setup of <a href="basicread">Basic Read Scenario</a>)</p>
<h3 id="shortcut">Shortcut<a class="headerlink" href="#shortcut" title="Permalink">&para;</a></h3>
<p>If you like to directly experiment with the results of the extented basic read scenario, you can use this shortcut:</p>
<ul>
<li>Download and unzip the <a href="apache-olingo-tutorial-adv_read_mediaresource.zip">Olingo Tutorial 'Basic Read with Media Resource extension' Project</a> to your local drive which is your OData Tutorial project folder (referenced as <code>$ODATA_PROJECT_HOME</code> in the turorial).</li>
<li>Start the command line tool and run maven in the folder <code>$ODATA_PROJECT_HOME</code> to build the war file which then can be deployed.</li>
<li>Deploy the resulting war to your favorite application server.
<ul>
<li>For a Tomcat application server copy the war into the <em>$TOMCAT_HOME/webapps</em> folder and start the server via <code>$TOMCAT_HOME/bin/startup.sh</code> (at Windows via <code>$TOMCAT_HOME/bin/startup.bat</code>).</li>
</ul>
</li>
<li>Optional: To import the sample project into Eclipse run the following steps:
<ul>
<li>Start the command line tool and run <code>mvn eclipse:eclipse clean install</code> in the folder <code>$ODATA_PROJECT_HOME</code> to generate the Eclipse project settings and do an initial build.</li>
<li>Go into Eclipse and import the project into your workspace by...
<ul>
<li>Menue "File" -&gt; "Import..."</li>
<li>"Existing projects into workspace" then choose the olingo.odata2.sample folder</li>
<li>Select both projects olingo.odata2.sample.service and olingo.odata2.sample.web and press "Finish"</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="hints">Hints<a class="headerlink" href="#hints" title="Permalink">&para;</a></h3>
<ul>
<li>Sometimes a code extension needs one or more new/additional imports. These are not shown in the examples because it would blow up the source code examples and normally the IDE should support an auto fix of missing imports during typing of the code or after an insert of copied code.</li>
</ul>
<h3 id="extend-read-scenario">Extend Read Scenario<a class="headerlink" href="#extend-read-scenario" title="Permalink">&para;</a></h3>
<p>The steps to extend the read scenario (already with <code>$expand</code> support) with support for a Driver which is a media link entry with an associated media resource and therefore contains an image as media is to override and implement the <code>readEntityMedia(uriInfo:GetMediaResourceUriInfo, contentType:String):ODataResponse</code> method within the <code>MyODataSingleProcessor</code>.</p>
<p>All $value requests - where $value is the next segment to an entity type instance identified by an EntitySet with key predicate or a navigation property (to one relation or key predicate for to many relation) - to the service are delegated to this method which then handles the creation of the according response.</p>
<h3 id="extend-myedmprovider-and-myodatasingleprocessor">Extend MyEdmProvider and MyODataSingleProcessor<a class="headerlink" href="#extend-myedmprovider-and-myodatasingleprocessor" title="Permalink">&para;</a></h3>
<h4 id="small-sample-code-prerequisites">Small sample code Prerequisites<a class="headerlink" href="#small-sample-code-prerequisites" title="Permalink">&para;</a></h4>
<p>Not directly related to the OData Library parts but necessary for the sample project is the extension of the DataStore with methods to access the new Driver and the binary data for the media resource of the Driver.
Because this extension is more boilerplate code with no direct OData impact it is recommended to simply copy the DataStore.java into the project.
As conclusion following methods are added which are accessed from the <code>MyODataSingleProcessor</code>:</p>
<ul>
<li><code>readDriverImage(entitySet:EdmEntitySet, id:int):byte[]</code></li>
<li><code>getDriverFor(carId:int):Map&lt;String, Object&gt;</code></li>
<li><code>getCarFor(driverKey:int):Map&lt;String, Object&gt;</code></li>
<li><code>getDriver(id:int):Map&lt;String, Object&gt;</code></li>
<li><code>getDrivers():List&lt;Map&lt;String, Object&gt;&gt;</code></li>
</ul>
<p>Additional and in conclusion with the <code>DataStore</code> three images (png) are added to the sample project. These images are located in <em>/sample-service/src/main/resources/</em> and are named Driver_'x'.png were 'x' is replaced by a number.
To really get an image for a media resource request it is necessary to copy these images (or create own PNG files which follows the naming schema).
If nothing is copied/created the sample will still work but does not show an image for a media resource request (instead a HTTP Response 404 - Entity not found is shown).</p>
<p>** Extend MyEdmProvider with Driver data model **<br/></p>
<p>First the new Driver is added in the EDM.
The Driver gets a Key (Id) and some properties (Name, Surname, Nickname, Updates). For simplification currently we do not add any associations to another entities.</p>
<p>To mark the Driver as a media link entry with an associated media resource extension it is mandatory to set the stream property to true via the <code>setHasStream(true)</code> method when creating the <code>EntityType</code>.</p>
<p>As conclusion the <code>getEntityType(&hellip;)</code> method is extended as follows:</p>
<h5 id="sample-code">Sample Code<a class="headerlink" href="#sample-code" title="Permalink">&para;</a></h5>
<pre><code class="language-java">&hellip;
} else if (ENTITY_TYPE_1_3.getName().equals(edmFQName.getName())) {
List&lt;Property&gt; properties = new ArrayList&lt;Property&gt;();
properties.add(new SimpleProperty().setName("Id").setType(EdmSimpleTypeKind.Int32).setFacets(new Facets().setNullable(false)));
properties.add(new SimpleProperty().setName("Name").setType(EdmSimpleTypeKind.String).setFacets(new Facets().setNullable(false).setMaxLength(50)));
properties.add(new SimpleProperty().setName("Surname").setType(EdmSimpleTypeKind.String).setFacets(new Facets().setNullable(false).setMaxLength(80))
.setCustomizableFeedMappings(new CustomizableFeedMappings().setFcTargetPath(EdmTargetPath.SYNDICATION_TITLE)));
properties.add(new SimpleProperty().setName("Nickname").setType(EdmSimpleTypeKind.String).setFacets(new Facets().setNullable(true).setMaxLength(50)));
properties.add(new SimpleProperty().setName("Updated").setType(EdmSimpleTypeKind.DateTime)
.setFacets(new Facets().setNullable(false).setConcurrencyMode(EdmConcurrencyMode.Fixed))
.setCustomizableFeedMappings(new CustomizableFeedMappings().setFcTargetPath(EdmTargetPath.SYNDICATION_UPDATED)));
// Navigation properties
List&lt;NavigationProperty&gt; navigationProperties = new ArrayList&lt;NavigationProperty&gt;();
// Key
List&lt;PropertyRef&gt; keyProperties = new ArrayList&lt;PropertyRef&gt;();
keyProperties.add(new PropertyRef().setName("Id"));
Key key = new Key().setKeys(keyProperties);
// finish
return new EntityType().setName(ENTITY_TYPE_1_3.getName())
.setProperties(properties)
.setHasStream(true)
.setKey(key)
.setNavigationProperties(navigationProperties)
.setMapping(new Mapping().setMimeType("image/png"));
}
...
</code></pre>
<p>In addition it is necessary to extend the <code>getSchemas(&hellip;)</code> method with the according <code>EntityType</code> and <code>EntitySet</code> of the new Driver.</p>
<pre><code class="language-java">entityTypes.add(getEntityType(ENTITY_TYPE_1_3));
entitySets.add(getEntitySet(ENTITY_CONTAINER, ENTITY_SET_NAME_DRIVERS));
</code></pre>
<p>And at last following constants are added to the <code>MyEdmProvider</code> for cleaner code.</p>
<pre><code class="language-java"> static final String ENTITY_SET_NAME_DRIVERS = "Drivers";
static final String ENTITY_NAME_DRIVER = "Driver";
private static final FullQualifiedName ENTITY_TYPE_1_3 = new FullQualifiedName(NAMESPACE, ENTITY_NAME_DRIVER);
</code></pre>
<p><strong>Extend <code>MyODataSingleProcessor</code> with <code>readEntityMedia(uriInfo:GetMediaResourceUriInfo, contentType:String):ODataResponse</code> method</strong><br/>
All requests for media resources are done via the specified $value property in the URL (e.g. <em>.../MyODataSample.svc/Drivers(1)/$value</em>). Such a request will be dispatched to an <code>EntityMediaProcessor</code> which is in our case the <code>MyODataSingleProcessor</code> (inherited from <code>ODataSingleProcessor</code>).
To handle now such read requests for our media resources we override and implement the <code>readEntityMedia(uriInfo:GetMediaResourceUriInfo, contentType:String):ODataResponse</code> method.
For our scenario we simply have to validate the correct requested target <code>EntitySet</code>, get the key for requesting the data from our <code>DataStore</code> (which contains the binary data of our media resource), use the <code>EntityProvider</code> to write the data and at last build the <code>ODataResponse</code>.
Seems a lot but in code this are only these few lines:</p>
<pre><code class="language-java">@Override
public ODataResponse readEntityMedia(final GetMediaResourceUriInfo uriInfo, final String contentType) throws ODataException {
final EdmEntitySet entitySet = uriInfo.getTargetEntitySet();
if(ENTITY_SET_NAME_DRIVERS.equals(entitySet.getName())) {
int id = getKeyValue(uriInfo.getKeyPredicates().get(0));
byte[] image = dataStore.readDriverImage(entitySet, id);
if (image == null) {
throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
}
String mimeType = "image/png";
return ODataResponse.fromResponse(EntityProvider.writeBinary(mimeType, image)).build();
}
throw new ODataNotImplementedException();
}
</code></pre>
<p>With these extension it is possible to read the media resource, but for access to the Driver <code>EntitySet</code> and <code>Entity</code> the according read methods have to be extended.</p>
<p>** Extend existing <code>readEntitySet(...)</code> and <code>readEntity(...)</code> methods in <code>MyODataSingleProcessor</code> methods **<br/>
For access to the Driver as <code>Entity</code> and as <code>EntitySet</code> the according <code>readreadEntitySet(...)</code> and <code>readEntity(...)</code> methods have to be extended.</p>
<p>But its quite the same procedure as in the basic read. Validate the requested Entity, get the key for requesting the <code>DataStore</code> and write the result data via the <code>EntityProvider</code>.</p>
<p>The resulting extension for <code>readEntity(&hellip;)</code>:</p>
<pre><code class="language-java"> } else if (ENTITY_SET_NAME_DRIVERS.equals(entitySet.getName())) {
int id = getKeyValue(uriInfo.getKeyPredicates().get(0));
Map&lt;String, Object&gt; data = dataStore.getDriver(id);
if (data != null) {
URI serviceRoot = getContext().getPathInfo().getServiceRoot();
ODataEntityProviderPropertiesBuilder propertiesBuilder = EntityProviderWriteProperties.serviceRoot(serviceRoot);
return EntityProvider.writeEntry(contentType, entitySet, data, propertiesBuilder.build());
}
</code></pre>
<p>and <code>readEntitySet(&hellip;)</code>:</p>
<pre><code class="language-java"> } else if (ENTITY_SET_NAME_DRIVERS.equals(entitySet.getName())) {
return EntityProvider.writeFeed(contentType, entitySet, dataStore.getDrivers(), EntityProviderWriteProperties.serviceRoot(getContext().getPathInfo().getServiceRoot()).build());
</code></pre>
<p><strong>Conclusion for media resource extension</strong><br/>
After finishing all steps above the project can be built and deployed containing a Driver type which is a media link entry with associated media resource. <em>Congratulations.</em></p>
<p>For a more interesting sample and to update before learned knowledge about associations and <code>$expand</code> it is recommended to finish this HowTo with the creation of an association between a Driver and his Car with supported <code>$expand</code>.</p>
<p><strong>Extend Driver with association to Car</strong><br/>
For a more interesting sample we now create an association between a Driver and his Car.</p>
<p><strong>Extend Driver and Car in MyEdmProvider with a navigation property</strong><br/>
At first we introduce the necessary constants:</p>
<pre><code class="language-java"> private static final FullQualifiedName ASSOCIATION_DRIVER_CAR = new FullQualifiedName(NAMESPACE, "Driver_Car-Car_Driver");
private static final String ROLE_1_3 = "Car_Driver";
private static final String ROLE_3_1 = "Driver_Car";
private static final String ASSOCIATION_SET = "Cars_Manufacturers";
private static final String ASSOCIATION_SET_CARS_DRIVERS = "Cars_Drivers";
</code></pre>
<p>Then the <code>getSchemas()</code> in <code>MyEdmProvider</code> is extended with the new association:</p>
<pre><code class="language-java">associations.add(getAssociation(ASSOCIATION_DRIVER_CAR));
...
associationSets.add(getAssociationSet(ENTITY_CONTAINER, ASSOCIATION_DRIVER_CAR, ENTITY_SET_NAME_DRIVERS, ROLE_3_1));
</code></pre>
<p>Next step is the extension of the entity types in <code>getEntityType()</code> in <code>MyEdmProvider</code>.</p>
<p>For the Car:</p>
<pre><code class="language-java"> if (ENTITY_TYPE_1_1.getName().equals(edmFQName.getName())) {
...
navigationProperties.add(new NavigationProperty().setName("Driver")
.setRelationship(ASSOCIATION_DRIVER_CAR).setFromRole(ROLE_1_3).setToRole(ROLE_3_1));
&hellip;
}
</code></pre>
<p>And the Driver:</p>
<pre><code class="language-java"> if (ENTITY_TYPE_1_3.getName().equals(edmFQName.getName())) {
...
properties.add(new SimpleProperty().setName("CarId").setType(EdmSimpleTypeKind.Int32));
...
navigationProperties.add(new NavigationProperty().setName("Car").setRelationship(ASSOCIATION_DRIVER_CAR).setFromRole(ROLE_3_1).setToRole(ROLE_1_3));
...
}
</code></pre>
<p>At last the <code>getAssociation(&hellip;)</code> and <code>getAssociationSet(...)</code> has also to be extended and has to look like:</p>
<pre><code class="language-java">@Override
public Association getAssociation(FullQualifiedName edmFQName) throws ODataException {
if (NAMESPACE.equals(edmFQName.getNamespace())) {
if (ASSOCIATION_CAR_MANUFACTURER.getName().equals(edmFQName.getName())) {
return new Association().setName(ASSOCIATION_CAR_MANUFACTURER.getName())
.setEnd1(new AssociationEnd().setType(ENTITY_TYPE_1_1).setRole(ROLE_1_1).setMultiplicity(EdmMultiplicity.MANY))
.setEnd2(new AssociationEnd().setType(ENTITY_TYPE_1_2).setRole(ROLE_1_2).setMultiplicity(EdmMultiplicity.ONE));
} else if (ASSOCIATION_DRIVER_CAR.getName().equals(edmFQName.getName())) {
return new Association().setName(ASSOCIATION_DRIVER_CAR.getName())
.setEnd1(new AssociationEnd().setType(ENTITY_TYPE_1_1).setRole(ROLE_1_3).setMultiplicity(EdmMultiplicity.ONE))
.setEnd2(new AssociationEnd().setType(ENTITY_TYPE_1_3).setRole(ROLE_3_1).setMultiplicity(EdmMultiplicity.ONE));
}
}
return null;
}
@Override
public AssociationSet getAssociationSet(String entityContainer, FullQualifiedName association, String sourceEntitySetName, String sourceEntitySetRole) throws ODataException {
if (ENTITY_CONTAINER.equals(entityContainer)) {
if (ASSOCIATION_CAR_MANUFACTURER.equals(association)) {
return new AssociationSet().setName(ASSOCIATION_SET)
.setAssociation(ASSOCIATION_CAR_MANUFACTURER)
.setEnd1(new AssociationSetEnd().setRole(ROLE_1_2).setEntitySet(ENTITY_SET_NAME_MANUFACTURERS))
.setEnd2(new AssociationSetEnd().setRole(ROLE_1_1).setEntitySet(ENTITY_SET_NAME_CARS));
} else if (ASSOCIATION_DRIVER_CAR.equals(association)) {
return new AssociationSet().setName(ASSOCIATION_SET_CARS_DRIVERS)
.setAssociation(ASSOCIATION_DRIVER_CAR)
.setEnd1(new AssociationSetEnd().setRole(ROLE_3_1).setEntitySet(ENTITY_SET_NAME_DRIVERS))
.setEnd2(new AssociationSetEnd().setRole(ROLE_1_3).setEntitySet(ENTITY_SET_NAME_CARS));
}
}
return null;
}
</code></pre>
<p><strong>Extend existing <code>readreadEntitySet(...)</code> and <code>readEntity(...)</code> methods in <code>MyODataSingleProcessor</code></strong><br/>
For cleaner code we introduce at first following method in the <code>MyODataSingleProcessor</code> which validate if the uri contains the expected association.</p>
<pre><code class="language-java">private boolean isAssociation(GetEntityUriInfo uriInfo, String startName, String targetName) throws EdmException {
if(startName == null || targetName == null) {
return false;
}
EdmEntitySet startEntitySet = uriInfo.getStartEntitySet();
EdmEntitySet targetEntitySet = uriInfo.getTargetEntitySet();
return startName.equals(startEntitySet.getName()) &amp;&amp; targetName.equals(targetEntitySet.getName());
}
</code></pre>
<p>The procedure should be already familiar. At first it is checked for the correct association of the requested Entity, then the key for requesting the DataStore is get as well as the data and then result data is written via the <code>EntityProvider</code>.</p>
<pre><code class="language-java">} else if (uriInfo.getNavigationSegments().size() == 1) {
//navigation first level, simplified example for illustration purposes only
EdmEntitySet entitySet = uriInfo.getTargetEntitySet();
Map&lt;String, Object&gt; data = null;
if (ENTITY_SET_NAME_MANUFACTURERS.equals(entitySet.getName())) {
int carKey = getKeyValue(uriInfo.getKeyPredicates().get(0));
data = dataStore.getManufacturerFor(carKey);
} else if(isAssociation(uriInfo, ENTITY_SET_NAME_CARS, ENTITY_SET_NAME_DRIVERS)) {
int carKey = getKeyValue(uriInfo.getKeyPredicates().get(0));
data = dataStore.getDriverFor(carKey);
} else if(isAssociation(uriInfo, ENTITY_SET_NAME_DRIVERS, ENTITY_SET_NAME_CARS)) {
int driverKey = getKeyValue(uriInfo.getKeyPredicates().get(0));
data = dataStore.getCarFor(driverKey);
}
if(data != null) {
return EntityProvider.writeEntry(contentType, uriInfo.getTargetEntitySet(),
data, EntityProviderWriteProperties.serviceRoot(getContext().getPathInfo().getServiceRoot()).build());
}
throw new ODataNotFoundException(ODataNotFoundException.ENTITY);
}
</code></pre>
<p><strong>Add $expand support for Driver to/from Car association</strong><br/>
The last missing step is to add the <code>$expand</code> support for the new Driver to/from Car association.</p>
<p><strong>Extend MyCallback for Driver and Car association</strong><br/>
Add first the extension in the MyCallback for each entity is done in the <code>retrieveEntryResult()</code> method.
The procedure is similar to the Cars - Manufacturers association. At first it is checked for the correct association of the requested Entity, then the key for requesting the DataStore is get as well as the data and then result data is attached to the <code>WriteEntryCallbackResult</code>.</p>
<p>The resulting method extension is:</p>
<pre><code class="language-java">...
if(isNavigationFromTo(context, ENTITY_SET_NAME_CARS, ENTITY_NAME_DRIVER)) {
EntityProviderWriteProperties inlineProperties = EntityProviderWriteProperties.serviceRoot(serviceRoot)
.expandSelectTree(context.getCurrentExpandSelectTreeNode())
.build();
Map&lt;String, Object&gt; keys = context.extractKeyFromEntryData();
Integer carId = (Integer) keys.get("Id");
result.setEntryData(dataStore.getDriverFor(carId));
result.setInlineProperties(inlineProperties);
} else if(isNavigationFromTo(context, ENTITY_SET_NAME_DRIVERS, ENTITY_NAME_CAR)) {
EntityProviderWriteProperties inlineProperties = EntityProviderWriteProperties.serviceRoot(serviceRoot)
.expandSelectTree(context.getCurrentExpandSelectTreeNode())
.build();
Map&lt;String, Object&gt; keys = context.extractKeyFromEntryData();
Integer driverId = (Integer) keys.get("Id");
result.setEntryData(dataStore.getCarFor(driverId));
result.setInlineProperties(inlineProperties);
}
...
</code></pre>
<p><strong>Add registration of MyCallback for Driver and Car association</strong><br/>
After extension of <code>MyCallback</code> it is necessary to register a callback within the <code>readEntity()</code> in the <code>MyODataSingleProcessor</code>.</p>
<p>For the Driver we add the complete callback registration (code between the comments) which results in final code for the complete Driver Entity handling:</p>
<pre><code class="language-java">...
} else if (ENTITY_SET_NAME_DRIVERS.equals(entitySet.getName())) {
int id = getKeyValue(uriInfo.getKeyPredicates().get(0));
Map&lt;String, Object&gt; data = dataStore.getDriver(id);
if (data != null) {
URI serviceRoot = getContext().getPathInfo().getServiceRoot();
ODataEntityProviderPropertiesBuilder propertiesBuilder = EntityProviderWriteProperties.serviceRoot(serviceRoot);
// create and register callback
Map&lt;String, ODataCallback&gt; callbacks = new HashMap&lt;String, ODataCallback&gt;();
callbacks.put(ENTITY_NAME_CAR, new MyCallback(dataStore, serviceRoot));
ExpandSelectTreeNode expandSelectTreeNode = UriParser.createExpandSelectTree(uriInfo.getSelect(), uriInfo.getExpand());
propertiesBuilder.expandSelectTree(expandSelectTreeNode).callbacks(callbacks);
// end callback handling
return EntityProvider.writeEntry(contentType, entitySet, data, propertiesBuilder.build());
}
}
...
</code></pre>
<p>For the Car it is only necessary to add the single code line below to register the additional callback and enable the <code>$expand</code>:</p>
<pre><code class="language-java">if (ENTITY_SET_NAME_CARS.equals(entitySet.getName())) {
...
callbacks.put(ENTITY_NAME_DRIVER, new MyCallback(dataStore, serviceRoot));
...
}
</code></pre>
<p>Deploy, run and test
Like in the basic read scenario follow these steps:</p>
<ul>
<li>Build your project mvn clean install</li>
<li>Deploy in Web Application server. When using within Eclipse simply run the Web Application via Run As -&gt; Run on Server</li>
<li>After successful server start and deployment the following uris from the read scenario work as before:
<ul>
<li>Show the Manufacturers: <a href="http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Manufacturers">http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Manufacturers</a></li>
<li>Show one Manufacturer: <a href="http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Manufacturers(1)">http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Manufacturers(1)</a></li>
<li>Show the Cars: <a href="http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Cars">http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Cars</a></li>
<li>Show one Car: <a href="http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Cars(2)">http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Cars(2)</a></li>
<li>Show the related Manufacturer of a Car: <a href="http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Cars(2)/Manufacturer">http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Cars(2)/Manufacturer</a></li>
<li>Show the related Cars of a Manufacturer: <a href="http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Manufacturers(1)/Cars">http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Manufacturers(1)/Cars </a></li>
<li>Show Car with its Manufacturer: <a href="http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Cars(2)?$expand=Manufacturer">http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Cars(2)?$expand=Manufacturer </a></li>
<li>Show Manufacturer with its Cars: <a href="http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Manufacturers(1)?$expand=Cars">http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Manufacturers(1)?$expand=Cars </a></li>
</ul>
</li>
<li>And in addition we now can access the drivers with their media resource ($value) and the association to their car.
<ul>
<li>Show one Driver: <a href="http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Drivers(3)">http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Drivers(3)</a></li>
<li>Show Media Resource of Driver: <a href="http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Drivers(3)/$value">http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Drivers(3)/$value</a></li>
<li>Show Car of the Driver: <a href="http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Drivers(3)/Car">http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Drivers(3)/Car</a></li>
</ul>
</li>
<li>Show Driver with expanded Car: <a href="http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Drivers(3)?$expand=Car">http://localhost:8080/olingo.odata2.sample.cars.web/MyODataSample.svc/Drivers(3)?$expand=Car </a></li>
</ul>
<h3 id="conclusion">Conclusion<a class="headerlink" href="#conclusion" title="Permalink">&para;</a></h3>
<p>After finishing all steps of this tutorial your project contains three different entities with relations between them and one of them with media link entry and media resource support.</p>
<p>If something does not compile or run it is recommended to compare to the complete sample project source code in the <a href="apache-olingo-tutorial-adv_read_mediaresource">Olingo Tutorial 'Basic Read with Media Resource extension' Project</a>.
For more details about how to use/setup the project in the zip see section <em><strong>Shortcut</strong></em>.</p>
<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>