[OLINGO-205, OLINGO-175] provided JSON integration tests + refactoring and fixes

This commit is contained in:
fmartelli 2014-03-31 17:16:44 +02:00
parent de591bb583
commit c73772f041
43 changed files with 557 additions and 1042 deletions

View File

@ -24,8 +24,6 @@ import org.apache.olingo.fit.utils.AbstractJSONUtilities;
import org.apache.olingo.fit.utils.ODataVersion;
import org.apache.olingo.fit.utils.FSManager;
import static org.apache.olingo.fit.utils.Constants.*;
import org.apache.olingo.fit.methods.MERGE;
import org.apache.olingo.fit.methods.PATCH;
import org.apache.olingo.fit.utils.AbstractUtilities;
@ -57,6 +55,7 @@ import javax.ws.rs.core.Response;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.olingo.fit.utils.ConstantKey;
import org.apache.olingo.fit.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -71,7 +70,6 @@ public abstract class AbstractServices {
private static final Set<ODataVersion> INITIALIZED = EnumSet.noneOf(ODataVersion.class);
protected abstract ODataVersion getVersion();
protected final AbstractXMLUtilities xml;
protected final AbstractJSONUtilities json;
@ -107,7 +105,8 @@ public abstract class AbstractServices {
}
return xml.createResponse(
FSManager.instance(getVersion()).readFile(SERVICES, acceptType), null, acceptType);
FSManager.instance(getVersion()).readFile(Constants.get(getVersion(), ConstantKey.SERVICES), acceptType),
null, acceptType);
} catch (Exception e) {
return xml.createFaultResponse(accept, e);
}
@ -122,7 +121,7 @@ public abstract class AbstractServices {
@Path("/$metadata")
@Produces("application/xml")
public Response getMetadata() {
return getMetadata(METADATA);
return getMetadata(Constants.get(getVersion(), ConstantKey.METADATA));
}
/**
@ -134,7 +133,7 @@ public abstract class AbstractServices {
@Path("/large/$metadata")
@Produces("application/xml")
public Response getLargeMetadata() {
return getMetadata("large" + StringUtils.capitalize(METADATA));
return getMetadata("large" + StringUtils.capitalize(Constants.get(getVersion(), ConstantKey.METADATA)));
}
protected Response getMetadata(final String filename) {
@ -150,7 +149,7 @@ public abstract class AbstractServices {
// public Response getEntityReference(@QueryParam("$id") String id){
// return null;
// }
/**
* Retrieve entity reference sample.
*
@ -176,7 +175,8 @@ public abstract class AbstractServices {
final String filename = Base64.encodeBase64String(path.getBytes("UTF-8"));
return utils.getValue().createResponse(
FSManager.instance(getVersion()).readFile(Constants.REF + File.separatorChar + filename, utils.getKey()),
FSManager.instance(getVersion()).readFile(Constants.get(getVersion(), ConstantKey.REF)
+ File.separatorChar + filename, utils.getKey()),
null,
utils.getKey());
} catch (Exception e) {
@ -419,15 +419,20 @@ public abstract class AbstractServices {
builder.append(basePath);
if (StringUtils.isNotBlank(orderby)) {
builder.append(ORDERBY).append(File.separatorChar).append(orderby).append(File.separatorChar);
builder.append(Constants.get(getVersion(), ConstantKey.ORDERBY)).append(File.separatorChar).
append(orderby).append(File.separatorChar);
}
if (StringUtils.isNotBlank(filter)) {
builder.append(FILTER).append(File.separatorChar).append(filter.replaceAll("/", "."));
builder.append(Constants.get(getVersion(), ConstantKey.FILTER)).append(File.separatorChar).
append(filter.replaceAll("/", "."));
} else if (StringUtils.isNotBlank(skiptoken)) {
builder.append(SKIP_TOKEN).append(File.separatorChar).append(skiptoken);
builder.append(Constants.get(getVersion(), ConstantKey.SKIP_TOKEN)).append(File.separatorChar).
append(skiptoken);
} else {
builder.append(Commons.getLinkInfo().get(getVersion()).isSingleton(name) ? ENTITY : FEED);
builder.append(Commons.getLinkInfo().get(getVersion()).isSingleton(name)
? Constants.get(getVersion(), ConstantKey.ENTITY)
: Constants.get(getVersion(), ConstantKey.FEED));
}
InputStream feed = FSManager.instance(getVersion()).readFile(builder.toString(), acceptType);
@ -524,7 +529,8 @@ public abstract class AbstractServices {
if (keyAsSegment) {
entity = utils.getValue().addEditLink(
entity, entitySetName, Constants.DEFAULT_SERVICE_URL + entitySetName + "/" + entityId);
entity, entitySetName,
Constants.get(getVersion(), ConstantKey.DEFAULT_SERVICE_URL) + entitySetName + "/" + entityId);
}
if (StringUtils.isNotBlank(select)) {
@ -589,7 +595,7 @@ public abstract class AbstractServices {
final String basePath =
entitySetName + File.separatorChar + Commons.getEntityKey(entityId) + File.separatorChar;
FSManager.instance(getVersion()).deleteFile(basePath + ENTITY);
FSManager.instance(getVersion()).deleteFile(basePath + Constants.get(getVersion(), ConstantKey.ENTITY));
return xml.createResponse(null, null, null, Response.Status.NO_CONTENT);
} catch (Exception e) {
@ -1012,7 +1018,7 @@ public abstract class AbstractServices {
final String basePath = Commons.getEntityBasePath(entitySetName, entityId);
InputStream stream = FSManager.instance(getVersion()).readFile(
basePath + ENTITY, acceptType == null || acceptType == Accept.TEXT
basePath + Constants.get(getVersion(), ConstantKey.ENTITY), acceptType == null || acceptType == Accept.TEXT
? Accept.XML : acceptType);
final AbstractUtilities utils = getUtilities(acceptType);

View File

@ -23,7 +23,8 @@ import org.apache.olingo.fit.utils.XHTTPMethodInterceptor;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.apache.cxf.interceptor.InInterceptors;
import static org.apache.olingo.fit.utils.Constants.METADATA;
import org.apache.olingo.fit.utils.ConstantKey;
import org.apache.olingo.fit.utils.Constants;
@Path("/V40/NorthWind.svc")
@InInterceptors(classes = XHTTPMethodInterceptor.class)
@ -40,7 +41,7 @@ public class V4NorthWind extends AbstractServices {
@Override
public Response getMetadata() {
return getMetadata("northwind-" + METADATA);
return getMetadata("northwind-" + Constants.get(getVersion(), ConstantKey.METADATA));
}
}

View File

@ -23,7 +23,8 @@ import org.apache.olingo.fit.utils.XHTTPMethodInterceptor;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.apache.cxf.interceptor.InInterceptors;
import static org.apache.olingo.fit.utils.Constants.METADATA;
import org.apache.olingo.fit.utils.ConstantKey;
import org.apache.olingo.fit.utils.Constants;
import org.apache.olingo.fit.utils.ResolvingReferencesInterceptor;
@Path("/V40/NorthWindExt.svc")
@ -41,7 +42,7 @@ public class V4NorthWindExt extends AbstractServices {
@Override
public Response getMetadata() {
return getMetadata("northwindExt-" + METADATA);
return getMetadata("northwindExt-" + Constants.get(getVersion(), ConstantKey.METADATA));
}
}

View File

@ -18,8 +18,6 @@
*/
package org.apache.olingo.fit.utils;
import static org.apache.olingo.fit.utils.Constants.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
@ -61,7 +59,7 @@ public abstract class AbstractJSONUtilities extends AbstractUtilities {
IOUtils.closeQuietly(is);
for (String link : links) {
srcNode.set(link + JSON_NAVIGATION_SUFFIX,
srcNode.set(link + Constants.get(version, ConstantKey.JSON_NAVIGATION_SUFFIX),
new TextNode(Commons.getLinksURI(version, entitySetName, entitykey, link)));
}
@ -81,10 +79,10 @@ public abstract class AbstractJSONUtilities extends AbstractUtilities {
while (fieldIter.hasNext()) {
final String field = fieldIter.next();
if (field.endsWith(JSON_NAVIGATION_BIND_SUFFIX)
|| field.endsWith(JSON_NAVIGATION_SUFFIX)
|| field.endsWith(JSON_MEDIA_SUFFIX)
|| field.endsWith(JSON_EDITLINK_NAME)) {
if (field.endsWith(Constants.get(version, ConstantKey.JSON_NAVIGATION_BIND_SUFFIX))
|| field.endsWith(Constants.get(version, ConstantKey.JSON_NAVIGATION_SUFFIX))
|| field.endsWith(Constants.get(version, ConstantKey.JSON_MEDIA_SUFFIX))
|| field.endsWith(Constants.get(version, ConstantKey.JSON_EDITLINK_NAME))) {
if (field.indexOf('@') > 0) {
links.add(field.substring(0, field.indexOf('@')));
} else {
@ -113,7 +111,7 @@ public abstract class AbstractJSONUtilities extends AbstractUtilities {
while (fieldIter.hasNext()) {
final Map.Entry<String, JsonNode> field = fieldIter.next();
if (field.getKey().endsWith(JSON_NAVIGATION_BIND_SUFFIX)) {
if (field.getKey().endsWith(Constants.get(version, ConstantKey.JSON_NAVIGATION_BIND_SUFFIX))) {
final String title = field.getKey().substring(0, field.getKey().indexOf('@'));
final List<String> hrefs = new ArrayList<String>();
if (field.getValue().isArray()) {
@ -148,17 +146,17 @@ public abstract class AbstractJSONUtilities extends AbstractUtilities {
if (links != null) {
for (String linkTitle : links.getLinkNames()) {
// normalize link
srcNode.remove(linkTitle + JSON_NAVIGATION_BIND_SUFFIX);
srcNode.remove(linkTitle + Constants.get(version, ConstantKey.JSON_NAVIGATION_BIND_SUFFIX));
srcNode.set(
linkTitle + JSON_NAVIGATION_SUFFIX,
linkTitle + Constants.get(version, ConstantKey.JSON_NAVIGATION_SUFFIX),
new TextNode(String.format("%s(%s)/%s", entitySetName, entityKey, linkTitle)));
}
for (String linkTitle : links.getInlineNames()) {
// normalize link if exist; declare a new one if missing
srcNode.remove(linkTitle + JSON_NAVIGATION_BIND_SUFFIX);
srcNode.remove(linkTitle + Constants.get(version, ConstantKey.JSON_NAVIGATION_BIND_SUFFIX));
srcNode.set(
linkTitle + JSON_NAVIGATION_SUFFIX,
linkTitle + Constants.get(version, ConstantKey.JSON_NAVIGATION_SUFFIX),
new TextNode(String.format("%s(%s)/%s", entitySetName, entityKey, linkTitle)));
// remove inline
@ -170,8 +168,8 @@ public abstract class AbstractJSONUtilities extends AbstractUtilities {
}
srcNode.set(
JSON_EDITLINK_NAME,
new TextNode(Constants.DEFAULT_SERVICE_URL + entitySetName + "(" + entityKey + ")"));
Constants.get(version, ConstantKey.JSON_EDITLINK_NAME), new TextNode(
Constants.get(version, ConstantKey.DEFAULT_SERVICE_URL) + entitySetName + "(" + entityKey + ")"));
return IOUtils.toInputStream(srcNode.toString());
}
@ -190,8 +188,9 @@ public abstract class AbstractJSONUtilities extends AbstractUtilities {
final String entitySetName, final String entityId, final List<String> path, final String edmType)
throws Exception {
final InputStream src =
fsManager.readFile(Commons.getEntityBasePath(entitySetName, entityId) + ENTITY, Accept.JSON_FULLMETA);
final InputStream src = fsManager.readFile(
Commons.getEntityBasePath(entitySetName, entityId) + Constants.get(version, ConstantKey.ENTITY),
Accept.JSON_FULLMETA);
final ObjectMapper mapper = new ObjectMapper();
final JsonNode srcNode = mapper.readTree(src);
@ -199,7 +198,9 @@ public abstract class AbstractJSONUtilities extends AbstractUtilities {
final ObjectNode propertyNode = new ObjectNode(JsonNodeFactory.instance);
if (StringUtils.isNotBlank(edmType)) {
propertyNode.put(JSON_ODATAMETADATA_NAME, ODATA_METADATA_PREFIX + edmType);
propertyNode.put(Constants.get(
version, ConstantKey.JSON_ODATAMETADATA_NAME),
Constants.get(version, ConstantKey.ODATA_METADATA_PREFIX) + edmType);
}
JsonNode jsonNode = getProperty(srcNode, path);
@ -241,7 +242,7 @@ public abstract class AbstractJSONUtilities extends AbstractUtilities {
final ObjectMapper mapper = new ObjectMapper();
final JsonNode srcNode = mapper.readTree(src);
((ObjectNode) srcNode).put(ODATA_COUNT_NAME, count);
((ObjectNode) srcNode).put(Constants.get(version, ConstantKey.ODATA_COUNT_NAME), count);
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
mapper.writeValue(bos, srcNode);
@ -258,14 +259,14 @@ public abstract class AbstractJSONUtilities extends AbstractUtilities {
final ObjectNode res;
final JsonNode value = node.get(JSON_VALUE_NAME);
final JsonNode value = node.get(Constants.get(version, ConstantKey.JSON_VALUE_NAME));
if (value.isArray()) {
res = mapper.createObjectNode();
res.set("value", value);
final JsonNode next = node.get(JSON_NEXTLINK_NAME);
final JsonNode next = node.get(Constants.get(version, ConstantKey.JSON_NEXTLINK_NAME));
if (next != null) {
res.set(JSON_NEXTLINK_NAME, next);
res.set(Constants.get(version, ConstantKey.JSON_NEXTLINK_NAME), next);
}
} else {
res = (ObjectNode) value;
@ -286,18 +287,18 @@ public abstract class AbstractJSONUtilities extends AbstractUtilities {
final ObjectNode srcNode = (ObjectNode) mapper.readTree(src);
final Set<String> retain = new HashSet<String>();
retain.add(JSON_ID_NAME);
retain.add(JSON_TYPE_NAME);
retain.add(JSON_EDITLINK_NAME);
retain.add(JSON_NEXTLINK_NAME);
retain.add(JSON_ODATAMETADATA_NAME);
retain.add(JSON_VALUE_NAME);
retain.add(Constants.get(version, ConstantKey.JSON_ID_NAME));
retain.add(Constants.get(version, ConstantKey.JSON_TYPE_NAME));
retain.add(Constants.get(version, ConstantKey.JSON_EDITLINK_NAME));
retain.add(Constants.get(version, ConstantKey.JSON_NEXTLINK_NAME));
retain.add(Constants.get(version, ConstantKey.JSON_ODATAMETADATA_NAME));
retain.add(Constants.get(version, ConstantKey.JSON_VALUE_NAME));
for (String name : propertyNames) {
retain.add(name);
retain.add(name + JSON_NAVIGATION_SUFFIX);
retain.add(name + JSON_MEDIA_SUFFIX);
retain.add(name + JSON_TYPE_SUFFIX);
retain.add(name + Constants.get(version, ConstantKey.JSON_NAVIGATION_SUFFIX));
retain.add(name + Constants.get(version, ConstantKey.JSON_MEDIA_SUFFIX));
retain.add(name + Constants.get(version, ConstantKey.JSON_TYPE_SUFFIX));
}
srcNode.retain(retain);
@ -344,10 +345,11 @@ public abstract class AbstractJSONUtilities extends AbstractUtilities {
bos.write("]".getBytes());
}
node.set(JSON_VALUE_NAME, mapper.readTree(new ByteArrayInputStream(bos.toByteArray())));
node.set(Constants.get(version, ConstantKey.JSON_VALUE_NAME),
mapper.readTree(new ByteArrayInputStream(bos.toByteArray())));
if (StringUtils.isNotBlank(next)) {
node.set(JSON_NEXTLINK_NAME, new TextNode(next));
node.set(Constants.get(version, ConstantKey.JSON_NEXTLINK_NAME), new TextNode(next));
}
return IOUtils.toInputStream(node.toString());
@ -362,15 +364,15 @@ public abstract class AbstractJSONUtilities extends AbstractUtilities {
final ObjectNode toBeChangedNode = (ObjectNode) mapper.readTree(toBeChanged);
final ObjectNode replacementNode = (ObjectNode) mapper.readTree(replacement);
if (toBeChangedNode.get(linkName + JSON_NAVIGATION_SUFFIX) == null) {
if (toBeChangedNode.get(linkName + Constants.get(version, ConstantKey.JSON_NAVIGATION_SUFFIX)) == null) {
throw new NotFoundException();
}
toBeChangedNode.set(linkName, replacementNode.get(JSON_VALUE_NAME));
toBeChangedNode.set(linkName, replacementNode.get(Constants.get(version, ConstantKey.JSON_VALUE_NAME)));
final JsonNode next = replacementNode.get(linkName + JSON_NEXTLINK_NAME);
final JsonNode next = replacementNode.get(linkName + Constants.get(version, ConstantKey.JSON_NEXTLINK_NAME));
if (next != null) {
toBeChangedNode.set(linkName + JSON_NEXTLINK_SUFFIX, next);
toBeChangedNode.set(linkName + Constants.get(version, ConstantKey.JSON_NEXTLINK_SUFFIX), next);
}
return IOUtils.toInputStream(toBeChangedNode.toString());
@ -437,7 +439,7 @@ public abstract class AbstractJSONUtilities extends AbstractUtilities {
}
}
final JsonNode next = srcNode.get(JSON_NEXTLINK_NAME);
final JsonNode next = srcNode.get(Constants.get(version, ConstantKey.JSON_NEXTLINK_NAME));
return new SimpleEntry<String, List<String>>(next == null ? null : next.asText(), links);
}
@ -449,7 +451,7 @@ public abstract class AbstractJSONUtilities extends AbstractUtilities {
final ObjectNode srcNode = (ObjectNode) mapper.readTree(content);
IOUtils.closeQuietly(content);
srcNode.set(JSON_EDITLINK_NAME, new TextNode(href));
srcNode.set(Constants.get(version, ConstantKey.JSON_EDITLINK_NAME), new TextNode(href));
return IOUtils.toInputStream(srcNode.toString());
}

View File

@ -19,7 +19,6 @@
package org.apache.olingo.fit.utils;
import static org.apache.olingo.fit.utils.Commons.sequence;
import static org.apache.olingo.fit.utils.Constants.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
@ -134,7 +133,8 @@ public abstract class AbstractUtilities {
// 0. Get the path
// -----------------------------------------
final String path =
entitySetName + File.separatorChar + Commons.getEntityKey(key) + File.separatorChar + ENTITY;
entitySetName + File.separatorChar + Commons.getEntityKey(key) + File.separatorChar
+ Constants.get(version, ConstantKey.ENTITY);
// -----------------------------------------
// -----------------------------------------
@ -229,7 +229,7 @@ public abstract class AbstractUtilities {
// -----------------------------------------
final FileObject fo = fsManager.putInMemory(
normalizedEntity,
fsManager.getAbsolutePath(path + ENTITY, getDefaultFormat()));
fsManager.getAbsolutePath(path + Constants.get(version, ConstantKey.ENTITY), getDefaultFormat()));
// -----------------------------------------
// -----------------------------------------
@ -282,7 +282,8 @@ public abstract class AbstractUtilities {
// -----------------------------------------
// 1. save the media entity value
// -----------------------------------------
fsManager.putInMemory(is, fsManager.getAbsolutePath(path + MEDIA_CONTENT_FILENAME, null));
fsManager.putInMemory(is, fsManager.getAbsolutePath(path
+ Constants.get(version, ConstantKey.MEDIA_CONTENT_FILENAME), null));
IOUtils.closeQuietly(is);
// -----------------------------------------
@ -291,13 +292,13 @@ public abstract class AbstractUtilities {
// -----------------------------------------
final String entityURI = Commons.getEntityURI(entitySetName, entityKey);
String entity = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<entry xml:base=\"" + DEFAULT_SERVICE_URL + "\" "
+ "<entry xml:base=\"" + Constants.get(version, ConstantKey.DEFAULT_SERVICE_URL) + "\" "
+ "xmlns=\"http://www.w3.org/2005/Atom\" "
+ "xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\" "
+ "xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\" "
+ "xmlns:georss=\"http://www.georss.org/georss\" "
+ "xmlns:gml=\"http://www.opengis.net/gml\">"
+ "<id>" + DEFAULT_SERVICE_URL + entityURI + "</id>"
+ "<id>" + Constants.get(version, ConstantKey.DEFAULT_SERVICE_URL) + entityURI + "</id>"
+ "<category term=\"Microsoft.Test.OData.Services.AstoriaDefaultService." + entitySetName + "\" "
+ "scheme=\"http://schemas.microsoft.com/ado/2007/08/dataservices/scheme\" />"
+ "<link rel=\"edit\" title=\"Car\" href=\"" + entityURI + "\" />"
@ -310,16 +311,18 @@ public abstract class AbstractUtilities {
+ "</entry>";
fsManager.putInMemory(
IOUtils.toInputStream(entity), fsManager.getAbsolutePath(path + ENTITY, Accept.ATOM));
IOUtils.toInputStream(entity),
fsManager.getAbsolutePath(path + Constants.get(version, ConstantKey.ENTITY), Accept.ATOM));
// -----------------------------------------
// -----------------------------------------
// 3. save entity as json
// -----------------------------------------
entity = "{"
+ "\"odata.metadata\": \"" + DEFAULT_SERVICE_URL + "/$metadata#" + entitySetName + "/@Element\","
+ "\"odata.metadata\": \"" + Constants.get(version, ConstantKey.DEFAULT_SERVICE_URL)
+ "/$metadata#" + entitySetName + "/@Element\","
+ "\"odata.type\": \"Microsoft.Test.OData.Services.AstoriaDefaultService." + entitySetName + "\","
+ "\"odata.id\": \"" + DEFAULT_SERVICE_URL + entityURI + "\","
+ "\"odata.id\": \"" + Constants.get(version, ConstantKey.DEFAULT_SERVICE_URL) + entityURI + "\","
+ "\"odata.editLink\": \"" + entityURI + "\","
+ "\"odata.mediaEditLink\": \"" + entityURI + "/$value\","
+ "\"odata.mediaReadLink\": \"" + entityURI + "/$value\","
@ -328,7 +331,8 @@ public abstract class AbstractUtilities {
+ "\"Description\": null" + "}";
fsManager.putInMemory(
IOUtils.toInputStream(entity), fsManager.getAbsolutePath(path + ENTITY, Accept.JSON_FULLMETA));
IOUtils.toInputStream(entity), fsManager.getAbsolutePath(path + Constants.get(version, ConstantKey.ENTITY),
Accept.JSON_FULLMETA));
// -----------------------------------------
return readEntity(entitySetName, entityKey, getDefaultFormat()).getValue();
@ -376,7 +380,7 @@ public abstract class AbstractUtilities {
final InputStream entity, final String etag, final Accept accept, final Response.Status status) {
final Response.ResponseBuilder builder = Response.ok();
if (version == ODataVersion.v3) {
builder.header(ODATA_SERVICE_VERSION, version.getVersion() + ";");
builder.header(Constants.get(version, ConstantKey.ODATA_SERVICE_VERSION), version.getVersion() + ";");
}
if (StringUtils.isNotBlank(etag)) {
@ -426,7 +430,7 @@ public abstract class AbstractUtilities {
final Response.ResponseBuilder builder = Response.serverError();
if (version == ODataVersion.v3) {
builder.header(ODATA_SERVICE_VERSION, version.getVersion() + ";");
builder.header(Constants.get(version, ConstantKey.ODATA_SERVICE_VERSION), version + ";");
}
final String ext;
@ -612,7 +616,7 @@ public abstract class AbstractUtilities {
final String basePath =
entitySetName + File.separatorChar + Commons.getEntityKey(entityId) + File.separatorChar
+ LINKS_FILE_PATH + File.separatorChar;
+ Constants.get(version, ConstantKey.LINKS_FILE_PATH) + File.separatorChar;
final LinkInfo linkInfo = new LinkInfo(fsManager.readFile(basePath + linkName, accept));
linkInfo.setEtag(Commons.getETag(basePath, version));
@ -631,7 +635,8 @@ public abstract class AbstractUtilities {
final String entitySetName, final String entityId, final String name, final InputStream value)
throws IOException {
final FileObject fo = fsManager.putInMemory(value, fsManager.getAbsolutePath(
Commons.getEntityBasePath(entitySetName, entityId) + (name == null ? MEDIA_CONTENT_FILENAME : name), null));
Commons.getEntityBasePath(entitySetName, entityId)
+ (name == null ? Constants.get(version, ConstantKey.MEDIA_CONTENT_FILENAME) : name), null));
return fo.getContent().getInputStream();
}
@ -644,7 +649,7 @@ public abstract class AbstractUtilities {
final String entitySetName, final String entityId, final String name) {
final String basePath = Commons.getEntityBasePath(entitySetName, entityId);
return new SimpleEntry<String, InputStream>(basePath, fsManager.readFile(basePath
+ (name == null ? MEDIA_CONTENT_FILENAME : name)));
+ (name == null ? Constants.get(version, ConstantKey.MEDIA_CONTENT_FILENAME) : name)));
}
public Map.Entry<String, InputStream> readEntity(
@ -654,7 +659,8 @@ public abstract class AbstractUtilities {
}
final String basePath = Commons.getEntityBasePath(entitySetName, entityId);
return new SimpleEntry<String, InputStream>(basePath, fsManager.readFile(basePath + ENTITY, accept));
return new SimpleEntry<String, InputStream>(basePath,
fsManager.readFile(basePath + Constants.get(version, ConstantKey.ENTITY), accept));
}
public InputStream expandEntity(
@ -719,15 +725,16 @@ public abstract class AbstractUtilities {
? Accept.XML : accept.getExtension().equals(Accept.JSON.getExtension()) ? Accept.JSON_FULLMETA : accept;
// read atom
InputStream stream = fsManager.readFile(basePath + ENTITY, acceptType);
InputStream stream = fsManager.readFile(basePath + Constants.get(version, ConstantKey.ENTITY), acceptType);
// change atom
stream = replaceProperty(stream, changes, path, justValue);
// save atom
fsManager.putInMemory(stream, fsManager.getAbsolutePath(basePath + ENTITY, acceptType));
fsManager.putInMemory(stream,
fsManager.getAbsolutePath(basePath + Constants.get(version, ConstantKey.ENTITY), acceptType));
return fsManager.readFile(basePath + ENTITY, acceptType);
return fsManager.readFile(basePath + Constants.get(version, ConstantKey.ENTITY), acceptType);
}
public InputStream deleteProperty(
@ -741,15 +748,16 @@ public abstract class AbstractUtilities {
? Accept.XML : accept.getExtension().equals(Accept.JSON.getExtension()) ? Accept.JSON_FULLMETA : accept;
// read atom
InputStream stream = fsManager.readFile(basePath + ENTITY, acceptType);
InputStream stream = fsManager.readFile(basePath + Constants.get(version, ConstantKey.ENTITY), acceptType);
// change atom
stream = deleteProperty(stream, path);
// save atom
fsManager.putInMemory(stream, fsManager.getAbsolutePath(basePath + ENTITY, acceptType));
fsManager.putInMemory(stream,
fsManager.getAbsolutePath(basePath + Constants.get(version, ConstantKey.ENTITY), acceptType));
return fsManager.readFile(basePath + ENTITY, acceptType);
return fsManager.readFile(basePath + Constants.get(version, ConstantKey.ENTITY), acceptType);
}
public abstract InputStream readEntities(

View File

@ -18,8 +18,6 @@
*/
package org.apache.olingo.fit.utils;
import static org.apache.olingo.fit.utils.Constants.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
@ -154,13 +152,16 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
attributes.add(eventFactory.createAttribute(new QName("title"), link));
attributes.add(eventFactory.createAttribute(new QName("href"),
Commons.getLinksURI(version, entitySetName, entitykey, link)));
attributes.add(eventFactory.createAttribute(new QName("rel"), Constants.ATOM_LINK_REL + link));
attributes.add(eventFactory.createAttribute(new QName("rel"),
Constants.get(version, ConstantKey.ATOM_LINK_REL) + link));
attributes.add(eventFactory.createAttribute(new QName("type"),
Commons.linkInfo.get(version).isFeed(entitySetName, link) ? Constants.ATOM_LINK_FEED
: Constants.ATOM_LINK_ENTRY));
Commons.linkInfo.get(version).isFeed(entitySetName, link)
? Constants.get(version, ConstantKey.ATOM_LINK_FEED)
: Constants.get(version, ConstantKey.ATOM_LINK_ENTRY)));
writer.add(eventFactory.createStartElement(new QName(LINK), attributes.iterator(), null));
writer.add(eventFactory.createEndElement(new QName(LINK), null));
writer.add(eventFactory.createStartElement(
new QName(Constants.get(version, ConstantKey.LINK)), attributes.iterator(), null));
writer.add(eventFactory.createEndElement(new QName(Constants.get(version, ConstantKey.LINK)), null));
}
writer.add(entry.getValue().getContentReader());
@ -190,7 +191,8 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
while (true) {
final Map.Entry<Integer, XmlElement> linkInfo =
extractElement(reader, null, Collections.<String>singletonList(LINK), startDepth, 2, 2);
extractElement(reader, null,
Collections.<String>singletonList(Constants.get(version, ConstantKey.LINK)), startDepth, 2, 2);
startDepth = linkInfo.getKey();
@ -228,7 +230,8 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
while (true) {
// a. search for link with type attribute equals to "application/atom+xml;type=entry/feed"
final Map.Entry<Integer, XmlElement> linkInfo = extractElement(
reader, null, Collections.<String>singletonList(LINK), filter, true, startDepth, 2, 2);
reader, null, Collections.<String>singletonList(Constants.get(version, ConstantKey.LINK)),
filter, true, startDepth, 2, 2);
final XmlElement link = linkInfo.getValue();
startDepth = linkInfo.getKey();
@ -239,7 +242,8 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
try {
final XmlElement inlineElement =
extractElement(link.getContentReader(), null, Collections.<String>singletonList(INLINE), 0, -1, -1).
extractElement(link.getContentReader(), null,
Collections.<String>singletonList(Constants.get(version, ConstantKey.INLINE)), 0, -1, -1).
getValue();
final XMLEventReader inlineReader = inlineElement.getContentReader();
@ -307,7 +311,8 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
while (true) {
// a. search for link with type attribute equals to "application/atom+xml;type=entry/feed"
linkInfo = extractElement(
reader, writer, Collections.<String>singletonList(LINK), filter, true,
reader, writer,
Collections.<String>singletonList(Constants.get(version, ConstantKey.LINK)), filter, true,
linkInfo == null ? 0 : linkInfo.getKey(), 2, 2);
final XmlElement link = linkInfo.getValue();
@ -342,7 +347,7 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
final InputStream content = addEditLink(
new ByteArrayInputStream(tmpBos.toByteArray()),
entitySetName,
Constants.DEFAULT_SERVICE_URL + entitySetName + "(" + entityKey + ")");
Constants.get(version, ConstantKey.DEFAULT_SERVICE_URL) + entitySetName + "(" + entityKey + ")");
// -----------------------------------------
// -----------------------------------------
@ -351,7 +356,7 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
return addAtomContent(
content,
entitySetName,
Constants.DEFAULT_SERVICE_URL + entitySetName + "(" + entityKey + ")");
Constants.get(version, ConstantKey.DEFAULT_SERVICE_URL) + entitySetName + "(" + entityKey + ")");
// -----------------------------------------
}
@ -439,7 +444,7 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
try {
// check edit link existence
extractElement(reader, writer, Collections.<String>singletonList(LINK),
extractElement(reader, writer, Collections.<String>singletonList(Constants.get(version, ConstantKey.LINK)),
Collections.<Map.Entry<String, String>>singletonList(
new AbstractMap.SimpleEntry<String, String>("rel", "edit")), false, 0, -1, -1);
@ -518,7 +523,8 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
} else {
try {
final XmlElement entryElement =
extractElement(reader, writer, Collections.<String>singletonList(PROPERTIES), 0, 2, 3).getValue();
extractElement(reader, writer, Collections.<String>singletonList(
Constants.get(version, ConstantKey.PROPERTIES)), 0, 2, 3).getValue();
addAtomElement(
IOUtils.toInputStream("<content type=\"application/xml\">"),
@ -564,9 +570,11 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
public int countAllElements(final String entitySetName) throws Exception {
final String basePath = entitySetName + File.separatorChar;
int count = countFeedElements(fsManager.readFile(basePath + FEED, Accept.XML), "entry");
int count = countFeedElements(fsManager.readFile(basePath + Constants.get(version, ConstantKey.FEED), Accept.XML),
"entry");
final String skipTokenDirPath = fsManager.getAbsolutePath(basePath + SKIP_TOKEN, null);
final String skipTokenDirPath = fsManager.getAbsolutePath(basePath + Constants.get(version, ConstantKey.SKIP_TOKEN),
null);
try {
@ -575,7 +583,8 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
for (FileObject file : files) {
count += countFeedElements(fsManager.readFile(
basePath + SKIP_TOKEN + File.separatorChar + file.getName().getBaseName(), null), "entry");
basePath + Constants.get(version, ConstantKey.SKIP_TOKEN) + File.separatorChar
+ file.getName().getBaseName(), null), "entry");
}
} catch (FileSystemException fse) {
LOG.debug("Resource path '{}' not found", skipTokenDirPath);
@ -739,7 +748,7 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
final List<String> pathElements = new ArrayList<String>();
for (String element : path) {
pathElements.add(ATOM_PROPERTY_PREFIX + element);
pathElements.add(Constants.get(version, ConstantKey.ATOM_PROPERTY_PREFIX) + element);
}
final XMLEventReader reader = getEventReader(is);
@ -770,28 +779,30 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
while (reader.hasNext()) {
final XMLEvent event = reader.nextEvent();
if (event.getEventType() == XMLStreamConstants.START_ELEMENT
&& LINK.equals(event.asStartElement().getName().getLocalPart())
&& Constants.get(version, ConstantKey.LINK).equals(event.asStartElement().getName().getLocalPart())
&& !fieldToBeSaved.contains(
event.asStartElement().getAttributeByName(new QName("title")).getValue())
&& !"edit".equals(event.asStartElement().getAttributeByName(new QName("rel")).getValue())) {
writeCurrent = false;
} else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
&& LINK.equals(event.asEndElement().getName().getLocalPart())) {
&& Constants.get(version, ConstantKey.LINK).equals(event.asEndElement().getName().getLocalPart())) {
writeNext = true;
} else if (event.getEventType() == XMLStreamConstants.START_ELEMENT
&& (PROPERTIES).equals(event.asStartElement().getName().getLocalPart())) {
&& (Constants.get(version, ConstantKey.PROPERTIES)).equals(
event.asStartElement().getName().getLocalPart())) {
writeCurrent = true;
writeNext = false;
inProperties = true;
} else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
&& (PROPERTIES).equals(event.asEndElement().getName().getLocalPart())) {
&& (Constants.get(version, ConstantKey.PROPERTIES)).equals(
event.asEndElement().getName().getLocalPart())) {
writeCurrent = true;
} else if (inProperties) {
if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
final String elementName = event.asStartElement().getName().getLocalPart();
for (String propertyName : propertyNames) {
if ((ATOM_PROPERTY_PREFIX + propertyName.trim()).equals(elementName)) {
if ((Constants.get(version, ConstantKey.ATOM_PROPERTY_PREFIX) + propertyName.trim()).equals(elementName)) {
writeCurrent = true;
found.remove(propertyName);
currentName = propertyName;
@ -800,7 +811,7 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
} else if (event.getEventType() == XMLStreamConstants.END_ELEMENT
&& StringUtils.isNotBlank(currentName)
&& (ATOM_PROPERTY_PREFIX + currentName.trim()).equals(
&& (Constants.get(version, ConstantKey.ATOM_PROPERTY_PREFIX) + currentName.trim()).equals(
event.asEndElement().getName().getLocalPart())) {
writeNext = false;
currentName = null;
@ -846,13 +857,14 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
// build a feed
bos.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>".getBytes());
bos.write(("<feed xml:base=\"" + DEFAULT_SERVICE_URL + "\" "
bos.write(("<feed xml:base=\"" + Constants.get(version, ConstantKey.DEFAULT_SERVICE_URL) + "\" "
+ "xmlns=\"http://www.w3.org/2005/Atom\" "
+ "xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\" "
+ "xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\">")
.getBytes());
bos.write(("<id>" + DEFAULT_SERVICE_URL + "entityset(entityid)/" + linkName + "</id>").getBytes());
bos.write(("<id>" + Constants.get(version, ConstantKey.DEFAULT_SERVICE_URL) + "entityset(entityid)/" + linkName
+ "</id>").getBytes());
bos.write(("<title type=\"text\">" + linkName + "</title>").getBytes());
bos.write("<updated>2014-03-03T13:40:49Z</updated>".getBytes());
@ -901,7 +913,8 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
XMLEventReader reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));
final Map.Entry<Integer, XmlElement> propertyElement =
extractElement(reader, null, Collections.<String>singletonList(PROPERTIES), 0, 2, 3);
extractElement(reader, null,
Collections.<String>singletonList(Constants.get(version, ConstantKey.PROPERTIES)), 0, 2, 3);
reader.close();
reader = propertyElement.getValue().getContentReader();
@ -924,9 +937,11 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
int pos = 0;
while (true) {
final Map.Entry<Integer, XmlElement> linkElement =
extractElement(reader, null, Collections.<String>singletonList(LINK), pos, 2, 2);
extractElement(reader, null,
Collections.<String>singletonList(Constants.get(version, ConstantKey.LINK)), pos, 2, 2);
res.put("[LINK]" + linkElement.getValue().getStart().getAttributeByName(new QName("title")).getValue(),
res.put("[Constants.get(version, ConstantKey.LINK)]"
+ linkElement.getValue().getStart().getAttributeByName(new QName("title")).getValue(),
linkElement.getValue().toStream());
pos = linkElement.getKey();
@ -952,7 +967,8 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
// add property changes
// ---------------------------------
Map.Entry<Integer, XmlElement> propertyElement =
extractElement(reader, writer, Collections.<String>singletonList(PROPERTIES), 0, 2, 3);
extractElement(reader, writer,
Collections.<String>singletonList(Constants.get(version, ConstantKey.PROPERTIES)), 0, 2, 3);
writer.flush();
@ -981,7 +997,7 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
}
for (Map.Entry<String, InputStream> remains : properties.entrySet()) {
if (!remains.getKey().startsWith("[LINK]")) {
if (!remains.getKey().startsWith("[Constants.get(version, ConstantKey.LINK)]")) {
pwriter.append(IOUtils.toString(remains.getValue()));
IOUtils.closeQuietly(remains.getValue());
}
@ -1009,7 +1025,7 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
// remove existent links
for (Map.Entry<String, InputStream> remains : properties.entrySet()) {
if (remains.getKey().startsWith("[LINK]")) {
if (remains.getKey().startsWith("[Constants.get(version, ConstantKey.LINK)]")) {
reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));
bos.reset();
@ -1018,7 +1034,7 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
try {
final String linkName = remains.getKey().substring(remains.getKey().indexOf("]") + 1);
extractElement(reader, writer, Collections.<String>singletonList(LINK),
extractElement(reader, writer, Collections.<String>singletonList(Constants.get(version, ConstantKey.LINK)),
Collections.<Map.Entry<String, String>>singleton(new SimpleEntry<String, String>("title", linkName)),
false, 0, 2, 2);
@ -1038,14 +1054,15 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
bos.reset();
writer = getEventWriter(bos);
propertyElement = extractElement(reader, writer, Collections.<String>singletonList(CONTENT), 0, 2, 2);
propertyElement = extractElement(reader, writer,
Collections.<String>singletonList(Constants.get(version, ConstantKey.CONTENT)), 0, 2, 2);
writer.flush();
pbos.reset();
pwriter = new OutputStreamWriter(pbos);
for (Map.Entry<String, InputStream> remains : properties.entrySet()) {
if (remains.getKey().startsWith("[LINK]")) {
if (remains.getKey().startsWith("[Constants.get(version, ConstantKey.LINK)]")) {
pwriter.append(IOUtils.toString(remains.getValue()));
IOUtils.closeQuietly(remains.getValue());
}
@ -1084,7 +1101,8 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
try {
final XmlElement linkElement =
extractElement(reader, writer, Collections.<String>singletonList(LINK),
extractElement(reader, writer,
Collections.<String>singletonList(Constants.get(version, ConstantKey.LINK)),
Collections.<Map.Entry<String, String>>singletonList(new SimpleEntry<String, String>("title", linkName)),
false, 0, -1, -1).getValue();
writer.add(linkElement.getStart());
@ -1116,23 +1134,26 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
public String getEdmTypeFromAtom(final String entitySetName, final String entityId, final List<String> path)
throws Exception {
InputStream src = fsManager.readFile(Commons.getEntityBasePath(entitySetName, entityId) + ENTITY, Accept.XML);
InputStream src = fsManager.readFile(Commons.getEntityBasePath(entitySetName, entityId)
+ Constants.get(version, ConstantKey.ENTITY), Accept.XML);
final List<String> atomPathElements = new ArrayList<String>();
for (String element : path) {
atomPathElements.add(ATOM_PROPERTY_PREFIX + element);
atomPathElements.add(Constants.get(version, ConstantKey.ATOM_PROPERTY_PREFIX) + element);
}
final Map.Entry<Integer, XmlElement> prop = extractElement(getEventReader(src), null, atomPathElements, 0, 3, 4);
IOUtils.closeQuietly(src);
final Attribute type = prop.getValue().getStart().getAttributeByName(new QName(TYPE));
final Attribute type =
prop.getValue().getStart().getAttributeByName(new QName(Constants.get(version, ConstantKey.TYPE)));
final String edmType;
if (type == null) {
edmType = Constants.ATOM_DEF_TYPE;
edmType = Constants.get(version, ConstantKey.ATOM_DEF_TYPE);
} else {
edmType = type.getValue();
}
@ -1189,11 +1210,12 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
final List<String> pathElements = new ArrayList<String>();
for (String element : path) {
pathElements.add(ATOM_PROPERTY_PREFIX + element);
pathElements.add(Constants.get(version, ConstantKey.ATOM_PROPERTY_PREFIX) + element);
}
final InputStream src =
fsManager.readFile(Commons.getEntityBasePath(entitySetName, entityId) + ENTITY, Accept.XML);
fsManager.readFile(Commons.getEntityBasePath(entitySetName, entityId)
+ Constants.get(version, ConstantKey.ENTITY), Accept.XML);
final XMLEventReader reader = getEventReader(src);
final XmlElement property = extractElement(reader, null, pathElements, 0, 3, 4).getValue();
@ -1208,21 +1230,17 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
writer.add(eventFactory.createStartDocument("UTF-8", "1.0"));
writer.add(property.getStart());
if (version == ODataVersion.v4) {
if (property.getStart().getAttributeByName(new QName(ATOM_DATASERVICE_NS)) == null) {
writer.add(eventFactory.createNamespace(ATOM_PROPERTY_PREFIX.substring(0, 1), V4_DATASERVICES_NS));
}
if (property.getStart().getAttributeByName(new QName(ATOM_METADATA_NS)) == null) {
writer.add(eventFactory.createNamespace(ATOM_METADATA_PREFIX.substring(0, 1), V4_METADATA_NS));
}
} else {
if (property.getStart().getAttributeByName(new QName(ATOM_DATASERVICE_NS)) == null) {
writer.add(eventFactory.createNamespace(ATOM_PROPERTY_PREFIX.substring(0, 1), V3_DATASERVICES_NS));
}
if (property.getStart().getAttributeByName(new QName(ATOM_METADATA_NS)) == null) {
writer.add(eventFactory.createNamespace(ATOM_METADATA_PREFIX.substring(0, 1), V3_METADATA_NS));
}
if (property.getStart().getAttributeByName(new QName(
Constants.get(version, ConstantKey.ATOM_DATASERVICE_NS))) == null) {
writer.add(eventFactory.createNamespace(
Constants.get(version, ConstantKey.ATOM_PROPERTY_PREFIX).substring(0, 1),
Constants.get(version, ConstantKey.DATASERVICES_NS)));
}
if (property.getStart().getAttributeByName(new QName(
Constants.get(version, ConstantKey.ATOM_METADATA_NS))) == null) {
writer.add(eventFactory.createNamespace(
Constants.get(version, ConstantKey.ATOM_METADATA_PREFIX).substring(0, 1),
Constants.get(version, ConstantKey.METADATA_NS)));
}
writer.add(property.getContentReader());
@ -1242,7 +1260,7 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
final List<String> pathElements = new ArrayList<String>();
for (String element : path) {
pathElements.add(ATOM_PROPERTY_PREFIX + element);
pathElements.add(Constants.get(version, ConstantKey.ATOM_PROPERTY_PREFIX) + element);
}
final XMLEventReader reader = getEventReader(src);
@ -1258,7 +1276,16 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
final XMLEventReader changesReader = new XMLEventReaderWrapper(replacement);
writer.add(changesReader);
while (changesReader.hasNext()) {
final XMLEvent event = changesReader.nextEvent();
if (event.isStartElement() && event.asStartElement().getName().equals(element.getValue().getStart().getName())) {
writer.add(element.getValue().getStart());
writer.add(changesReader);
} else {
writer.add(event);
}
}
changesReader.close();
IOUtils.closeQuietly(replacement);
@ -1283,7 +1310,7 @@ public abstract class AbstractXMLUtilities extends AbstractUtilities {
final List<String> pathElements = new ArrayList<String>();
for (String element : path) {
pathElements.add(ATOM_PROPERTY_PREFIX + element);
pathElements.add(Constants.get(version, ConstantKey.ATOM_PROPERTY_PREFIX) + element);
}
final XMLEventReader reader = getEventReader(src);

View File

@ -18,8 +18,6 @@
*/
package org.apache.olingo.fit.utils;
import static org.apache.olingo.fit.utils.Constants.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
@ -113,7 +111,8 @@ public abstract class Commons {
throws IOException {
try {
return FSManager.instance(version)
.getAbsolutePath(basePath + LINKS_FILE_PATH + File.separatorChar + linkName, accept);
.getAbsolutePath(basePath + Constants.get(version, ConstantKey.LINKS_FILE_PATH)
+ File.separatorChar + linkName, accept);
} catch (Exception e) {
throw new IOException(e);
}
@ -147,7 +146,7 @@ public abstract class Commons {
if (URI.create(uri).isAbsolute()) {
builder.append(uri);
} else {
builder.append(DEFAULT_SERVICE_URL).append(uri);
builder.append(Constants.get(ConstantKey.DEFAULT_SERVICE_URL)).append(uri);
}
builder.append("</uri>");
}
@ -162,8 +161,8 @@ public abstract class Commons {
throws IOException {
final ObjectNode links = new ObjectNode(JsonNodeFactory.instance);
links.put(
JSON_ODATAMETADATA_NAME,
ODATA_METADATA_PREFIX + entitySetName + "/$links/" + link.getKey());
Constants.get(ConstantKey.JSON_ODATAMETADATA_NAME),
Constants.get(ConstantKey.ODATA_METADATA_PREFIX) + entitySetName + "/$links/" + link.getKey());
final ArrayNode uris = new ArrayNode(JsonNodeFactory.instance);
@ -172,7 +171,7 @@ public abstract class Commons {
if (URI.create(uri).isAbsolute()) {
absoluteURI = uri;
} else {
absoluteURI = DEFAULT_SERVICE_URL + uri;
absoluteURI = Constants.get(ConstantKey.DEFAULT_SERVICE_URL) + uri;
}
uris.add(new ObjectNode(JsonNodeFactory.instance).put("url", absoluteURI));
}
@ -214,20 +213,20 @@ public abstract class Commons {
switch (target) {
case JSON_NOMETA:
// nometa + minimal
toBeRemoved.add(JSON_ODATAMETADATA_NAME);
toBeRemoved.add(Constants.get(ConstantKey.JSON_ODATAMETADATA_NAME));
case JSON:
// minimal
toBeRemoved.add(JSON_EDITLINK_NAME);
toBeRemoved.add(JSON_ID_NAME);
toBeRemoved.add(JSON_TYPE_NAME);
toBeRemoved.add(Constants.get(ConstantKey.JSON_EDITLINK_NAME));
toBeRemoved.add(Constants.get(ConstantKey.JSON_ID_NAME));
toBeRemoved.add(Constants.get(ConstantKey.JSON_TYPE_NAME));
final Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
while (fields.hasNext()) {
final Map.Entry<String, JsonNode> field = fields.next();
if (field.getKey().endsWith(JSON_MEDIA_SUFFIX)
|| field.getKey().endsWith(JSON_NAVIGATION_SUFFIX)
|| field.getKey().endsWith(JSON_TYPE_SUFFIX)) {
if (field.getKey().endsWith(Constants.get(ConstantKey.JSON_MEDIA_SUFFIX))
|| field.getKey().endsWith(Constants.get(ConstantKey.JSON_NAVIGATION_SUFFIX))
|| field.getKey().endsWith(Constants.get(ConstantKey.JSON_TYPE_SUFFIX))) {
toBeRemoved.add(field.getKey());
} else if (field.getValue().isObject()) {
toBeReplaced.put(field.getKey(), changeFormat((ObjectNode) field.getValue(), target));

View File

@ -0,0 +1,67 @@
/*
* 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.
*/
package org.apache.olingo.fit.utils;
public enum ConstantKey {
ODATA_SERVICE_VERSION,
DEFAULT_SERVICE_URL,
ODATA_COUNT_NAME,
ODATA_METADATA_PREFIX,
ATOM_DEF_TYPE,
ATOM_PROPERTY_PREFIX,
ATOM_METADATA_PREFIX,
ATOM_METADATA_NS,
ATOM_DATASERVICE_NS,
ATOM_LINK_ENTRY,
ATOM_LINK_FEED,
ATOM_LINK_REL,
TYPE,
INLINE_LOCAL,
INLINE_FILE_PATH,
LINKS_FILE_PATH,
INLINE,
CONTENT,
PROPERTIES,
LINK,
DATASERVICES_NS,
METADATA_NS,
METADATA,
SERVICES,
FEED,
ENTITY,
REF,
MEDIA_CONTENT_FILENAME,
SKIP_TOKEN,
FILTER,
ORDERBY,
JSON_VALUE_NAME,
JSON_NEXTLINK_NAME,
JSON_NEXTLINK_SUFFIX,
JSON_ODATAMETADATA_NAME,
JSON_NAVIGATION_BIND_SUFFIX,
JSON_NAVIGATION_SUFFIX,
JSON_MEDIA_SUFFIX,
JSON_TYPE_NAME,
JSON_TYPE_SUFFIX,
JSON_ID_NAME,
JSON_EDITLINK_NAME,
XHTTP_HEADER_NAME;
};

View File

@ -18,96 +18,83 @@
*/
package org.apache.olingo.fit.utils;
import java.util.EnumMap;
import java.util.Map;
public class Constants {
public final static String ODATA_SERVICE_VERSION = "DataServiceVersion";
private final static Map<ConstantKey, String> v4constants = new EnumMap<ConstantKey, String>(ConstantKey.class);
public final static String DEFAULT_SERVICE_URL = "http://localhost:9080/StaticService/V30/Static.svc/";
private final static Map<ConstantKey, String> constants = new EnumMap<ConstantKey, String>(ConstantKey.class);
public final static String ODATA_COUNT_NAME = "odata.count";
static {
public final static String ODATA_METADATA_PREFIX = DEFAULT_SERVICE_URL + "$metadata#";
// -----------------------------
// V4 only
// -----------------------------
v4constants.put(ConstantKey.JSON_NAVIGATION_SUFFIX, "@odata.navigationLink");
v4constants.put(ConstantKey.DATASERVICES_NS, "http://docs.oasis-open.org/odata/ns/dataservices");
v4constants.put(ConstantKey.METADATA_NS, "http://docs.oasis-open.org/odata/ns/metadata");
v4constants.put(ConstantKey.ODATA_SERVICE_VERSION, "OData-Version");
v4constants.put(ConstantKey.DEFAULT_SERVICE_URL, "http://localhost:9080/StaticService/V40/Static.svc/");
v4constants.put(ConstantKey.ODATA_METADATA_PREFIX, "http://localhost:9080/StaticService/V40/Static.svc/$metadata#");
// -----------------------------
public final static String ATOM_DEF_TYPE = "Edm.String";
// -----------------------------
// V3 and defaults
// -----------------------------
constants.put(ConstantKey.ODATA_SERVICE_VERSION, "DataServiceVersion");
constants.put(ConstantKey.DEFAULT_SERVICE_URL, "http://localhost:9080/StaticService/V30/Static.svc/");
constants.put(ConstantKey.ODATA_COUNT_NAME, "odata.count");
constants.put(ConstantKey.ODATA_METADATA_PREFIX, "http://localhost:9080/StaticService/V30/Static.svc/$metadata#");
constants.put(ConstantKey.ATOM_DEF_TYPE, "Edm.String");
constants.put(ConstantKey.ATOM_PROPERTY_PREFIX, "d:");
constants.put(ConstantKey.ATOM_METADATA_PREFIX, "m:");
constants.put(ConstantKey.ATOM_METADATA_NS, "xmlns:m");
constants.put(ConstantKey.ATOM_DATASERVICE_NS, "xmlns:d");
constants.put(ConstantKey.ATOM_LINK_ENTRY, "application/atom+xml;type=entry");
constants.put(ConstantKey.ATOM_LINK_FEED, "application/atom+xml;type=feed");
constants.put(ConstantKey.ATOM_LINK_REL, "http://schemas.microsoft.com/ado/2007/08/dataservices/related/");
constants.put(ConstantKey.TYPE, "m:type");
constants.put(ConstantKey.INLINE_LOCAL, "inline");
constants.put(ConstantKey.INLINE_FILE_PATH, "inline");
constants.put(ConstantKey.LINKS_FILE_PATH, "links");
constants.put(ConstantKey.INLINE, "m:inline");
constants.put(ConstantKey.CONTENT, "content");
constants.put(ConstantKey.PROPERTIES, "m:properties");
constants.put(ConstantKey.LINK, "link");
constants.put(ConstantKey.METADATA_NS, "http://schemas.microsoft.com/ado/2007/08/dataservices/metadta");
constants.put(ConstantKey.DATASERVICES_NS, "http://schemas.microsoft.com/ado/2007/08/dataservices");
constants.put(ConstantKey.METADATA, "metadata");
constants.put(ConstantKey.SERVICES, "services");
constants.put(ConstantKey.FEED, "feed");
constants.put(ConstantKey.ENTITY, "entity");
constants.put(ConstantKey.REF, "references");
constants.put(ConstantKey.MEDIA_CONTENT_FILENAME, "$value.bin");
constants.put(ConstantKey.SKIP_TOKEN, "skiptoken");
constants.put(ConstantKey.FILTER, "filter");
constants.put(ConstantKey.ORDERBY, "orderby");
constants.put(ConstantKey.JSON_VALUE_NAME, "value");
constants.put(ConstantKey.JSON_NEXTLINK_NAME, "odata.nextLink");
constants.put(ConstantKey.JSON_NEXTLINK_SUFFIX, "@odata.nextLink");
constants.put(ConstantKey.JSON_ODATAMETADATA_NAME, "odata.metadata");
constants.put(ConstantKey.JSON_NAVIGATION_BIND_SUFFIX, "@odata.bind");
constants.put(ConstantKey.JSON_NAVIGATION_SUFFIX, "@odata.navigationLinkUrl");
constants.put(ConstantKey.JSON_MEDIA_SUFFIX, "@odata.mediaEditLink");
constants.put(ConstantKey.JSON_TYPE_NAME, "odata.type");
constants.put(ConstantKey.JSON_TYPE_SUFFIX, "@odata.type");
constants.put(ConstantKey.JSON_ID_NAME, "odata.id");
constants.put(ConstantKey.JSON_EDITLINK_NAME, "odata.editLink");
constants.put(ConstantKey.XHTTP_HEADER_NAME, "X-HTTP-METHOD");
// -----------------------------
}
public final static String ATOM_PROPERTY_PREFIX = "d:";
public final static String ATOM_METADATA_PREFIX = "m:";
public final static String ATOM_METADATA_NS = "xmlns:m";
public final static String ATOM_DATASERVICE_NS = "xmlns:d";
public final static String ATOM_LINK_ENTRY = "application/atom+xml;type=entry";
public final static String ATOM_LINK_FEED = "application/atom+xml;type=feed";
public final static String ATOM_LINK_REL = "http://schemas.microsoft.com/ado/2007/08/dataservices/related/";
public final static String TYPE = ATOM_METADATA_PREFIX + "type";
public final static String INLINE_LOCAL = "inline";
public final static String INLINE_FILE_PATH = "inline";
public final static String LINKS_FILE_PATH = "links";
public final static String INLINE = ATOM_METADATA_PREFIX + INLINE_LOCAL;
public final static String CONTENT = "content";
public final static String PROPERTIES = ATOM_METADATA_PREFIX + "properties";
public final static String LINK = "link";
public final static String V3_DATASERVICES_NS = "http://schemas.microsoft.com/ado/2007/08/dataservices";
public final static String V4_DATASERVICES_NS = "http://docs.oasis-open.org/odata/ns/dataservices";
public final static String V3_METADATA_NS = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
public final static String V4_METADATA_NS = "http://docs.oasis-open.org/odata/ns/metadata";
public final static String METADATA = "metadata";
public final static String SERVICES = "services";
public final static String FEED = "feed";
public final static String ENTITY = "entity";
public final static String REF = "references";
public final static String MEDIA_CONTENT_FILENAME = "$value.bin";
public final static String SKIP_TOKEN = "skiptoken";
public final static String FILTER = "filter";
public final static String ORDERBY = "orderby";
public final static String JSON_VALUE_NAME = "value";
public final static String JSON_NEXTLINK_NAME = "odata.nextLink";
public final static String JSON_NEXTLINK_SUFFIX = "@" + JSON_NEXTLINK_NAME;
public final static String JSON_ODATAMETADATA_NAME = "odata.metadata";
public final static String JSON_NAVIGATION_BIND_SUFFIX = "@odata.bind";
public final static String JSON_NAVIGATION_SUFFIX = "@odata.navigationLinkUrl";
public final static String JSON_MEDIA_SUFFIX = "@odata.mediaEditLink";
public final static String JSON_TYPE_NAME = "odata.type";
public final static String JSON_TYPE_SUFFIX = "@" + JSON_TYPE_NAME;
public final static String JSON_ID_NAME = "odata.id";
public final static String JSON_EDITLINK_NAME = "odata.editLink";
public final static String XHTTP_HEADER_NAME = "X-HTTP-METHOD";
public static String get(final ConstantKey key) {
return get(null, key);
}
public static String get(final ODataVersion version, final ConstantKey key) {
return (version == null || version == ODataVersion.v3 || !v4constants.containsKey(key)
? constants : v4constants).get(key);
}
}

View File

@ -32,4 +32,4 @@ public enum ODataVersion {
public String getVersion() {
return version;
}
};
}

View File

@ -36,8 +36,9 @@ public class XHTTPMethodInterceptor extends AbstractPhaseInterceptor<Message> {
@SuppressWarnings("unchecked")
final Map<String, List<String>> headers = (Map<String, List<String>>) message.get(Message.PROTOCOL_HEADERS);
if (headers.containsKey(Constants.XHTTP_HEADER_NAME)) {
message.put(Message.HTTP_REQUEST_METHOD, headers.get(Constants.XHTTP_HEADER_NAME).iterator().next());
if (headers.containsKey(Constants.get(ConstantKey.XHTTP_HEADER_NAME))) {
message.put(Message.HTTP_REQUEST_METHOD, headers.get(Constants.get(ConstantKey.XHTTP_HEADER_NAME))
.iterator().next());
}
}
}

View File

@ -32,6 +32,7 @@ import javax.xml.stream.events.StartElement;
import org.apache.commons.io.IOUtils;
import org.apache.olingo.fit.utils.Accept;
import org.apache.olingo.fit.utils.Commons;
import org.apache.olingo.fit.utils.ConstantKey;
import org.apache.olingo.fit.utils.Constants;
import org.apache.olingo.fit.utils.MetadataLinkInfo;
import org.apache.olingo.fit.utils.ODataVersion;
@ -49,7 +50,7 @@ public class XMLUtilities extends org.apache.olingo.fit.utils.AbstractXMLUtiliti
final MetadataLinkInfo metadataLinkInfo = new MetadataLinkInfo();
Commons.getLinkInfo().put(version, metadataLinkInfo);
final InputStream metadata = fsManager.readFile(Constants.METADATA, Accept.XML);
final InputStream metadata = fsManager.readFile(Constants.get(version, ConstantKey.METADATA), Accept.XML);
final XMLEventReader reader = getEventReader(metadata);
try {
@ -69,7 +70,7 @@ public class XMLUtilities extends org.apache.olingo.fit.utils.AbstractXMLUtiliti
private void retrieveLinks(final XmlElement entitySetElement, final MetadataLinkInfo metadataLinkInfo)
throws Exception {
final InputStream metadata = fsManager.readFile(Constants.METADATA, Accept.XML);
final InputStream metadata = fsManager.readFile(Constants.get(version, ConstantKey.METADATA), Accept.XML);
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
IOUtils.copy(metadata, bos);
@ -120,7 +121,7 @@ public class XMLUtilities extends org.apache.olingo.fit.utils.AbstractXMLUtiliti
private Map.Entry<String, Boolean> getTargetInfo(final StartElement element, final String linkName)
throws Exception {
final InputStream metadata = fsManager.readFile(Constants.METADATA, Accept.XML);
final InputStream metadata = fsManager.readFile(Constants.get(version, ConstantKey.METADATA), Accept.XML);
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
IOUtils.copy(metadata, bos);

View File

@ -30,6 +30,7 @@ import javax.xml.stream.XMLEventReader;
import org.apache.commons.io.IOUtils;
import org.apache.olingo.fit.utils.Accept;
import org.apache.olingo.fit.utils.Commons;
import org.apache.olingo.fit.utils.ConstantKey;
import org.apache.olingo.fit.utils.Constants;
import org.apache.olingo.fit.utils.MetadataLinkInfo;
import org.apache.olingo.fit.utils.ODataVersion;
@ -47,7 +48,7 @@ public class XMLUtilities extends org.apache.olingo.fit.utils.AbstractXMLUtiliti
final MetadataLinkInfo metadataLinkInfo = new MetadataLinkInfo();
Commons.getLinkInfo().put(version, metadataLinkInfo);
final InputStream metadata = fsManager.readFile(Constants.METADATA, Accept.XML);
final InputStream metadata = fsManager.readFile(Constants.get(version, ConstantKey.METADATA), Accept.XML);
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
IOUtils.copy(metadata, bos);

View File

@ -37,20 +37,6 @@ public interface ServiceDocument {
*/
URI getBaseURI();
/**
* Returns metadata context.
*
* @return metadata context
*/
String getMetadataContext();
/**
* Returns metadata ETag.
*
* @return metadata ETag
*/
String getMetadataETag();
/**
* Gets top level entity sets.
*
@ -134,5 +120,4 @@ public interface ServiceDocument {
* @return related service document with given title if found, otherwise null
*/
ServiceDocumentItem getRelatedServiceDocumentByTitle(String title);
}

View File

@ -88,7 +88,7 @@ public class ODataPropertyRequestImpl<T extends CommonODataProperty>
try {
final Container<Property> container =
odataClient.getDeserializer().toProperty(
res.getEntity().getContent(), ODataFormat.fromString(getContentType()));
res.getEntity().getContent(), ODataFormat.fromString(getContentType()));
property = (T) odataClient.getBinder().getODataProperty(extractFromContainer(container));
} catch (IOException e) {

View File

@ -18,6 +18,7 @@
*/
package org.apache.olingo.client.core.data;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ -28,6 +29,7 @@ import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.olingo.client.api.data.ServiceDocument;
import org.apache.olingo.client.api.data.ServiceDocumentItem;
import org.apache.olingo.commons.api.Constants;
public abstract class AbstractServiceDocument implements ServiceDocument {
@ -35,14 +37,35 @@ public abstract class AbstractServiceDocument implements ServiceDocument {
private final List<ServiceDocumentItem> entitySets = new ArrayList<ServiceDocumentItem>();
@Override
public String getMetadataContext() {
return null;
}
private String metadata;
@Override
public String getMetadataETag() {
return null;
public URI getBaseURI() {
URI baseURI = null;
if (metadata != null) {
final String metadataURI = getMetadata();
baseURI = URI.create(metadataURI.substring(0, metadataURI.indexOf(Constants.METADATA)));
}
return baseURI;
}
/**
* Gets the metadata URI.
*
* @return the metadata URI
*/
public String getMetadata() {
return metadata;
}
/**
* Sets the metadata URI.
*
* @param metadata metadata URI.
*/
public void setMetadata(final String metadata) {
this.metadata = metadata;
}
@Override

View File

@ -25,17 +25,20 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.net.URI;
import java.util.Iterator;
import org.apache.commons.lang3.StringUtils;
import org.apache.olingo.commons.api.Constants;
import org.apache.olingo.commons.api.data.Container;
import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion;
import org.apache.olingo.commons.core.data.ODataJacksonDeserializer;
public class JSONServiceDocumentDeserializer extends ODataJacksonDeserializer<AbstractServiceDocument> {
public class JSONServiceDocumentDeserializer extends ODataJacksonDeserializer<Container<AbstractServiceDocument>> {
@Override
protected AbstractServiceDocument doDeserialize(final JsonParser parser, final DeserializationContext ctxt)
protected Container<AbstractServiceDocument> doDeserialize(
final JsonParser parser, final DeserializationContext ctxt)
throws IOException, JsonProcessingException {
final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);
@ -44,19 +47,28 @@ public class JSONServiceDocumentDeserializer extends ODataJacksonDeserializer<Ab
? new org.apache.olingo.client.core.data.v3.JSONServiceDocumentImpl()
: new org.apache.olingo.client.core.data.v4.JSONServiceDocumentImpl();
if (tree.hasNonNull(Constants.JSON_METADATA)
&& serviceDocument instanceof org.apache.olingo.client.core.data.v3.JSONServiceDocumentImpl) {
final String metadataETag;
final URI contextURL;
((org.apache.olingo.client.core.data.v3.JSONServiceDocumentImpl) serviceDocument).
setMetadata(tree.get(Constants.JSON_METADATA).textValue());
if (tree.hasNonNull(Constants.JSON_METADATA_ETAG)) {
metadataETag = tree.get(Constants.JSON_METADATA_ETAG).textValue();
tree.remove(Constants.JSON_METADATA_ETAG);
} else {
metadataETag = null;
}
if (tree.hasNonNull(Constants.JSON_CONTEXT)
&& serviceDocument instanceof org.apache.olingo.client.core.data.v4.JSONServiceDocumentImpl) {
((org.apache.olingo.client.core.data.v4.JSONServiceDocumentImpl) serviceDocument).
setMetadataContext(tree.get(Constants.JSON_CONTEXT).textValue());
if (tree.hasNonNull(Constants.JSON_CONTEXT)) {
contextURL = URI.create(tree.get(Constants.JSON_CONTEXT).textValue());
tree.remove(Constants.JSON_CONTEXT);
} else if (tree.hasNonNull(Constants.JSON_METADATA)) {
contextURL = URI.create(tree.get(Constants.JSON_METADATA).textValue());
tree.remove(Constants.JSON_METADATA);
} else {
contextURL = null;
}
serviceDocument.setMetadata(contextURL == null ? null : contextURL.toASCIIString());
for (final Iterator<JsonNode> itor = tree.get(Constants.VALUE).elements(); itor.hasNext();) {
final JsonNode node = itor.next();
@ -79,7 +91,6 @@ public class JSONServiceDocumentDeserializer extends ODataJacksonDeserializer<Ab
}
}
return serviceDocument;
return new Container<AbstractServiceDocument>(contextURL, metadataETag, serviceDocument);
}
}

View File

@ -29,9 +29,11 @@ import java.io.IOException;
import java.net.URI;
import org.apache.olingo.client.api.data.ServiceDocument;
import org.apache.olingo.client.core.uri.URIUtils;
import org.apache.olingo.commons.api.data.Container;
import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion;
public class XMLServiceDocumentDeserializer extends ODataJacksonDeserializer<ServiceDocument> {
public class XMLServiceDocumentDeserializer extends ODataJacksonDeserializer<Container<ServiceDocument>> {
private String getTitle(final JsonParser jp) throws IOException {
String title = jp.nextTextValue();
@ -67,32 +69,28 @@ public class XMLServiceDocumentDeserializer extends ODataJacksonDeserializer<Ser
}
@Override
protected ServiceDocument doDeserialize(final JsonParser jp, final DeserializationContext ctxt)
protected Container<ServiceDocument> doDeserialize(final JsonParser jp, final DeserializationContext ctxt)
throws IOException, JsonProcessingException {
final AbstractServiceDocument sdoc = ODataServiceVersion.V30 == version
? new org.apache.olingo.client.core.data.v3.XMLServiceDocumentImpl()
: new org.apache.olingo.client.core.data.v4.XMLServiceDocumentImpl();
URI contextURL = null;
String metadataETag = null;
String base = null;
for (; jp.getCurrentToken() != JsonToken.END_OBJECT
|| !"service".equals(((FromXmlParser) jp).getStaxReader().getLocalName()); jp.nextToken()) {
final JsonToken token = jp.getCurrentToken();
if (token == JsonToken.FIELD_NAME) {
if ("base".equals(jp.getCurrentName())) {
if (sdoc instanceof org.apache.olingo.client.core.data.v3.XMLServiceDocumentImpl) {
((org.apache.olingo.client.core.data.v3.XMLServiceDocumentImpl) sdoc).
setBaseURI(URI.create(jp.nextTextValue()));
} else {
((org.apache.olingo.client.core.data.v4.XMLServiceDocumentImpl) sdoc).
setBaseURI(URI.create(jp.nextTextValue()));
}
base = jp.nextTextValue();
} else if ("context".equals(jp.getCurrentName())) {
((org.apache.olingo.client.core.data.v4.XMLServiceDocumentImpl) sdoc).
setMetadataContext(jp.nextTextValue());
contextURL = URI.create(jp.nextTextValue());
} else if ("metadata-etag".equals(jp.getCurrentName())) {
((org.apache.olingo.client.core.data.v4.XMLServiceDocumentImpl) sdoc).
setMetadataETag(jp.nextTextValue());
metadataETag = jp.nextTextValue();
} else if ("workspace".equals(jp.getCurrentName())) {
jp.nextToken();
jp.nextToken();
@ -115,7 +113,12 @@ public class XMLServiceDocumentDeserializer extends ODataJacksonDeserializer<Ser
}
}
return sdoc;
}
sdoc.setMetadata((contextURL == null
? URIUtils.getURI(base, "$metadata")
: URIUtils.getURI(base, contextURL.toASCIIString())).toASCIIString());
return new Container<ServiceDocument>(
contextURL == null ? null : URIUtils.getURI(sdoc.getBaseURI(), contextURL),
metadataETag, sdoc);
}
}

View File

@ -20,11 +20,9 @@ package org.apache.olingo.client.core.data.v3;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.net.URI;
import org.apache.olingo.client.core.data.AbstractServiceDocument;
import org.apache.olingo.client.core.data.JSONServiceDocumentDeserializer;
import org.apache.olingo.commons.api.Constants;
/**
* Service document, represented via JSON.
@ -34,34 +32,4 @@ public class JSONServiceDocumentImpl extends AbstractServiceDocument {
private static final long serialVersionUID = 4195734928526398830L;
private String metadata;
@Override
public URI getBaseURI() {
URI baseURI = null;
if (metadata != null) {
final String metadataURI = getMetadata();
baseURI = URI.create(metadataURI.substring(0, metadataURI.indexOf(Constants.METADATA)));
}
return baseURI;
}
/**
* Gets the metadata URI.
*
* @return the metadata URI
*/
public String getMetadata() {
return metadata;
}
/**
* Sets the metadata URI.
*
* @param metadata metadata URI.
*/
public void setMetadata(final String metadata) {
this.metadata = metadata;
}
}

View File

@ -20,7 +20,6 @@ package org.apache.olingo.client.core.data.v3;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.net.URI;
import org.apache.olingo.client.api.data.ServiceDocument;
import org.apache.olingo.client.core.data.AbstractServiceDocument;
@ -28,21 +27,4 @@ import org.apache.olingo.client.core.data.XMLServiceDocumentDeserializer;
@JsonDeserialize(using = XMLServiceDocumentDeserializer.class)
public class XMLServiceDocumentImpl extends AbstractServiceDocument implements ServiceDocument {
private URI baseURI;
@Override
public URI getBaseURI() {
return this.baseURI;
}
/**
* Sets base URI.
*
* @param baseURI base URI.
*/
public void setBaseURI(final URI baseURI) {
this.baseURI = baseURI;
}
}

View File

@ -18,7 +18,6 @@
*/
package org.apache.olingo.client.core.data.v4;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
@ -27,50 +26,12 @@ import org.apache.olingo.client.api.data.ServiceDocumentItem;
public abstract class AbstractServiceDocument
extends org.apache.olingo.client.core.data.AbstractServiceDocument {
private URI baseURI;
private String metadataContext;
private String metadataETag;
private List<ServiceDocumentItem> functionImports = new ArrayList<ServiceDocumentItem>();
private List<ServiceDocumentItem> singletons = new ArrayList<ServiceDocumentItem>();
private List<ServiceDocumentItem> relatedServiceDocuments = new ArrayList<ServiceDocumentItem>();
@Override
public URI getBaseURI() {
return this.baseURI;
}
/**
* Sets base URI.
*
* @param baseURI base URI.
*/
public void setBaseURI(final URI baseURI) {
this.baseURI = baseURI;
}
@Override
public String getMetadataContext() {
return metadataContext;
}
public void setMetadataContext(final String metadataContext) {
this.metadataContext = metadataContext;
}
@Override
public String getMetadataETag() {
return metadataETag;
}
public void setMetadataETag(final String metadataETag) {
this.metadataETag = metadataETag;
}
@Override
public List<ServiceDocumentItem> getFunctionImports() {
return functionImports;
@ -85,5 +46,4 @@ public abstract class AbstractServiceDocument
public List<ServiceDocumentItem> getRelatedServiceDocuments() {
return relatedServiceDocuments;
}
}

View File

@ -23,21 +23,6 @@ import org.apache.olingo.client.core.data.JSONServiceDocumentDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import java.net.URI;
import org.apache.olingo.commons.api.Constants;
@JsonDeserialize(using = JSONServiceDocumentDeserializer.class)
public class JSONServiceDocumentImpl extends AbstractServiceDocument implements ServiceDocument {
@Override
public URI getBaseURI() {
URI baseURI = null;
if (getMetadataContext() != null) {
final String metadataURI = getMetadataContext();
baseURI = URI.create(metadataURI.substring(0, metadataURI.indexOf(Constants.METADATA)));
}
return baseURI;
}
}

View File

@ -25,5 +25,4 @@ import org.apache.olingo.client.core.data.XMLServiceDocumentDeserializer;
@JsonDeserialize(using = XMLServiceDocumentDeserializer.class)
public class XMLServiceDocumentImpl extends AbstractServiceDocument implements ServiceDocument {
}

View File

@ -292,7 +292,7 @@ public abstract class AbstractODataBinder implements CommonODataBinder {
final CommonODataEntity entity = resource.getSelfLink() == null
? client.getObjectFactory().newEntity(resource.getType())
: client.getObjectFactory().newEntity(resource.getType(),
URIUtils.getURI(base, resource.getSelfLink().getHref()));
URIUtils.getURI(base, resource.getSelfLink().getHref()));
if (StringUtils.isNotBlank(resource.getETag())) {
entity.setETag(resource.getETag());
@ -321,12 +321,12 @@ public abstract class AbstractODataBinder implements CommonODataBinder {
entity.addLink(client.getObjectFactory().newInlineEntity(
link.getTitle(), base, link.getHref(),
getODataEntity(inlineEntry,
inlineEntry.getBaseURI() == null ? base : inlineEntry.getBaseURI())));
inlineEntry.getBaseURI() == null ? base : inlineEntry.getBaseURI())));
} else {
entity.addLink(client.getObjectFactory().newInlineEntitySet(
link.getTitle(), base, link.getHref(),
getODataEntitySet(inlineFeed,
inlineFeed.getBaseURI() == null ? base : inlineFeed.getBaseURI())));
inlineFeed.getBaseURI() == null ? base : inlineFeed.getBaseURI())));
}
}
@ -363,18 +363,18 @@ public abstract class AbstractODataBinder implements CommonODataBinder {
value = client.getObjectFactory().newPrimitiveValueBuilder().
setText(resource.getValue().asPrimitive().get()).
setType(typeInfo == null
? null
: EdmPrimitiveTypeKind.valueOfFQN(
client.getServiceVersion(), typeInfo.getFullQualifiedName().toString())).build();
? null
: EdmPrimitiveTypeKind.valueOfFQN(
client.getServiceVersion(), typeInfo.getFullQualifiedName().toString())).build();
} else if (resource.getValue().isGeospatial()) {
value = client.getObjectFactory().newPrimitiveValueBuilder().
setValue(resource.getValue().asGeospatial().get()).
setType(typeInfo == null
|| EdmPrimitiveTypeKind.Geography.getFullQualifiedName().equals(typeInfo.getFullQualifiedName())
|| EdmPrimitiveTypeKind.Geometry.getFullQualifiedName().equals(typeInfo.getFullQualifiedName())
? resource.getValue().asGeospatial().get().getEdmPrimitiveTypeKind()
: EdmPrimitiveTypeKind.valueOfFQN(
client.getServiceVersion(), typeInfo.getFullQualifiedName().toString())).build();
|| EdmPrimitiveTypeKind.Geography.getFullQualifiedName().equals(typeInfo.getFullQualifiedName())
|| EdmPrimitiveTypeKind.Geometry.getFullQualifiedName().equals(typeInfo.getFullQualifiedName())
? resource.getValue().asGeospatial().get().getEdmPrimitiveTypeKind()
: EdmPrimitiveTypeKind.valueOfFQN(
client.getServiceVersion(), typeInfo.getFullQualifiedName().toString())).build();
} else if (resource.getValue().isComplex()) {
value = client.getObjectFactory().newComplexValue(typeInfo == null
? null : typeInfo.getFullQualifiedName().toString());

View File

@ -64,19 +64,19 @@ public class ODataBinderImpl extends AbstractODataBinder implements ODataBinder
public ODataServiceDocument getODataServiceDocument(final ServiceDocument resource) {
final ODataServiceDocument serviceDocument = super.getODataServiceDocument(resource);
serviceDocument.setMetadataContext(URIUtils.getURI(resource.getBaseURI(), resource.getMetadataContext()));
serviceDocument.setMetadataETag(resource.getMetadataETag());
for (ServiceDocumentItem functionImport : resource.getFunctionImports()) {
serviceDocument.getFunctionImports().put(functionImport.getTitle(),
serviceDocument.getFunctionImports().put(
functionImport.getName() == null ? functionImport.getHref() : functionImport.getName(),
URIUtils.getURI(resource.getBaseURI(), functionImport.getHref()));
}
for (ServiceDocumentItem singleton : resource.getSingletons()) {
serviceDocument.getSingletons().put(singleton.getTitle(),
serviceDocument.getSingletons().put(
singleton.getName() == null ? singleton.getHref() : singleton.getName(),
URIUtils.getURI(resource.getBaseURI(), singleton.getHref()));
}
for (ServiceDocumentItem sdoc : resource.getRelatedServiceDocuments()) {
serviceDocument.getRelatedServiceDocuments().put(sdoc.getTitle(),
serviceDocument.getRelatedServiceDocuments().put(
sdoc.getName() == null ? sdoc.getHref() : sdoc.getName(),
URIUtils.getURI(resource.getBaseURI(), sdoc.getHref()));
}

View File

@ -97,7 +97,6 @@ public class AsyncTestITCase extends AbstractTestITCase {
* @see MediaEntityTest#createMediaEntity(com.msopentech.odatajclient.engine.format.ODataPubFormat)
*/
@Test
@Ignore
public void createMediaEntity() throws Exception {
CommonURIBuilder<?> builder = client.getURIBuilder(testStaticServiceRootURL).appendEntitySetSegment("Car");

View File

@ -1,534 +0,0 @@
/*
* 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.
*/
package org.apache.olingo.client.core.it.v3;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.olingo.client.api.communication.request.cud.ODataDeleteRequest;
import org.apache.olingo.client.api.communication.request.cud.ODataEntityCreateRequest;
import org.apache.olingo.client.api.communication.request.retrieve.ODataEntityRequest;
import org.apache.olingo.client.api.communication.request.retrieve.ODataEntitySetRequest;
import org.apache.olingo.client.api.communication.response.ODataDeleteResponse;
import org.apache.olingo.client.api.communication.response.ODataEntityCreateResponse;
import org.apache.olingo.client.api.communication.response.ODataRetrieveResponse;
import org.apache.olingo.client.api.http.HttpClientException;
import org.apache.olingo.client.api.uri.CommonURIBuilder;
import org.apache.olingo.client.core.uri.URIUtils;
import org.apache.olingo.commons.api.domain.CommonODataEntity;
import org.apache.olingo.commons.api.domain.CommonODataEntitySet;
import org.apache.olingo.commons.api.domain.CommonODataProperty;
import org.apache.olingo.commons.api.domain.ODataCollectionValue;
import org.apache.olingo.commons.api.domain.ODataComplexValue;
import org.apache.olingo.commons.api.domain.ODataInlineEntity;
import org.apache.olingo.commons.api.domain.ODataInlineEntitySet;
import org.apache.olingo.commons.api.domain.ODataLink;
import org.apache.olingo.commons.api.domain.ODataValue;
import org.apache.olingo.commons.api.domain.v3.ODataEntity;
import org.apache.olingo.commons.api.domain.v3.ODataEntitySet;
import org.apache.olingo.commons.api.domain.v3.ODataProperty;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.apache.olingo.commons.api.format.ODataPubFormat;
import org.junit.Ignore;
import org.junit.Test;
public class NavigationLinkCreateTestITCase extends AbstractTestITCase {
// create navigation link with ATOM
@Test
public void createNavWithAtom() {
final ODataPubFormat format = ODataPubFormat.ATOM;
final String contentType = "application/atom+xml";
final String prefer = "return-content";
final ODataEntity actual = createNavigation(format, 20, contentType, prefer);
delete(format, actual, false, testStaticServiceRootURL);
}
// create navigation link with JSON full metadata
@Test
public void createNavWithJSONFullMetadata() {
final ODataPubFormat format = ODataPubFormat.JSON_FULL_METADATA;
final String contentType = "application/json;odata=fullmetadata";
final String prefer = "return-content";
final ODataEntity actual = createNavigation(format, 21, contentType, prefer);
delete(format, actual, false, testStaticServiceRootURL);
}
// throws Null pointer exception when the format is JSON No metadata
@Test(expected = HttpClientException.class)
public void createNavWithJSONNoMetadata() {
final ODataPubFormat format = ODataPubFormat.JSON_NO_METADATA;
final String contentType = "application/json;odata=nometadata";
final String prefer = "return-content";
final ODataEntity actual = createNavigation(format, 22, contentType, prefer);
delete(format, actual, false, testStaticServiceRootURL);
}
// test with JSON accept and atom content type
@Test
@Ignore
public void createNavWithJSONAndATOM() {
final ODataPubFormat format = ODataPubFormat.JSON_FULL_METADATA;
final String contentType = "application/atom+xml";
final String prefer = "return-content";
final ODataEntity actual = createNavigation(format, 23, contentType, prefer);
delete(format, actual, false, testStaticServiceRootURL);
}
// test with JSON full metadata in format and json no metadata in content type
@Test
public void createNavWithDiffJSON() {
final ODataPubFormat format = ODataPubFormat.JSON_FULL_METADATA;
final String contentType = "application/json;odata=nometadata";
final String prefer = "return-content";
final ODataEntity actual = createNavigation(format, 24, contentType, prefer);
delete(format, actual, false, testStaticServiceRootURL);
}
// test with JSON no metadata format and json no metadata in content type
@Test(expected = HttpClientException.class)
public void createNavWithNoMetadata() {
final ODataPubFormat format = ODataPubFormat.JSON_NO_METADATA;
final String contentType = "application/json;odata=fullmetadata";
final String prefer = "return-content";
final ODataEntity actual = createNavigation(format, 25, contentType, prefer);
delete(format, actual, false, testStaticServiceRootURL);
}
// create collection navigation link with ATOM
@Test
public void createCollectionNavWithAtom() throws EdmPrimitiveTypeException {
final ODataPubFormat format = ODataPubFormat.ATOM;
final String contentType = "application/atom+xml";
final String prefer = "return-content";
final ODataEntity actual = createCollectionNavigation(format, 55, contentType, prefer);
delete(format, actual, false, testStaticServiceRootURL);
}
// create collection navigation link with JSON
@Test
public void createCollectionNavWithJSON() throws EdmPrimitiveTypeException {
final ODataPubFormat format = ODataPubFormat.JSON_FULL_METADATA;
final String contentType = "application/json;odata=fullmetadata";
final String prefer = "return-content";
final ODataEntity actual = createCollectionNavigation(format, 77, contentType, prefer);
delete(format, actual, false, testStaticServiceRootURL);
}
// create a navigation link
public ODataEntity createNavigation(final ODataPubFormat format, final int id, final String contenttype,
final String prefer) {
final String name = "Customer Navigation test";
final ODataEntity original = getNewCustomer(id, name, false);
original.addLink(client.getObjectFactory().newEntityNavigationLink(
"Info", URI.create(testStaticServiceRootURL + "/CustomerInfo(11)")));
final ODataEntity created = createNav(testStaticServiceRootURL, format, original, "Customer", contenttype,
prefer);
final ODataEntity actual = validateEntities(testStaticServiceRootURL, format, created, id, null, "Customer");
final CommonURIBuilder<?> uriBuilder = client.getURIBuilder(testStaticServiceRootURL);
uriBuilder.appendEntitySetSegment("Customer").appendKeySegment(id).appendEntitySetSegment("Info");
final ODataEntityRequest<ODataEntity> req = client.getRetrieveRequestFactory().getEntityRequest(uriBuilder.build());
req.setFormat(format);
req.setContentType(contenttype);
req.setPrefer(prefer);
final ODataRetrieveResponse<ODataEntity> res = req.execute();
assertEquals(200, res.getStatusCode());
assertTrue(res.getHeader("DataServiceVersion").contains("3.0;"));
final ODataEntity entity = res.getBody();
assertNotNull(entity);
for (ODataProperty prop : entity.getProperties()) {
if ("CustomerInfoId".equals(prop.getName())) {
assertEquals("11", prop.getValue().toString());
}
}
return actual;
}
// create a navigation link
public ODataEntity createNav(final String url, final ODataPubFormat format, final ODataEntity original,
final String entitySetName, final String contentType, final String prefer) {
final CommonURIBuilder<?> uriBuilder = client.getURIBuilder(url);
uriBuilder.appendEntitySetSegment(entitySetName);
final ODataEntityCreateRequest<ODataEntity> createReq =
client.getCUDRequestFactory().getEntityCreateRequest(uriBuilder.build(), original);
createReq.setFormat(format);
createReq.setContentType(contentType);
createReq.setPrefer(prefer);
final ODataEntityCreateResponse<ODataEntity> createRes = createReq.execute();
assertEquals(201, createRes.getStatusCode());
assertEquals("Created", createRes.getStatusMessage());
final ODataEntity created = createRes.getBody();
assertNotNull(created);
return created;
}
// create collection navigation link
public ODataEntity createCollectionNavigation(final ODataPubFormat format, final int id,
final String contentType, final String prefer) throws EdmPrimitiveTypeException {
{
final String name = "Collection Navigation Key Customer";
final ODataEntity original = getNewCustomer(id, name, false);
final Set<Integer> navigationKeys = new HashSet<Integer>();
navigationKeys.add(-118);
navigationKeys.add(-119);
for (Integer key : navigationKeys) {
final ODataEntity orderEntity =
client.getObjectFactory().newEntity("Microsoft.Test.OData.Services.AstoriaDefaultService.Order");
getClient().getBinder().add(orderEntity,
client.getObjectFactory().newPrimitiveProperty("OrderId",
client.getObjectFactory().newPrimitiveValueBuilder().setValue(key).
setType(EdmPrimitiveTypeKind.Int32).build()));
getClient().getBinder().add(orderEntity,
client.getObjectFactory().newPrimitiveProperty("CustomerId",
client.getObjectFactory().newPrimitiveValueBuilder().setValue(id).
setType(EdmPrimitiveTypeKind.Int32).build()));
final ODataEntityCreateRequest<ODataEntity> createReq = client.getCUDRequestFactory().getEntityCreateRequest(
client.getURIBuilder(testStaticServiceRootURL).appendEntitySetSegment("Order").build(),
orderEntity);
createReq.setFormat(format);
createReq.setContentType(contentType);
original.addLink(client.getObjectFactory().newEntitySetNavigationLink(
"Orders",
createReq.execute().getBody().getEditLink()));
}
final ODataEntity createdEntity = createNav(testStaticServiceRootURL, format, original, "Customer",
contentType, prefer);
final ODataEntity actualEntity =
validateEntities(testStaticServiceRootURL, format, createdEntity, id, null, "Customer");
final CommonURIBuilder<?> uriBuilder = client.getURIBuilder(testStaticServiceRootURL);
uriBuilder.appendEntitySetSegment("Customer").appendKeySegment(id).appendEntitySetSegment("Orders");
final ODataEntitySetRequest<ODataEntitySet> req = client.getRetrieveRequestFactory().
getEntitySetRequest(uriBuilder.build());
req.setFormat(format);
final ODataRetrieveResponse<ODataEntitySet> res = req.execute();
assertEquals(200, res.getStatusCode());
final ODataEntitySet entitySet = res.getBody();
assertNotNull(entitySet);
assertEquals(2, entitySet.getCount());
for (ODataEntity entity : entitySet.getEntities()) {
final Integer key = entity.getProperty("OrderId").getPrimitiveValue().toCastValue(Integer.class);
final Integer customerId = entity.getProperty("CustomerId").getPrimitiveValue().toCastValue(Integer.class);
assertTrue(navigationKeys.contains(key));
assertEquals(Integer.valueOf(id), customerId);
navigationKeys.remove(key);
final ODataDeleteRequest deleteReq = client.getCUDRequestFactory().getDeleteRequest(
URIUtils.getURI(testStaticServiceRootURL, entity.getEditLink().toASCIIString()));
deleteReq.setFormat(format);
assertEquals(204, deleteReq.execute().getStatusCode());
}
return actualEntity;
}
}
// get a Customer entity to be created
public ODataEntity getNewCustomer(
final int id, final String name, final boolean withInlineInfo) {
final ODataEntity entity =
client.getObjectFactory().newEntity("Microsoft.Test.OData.Services.AstoriaDefaultService.Customer");
// add name attribute
getClient().getBinder().add(entity,
client.getObjectFactory().newPrimitiveProperty("Name",
client.getObjectFactory().newPrimitiveValueBuilder().setText(name).
setType(EdmPrimitiveTypeKind.String).build()));
// add key attribute
if (id != 0) {
getClient().getBinder().add(entity,
client.getObjectFactory().newPrimitiveProperty("CustomerId",
client.getObjectFactory().newPrimitiveValueBuilder().setText(String.valueOf(id)).
setType(EdmPrimitiveTypeKind.Int32).build()));
}
final ODataCollectionValue<ODataValue> backupContactInfoValue = getClient().getObjectFactory().newCollectionValue(
"Collection(Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails)");
final ODataComplexValue<ODataProperty> contactDetails = getClient().getObjectFactory().newComplexValue(
"Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails");
final ODataCollectionValue<ODataValue> altNamesValue = getClient().getObjectFactory().
newCollectionValue("Collection(Edm.String)");
altNamesValue.add(client.getObjectFactory().newPrimitiveValueBuilder().
setText("My Alternative name").setType(EdmPrimitiveTypeKind.String).build());
contactDetails.add(client.getObjectFactory().newCollectionProperty("AlternativeNames", altNamesValue));
final ODataCollectionValue<ODataValue> emailBagValue = getClient().getObjectFactory().
newCollectionValue("Collection(Edm.String)");
emailBagValue.add(client.getObjectFactory().newPrimitiveValueBuilder().
setText("altname@mydomain.com").setType(EdmPrimitiveTypeKind.String).build());
contactDetails.add(client.getObjectFactory().newCollectionProperty("EmailBag", emailBagValue));
final ODataComplexValue<ODataProperty> contactAliasValue = getClient().getObjectFactory().newComplexValue(
"Microsoft.Test.OData.Services.AstoriaDefaultService.Aliases");
contactDetails.add(client.getObjectFactory().newComplexProperty("ContactAlias", contactAliasValue));
final ODataCollectionValue<ODataValue> aliasAltNamesValue = getClient().getObjectFactory().
newCollectionValue("Collection(Edm.String)");
aliasAltNamesValue.add(client.getObjectFactory().newPrimitiveValueBuilder().
setText("myAlternativeName").setType(EdmPrimitiveTypeKind.String).build());
contactAliasValue.add(client.getObjectFactory().newCollectionProperty("AlternativeNames", aliasAltNamesValue));
final ODataComplexValue<ODataProperty> homePhone = getClient().getObjectFactory().newComplexValue(
"Microsoft.Test.OData.Services.AstoriaDefaultService.Phone");
homePhone.add(client.getObjectFactory().newPrimitiveProperty("PhoneNumber",
client.getObjectFactory().newPrimitiveValueBuilder().setText("8437568356834568").
setType(EdmPrimitiveTypeKind.String).build()));
homePhone.add(client.getObjectFactory().newPrimitiveProperty("Extension",
client.getObjectFactory().newPrimitiveValueBuilder().setText("124365426534621534423ttrf").
setType(EdmPrimitiveTypeKind.String).
build()));
contactDetails.add(client.getObjectFactory().newComplexProperty("HomePhone", homePhone));
backupContactInfoValue.add(contactDetails);
getClient().getBinder().add(entity,
client.getObjectFactory().newCollectionProperty("BackupContactInfo", backupContactInfoValue));
if (withInlineInfo) {
final ODataInlineEntity inlineInfo = client.getObjectFactory().newInlineEntity("Info", URI.create(
"Customer(" + id
+ ")/Info"), getInfo(id, name + "_Info"));
inlineInfo.getEntity().setMediaEntity(true);
entity.addLink(inlineInfo);
}
return entity;
}
//delete an entity and associated links after creation
public void delete(final ODataPubFormat format, final ODataEntity created, final boolean includeInline,
final String baseUri) {
final Set<URI> toBeDeleted = new HashSet<URI>();
toBeDeleted.add(created.getEditLink());
if (includeInline) {
for (ODataLink link : created.getNavigationLinks()) {
if (link instanceof ODataInlineEntity) {
final CommonODataEntity inline = ((ODataInlineEntity) link).getEntity();
if (inline.getEditLink() != null) {
toBeDeleted.add(URIUtils.getURI(baseUri, inline.getEditLink().toASCIIString()));
}
}
if (link instanceof ODataInlineEntitySet) {
final CommonODataEntitySet inline = ((ODataInlineEntitySet) link).getEntitySet();
for (CommonODataEntity entity : inline.getEntities()) {
if (entity.getEditLink() != null) {
toBeDeleted.add(URIUtils.getURI(baseUri, entity.getEditLink().toASCIIString()));
}
}
}
}
}
assertFalse(toBeDeleted.isEmpty());
for (URI link : toBeDeleted) {
final ODataDeleteRequest deleteReq = client.getCUDRequestFactory().getDeleteRequest(link);
final ODataDeleteResponse deleteRes = deleteReq.execute();
assertEquals(204, deleteRes.getStatusCode());
assertEquals("No Content", deleteRes.getStatusMessage());
deleteRes.close();
}
}
// add Information property
public ODataEntity getInfo(final int id, final String info) {
final ODataEntity entity =
client.getObjectFactory().newEntity("Microsoft.Test.OData.Services.AstoriaDefaultService.CustomerInfo");
entity.setMediaEntity(true);
getClient().getBinder().add(entity, client.getObjectFactory().newPrimitiveProperty("Information",
client.getObjectFactory().newPrimitiveValueBuilder().setText(info).
setType(EdmPrimitiveTypeKind.String).build()));
return entity;
}
// validate newly created entities
public ODataEntity validateEntities(final String serviceRootURL,
final ODataPubFormat format,
final ODataEntity original,
final int actualObjectId,
final Collection<String> expands, final String entitySetName) {
final CommonURIBuilder<?> uriBuilder = client.getURIBuilder(serviceRootURL).
appendEntitySetSegment(entitySetName).appendKeySegment(actualObjectId);
if (expands != null) {
for (String expand : expands) {
uriBuilder.expand(expand);
}
}
final ODataEntityRequest<ODataEntity> req = client.getRetrieveRequestFactory().getEntityRequest(uriBuilder.build());
req.setFormat(format);
final ODataRetrieveResponse<ODataEntity> res = req.execute();
assertEquals(200, res.getStatusCode());
final ODataEntity actual = res.getBody();
assertNotNull(actual);
validateLinks(original.getAssociationLinks(), actual.getAssociationLinks());
validateLinks(original.getEditMediaLinks(), actual.getEditMediaLinks());
validateLinks(original.getNavigationLinks(), actual.getNavigationLinks());
checkProperties(original.getProperties(), actual.getProperties());
return actual;
}
// compares links of the newly created entity with the previous
public void validateLinks(final Collection<ODataLink> original, final Collection<ODataLink> actual) {
assertTrue(original.size() <= actual.size());
for (ODataLink originalLink : original) {
ODataLink foundOriginal = null;
ODataLink foundActual = null;
for (ODataLink actualLink : actual) {
if (actualLink.getType() == originalLink.getType()
&& (originalLink.getLink() == null
|| actualLink.getLink().toASCIIString().endsWith(originalLink.getLink().toASCIIString()))
&& actualLink.getName().equals(originalLink.getName())) {
foundOriginal = originalLink;
foundActual = actualLink;
}
}
assertNotNull(foundOriginal);
assertNotNull(foundActual);
if (foundOriginal instanceof ODataInlineEntity && foundActual instanceof ODataInlineEntity) {
final CommonODataEntity originalInline = ((ODataInlineEntity) foundOriginal).getEntity();
assertNotNull(originalInline);
final CommonODataEntity actualInline = ((ODataInlineEntity) foundActual).getEntity();
assertNotNull(actualInline);
checkProperties(originalInline.getProperties(), actualInline.getProperties());
}
}
}
// compares properties of the newly created entity with the properties that were originally provided
@Override
public void checkProperties(final Collection<? extends CommonODataProperty> original,
final Collection<? extends CommonODataProperty> actual) {
assertTrue(original.size() <= actual.size());
final Map<String, CommonODataProperty> actualProperties = new HashMap<String, CommonODataProperty>(actual.size());
for (CommonODataProperty prop : actual) {
assertFalse(actualProperties.containsKey(prop.getName()));
actualProperties.put(prop.getName(), prop);
}
assertTrue(actual.size() <= actualProperties.size());
for (CommonODataProperty prop : original) {
assertNotNull(prop);
if (actualProperties.containsKey(prop.getName())) {
final CommonODataProperty actualProp = actualProperties.get(prop.getName());
assertNotNull(actualProp);
if (prop.getValue() != null && actualProp.getValue() != null) {
checkPropertyValue(prop.getName(), prop.getValue(), actualProp.getValue());
}
}
}
}
// compares property value of the newly created entity with the property value that were originally provided
@Override
public void checkPropertyValue(final String propertyName,
final ODataValue original, final ODataValue actual) {
assertNotNull("Null original value for " + propertyName, original);
assertNotNull("Null actual value for " + propertyName, actual);
assertEquals("Type mismatch for '" + propertyName + "'",
original.getClass().getSimpleName(), actual.getClass().getSimpleName());
if (original.isComplex()) {
final List<CommonODataProperty> originalPropertyValue = new ArrayList<CommonODataProperty>();
for (CommonODataProperty prop : original.asComplex()) {
originalPropertyValue.add(prop);
}
final List<CommonODataProperty> actualPropertyValue = new ArrayList<CommonODataProperty>();
for (CommonODataProperty prop : actual.asComplex()) {
actualPropertyValue.add(prop);
}
checkProperties(originalPropertyValue, actualPropertyValue);
} else if (original.isCollection()) {
assertTrue(original.asCollection().size() <= actual.asCollection().size());
boolean found = original.asCollection().isEmpty();
for (ODataValue originalValue : original.asCollection()) {
for (ODataValue actualValue : actual.asCollection()) {
try {
checkPropertyValue(propertyName, originalValue, actualValue);
found = true;
} catch (AssertionError error) {
}
}
}
assertTrue("Found " + actual + " and expected " + original, found);
} else {
assertTrue("Primitive value for '" + propertyName + "' type mismatch",
original.asPrimitive().getTypeKind() == actual.asPrimitive().getTypeKind());
assertEquals("Primitive value for '" + propertyName + "' mismatch",
original.asPrimitive().toString(), actual.asPrimitive().toString());
}
}
}

View File

@ -253,7 +253,7 @@ public class PropertyTestITCase extends AbstractTestITCase {
private void updateCollectionProperty(final ODataFormat format) throws IOException {
final CommonURIBuilder<?> uriBuilder = client.getURIBuilder(getServiceRoot());
uriBuilder.appendEntitySetSegment("Customer").appendKeySegment(-9).
uriBuilder.appendEntitySetSegment("Customer").appendKeySegment(-10).
appendPropertySegment("PrimaryContactInfo").appendPropertySegment("AlternativeNames");
ODataPropertyRequest<ODataProperty> retrieveReq = client.getRetrieveRequestFactory().
@ -277,7 +277,7 @@ public class PropertyTestITCase extends AbstractTestITCase {
final ODataPropertyUpdateRequest updateReq =
client.getCUDRequestFactory().getPropertyCollectionValueUpdateRequest(uriBuilder.build(),
alternativeNames);
alternativeNames);
if (client.getConfiguration().isUseXHTTPMethod()) {
assertEquals(HttpMethod.POST, updateReq.getMethod());
} else {

View File

@ -22,6 +22,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import java.net.URI;
import java.util.LinkedHashMap;
@ -42,7 +43,7 @@ import org.apache.olingo.commons.api.domain.v4.ODataEntity;
import org.apache.olingo.commons.api.domain.v4.ODataEntitySet;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.format.ODataPubFormat;
import org.junit.Ignore;
import org.junit.Test;
/**
@ -70,7 +71,13 @@ public class EntityRetrieveTestITCase extends AbstractTestITCase {
assertEquals(getServiceRoot() + "/Customers(PersonID=1)", entity.getEditLink().toASCIIString());
assertEquals(3, entity.getNavigationLinks().size());
assertTrue(entity.getAssociationLinks().isEmpty());
if (ODataPubFormat.ATOM == format) {
assertTrue(entity.getAssociationLinks().isEmpty());
} else {
// In JSON, association links for each $ref link will exist.
assertFalse(entity.getAssociationLinks().isEmpty());
}
boolean found = false;
@ -106,7 +113,6 @@ public class EntityRetrieveTestITCase extends AbstractTestITCase {
}
@Test
@Ignore
public void withInlineEntryFromJSON() {
// this needs to be full, otherwise there is no mean to recognize links
withInlineEntry(ODataPubFormat.JSON_FULL_METADATA);
@ -144,7 +150,6 @@ public class EntityRetrieveTestITCase extends AbstractTestITCase {
}
@Test
@Ignore
public void withInlineFeedFromJSON() {
// this needs to be full, otherwise there is no mean to recognize links
withInlineFeed(ODataPubFormat.JSON_FULL_METADATA);
@ -173,7 +178,6 @@ public class EntityRetrieveTestITCase extends AbstractTestITCase {
}
@Test
@Ignore
public void rawRequestAsJSON() {
// this needs to be full, otherwise actions will not be provided
rawRequest(ODataPubFormat.JSON_FULL_METADATA);
@ -203,7 +207,6 @@ public class EntityRetrieveTestITCase extends AbstractTestITCase {
}
@Test
@Ignore
public void multiKeyAsJSON() throws EdmPrimitiveTypeException {
multiKey(ODataPubFormat.JSON_FULL_METADATA);
}
@ -214,7 +217,6 @@ public class EntityRetrieveTestITCase extends AbstractTestITCase {
}
@Test
@Ignore
public void checkForETagAsJSON() {
checkForETag(ODataPubFormat.JSON_FULL_METADATA);
}
@ -237,9 +239,8 @@ public class EntityRetrieveTestITCase extends AbstractTestITCase {
}
@Test(expected = IllegalArgumentException.class)
@Ignore
public void issue99() {
final CommonURIBuilder<?> uriBuilder = client.getURIBuilder(getServiceRoot()).appendEntitySetSegment("Car");
final CommonURIBuilder<?> uriBuilder = client.getURIBuilder(getServiceRoot()).appendEntitySetSegment("Orders");
final ODataEntityRequest<ODataEntity> req = client.getRetrieveRequestFactory().getEntityRequest(uriBuilder.build());
req.setFormat(ODataPubFormat.JSON);
@ -255,7 +256,6 @@ public class EntityRetrieveTestITCase extends AbstractTestITCase {
}
@Test
@Ignore
public void retrieveEntityViaReferenceAsJSON() {
retrieveEntityViaReference(ODataPubFormat.JSON_FULL_METADATA);
}

View File

@ -36,7 +36,6 @@ import org.apache.olingo.commons.api.domain.CommonODataEntitySet;
import org.apache.olingo.commons.api.domain.v4.ODataEntity;
import org.apache.olingo.commons.api.domain.v4.ODataEntitySet;
import org.apache.olingo.commons.api.format.ODataPubFormat;
import org.junit.Ignore;
import org.junit.Test;
/**
@ -54,7 +53,6 @@ public class EntitySetTestITCase extends AbstractTestITCase {
}
@Test
@Ignore
public void rawRequestAsJSON() throws IOException {
rawRequest(ODataPubFormat.JSON);
}
@ -65,19 +63,16 @@ public class EntitySetTestITCase extends AbstractTestITCase {
}
@Test
@Ignore
public void readODataEntitySetIteratorFromJSON() {
readODataEntitySetIterator(ODataPubFormat.JSON);
}
@Test
@Ignore
public void readODataEntitySetIteratorFromJSONFullMeta() {
readODataEntitySetIterator(ODataPubFormat.JSON_FULL_METADATA);
}
@Test
@Ignore
public void readODataEntitySetIteratorFromJSONNoMeta() {
readODataEntitySetIterator(ODataPubFormat.JSON_NO_METADATA);
}
@ -88,7 +83,6 @@ public class EntitySetTestITCase extends AbstractTestITCase {
}
@Test
@Ignore
public void readODataEntitySetWithNextFromJSON() {
readEntitySetWithNextLink(ODataPubFormat.JSON_FULL_METADATA);
}
@ -126,7 +120,7 @@ public class EntitySetTestITCase extends AbstractTestITCase {
req.setFormat(format);
final ODataRetrieveResponse<ODataEntitySetIterator<ODataEntitySet, ODataEntity>> res = req.execute();
final ODataEntitySetIterator feedIterator = res.getBody();
final ODataEntitySetIterator<ODataEntitySet, ODataEntity> feedIterator = res.getBody();
assertNotNull(feedIterator);

View File

@ -26,7 +26,6 @@ import org.apache.olingo.client.api.communication.request.retrieve.ODataServiceD
import org.apache.olingo.client.api.communication.response.ODataRetrieveResponse;
import org.apache.olingo.commons.api.domain.ODataServiceDocument;
import org.apache.olingo.commons.api.format.ODataFormat;
import org.junit.Ignore;
import org.junit.Test;
public class ServiceDocumentTestITCase extends AbstractTestITCase {
@ -40,9 +39,9 @@ public class ServiceDocumentTestITCase extends AbstractTestITCase {
assertEquals(200, res.getStatusCode());
final ODataServiceDocument serviceDocument = res.getBody();
assertEquals(12, serviceDocument.getEntitySetTitles().size());
assertEquals(6, serviceDocument.getSingletonTitles().size());
assertEquals(6, serviceDocument.getFunctionImportTitles().size());
assertEquals(12, serviceDocument.getEntitySets().size());
assertEquals(6, serviceDocument.getSingletons().size());
assertEquals(6, serviceDocument.getFunctionImports().size());
assertTrue(res.getContextURL().toASCIIString().endsWith("/StaticService/V40/Static.svc/$metadata"));
assertEquals(URI.create(testStaticServiceRootURL + "/ProductDetails"),
@ -59,7 +58,6 @@ public class ServiceDocumentTestITCase extends AbstractTestITCase {
}
@Test
@Ignore
public void retrieveServiceDocumentAsJSON() {
retrieveServiceDocument(ODataFormat.JSON);
}

View File

@ -23,11 +23,13 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import org.apache.olingo.client.api.data.ServiceDocument;
import org.apache.olingo.client.api.v4.ODataClient;
import org.apache.olingo.commons.api.domain.ODataServiceDocument;
import org.apache.olingo.commons.api.format.ODataFormat;
import org.apache.olingo.client.core.AbstractTest;
import org.apache.olingo.commons.api.data.Container;
import org.junit.Test;
public class ServiceDocumentTest extends AbstractTest {
@ -42,13 +44,18 @@ public class ServiceDocumentTest extends AbstractTest {
}
private ODataServiceDocument parse(final ODataFormat format) {
final ODataServiceDocument serviceDocument = getClient().getReader().readServiceDocument(
Container<ServiceDocument> service = getClient().getDeserializer().toServiceDocument(
getClass().getResourceAsStream("serviceDocument." + getFileExtension(format)), format);
assertEquals(URI.create("http://host/service/$metadata"), service.getContextURL());
assertEquals("W/\"MjAxMy0wNS0xM1QxNDo1NFo=\"", service.getMetadataETag());
final ODataServiceDocument serviceDocument = getClient().getBinder().getODataServiceDocument(service.getObject());
assertNotNull(serviceDocument);
assertEquals(URI.create("http://host/service/$metadata"), serviceDocument.getMetadataContext());
assertTrue(serviceDocument.getEntitySetTitles().contains("Order Details"));
assertEquals(URI.create("http://host/service/TopProducts"),
serviceDocument.getFunctionImportURI("Best-Selling Products"));
serviceDocument.getFunctionImportURI("TopProducts"));
assertEquals(URI.create("http://host/HR/"),
serviceDocument.getRelatedServiceDocumentsURIs().iterator().next());
@ -63,6 +70,5 @@ public class ServiceDocumentTest extends AbstractTest {
@Test
public void xml() {
final ODataServiceDocument serviceDocument = parse(ODataFormat.XML);
assertEquals("W/\"MjAxMy0wNS0xM1QxNDo1NFo=\"", serviceDocument.getMetadataETag());
}
}

View File

@ -1,5 +1,6 @@
{
"@odata.context": "http://host/service/$metadata",
"@odata.metadataEtag": "W/\"MjAxMy0wNS0xM1QxNDo1NFo=\"",
"value": [
{
"name": "Orders",

View File

@ -25,10 +25,6 @@ import java.util.Map;
public class ODataServiceDocument {
private URI metadataContext;
private String metadataETag;
private final Map<String, URI> entitySets = new HashMap<String, URI>();
private final Map<String, URI> functionImports = new HashMap<String, URI>();
@ -37,22 +33,6 @@ public class ODataServiceDocument {
private final Map<String, URI> relatedServiceDocuments = new HashMap<String, URI>();
public URI getMetadataContext() {
return metadataContext;
}
public void setMetadataContext(final URI metadataContext) {
this.metadataContext = metadataContext;
}
public String getMetadataETag() {
return metadataETag;
}
public void setMetadataETag(final String metadataETag) {
this.metadataETag = metadataETag;
}
public Map<String, URI> getEntitySets() {
return entitySets;
}

View File

@ -25,12 +25,13 @@ import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.olingo.commons.api.data.CollectionValue;
import org.apache.olingo.commons.api.data.ComplexValue;
import org.apache.olingo.commons.api.data.Container;
import org.apache.olingo.commons.api.data.Value;
import org.apache.olingo.commons.api.domain.ODataPropertyType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.apache.olingo.commons.core.edm.EdmTypeInfo;
abstract class AbstractJsonDeserializer<T> extends ODataJacksonDeserializer<T> {
abstract class AbstractJsonDeserializer<T> extends ODataJacksonDeserializer<Container<T>> {
private JSONGeoValueDeserializer geoDeserializer;

View File

@ -22,6 +22,7 @@ import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
@ -33,6 +34,7 @@ import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.olingo.commons.api.Constants;
import org.apache.olingo.commons.api.data.Container;
import org.apache.olingo.commons.api.data.Link;
import org.apache.olingo.commons.api.domain.ODataLinkType;
import org.apache.olingo.commons.api.domain.ODataOperation;
@ -58,7 +60,10 @@ public class JSONEntryDeserializer extends AbstractJsonDeserializer<JSONEntryImp
if (inline instanceof ObjectNode) {
link.setType(ODataLinkType.ENTITY_NAVIGATION.toString());
link.setInlineEntry(inline.traverse(codec).readValuesAs(JSONEntryImpl.class).next());
link.setInlineEntry(inline.traverse(codec).<Container<JSONEntryImpl>>readValueAs(
new TypeReference<JSONEntryImpl>() {
}).getObject());
}
if (inline instanceof ArrayNode) {
@ -67,7 +72,9 @@ public class JSONEntryDeserializer extends AbstractJsonDeserializer<JSONEntryImp
final JSONFeedImpl feed = new JSONFeedImpl();
final Iterator<JsonNode> entries = ((ArrayNode) inline).elements();
while (entries.hasNext()) {
feed.getEntries().add(entries.next().traverse(codec).readValuesAs(JSONEntryImpl.class).next());
feed.getEntries().add(entries.next().traverse(codec).<Container<JSONEntryImpl>>readValuesAs(
new TypeReference<JSONEntryImpl>() {
}).next().getObject());
}
link.setInlineFeed(feed);
@ -77,7 +84,7 @@ public class JSONEntryDeserializer extends AbstractJsonDeserializer<JSONEntryImp
}
@Override
protected JSONEntryImpl doDeserialize(final JsonParser parser, final DeserializationContext ctxt)
protected Container<JSONEntryImpl> doDeserialize(final JsonParser parser, final DeserializationContext ctxt)
throws IOException, JsonProcessingException {
final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);
@ -86,18 +93,30 @@ public class JSONEntryDeserializer extends AbstractJsonDeserializer<JSONEntryImp
throw new JsonParseException("Expected OData Entity, found EntitySet", parser.getCurrentLocation());
}
final String metadataETag;
final URI contextURL;
final JSONEntryImpl entry = new JSONEntryImpl();
String contextURL = null;
if (tree.hasNonNull(Constants.JSON_METADATA_ETAG)) {
metadataETag = tree.get(Constants.JSON_METADATA_ETAG).textValue();
tree.remove(Constants.JSON_METADATA_ETAG);
} else {
metadataETag = null;
}
if (tree.hasNonNull(Constants.JSON_CONTEXT)) {
contextURL = tree.get(Constants.JSON_CONTEXT).textValue();
contextURL = URI.create(tree.get(Constants.JSON_CONTEXT).textValue());
tree.remove(Constants.JSON_CONTEXT);
} else if (tree.hasNonNull(Constants.JSON_METADATA)) {
contextURL = tree.get(Constants.JSON_METADATA).textValue();
contextURL = URI.create(tree.get(Constants.JSON_METADATA).textValue());
tree.remove(Constants.JSON_METADATA);
} else {
contextURL = null;
}
if (contextURL != null) {
entry.setBaseURI(contextURL.substring(0, contextURL.indexOf(Constants.METADATA)));
String url = contextURL.toASCIIString();
entry.setBaseURI(url.substring(0, url.indexOf(Constants.METADATA)));
}
if (tree.hasNonNull(jsonETag)) {
@ -237,6 +256,6 @@ public class JSONEntryDeserializer extends AbstractJsonDeserializer<JSONEntryImp
}
}
return entry;
return new Container<JSONEntryImpl>(contextURL, metadataETag, entry);
}
}

View File

@ -20,6 +20,7 @@ package org.apache.olingo.commons.core.data;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
@ -27,6 +28,7 @@ import java.io.IOException;
import java.net.URI;
import java.util.Iterator;
import org.apache.olingo.commons.api.Constants;
import org.apache.olingo.commons.api.data.Container;
/**
* Reads JSON string into a feed.
@ -36,7 +38,7 @@ import org.apache.olingo.commons.api.Constants;
public class JSONFeedDeserializer extends AbstractJsonDeserializer<JSONFeedImpl> {
@Override
protected JSONFeedImpl doDeserialize(final JsonParser parser, final DeserializationContext ctxt)
protected Container<JSONFeedImpl> doDeserialize(final JsonParser parser, final DeserializationContext ctxt)
throws IOException, JsonProcessingException {
final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);
@ -45,16 +47,29 @@ public class JSONFeedDeserializer extends AbstractJsonDeserializer<JSONFeedImpl>
return null;
}
final String metadataETag;
final URI contextURL;
final JSONFeedImpl feed = new JSONFeedImpl();
if (tree.hasNonNull(Constants.JSON_METADATA_ETAG)) {
metadataETag = tree.get(Constants.JSON_METADATA_ETAG).textValue();
tree.remove(Constants.JSON_METADATA_ETAG);
} else {
metadataETag = null;
}
if (tree.hasNonNull(Constants.JSON_CONTEXT)) {
feed.setContextURL(URI.create(tree.get(Constants.JSON_CONTEXT).textValue()));
contextURL = URI.create(tree.get(Constants.JSON_CONTEXT).textValue());
tree.remove(Constants.JSON_CONTEXT);
} else if (tree.hasNonNull(Constants.JSON_METADATA)) {
feed.setContextURL(URI.create(tree.get(Constants.JSON_METADATA).textValue()));
contextURL = URI.create(tree.get(Constants.JSON_METADATA).textValue());
tree.remove(Constants.JSON_METADATA);
} else {
contextURL = null;
}
feed.setMetadataContextURL(contextURL);
if (tree.hasNonNull(Constants.JSON_COUNT)) {
feed.setCount(tree.get(Constants.JSON_COUNT).asInt());
}
@ -64,10 +79,13 @@ public class JSONFeedDeserializer extends AbstractJsonDeserializer<JSONFeedImpl>
if (tree.hasNonNull(Constants.VALUE)) {
for (final Iterator<JsonNode> itor = tree.get(Constants.VALUE).iterator(); itor.hasNext();) {
feed.getEntries().add(itor.next().traverse(parser.getCodec()).readValueAs(JSONEntryImpl.class));
feed.getEntries().add(
itor.next().traverse(parser.getCodec()).<Container<JSONEntryImpl>>readValueAs(
new TypeReference<JSONEntryImpl>() {
}).getObject());
}
}
return feed;
return new Container<JSONFeedImpl>(contextURL, metadataETag, feed);
}
}

View File

@ -38,7 +38,7 @@ public class JSONFeedImpl extends AbstractPayloadObject implements Feed {
private static final long serialVersionUID = -3576372289800799417L;
private URI contextURL;
private URI metadataContextURL;
private String id;
@ -51,16 +51,16 @@ public class JSONFeedImpl extends AbstractPayloadObject implements Feed {
@Override
public URI getBaseURI() {
URI baseURI = null;
if (contextURL != null) {
final String metadataURI = contextURL.toASCIIString();
if (metadataContextURL != null) {
final String metadataURI = metadataContextURL.toASCIIString();
baseURI = URI.create(metadataURI.substring(0, metadataURI.indexOf(Constants.METADATA)));
}
return baseURI;
}
public void setContextURL(final URI context) {
this.contextURL = context;
public void setMetadataContextURL(final URI metadataContextURL) {
this.metadataContextURL = metadataContextURL;
}
@Override

View File

@ -25,11 +25,12 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import org.apache.olingo.commons.api.Constants;
import org.apache.olingo.commons.api.data.Container;
public class JSONODataErrorDeserializer extends AbstractJsonDeserializer<JSONODataErrorImpl> {
@Override
protected JSONODataErrorImpl doDeserialize(final JsonParser parser, final DeserializationContext ctxt)
protected Container<JSONODataErrorImpl> doDeserialize(final JsonParser parser, final DeserializationContext ctxt)
throws IOException, JsonProcessingException {
final JSONODataErrorImpl error = new JSONODataErrorImpl();
@ -54,7 +55,6 @@ public class JSONODataErrorDeserializer extends AbstractJsonDeserializer<JSONODa
}
}
return error;
return new Container<JSONODataErrorImpl>(null, null, error);
}
}

View File

@ -23,8 +23,10 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.net.URI;
import org.apache.commons.lang3.StringUtils;
import org.apache.olingo.commons.api.Constants;
import org.apache.olingo.commons.api.data.Container;
/**
* Parse JSON string into <tt>JSONPropertyImpl</tt>.
@ -34,27 +36,35 @@ import org.apache.olingo.commons.api.Constants;
public class JSONPropertyDeserializer extends AbstractJsonDeserializer<JSONPropertyImpl> {
@Override
protected JSONPropertyImpl doDeserialize(final JsonParser parser, final DeserializationContext ctxt)
protected Container<JSONPropertyImpl> doDeserialize(final JsonParser parser, final DeserializationContext ctxt)
throws IOException, JsonProcessingException {
final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);
final String metadataETag;
final URI contextURL;
final JSONPropertyImpl property = new JSONPropertyImpl();
if (tree.hasNonNull(Constants.JSON_CONTEXT)) {
final String contextURL = tree.get(Constants.JSON_CONTEXT).textValue();
property.setName(StringUtils.substringAfterLast(contextURL, "/"));
tree.remove(Constants.JSON_CONTEXT);
} else if (tree.hasNonNull(Constants.JSON_METADATA)) {
final String metadata = tree.get(Constants.JSON_METADATA).textValue();
final int dashIdx = metadata.lastIndexOf('#');
if (dashIdx != -1) {
property.setType(metadata.substring(dashIdx + 1));
}
tree.remove(Constants.JSON_METADATA);
if (tree.hasNonNull(Constants.JSON_METADATA_ETAG)) {
metadataETag = tree.get(Constants.JSON_METADATA_ETAG).textValue();
tree.remove(Constants.JSON_METADATA_ETAG);
} else {
metadataETag = null;
}
if (tree.has(jsonType) && property.getType() == null) {
if (tree.hasNonNull(Constants.JSON_CONTEXT)) {
contextURL = URI.create(tree.get(Constants.JSON_CONTEXT).textValue());
property.setName(StringUtils.substringAfterLast(contextURL.toASCIIString(), "/"));
tree.remove(Constants.JSON_CONTEXT);
} else if (tree.hasNonNull(Constants.JSON_METADATA)) {
contextURL = URI.create(tree.get(Constants.JSON_METADATA).textValue());
property.setType(StringUtils.substringAfterLast(contextURL.toASCIIString(), "#"));
tree.remove(Constants.JSON_METADATA);
} else {
contextURL = null;
}
if (tree.has(jsonType)) {
property.setType(tree.get(jsonType).asText());
}
@ -66,6 +76,6 @@ public class JSONPropertyDeserializer extends AbstractJsonDeserializer<JSONPrope
value(property, tree.has(Constants.VALUE) ? tree.get(Constants.VALUE) : tree);
}
return property;
return new Container<JSONPropertyImpl>(contextURL, metadataETag, property);
}
}

View File

@ -22,7 +22,6 @@ import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.edm.geo.Geospatial.Dimension;
import org.apache.olingo.commons.api.edm.geo.Geospatial.Type;
import org.apache.olingo.commons.api.edm.geo.MultiPoint;
import org.apache.olingo.commons.api.edm.geo.Point;
public final class EdmGeographyMultiPoint extends AbstractGeospatialType<MultiPoint> {

View File

@ -22,7 +22,6 @@ import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.edm.geo.Geospatial.Dimension;
import org.apache.olingo.commons.api.edm.geo.Geospatial.Type;
import org.apache.olingo.commons.api.edm.geo.GeospatialCollection;
import org.apache.olingo.commons.api.edm.geo.Point;
public final class EdmGeometryCollection extends AbstractGeospatialType<GeospatialCollection> {

View File

@ -18,9 +18,11 @@
*/
package org.apache.olingo.commons.core.op;
import com.fasterxml.jackson.core.type.TypeReference;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.Type;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
@ -101,10 +103,9 @@ public abstract class AbstractODataDeserializer extends AbstractJacksonTool impl
writer.flush();
writer.close();
return (Container<T>) atomDeserializer.getContainer(
start, getXmlMapper().readValue(new ByteArrayInputStream(baos.toByteArray()), reference));
final V obj = getXmlMapper().readValue(new ByteArrayInputStream(baos.toByteArray()), reference);
return (Container<T>) (obj instanceof Container ? obj : atomDeserializer.getContainer(start, obj));
} catch (Exception e) {
e.printStackTrace();
throw new IllegalArgumentException("While deserializing " + reference.getName(), e);
}
}
@ -119,7 +120,14 @@ public abstract class AbstractODataDeserializer extends AbstractJacksonTool impl
protected <T, V extends T> Container<T> json(final InputStream input, final Class<V> reference) {
try {
return new Container<T>(null, null, getObjectMapper().readValue(input, reference));
T obj = getObjectMapper().readValue(input, new TypeReference<V>() {
@Override
public Type getType() {
return reference;
}
});
return obj instanceof Container ? (Container<T>) obj : new Container<T>(null, null, obj);
} catch (Exception e) {
throw new IllegalArgumentException("While deserializing " + reference.getName(), e);
}