You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@olingo.apache.org by mi...@apache.org on 2014/02/24 13:54:18 UTC
svn commit: r1571269 -
/incubator/olingo/site/trunk/content/doc/tutorials/OlingoV2BasicClientSample.mdtext
Author: mibo
Date: Mon Feb 24 12:54:18 2014
New Revision: 1571269
URL: http://svn.apache.org/r1571269
Log:
CMS commit to olingo by mibo
Modified:
incubator/olingo/site/trunk/content/doc/tutorials/OlingoV2BasicClientSample.mdtext
Modified: incubator/olingo/site/trunk/content/doc/tutorials/OlingoV2BasicClientSample.mdtext
URL: http://svn.apache.org/viewvc/incubator/olingo/site/trunk/content/doc/tutorials/OlingoV2BasicClientSample.mdtext?rev=1571269&r1=1571268&r2=1571269&view=diff
==============================================================================
--- incubator/olingo/site/trunk/content/doc/tutorials/OlingoV2BasicClientSample.mdtext (original)
+++ incubator/olingo/site/trunk/content/doc/tutorials/OlingoV2BasicClientSample.mdtext Mon Feb 24 12:54:18 2014
@@ -22,7 +22,7 @@ This Tutorial shows how to use the Apach
Therefore it contains the [Explaining the Client](#start) section which explains how to implement the CRUD operations based on sample code and a [Client Quickstart Guide](#quickstart) which give a step by step guide to create a sample and server to see both together in action.
- * [Client Quickstart Guide](#quickstart): Get a running sample client and server within a few minutes (Requirements at least *Java 7 Runtime* and *Maven 3*)
+ * [Client Quickstart Guide](#quickstart): Get a running sample client and server within a few minutes (Requirements at least *Java 6 Runtime* and *Maven 3*)
* [Explaining the Client](#start): The actual *How To* with explanation and sample code for following use cases: [Read the Metadata](#readmetadata), [Read the Data](#readdata), [Create more Data](#createdata), [Update the Data](#updatedata) and [Delete the Data](#deletedata). After this *How To* the sample code from all samples can be put together and be executed against a Sample Service which is shown in the [Run the Client](#run) section.
---
@@ -30,7 +30,7 @@ Therefore it contains the [Explaining th
<a name="quickstart"></a>
### Client Quickstart Guide
With this Quickstart guide the runable sample client and an sample service is created within a few minutes.
-Therefore it just requires an installed *Java 7 Runtime*, *Maven 3* and an internet connection.
+Therefore it just requires an installed *Java 6 Runtime*, *Maven 3* and an internet connection.
1. Start in some folder (e.g. `Quickstart`) which is called our `$ROOT` in the steps below.
1. Create sample Client project ([more details](#projectstructure))
@@ -48,7 +48,7 @@ Therefore it just requires an installed
-DartifactId=my-car-service
-DarchetypeGroupId=org.apache.olingo
-DarchetypeArtifactId=olingo-odata2-sample-cars-annotation-archetype-incubating
- -DarchetypeVersion=1.1.0
+ -DarchetypeVersion=1.2.0-SNAPSHOT
</div>
3. Go into from archetype created folder `my-car-service` and just run `mvn` to start the Sample Service on a *Jetty Web Server* at [http://localhost:8080](http://localhost:8080).
4. Run `OlingoSampleApp` against sample Service ([more details](#runsample))
@@ -446,7 +446,7 @@ Between the interaction with the `Olingo
**Shortcut**
-Instead of copy and paste all code samples from above and the main sample method below in section [Copy and Paste](#copypaste) is the whole sample code as `OlingoSampleApp.java` available ([here](#sampleclient)) as well as a `pom.xml` ([here](#pom)) to set up a maven project which all necessary build information. Only requirements are an installed *Java 7 Runtime* and *Maven 3* environment.
+Instead of copy and paste all code samples from above and the main sample method below in section [Copy and Paste](#copypaste) is the whole sample code as `OlingoSampleApp.java` available ([here](#sampleclient)) as well as a `pom.xml` ([here](#pom)) to set up a maven project which all necessary build information. Only requirements are an installed *Java 6 Runtime* and *Maven 3* environment.
**Main sample method**
@@ -456,6 +456,9 @@ Instead of copy and paste all code sampl
String serviceUrl = "http://localhost:8080/MyFormula.svc";
String usedFormat = APPLICATION_JSON; // could also be APPLICATION_ATOM_XML
+
+ print("\n----- Generate sample data ------------------");
+ app.generateSampleData(serviceUrl);
print("\n----- Read Edm ------------------------------");
Edm edm = app.readEdm(serviceUrl);
@@ -511,6 +514,21 @@ Instead of copy and paste all code sampl
}
}
+**Genration of sample data**
+
+The `generateSampleData` method is used for creation of sample data at the *ODataService* based on the [Apache Olingo archetype sample service](#sampleservice)).
+
+ :::java
+ public void generateSampleData(String serviceUrl) throws MalformedURLException, IOException {
+ String url = serviceUrl.substring(0, serviceUrl.lastIndexOf(SEPARATOR));
+ HttpURLConnection connection = initializeConnection(url + INDEX, APPLICATION_FORM, HTTP_METHOD_POST);
+ String content = "genSampleData=true";
+ connection.getOutputStream().write(content.getBytes());
+ print("Generate response: " + checkStatus(connection));
+ connection.disconnect();
+ }
+
+
**Print methods**
The `print` methods are only for simplified print/write logging to some output channel. In the sample it is just the `System.out` stream.
@@ -566,7 +584,7 @@ To use the archtype and create this samp
-DartifactId=my-car-service \
-DarchetypeGroupId=org.apache.olingo \
-DarchetypeArtifactId=olingo-odata2-sample-cars-annotation-archetype-incubating \
- -DarchetypeVersion=1.1.0
+ -DarchetypeVersion=1.2.0-SNAPSHOT
In the generated sample project you now can simply run Maven with the default goal (run `mvn` in the shell) which compiles the sources and starts a *Jetty Web Server* at [http://localhost:8080](http://localhost:8080).
@@ -693,6 +711,7 @@ Maven project POM (`pom.xml`)
Complete `OlingoSampleApp` with `main` which can be *copy/pasted* into a `OlingoSampleApp.java`, then compiled and run.
+ :::java
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -712,7 +731,7 @@ Complete `OlingoSampleApp` with `main` w
* under the License.
******************************************************************************/
package org.apache.olingo.sample.client;
-
+
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -725,10 +744,11 @@ Complete `OlingoSampleApp` with `main` w
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
+ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
-
+
import org.apache.olingo.odata2.api.commons.HttpStatusCodes;
import org.apache.olingo.odata2.api.edm.Edm;
import org.apache.olingo.odata2.api.edm.EdmEntityContainer;
@@ -739,10 +759,11 @@ Complete `OlingoSampleApp` with `main` w
import org.apache.olingo.odata2.api.ep.EntityProviderReadProperties;
import org.apache.olingo.odata2.api.ep.EntityProviderWriteProperties;
import org.apache.olingo.odata2.api.ep.entry.ODataEntry;
+ import org.apache.olingo.odata2.api.ep.feed.ODataDeltaFeed;
import org.apache.olingo.odata2.api.ep.feed.ODataFeed;
import org.apache.olingo.odata2.api.exception.ODataException;
import org.apache.olingo.odata2.api.processor.ODataResponse;
-
+
/**
*
*/
@@ -758,10 +779,13 @@ Complete `OlingoSampleApp` with `main` w
public static final String APPLICATION_JSON = "application/json";
public static final String APPLICATION_XML = "application/xml";
public static final String APPLICATION_ATOM_XML = "application/atom+xml";
+ public static final String APPLICATION_FORM = "application/x-www-form-urlencoded";
public static final String METADATA = "$metadata";
-
+ public static final String INDEX = "/index.jsp";
+ public static final String SEPARATOR = "/";
+
public static final boolean PRINT_RAW_CONTENT = true;
-
+
public static void main(String[] paras) throws Exception {
OlingoSampleApp app = new OlingoSampleApp();
@@ -769,14 +793,17 @@ Complete `OlingoSampleApp` with `main` w
String serviceUrl = "http://localhost:8080/MyFormula.svc";
// String usedFormat = APPLICATION_ATOM_XML;
String usedFormat = APPLICATION_JSON;
-
+
+ print("\n----- Generate sample data ------------------------------");
+ app.generateSampleData(serviceUrl);
+
print("\n----- Read Edm ------------------------------");
Edm edm = app.readEdm(serviceUrl);
print("Read default EntityContainer: " + edm.getDefaultEntityContainer().getName());
-
+
print("\n----- Read Feed ------------------------------");
ODataFeed feed = app.readFeed(edm, serviceUrl, usedFormat, "Manufacturers");
-
+
print("Read: " + feed.getEntries().size() + " entries: ");
for (ODataEntry entry : feed.getEntries()) {
print("##########");
@@ -786,7 +813,7 @@ Complete `OlingoSampleApp` with `main` w
print("\n----- Read Entry ------------------------------");
ODataEntry entry = app.readEntry(edm, serviceUrl, usedFormat, "Manufacturers", "'1'");
- print("Single Entry: " + prettyPrint(entry));
+ print("Single Entry:\n" + prettyPrint(entry));
Map<String, Object> data = new HashMap<String, Object>();
data.put("Id", "123");
@@ -799,6 +826,13 @@ Complete `OlingoSampleApp` with `main` w
address.put("City", "Fairy City");
address.put("Country", "FarFarAway");
data.put("Address", address);
+
+ //
+ print("\n----- Read Entry with $expand ------------------------------");
+ ODataEntry entryExpanded = app.readEntry(edm, serviceUrl, usedFormat, "Manufacturers", "'1'", "Cars");
+ print("Single Entry with expanded Cars relation:\n" + prettyPrint(entryExpanded));
+
+ //
//
print("\n----- Create Entry ------------------------------");
ODataEntry createdEntry = app.createEntry(edm, serviceUrl, usedFormat, "Manufacturers", data);
@@ -823,11 +857,11 @@ Complete `OlingoSampleApp` with `main` w
print(e.getMessage());
}
}
-
+
private static void print(String content) {
System.out.println(content);
}
-
+
private static String prettyPrint(ODataEntry createdEntry) {
return prettyPrint(createdEntry.getProperties(), 0);
}
@@ -842,68 +876,93 @@ Complete `OlingoSampleApp` with `main` w
Object value = entry.getValue();
if(value instanceof Map) {
value = prettyPrint((Map<String, Object>)value, level+1);
- b.append("\n");
+ b.append(value).append("\n");
} else if(value instanceof Calendar) {
Calendar cal = (Calendar) value;
value = SimpleDateFormat.getInstance().format(cal.getTime());
+ b.append(value).append("\n");
+ } else if(value instanceof ODataDeltaFeed) {
+ ODataDeltaFeed feed = (ODataDeltaFeed) value;
+ List<ODataEntry> inlineEntries = feed.getEntries();
+ b.append("{");
+ for (ODataEntry oDataEntry : inlineEntries) {
+ value = prettyPrint((Map<String, Object>)oDataEntry.getProperties(), level+1);
+ b.append("\n[\n").append(value).append("\n],");
+ }
+ b.deleteCharAt(b.length()-1);
+ intend(b, level);
+ b.append("}\n");
+ } else {
+ b.append(value).append("\n");
}
- b.append(value).append("\n");
}
// remove last line break
b.deleteCharAt(b.length()-1);
return b.toString();
}
-
+
private static void intend(StringBuilder builder, int intendLevel) {
for (int i = 0; i < intendLevel; i++) {
builder.append(" ");
}
}
-
+
+ public void generateSampleData(String serviceUrl) throws MalformedURLException, IOException {
+ String url = serviceUrl.substring(0, serviceUrl.lastIndexOf(SEPARATOR));
+ HttpURLConnection connection = initializeConnection(url + INDEX, APPLICATION_FORM, HTTP_METHOD_POST);
+ String content = "genSampleData=true";
+ connection.getOutputStream().write(content.getBytes());
+ print("Generate response: " + checkStatus(connection));
+ connection.disconnect();
+ }
+
public Edm readEdm(String serviceUrl) throws IOException, ODataException {
- InputStream content = execute(serviceUrl + "/" + METADATA, APPLICATION_XML, HTTP_METHOD_GET);
+ InputStream content = execute(serviceUrl + SEPARATOR + METADATA, APPLICATION_XML, HTTP_METHOD_GET);
return EntityProvider.readMetadata(content, false);
}
-
+
public ODataFeed readFeed(Edm edm, String serviceUri, String contentType, String entitySetName)
throws IOException, ODataException {
EdmEntityContainer entityContainer = edm.getDefaultEntityContainer();
String absolutUri = createUri(serviceUri, entitySetName, null);
-
+
InputStream content = execute(absolutUri, contentType, HTTP_METHOD_GET);
return EntityProvider.readFeed(contentType,
entityContainer.getEntitySet(entitySetName),
content,
EntityProviderReadProperties.init().build());
}
-
+
public ODataEntry readEntry(Edm edm, String serviceUri, String contentType, String entitySetName, String keyValue)
throws IOException, ODataException {
+ return readEntry(edm, serviceUri, contentType, entitySetName, keyValue, null);
+ }
+
+ public ODataEntry readEntry(Edm edm, String serviceUri, String contentType,
+ String entitySetName, String keyValue, String expandRelationName)
+ throws IOException, ODataException {
// working with the default entity container
EdmEntityContainer entityContainer = edm.getDefaultEntityContainer();
- // create absolute uri based on service uri, entity set name and key property value
- String absolutUri = createUri(serviceUri, entitySetName, keyValue);
-
+ // create absolute uri based on service uri, entity set name with its key property value and optional expanded relation name
+ String absolutUri = createUri(serviceUri, entitySetName, keyValue, expandRelationName);
+
InputStream content = execute(absolutUri, contentType, HTTP_METHOD_GET);
-
+
return EntityProvider.readEntry(contentType,
entityContainer.getEntitySet(entitySetName),
content,
EntityProviderReadProperties.init().build());
}
-
+
private InputStream logRawContent(String prefix, InputStream content, String postfix) throws IOException {
if(PRINT_RAW_CONTENT) {
byte[] buffer = streamToArray(content);
- content.close();
-
print(prefix + new String(buffer) + postfix);
-
return new ByteArrayInputStream(buffer);
}
return content;
}
-
+
private byte[] streamToArray(InputStream stream) throws IOException {
byte[] result = new byte[0];
byte[] tmp = new byte[8192];
@@ -915,9 +974,10 @@ Complete `OlingoSampleApp` with `main` w
result = innerTmp;
readCount = stream.read(tmp);
}
+ stream.close();
return result;
}
-
+
public ODataEntry createEntry(Edm edm, String serviceUri, String contentType,
String entitySetName, Map<String, Object> data) throws Exception {
String absolutUri = createUri(serviceUri, entitySetName, null);
@@ -929,24 +989,24 @@ Complete `OlingoSampleApp` with `main` w
String absolutUri = createUri(serviceUri, entitySetName, id);
writeEntity(edm, absolutUri, entitySetName, data, contentType, HTTP_METHOD_PUT);
}
-
+
public HttpStatusCodes deleteEntry(String serviceUri, String entityName, String id) throws IOException {
String absolutUri = createUri(serviceUri, entityName, id);
HttpURLConnection connection = connect(absolutUri, APPLICATION_XML, HTTP_METHOD_DELETE);
return HttpStatusCodes.fromStatusCode(connection.getResponseCode());
}
-
+
private ODataEntry writeEntity(Edm edm, String absolutUri, String entitySetName,
Map<String, Object> data, String contentType, String httpMethod)
throws EdmException, MalformedURLException, IOException, EntityProviderException, URISyntaxException {
-
+
HttpURLConnection connection = initializeConnection(absolutUri, contentType, httpMethod);
-
+
EdmEntityContainer entityContainer = edm.getDefaultEntityContainer();
EdmEntitySet entitySet = entityContainer.getEntitySet(entitySetName);
URI rootUri = new URI(entitySetName);
-
+
EntityProviderWriteProperties properties = EntityProviderWriteProperties.serviceRoot(rootUri).build();
// serialize data into ODataResponse object
ODataResponse response = EntityProvider.writeEntry(contentType, entitySet, data, properties);
@@ -956,28 +1016,28 @@ Complete `OlingoSampleApp` with `main` w
byte[] buffer = streamToArray((InputStream) entity);
// just for logging
String content = new String(buffer);
- print(httpMethod + " request:\n " + content + "\n");
+ print(httpMethod + " request on uri '" + absolutUri + "' with content:\n " + content + "\n");
//
connection.getOutputStream().write(buffer);
}
-
+
// if a entity is created (via POST request) the response body contains the new created entity
ODataEntry entry = null;
HttpStatusCodes statusCode = HttpStatusCodes.fromStatusCode(connection.getResponseCode());
if(statusCode == HttpStatusCodes.CREATED) {
// get the content as InputStream and de-serialize it into an ODataEntry object
InputStream content = connection.getInputStream();
- content = logRawContent(httpMethod + " response:\n ", content, "\n");
+ content = logRawContent(httpMethod + " request on uri '" + absolutUri + "' with content:\n ", content, "\n");
entry = EntityProvider.readEntry(contentType,
entitySet, content, EntityProviderReadProperties.init().build());
}
-
+
//
connection.disconnect();
return entry;
}
-
+
private HttpStatusCodes checkStatus(HttpURLConnection connection) throws IOException {
HttpStatusCodes httpStatusCode = HttpStatusCodes.fromStatusCode(connection.getResponseCode());
if (400 <= httpStatusCode.getStatusCode() && httpStatusCode.getStatusCode() <= 599) {
@@ -985,47 +1045,55 @@ Complete `OlingoSampleApp` with `main` w
}
return httpStatusCode;
}
-
+
private String createUri(String serviceUri, String entitySetName, String id) {
- final StringBuilder absolutUri = new StringBuilder(serviceUri).append("/").append(entitySetName);
+ return createUri(serviceUri, entitySetName, id, null);
+ }
+
+ private String createUri(String serviceUri, String entitySetName, String id, String expand) {
+ final StringBuilder absolutUri = new StringBuilder(serviceUri).append(SEPARATOR).append(entitySetName);
if(id != null) {
absolutUri.append("(").append(id).append(")");
}
+ if(expand != null) {
+ absolutUri.append("/?$expand=").append(expand);
+ }
return absolutUri.toString();
}
-
+
private InputStream execute(String relativeUri, String contentType, String httpMethod) throws IOException {
HttpURLConnection connection = initializeConnection(relativeUri, contentType, httpMethod);
-
+
connection.connect();
checkStatus(connection);
-
+
InputStream content = connection.getInputStream();
- content = logRawContent(httpMethod + " request:\n ", content, "\n");
+ content = logRawContent(httpMethod + " request on uri '" + relativeUri + "' with content:\n ", content, "\n");
return content;
}
-
+
private HttpURLConnection connect(String relativeUri, String contentType, String httpMethod) throws IOException {
HttpURLConnection connection = initializeConnection(relativeUri, contentType, httpMethod);
-
+
connection.connect();
checkStatus(connection);
-
+
return connection;
}
-
+
private HttpURLConnection initializeConnection(String absolutUri, String contentType, String httpMethod)
throws MalformedURLException, IOException {
URL url = new URL(absolutUri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
-
+
connection.setRequestMethod(httpMethod);
connection.setRequestProperty(HTTP_HEADER_ACCEPT, contentType);
if(HTTP_METHOD_POST.equals(httpMethod) || HTTP_METHOD_PUT.equals(httpMethod)) {
connection.setDoOutput(true);
connection.setRequestProperty(HTTP_HEADER_CONTENT_TYPE, contentType);
}
-
+
return connection;
}
- }
\ No newline at end of file
+ }
+
\ No newline at end of file