diff --git a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/AbstractInvocationHandler.java b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/AbstractInvocationHandler.java index 258a49620..ff4663e3f 100644 --- a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/AbstractInvocationHandler.java +++ b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/AbstractInvocationHandler.java @@ -69,7 +69,7 @@ abstract class AbstractInvocationHandler implements InvocationHandler { return service.getContext(); } - protected boolean isSelfMethod(final Method method, final Object[] args) { + protected boolean isSelfMethod(final Method method) { final Method[] selfMethods = getClass().getMethods(); boolean result = false; @@ -161,7 +161,7 @@ abstract class AbstractInvocationHandler implements InvocationHandler { CoreUtils.addProperties(getClient(), handler.getPropertyChanges(), template); final Object key = CoreUtils.getKey(getClient(), handler, handler.getUUID().getType(), template); - entityURI = CoreUtils.buildEditLink(getClient(), baseURI.toASCIIString(), template, key).build(); + entityURI = CoreUtils.buildEditLink(getClient(), baseURI.toASCIIString(), key).build(); template.setEditLink(entityURI); } else { entityURI = handler.getEntityURI(); @@ -182,32 +182,25 @@ abstract class AbstractInvocationHandler implements InvocationHandler { } } - protected static URIBuilder buildEntitySetURI( - final Class ref, - final AbstractService service) { + protected static URIBuilder buildEntitySetURI(final Class ref, final AbstractService service) { - final String containerNS; final String entitySetName; Annotation ann = ref.getAnnotation(EntitySet.class); if (ann instanceof EntitySet) { - containerNS = EntitySet.class.cast(ann).container(); entitySetName = EntitySet.class.cast(ann).name(); } else { ann = ref.getAnnotation(Singleton.class); if (ann instanceof Singleton) { - containerNS = Singleton.class.cast(ann).container(); entitySetName = Singleton.class.cast(ann).name(); } else { - containerNS = null; entitySetName = null; } } - return buildEntitySetURI(containerNS, entitySetName, service); + return buildEntitySetURI(entitySetName, service); } - protected static URIBuilder buildEntitySetURI( - final String containerNS, final String entitySetName, final AbstractService service) { + protected static URIBuilder buildEntitySetURI(final String entitySetName, final AbstractService service) { final URIBuilder uriBuilder = service.getClient().newURIBuilder(); final StringBuilder entitySetSegment = new StringBuilder(); diff --git a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/AbstractStructuredInvocationHandler.java b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/AbstractStructuredInvocationHandler.java index 96b3f2698..a44818692 100644 --- a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/AbstractStructuredInvocationHandler.java +++ b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/AbstractStructuredInvocationHandler.java @@ -210,7 +210,7 @@ public abstract class AbstractStructuredInvocationHandler extends AbstractInvoca || "refs".equals(method.getName())) { invokeSelfMethod(method, args); return proxy; - } else if (isSelfMethod(method, args)) { + } else if (isSelfMethod(method)) { return invokeSelfMethod(method, args); } else if ("load".equals(method.getName()) && ArrayUtils.isEmpty(args)) { load(); diff --git a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/AnnotatationsInvocationHandler.java b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/AnnotatationsInvocationHandler.java index fcd507899..8f0951d03 100644 --- a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/AnnotatationsInvocationHandler.java +++ b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/AnnotatationsInvocationHandler.java @@ -55,7 +55,7 @@ public class AnnotatationsInvocationHandler extends AbstractInvocationHandler { @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { - if (isSelfMethod(method, args)) { + if (isSelfMethod(method)) { return invokeSelfMethod(method, args); } else if (method.getName().startsWith("get") && method.getName().endsWith("Annotations")) { final Method getter = proxy.getClass().getInterfaces()[0].getMethod(method.getName()); diff --git a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/ComplexCollectionInvocationHandler.java b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/ComplexCollectionInvocationHandler.java index ff4fc66d4..8699ed4b8 100644 --- a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/ComplexCollectionInvocationHandler.java +++ b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/ComplexCollectionInvocationHandler.java @@ -80,7 +80,7 @@ public class ComplexCollectionInvocationHandler> invokeSelfMethod(method, args); return proxy; - } else if (isSelfMethod(method, args)) { + } else if (isSelfMethod(method)) { return invokeSelfMethod(method, args); } else if ("operations".equals(method.getName()) && ArrayUtils.isEmpty(args)) { final Class returnType = method.getReturnType(); diff --git a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/ComplexInvocationHandler.java b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/ComplexInvocationHandler.java index 3aa332608..1e2197c56 100644 --- a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/ComplexInvocationHandler.java +++ b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/ComplexInvocationHandler.java @@ -63,11 +63,7 @@ public class ComplexInvocationHandler extends AbstractStructuredInvocationHandle return new ImmutablePair>(complex, complexTypeRef); } - public static ComplexInvocationHandler getInstance( - final String propertyName, - final EntityInvocationHandler handler, - final Class typeRef) { - + public static ComplexInvocationHandler getInstance(final EntityInvocationHandler handler, final Class typeRef) { final Pair> init = init(typeRef, handler.service); return new ComplexInvocationHandler(init.getLeft(), init.getRight(), handler); } diff --git a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EdmStreamValueHandler.java b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EdmStreamValueHandler.java index d197f58d8..c13a3cf0d 100644 --- a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EdmStreamValueHandler.java +++ b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EdmStreamValueHandler.java @@ -59,7 +59,7 @@ public class EdmStreamValueHandler extends AbstractInvocationHandler { load(); return proxy; } else { - if (isSelfMethod(method, args)) { + if (isSelfMethod(method)) { return invokeSelfMethod(method, args); } else { throw new NoSuchMethodException(method.getName()); diff --git a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EntityCollectionInvocationHandler.java b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EntityCollectionInvocationHandler.java index 5c8da2c5c..e7d819aa6 100644 --- a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EntityCollectionInvocationHandler.java +++ b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EntityCollectionInvocationHandler.java @@ -62,7 +62,7 @@ public class EntityCollectionInvocationHandler> || "execute".equals(method.getName())) { invokeSelfMethod(method, args); return proxy; - } else if (isSelfMethod(method, args)) { + } else if (isSelfMethod(method)) { return invokeSelfMethod(method, args); } else if ("operations".equals(method.getName()) && ArrayUtils.isEmpty(args)) { final Class returnType = method.getReturnType(); diff --git a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EntityContainerInvocationHandler.java b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EntityContainerInvocationHandler.java index cb721269a..af8101b0c 100644 --- a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EntityContainerInvocationHandler.java +++ b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EntityContainerInvocationHandler.java @@ -80,7 +80,7 @@ public final class EntityContainerInvocationHandler extends AbstractInvocationHa @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { - if (isSelfMethod(method, args)) { + if (isSelfMethod(method)) { return invokeSelfMethod(method, args); } else if ("flush".equals(method.getName()) && ArrayUtils.isEmpty(args)) { service.getPersistenceManager().flush(); @@ -114,7 +114,7 @@ public final class EntityContainerInvocationHandler extends AbstractInvocationHa final Class typeRef = method.getReturnType(); final Singleton singleton = method.getAnnotation(Singleton.class); - final URI uri = buildEntitySetURI(singleton.container(), singleton.name(), service).build(); + final URI uri = buildEntitySetURI(singleton.name(), service).build(); final EntityUUID uuid = new EntityUUID(uri, typeRef); LOG.debug("Ask for singleton '{}'", typeRef.getSimpleName()); diff --git a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EntityInvocationHandler.java b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EntityInvocationHandler.java index c124402d3..e99314037 100644 --- a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EntityInvocationHandler.java +++ b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EntityInvocationHandler.java @@ -191,7 +191,7 @@ public class EntityInvocationHandler extends AbstractStructuredInvocationHandler this.uri = getClient().newURIBuilder(baseURI.toASCIIString()); } else if (key != null) { final URIBuilder uriBuilder = - CoreUtils.buildEditLink(getClient(), entitySetURI.toASCIIString(), entity, key); + CoreUtils.buildEditLink(getClient(), entitySetURI.toASCIIString(), key); this.uri = uriBuilder; this.baseURI = this.uri.build(); @@ -219,7 +219,7 @@ public class EntityInvocationHandler extends AbstractStructuredInvocationHandler if (this.uri == null) { final URIBuilder uriBuilder = entity.getEditLink() == null - ? CoreUtils.buildEditLink(getClient(), getUUID().getEntitySetURI().toASCIIString(), entity, key) + ? CoreUtils.buildEditLink(getClient(), getUUID().getEntitySetURI().toASCIIString(), key) : getClient().newURIBuilder(entity.getEditLink().toASCIIString()); this.uri = uriBuilder; @@ -252,7 +252,7 @@ public class EntityInvocationHandler extends AbstractStructuredInvocationHandler if (this.uri == null) { final URIBuilder uriBuilder = getEntity().getEditLink() == null - ? CoreUtils.buildEditLink(getClient(), entitySetURI.toASCIIString(), getEntity(), key) + ? CoreUtils.buildEditLink(getClient(), entitySetURI.toASCIIString(), key) : getClient().newURIBuilder(getEntity().getEditLink().toASCIIString()); this.uri = uriBuilder; diff --git a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EntitySetInvocationHandler.java b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EntitySetInvocationHandler.java index 8250f7224..9d1970abc 100644 --- a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EntitySetInvocationHandler.java +++ b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/EntitySetInvocationHandler.java @@ -84,7 +84,7 @@ public class EntitySetInvocationHandler< invokeSelfMethod(method, args); return proxy; - } else if (isSelfMethod(method, args)) { + } else if (isSelfMethod(method)) { return invokeSelfMethod(method, args); } else { throw new NoSuchMethodException(method.getName()); diff --git a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/InvokerInvocationHandler.java b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/InvokerInvocationHandler.java index 53208f782..3ed6121a5 100644 --- a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/InvokerInvocationHandler.java +++ b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/InvokerInvocationHandler.java @@ -276,7 +276,7 @@ public class InvokerInvocationHandler extends AbstractI return Proxy.newProxyInstance( Thread.currentThread().getContextClassLoader(), new Class[] {operationRef}, handler); - } else if (isSelfMethod(method, args)) { + } else if (isSelfMethod(method)) { return invokeSelfMethod(method, args); } else { throw new NoSuchMethodException(method.getName()); diff --git a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/OperationInvocationHandler.java b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/OperationInvocationHandler.java index bdab06cee..23cd25cef 100644 --- a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/OperationInvocationHandler.java +++ b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/OperationInvocationHandler.java @@ -133,7 +133,7 @@ final class OperationInvocationHandler extends AbstractInvocationHandler { @Override @SuppressWarnings({"unchecked", "rawtypes"}) public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { - if (isSelfMethod(method, args)) { + if (isSelfMethod(method)) { return invokeSelfMethod(method, args); } else { final Operation operation = method.getAnnotation(Operation.class); diff --git a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/PrimitiveCollectionInvocationHandler.java b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/PrimitiveCollectionInvocationHandler.java index 553af6e86..67d6e86e6 100644 --- a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/PrimitiveCollectionInvocationHandler.java +++ b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/PrimitiveCollectionInvocationHandler.java @@ -75,7 +75,7 @@ public class PrimitiveCollectionInvocationHandler invokeSelfMethod(method, args); return proxy; - } else if (isSelfMethod(method, args)) { + } else if (isSelfMethod(method)) { return invokeSelfMethod(method, args); } else if ("operations".equals(method.getName()) && ArrayUtils.isEmpty(args)) { final Class returnType = method.getReturnType(); diff --git a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/StructuredComposableInvokerInvocationHandler.java b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/StructuredComposableInvokerInvocationHandler.java index 41ec9ce82..00670b38c 100644 --- a/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/StructuredComposableInvokerInvocationHandler.java +++ b/ext/client-proxy/src/main/java/org/apache/olingo/ext/proxy/commons/StructuredComposableInvokerInvocationHandler.java @@ -75,7 +75,7 @@ public class StructuredComposableInvokerInvocationHandler[] { getter.getReturnType() }, - ComplexInvocationHandler.getInstance(property.getName(), typeHandler, getter.getReturnType())); + ComplexInvocationHandler.getInstance(typeHandler, getter.getReturnType())); populate(client, typeHandler, complex, Property.class, property.getValue().asComplex().iterator()); setPropertyValue(bean, getter, complex); @@ -530,7 +529,7 @@ public final class CoreUtils { final Object collItem = Proxy.newProxyInstance( Thread.currentThread().getContextClassLoader(), new Class[] { collItemClass }, - ComplexInvocationHandler.getInstance(property.getName(), typeHandler, collItemClass)); + ComplexInvocationHandler.getInstance(typeHandler, collItemClass)); populate(client, typeHandler, collItem, Property.class, value.asComplex().iterator()); collection.add(collItem); diff --git a/fit/src/main/java/org/apache/olingo/fit/AbstractServices.java b/fit/src/main/java/org/apache/olingo/fit/AbstractServices.java deleted file mode 100644 index c287e5b1e..000000000 --- a/fit/src/main/java/org/apache/olingo/fit/AbstractServices.java +++ /dev/null @@ -1,1947 +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.fit; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStreamWriter; -import java.net.URI; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.ConcurrentModificationException; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.mail.Header; -import javax.mail.internet.MimeBodyPart; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.HeaderParam; -import javax.ws.rs.NotFoundException; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.cxf.jaxrs.client.WebClient; -import org.apache.cxf.jaxrs.ext.multipart.Attachment; -import org.apache.cxf.jaxrs.ext.multipart.Multipart; -import org.apache.cxf.jaxrs.ext.multipart.MultipartBody; -import org.apache.olingo.client.api.data.ResWrap; -import org.apache.olingo.client.api.serialization.ODataDeserializer; -import org.apache.olingo.client.api.serialization.ODataSerializer; -import org.apache.olingo.client.core.serialization.AtomSerializer; -import org.apache.olingo.client.core.serialization.JsonDeserializer; -import org.apache.olingo.client.core.serialization.JsonSerializer; -import org.apache.olingo.commons.api.data.ComplexValue; -import org.apache.olingo.commons.api.data.Entity; -import org.apache.olingo.commons.api.data.EntityCollection; -import org.apache.olingo.commons.api.data.Link; -import org.apache.olingo.commons.api.data.Property; -import org.apache.olingo.commons.api.data.ValueType; -import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException; -import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; -import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion; -import org.apache.olingo.commons.api.format.ContentType; -import org.apache.olingo.commons.core.edm.primitivetype.EdmPrimitiveTypeFactory; -import org.apache.olingo.fit.metadata.EntityType; -import org.apache.olingo.fit.metadata.Metadata; -import org.apache.olingo.fit.metadata.NavigationProperty; -import org.apache.olingo.fit.methods.PATCH; -import org.apache.olingo.fit.serializer.FITAtomDeserializer; -import org.apache.olingo.fit.utils.AbstractUtilities; -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.FSManager; -import org.apache.olingo.fit.utils.JSONUtilities; -import org.apache.olingo.fit.utils.LinkInfo; -import org.apache.olingo.fit.utils.XMLUtilities; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -public abstract class AbstractServices { - - /** - * Logger. - */ - protected static final Logger LOG = LoggerFactory.getLogger(AbstractServices.class); - - private static final Pattern REQUEST_PATTERN = Pattern.compile("(.*) (http://.*) HTTP/.*"); - - private static final Pattern BATCH_REQUEST_REF_PATTERN = Pattern.compile("(.*) ([$]\\d+)(.*) HTTP/.*"); - - private static final Pattern REF_PATTERN = Pattern.compile("([$]\\d+)"); - - protected static final String BOUNDARY = "batch_243234_25424_ef_892u748"; - - protected static final String MULTIPART_MIXED = "multipart/mixed"; - - protected static final String APPLICATION_OCTET_STREAM = "application/octet-stream"; - - protected final ODataServiceVersion version; - - protected final Metadata metadata; - - protected final ODataDeserializer atomDeserializer; - - protected final ODataDeserializer jsonDeserializer; - - protected final ODataSerializer atomSerializer; - - protected final ODataSerializer jsonSerializer; - - protected final XMLUtilities xml; - - protected final JSONUtilities json; - - public AbstractServices(final ODataServiceVersion version, final Metadata metadata) throws IOException { - this.version = version; - this.metadata = metadata; - - atomDeserializer = new FITAtomDeserializer(); - jsonDeserializer = new JsonDeserializer(true); - atomSerializer = new AtomSerializer(true); - jsonSerializer = new JsonSerializer(true, ContentType.JSON_FULL_METADATA); - - xml = new XMLUtilities(metadata); - json = new JSONUtilities(metadata); - } - - /** - * Provide sample services. - * - * @param accept Accept header. - * @return OData services. - */ - @GET - public Response getSevices(@HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept) { - try { - final Accept acceptType = Accept.parse(accept); - - if (acceptType == Accept.ATOM) { - throw new UnsupportedMediaTypeException("Unsupported media type"); - } - - return xml.createResponse( - null, - FSManager.instance(version).readFile(Constants.get(ConstantKey.SERVICES), acceptType), - null, acceptType); - } catch (Exception e) { - return xml.createFaultResponse(accept, e); - } - } - - /** - * Provide sample getMetadata(). - * - * @return getMetadata(). - */ - @GET - @Path("/$metadata") - @Produces(MediaType.APPLICATION_XML) - public Response getMetadata() { - return getMetadata(Constants.get(ConstantKey.METADATA)); - } - - protected Response getMetadata(final String filename) { - try { - return xml.createResponse(null, FSManager.instance(version).readRes(filename, Accept.XML), null, Accept.XML); - } catch (Exception e) { - return xml.createFaultResponse(Accept.XML.toString(), e); - } - } - - @POST - @Path("/$batch") - @Consumes(MULTIPART_MIXED) - @Produces(APPLICATION_OCTET_STREAM + ";boundary=" + BOUNDARY) - public Response batch( - @HeaderParam("Authorization") @DefaultValue(StringUtils.EMPTY) final String authorization, - @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, - final @Multipart MultipartBody attachment) { - try { - final boolean continueOnError = prefer.contains("odata.continue-on-error"); - return xml.createBatchResponse( - exploreMultipart(attachment.getAllAttachments(), BOUNDARY, continueOnError)); - } catch (IOException e) { - return xml.createFaultResponse(Accept.XML.toString(), e); - } - } - - // ---------------------------------------------- - // just for non nullable property test into PropertyTestITCase - // ---------------------------------------------- - @PATCH - @Path("/Driver('2')") - public Response patchDriver() { - return xml.createFaultResponse(Accept.JSON_FULLMETA.toString(), new Exception("Non nullable properties")); - } - - @GET - @Path("/StoredPIs(1000)") - public Response getStoredPI(@Context final UriInfo uriInfo) { - final Entity entity = new Entity(); - entity.setType("Microsoft.Test.OData.Services.ODataWCFService.StoredPI"); - final Property id = new Property(); - id.setType("Edm.Int32"); - id.setName("StoredPIID"); - id.setValue(ValueType.PRIMITIVE, 1000); - entity.getProperties().add(id); - final Link edit = new Link(); - edit.setHref(uriInfo.getRequestUri().toASCIIString()); - edit.setRel("edit"); - edit.setTitle("StoredPI"); - entity.setEditLink(edit); - - final ByteArrayOutputStream content = new ByteArrayOutputStream(); - final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING); - try { - jsonSerializer.write(writer, new ResWrap((URI) null, null, entity)); - return xml.createResponse(new ByteArrayInputStream(content.toByteArray()), null, Accept.JSON_FULLMETA); - } catch (Exception e) { - LOG.error("While creating StoredPI", e); - return xml.createFaultResponse(Accept.JSON_FULLMETA.toString(), e); - } - } - - @PATCH - @Path("/StoredPIs(1000)") - public Response patchStoredPI() { - // just for non nullable property test into PropertyTestITCase - return xml.createFaultResponse(Accept.JSON_FULLMETA.toString(), new Exception("Non nullable properties")); - } - - // ---------------------------------------------- - - protected Response bodyPartRequest(final MimeBodyPart body) throws Exception { - return bodyPartRequest(body, Collections. emptyMap()); - } - - protected Response bodyPartRequest(final MimeBodyPart body, final Map references) throws Exception { - @SuppressWarnings("unchecked") - final Enumeration
en = body.getAllHeaders(); - - Header header = en.nextElement(); - final String request = - header.getName() + (StringUtils.isNotBlank(header.getValue()) ? ":" + header.getValue() : ""); - - final Matcher matcher = REQUEST_PATTERN.matcher(request); - final Matcher matcherRef = BATCH_REQUEST_REF_PATTERN.matcher(request); - - final MultivaluedMap headers = new MultivaluedHashMap(); - - while (en.hasMoreElements()) { - header = en.nextElement(); - headers.putSingle(header.getName(), header.getValue()); - } - - final Response res; - final String url; - final String method; - - if (matcher.find()) { - url = matcher.group(2); - method = matcher.group(1); - } else if (matcherRef.find()) { - url = references.get(matcherRef.group(2)) + matcherRef.group(3); - method = matcherRef.group(1); - } else { - url = null; - method = null; - } - - if (url == null) { - res = null; - } else { - final WebClient client = WebClient.create(url, "odatajclient", "odatajclient", null); - client.headers(headers); - - if ("DELETE".equals(method)) { - res = client.delete(); - } else { - final InputStream is = body.getDataHandler().getInputStream(); - String content = IOUtils.toString(is); - IOUtils.closeQuietly(is); - - final Matcher refs = REF_PATTERN.matcher(content); - - while (refs.find()) { - content = content.replace(refs.group(1), references.get(refs.group(1))); - } - - if ("PATCH".equals(method) || "MERGE".equals(method)) { - client.header("X-HTTP-METHOD", method); - res = client.invoke("POST", IOUtils.toInputStream(content)); - } else { - res = client.invoke(method, IOUtils.toInputStream(content)); - } - } - - // When updating to CXF 3.0.1, uncomment the following line, see CXF-5865 - // client.close(); - } - - return res; - } - - protected abstract InputStream exploreMultipart( - final List attachments, final String boundary, final boolean continueOnError) - throws IOException; - - protected void addItemIntro(final ByteArrayOutputStream bos) throws IOException { - addItemIntro(bos, null); - } - - protected void addItemIntro(final ByteArrayOutputStream bos, final String contentId) throws IOException { - bos.write("Content-Type: application/http".getBytes()); - bos.write(Constants.CRLF); - bos.write("Content-Transfer-Encoding: binary".getBytes()); - bos.write(Constants.CRLF); - - if (StringUtils.isNotBlank(contentId)) { - bos.write(("Content-ID: " + contentId).getBytes()); - bos.write(Constants.CRLF); - } - - bos.write(Constants.CRLF); - } - - protected void addChangesetItemIntro( - final ByteArrayOutputStream bos, final String contentId, final String cboundary) throws IOException { - bos.write(("--" + cboundary).getBytes()); - bos.write(Constants.CRLF); - bos.write(("Content-ID: " + contentId).getBytes()); - bos.write(Constants.CRLF); - addItemIntro(bos); - } - - protected void addSingleBatchResponse( - final Response response, final ByteArrayOutputStream bos) throws IOException { - addSingleBatchResponse(response, null, bos); - } - - protected void addSingleBatchResponse( - final Response response, final String contentId, final ByteArrayOutputStream bos) throws IOException { - bos.write("HTTP/1.1 ".getBytes()); - bos.write(String.valueOf(response.getStatusInfo().getStatusCode()).getBytes()); - bos.write(" ".getBytes()); - bos.write(response.getStatusInfo().getReasonPhrase().getBytes()); - bos.write(Constants.CRLF); - - for (Map.Entry> header : response.getHeaders().entrySet()) { - final StringBuilder builder = new StringBuilder(); - for (Object value : header.getValue()) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append(value.toString()); - } - builder.insert(0, ": ").insert(0, header.getKey()); - bos.write(builder.toString().getBytes()); - bos.write(Constants.CRLF); - } - - if (StringUtils.isNotBlank(contentId)) { - bos.write(("Content-ID: " + contentId).getBytes()); - bos.write(Constants.CRLF); - } - - bos.write(Constants.CRLF); - - final Object entity = response.getEntity(); - if (entity != null) { - bos.write(IOUtils.toByteArray((InputStream) entity)); - bos.write(Constants.CRLF); - } - - bos.write(Constants.CRLF); - } - - protected void addErrorBatchResponse(final Exception e, final ByteArrayOutputStream bos) - throws IOException { - addErrorBatchResponse(e, null, bos); - } - - protected void addErrorBatchResponse(final Exception e, final String contentId, final ByteArrayOutputStream bos) - throws IOException { - addSingleBatchResponse(xml.createFaultResponse(Accept.XML.toString(), e), contentId, bos); - } - - @PATCH - @Path("/{entitySetName}({entityId})") - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON }) - @Consumes({ MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON }) - public Response patchEntity( - @Context final UriInfo uriInfo, - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType, - @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, - @HeaderParam("If-Match") @DefaultValue(StringUtils.EMPTY) final String ifMatch, - @PathParam("entitySetName") final String entitySetName, - @PathParam("entityId") final String entityId, - final String changes) { - - try { - final Accept acceptType = Accept.parse(accept); - - if (acceptType == Accept.XML || acceptType == Accept.TEXT) { - throw new UnsupportedMediaTypeException("Unsupported media type"); - } - - final Map.Entry entityInfo = xml.readEntity(entitySetName, entityId, Accept.ATOM); - - final String etag = Commons.getETag(entityInfo.getKey()); - if (StringUtils.isNotBlank(ifMatch) && !ifMatch.equals(etag)) { - throw new ConcurrentModificationException("Concurrent modification"); - } - - final Accept contentTypeValue = Accept.parse(contentType); - - final Entity entryChanges; - - if (contentTypeValue == Accept.XML || contentTypeValue == Accept.TEXT) { - throw new UnsupportedMediaTypeException("Unsupported media type"); - } else if (contentTypeValue == Accept.ATOM) { - entryChanges = atomDeserializer.toEntity( - IOUtils.toInputStream(changes, Constants.ENCODING)).getPayload(); - } else { - final ResWrap jcont = jsonDeserializer.toEntity(IOUtils.toInputStream(changes, Constants.ENCODING)); - entryChanges = jcont.getPayload(); - } - - final ResWrap container = atomDeserializer.toEntity(entityInfo.getValue()); - - for (Property property : entryChanges.getProperties()) { - final Property _property = container.getPayload().getProperty(property.getName()); - if (_property == null) { - container.getPayload().getProperties().add(property); - } else { - _property.setValue(property.getValueType(), property.getValue()); - } - } - - for (Link link : entryChanges.getNavigationLinks()) { - container.getPayload().getNavigationLinks().add(link); - } - - final ByteArrayOutputStream content = new ByteArrayOutputStream(); - final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING); - atomSerializer.write(writer, container); - writer.flush(); - writer.close(); - - final InputStream res = xml.addOrReplaceEntity( - entityId, entitySetName, new ByteArrayInputStream(content.toByteArray()), container.getPayload()); - - final ResWrap cres = atomDeserializer.toEntity(res); - - normalizeAtomEntry(cres.getPayload(), entitySetName, entityId); - - final String path = Commons.getEntityBasePath(entitySetName, entityId); - FSManager.instance(version).putInMemory( - cres, path + File.separatorChar + Constants.get(ConstantKey.ENTITY)); - - final Response response; - if ("return-content".equalsIgnoreCase(prefer)) { - response = xml.createResponse( - uriInfo.getRequestUri().toASCIIString(), - xml.readEntity(entitySetName, entityId, acceptType).getValue(), - null, acceptType, Response.Status.OK); - } else { - res.close(); - response = xml.createResponse( - uriInfo.getRequestUri().toASCIIString(), - null, - null, - acceptType, Response.Status.NO_CONTENT); - } - - if (StringUtils.isNotBlank(prefer)) { - response.getHeaders().put("Preference-Applied", Collections. singletonList(prefer)); - } - - return response; - } catch (Exception e) { - return xml.createFaultResponse(accept, e); - } - } - - @PUT - @Path("/{entitySetName}({entityId})") - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON }) - @Consumes({ MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON }) - public Response replaceEntity( - @Context final UriInfo uriInfo, - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType, - @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, - @PathParam("entitySetName") final String entitySetName, - @PathParam("entityId") final String entityId, - final String entity) { - - try { - final Accept acceptType = Accept.parse(accept); - - if (acceptType == Accept.XML || acceptType == Accept.TEXT) { - throw new UnsupportedMediaTypeException("Unsupported media type"); - } - - final InputStream res = getUtilities(acceptType).addOrReplaceEntity(entityId, entitySetName, - IOUtils.toInputStream(entity, Constants.ENCODING), - xml.readEntity(acceptType, IOUtils.toInputStream(entity, Constants.ENCODING))); - - final ResWrap cres; - if (acceptType == Accept.ATOM) { - cres = atomDeserializer.toEntity(res); - } else { - cres = jsonDeserializer.toEntity(res); - } - - final String path = Commons.getEntityBasePath(entitySetName, entityId); - FSManager.instance(version).putInMemory( - cres, path + File.separatorChar + Constants.get(ConstantKey.ENTITY)); - - final Response response; - if ("return-content".equalsIgnoreCase(prefer)) { - response = xml.createResponse( - uriInfo.getRequestUri().toASCIIString(), - xml.readEntity(entitySetName, entityId, acceptType).getValue(), - null, - acceptType, - Response.Status.OK); - } else { - res.close(); - response = xml.createResponse( - uriInfo.getRequestUri().toASCIIString(), - null, - null, - acceptType, - Response.Status.NO_CONTENT); - } - - if (StringUtils.isNotBlank(prefer)) { - response.getHeaders().put("Preference-Applied", Collections. singletonList(prefer)); - } - - return response; - } catch (Exception e) { - return xml.createFaultResponse(accept, e); - } - } - - @POST - @Path("/{entitySetName}") - @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON }) - @Consumes({ MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM }) - public Response postNewEntity( - @Context final UriInfo uriInfo, - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType, - @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, - @PathParam("entitySetName") final String entitySetName, - final String entity) { - - try { - final Accept acceptType = Accept.parse(accept); - if (acceptType == Accept.XML || acceptType == Accept.TEXT) { - throw new UnsupportedMediaTypeException("Unsupported media type"); - } - - final ResWrap container; - - final org.apache.olingo.fit.metadata.EntitySet entitySet = metadata.getEntitySet(entitySetName); - - final Entity entry; - final String entityKey; - if (xml.isMediaContent(entitySetName)) { - entry = new Entity(); - entry.setMediaContentType(ContentType.APPLICATION_OCTET_STREAM.toContentTypeString()); - entry.setType(entitySet.getType()); - - entityKey = xml.getDefaultEntryKey(entitySetName, entry); - - xml.addMediaEntityValue(entitySetName, entityKey, IOUtils.toInputStream(entity, Constants.ENCODING)); - - final Pair id = Commons.getMediaContent().get(entitySetName); - if (id != null) { - final Property prop = new Property(); - prop.setName(id.getKey()); - prop.setType(id.getValue().toString()); - prop.setValue(ValueType.PRIMITIVE, - id.getValue() == EdmPrimitiveTypeKind.Int32 - ? Integer.parseInt(entityKey) - : id.getValue() == EdmPrimitiveTypeKind.Guid - ? UUID.fromString(entityKey) - : entityKey); - entry.getProperties().add(prop); - } - - final Link editLink = new Link(); - editLink.setHref(Commons.getEntityURI(entitySetName, entityKey)); - editLink.setRel("edit"); - editLink.setTitle(entitySetName); - entry.setEditLink(editLink); - - entry.setMediaContentSource(URI.create(editLink.getHref() + "/$value")); - - container = new ResWrap((URI) null, null, entry); - } else { - final Accept contentTypeValue = Accept.parse(contentType); - if (Accept.ATOM == contentTypeValue) { - container = atomDeserializer.toEntity(IOUtils.toInputStream(entity, Constants.ENCODING)); - } else { - container = jsonDeserializer.toEntity(IOUtils.toInputStream(entity, Constants.ENCODING)); - } - entry = container.getPayload(); - updateInlineEntities(entry); - - entityKey = xml.getDefaultEntryKey(entitySetName, entry); - } - - normalizeAtomEntry(entry, entitySetName, entityKey); - - final ByteArrayOutputStream content = new ByteArrayOutputStream(); - final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING); - atomSerializer.write(writer, container); - writer.flush(); - writer.close(); - - final InputStream serialization = - xml.addOrReplaceEntity(entityKey, entitySetName, new ByteArrayInputStream(content.toByteArray()), entry); - - ResWrap result = atomDeserializer.toEntity(serialization); - result = new ResWrap( - URI.create(Constants.get(ConstantKey.ODATA_METADATA_PREFIX) - + entitySetName + Constants.get(ConstantKey.ODATA_METADATA_ENTITY_SUFFIX)), - null, result.getPayload()); - - final String path = Commons.getEntityBasePath(entitySetName, entityKey); - FSManager.instance(version).putInMemory(result, path + Constants.get(ConstantKey.ENTITY)); - - final String location; - - if ((this instanceof KeyAsSegment)) { - location = uriInfo.getRequestUri().toASCIIString() + "/" + entityKey; - - final Link editLink = new Link(); - editLink.setRel("edit"); - editLink.setTitle(entitySetName); - editLink.setHref(location); - - result.getPayload().setEditLink(editLink); - } else { - location = uriInfo.getRequestUri().toASCIIString() + "(" + entityKey + ")"; - } - - final Response response; - if ("return-no-content".equalsIgnoreCase(prefer)) { - response = xml.createResponse( - location, - null, - null, - acceptType, - Response.Status.NO_CONTENT); - } else { - response = xml.createResponse( - location, - xml.writeEntity(acceptType, result), - null, - acceptType, - Response.Status.CREATED); - } - - if (StringUtils.isNotBlank(prefer)) { - response.getHeaders().put("Preference-Applied", Collections. singletonList(prefer)); - } - - return response; - } catch (Exception e) { - LOG.error("While creating new entity", e); - return xml.createFaultResponse(accept, e); - } - } - - @POST - @Path("/Person({entityId})/{type:.*}/Sack") - public Response actionSack( - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @PathParam("entityId") final String entityId, - @PathParam("type") final String type, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) { - - final Map.Entry utils = getUtilities(accept, format); - - if (utils.getKey() == Accept.XML || utils.getKey() == Accept.TEXT) { - throw new UnsupportedMediaTypeException("Unsupported media type"); - } - - try { - final Map.Entry entityInfo = xml.readEntity("Person", entityId, Accept.ATOM); - - final InputStream entity = entityInfo.getValue(); - final ResWrap container = atomDeserializer.toEntity(entity); - - container.getPayload().getProperty("Salary").setValue(ValueType.PRIMITIVE, 0); - container.getPayload().getProperty("Title").setValue(ValueType.PRIMITIVE, "[Sacked]"); - - final FSManager fsManager = FSManager.instance(version); - fsManager.putInMemory(xml.writeEntity(Accept.ATOM, container), - fsManager.getAbsolutePath(Commons.getEntityBasePath("Person", entityId) + Constants.get( - ConstantKey.ENTITY), Accept.ATOM)); - - return utils.getValue().createResponse(null, null, null, utils.getKey(), Response.Status.NO_CONTENT); - } catch (Exception e) { - return xml.createFaultResponse(accept, e); - } - } - - @POST - @Path("/Person/{type:.*}/IncreaseSalaries") - public Response actionIncreaseSalaries( - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @PathParam("type") final String type, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, - final String body) { - - final String name = "Person"; - try { - final Accept acceptType = Accept.parse(accept); - if (acceptType == Accept.XML || acceptType == Accept.TEXT) { - throw new UnsupportedMediaTypeException("Unsupported media type"); - } - - final JsonNode tree = new ObjectMapper().readTree(body); - if (!tree.has("n")) { - throw new Exception("Missing parameter: n"); - } - final int n = tree.get("n").asInt(); - - final StringBuilder path = new StringBuilder(name). - append(File.separatorChar).append(type). - append(File.separatorChar); - - path.append(metadata.getEntitySet(name).isSingleton() - ? Constants.get(ConstantKey.ENTITY) - : Constants.get(ConstantKey.FEED)); - - final InputStream feed = FSManager.instance(version).readFile(path.toString(), acceptType); - - final ByteArrayOutputStream copy = new ByteArrayOutputStream(); - IOUtils.copy(feed, copy); - IOUtils.closeQuietly(feed); - - String newContent = new String(copy.toByteArray(), "UTF-8"); - final Pattern salary = Pattern.compile(acceptType == Accept.ATOM - ? "\\(-?\\d+)\\" - : "\"Salary\":(-?\\d+),"); - final Matcher salaryMatcher = salary.matcher(newContent); - while (salaryMatcher.find()) { - final Long newSalary = Long.valueOf(salaryMatcher.group(1)) + n; - newContent = newContent. - replaceAll("\"Salary\":" + salaryMatcher.group(1) + ",", - "\"Salary\":" + newSalary + ","). - replaceAll("\\" + salaryMatcher.group(1) + "", - "" + newSalary + ""); - } - - FSManager.instance(version).putInMemory(IOUtils.toInputStream(newContent, Constants.ENCODING), - FSManager.instance(version).getAbsolutePath(path.toString(), acceptType)); - - return xml.createResponse(null, null, null, acceptType, Response.Status.NO_CONTENT); - } catch (Exception e) { - return xml.createFaultResponse(accept, e); - } - } - - @POST - @Path("/Product({entityId})/ChangeProductDimensions") - public Response actionChangeProductDimensions( - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @PathParam("entityId") final String entityId, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, - final String argument) { - - final Map.Entry utils = getUtilities(accept, format); - - if (utils.getKey() == Accept.XML || utils.getKey() == Accept.TEXT) { - throw new UnsupportedMediaTypeException("Unsupported media type"); - } - - try { - final Map.Entry entityInfo = xml.readEntity("Product", entityId, Accept.ATOM); - - final InputStream entity = entityInfo.getValue(); - final ResWrap container = atomDeserializer.toEntity(entity); - - final Entity param = xml.readEntity(utils.getKey(), IOUtils.toInputStream(argument, Constants.ENCODING)); - - final Property property = param.getProperty("dimensions"); - container.getPayload().getProperty("Dimensions").setValue(property.getValueType(), property.getValue()); - - final FSManager fsManager = FSManager.instance(version); - fsManager.putInMemory(xml.writeEntity(Accept.ATOM, container), - fsManager.getAbsolutePath(Commons.getEntityBasePath("Product", entityId) + Constants.get( - ConstantKey.ENTITY), Accept.ATOM)); - - return utils.getValue().createResponse(null, null, null, utils.getKey(), Response.Status.NO_CONTENT); - } catch (Exception e) { - return xml.createFaultResponse(accept, e); - } - } - - @POST - @Path("/ComputerDetail({entityId})/ResetComputerDetailsSpecifications") - public Response actionResetComputerDetailsSpecifications( - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @PathParam("entityId") final String entityId, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, - final String argument) { - - final Map.Entry utils = getUtilities(accept, format); - - if (utils.getKey() == Accept.XML || utils.getKey() == Accept.TEXT) { - throw new UnsupportedMediaTypeException("Unsupported media type"); - } - - try { - final Map.Entry entityInfo = xml.readEntity("ComputerDetail", entityId, Accept.ATOM); - - final InputStream entity = entityInfo.getValue(); - final ResWrap container = atomDeserializer.toEntity(entity); - - final Entity param = xml.readEntity(utils.getKey(), IOUtils.toInputStream(argument, Constants.ENCODING)); - - Property property = param.getProperty("specifications"); - container.getPayload().getProperty("SpecificationsBag").setValue(property.getValueType(), property.getValue()); - property = param.getProperty("purchaseTime"); - container.getPayload().getProperty("PurchaseDate").setValue(property.getValueType(), property.getValue()); - - final FSManager fsManager = FSManager.instance(version); - fsManager.putInMemory(xml.writeEntity(Accept.ATOM, container), - fsManager.getAbsolutePath(Commons.getEntityBasePath("ComputerDetail", entityId) + Constants.get( - ConstantKey.ENTITY), Accept.ATOM)); - - return utils.getValue().createResponse(null, null, null, utils.getKey(), Response.Status.NO_CONTENT); - } catch (Exception e) { - return xml.createFaultResponse(accept, e); - } - } - - /** - * Retrieve entities from the given entity set and the given type. - * - * @param accept Accept header. - * @param name entity set. - * @param type entity type. - * @return entity set. - */ - @GET - @Path("/{name}/{type:[a-zA-Z].*}") - public Response getEntitySet( - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @PathParam("name") final String name, - @PathParam("type") final String type) { - - try { - final Accept acceptType = Accept.parse(accept); - if (acceptType == Accept.XML || acceptType == Accept.TEXT) { - throw new UnsupportedMediaTypeException("Unsupported media type"); - } - - final String basePath = name + File.separatorChar; - final StringBuilder path = new StringBuilder(name). - append(File.separatorChar).append(type). - append(File.separatorChar); - - path.append(metadata.getEntitySet(name).isSingleton() - ? Constants.get(ConstantKey.ENTITY) - : Constants.get(ConstantKey.FEED)); - - final InputStream feed = FSManager.instance(version).readFile(path.toString(), acceptType); - return xml.createResponse(null, feed, Commons.getETag(basePath), acceptType); - } catch (Exception e) { - return xml.createFaultResponse(accept, e); - } - } - - @GET - @Path("/{name}/{type:[a-zA-Z].*}") - public Response getEntitySet(@Context final UriInfo uriInfo, - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @PathParam("name") final String name, - @QueryParam("$top") @DefaultValue(StringUtils.EMPTY) final String top, - @QueryParam("$skip") @DefaultValue(StringUtils.EMPTY) final String skip, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, - @QueryParam("$count") @DefaultValue(StringUtils.EMPTY) final String count, - @QueryParam("$filter") @DefaultValue(StringUtils.EMPTY) final String filter, - @QueryParam("$orderby") @DefaultValue(StringUtils.EMPTY) final String orderby, - @QueryParam("$skiptoken") @DefaultValue(StringUtils.EMPTY) final String skiptoken, - @PathParam("type") final String type) { - - try { - final Accept acceptType; - if (StringUtils.isNotBlank(format)) { - acceptType = Accept.valueOf(format.toUpperCase()); - } else { - acceptType = Accept.parse(accept); - } - - final String location = uriInfo.getRequestUri().toASCIIString(); - try { - // search for function ... - final InputStream func = FSManager.instance(version).readFile(name, acceptType); - return xml.createResponse(location, func, null, acceptType); - } catch (NotFoundException e) { - if (acceptType == Accept.XML || acceptType == Accept.TEXT) { - throw new UnsupportedMediaTypeException("Unsupported media type"); - } - - // search for entitySet ... - final String basePath = name + File.separatorChar; - - final StringBuilder builder = new StringBuilder(); - builder.append(basePath); - - if (type != null) { - builder.append(type).append(File.separatorChar); - } - - if (StringUtils.isNotBlank(orderby)) { - builder.append(Constants.get(ConstantKey.ORDERBY)).append(File.separatorChar). - append(orderby).append(File.separatorChar); - } - - if (StringUtils.isNotBlank(filter)) { - builder.append(Constants.get(ConstantKey.FILTER)).append(File.separatorChar). - append(filter.replaceAll("/", ".")); - } else if (StringUtils.isNotBlank(skiptoken)) { - builder.append(Constants.get(ConstantKey.SKIP_TOKEN)).append(File.separatorChar). - append(skiptoken); - } else { - builder.append(metadata.getEntitySet(name).isSingleton() - ? Constants.get(ConstantKey.ENTITY) - : Constants.get(ConstantKey.FEED)); - } - - final InputStream feed = FSManager.instance(version).readFile(builder.toString(), Accept.ATOM); - - final ResWrap container = atomDeserializer.toEntitySet(feed); - - setInlineCount(container.getPayload(), count); - - final ByteArrayOutputStream content = new ByteArrayOutputStream(); - final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING); - - // ----------------------------------------------- - // Evaluate $skip and $top - // ----------------------------------------------- - List entries = new ArrayList(container.getPayload().getEntities()); - - if (StringUtils.isNotBlank(skip)) { - entries = entries.subList(Integer.valueOf(skip), entries.size()); - } - - if (StringUtils.isNotBlank(top)) { - entries = entries.subList(0, Integer.valueOf(top)); - } - - container.getPayload().getEntities().clear(); - container.getPayload().getEntities().addAll(entries); - // ----------------------------------------------- - - if (acceptType == Accept.ATOM) { - atomSerializer.write(writer, container); - } else { - jsonSerializer.write(writer, container); - } - writer.flush(); - writer.close(); - - return xml.createResponse( - location, - new ByteArrayInputStream(content.toByteArray()), - Commons.getETag(basePath), - acceptType); - } - } catch (Exception e) { - return xml.createFaultResponse(accept, e); - } - } - - /** - * Retrieve entity set or function execution sample. - * - * @param accept Accept header. - * @param name entity set or function name. - * @param format format query option. - * @param count count query option. - * @param filter filter query option. - * @param orderby orderby query option. - * @param skiptoken skiptoken query option. - * @return entity set or function result. - */ - @GET - @Path("/{name}") - public Response getEntitySet( - @Context final UriInfo uriInfo, - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @PathParam("name") final String name, - @QueryParam("$top") @DefaultValue(StringUtils.EMPTY) final String top, - @QueryParam("$skip") @DefaultValue(StringUtils.EMPTY) final String skip, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, - @QueryParam("$count") @DefaultValue(StringUtils.EMPTY) final String count, - @QueryParam("$filter") @DefaultValue(StringUtils.EMPTY) final String filter, - @QueryParam("$orderby") @DefaultValue(StringUtils.EMPTY) final String orderby, - @QueryParam("$skiptoken") @DefaultValue(StringUtils.EMPTY) final String skiptoken) { - - return getEntitySet(uriInfo, accept, name, top, skip, format, count, filter, orderby, skiptoken, null); - } - - protected abstract void setInlineCount(final EntityCollection feed, final String count); - - @GET - @Path("/Person({entityId})") - public Response getPerson( - @Context final UriInfo uriInfo, - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @PathParam("entityId") final String entityId, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) { - - final Map.Entry utils = getUtilities(accept, format); - - final Response internal = getEntityInternal( - uriInfo.getRequestUri().toASCIIString(), accept, "Person", entityId, format, null, null); - if (internal.getStatus() == 200) { - InputStream entity = (InputStream) internal.getEntity(); - try { - if (utils.getKey() == Accept.JSON_FULLMETA || utils.getKey() == Accept.ATOM) { - entity = utils.getValue().addOperation(entity, "Sack", "#DefaultContainer.Sack", - uriInfo.getAbsolutePath().toASCIIString() - + "/Microsoft.Test.OData.Services.AstoriaDefaultService.SpecialEmployee/Sack"); - } - - return utils.getValue().createResponse( - uriInfo.getRequestUri().toASCIIString(), - entity, - internal.getHeaderString("ETag"), - utils.getKey()); - } catch (Exception e) { - LOG.error("Error retrieving entity", e); - return xml.createFaultResponse(accept, e); - } - } else { - return internal; - } - } - - @GET - @Path("/Product({entityId})") - public Response getProduct( - @Context final UriInfo uriInfo, - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @PathParam("entityId") final String entityId, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) { - - final Map.Entry utils = getUtilities(accept, format); - - final Response internal = getEntityInternal( - uriInfo.getRequestUri().toASCIIString(), accept, "Product", entityId, format, null, null); - if (internal.getStatus() == 200) { - InputStream entity = (InputStream) internal.getEntity(); - try { - if (utils.getKey() == Accept.JSON_FULLMETA || utils.getKey() == Accept.ATOM) { - entity = utils.getValue().addOperation(entity, - "ChangeProductDimensions", "#DefaultContainer.ChangeProductDimensions", - uriInfo.getAbsolutePath().toASCIIString() + "/ChangeProductDimensions"); - } - - return utils.getValue().createResponse( - uriInfo.getRequestUri().toASCIIString(), - entity, - internal.getHeaderString("ETag"), - utils.getKey()); - } catch (Exception e) { - LOG.error("Error retrieving entity", e); - return xml.createFaultResponse(accept, e); - } - } else { - return internal; - } - } - - @GET - @Path("/ComputerDetail({entityId})") - public Response getComputerDetail( - @Context final UriInfo uriInfo, - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @PathParam("entityId") final String entityId, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) { - - final Map.Entry utils = getUtilities(accept, format); - - final Response internal = getEntityInternal( - uriInfo.getRequestUri().toASCIIString(), accept, "ComputerDetail", entityId, format, null, null); - if (internal.getStatus() == 200) { - InputStream entity = (InputStream) internal.getEntity(); - try { - if (utils.getKey() == Accept.JSON_FULLMETA || utils.getKey() == Accept.ATOM) { - entity = utils.getValue().addOperation(entity, - "ResetComputerDetailsSpecifications", "#DefaultContainer.ResetComputerDetailsSpecifications", - uriInfo.getAbsolutePath().toASCIIString() + "/ResetComputerDetailsSpecifications"); - } - - return utils.getValue().createResponse( - uriInfo.getRequestUri().toASCIIString(), - entity, - internal.getHeaderString("ETag"), - utils.getKey()); - } catch (Exception e) { - LOG.error("Error retrieving entity", e); - return xml.createFaultResponse(accept, e); - } - } else { - return internal; - } - } - - /** - * Retrieve entity sample. - * - * @param accept Accept header. - * @param entitySetName Entity set name. - * @param entityId entity id. - * @param format format query option. - * @param expand expand query option. - * @param select select query option. - * @return entity. - */ - @GET - @Path("/{entitySetName}({entityId})") - public Response getEntity( - @Context final UriInfo uriInfo, - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @PathParam("entitySetName") final String entitySetName, - @PathParam("entityId") final String entityId, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, - @QueryParam("$expand") @DefaultValue(StringUtils.EMPTY) final String expand, - @QueryParam("$select") @DefaultValue(StringUtils.EMPTY) final String select) { - - return getEntityInternal( - uriInfo.getRequestUri().toASCIIString(), accept, entitySetName, entityId, format, expand, select); - } - - protected Response getEntityInternal( - final String location, - final String accept, - final String entitySetName, - final String entityId, - final String format, - final String expand, - final String select) { - - try { - final Map.Entry utils = getUtilities(accept, format); - - if (utils.getKey() == Accept.XML || utils.getKey() == Accept.TEXT) { - throw new UnsupportedMediaTypeException("Unsupported media type"); - } - - final Map.Entry entityInfo = - utils.getValue().readEntity(entitySetName, entityId, Accept.ATOM); - - final InputStream entity = entityInfo.getValue(); - - ResWrap container = atomDeserializer.toEntity(entity); - if (container.getContextURL() == null) { - container = new ResWrap(URI.create(Constants.get(ConstantKey.ODATA_METADATA_PREFIX) - + entitySetName + Constants.get(ConstantKey.ODATA_METADATA_ENTITY_SUFFIX)), - container.getMetadataETag(), container.getPayload()); - } - final Entity entry = container.getPayload(); - - if ((this instanceof KeyAsSegment)) { - final Link editLink = new Link(); - editLink.setRel("edit"); - editLink.setTitle(entitySetName); - editLink.setHref(Constants.get(ConstantKey.DEFAULT_SERVICE_URL) + entitySetName + "/" + entityId); - - entry.setEditLink(editLink); - } - - if (StringUtils.isNotBlank(select)) { - final List properties = Arrays.asList(select.split(",")); - final Set toBeRemoved = new HashSet(); - - for (Property property : entry.getProperties()) { - if (!properties.contains(property.getName())) { - toBeRemoved.add(property); - } - } - - entry.getProperties().removeAll(toBeRemoved); - - final Set linkToBeRemoved = new HashSet(); - - for (Link link : entry.getNavigationLinks()) { - if (!properties.contains(link.getTitle().replaceAll("@.*$", "")) && !properties.contains(link.getTitle())) { - linkToBeRemoved.add(link); - } - } - - entry.getNavigationLinks().removeAll(linkToBeRemoved); - } - - String tempExpand = expand; - if (StringUtils.isNotBlank(tempExpand)) { - tempExpand = StringUtils.substringBefore(tempExpand, "("); - final List links = Arrays.asList(tempExpand.split(",")); - - final Map replace = new HashMap(); - - for (Link link : entry.getNavigationLinks()) { - if (links.contains(link.getTitle())) { - // expand link - final Link rep = new Link(); - rep.setHref(link.getHref()); - rep.setRel(link.getRel()); - rep.setTitle(link.getTitle()); - rep.setType(link.getType()); - if (link.getType().equals(Constants.get(ConstantKey.ATOM_LINK_ENTRY))) { - // inline entry - final Entity inline = atomDeserializer.toEntity( - xml.expandEntity(entitySetName, entityId, link.getTitle())).getPayload(); - rep.setInlineEntity(inline); - } else if (link.getType().equals(Constants.get(ConstantKey.ATOM_LINK_FEED))) { - // inline feed - final EntityCollection inline = atomDeserializer.toEntitySet( - xml.expandEntity(entitySetName, entityId, link.getTitle())).getPayload(); - rep.setInlineEntitySet(inline); - } - replace.put(link, rep); - } - } - - for (Map.Entry link : replace.entrySet()) { - entry.getNavigationLinks().remove(link.getKey()); - entry.getNavigationLinks().add(link.getValue()); - } - } - - return xml.createResponse( - location, - xml.writeEntity(utils.getKey(), container), - Commons.getETag(entityInfo.getKey()), - utils.getKey()); - } catch (Exception e) { - LOG.error("Error retrieving entity", e); - return xml.createFaultResponse(accept, e); - } - } - - @GET - @Path("/{entitySetName}({entityId})/$value") - public Response getMediaEntity( - @Context final UriInfo uriInfo, - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @PathParam("entitySetName") final String entitySetName, - @PathParam("entityId") final String entityId) { - - try { - if (!accept.contains("*/*") && !accept.contains("application/octet-stream")) { - throw new UnsupportedMediaTypeException("Unsupported media type"); - } - - final AbstractUtilities utils = getUtilities(null); - final Map.Entry entityInfo = utils.readMediaEntity(entitySetName, entityId); - return utils.createResponse( - uriInfo.getRequestUri().toASCIIString(), - entityInfo.getValue(), - Commons.getETag(entityInfo.getKey()), - null); - - } catch (Exception e) { - LOG.error("Error retrieving entity", e); - return xml.createFaultResponse(accept, e); - } - } - - @DELETE - @Path("/{entitySetName}({entityId})") - public Response removeEntity( - @PathParam("entitySetName") final String entitySetName, - @PathParam("entityId") final String entityId) { - - try { - final String basePath = entitySetName + File.separatorChar + Commons.getEntityKey(entityId); - - FSManager.instance(version).deleteEntity(basePath); - - return xml.createResponse(null, null, null, null, Response.Status.NO_CONTENT); - } catch (Exception e) { - return xml.createFaultResponse(Accept.XML.toString(), e); - } - } - - private Response replaceProperty( - final String location, - final String accept, - final String contentType, - final String prefer, - final String entitySetName, - final String entityId, - final String path, - final String format, - final String changes, - final boolean justValue) { - - // if the given path is not about any link then search for property - LOG.info("Retrieve property {}", path); - - try { - final FSManager fsManager = FSManager.instance(version); - final String basePath = Commons.getEntityBasePath(entitySetName, entityId); - - final ResWrap container = xml.readContainerEntity(Accept.ATOM, - fsManager.readFile(basePath + Constants.get(ConstantKey.ENTITY), Accept.ATOM)); - - final Entity entry = container.getPayload(); - - Property toBeReplaced = null; - for (String element : path.split("/")) { - if (toBeReplaced == null) { - toBeReplaced = entry.getProperty(element.trim()); - } else { - List value = toBeReplaced.asComplex().getValue(); - for (Property field : value) { - if (field.getName().equalsIgnoreCase(element)) { - toBeReplaced = field; - } - } - } - } - - if (toBeReplaced == null) { - throw new NotFoundException(); - } - - if (justValue) { - // just for primitive values - toBeReplaced.setValue(ValueType.PRIMITIVE, changes); - } else { - final Property pchanges = xml.readProperty( - Accept.parse(contentType), - IOUtils.toInputStream(changes, Constants.ENCODING)); - - toBeReplaced.setValue(pchanges.getValueType(), pchanges.getValue()); - } - - fsManager.putInMemory(xml.writeEntity(Accept.ATOM, container), - fsManager.getAbsolutePath(basePath + Constants.get(ConstantKey.ENTITY), Accept.ATOM)); - - final Response response; - if ("return-content".equalsIgnoreCase(prefer)) { - response = getEntityInternal(location, accept, entitySetName, entityId, format, null, null); - } else { - Accept acceptType = null; - if (StringUtils.isNotBlank(format)) { - acceptType = Accept.valueOf(format.toUpperCase()); - } else if (StringUtils.isNotBlank(accept)) { - acceptType = Accept.parse(accept, null); - } - - response = xml.createResponse(null, null, null, acceptType, Response.Status.NO_CONTENT); - } - - if (StringUtils.isNotBlank(prefer)) { - response.getHeaders().put("Preference-Applied", Collections. singletonList(prefer)); - } - - return response; - } catch (Exception e) { - return xml.createFaultResponse(accept, e); - } - } - - private Response deletePropertyValue( - final String accept, - final String prefer, - final String entitySetName, - final String entityId, - final String path, - final String format) { - try { - Accept acceptType = null; - if (StringUtils.isNotBlank(format)) { - acceptType = Accept.valueOf(format.toUpperCase()); - } else if (StringUtils.isNotBlank(accept)) { - acceptType = Accept.parse(accept, null); - } - - // if the given path is not about any link then search for property - LOG.info("Retrieve property {}", path); - - final AbstractUtilities utils = getUtilities(acceptType); - - final InputStream changed = utils.deleteProperty( - entitySetName, - entityId, - Arrays.asList(path.split("/")), - acceptType); - - final Response response; - if ("return-content".equalsIgnoreCase(prefer)) { - response = xml.createResponse(null, changed, null, acceptType, Response.Status.OK); - } else { - changed.close(); - response = xml.createResponse(null, null, null, acceptType, Response.Status.NO_CONTENT); - } - - if (StringUtils.isNotBlank(prefer)) { - response.getHeaders().put("Preference-Applied", Collections. singletonList(prefer)); - } - - return response; - - } catch (Exception e) { - return xml.createFaultResponse(accept, e); - } - } - - /** - * Replace property value. - * - * @param accept - * @param entitySetName - * @param entityId - * @param path - * @param format - * @param changes - * @return response - */ - @PUT - @Path("/{entitySetName}({entityId})/{path:.*}/$value") - public Response replacePropertyValue( - @Context final UriInfo uriInfo, - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType, - @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, - @PathParam("entitySetName") final String entitySetName, - @PathParam("entityId") final String entityId, - @PathParam("path") final String path, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, - final String changes) { - - return replaceProperty(uriInfo.getRequestUri().toASCIIString(), - accept, contentType, prefer, entitySetName, entityId, path, format, changes, true); - } - - /** - * Replace property. - * - * @param accept - * @param entitySetName - * @param entityId - * @param path - * @param format - * @param changes - * @return response - */ - @PATCH - @Path("/{entitySetName}({entityId})/{path:.*}") - public Response patchProperty( - @Context final UriInfo uriInfo, - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType, - @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, - @PathParam("entitySetName") final String entitySetName, - @PathParam("entityId") final String entityId, - @PathParam("path") final String path, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, - final String changes) { - - return replaceProperty(uriInfo.getRequestUri().toASCIIString(), - accept, contentType, prefer, entitySetName, entityId, path, format, changes, false); - } - - @PUT - @Produces({ MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON }) - @Consumes({ MediaType.WILDCARD, MediaType.APPLICATION_OCTET_STREAM }) - @Path("/{entitySetName}({entityId})/$value") - public Response replaceMediaEntity( - @Context final UriInfo uriInfo, - @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, - @PathParam("entitySetName") final String entitySetName, - @PathParam("entityId") final String entityId, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, - final String value) { - try { - - final AbstractUtilities utils = getUtilities(null); - - final InputStream res = utils.putMediaInMemory( - entitySetName, entityId, IOUtils.toInputStream(value, Constants.ENCODING)); - - final String location = uriInfo.getRequestUri().toASCIIString().replace("/$value", ""); - - final Response response; - if ("return-content".equalsIgnoreCase(prefer)) { - response = xml.createResponse(location, res, null, null, Response.Status.OK); - } else { - res.close(); - response = xml.createResponse(location, null, null, null, Response.Status.NO_CONTENT); - } - - if (StringUtils.isNotBlank(prefer)) { - response.getHeaders().put("Preference-Applied", Collections. singletonList(prefer)); - } - - return response; - - } catch (Exception e) { - LOG.error("Error retrieving entity", e); - return xml.createFaultResponse(Accept.JSON.toString(), e); - } - } - - /** - * Replace property. - * - * @param accept - * @param entitySetName - * @param entityId - * @param path - * @param format - * @param changes - * @return response - */ - @PUT - @Path("/{entitySetName}({entityId})/{path:.*}") - public Response replaceProperty( - @Context final UriInfo uriInfo, - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType, - @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, - @PathParam("entitySetName") final String entitySetName, - @PathParam("entityId") final String entityId, - @PathParam("path") final String path, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, - final String changes) { - - if (xml.isMediaContent(entitySetName + "/" + path)) { - return replaceMediaProperty(prefer, entitySetName, entityId, path, changes); - } else { - return replaceProperty(uriInfo.getRequestUri().toASCIIString(), - accept, contentType, prefer, entitySetName, entityId, path, format, changes, false); - } - } - - private Response replaceMediaProperty( - final String prefer, - final String entitySetName, - final String entityId, - final String path, - final String value) { - - try { - final AbstractUtilities utils = getUtilities(null); - - InputStream res = utils.putMediaInMemory( - entitySetName, entityId, path, IOUtils.toInputStream(value, Constants.ENCODING)); - - final Response response; - if ("return-content".equalsIgnoreCase(prefer)) { - response = xml.createResponse(null, res, null, null, Response.Status.OK); - } else { - res.close(); - response = xml.createResponse(null, null, null, null, Response.Status.NO_CONTENT); - } - - if (StringUtils.isNotBlank(prefer)) { - response.getHeaders().put("Preference-Applied", Collections. singletonList(prefer)); - } - - return response; - } catch (Exception e) { - LOG.error("Error retrieving entity", e); - return xml.createFaultResponse(Accept.JSON.toString(), e); - } - } - - /** - * Nullify property value. - * - * @param accept - * @param entitySetName - * @param entityId - * @param path - * @param format - * @return response - */ - @DELETE - @Path("/{entitySetName}({entityId})/{path:.*}/$value") - public Response deleteProperty( - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, - @PathParam("entitySetName") final String entitySetName, - @PathParam("entityId") final String entityId, - @PathParam("path") final String path, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) { - return deletePropertyValue(accept, prefer, entitySetName, entityId, path, format); - } - - /** - * Retrieve property sample. - * - * @param accept Accept header. - * @param entitySetName Entity set name. - * @param entityId entity id. - * @param path path. - * @param format format query option. - * @return property. - */ - @GET - @Path("/{entitySetName}({entityId})/{path:.*}/$value") - public Response getPathValue( - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @PathParam("entitySetName") final String entitySetName, - @PathParam("entityId") final String entityId, - @PathParam("path") final String path, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) { - - try { - Accept acceptType = null; - if (StringUtils.isNotBlank(format)) { - acceptType = Accept.valueOf(format.toUpperCase()); - } else if (StringUtils.isNotBlank(accept)) { - acceptType = Accept.parse(accept, null); - } - - return navigateProperty(acceptType, entitySetName, entityId, path, true); - } catch (Exception e) { - return xml.createFaultResponse(accept, e); - } - } - - /** - * Retrieve property sample. - * - * @param accept Accept header. - * @param entitySetName Entity set name. - * @param entityId entity id. - * @param path path. - * @param format format query option. - * @return property. - */ - @GET - @Path("/{entitySetName}({entityId})/{path:.*}") - public Response getPath( - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @PathParam("entitySetName") final String entitySetName, - @PathParam("entityId") final String entityId, - @PathParam("path") final String path, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) { - - // default utilities - final AbstractUtilities utils = xml; - - try { - if (utils.isMediaContent(entitySetName + "/" + path)) { - return navigateStreamedEntity(entitySetName, entityId, path); - } else { - Accept acceptType = null; - if (StringUtils.isNotBlank(format)) { - acceptType = Accept.valueOf(format.toUpperCase()); - } else if (StringUtils.isNotBlank(accept)) { - acceptType = Accept.parse(accept, null); - } - - try { - final LinkInfo linkInfo = xml.readLinks(entitySetName, entityId, path, Accept.XML); - final Map.Entry> links = xml.extractLinkURIs(linkInfo.getLinks()); - final InputStream stream = xml.readEntities(links.getValue(), path, links.getKey(), linkInfo.isFeed()); - - final ByteArrayOutputStream content = new ByteArrayOutputStream(); - final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING); - - final ResWrap container = linkInfo.isFeed() ? atomDeserializer.toEntitySet(stream) : atomDeserializer. - toEntity(stream); - if (acceptType == Accept.ATOM) { - atomSerializer.write(writer, container); - } else { - jsonSerializer.write(writer, container); - } - writer.flush(); - writer.close(); - - final String basePath = Commons.getEntityBasePath(entitySetName, entityId); - - return xml.createResponse( - null, - new ByteArrayInputStream(content.toByteArray()), - Commons.getETag(basePath), - acceptType); - - } catch (NotFoundException e) { - // if the given path is not about any link then search for property - return navigateProperty(acceptType, entitySetName, entityId, path, false); - } - } - } catch (Exception e) { - return utils.createFaultResponse(accept, e); - } - } - - private Response navigateStreamedEntity( - final String entitySetName, - final String entityId, - final String path) throws Exception { - - final AbstractUtilities utils = getUtilities(null); - final Map.Entry entityInfo = utils.readMediaEntity(entitySetName, entityId, path); - return utils.createResponse(null, entityInfo.getValue(), Commons.getETag(entityInfo.getKey()), null); - } - - private Response navigateProperty( - final Accept acceptType, - final String entitySetName, - final String entityId, - final String path, - final boolean searchForValue) throws Exception { - - if ((searchForValue && acceptType != null && acceptType != Accept.TEXT) || acceptType == Accept.ATOM) { - throw new UnsupportedMediaTypeException("Unsupported media type " + acceptType); - } - - final AbstractUtilities utils = getUtilities(acceptType); - - final Map.Entry entityInfo = utils.readEntity(entitySetName, entityId, Accept.ATOM); - - final InputStream entity = entityInfo.getValue(); - - final ResWrap entryContainer = atomDeserializer.toEntity(entity); - - final String[] pathElems = StringUtils.split(path, "/"); - Property property = entryContainer.getPayload().getProperty(pathElems[0]); - if (pathElems.length > 1 && property.isComplex()) { - for (Property sub : property.asComplex().getValue()) { - if (pathElems[1].equals(sub.getName())) { - property = sub; - if (pathElems.length > 2 && property.isComplex()) { - for (Property subsub : property.asComplex().getValue()) { - if (pathElems[2].equals(subsub.getName())) { - property = subsub; - } - } - } - } - } - } - - final ResWrap container = new ResWrap( - URI.create(Constants.get(ConstantKey.ODATA_METADATA_PREFIX) + entitySetName + "(" + entityId + ")/" + path), - entryContainer.getMetadataETag(), - property); - - return xml.createResponse(null, - searchForValue ? IOUtils.toInputStream( - container.getPayload().isNull() ? StringUtils.EMPTY : stringValue(container.getPayload()), - Constants.ENCODING) : utils.writeProperty(acceptType, container), - Commons.getETag(Commons.getEntityBasePath(entitySetName, entityId)), - acceptType); - } - - private String stringValue(final Property property) { - EdmPrimitiveTypeKind kind = EdmPrimitiveTypeKind.valueOfFQN(property.getType()); - try { - return EdmPrimitiveTypeFactory.getInstance(kind) - .valueToString(property.asPrimitive(), null, null, - org.apache.olingo.commons.api.Constants.DEFAULT_PRECISION, - org.apache.olingo.commons.api.Constants.DEFAULT_SCALE, null); - } catch (final EdmPrimitiveTypeException e) { - return property.asPrimitive().toString(); - } - } - - /** - * Count sample. - * - * @param accept Accept header. - * @param entitySetName entity set name. - * @return count. - */ - @GET - @Path("/{entitySetName}/$count") - public Response count( - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @PathParam("entitySetName") final String entitySetName) { - try { - final Accept acceptType = Accept.parse(accept, Accept.TEXT); - - if (acceptType != Accept.TEXT) { - throw new UnsupportedMediaTypeException("Unsupported type " + accept); - } - - int count = xml.countAllElements(entitySetName); - - final Response.ResponseBuilder builder = Response.ok(); - builder.entity(count); - - return builder.build(); - } catch (Exception e) { - return xml.createFaultResponse(accept, e); - } - } - - public Map.Entry getUtilities(final String accept, final String format) { - Accept acceptType; - if (StringUtils.isNotBlank(format)) { - try { - acceptType = Accept.valueOf(format.toUpperCase()); - } catch (Exception e) { - acceptType = Accept.parse(format); - } - } else { - acceptType = Accept.parse(accept); - } - - return new AbstractMap.SimpleEntry(acceptType, getUtilities(acceptType)); - } - - protected AbstractUtilities getUtilities(final Accept accept) { - final AbstractUtilities utils; - if (accept == Accept.XML || accept == Accept.TEXT || accept == Accept.ATOM) { - utils = xml; - } else { - utils = json; - } - - return utils; - } - - protected void updateInlineEntities(final Entity entity) { - final String type = entity.getType(); - EntityType entityType; - Map navProperties = Collections.emptyMap(); - if (type != null && type.length() > 0) { - entityType = metadata.getEntityOrComplexType(type); - navProperties = entityType.getNavigationPropertyMap(); - } - - for (Property property : entity.getProperties()) { - if (navProperties.containsKey(property.getName())) { - Link alink = new Link(); - alink.setTitle(property.getName()); - alink.getAnnotations().addAll(property.getAnnotations()); - - alink.setType(navProperties.get(property.getName()).isEntitySet() - ? Constants.get(ConstantKey.ATOM_LINK_FEED) - : Constants.get(ConstantKey.ATOM_LINK_ENTRY)); - - alink.setRel(Constants.get(ConstantKey.ATOM_LINK_REL) + property.getName()); - - if (property.isCollection()) { - EntityCollection inline = new EntityCollection(); - for (Object value : property.asCollection()) { - Entity inlineEntity = new Entity(); - inlineEntity.setType(navProperties.get(property.getName()).getType()); - for (Property prop : ((ComplexValue) value).getValue()) { - inlineEntity.getProperties().add(prop); - } - inline.getEntities().add(inlineEntity); - } - alink.setInlineEntitySet(inline); - } else if (property.isComplex()) { - Entity inline = new Entity(); - inline.setType(navProperties.get(property.getName()).getType()); - for (Property prop : property.asComplex().getValue()) { - inline.getProperties().add(prop); - } - alink.setInlineEntity(inline); - - } else { - throw new IllegalStateException("Invalid navigation property " + property); - } - entity.getNavigationLinks().add(alink); - } - } - } - - protected void normalizeAtomEntry(final Entity entry, final String entitySetName, final String entityKey) { - final org.apache.olingo.fit.metadata.EntitySet entitySet = metadata.getEntitySet(entitySetName); - final EntityType entityType = metadata.getEntityOrComplexType(entitySet.getType()); - for (Map.Entry property : entityType.getPropertyMap().entrySet()) { - if (entry.getProperty(property.getKey()) == null && property.getValue().isNullable()) { - final Property prop = new Property(); - prop.setName(property.getKey()); - prop.setValue(ValueType.PRIMITIVE, null); - entry.getProperties().add(prop); - } - } - - for (Map.Entry property : entityType.getNavigationPropertyMap().entrySet()) { - boolean found = false; - for (Link link : entry.getNavigationLinks()) { - if (link.getTitle().equals(property.getKey())) { - found = true; - } - } - - if (!found) { - final Link link = new Link(); - link.setTitle(property.getKey()); - link.setType(property.getValue().isEntitySet() - ? Constants.get(ConstantKey.ATOM_LINK_FEED) - : Constants.get(ConstantKey.ATOM_LINK_ENTRY)); - link.setRel(Constants.get(ConstantKey.ATOM_LINK_REL) + property.getKey()); - link.setHref(entitySetName + "(" + entityKey + ")/" + property.getKey()); - entry.getNavigationLinks().add(link); - } - } - } -} diff --git a/fit/src/main/java/org/apache/olingo/fit/Demo.java b/fit/src/main/java/org/apache/olingo/fit/Demo.java index c591f0115..697b7c93a 100644 --- a/fit/src/main/java/org/apache/olingo/fit/Demo.java +++ b/fit/src/main/java/org/apache/olingo/fit/Demo.java @@ -40,7 +40,6 @@ import javax.ws.rs.core.UriInfo; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion; import org.apache.olingo.fit.metadata.Metadata; import org.apache.olingo.fit.methods.PATCH; import org.apache.olingo.fit.utils.Accept; @@ -54,7 +53,7 @@ import org.springframework.stereotype.Service; public class Demo extends Services { public Demo() throws IOException { - super(new Metadata(FSManager.instance(ODataServiceVersion.V40). + super(new Metadata(FSManager.instance(). readRes("demo" + StringUtils.capitalize(Constants.get(ConstantKey.METADATA)), Accept.XML))); } @@ -166,9 +165,8 @@ public class Demo extends Services { @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, @PathParam("entitySetName") final String entitySetName, @PathParam("entityId") final String entityId, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, final String value) { - return super.replaceMediaEntity(uriInfo, prefer, entitySetName, entityId, format, value); + return super.replaceMediaEntity(uriInfo, prefer, entitySetName, entityId, value); } } diff --git a/fit/src/main/java/org/apache/olingo/fit/OpenType.java b/fit/src/main/java/org/apache/olingo/fit/OpenType.java index e65c5bf8a..a15128e12 100644 --- a/fit/src/main/java/org/apache/olingo/fit/OpenType.java +++ b/fit/src/main/java/org/apache/olingo/fit/OpenType.java @@ -40,7 +40,6 @@ import javax.ws.rs.core.UriInfo; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion; import org.apache.olingo.fit.metadata.Metadata; import org.apache.olingo.fit.utils.Accept; import org.apache.olingo.fit.utils.ConstantKey; @@ -53,8 +52,8 @@ import org.springframework.stereotype.Service; public class OpenType extends Services { public OpenType() throws IOException { - super(new Metadata(FSManager.instance(ODataServiceVersion.V40). - readRes("openType" + StringUtils.capitalize(Constants.get(ConstantKey.METADATA)), Accept.XML))); + super(new Metadata(FSManager.instance() + .readRes("openType" + StringUtils.capitalize(Constants.get(ConstantKey.METADATA)), Accept.XML))); } private Response replaceServiceName(final Response response) { diff --git a/fit/src/main/java/org/apache/olingo/fit/Services.java b/fit/src/main/java/org/apache/olingo/fit/Services.java index 45f11a5cd..698938eba 100644 --- a/fit/src/main/java/org/apache/olingo/fit/Services.java +++ b/fit/src/main/java/org/apache/olingo/fit/Services.java @@ -25,15 +25,22 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.URI; +import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.ConcurrentModificationException; +import java.util.Enumeration; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; +import java.util.regex.Matcher; import java.util.regex.Pattern; +import javax.mail.Header; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMultipart; import javax.ws.rs.BadRequestException; @@ -51,6 +58,8 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; @@ -59,63 +68,140 @@ import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; +import org.apache.commons.lang3.tuple.Pair; import org.apache.cxf.interceptor.InInterceptors; +import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.Multipart; import org.apache.cxf.jaxrs.ext.multipart.MultipartBody; import org.apache.olingo.client.api.data.ResWrap; +import org.apache.olingo.client.api.serialization.ODataDeserializer; +import org.apache.olingo.client.api.serialization.ODataSerializer; +import org.apache.olingo.client.core.serialization.AtomSerializer; +import org.apache.olingo.client.core.serialization.JsonDeserializer; +import org.apache.olingo.client.core.serialization.JsonSerializer; +import org.apache.olingo.commons.api.data.ComplexValue; import org.apache.olingo.commons.api.data.Entity; import org.apache.olingo.commons.api.data.EntityCollection; import org.apache.olingo.commons.api.data.Link; import org.apache.olingo.commons.api.data.Property; import org.apache.olingo.commons.api.data.ValueType; -import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion; +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException; +import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; import org.apache.olingo.commons.api.format.ContentType; import org.apache.olingo.commons.core.edm.EdmTypeInfo; +import org.apache.olingo.commons.core.edm.primitivetype.EdmPrimitiveTypeFactory; +import org.apache.olingo.fit.metadata.EntityType; import org.apache.olingo.fit.metadata.Metadata; +import org.apache.olingo.fit.metadata.NavigationProperty; import org.apache.olingo.fit.methods.PATCH; import org.apache.olingo.fit.rest.ResolvingReferencesInterceptor; import org.apache.olingo.fit.rest.XHTTPMethodInterceptor; +import org.apache.olingo.fit.serializer.FITAtomDeserializer; import org.apache.olingo.fit.utils.AbstractUtilities; 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.FSManager; +import org.apache.olingo.fit.utils.JSONUtilities; import org.apache.olingo.fit.utils.LinkInfo; +import org.apache.olingo.fit.utils.XMLUtilities; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + @Service @Path("/V40/Static.svc") @InInterceptors(classes = { XHTTPMethodInterceptor.class, ResolvingReferencesInterceptor.class }) -public class Services extends AbstractServices { +public class Services { /** - * CR/LF. + * Logger. */ - protected static final byte[] CRLF = { 13, 10 }; + protected static final Logger LOG = LoggerFactory.getLogger(Services.class); - protected static final Pattern RELENTITY_SELECT_PATTERN = Pattern.compile("^.*\\(\\$select=.*\\)$"); - - protected static final Pattern CROSSJOIN_PATTERN = Pattern.compile( + private static final Pattern REQUEST_PATTERN = Pattern.compile("(.*) (http://.*) HTTP/.*"); + private static final Pattern BATCH_REQUEST_REF_PATTERN = Pattern.compile("(.*) ([$]\\d+)(.*) HTTP/.*"); + private static final Pattern REF_PATTERN = Pattern.compile("([$]\\d+)"); + private static final Pattern RELENTITY_SELECT_PATTERN = Pattern.compile("^.*\\(\\$select=.*\\)$"); + private static final Pattern CROSSJOIN_PATTERN = Pattern.compile( "^\\$crossjoin\\(.*\\)\\?\\$filter=\\([a-zA-Z/]+ eq [a-zA-Z/]+\\)$"); + protected static final String BOUNDARY = "batch_243234_25424_ef_892u748"; + protected static final String MULTIPART_MIXED = "multipart/mixed"; + protected static final String APPLICATION_OCTET_STREAM = "application/octet-stream"; private final Map providedAsync = new HashMap(); + protected final ODataDeserializer atomDeserializer = new FITAtomDeserializer(); + protected final ODataDeserializer jsonDeserializer = new JsonDeserializer(true); + protected final ODataSerializer atomSerializer = new AtomSerializer(true); + protected final ODataSerializer jsonSerializer = new JsonSerializer(true, ContentType.JSON_FULL_METADATA); + + protected final Metadata metadata; + protected final XMLUtilities xml; + protected final JSONUtilities json; + public Services() throws IOException { - super(ODataServiceVersion.V40, Commons.getMetadata(ODataServiceVersion.V40)); + this(Commons.getMetadata()); } protected Services(final Metadata metadata) throws IOException { - super(ODataServiceVersion.V40, metadata); + this.metadata = metadata; + xml = new XMLUtilities(metadata); + json = new JSONUtilities(metadata); + } + + /** + * Provide sample services. + * + * @param accept Accept header. + * @return OData services. + */ + @GET + public Response getServices(@HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept) { + try { + final Accept acceptType = Accept.parse(accept); + + if (acceptType == Accept.ATOM) { + throw new UnsupportedMediaTypeException("Unsupported media type"); + } + + return xml.createResponse( + null, + FSManager.instance().readFile(Constants.get(ConstantKey.SERVICES), acceptType), + null, acceptType); + } catch (Exception e) { + return xml.createFaultResponse(accept, e); + } + } + + /** + * Provide sample getMetadata(). + * + * @return getMetadata(). + */ + @GET + @Path("/$metadata") + @Produces(MediaType.APPLICATION_XML) + public Response getMetadata() { + return getMetadata(Constants.get(ConstantKey.METADATA)); + } + + protected Response getMetadata(final String filename) { + try { + return xml.createResponse(null, FSManager.instance().readRes(filename, Accept.XML), null, Accept.XML); + } catch (Exception e) { + return xml.createFaultResponse(Accept.XML.toString(), e); + } } @GET @Path("/redirect/{name}({id})") - public Response conformanceRedirect( - @Context final UriInfo uriInfo, - @PathParam("name") final String name, - @PathParam("id") final String id) { + public Response conformanceRedirect(@Context final UriInfo uriInfo) { return Response.temporaryRedirect( URI.create(uriInfo.getRequestUri().toASCIIString().replace("/redirect", ""))).build(); } @@ -128,7 +214,7 @@ public class Services extends AbstractServices { try { if (CROSSJOIN_PATTERN.matcher("$crossjoin(" + elements + ")?$filter=" + filter).matches()) { - final InputStream feed = FSManager.instance(version).readFile("crossjoin", Accept.JSON); + final InputStream feed = FSManager.instance().readFile("crossjoin", Accept.JSON); return xml.createResponse(feed, null, Accept.JSON_FULLMETA); } else { @@ -141,9 +227,7 @@ public class Services extends AbstractServices { @GET @Path("/relatedEntitySelect/{path:.*}") - public Response relatedEntitySelect( - @PathParam("path") final String path, - @QueryParam("$expand") final String expand) { + public Response relatedEntitySelect(@QueryParam("$expand") final String expand) { if (RELENTITY_SELECT_PATTERN.matcher(expand).matches()) { return xml.createResponse(null, null, Accept.JSON_FULLMETA); @@ -177,7 +261,6 @@ public class Services extends AbstractServices { @PUT @Path("/People(1)/Parent") public Response changeSingleValuedNavigationPropertyReference( - @Context final UriInfo uriInfo, @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType, final String content) { @@ -196,39 +279,95 @@ public class Services extends AbstractServices { } @POST - @Path("/async/$batch") - public Response async( - @Context final UriInfo uriInfo, + @Path("/$batch") + @Consumes(MULTIPART_MIXED) + @Produces(APPLICATION_OCTET_STREAM + ";boundary=" + BOUNDARY) + public Response batch( @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, final @Multipart MultipartBody attachment) { + try { + final boolean continueOnError = prefer.contains("odata.continue-on-error"); + return xml.createBatchResponse( + exploreMultipart(attachment.getAllAttachments(), BOUNDARY, continueOnError)); + } catch (IOException e) { + return xml.createFaultResponse(Accept.XML.toString(), e); + } + } + + // ---------------------------------------------- + // just for non nullable property test into PropertyTestITCase + // ---------------------------------------------- + @PATCH + @Path("/Driver('2')") + public Response patchDriver() { + return xml.createFaultResponse(Accept.JSON_FULLMETA.toString(), new Exception("Non nullable properties")); + } + + @GET + @Path("/StoredPIs(1000)") + public Response getStoredPI(@Context final UriInfo uriInfo) { + final Entity entity = new Entity(); + entity.setType("Microsoft.Test.OData.Services.ODataWCFService.StoredPI"); + final Property id = new Property(); + id.setType("Edm.Int32"); + id.setName("StoredPIID"); + id.setValue(ValueType.PRIMITIVE, 1000); + entity.getProperties().add(id); + final Link edit = new Link(); + edit.setHref(uriInfo.getRequestUri().toASCIIString()); + edit.setRel("edit"); + edit.setTitle("StoredPI"); + entity.setEditLink(edit); + + final ByteArrayOutputStream content = new ByteArrayOutputStream(); + final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING); + try { + jsonSerializer.write(writer, new ResWrap((URI) null, null, entity)); + return xml.createResponse(new ByteArrayInputStream(content.toByteArray()), null, Accept.JSON_FULLMETA); + } catch (Exception e) { + LOG.error("While creating StoredPI", e); + return xml.createFaultResponse(Accept.JSON_FULLMETA.toString(), e); + } + } + + @PATCH + @Path("/StoredPIs(1000)") + public Response patchStoredPI() { + // just for non nullable property test into PropertyTestITCase + return xml.createFaultResponse(Accept.JSON_FULLMETA.toString(), new Exception("Non nullable properties")); + } + + @POST + @Path("/async/$batch") + public Response async(@Context final UriInfo uriInfo) { try { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); bos.write("HTTP/1.1 200 Ok".getBytes()); - bos.write(CRLF); + bos.write(Constants.CRLF); bos.write("OData-Version: 4.0".getBytes()); - bos.write(CRLF); + bos.write(Constants.CRLF); bos.write(("Content-Type: " + ContentType.APPLICATION_OCTET_STREAM + ";boundary=" + BOUNDARY).getBytes()); - bos.write(CRLF); - bos.write(CRLF); + bos.write(Constants.CRLF); + bos.write(Constants.CRLF); bos.write(("--" + BOUNDARY).getBytes()); - bos.write(CRLF); + bos.write(Constants.CRLF); bos.write("Content-Type: application/http".getBytes()); - bos.write(CRLF); + bos.write(Constants.CRLF); bos.write("Content-Transfer-Encoding: binary".getBytes()); - bos.write(CRLF); - bos.write(CRLF); + bos.write(Constants.CRLF); + bos.write(Constants.CRLF); bos.write("HTTP/1.1 202 Accepted".getBytes()); - bos.write(CRLF); + bos.write(Constants.CRLF); bos.write("Location: http://service-root/async-monitor".getBytes()); - bos.write(CRLF); + bos.write(Constants.CRLF); bos.write("Retry-After: 10".getBytes()); - bos.write(CRLF); - bos.write(CRLF); + bos.write(Constants.CRLF); + bos.write(Constants.CRLF); bos.write(("--" + BOUNDARY + "--").getBytes()); - bos.write(CRLF); + bos.write(Constants.CRLF); final UUID uuid = UUID.randomUUID(); providedAsync.put(uuid.toString(), bos.toString(Constants.ENCODING.toString())); @@ -263,11 +402,13 @@ public class Services extends AbstractServices { ? Constants.get(ConstantKey.ENTITY) : Constants.get(ConstantKey.FEED)); - final InputStream feed = FSManager.instance(version).readFile(path.toString(), acceptType); + final InputStream feed = FSManager.instance().readFile(path.toString(), acceptType); final StringBuilder builder = new StringBuilder(); - builder.append("HTTP/1.1 200 Ok").append(new String(CRLF)); - builder.append("Content-Type: ").append(accept).append(new String(CRLF)).append(new String(CRLF)); + builder.append("HTTP/1.1 200 Ok").append(new String(Constants.CRLF)); + builder.append("Content-Type: ").append(accept) + .append(new String(Constants.CRLF)) + .append(new String(Constants.CRLF)); builder.append(IOUtils.toString(feed)); IOUtils.closeQuietly(feed); @@ -281,15 +422,80 @@ public class Services extends AbstractServices { } } - @Override - protected void setInlineCount(final EntityCollection entitySet, final String count) { + private void setInlineCount(final EntityCollection entitySet, final String count) { if ("true".equals(count)) { entitySet.setCount(entitySet.getEntities().size()); } } - @Override - public InputStream exploreMultipart( + private Response bodyPartRequest(final MimeBodyPart body, final Map references) throws Exception { + @SuppressWarnings("unchecked") + final Enumeration
en = body.getAllHeaders(); + + Header header = en.nextElement(); + final String request = + header.getName() + (StringUtils.isNotBlank(header.getValue()) ? ":" + header.getValue() : ""); + + final Matcher matcher = REQUEST_PATTERN.matcher(request); + final Matcher matcherRef = BATCH_REQUEST_REF_PATTERN.matcher(request); + + final MultivaluedMap headers = new MultivaluedHashMap(); + + while (en.hasMoreElements()) { + header = en.nextElement(); + headers.putSingle(header.getName(), header.getValue()); + } + + final Response res; + final String url; + final String method; + + if (matcher.find()) { + url = matcher.group(2); + method = matcher.group(1); + } else if (matcherRef.find()) { + url = references.get(matcherRef.group(2)) + matcherRef.group(3); + method = matcherRef.group(1); + } else { + url = null; + method = null; + } + + if (url == null) { + res = null; + } else { + final WebClient client = WebClient.create(url, "odatajclient", "odatajclient", null); + client.headers(headers); + + if ("DELETE".equals(method)) { + res = client.delete(); + } else { + final InputStream is = body.getDataHandler().getInputStream(); + String content = IOUtils.toString(is); + IOUtils.closeQuietly(is); + + final Matcher refs = REF_PATTERN.matcher(content); + + while (refs.find()) { + content = content.replace(refs.group(1), references.get(refs.group(1))); + } + + if ("PATCH".equals(method) || "MERGE".equals(method)) { + client.header("X-HTTP-METHOD", method); + res = client.invoke("POST", IOUtils.toInputStream(content)); + } else { + res = client.invoke(method, IOUtils.toInputStream(content)); + } + } + + // When updating to CXF 3.0.1, uncomment the following line, see CXF-5865 + // client.close(); + } + + return res; + } + + private InputStream exploreMultipart( final List attachments, final String boundary, final boolean continueOnError) throws IOException { @@ -349,9 +555,10 @@ public class Services extends AbstractServices { goon = continueOnError; } } else { - addItemIntro(bos); + addItemIntro(bos, null); - res = bodyPartRequest(new MimeBodyPart(obj.getDataHandler().getInputStream())); + res = bodyPartRequest(new MimeBodyPart(obj.getDataHandler().getInputStream()), + Collections. emptyMap()); if (res.getStatus() >= 400) { goon = continueOnError; @@ -374,6 +581,517 @@ public class Services extends AbstractServices { return new ByteArrayInputStream(bos.toByteArray()); } + private void addItemIntro(final ByteArrayOutputStream bos, final String contentId) throws IOException { + bos.write("Content-Type: application/http".getBytes()); + bos.write(Constants.CRLF); + bos.write("Content-Transfer-Encoding: binary".getBytes()); + bos.write(Constants.CRLF); + + if (StringUtils.isNotBlank(contentId)) { + bos.write(("Content-ID: " + contentId).getBytes()); + bos.write(Constants.CRLF); + } + + bos.write(Constants.CRLF); + } + + private void addChangesetItemIntro( + final ByteArrayOutputStream bos, final String contentId, final String cboundary) throws IOException { + bos.write(("--" + cboundary).getBytes()); + bos.write(Constants.CRLF); + bos.write(("Content-ID: " + contentId).getBytes()); + bos.write(Constants.CRLF); + addItemIntro(bos, null); + } + + private void addSingleBatchResponse( + final Response response, final ByteArrayOutputStream bos) throws IOException { + addSingleBatchResponse(response, null, bos); + } + + private void addSingleBatchResponse( + final Response response, final String contentId, final ByteArrayOutputStream bos) throws IOException { + bos.write("HTTP/1.1 ".getBytes()); + bos.write(String.valueOf(response.getStatusInfo().getStatusCode()).getBytes()); + bos.write(" ".getBytes()); + bos.write(response.getStatusInfo().getReasonPhrase().getBytes()); + bos.write(Constants.CRLF); + + for (Map.Entry> header : response.getHeaders().entrySet()) { + final StringBuilder builder = new StringBuilder(); + for (Object value : header.getValue()) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append(value.toString()); + } + builder.insert(0, ": ").insert(0, header.getKey()); + bos.write(builder.toString().getBytes()); + bos.write(Constants.CRLF); + } + + if (StringUtils.isNotBlank(contentId)) { + bos.write(("Content-ID: " + contentId).getBytes()); + bos.write(Constants.CRLF); + } + + bos.write(Constants.CRLF); + + final Object entity = response.getEntity(); + if (entity != null) { + bos.write(IOUtils.toByteArray((InputStream) entity)); + bos.write(Constants.CRLF); + } + + bos.write(Constants.CRLF); + } + + protected void addErrorBatchResponse(final Exception e, final ByteArrayOutputStream bos) + throws IOException { + addErrorBatchResponse(e, null, bos); + } + + protected void addErrorBatchResponse(final Exception e, final String contentId, final ByteArrayOutputStream bos) + throws IOException { + addSingleBatchResponse(xml.createFaultResponse(Accept.XML.toString(), e), contentId, bos); + } + + /** + * Retrieve entities from the given entity set and the given type. + * + * @param accept Accept header. + * @param name entity set. + * @param type entity type. + * @return entity set. + */ + @GET + @Path("/{name}/{type:[a-zA-Z].*}") + public Response getEntitySet( + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @PathParam("name") final String name, + @PathParam("type") final String type) { + + try { + final Accept acceptType = Accept.parse(accept); + if (acceptType == Accept.XML || acceptType == Accept.TEXT) { + throw new UnsupportedMediaTypeException("Unsupported media type"); + } + + final String basePath = name + File.separatorChar; + final StringBuilder path = new StringBuilder(name). + append(File.separatorChar).append(type). + append(File.separatorChar); + + path.append(metadata.getEntitySet(name).isSingleton() + ? Constants.get(ConstantKey.ENTITY) + : Constants.get(ConstantKey.FEED)); + + final InputStream feed = FSManager.instance().readFile(path.toString(), acceptType); + return xml.createResponse(null, feed, Commons.getETag(basePath), acceptType); + } catch (Exception e) { + return xml.createFaultResponse(accept, e); + } + } + + @GET + @Path("/{name}/{type:[a-zA-Z].*}") + public Response getEntitySet(@Context final UriInfo uriInfo, + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @PathParam("name") final String name, + @QueryParam("$top") @DefaultValue(StringUtils.EMPTY) final String top, + @QueryParam("$skip") @DefaultValue(StringUtils.EMPTY) final String skip, + @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, + @QueryParam("$count") @DefaultValue(StringUtils.EMPTY) final String count, + @QueryParam("$filter") @DefaultValue(StringUtils.EMPTY) final String filter, + @QueryParam("$orderby") @DefaultValue(StringUtils.EMPTY) final String orderby, + @QueryParam("$skiptoken") @DefaultValue(StringUtils.EMPTY) final String skiptoken, + @PathParam("type") final String type) { + + try { + final Accept acceptType; + if (StringUtils.isNotBlank(format)) { + acceptType = Accept.valueOf(format.toUpperCase()); + } else { + acceptType = Accept.parse(accept); + } + + final String location = uriInfo.getRequestUri().toASCIIString(); + try { + // search for function ... + final InputStream func = FSManager.instance().readFile(name, acceptType); + return xml.createResponse(location, func, null, acceptType); + } catch (NotFoundException e) { + if (acceptType == Accept.XML || acceptType == Accept.TEXT) { + throw new UnsupportedMediaTypeException("Unsupported media type"); + } + + // search for entitySet ... + final String basePath = name + File.separatorChar; + + final StringBuilder builder = new StringBuilder(); + builder.append(basePath); + + if (type != null) { + builder.append(type).append(File.separatorChar); + } + + if (StringUtils.isNotBlank(orderby)) { + builder.append(Constants.get(ConstantKey.ORDERBY)).append(File.separatorChar). + append(orderby).append(File.separatorChar); + } + + if (StringUtils.isNotBlank(filter)) { + builder.append(Constants.get(ConstantKey.FILTER)).append(File.separatorChar). + append(filter.replaceAll("/", ".")); + } else if (StringUtils.isNotBlank(skiptoken)) { + builder.append(Constants.get(ConstantKey.SKIP_TOKEN)).append(File.separatorChar). + append(skiptoken); + } else { + builder.append(metadata.getEntitySet(name).isSingleton() + ? Constants.get(ConstantKey.ENTITY) + : Constants.get(ConstantKey.FEED)); + } + + final InputStream feed = FSManager.instance().readFile(builder.toString(), Accept.ATOM); + + final ResWrap container = atomDeserializer.toEntitySet(feed); + + setInlineCount(container.getPayload(), count); + + final ByteArrayOutputStream content = new ByteArrayOutputStream(); + final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING); + + // ----------------------------------------------- + // Evaluate $skip and $top + // ----------------------------------------------- + List entries = new ArrayList(container.getPayload().getEntities()); + + if (StringUtils.isNotBlank(skip)) { + entries = entries.subList(Integer.valueOf(skip), entries.size()); + } + + if (StringUtils.isNotBlank(top)) { + entries = entries.subList(0, Integer.valueOf(top)); + } + + container.getPayload().getEntities().clear(); + container.getPayload().getEntities().addAll(entries); + // ----------------------------------------------- + + if (acceptType == Accept.ATOM) { + atomSerializer.write(writer, container); + } else { + jsonSerializer.write(writer, container); + } + writer.flush(); + writer.close(); + + return xml.createResponse( + location, + new ByteArrayInputStream(content.toByteArray()), + Commons.getETag(basePath), + acceptType); + } + } catch (Exception e) { + return xml.createFaultResponse(accept, e); + } + } + + /** + * Retrieve entity set or function execution sample. + * + * @param accept Accept header. + * @param name entity set or function name. + * @param format format query option. + * @param count count query option. + * @param filter filter query option. + * @param orderby orderby query option. + * @param skiptoken skiptoken query option. + * @return entity set or function result. + */ + @GET + @Path("/{name}") + public Response getEntitySet( + @Context final UriInfo uriInfo, + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @PathParam("name") final String name, + @QueryParam("$top") @DefaultValue(StringUtils.EMPTY) final String top, + @QueryParam("$skip") @DefaultValue(StringUtils.EMPTY) final String skip, + @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, + @QueryParam("$count") @DefaultValue(StringUtils.EMPTY) final String count, + @QueryParam("$filter") @DefaultValue(StringUtils.EMPTY) final String filter, + @QueryParam("$orderby") @DefaultValue(StringUtils.EMPTY) final String orderby, + @QueryParam("$skiptoken") @DefaultValue(StringUtils.EMPTY) final String skiptoken) { + + return getEntitySet(uriInfo, accept, name, top, skip, format, count, filter, orderby, skiptoken, null); + } + + @GET + @Path("/Person({entityId})") + public Response getPerson( + @Context final UriInfo uriInfo, + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @PathParam("entityId") final String entityId, + @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) { + + final Map.Entry utils = getUtilities(accept, format); + + final Response internal = getEntityInternal( + uriInfo.getRequestUri().toASCIIString(), accept, "Person", entityId, format, null, null); + if (internal.getStatus() == 200) { + InputStream entity = (InputStream) internal.getEntity(); + try { + if (utils.getKey() == Accept.JSON_FULLMETA || utils.getKey() == Accept.ATOM) { + entity = utils.getValue().addOperation(entity, "Sack", "#DefaultContainer.Sack", + uriInfo.getAbsolutePath().toASCIIString() + + "/Microsoft.Test.OData.Services.AstoriaDefaultService.SpecialEmployee/Sack"); + } + + return utils.getValue().createResponse( + uriInfo.getRequestUri().toASCIIString(), + entity, + internal.getHeaderString("ETag"), + utils.getKey()); + } catch (Exception e) { + LOG.error("Error retrieving entity", e); + return xml.createFaultResponse(accept, e); + } + } else { + return internal; + } + } + + @GET + @Path("/Product({entityId})") + public Response getProduct( + @Context final UriInfo uriInfo, + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @PathParam("entityId") final String entityId, + @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) { + + final Map.Entry utils = getUtilities(accept, format); + + final Response internal = getEntityInternal( + uriInfo.getRequestUri().toASCIIString(), accept, "Product", entityId, format, null, null); + if (internal.getStatus() == 200) { + InputStream entity = (InputStream) internal.getEntity(); + try { + if (utils.getKey() == Accept.JSON_FULLMETA || utils.getKey() == Accept.ATOM) { + entity = utils.getValue().addOperation(entity, + "ChangeProductDimensions", "#DefaultContainer.ChangeProductDimensions", + uriInfo.getAbsolutePath().toASCIIString() + "/ChangeProductDimensions"); + } + + return utils.getValue().createResponse( + uriInfo.getRequestUri().toASCIIString(), + entity, + internal.getHeaderString("ETag"), + utils.getKey()); + } catch (Exception e) { + LOG.error("Error retrieving entity", e); + return xml.createFaultResponse(accept, e); + } + } else { + return internal; + } + } + + @GET + @Path("/ComputerDetail({entityId})") + public Response getComputerDetail( + @Context final UriInfo uriInfo, + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @PathParam("entityId") final String entityId, + @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) { + + final Map.Entry utils = getUtilities(accept, format); + + final Response internal = getEntityInternal( + uriInfo.getRequestUri().toASCIIString(), accept, "ComputerDetail", entityId, format, null, null); + if (internal.getStatus() == 200) { + InputStream entity = (InputStream) internal.getEntity(); + try { + if (utils.getKey() == Accept.JSON_FULLMETA || utils.getKey() == Accept.ATOM) { + entity = utils.getValue().addOperation(entity, + "ResetComputerDetailsSpecifications", "#DefaultContainer.ResetComputerDetailsSpecifications", + uriInfo.getAbsolutePath().toASCIIString() + "/ResetComputerDetailsSpecifications"); + } + + return utils.getValue().createResponse( + uriInfo.getRequestUri().toASCIIString(), + entity, + internal.getHeaderString("ETag"), + utils.getKey()); + } catch (Exception e) { + LOG.error("Error retrieving entity", e); + return xml.createFaultResponse(accept, e); + } + } else { + return internal; + } + } + + /** + * Retrieve entity sample. + * + * @param accept Accept header. + * @param entitySetName Entity set name. + * @param entityId entity id. + * @param format format query option. + * @param expand expand query option. + * @param select select query option. + * @return entity. + */ + @GET + @Path("/{entitySetName}({entityId})") + public Response getEntity( + @Context final UriInfo uriInfo, + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @PathParam("entitySetName") final String entitySetName, + @PathParam("entityId") final String entityId, + @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, + @QueryParam("$expand") @DefaultValue(StringUtils.EMPTY) final String expand, + @QueryParam("$select") @DefaultValue(StringUtils.EMPTY) final String select) { + + return getEntityInternal( + uriInfo.getRequestUri().toASCIIString(), accept, entitySetName, entityId, format, expand, select); + } + + protected Response getEntityInternal( + final String location, + final String accept, + final String entitySetName, + final String entityId, + final String format, + final String expand, + final String select) { + + try { + final Map.Entry utils = getUtilities(accept, format); + + if (utils.getKey() == Accept.XML || utils.getKey() == Accept.TEXT) { + throw new UnsupportedMediaTypeException("Unsupported media type"); + } + + final Map.Entry entityInfo = + utils.getValue().readEntity(entitySetName, entityId, Accept.ATOM); + + final InputStream entity = entityInfo.getValue(); + + ResWrap container = atomDeserializer.toEntity(entity); + if (container.getContextURL() == null) { + container = new ResWrap(URI.create(Constants.get(ConstantKey.ODATA_METADATA_PREFIX) + + entitySetName + Constants.get(ConstantKey.ODATA_METADATA_ENTITY_SUFFIX)), + container.getMetadataETag(), container.getPayload()); + } + final Entity entry = container.getPayload(); + + if ((this instanceof KeyAsSegment)) { + final Link editLink = new Link(); + editLink.setRel("edit"); + editLink.setTitle(entitySetName); + editLink.setHref(Constants.get(ConstantKey.DEFAULT_SERVICE_URL) + entitySetName + "/" + entityId); + + entry.setEditLink(editLink); + } + + if (StringUtils.isNotBlank(select)) { + final List properties = Arrays.asList(select.split(",")); + final Set toBeRemoved = new HashSet(); + + for (Property property : entry.getProperties()) { + if (!properties.contains(property.getName())) { + toBeRemoved.add(property); + } + } + + entry.getProperties().removeAll(toBeRemoved); + + final Set linkToBeRemoved = new HashSet(); + + for (Link link : entry.getNavigationLinks()) { + if (!properties.contains(link.getTitle().replaceAll("@.*$", "")) && !properties.contains(link.getTitle())) { + linkToBeRemoved.add(link); + } + } + + entry.getNavigationLinks().removeAll(linkToBeRemoved); + } + + String tempExpand = expand; + if (StringUtils.isNotBlank(tempExpand)) { + tempExpand = StringUtils.substringBefore(tempExpand, "("); + final List links = Arrays.asList(tempExpand.split(",")); + + final Map replace = new HashMap(); + + for (Link link : entry.getNavigationLinks()) { + if (links.contains(link.getTitle())) { + // expand link + final Link rep = new Link(); + rep.setHref(link.getHref()); + rep.setRel(link.getRel()); + rep.setTitle(link.getTitle()); + rep.setType(link.getType()); + if (link.getType().equals(Constants.get(ConstantKey.ATOM_LINK_ENTRY))) { + // inline entry + final Entity inline = atomDeserializer.toEntity( + xml.expandEntity(entitySetName, entityId, link.getTitle())).getPayload(); + rep.setInlineEntity(inline); + } else if (link.getType().equals(Constants.get(ConstantKey.ATOM_LINK_FEED))) { + // inline feed + final EntityCollection inline = atomDeserializer.toEntitySet( + xml.expandEntity(entitySetName, entityId, link.getTitle())).getPayload(); + rep.setInlineEntitySet(inline); + } + replace.put(link, rep); + } + } + + for (Map.Entry link : replace.entrySet()) { + entry.getNavigationLinks().remove(link.getKey()); + entry.getNavigationLinks().add(link.getValue()); + } + } + + return xml.createResponse( + location, + xml.writeEntity(utils.getKey(), container), + Commons.getETag(entityInfo.getKey()), + utils.getKey()); + } catch (Exception e) { + LOG.error("Error retrieving entity", e); + return xml.createFaultResponse(accept, e); + } + } + + @GET + @Path("/{entitySetName}({entityId})/$value") + public Response getMediaEntity( + @Context final UriInfo uriInfo, + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @PathParam("entitySetName") final String entitySetName, + @PathParam("entityId") final String entityId) { + + try { + if (!accept.contains("*/*") && !accept.contains("application/octet-stream")) { + throw new UnsupportedMediaTypeException("Unsupported media type"); + } + + final AbstractUtilities utils = getUtilities(null); + final Map.Entry entityInfo = utils.readMediaEntity(entitySetName, entityId); + return utils.createResponse( + uriInfo.getRequestUri().toASCIIString(), + entityInfo.getValue(), + Commons.getETag(entityInfo.getKey()), + null); + + } catch (Exception e) { + LOG.error("Error retrieving entity", e); + return xml.createFaultResponse(accept, e); + } + } + @GET @Path("/People/{type:.*}") public Response getPeople( @@ -389,12 +1107,11 @@ public class Services extends AbstractServices { @QueryParam("$orderby") @DefaultValue(StringUtils.EMPTY) final String orderby, @QueryParam("$skiptoken") @DefaultValue(StringUtils.EMPTY) final String skiptoken) { - return StringUtils.isBlank(filter) && StringUtils.isBlank(search) - ? NumberUtils.isNumber(type) - ? super.getEntityInternal( - uriInfo.getRequestUri().toASCIIString(), accept, "People", type, format, null, null) - : super.getEntitySet(accept, "People", type) - : super.getEntitySet(uriInfo, accept, "People", top, skip, format, count, filter, orderby, skiptoken, type); + return StringUtils.isBlank(filter) && StringUtils.isBlank(search) ? + NumberUtils.isNumber(type) ? + getEntityInternal(uriInfo.getRequestUri().toASCIIString(), accept, "People", type, format, null, null) : + getEntitySet(accept, "People", type) : + getEntitySet(uriInfo, accept, "People", top, skip, format, count, filter, orderby, skiptoken, type); } @GET @@ -431,7 +1148,7 @@ public class Services extends AbstractServices { @HeaderParam("If-Match") @DefaultValue(StringUtils.EMPTY) final String ifMatch, final String changes) { - return super.patchEntity(uriInfo, accept, contentType, prefer, ifMatch, "Company", StringUtils.EMPTY, changes); + return patchEntityInternal(uriInfo, accept, contentType, prefer, ifMatch, "Company", StringUtils.EMPTY, changes); } @GET @@ -467,7 +1184,7 @@ public class Services extends AbstractServices { null, entitySet)); } else { - output = FSManager.instance(version).readFile("delta", acceptType); + output = FSManager.instance().readFile("delta", acceptType); } final Response response = xml.createResponse( @@ -484,6 +1201,219 @@ public class Services extends AbstractServices { } } + @POST + @Path("/{entitySetName}") + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON }) + @Consumes({ MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM }) + public Response postNewEntity( + @Context final UriInfo uriInfo, + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType, + @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, + @PathParam("entitySetName") final String entitySetName, + final String entity) { + + try { + final Accept acceptType = Accept.parse(accept); + if (acceptType == Accept.XML || acceptType == Accept.TEXT) { + throw new UnsupportedMediaTypeException("Unsupported media type"); + } + + final ResWrap container; + + final org.apache.olingo.fit.metadata.EntitySet entitySet = metadata.getEntitySet(entitySetName); + + final Entity entry; + final String entityKey; + if (xml.isMediaContent(entitySetName)) { + entry = new Entity(); + entry.setMediaContentType(ContentType.APPLICATION_OCTET_STREAM.toContentTypeString()); + entry.setType(entitySet.getType()); + + entityKey = xml.getDefaultEntryKey(entitySetName, entry); + + xml.addMediaEntityValue(entitySetName, entityKey, IOUtils.toInputStream(entity, Constants.ENCODING)); + + final Pair id = Commons.getMediaContent().get(entitySetName); + if (id != null) { + final Property prop = new Property(); + prop.setName(id.getKey()); + prop.setType(id.getValue().toString()); + prop.setValue(ValueType.PRIMITIVE, + id.getValue() == EdmPrimitiveTypeKind.Int32 + ? Integer.parseInt(entityKey) + : id.getValue() == EdmPrimitiveTypeKind.Guid + ? UUID.fromString(entityKey) + : entityKey); + entry.getProperties().add(prop); + } + + final Link editLink = new Link(); + editLink.setHref(Commons.getEntityURI(entitySetName, entityKey)); + editLink.setRel("edit"); + editLink.setTitle(entitySetName); + entry.setEditLink(editLink); + + entry.setMediaContentSource(URI.create(editLink.getHref() + "/$value")); + + container = new ResWrap((URI) null, null, entry); + } else { + final Accept contentTypeValue = Accept.parse(contentType); + if (Accept.ATOM == contentTypeValue) { + container = atomDeserializer.toEntity(IOUtils.toInputStream(entity, Constants.ENCODING)); + } else { + container = jsonDeserializer.toEntity(IOUtils.toInputStream(entity, Constants.ENCODING)); + } + entry = container.getPayload(); + updateInlineEntities(entry); + + entityKey = xml.getDefaultEntryKey(entitySetName, entry); + } + + normalizeAtomEntry(entry, entitySetName, entityKey); + + final ByteArrayOutputStream content = new ByteArrayOutputStream(); + final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING); + atomSerializer.write(writer, container); + writer.flush(); + writer.close(); + + final InputStream serialization = + xml.addOrReplaceEntity(entityKey, entitySetName, new ByteArrayInputStream(content.toByteArray()), entry); + + ResWrap result = atomDeserializer.toEntity(serialization); + result = new ResWrap( + URI.create(Constants.get(ConstantKey.ODATA_METADATA_PREFIX) + + entitySetName + Constants.get(ConstantKey.ODATA_METADATA_ENTITY_SUFFIX)), + null, result.getPayload()); + + final String path = Commons.getEntityBasePath(entitySetName, entityKey); + FSManager.instance().putInMemory(result, path + Constants.get(ConstantKey.ENTITY)); + + final String location; + + if ((this instanceof KeyAsSegment)) { + location = uriInfo.getRequestUri().toASCIIString() + "/" + entityKey; + + final Link editLink = new Link(); + editLink.setRel("edit"); + editLink.setTitle(entitySetName); + editLink.setHref(location); + + result.getPayload().setEditLink(editLink); + } else { + location = uriInfo.getRequestUri().toASCIIString() + "(" + entityKey + ")"; + } + + final Response response; + if ("return-no-content".equalsIgnoreCase(prefer)) { + response = xml.createResponse( + location, + null, + null, + acceptType, + Response.Status.NO_CONTENT); + } else { + response = xml.createResponse( + location, + xml.writeEntity(acceptType, result), + null, + acceptType, + Response.Status.CREATED); + } + + if (StringUtils.isNotBlank(prefer)) { + response.getHeaders().put("Preference-Applied", Collections. singletonList(prefer)); + } + + return response; + } catch (Exception e) { + LOG.error("While creating new entity", e); + return xml.createFaultResponse(accept, e); + } + } + + private void updateInlineEntities(final Entity entity) { + final String type = entity.getType(); + EntityType entityType; + Map navProperties = Collections.emptyMap(); + if (type != null && type.length() > 0) { + entityType = metadata.getEntityOrComplexType(type); + navProperties = entityType.getNavigationPropertyMap(); + } + + for (Property property : entity.getProperties()) { + if (navProperties.containsKey(property.getName())) { + Link alink = new Link(); + alink.setTitle(property.getName()); + alink.getAnnotations().addAll(property.getAnnotations()); + + alink.setType(navProperties.get(property.getName()).isEntitySet() + ? Constants.get(ConstantKey.ATOM_LINK_FEED) + : Constants.get(ConstantKey.ATOM_LINK_ENTRY)); + + alink.setRel(Constants.get(ConstantKey.ATOM_LINK_REL) + property.getName()); + + if (property.isCollection()) { + EntityCollection inline = new EntityCollection(); + for (Object value : property.asCollection()) { + Entity inlineEntity = new Entity(); + inlineEntity.setType(navProperties.get(property.getName()).getType()); + for (Property prop : ((ComplexValue) value).getValue()) { + inlineEntity.getProperties().add(prop); + } + inline.getEntities().add(inlineEntity); + } + alink.setInlineEntitySet(inline); + } else if (property.isComplex()) { + Entity inline = new Entity(); + inline.setType(navProperties.get(property.getName()).getType()); + for (Property prop : property.asComplex().getValue()) { + inline.getProperties().add(prop); + } + alink.setInlineEntity(inline); + + } else { + throw new IllegalStateException("Invalid navigation property " + property); + } + entity.getNavigationLinks().add(alink); + } + } + } + + private void normalizeAtomEntry(final Entity entry, final String entitySetName, final String entityKey) { + final org.apache.olingo.fit.metadata.EntitySet entitySet = metadata.getEntitySet(entitySetName); + final EntityType entityType = metadata.getEntityOrComplexType(entitySet.getType()); + for (Map.Entry property : entityType.getPropertyMap().entrySet()) { + if (entry.getProperty(property.getKey()) == null && property.getValue().isNullable()) { + final Property prop = new Property(); + prop.setName(property.getKey()); + prop.setValue(ValueType.PRIMITIVE, null); + entry.getProperties().add(prop); + } + } + + for (Map.Entry property : entityType.getNavigationPropertyMap().entrySet()) { + boolean found = false; + for (Link link : entry.getNavigationLinks()) { + if (link.getTitle().equals(property.getKey())) { + found = true; + } + } + + if (!found) { + final Link link = new Link(); + link.setTitle(property.getKey()); + link.setType(property.getValue().isEntitySet() + ? Constants.get(ConstantKey.ATOM_LINK_FEED) + : Constants.get(ConstantKey.ATOM_LINK_ENTRY)); + link.setRel(Constants.get(ConstantKey.ATOM_LINK_REL) + property.getKey()); + link.setHref(entitySetName + "(" + entityKey + ")/" + property.getKey()); + entry.getNavigationLinks().add(link); + } + } + } + @GET @Path("/Company/Microsoft.Test.OData.Services.ODataWCFService.GetEmployeesCount{paren:[\\(\\)]*}") public Response functionGetEmployeesCount( @@ -515,6 +1445,170 @@ public class Services extends AbstractServices { } } + @POST + @Path("/Person({entityId})/{type:.*}/Sack") + public Response actionSack( + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @PathParam("entityId") final String entityId, + @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) { + + final Map.Entry utils = getUtilities(accept, format); + + if (utils.getKey() == Accept.XML || utils.getKey() == Accept.TEXT) { + throw new UnsupportedMediaTypeException("Unsupported media type"); + } + + try { + final Map.Entry entityInfo = xml.readEntity("Person", entityId, Accept.ATOM); + + final InputStream entity = entityInfo.getValue(); + final ResWrap container = atomDeserializer.toEntity(entity); + + container.getPayload().getProperty("Salary").setValue(ValueType.PRIMITIVE, 0); + container.getPayload().getProperty("Title").setValue(ValueType.PRIMITIVE, "[Sacked]"); + + final FSManager fsManager = FSManager.instance(); + fsManager.putInMemory(xml.writeEntity(Accept.ATOM, container), + fsManager.getAbsolutePath(Commons.getEntityBasePath("Person", entityId) + Constants.get( + ConstantKey.ENTITY), Accept.ATOM)); + + return utils.getValue().createResponse(null, null, null, utils.getKey(), Response.Status.NO_CONTENT); + } catch (Exception e) { + return xml.createFaultResponse(accept, e); + } + } + + @POST + @Path("/Person/{type:.*}/IncreaseSalaries") + public Response actionIncreaseSalaries( + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @PathParam("type") final String type, + final String body) { + + final String name = "Person"; + try { + final Accept acceptType = Accept.parse(accept); + if (acceptType == Accept.XML || acceptType == Accept.TEXT) { + throw new UnsupportedMediaTypeException("Unsupported media type"); + } + + final JsonNode tree = new ObjectMapper().readTree(body); + if (!tree.has("n")) { + throw new Exception("Missing parameter: n"); + } + final int n = tree.get("n").asInt(); + + final StringBuilder path = new StringBuilder(name). + append(File.separatorChar).append(type). + append(File.separatorChar); + + path.append(metadata.getEntitySet(name).isSingleton() + ? Constants.get(ConstantKey.ENTITY) + : Constants.get(ConstantKey.FEED)); + + final InputStream feed = FSManager.instance().readFile(path.toString(), acceptType); + + final ByteArrayOutputStream copy = new ByteArrayOutputStream(); + IOUtils.copy(feed, copy); + IOUtils.closeQuietly(feed); + + String newContent = new String(copy.toByteArray(), "UTF-8"); + final Pattern salary = Pattern.compile(acceptType == Accept.ATOM + ? "\\(-?\\d+)\\" + : "\"Salary\":(-?\\d+),"); + final Matcher salaryMatcher = salary.matcher(newContent); + while (salaryMatcher.find()) { + final Long newSalary = Long.valueOf(salaryMatcher.group(1)) + n; + newContent = newContent. + replaceAll("\"Salary\":" + salaryMatcher.group(1) + ",", + "\"Salary\":" + newSalary + ","). + replaceAll("\\" + salaryMatcher.group(1) + "", + "" + newSalary + ""); + } + + FSManager.instance().putInMemory(IOUtils.toInputStream(newContent, Constants.ENCODING), + FSManager.instance().getAbsolutePath(path.toString(), acceptType)); + + return xml.createResponse(null, null, null, acceptType, Response.Status.NO_CONTENT); + } catch (Exception e) { + return xml.createFaultResponse(accept, e); + } + } + + @POST + @Path("/Product({entityId})/ChangeProductDimensions") + public Response actionChangeProductDimensions( + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @PathParam("entityId") final String entityId, + @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, + final String argument) { + + final Map.Entry utils = getUtilities(accept, format); + + if (utils.getKey() == Accept.XML || utils.getKey() == Accept.TEXT) { + throw new UnsupportedMediaTypeException("Unsupported media type"); + } + + try { + final Map.Entry entityInfo = xml.readEntity("Product", entityId, Accept.ATOM); + + final InputStream entity = entityInfo.getValue(); + final ResWrap container = atomDeserializer.toEntity(entity); + + final Entity param = xml.readEntity(utils.getKey(), IOUtils.toInputStream(argument, Constants.ENCODING)); + + final Property property = param.getProperty("dimensions"); + container.getPayload().getProperty("Dimensions").setValue(property.getValueType(), property.getValue()); + + final FSManager fsManager = FSManager.instance(); + fsManager.putInMemory(xml.writeEntity(Accept.ATOM, container), + fsManager.getAbsolutePath(Commons.getEntityBasePath("Product", entityId) + Constants.get( + ConstantKey.ENTITY), Accept.ATOM)); + + return utils.getValue().createResponse(null, null, null, utils.getKey(), Response.Status.NO_CONTENT); + } catch (Exception e) { + return xml.createFaultResponse(accept, e); + } + } + + @POST + @Path("/ComputerDetail({entityId})/ResetComputerDetailsSpecifications") + public Response actionResetComputerDetailsSpecifications( + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @PathParam("entityId") final String entityId, + @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, + final String argument) { + + final Map.Entry utils = getUtilities(accept, format); + + if (utils.getKey() == Accept.XML || utils.getKey() == Accept.TEXT) { + throw new UnsupportedMediaTypeException("Unsupported media type"); + } + + try { + final Map.Entry entityInfo = xml.readEntity("ComputerDetail", entityId, Accept.ATOM); + + final InputStream entity = entityInfo.getValue(); + final ResWrap container = atomDeserializer.toEntity(entity); + + final Entity param = xml.readEntity(utils.getKey(), IOUtils.toInputStream(argument, Constants.ENCODING)); + + Property property = param.getProperty("specifications"); + container.getPayload().getProperty("SpecificationsBag").setValue(property.getValueType(), property.getValue()); + property = param.getProperty("purchaseTime"); + container.getPayload().getProperty("PurchaseDate").setValue(property.getValueType(), property.getValue()); + + final FSManager fsManager = FSManager.instance(); + fsManager.putInMemory(xml.writeEntity(Accept.ATOM, container), + fsManager.getAbsolutePath(Commons.getEntityBasePath("ComputerDetail", entityId) + Constants.get( + ConstantKey.ENTITY), Accept.ATOM)); + + return utils.getValue().createResponse(null, null, null, utils.getKey(), Response.Status.NO_CONTENT); + } catch (Exception e) { + return xml.createFaultResponse(accept, e); + } + } + @POST @Path("/Company/Microsoft.Test.OData.Services.ODataWCFService.IncreaseRevenue{paren:[\\(\\)]*}") public Response actionIncreaseRevenue( @@ -719,7 +1813,6 @@ public class Services extends AbstractServices { @Path("/Accounts({entityId})/MyGiftCard/Microsoft.Test.OData.Services.ODataWCFService.GetActualAmount({param:.*})") public Response functionGetActualAmount( @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @PathParam("entityId") final String entityId, @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) { try { @@ -771,7 +1864,7 @@ public class Services extends AbstractServices { final String filename = Base64.encodeBase64String(path.getBytes("UTF-8")); return utils.getValue().createResponse( - FSManager.instance(version).readFile(Constants.get(ConstantKey.REF) + FSManager.instance().readFile(Constants.get(ConstantKey.REF) + File.separatorChar + filename, utils.getKey()), null, utils.getKey()); @@ -796,42 +1889,191 @@ public class Services extends AbstractServices { return xml.createFaultResponse(accept, new BadRequestException()); } - return super.postNewEntity(uriInfo, accept, contentType, prefer, "People", entity); + return postNewEntity(uriInfo, accept, contentType, prefer, "People", entity); } - @Override + private Response patchEntityInternal(final UriInfo uriInfo, + final String accept, final String contentType, final String prefer, final String ifMatch, + final String entitySetName, final String entityId, final String changes) { + + try { + final Accept acceptType = Accept.parse(accept); + + if (acceptType == Accept.XML || acceptType == Accept.TEXT) { + throw new UnsupportedMediaTypeException("Unsupported media type"); + } + + final Map.Entry entityInfo = xml.readEntity(entitySetName, entityId, Accept.ATOM); + + final String etag = Commons.getETag(entityInfo.getKey()); + if (StringUtils.isNotBlank(ifMatch) && !ifMatch.equals(etag)) { + throw new ConcurrentModificationException("Concurrent modification"); + } + + final Accept contentTypeValue = Accept.parse(contentType); + + final Entity entryChanges; + + if (contentTypeValue == Accept.XML || contentTypeValue == Accept.TEXT) { + throw new UnsupportedMediaTypeException("Unsupported media type"); + } else if (contentTypeValue == Accept.ATOM) { + entryChanges = atomDeserializer.toEntity( + IOUtils.toInputStream(changes, Constants.ENCODING)).getPayload(); + } else { + final ResWrap jcont = jsonDeserializer.toEntity(IOUtils.toInputStream(changes, Constants.ENCODING)); + entryChanges = jcont.getPayload(); + } + + final ResWrap container = atomDeserializer.toEntity(entityInfo.getValue()); + + for (Property property : entryChanges.getProperties()) { + final Property _property = container.getPayload().getProperty(property.getName()); + if (_property == null) { + container.getPayload().getProperties().add(property); + } else { + _property.setValue(property.getValueType(), property.getValue()); + } + } + + for (Link link : entryChanges.getNavigationLinks()) { + container.getPayload().getNavigationLinks().add(link); + } + + final ByteArrayOutputStream content = new ByteArrayOutputStream(); + final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING); + atomSerializer.write(writer, container); + writer.flush(); + writer.close(); + + final InputStream res = xml.addOrReplaceEntity( + entityId, entitySetName, new ByteArrayInputStream(content.toByteArray()), container.getPayload()); + + final ResWrap cres = atomDeserializer.toEntity(res); + + normalizeAtomEntry(cres.getPayload(), entitySetName, entityId); + + final String path = Commons.getEntityBasePath(entitySetName, entityId); + FSManager.instance().putInMemory( + cres, path + File.separatorChar + Constants.get(ConstantKey.ENTITY)); + + final Response response; + if ("return-content".equalsIgnoreCase(prefer)) { + response = xml.createResponse( + uriInfo.getRequestUri().toASCIIString(), + xml.readEntity(entitySetName, entityId, acceptType).getValue(), + null, acceptType, Response.Status.OK); + } else { + res.close(); + response = xml.createResponse( + uriInfo.getRequestUri().toASCIIString(), + null, + null, + acceptType, Response.Status.NO_CONTENT); + } + + if (StringUtils.isNotBlank(prefer)) { + response.getHeaders().put("Preference-Applied", Collections. singletonList(prefer)); + } + + return response; + } catch (Exception e) { + return xml.createFaultResponse(accept, e); + } + } + + @PATCH + @Path("/{entitySetName}({entityId})") + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON }) + @Consumes({ MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON }) public Response patchEntity( - final UriInfo uriInfo, - final String accept, - final String contentType, - final String prefer, - final String ifMatch, - final String entitySetName, - final String entityId, + @Context final UriInfo uriInfo, + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType, + @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, + @HeaderParam("If-Match") @DefaultValue(StringUtils.EMPTY) final String ifMatch, + @PathParam("entitySetName") final String entitySetName, + @PathParam("entityId") final String entityId, final String changes) { final Response response = getEntityInternal(uriInfo.getRequestUri().toASCIIString(), accept, entitySetName, entityId, accept, StringUtils.EMPTY, StringUtils.EMPTY); - return response.getStatus() >= 400 - ? super.postNewEntity(uriInfo, accept, contentType, prefer, entitySetName, changes) - : super.patchEntity(uriInfo, accept, contentType, prefer, ifMatch, entitySetName, entityId, changes); + return response.getStatus() >= 400 ? + postNewEntity(uriInfo, accept, contentType, prefer, entitySetName, changes) : + patchEntityInternal(uriInfo, accept, contentType, prefer, ifMatch, entitySetName, entityId, changes); } - @Override + private Response replaceEntity(final UriInfo uriInfo, + final String accept, final String prefer, + final String entitySetName, final String entityId, final String entity) { + + try { + final Accept acceptType = Accept.parse(accept); + + if (acceptType == Accept.XML || acceptType == Accept.TEXT) { + throw new UnsupportedMediaTypeException("Unsupported media type"); + } + + final InputStream res = getUtilities(acceptType).addOrReplaceEntity(entityId, entitySetName, + IOUtils.toInputStream(entity, Constants.ENCODING), + xml.readEntity(acceptType, IOUtils.toInputStream(entity, Constants.ENCODING))); + + final ResWrap cres; + if (acceptType == Accept.ATOM) { + cres = atomDeserializer.toEntity(res); + } else { + cres = jsonDeserializer.toEntity(res); + } + + final String path = Commons.getEntityBasePath(entitySetName, entityId); + FSManager.instance().putInMemory( + cres, path + File.separatorChar + Constants.get(ConstantKey.ENTITY)); + + final Response response; + if ("return-content".equalsIgnoreCase(prefer)) { + response = xml.createResponse( + uriInfo.getRequestUri().toASCIIString(), + xml.readEntity(entitySetName, entityId, acceptType).getValue(), + null, + acceptType, + Response.Status.OK); + } else { + res.close(); + response = xml.createResponse( + uriInfo.getRequestUri().toASCIIString(), + null, + null, + acceptType, + Response.Status.NO_CONTENT); + } + + if (StringUtils.isNotBlank(prefer)) { + response.getHeaders().put("Preference-Applied", Collections. singletonList(prefer)); + } + + return response; + } catch (Exception e) { + return xml.createFaultResponse(accept, e); + } + } + + @PUT + @Path("/{entitySetName}({entityId})") + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON }) + @Consumes({ MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON }) public Response replaceEntity( - final UriInfo uriInfo, - final String accept, - final String contentType, - final String prefer, - final String entitySetName, - final String entityId, + @Context final UriInfo uriInfo, + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType, + @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, + @PathParam("entitySetName") final String entitySetName, + @PathParam("entityId") final String entityId, final String entity) { try { getEntityInternal(uriInfo.getRequestUri().toASCIIString(), accept, entitySetName, entityId, accept, StringUtils.EMPTY, StringUtils.EMPTY); - return super.replaceEntity(uriInfo, accept, contentType, prefer, entitySetName, entityId, entity); + return replaceEntity(uriInfo, accept, prefer, entitySetName, entityId, entity); } catch (NotFoundException e) { return postNewEntity(uriInfo, accept, contentType, prefer, entitySetName, entityId); } @@ -844,6 +2086,532 @@ public class Services extends AbstractServices { append(containedEntitySetName); } + @DELETE + @Path("/{entitySetName}({entityId})") + public Response removeEntity( + @PathParam("entitySetName") final String entitySetName, + @PathParam("entityId") final String entityId) { + + try { + final String basePath = entitySetName + File.separatorChar + Commons.getEntityKey(entityId); + + FSManager.instance().deleteEntity(basePath); + + return xml.createResponse(null, null, null, null, Response.Status.NO_CONTENT); + } catch (Exception e) { + return xml.createFaultResponse(Accept.XML.toString(), e); + } + } + + private Response replaceProperty( + final String location, + final String accept, + final String contentType, + final String prefer, + final String entitySetName, + final String entityId, + final String path, + final String format, + final String changes, + final boolean justValue) { + + // if the given path is not about any link then search for property + LOG.info("Retrieve property {}", path); + + try { + final FSManager fsManager = FSManager.instance(); + final String basePath = Commons.getEntityBasePath(entitySetName, entityId); + + final ResWrap container = xml.readContainerEntity(Accept.ATOM, + fsManager.readFile(basePath + Constants.get(ConstantKey.ENTITY), Accept.ATOM)); + + final Entity entry = container.getPayload(); + + Property toBeReplaced = null; + for (String element : path.split("/")) { + if (toBeReplaced == null) { + toBeReplaced = entry.getProperty(element.trim()); + } else { + List value = toBeReplaced.asComplex().getValue(); + for (Property field : value) { + if (field.getName().equalsIgnoreCase(element)) { + toBeReplaced = field; + } + } + } + } + + if (toBeReplaced == null) { + throw new NotFoundException(); + } + + if (justValue) { + // just for primitive values + toBeReplaced.setValue(ValueType.PRIMITIVE, changes); + } else { + final Property pchanges = xml.readProperty( + Accept.parse(contentType), + IOUtils.toInputStream(changes, Constants.ENCODING)); + + toBeReplaced.setValue(pchanges.getValueType(), pchanges.getValue()); + } + + fsManager.putInMemory(xml.writeEntity(Accept.ATOM, container), + fsManager.getAbsolutePath(basePath + Constants.get(ConstantKey.ENTITY), Accept.ATOM)); + + final Response response; + if ("return-content".equalsIgnoreCase(prefer)) { + response = getEntityInternal(location, accept, entitySetName, entityId, format, null, null); + } else { + Accept acceptType = null; + if (StringUtils.isNotBlank(format)) { + acceptType = Accept.valueOf(format.toUpperCase()); + } else if (StringUtils.isNotBlank(accept)) { + acceptType = Accept.parse(accept, null); + } + + response = xml.createResponse(null, null, null, acceptType, Response.Status.NO_CONTENT); + } + + if (StringUtils.isNotBlank(prefer)) { + response.getHeaders().put("Preference-Applied", Collections. singletonList(prefer)); + } + + return response; + } catch (Exception e) { + return xml.createFaultResponse(accept, e); + } + } + + private Response deletePropertyValue( + final String accept, + final String prefer, + final String entitySetName, + final String entityId, + final String path, + final String format) { + try { + Accept acceptType = null; + if (StringUtils.isNotBlank(format)) { + acceptType = Accept.valueOf(format.toUpperCase()); + } else if (StringUtils.isNotBlank(accept)) { + acceptType = Accept.parse(accept, null); + } + + // if the given path is not about any link then search for property + LOG.info("Retrieve property {}", path); + + final AbstractUtilities utils = getUtilities(acceptType); + + final InputStream changed = utils.deleteProperty( + entitySetName, + entityId, + Arrays.asList(path.split("/")), + acceptType); + + final Response response; + if ("return-content".equalsIgnoreCase(prefer)) { + response = xml.createResponse(null, changed, null, acceptType, Response.Status.OK); + } else { + changed.close(); + response = xml.createResponse(null, null, null, acceptType, Response.Status.NO_CONTENT); + } + + if (StringUtils.isNotBlank(prefer)) { + response.getHeaders().put("Preference-Applied", Collections. singletonList(prefer)); + } + + return response; + + } catch (Exception e) { + return xml.createFaultResponse(accept, e); + } + } + + /** + * Replace property value. + * + * @param accept + * @param entitySetName + * @param entityId + * @param path + * @param format + * @param changes + * @return response + */ + @PUT + @Path("/{entitySetName}({entityId})/{path:.*}/$value") + public Response replacePropertyValue( + @Context final UriInfo uriInfo, + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType, + @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, + @PathParam("entitySetName") final String entitySetName, + @PathParam("entityId") final String entityId, + @PathParam("path") final String path, + @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, + final String changes) { + + return replaceProperty(uriInfo.getRequestUri().toASCIIString(), + accept, contentType, prefer, entitySetName, entityId, path, format, changes, true); + } + + /** + * Replace property. + * + * @param accept + * @param entitySetName + * @param entityId + * @param path + * @param format + * @param changes + * @return response + */ + @PATCH + @Path("/{entitySetName}({entityId})/{path:.*}") + public Response patchProperty( + @Context final UriInfo uriInfo, + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType, + @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, + @PathParam("entitySetName") final String entitySetName, + @PathParam("entityId") final String entityId, + @PathParam("path") final String path, + @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, + final String changes) { + + return replaceProperty(uriInfo.getRequestUri().toASCIIString(), + accept, contentType, prefer, entitySetName, entityId, path, format, changes, false); + } + + @PUT + @Produces({ MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON }) + @Consumes({ MediaType.WILDCARD, MediaType.APPLICATION_OCTET_STREAM }) + @Path("/{entitySetName}({entityId})/$value") + public Response replaceMediaEntity( + @Context final UriInfo uriInfo, + @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, + @PathParam("entitySetName") final String entitySetName, + @PathParam("entityId") final String entityId, + final String value) { + try { + + final AbstractUtilities utils = getUtilities(null); + + final InputStream res = utils.putMediaInMemory( + entitySetName, entityId, IOUtils.toInputStream(value, Constants.ENCODING)); + + final String location = uriInfo.getRequestUri().toASCIIString().replace("/$value", ""); + + final Response response; + if ("return-content".equalsIgnoreCase(prefer)) { + response = xml.createResponse(location, res, null, null, Response.Status.OK); + } else { + res.close(); + response = xml.createResponse(location, null, null, null, Response.Status.NO_CONTENT); + } + + if (StringUtils.isNotBlank(prefer)) { + response.getHeaders().put("Preference-Applied", Collections. singletonList(prefer)); + } + + return response; + + } catch (Exception e) { + LOG.error("Error retrieving entity", e); + return xml.createFaultResponse(Accept.JSON.toString(), e); + } + } + + /** + * Replace property. + * + * @param accept + * @param entitySetName + * @param entityId + * @param path + * @param format + * @param changes + * @return response + */ + @PUT + @Path("/{entitySetName}({entityId})/{path:.*}") + public Response replaceProperty( + @Context final UriInfo uriInfo, + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType, + @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, + @PathParam("entitySetName") final String entitySetName, + @PathParam("entityId") final String entityId, + @PathParam("path") final String path, + @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, + final String changes) { + + if (xml.isMediaContent(entitySetName + "/" + path)) { + return replaceMediaProperty(prefer, entitySetName, entityId, path, changes); + } else { + return replaceProperty(uriInfo.getRequestUri().toASCIIString(), + accept, contentType, prefer, entitySetName, entityId, path, format, changes, false); + } + } + + private Response replaceMediaProperty( + final String prefer, + final String entitySetName, + final String entityId, + final String path, + final String value) { + + try { + final AbstractUtilities utils = getUtilities(null); + + InputStream res = utils.putMediaInMemory( + entitySetName, entityId, path, IOUtils.toInputStream(value, Constants.ENCODING)); + + final Response response; + if ("return-content".equalsIgnoreCase(prefer)) { + response = xml.createResponse(null, res, null, null, Response.Status.OK); + } else { + res.close(); + response = xml.createResponse(null, null, null, null, Response.Status.NO_CONTENT); + } + + if (StringUtils.isNotBlank(prefer)) { + response.getHeaders().put("Preference-Applied", Collections. singletonList(prefer)); + } + + return response; + } catch (Exception e) { + LOG.error("Error retrieving entity", e); + return xml.createFaultResponse(Accept.JSON.toString(), e); + } + } + + /** + * Nullify property value. + * + * @param accept + * @param entitySetName + * @param entityId + * @param path + * @param format + * @return response + */ + @DELETE + @Path("/{entitySetName}({entityId})/{path:.*}/$value") + public Response deleteProperty( + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer, + @PathParam("entitySetName") final String entitySetName, + @PathParam("entityId") final String entityId, + @PathParam("path") final String path, + @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) { + return deletePropertyValue(accept, prefer, entitySetName, entityId, path, format); + } + + /** + * Retrieve property sample. + * + * @param accept Accept header. + * @param entitySetName Entity set name. + * @param entityId entity id. + * @param path path. + * @param format format query option. + * @return property. + */ + @GET + @Path("/{entitySetName}({entityId})/{path:.*}/$value") + public Response getPathValue( + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @PathParam("entitySetName") final String entitySetName, + @PathParam("entityId") final String entityId, + @PathParam("path") final String path, + @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) { + + try { + Accept acceptType = null; + if (StringUtils.isNotBlank(format)) { + acceptType = Accept.valueOf(format.toUpperCase()); + } else if (StringUtils.isNotBlank(accept)) { + acceptType = Accept.parse(accept, null); + } + + return navigateProperty(acceptType, entitySetName, entityId, path, true); + } catch (Exception e) { + return xml.createFaultResponse(accept, e); + } + } + + /** + * Retrieve property sample. + * + * @param accept Accept header. + * @param entitySetName Entity set name. + * @param entityId entity id. + * @param path path. + * @param format format query option. + * @return property. + */ + @GET + @Path("/{entitySetName}({entityId})/{path:.*}") + public Response getPath( + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @PathParam("entitySetName") final String entitySetName, + @PathParam("entityId") final String entityId, + @PathParam("path") final String path, + @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format) { + + // default utilities + final AbstractUtilities utils = xml; + + try { + if (utils.isMediaContent(entitySetName + "/" + path)) { + return navigateStreamedEntity(entitySetName, entityId, path); + } else { + Accept acceptType = null; + if (StringUtils.isNotBlank(format)) { + acceptType = Accept.valueOf(format.toUpperCase()); + } else if (StringUtils.isNotBlank(accept)) { + acceptType = Accept.parse(accept, null); + } + + try { + final LinkInfo linkInfo = xml.readLinks(entitySetName, entityId, path, Accept.XML); + final Map.Entry> links = xml.extractLinkURIs(linkInfo.getLinks()); + final InputStream stream = xml.readEntities(links.getValue(), path, links.getKey(), linkInfo.isFeed()); + + final ByteArrayOutputStream content = new ByteArrayOutputStream(); + final OutputStreamWriter writer = new OutputStreamWriter(content, Constants.ENCODING); + + final ResWrap container = linkInfo.isFeed() ? atomDeserializer.toEntitySet(stream) : atomDeserializer. + toEntity(stream); + if (acceptType == Accept.ATOM) { + atomSerializer.write(writer, container); + } else { + jsonSerializer.write(writer, container); + } + writer.flush(); + writer.close(); + + final String basePath = Commons.getEntityBasePath(entitySetName, entityId); + + return xml.createResponse( + null, + new ByteArrayInputStream(content.toByteArray()), + Commons.getETag(basePath), + acceptType); + + } catch (NotFoundException e) { + // if the given path is not about any link then search for property + return navigateProperty(acceptType, entitySetName, entityId, path, false); + } + } + } catch (Exception e) { + return utils.createFaultResponse(accept, e); + } + } + + private Response navigateStreamedEntity( + final String entitySetName, + final String entityId, + final String path) throws Exception { + + final AbstractUtilities utils = getUtilities(null); + final Map.Entry entityInfo = utils.readMediaEntity(entitySetName, entityId, path); + return utils.createResponse(null, entityInfo.getValue(), Commons.getETag(entityInfo.getKey()), null); + } + + private Response navigateProperty( + final Accept acceptType, + final String entitySetName, + final String entityId, + final String path, + final boolean searchForValue) throws Exception { + + if ((searchForValue && acceptType != null && acceptType != Accept.TEXT) || acceptType == Accept.ATOM) { + throw new UnsupportedMediaTypeException("Unsupported media type " + acceptType); + } + + final AbstractUtilities utils = getUtilities(acceptType); + + final Map.Entry entityInfo = utils.readEntity(entitySetName, entityId, Accept.ATOM); + + final InputStream entity = entityInfo.getValue(); + + final ResWrap entryContainer = atomDeserializer.toEntity(entity); + + final String[] pathElems = StringUtils.split(path, "/"); + Property property = entryContainer.getPayload().getProperty(pathElems[0]); + if (pathElems.length > 1 && property.isComplex()) { + for (Property sub : property.asComplex().getValue()) { + if (pathElems[1].equals(sub.getName())) { + property = sub; + if (pathElems.length > 2 && property.isComplex()) { + for (Property subsub : property.asComplex().getValue()) { + if (pathElems[2].equals(subsub.getName())) { + property = subsub; + } + } + } + } + } + } + + final ResWrap container = new ResWrap( + URI.create(Constants.get(ConstantKey.ODATA_METADATA_PREFIX) + entitySetName + "(" + entityId + ")/" + path), + entryContainer.getMetadataETag(), + property); + + return xml.createResponse(null, + searchForValue ? IOUtils.toInputStream( + container.getPayload().isNull() ? StringUtils.EMPTY : stringValue(container.getPayload()), + Constants.ENCODING) : utils.writeProperty(acceptType, container), + Commons.getETag(Commons.getEntityBasePath(entitySetName, entityId)), + acceptType); + } + + private String stringValue(final Property property) { + EdmPrimitiveTypeKind kind = EdmPrimitiveTypeKind.valueOfFQN(property.getType()); + try { + return EdmPrimitiveTypeFactory.getInstance(kind) + .valueToString(property.asPrimitive(), null, null, + org.apache.olingo.commons.api.Constants.DEFAULT_PRECISION, + org.apache.olingo.commons.api.Constants.DEFAULT_SCALE, null); + } catch (final EdmPrimitiveTypeException e) { + return property.asPrimitive().toString(); + } + } + + /** + * Count sample. + * + * @param accept Accept header. + * @param entitySetName entity set name. + * @return count. + */ + @GET + @Path("/{entitySetName}/$count") + public Response count( + @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, + @PathParam("entitySetName") final String entitySetName) { + try { + final Accept acceptType = Accept.parse(accept, Accept.TEXT); + + if (acceptType != Accept.TEXT) { + throw new UnsupportedMediaTypeException("Unsupported type " + accept); + } + + int count = xml.countAllElements(entitySetName); + + final Response.ResponseBuilder builder = Response.ok(); + builder.entity(count); + + return builder.build(); + } catch (Exception e) { + return xml.createFaultResponse(accept, e); + } + } + @GET @Path("/Accounts({entityId})/{containedEntitySetName}({containedEntityId})") public Response getContainedEntity( @@ -868,7 +2636,7 @@ public class Services extends AbstractServices { if (StringUtils.isNotBlank(containedEntityId)) { containedPath.append('(').append(containedEntityId).append(')'); } - final InputStream entry = FSManager.instance(version).readFile(containedPath.toString(), Accept.ATOM); + final InputStream entry = FSManager.instance().readFile(containedPath.toString(), Accept.ATOM); final ResWrap container = atomDeserializer.toEntity(entry); @@ -926,13 +2694,13 @@ public class Services extends AbstractServices { // 2. Store the new entity final String atomEntryRelativePath = containedPath(entityId, containedEntitySetName). append('(').append(entityKey).append(')').toString(); - FSManager.instance(version).putInMemory( + FSManager.instance().putInMemory( utils.writeEntity(Accept.ATOM, entryContainer), - FSManager.instance(version).getAbsolutePath(atomEntryRelativePath, Accept.ATOM)); + FSManager.instance().getAbsolutePath(atomEntryRelativePath, Accept.ATOM)); // 3. Update the contained entity set final String atomFeedRelativePath = containedPath(entityId, containedEntitySetName).toString(); - final InputStream feedIS = FSManager.instance(version).readFile(atomFeedRelativePath, Accept.ATOM); + final InputStream feedIS = FSManager.instance().readFile(atomFeedRelativePath, Accept.ATOM); final ResWrap feedContainer = atomDeserializer.toEntitySet(feedIS); feedContainer.getPayload().getEntities().add(entry); @@ -942,9 +2710,9 @@ public class Services extends AbstractServices { writer.flush(); writer.close(); - FSManager.instance(version).putInMemory( + FSManager.instance().putInMemory( new ByteArrayInputStream(content.toByteArray()), - FSManager.instance(version).getAbsolutePath(atomFeedRelativePath, Accept.ATOM)); + FSManager.instance().getAbsolutePath(atomFeedRelativePath, Accept.ATOM)); // Finally, return return utils.createResponse( @@ -1018,7 +2786,7 @@ public class Services extends AbstractServices { original.getProperties().add(property); } - FSManager.instance(version).putInMemory(new ResWrap((URI) null, null, original), + FSManager.instance().putInMemory(new ResWrap((URI) null, null, original), xml.getLinksBasePath(entitySetName, entityId) + containedEntitySetName + "(" + containedEntityId + ")"); return xml.createResponse(null, null, acceptType, Response.Status.NO_CONTENT); @@ -1036,7 +2804,7 @@ public class Services extends AbstractServices { try { // 1. Fetch the contained entity to be removed - final InputStream entry = FSManager.instance(version). + final InputStream entry = FSManager.instance(). readFile(containedPath(entityId, containedEntitySetName). append('(').append(containedEntityId).append(')').toString(), Accept.ATOM); final ResWrap container = atomDeserializer.toEntity(entry); @@ -1044,11 +2812,11 @@ public class Services extends AbstractServices { // 2. Remove the contained entity final String atomEntryRelativePath = containedPath(entityId, containedEntitySetName). append('(').append(containedEntityId).append(')').toString(); - FSManager.instance(version).deleteFile(atomEntryRelativePath); + FSManager.instance().deleteFile(atomEntryRelativePath); // 3. Update the contained entity set final String atomFeedRelativePath = containedPath(entityId, containedEntitySetName).toString(); - final InputStream feedIS = FSManager.instance(version).readFile(atomFeedRelativePath, Accept.ATOM); + final InputStream feedIS = FSManager.instance().readFile(atomFeedRelativePath, Accept.ATOM); final ResWrap feedContainer = atomDeserializer.toEntitySet(feedIS); feedContainer.getPayload().getEntities().remove(container.getPayload()); @@ -1058,9 +2826,9 @@ public class Services extends AbstractServices { writer.flush(); writer.close(); - FSManager.instance(version).putInMemory( + FSManager.instance().putInMemory( new ByteArrayInputStream(content.toByteArray()), - FSManager.instance(version).getAbsolutePath(atomFeedRelativePath, Accept.ATOM)); + FSManager.instance().getAbsolutePath(atomFeedRelativePath, Accept.ATOM)); return xml.createResponse(null, null, null, null, Response.Status.NO_CONTENT); } catch (Exception e) { @@ -1099,7 +2867,7 @@ public class Services extends AbstractServices { derivedType = parts[1]; } - final InputStream feed = FSManager.instance(version). + final InputStream feed = FSManager.instance(). readFile(containedPath(entityId, tempContainedESName).toString(), Accept.ATOM); final ResWrap container = atomDeserializer.toEntitySet(feed); @@ -1322,7 +3090,7 @@ public class Services extends AbstractServices { try { final String basePath = "Products" + File.separatorChar + "feed"; - final InputStream feed = FSManager.instance(version).readFile(basePath, Accept.JSON_FULLMETA); + final InputStream feed = FSManager.instance().readFile(basePath, Accept.JSON_FULLMETA); return xml.createResponse(null, feed, Commons.getETag(basePath), Accept.JSON_FULLMETA); } catch (Exception e) { return xml.createFaultResponse(Accept.JSON_FULLMETA.toString(), e); @@ -1402,34 +3170,19 @@ public class Services extends AbstractServices { @POST @Path("/Products({productId})/Categories/$ref") - public Response createLinked( - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, - final String entity) { - + public Response createLinked() { return xml.createResponse(null, null, null, Status.NO_CONTENT); } @POST @Path("/Customers(1)/Orders/$ref") - public Response linkOrderViaRef( - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, - final String entity) { - + public Response linkOrderViaRef() { return xml.createResponse(null, null, null, Status.NO_CONTENT); } @DELETE @Path("/Products({productId})/Categories({categoryId})/$ref") - public Response deleteLinked( - @HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) final String accept, - @HeaderParam("Content-Type") @DefaultValue(StringUtils.EMPTY) final String contentType, - @QueryParam("$format") @DefaultValue(StringUtils.EMPTY) final String format, - final String entity) { - + public Response deleteLinked() { return xml.createResponse(null, null, null, Status.NO_CONTENT); } @@ -1442,7 +3195,33 @@ public class Services extends AbstractServices { @QueryParam("$expand") @DefaultValue(StringUtils.EMPTY) final String expand, @QueryParam("$select") @DefaultValue(StringUtils.EMPTY) final String select) { - return super.getEntityInternal( + return getEntityInternal( uriInfo.getRequestUri().toASCIIString(), accept, "VipCustomer", "1", format, expand, select); } + + protected Map.Entry getUtilities(final String accept, final String format) { + Accept acceptType; + if (StringUtils.isNotBlank(format)) { + try { + acceptType = Accept.valueOf(format.toUpperCase()); + } catch (Exception e) { + acceptType = Accept.parse(format); + } + } else { + acceptType = Accept.parse(accept); + } + + return new AbstractMap.SimpleEntry(acceptType, getUtilities(acceptType)); + } + + protected AbstractUtilities getUtilities(final Accept accept) { + final AbstractUtilities utils; + if (accept == Accept.XML || accept == Accept.TEXT || accept == Accept.ATOM) { + utils = xml; + } else { + utils = json; + } + + return utils; + } } diff --git a/fit/src/main/java/org/apache/olingo/fit/Vocabularies.java b/fit/src/main/java/org/apache/olingo/fit/Vocabularies.java index 0390eae33..c13bf3593 100644 --- a/fit/src/main/java/org/apache/olingo/fit/Vocabularies.java +++ b/fit/src/main/java/org/apache/olingo/fit/Vocabularies.java @@ -27,7 +27,6 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion; import org.apache.olingo.fit.metadata.Metadata; import org.apache.olingo.fit.utils.Accept; import org.apache.olingo.fit.utils.ConstantKey; @@ -43,8 +42,8 @@ public class Vocabularies { private final XMLUtilities xml; public Vocabularies() throws IOException { - Metadata metadata = new Metadata(FSManager.instance(ODataServiceVersion.V40).readRes( - "vocabularies-" + Constants.get(ConstantKey.METADATA), Accept.XML)); + Metadata metadata = new Metadata(FSManager.instance() + .readRes("vocabularies-" + Constants.get(ConstantKey.METADATA), Accept.XML)); xml = new XMLUtilities(metadata); } @@ -55,8 +54,7 @@ public class Vocabularies { try { return xml.createResponse( null, - FSManager.instance(ODataServiceVersion.V40).readRes( - "vocabularies-" + Constants.get(ConstantKey.METADATA), Accept.XML), + FSManager.instance().readRes("vocabularies-" + Constants.get(ConstantKey.METADATA), Accept.XML), null, Accept.XML); } catch (Exception e) { @@ -71,7 +69,7 @@ public class Vocabularies { try { return xml.createResponse( null, - FSManager.instance(ODataServiceVersion.V40).readFile(vocabulary, null), + FSManager.instance().readFile(vocabulary, null), null, Accept.XML); } catch (Exception e) { diff --git a/fit/src/main/java/org/apache/olingo/fit/metadata/EntitySet.java b/fit/src/main/java/org/apache/olingo/fit/metadata/EntitySet.java index 15285d252..c165bb7f4 100644 --- a/fit/src/main/java/org/apache/olingo/fit/metadata/EntitySet.java +++ b/fit/src/main/java/org/apache/olingo/fit/metadata/EntitySet.java @@ -24,18 +24,10 @@ import java.util.Map; public class EntitySet extends AbstractMetadataElement { private final String name; - private String type; - private final boolean singleton; - - // -------------------------- - // V4 only - // -------------------------- private final Map binding; - // -------------------------- - public EntitySet(final String name, final boolean singleton) { this.name = name; this.singleton = singleton; diff --git a/fit/src/main/java/org/apache/olingo/fit/rest/OAuth2RequestFilter.java b/fit/src/main/java/org/apache/olingo/fit/rest/OAuth2RequestFilter.java index 17476dd6c..a7ab945c0 100644 --- a/fit/src/main/java/org/apache/olingo/fit/rest/OAuth2RequestFilter.java +++ b/fit/src/main/java/org/apache/olingo/fit/rest/OAuth2RequestFilter.java @@ -19,14 +19,13 @@ package org.apache.olingo.fit.rest; import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.ext.Provider; import org.apache.commons.lang3.StringUtils; import org.apache.cxf.rs.security.oauth2.filters.OAuthRequestFilter; @Provider -public class OAuth2RequestFilter extends OAuthRequestFilter implements ContainerRequestFilter { +public class OAuth2RequestFilter extends OAuthRequestFilter { @Override public void filter(final ContainerRequestContext context) { diff --git a/fit/src/main/java/org/apache/olingo/fit/serializer/FITAtomDeserializer.java b/fit/src/main/java/org/apache/olingo/fit/serializer/FITAtomDeserializer.java index d02475d47..357dc5aad 100644 --- a/fit/src/main/java/org/apache/olingo/fit/serializer/FITAtomDeserializer.java +++ b/fit/src/main/java/org/apache/olingo/fit/serializer/FITAtomDeserializer.java @@ -21,7 +21,6 @@ package org.apache.olingo.fit.serializer; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; import javax.xml.stream.XMLEventReader; @@ -32,19 +31,15 @@ import org.apache.olingo.commons.api.Constants; public class FITAtomDeserializer extends AtomDeserializer { - private static final Charset ENCODING = Charset.forName(Constants.UTF8); - public FITAtomDeserializer() { super(); } @Override protected XMLEventReader getReader(final InputStream input) throws XMLStreamException { - final CharsetDecoder decoder = ENCODING.newDecoder(); - decoder.onMalformedInput(CodingErrorAction.IGNORE); - decoder.onUnmappableCharacter(CodingErrorAction.IGNORE); - - return FACTORY.createXMLEventReader(new InputStreamReader(input, decoder)); + return FACTORY.createXMLEventReader(new InputStreamReader(input, + Charset.forName(Constants.UTF8).newDecoder() + .onMalformedInput(CodingErrorAction.IGNORE) + .onUnmappableCharacter(CodingErrorAction.IGNORE))); } - } diff --git a/fit/src/main/java/org/apache/olingo/fit/utils/AbstractUtilities.java b/fit/src/main/java/org/apache/olingo/fit/utils/AbstractUtilities.java index ee87eb0b2..a14cb8b8f 100644 --- a/fit/src/main/java/org/apache/olingo/fit/utils/AbstractUtilities.java +++ b/fit/src/main/java/org/apache/olingo/fit/utils/AbstractUtilities.java @@ -34,7 +34,6 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; -import java.util.regex.Pattern; import javax.ws.rs.NotFoundException; import javax.ws.rs.core.Response; @@ -70,38 +69,19 @@ public abstract class AbstractUtilities { */ protected static final Logger LOG = LoggerFactory.getLogger(AbstractUtilities.class); - protected static final Pattern ENTITY_URI_PATTERN = Pattern.compile(".*\\/.*\\(.*\\)"); - - /** - * Batch/Changeset content type. - */ - public static final String MULTIPART_CONTENT_TYPE = "multipart/mixed"; - - /** - * Batch item content type. - */ - public static final String ITEM_CONTENT_TYPE = "application/http"; - - /** - * Boundary key. - */ - public static final String BOUNDARY = "boundary"; - protected final Metadata metadata; protected final FSManager fsManager; protected final ODataDeserializer atomDeserializer; - protected final ODataDeserializer jsonDeserializer; protected final ODataSerializer atomSerializer; - protected final ODataSerializer jsonSerializer; public AbstractUtilities(final Metadata metadata) throws IOException { this.metadata = metadata; - fsManager = FSManager.instance(ODataServiceVersion.V40); + fsManager = FSManager.instance(); atomDeserializer = new FITAtomDeserializer(); jsonDeserializer = new JsonDeserializer(true); atomSerializer = new AtomSerializer(true); diff --git a/fit/src/main/java/org/apache/olingo/fit/utils/Accept.java b/fit/src/main/java/org/apache/olingo/fit/utils/Accept.java index 5f9a7247b..9acda3128 100644 --- a/fit/src/main/java/org/apache/olingo/fit/utils/Accept.java +++ b/fit/src/main/java/org/apache/olingo/fit/utils/Accept.java @@ -20,33 +20,31 @@ package org.apache.olingo.fit.utils; import java.util.regex.Pattern; -import org.apache.commons.lang3.StringUtils; -import org.apache.http.entity.ContentType; +import org.apache.olingo.commons.api.format.ContentType; import org.apache.olingo.fit.UnsupportedMediaTypeException; public enum Accept { - TEXT(ContentType.TEXT_PLAIN.getMimeType(), ".txt"), - XML(ContentType.APPLICATION_XML.getMimeType(), ".xml"), - ATOM(ContentType.APPLICATION_ATOM_XML.getMimeType(), ".xml"), - JSON(ContentType.APPLICATION_JSON.getMimeType() + ";odata.metadata=minimal", ".full.json"), - JSON_NOMETA(ContentType.APPLICATION_JSON.getMimeType() + ";odata.metadata=none", ".full.json"), - JSON_FULLMETA(ContentType.APPLICATION_JSON.getMimeType() + ";odata.metadata=full", ".full.json"); - - private final String contentTypeV4; - - private final String fileExtension; + TEXT(ContentType.TEXT_PLAIN, ".txt"), + XML(ContentType.APPLICATION_XML, ".xml"), + ATOM(ContentType.APPLICATION_ATOM_XML, ".xml"), + JSON(ContentType.JSON, ".full.json"), + JSON_NOMETA(ContentType.JSON_NO_METADATA, ".full.json"), + JSON_FULLMETA(ContentType.JSON_FULL_METADATA, ".full.json"); private static Pattern allTypesPattern = Pattern.compile("(.*,)?\\*/\\*([,;].*)?"); - Accept(final String contentTypeV4, final String fileExtension) { - this.contentTypeV4 = contentTypeV4; + private final ContentType contentType; + private final String fileExtension; + + Accept(final ContentType contentType, final String fileExtension) { + this.contentType = contentType; this.fileExtension = fileExtension; } @Override public String toString() { - return contentTypeV4; + return contentType.toContentTypeString(); } public String getExtension() { @@ -58,15 +56,14 @@ public enum Accept { } public static Accept parse(final String contentType, final Accept def) { - if (StringUtils.isBlank(contentType) || allTypesPattern.matcher(contentType).matches()) { + if (contentType == null || contentType.isEmpty() || allTypesPattern.matcher(contentType).matches()) { return def; } else if (contentType.startsWith(JSON_NOMETA.toString())) { return JSON_NOMETA; } else if (contentType.startsWith(JSON_FULLMETA.toString())) { return JSON_FULLMETA; } else if (contentType.startsWith(JSON.toString()) - || contentType.startsWith(ContentType.APPLICATION_JSON.getMimeType())) { - + || contentType.startsWith(ContentType.APPLICATION_JSON.toContentTypeString())) { return JSON; } else if (contentType.startsWith(XML.toString())) { return XML; diff --git a/fit/src/main/java/org/apache/olingo/fit/utils/Commons.java b/fit/src/main/java/org/apache/olingo/fit/utils/Commons.java index 32644d9a1..5ee4d25ed 100644 --- a/fit/src/main/java/org/apache/olingo/fit/utils/Commons.java +++ b/fit/src/main/java/org/apache/olingo/fit/utils/Commons.java @@ -27,7 +27,6 @@ import java.net.URI; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collection; -import java.util.EnumMap; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -40,7 +39,6 @@ import org.apache.commons.lang3.tuple.Pair; import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion; import org.apache.olingo.fit.metadata.Metadata; -import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -59,9 +57,6 @@ public abstract class Commons { */ protected static final Logger LOG = LoggerFactory.getLogger(Commons.class); - private static final EnumMap METADATA = - new EnumMap(ODataServiceVersion.class); - protected static final Pattern MULTIKEY_PATTERN = Pattern.compile("(.*=.*,?)+"); protected static final Map SEQUENCE = new HashMap(); @@ -99,14 +94,11 @@ public abstract class Commons { new ImmutablePair("ID", EdmPrimitiveTypeKind.Guid)); } - public static Metadata getMetadata(final ODataServiceVersion version) { - if (!METADATA.containsKey(version)) { - final InputStream is = Commons.class.getResourceAsStream("/" + version.name() + "/metadata.xml"); + private static final Metadata METADATA = + new Metadata(Commons.class.getResourceAsStream("/" + ODataServiceVersion.V40.name() + "/metadata.xml")); - METADATA.put(version, new Metadata(is)); - } - - return METADATA.get(version); + public static Metadata getMetadata() { + return METADATA; } public static Map> getMediaContent() { @@ -115,13 +107,13 @@ public abstract class Commons { public static String getEntityURI(final String entitySetName, final String entityKey) { // expected singleton in case of null key - return entitySetName + (StringUtils.isNotBlank(entityKey) ? "(" + entityKey + ")" : ""); + return entitySetName + (entityKey == null || entityKey.isEmpty() ? "" : "(" + entityKey + ")"); } public static String getEntityBasePath(final String entitySetName, final String entityKey) { // expected singleton in case of null key return entitySetName + File.separatorChar - + (StringUtils.isNotBlank(entityKey) ? getEntityKey(entityKey) + File.separatorChar : ""); + + (entityKey == null || entityKey.isEmpty() ? "" : getEntityKey(entityKey) + File.separatorChar); } public static String getLinksURI(final String entitySetName, final String entityId, final String linkName) @@ -138,7 +130,7 @@ public abstract class Commons { public static String getLinksPath(final String basePath, final String linkName, final Accept accept) throws IOException { try { - return FSManager.instance(ODataServiceVersion.V40) + return FSManager.instance() .getAbsolutePath(basePath + Constants.get(ConstantKey.LINKS_FILE_PATH) + File.separatorChar + linkName, accept); } catch (Exception e) { @@ -281,7 +273,7 @@ public abstract class Commons { public static String getETag(final String basePath) throws Exception { try { - final InputStream is = FSManager.instance(ODataServiceVersion.V40).readFile(basePath + "etag", Accept.TEXT); + final InputStream is = FSManager.instance().readFile(basePath + "etag", Accept.TEXT); if (is.available() <= 0) { return null; } else { diff --git a/fit/src/main/java/org/apache/olingo/fit/utils/ConstantKey.java b/fit/src/main/java/org/apache/olingo/fit/utils/ConstantKey.java index 731565208..a8425df81 100644 --- a/fit/src/main/java/org/apache/olingo/fit/utils/ConstantKey.java +++ b/fit/src/main/java/org/apache/olingo/fit/utils/ConstantKey.java @@ -25,20 +25,13 @@ public enum ConstantKey { ODATA_COUNT_NAME, ODATA_METADATA_PREFIX, ODATA_METADATA_ENTITY_SUFFIX, - 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, @@ -66,6 +59,5 @@ public enum ConstantKey { JSON_TYPE_SUFFIX, JSON_ID_NAME, JSON_EDITLINK_NAME, - XHTTP_HEADER_NAME; - + XHTTP_HEADER_NAME }; diff --git a/fit/src/main/java/org/apache/olingo/fit/utils/Constants.java b/fit/src/main/java/org/apache/olingo/fit/utils/Constants.java index d0915a4b7..6a1d16a47 100644 --- a/fit/src/main/java/org/apache/olingo/fit/utils/Constants.java +++ b/fit/src/main/java/org/apache/olingo/fit/utils/Constants.java @@ -55,19 +55,12 @@ public class Constants { "http://localhost:9080/stub/StaticService/V40/Static.svc/$metadata#"); constants.put(ConstantKey.ODATA_METADATA_ENTITY_SUFFIX, "/$entity"); constants.put(ConstantKey.ODATA_COUNT_NAME, "odata.count"); - 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.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, "metadata"); diff --git a/fit/src/main/java/org/apache/olingo/fit/utils/FSManager.java b/fit/src/main/java/org/apache/olingo/fit/utils/FSManager.java index d3530c88f..8202619db 100644 --- a/fit/src/main/java/org/apache/olingo/fit/utils/FSManager.java +++ b/fit/src/main/java/org/apache/olingo/fit/utils/FSManager.java @@ -25,8 +25,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; -import java.util.EnumMap; -import java.util.Map; import javax.ws.rs.NotFoundException; @@ -61,37 +59,34 @@ public class FSManager { private final FileSystemManager fsManager; - private static Map instance = - new EnumMap(ODataServiceVersion.class); + private static FSManager instance = null; - private final ODataServiceVersion version; - - public static FSManager instance(final ODataServiceVersion version) throws IOException { - if (!instance.containsKey(version)) { - instance.put(version, new FSManager(version)); + public static FSManager instance() throws IOException { + if (instance == null) { + instance = new FSManager(); } - return instance.get(version); + return instance; } - private FSManager(final ODataServiceVersion version) throws IOException { - this.version = version; + private FSManager() throws IOException { fsManager = VFS.getManager(); - final FileObject basePath = fsManager.resolveFile(RES_PREFIX + File.separatorChar + version.name()); + final FileObject basePath = + fsManager.resolveFile(RES_PREFIX + File.separatorChar + ODataServiceVersion.V40.name()); final String absoluteBaseFolder = basePath.getURL().getPath(); for (FileObject fo : find(basePath, null)) { if (fo.getType() == FileType.FILE && !fo.getName().getBaseName().contains("Metadata") && !fo.getName().getBaseName().contains("metadata")) { - final String path = fo.getURL().getPath().replace(absoluteBaseFolder, "//" + version.name()); + final String path = fo.getURL().getPath().replace(absoluteBaseFolder, "//" + ODataServiceVersion.V40.name()); putInMemory(fo.getContent().getInputStream(), path); } } } public String getAbsolutePath(final String relativePath, final Accept accept) { - return File.separatorChar + version.name() + File.separatorChar + relativePath + return File.separatorChar + ODataServiceVersion.V40.name() + File.separatorChar + relativePath + (accept == null ? "" : accept.getExtension()); } diff --git a/fit/src/main/java/org/apache/olingo/fit/utils/InjectableSerializerProvider.java b/fit/src/main/java/org/apache/olingo/fit/utils/InjectableSerializerProvider.java deleted file mode 100644 index 02ada0913..000000000 --- a/fit/src/main/java/org/apache/olingo/fit/utils/InjectableSerializerProvider.java +++ /dev/null @@ -1,42 +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.fit.utils; - -import com.fasterxml.jackson.databind.SerializationConfig; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider; -import com.fasterxml.jackson.databind.ser.SerializerFactory; - -public class InjectableSerializerProvider extends DefaultSerializerProvider { - - private static final long serialVersionUID = 3432260063063739646L; - - public InjectableSerializerProvider( - final SerializerProvider src, final SerializationConfig config, final SerializerFactory factory) { - - super(src, config, factory); - } - - @Override - public InjectableSerializerProvider createInstance( - final SerializationConfig config, final SerializerFactory factory) { - - return this; - } -} diff --git a/fit/src/main/java/org/apache/olingo/fit/utils/JSONUtilities.java b/fit/src/main/java/org/apache/olingo/fit/utils/JSONUtilities.java index 8be6b11c4..b18886d64 100644 --- a/fit/src/main/java/org/apache/olingo/fit/utils/JSONUtilities.java +++ b/fit/src/main/java/org/apache/olingo/fit/utils/JSONUtilities.java @@ -39,7 +39,6 @@ import org.apache.olingo.fit.metadata.Metadata; import org.apache.olingo.fit.metadata.NavigationProperty; import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.InjectableValues; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; @@ -48,21 +47,10 @@ import com.fasterxml.jackson.databind.node.TextNode; public class JSONUtilities extends AbstractUtilities { - private final ObjectMapper mapper; + private final ObjectMapper mapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); public JSONUtilities(final Metadata metadata) throws IOException { super(metadata); - - mapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.setInjectableValues(new InjectableValues.Std(). - addValue(Boolean.class, Boolean.TRUE)); - // addValue(ODataServiceVersion.class, version)) - - mapper.setSerializerProvider(new InjectableSerializerProvider(mapper.getSerializerProvider(), - mapper.getSerializationConfig(). - // withAttribute(ODataServiceVersion.class, version). - withAttribute(Boolean.class, Boolean.TRUE), - mapper.getSerializerFactory())); } @Override diff --git a/fit/src/main/java/org/apache/olingo/fit/utils/MetadataLinkInfo.java b/fit/src/main/java/org/apache/olingo/fit/utils/MetadataLinkInfo.java deleted file mode 100644 index e79ce96a5..000000000 --- a/fit/src/main/java/org/apache/olingo/fit/utils/MetadataLinkInfo.java +++ /dev/null @@ -1,182 +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.fit.utils; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.ws.rs.NotFoundException; - -public class MetadataLinkInfo { - - private Map entitySets = new HashMap(); - - public void setSingleton(final String entitySetName) { - entitySets.get(entitySetName).setSingleton(true); - } - - public boolean isSingleton(final String entitySetName) { - return entitySets.get(entitySetName).isSingleton(); - } - - public Set getEntitySets() { - return entitySets.keySet(); - } - - public void addEntitySet(final String entitySetName) { - if (!entitySets.containsKey(entitySetName)) { - entitySets.put(entitySetName, new EntitySet(entitySetName)); - } - } - - public void addLink( - final String entitySetName, final String linkName, final String targetName, final boolean isFeed) { - final EntitySet entitySet; - if (entitySets.containsKey(entitySetName)) { - entitySet = entitySets.get(entitySetName); - } else { - entitySet = new EntitySet(entitySetName); - entitySets.put(entitySetName, entitySet); - } - - entitySet.add(linkName, targetName, isFeed); - } - - public Set getNavigationLinkNames(final String entitySetName) { - final Set res = new HashSet(); - - if (!entitySets.containsKey(entitySetName)) { - throw new NotFoundException(); - } - - for (NavigationLink navigationLink : entitySets.get(entitySetName).getLinks()) { - res.add(navigationLink.getName()); - } - - return res; - } - - public boolean exists(final String entitySetName, final String linkName) { - try { - return getNavigationLinkNames(entitySetName).contains(linkName); - } catch (Exception e) { - return false; - } - } - - public boolean isFeed(final String entitySetName, final String linkName) { - return entitySets.containsKey(entitySetName) && entitySets.get(entitySetName).isFeed(linkName); - } - - public String getTargetName(final String entitySetName, final String linkName) { - if (!entitySets.containsKey(entitySetName)) { - throw new NotFoundException(); - } - - final String targetName = entitySets.get(entitySetName).getLink(linkName).getTargetName(); - return targetName.substring(targetName.lastIndexOf(".") + 1); - } - - private static class EntitySet { - - private String name; - - private Set links; - - private boolean singleton; - - public EntitySet(final String name) { - this.name = name; - links = new HashSet(); - } - - public void add(final String linkName, final String targetName, final boolean isFeed) { - links.add(new NavigationLink(linkName, targetName, isFeed)); - } - - public Set getLinks() { - return links; - } - - public NavigationLink getLink(final String linkName) { - for (NavigationLink navigationLink : links) { - if (linkName.equalsIgnoreCase(navigationLink.getName())) { - return navigationLink; - } - } - - throw new NotFoundException(); - } - - public boolean isFeed(final String linkName) { - try { - return getLink(linkName).isFeed(); - } catch (Exception e) { - return false; - } - } - - public boolean isSingleton() { - return singleton; - } - - public void setSingleton(final boolean singleton) { - this.singleton = singleton; - } - - @Override - public String toString() { - return name + ": " + links; - } - } - - private static class NavigationLink { - - private final String name; - - private final String targetName; - - private final boolean feed; - - public NavigationLink(final String name, final String targetName, final boolean feed) { - this.name = name; - this.targetName = targetName; - this.feed = feed; - } - - public String getName() { - return name; - } - - public String getTargetName() { - return targetName; - } - - public boolean isFeed() { - return feed; - } - - @Override - public String toString() { - return name + "(feed: " + isFeed() + ")"; - } - } -} diff --git a/fit/src/main/java/org/apache/olingo/fit/utils/XMLUtilities.java b/fit/src/main/java/org/apache/olingo/fit/utils/XMLUtilities.java index 1078e2f23..c7930f0cc 100644 --- a/fit/src/main/java/org/apache/olingo/fit/utils/XMLUtilities.java +++ b/fit/src/main/java/org/apache/olingo/fit/utils/XMLUtilities.java @@ -38,6 +38,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.regex.Pattern; import javax.ws.rs.NotFoundException; import javax.xml.namespace.QName; @@ -61,6 +62,8 @@ import org.apache.olingo.fit.metadata.NavigationProperty; public class XMLUtilities extends AbstractUtilities { + private static final Pattern ENTITY_URI_PATTERN = Pattern.compile(".*\\/.*\\(.*\\)"); + protected static XMLInputFactory ifactory = null; protected static XMLOutputFactory ofactory = null; diff --git a/fit/src/test/java/org/apache/olingo/fit/proxy/demo/odatademo/types/Customer.java b/fit/src/test/java/org/apache/olingo/fit/proxy/demo/odatademo/types/Customer.java index 405ce0a35..b9d15cc5d 100644 --- a/fit/src/test/java/org/apache/olingo/fit/proxy/demo/odatademo/types/Customer.java +++ b/fit/src/test/java/org/apache/olingo/fit/proxy/demo/odatademo/types/Customer.java @@ -18,9 +18,7 @@ */ package org.apache.olingo.fit.proxy.demo.odatademo.types; -// CHECKSTYLE:OFF (Maven checkstyle) import java.util.concurrent.Future; -// CHECKSTYLE:ON (Maven checkstyle) import org.apache.olingo.ext.proxy.api.annotations.Key; @@ -30,9 +28,7 @@ import org.apache.olingo.ext.proxy.api.annotations.Key; hasStream = false, isAbstract = false, baseType = "ODataDemo.Person") -public interface Customer - extends org.apache.olingo.ext.proxy.api.Annotatable, - Person { +public interface Customer extends Person { @Override Customer load(); diff --git a/fit/src/test/java/org/apache/olingo/fit/proxy/demo/odatademo/types/Employee.java b/fit/src/test/java/org/apache/olingo/fit/proxy/demo/odatademo/types/Employee.java index 4b55f5372..8b48599c3 100644 --- a/fit/src/test/java/org/apache/olingo/fit/proxy/demo/odatademo/types/Employee.java +++ b/fit/src/test/java/org/apache/olingo/fit/proxy/demo/odatademo/types/Employee.java @@ -18,9 +18,7 @@ */ package org.apache.olingo.fit.proxy.demo.odatademo.types; -// CHECKSTYLE:OFF (Maven checkstyle) import java.util.concurrent.Future; -// CHECKSTYLE:ON (Maven checkstyle) import org.apache.olingo.ext.proxy.api.annotations.Key; @@ -30,9 +28,7 @@ import org.apache.olingo.ext.proxy.api.annotations.Key; hasStream = false, isAbstract = false, baseType = "ODataDemo.Person") -public interface Employee - extends org.apache.olingo.ext.proxy.api.Annotatable, - Person { +public interface Employee extends Person { @Override Employee load(); diff --git a/fit/src/test/java/org/apache/olingo/fit/proxy/demo/odatademo/types/FeaturedProduct.java b/fit/src/test/java/org/apache/olingo/fit/proxy/demo/odatademo/types/FeaturedProduct.java index 0d09511bd..b38852cf1 100644 --- a/fit/src/test/java/org/apache/olingo/fit/proxy/demo/odatademo/types/FeaturedProduct.java +++ b/fit/src/test/java/org/apache/olingo/fit/proxy/demo/odatademo/types/FeaturedProduct.java @@ -18,9 +18,7 @@ */ package org.apache.olingo.fit.proxy.demo.odatademo.types; -// CHECKSTYLE:OFF (Maven checkstyle) import java.util.concurrent.Future; -// CHECKSTYLE:ON (Maven checkstyle) import org.apache.olingo.ext.proxy.api.annotations.Key; @@ -30,9 +28,7 @@ import org.apache.olingo.ext.proxy.api.annotations.Key; hasStream = false, isAbstract = false, baseType = "ODataDemo.Product") -public interface FeaturedProduct - extends org.apache.olingo.ext.proxy.api.Annotatable, - Product { +public interface FeaturedProduct extends Product { @Override FeaturedProduct load(); diff --git a/fit/src/test/java/org/apache/olingo/fit/proxy/opentype/microsoft/test/odata/services/opentypesservice/types/IndexedRow.java b/fit/src/test/java/org/apache/olingo/fit/proxy/opentype/microsoft/test/odata/services/opentypesservice/types/IndexedRow.java index 2de886916..f2618f2d5 100644 --- a/fit/src/test/java/org/apache/olingo/fit/proxy/opentype/microsoft/test/odata/services/opentypesservice/types/IndexedRow.java +++ b/fit/src/test/java/org/apache/olingo/fit/proxy/opentype/microsoft/test/odata/services/opentypesservice/types/IndexedRow.java @@ -18,11 +18,8 @@ */ package org.apache.olingo.fit.proxy.opentype.microsoft.test.odata.services.opentypesservice.types; -// CHECKSTYLE:OFF (Maven checkstyle) import java.util.concurrent.Future; -// CHECKSTYLE:ON (Maven checkstyle) -import org.apache.olingo.ext.proxy.api.AbstractOpenType; import org.apache.olingo.ext.proxy.api.annotations.Key; @org.apache.olingo.ext.proxy.api.annotations.Namespace("Microsoft.Test.OData.Services.OpenTypesServiceV4") @@ -31,10 +28,7 @@ import org.apache.olingo.ext.proxy.api.annotations.Key; hasStream = false, isAbstract = false, baseType = "Microsoft.Test.OData.Services.OpenTypesServiceV4.Row") -public interface IndexedRow - extends org.apache.olingo.ext.proxy.api.Annotatable, - Row, - AbstractOpenType { +public interface IndexedRow extends Row { @Override IndexedRow load(); diff --git a/fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/CreditCardPI.java b/fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/CreditCardPI.java index 6873492a9..179f2e18c 100644 --- a/fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/CreditCardPI.java +++ b/fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/CreditCardPI.java @@ -18,9 +18,7 @@ */ package org.apache.olingo.fit.proxy.staticservice.microsoft.test.odata.services.odatawcfservice.types; -// CHECKSTYLE:OFF (Maven checkstyle) import java.util.concurrent.Future; -// CHECKSTYLE:ON (Maven checkstyle) import org.apache.olingo.ext.proxy.api.AbstractEntitySet; import org.apache.olingo.ext.proxy.api.annotations.Key; @@ -31,9 +29,7 @@ import org.apache.olingo.ext.proxy.api.annotations.Key; hasStream = false, isAbstract = false, baseType = "Microsoft.Test.OData.Services.ODataWCFService.PaymentInstrument") -public interface CreditCardPI - extends org.apache.olingo.ext.proxy.api.Annotatable, - PaymentInstrument { +public interface CreditCardPI extends PaymentInstrument { @Override CreditCardPI load(); diff --git a/fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/Customer.java b/fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/Customer.java index ed6fdc175..af66869bb 100644 --- a/fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/Customer.java +++ b/fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/Customer.java @@ -18,9 +18,7 @@ */ package org.apache.olingo.fit.proxy.staticservice.microsoft.test.odata.services.odatawcfservice.types; -// CHECKSTYLE:OFF (Maven checkstyle) import java.util.concurrent.Future; -// CHECKSTYLE:ON (Maven checkstyle) import org.apache.olingo.ext.proxy.api.annotations.Key; @@ -30,9 +28,7 @@ import org.apache.olingo.ext.proxy.api.annotations.Key; hasStream = false, isAbstract = false, baseType = "Microsoft.Test.OData.Services.ODataWCFService.Person") -public interface Customer - extends org.apache.olingo.ext.proxy.api.Annotatable, - Person { +public interface Customer extends Person { @Override Customer load(); diff --git a/fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/Employee.java b/fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/Employee.java index f33ccb36a..f0b4e80dc 100644 --- a/fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/Employee.java +++ b/fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/Employee.java @@ -18,9 +18,7 @@ */ package org.apache.olingo.fit.proxy.staticservice.microsoft.test.odata.services.odatawcfservice.types; -// CHECKSTYLE:OFF (Maven checkstyle) import java.util.concurrent.Future; -// CHECKSTYLE:ON (Maven checkstyle) import org.apache.olingo.ext.proxy.api.annotations.Key; @@ -30,9 +28,7 @@ import org.apache.olingo.ext.proxy.api.annotations.Key; hasStream = false, isAbstract = false, baseType = "Microsoft.Test.OData.Services.ODataWCFService.Person") -public interface Employee - extends org.apache.olingo.ext.proxy.api.Annotatable, - Person { +public interface Employee extends Person { @Override Employee load(); diff --git a/fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/PublicCompany.java b/fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/PublicCompany.java index cdace92b0..40144ef56 100644 --- a/fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/PublicCompany.java +++ b/fit/src/test/java/org/apache/olingo/fit/proxy/staticservice/microsoft/test/odata/services/odatawcfservice/types/PublicCompany.java @@ -18,12 +18,9 @@ */ package org.apache.olingo.fit.proxy.staticservice.microsoft.test.odata.services.odatawcfservice.types; -// CHECKSTYLE:OFF (Maven checkstyle) import java.util.concurrent.Future; -// CHECKSTYLE:ON (Maven checkstyle) import org.apache.olingo.ext.proxy.api.AbstractEntitySet; -import org.apache.olingo.ext.proxy.api.AbstractOpenType; import org.apache.olingo.ext.proxy.api.annotations.Key; @org.apache.olingo.ext.proxy.api.annotations.Namespace("Microsoft.Test.OData.Services.ODataWCFService") @@ -32,10 +29,7 @@ import org.apache.olingo.ext.proxy.api.annotations.Key; hasStream = false, isAbstract = false, baseType = "Microsoft.Test.OData.Services.ODataWCFService.Company") -public interface PublicCompany - extends org.apache.olingo.ext.proxy.api.Annotatable, - Company, - AbstractOpenType { +public interface PublicCompany extends Company { @Override PublicCompany load(); diff --git a/fit/src/test/java/org/apache/olingo/fit/tecsvc/client/EntityReferencesITCase.java b/fit/src/test/java/org/apache/olingo/fit/tecsvc/client/EntityReferencesITCase.java index 94867af64..bac2927bc 100644 --- a/fit/src/test/java/org/apache/olingo/fit/tecsvc/client/EntityReferencesITCase.java +++ b/fit/src/test/java/org/apache/olingo/fit/tecsvc/client/EntityReferencesITCase.java @@ -24,6 +24,7 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import java.net.URI; +import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -553,11 +554,11 @@ public class EntityReferencesITCase extends AbstractParamTecSvcITCase { .getReferenceSingleChangeRequest(new URI(SERVICE_URI), uri, reference) .execute(); assertEquals(HttpStatusCode.NO_CONTENT.getStatusCode(), response.getStatusCode()); - + final String cookie = response.getHeader(HttpHeader.SET_COOKIE).iterator().next(); - Map expandOptions = new HashMap(); + Map expandOptions = new EnumMap(QueryOption.class); expandOptions.put(QueryOption.EXPAND, NAV_PROPERTY_ET_KEY_NAV_ONE); - + final URI getURI = getClient().newURIBuilder(SERVICE_URI) .appendEntitySetSegment(ES_TWO_KEY_NAV) .appendKeySegment(esTwoKeyNavKey) @@ -601,12 +602,12 @@ public class EntityReferencesITCase extends AbstractParamTecSvcITCase { .getReferenceAddingRequest(new URI(SERVICE_URI), uri, reference) .execute(); assertEquals(HttpStatusCode.NO_CONTENT.getStatusCode(), response.getStatusCode()); - + final String cookie = response.getHeader(HttpHeader.SET_COOKIE).iterator().next(); - final Map expandOptions = new HashMap(); + final Map expandOptions = new EnumMap(QueryOption.class); expandOptions.put(QueryOption.EXPAND, NAV_PROPERTY_ET_KEY_NAV_MANY); expandOptions.put(QueryOption.FILTER, "PropertyInt16 eq 1"); - + final URI getURI = getClient().newURIBuilder(SERVICE_URI) .appendEntitySetSegment(ES_TWO_KEY_NAV) .appendKeySegment(esTwoKeyNavKey) diff --git a/fit/src/test/java/org/apache/olingo/fit/tecsvc/client/ExpandWithSystemQueryOptionsITCase.java b/fit/src/test/java/org/apache/olingo/fit/tecsvc/client/ExpandWithSystemQueryOptionsITCase.java index 507b9a917..0f3743be8 100644 --- a/fit/src/test/java/org/apache/olingo/fit/tecsvc/client/ExpandWithSystemQueryOptionsITCase.java +++ b/fit/src/test/java/org/apache/olingo/fit/tecsvc/client/ExpandWithSystemQueryOptionsITCase.java @@ -23,6 +23,8 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.net.URI; +import java.util.Collections; +import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -49,11 +51,10 @@ public class ExpandWithSystemQueryOptionsITCase extends AbstractParamTecSvcITCas @Test public void filter() { - Map options = new HashMap(); - options.put(QueryOption.FILTER, "PropertyString eq '2'"); - final ODataRetrieveResponse response = - buildRequest(ES_TWO_KEY_NAV, NAV_PROPERTY_ET_TWO_KEY_NAV_MANY, options); + buildRequest(ES_TWO_KEY_NAV, NAV_PROPERTY_ET_TWO_KEY_NAV_MANY, + Collections.singletonMap(QueryOption.FILTER, (Object) "PropertyString eq '2'")); + final List entities = response.getBody().getEntities(); assertEquals(4, entities.size()); @@ -87,11 +88,9 @@ public class ExpandWithSystemQueryOptionsITCase extends AbstractParamTecSvcITCas @Test public void orderBy() { - Map options = new HashMap(); - options.put(QueryOption.ORDERBY, "PropertyString desc"); - final ODataRetrieveResponse response = - buildRequest(ES_TWO_KEY_NAV, NAV_PROPERTY_ET_TWO_KEY_NAV_MANY, options); + buildRequest(ES_TWO_KEY_NAV, NAV_PROPERTY_ET_TWO_KEY_NAV_MANY, + Collections. singletonMap(QueryOption.ORDERBY, "PropertyString desc")); final List entities = response.getBody().getEntities(); assertEquals(4, entities.size()); @@ -117,11 +116,9 @@ public class ExpandWithSystemQueryOptionsITCase extends AbstractParamTecSvcITCas @Test public void skip() { - Map options = new HashMap(); - options.put(QueryOption.SKIP, "1"); - final ODataRetrieveResponse response = - buildRequest(ES_KEY_NAV, NAV_PROPERTY_ET_KEY_NAV_MANY, options); + buildRequest(ES_KEY_NAV, NAV_PROPERTY_ET_KEY_NAV_MANY, + Collections.singletonMap(QueryOption.SKIP, (Object) "1")); final List entities = response.getBody().getEntities(); assertEquals(3, entities.size()); @@ -148,11 +145,9 @@ public class ExpandWithSystemQueryOptionsITCase extends AbstractParamTecSvcITCas @Test public void top() { - Map options = new HashMap(); - options.put(QueryOption.TOP, "1"); - final ODataRetrieveResponse response = - buildRequest(ES_KEY_NAV, NAV_PROPERTY_ET_KEY_NAV_MANY, options); + buildRequest(ES_KEY_NAV, NAV_PROPERTY_ET_KEY_NAV_MANY, + Collections. singletonMap(QueryOption.TOP, "1")); final List entities = response.getBody().getEntities(); assertEquals(3, entities.size()); @@ -179,7 +174,7 @@ public class ExpandWithSystemQueryOptionsITCase extends AbstractParamTecSvcITCas @Test public void combinedSystemQueryOptions() { - Map options = new HashMap(); + Map options = new EnumMap(QueryOption.class); options.put(QueryOption.SELECT, "PropertyInt16,PropertyString"); options.put(QueryOption.FILTER, "PropertyInt16 eq 1"); options.put(QueryOption.SKIP, "1"); @@ -217,7 +212,7 @@ public class ExpandWithSystemQueryOptionsITCase extends AbstractParamTecSvcITCas @Ignore("Server do not support navigation property count annotations") public void count() { final ODataClient client = getEdmEnabledClient(); - Map options = new HashMap(); + Map options = new EnumMap(QueryOption.class); options.put(QueryOption.SELECT, "PropertyInt16"); options.put(QueryOption.COUNT, true); @@ -255,14 +250,14 @@ public class ExpandWithSystemQueryOptionsITCase extends AbstractParamTecSvcITCas public void singleEntityWithExpand() { /* A single entity request will be dispatched to a different processor method than entity set request */ final ODataClient client = getEdmEnabledClient(); - Map options = new HashMap(); - options.put(QueryOption.FILTER, "PropertyInt16 lt 2"); Map keys = new HashMap(); keys.put("PropertyInt16", 1); keys.put("PropertyString", "1"); final URI uri = client.newURIBuilder(SERVICE_URI).appendEntitySetSegment(ES_TWO_KEY_NAV).appendKeySegment(keys) - .expandWithOptions(NAV_PROPERTY_ET_KEY_NAV_MANY, options).build(); + .expandWithOptions(NAV_PROPERTY_ET_KEY_NAV_MANY, + Collections.singletonMap(QueryOption.FILTER, (Object) "PropertyInt16 lt 2")) + .build(); final ODataRetrieveResponse response = client.getRetrieveRequestFactory().getEntityRequest(uri).execute(); assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode()); @@ -275,11 +270,12 @@ public class ExpandWithSystemQueryOptionsITCase extends AbstractParamTecSvcITCas @Test public void URIEscaping() { - Map options = new HashMap(); - options.put(QueryOption.FILTER, "PropertyInt16 eq 1" - + " and PropertyComp/PropertyComp/PropertyDuration eq duration'PT1S' and length(PropertyString) gt 4"); final ODataRetrieveResponse response = - buildRequest(ES_TWO_KEY_NAV, NAV_PROPERTY_ET_TWO_KEY_NAV_MANY, options); + buildRequest(ES_TWO_KEY_NAV, NAV_PROPERTY_ET_TWO_KEY_NAV_MANY, + Collections. singletonMap(QueryOption.FILTER, + "PropertyInt16 eq 1" + + " and PropertyComp/PropertyComp/PropertyDuration eq duration'PT1S'" + + " and length(PropertyString) gt 4")); final List entities = response.getBody().getEntities(); assertEquals(HttpStatusCode.OK.getStatusCode(), response.getStatusCode()); @@ -296,7 +292,7 @@ public class ExpandWithSystemQueryOptionsITCase extends AbstractParamTecSvcITCas // Define filters to select explicit the entities at any level => Circle final ODataClient client = getEdmEnabledClient(); - Map options = new HashMap(); + Map options = new EnumMap(QueryOption.class); options.put(QueryOption.EXPAND, NAV_PROPERTY_ET_TWO_KEY_NAV_MANY + "($expand=" + NAV_PROPERTY_ET_TWO_KEY_NAV_MANY + "($expand=" + NAV_PROPERTY_ET_TWO_KEY_NAV_MANY + "))"); @@ -371,7 +367,7 @@ public class ExpandWithSystemQueryOptionsITCase extends AbstractParamTecSvcITCas @Test public void systemQueryOptionOnThirdLevel() { final ODataClient client = getEdmEnabledClient(); - Map options = new HashMap(); + Map options = new EnumMap(QueryOption.class); options.put(QueryOption.EXPAND, NAV_PROPERTY_ET_TWO_KEY_NAV_MANY + "($expand=" + NAV_PROPERTY_ET_TWO_KEY_NAV_MANY + "($expand=" + NAV_PROPERTY_ET_TWO_KEY_NAV_MANY @@ -444,7 +440,7 @@ public class ExpandWithSystemQueryOptionsITCase extends AbstractParamTecSvcITCas @Test public void expandWithSearchQuery() { final ODataClient client = getEdmEnabledClient(); - Map expandOptions = new HashMap(); + Map expandOptions = new EnumMap(QueryOption.class); expandOptions.put(QueryOption.SEARCH, "abc"); expandOptions.put(QueryOption.FILTER, "PropertyInt16 eq 1"); @@ -464,12 +460,10 @@ public class ExpandWithSystemQueryOptionsITCase extends AbstractParamTecSvcITCas @Test public void expandWithLevels() { final ODataClient client = getEdmEnabledClient(); - Map expandOptions = new HashMap(); - expandOptions.put(QueryOption.LEVELS, 2); // expand=*($levels=2) URI uri = client.newURIBuilder(SERVICE_URI).appendEntitySetSegment(ES_KEY_NAV) - .expandWithOptions("*", expandOptions) + .expandWithOptions("*", Collections. singletonMap(QueryOption.LEVELS, 2)) .build(); try { @@ -479,10 +473,9 @@ public class ExpandWithSystemQueryOptionsITCase extends AbstractParamTecSvcITCas } // expand=NavPropertyETTwoKeyNavMany($levels=2) - expandOptions.clear(); - expandOptions.put(QueryOption.LEVELS, 2); uri = client.newURIBuilder(SERVICE_URI).appendEntitySetSegment(ES_KEY_NAV) - .expandWithOptions(NAV_PROPERTY_ET_TWO_KEY_NAV_MANY, expandOptions) + .expandWithOptions(NAV_PROPERTY_ET_TWO_KEY_NAV_MANY, + Collections. singletonMap(QueryOption.LEVELS, 2)) .build(); try { @@ -492,10 +485,10 @@ public class ExpandWithSystemQueryOptionsITCase extends AbstractParamTecSvcITCas } // expand=NavPropertyETTwoKeyNavMany($expand=NavPropertyETTwoKeyNavMany($levels=2)) - expandOptions.clear(); - expandOptions.put(QueryOption.EXPAND, NAV_PROPERTY_ET_TWO_KEY_NAV_MANY + "($levels=2)"); uri = client.newURIBuilder(SERVICE_URI).appendEntitySetSegment(ES_KEY_NAV) - .expandWithOptions(NAV_PROPERTY_ET_TWO_KEY_NAV_MANY, expandOptions) + .expandWithOptions(NAV_PROPERTY_ET_TWO_KEY_NAV_MANY, + Collections. singletonMap(QueryOption.EXPAND, + NAV_PROPERTY_ET_TWO_KEY_NAV_MANY + "($levels=2)")) .build(); try { @@ -505,10 +498,9 @@ public class ExpandWithSystemQueryOptionsITCase extends AbstractParamTecSvcITCas } // expand=NavPropertyETTwoKeyNavMany($expand=NavPropertyETTwoKeyNavMany($levels=2);$levels=3) - expandOptions.clear(); - expandOptions.put(QueryOption.LEVELS, 2); uri = client.newURIBuilder(SERVICE_URI).appendEntitySetSegment(ES_KEY_NAV) - .expandWithOptions(NAV_PROPERTY_ET_TWO_KEY_NAV_MANY, expandOptions) + .expandWithOptions(NAV_PROPERTY_ET_TWO_KEY_NAV_MANY, + Collections. singletonMap(QueryOption.LEVELS, 2)) .build(); try { @@ -518,7 +510,7 @@ public class ExpandWithSystemQueryOptionsITCase extends AbstractParamTecSvcITCas } // expand=NavPropertyETTwoKeyNavMany($expand=NavPropertyETTwoKeyNavMany($levels=2)) - expandOptions.clear(); + Map expandOptions = new EnumMap(QueryOption.class); expandOptions.put(QueryOption.EXPAND, NAV_PROPERTY_ET_TWO_KEY_NAV_MANY + "($levels=2)"); expandOptions.put(QueryOption.LEVELS, 3); uri = client.newURIBuilder(SERVICE_URI).appendEntitySetSegment(ES_KEY_NAV) diff --git a/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/AbstractClientEntitySet.java b/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/AbstractClientEntitySet.java deleted file mode 100644 index d59af9391..000000000 --- a/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/AbstractClientEntitySet.java +++ /dev/null @@ -1,114 +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.domain; - -import java.net.URI; - -import org.apache.olingo.client.api.domain.AbstractClientPayload; -import org.apache.olingo.client.api.domain.ClientEntitySet; - -public abstract class AbstractClientEntitySet extends AbstractClientPayload implements ClientEntitySet { - - /** - * Link to the next page. - */ - private URI next; - - /** - * Number of ODataEntities contained in this entity set. - *
- * If $count was requested, this value comes from there. - */ - private Integer count; - - /** - * Constructor. - */ - public AbstractClientEntitySet() { - super(null); - } - - /** - * Constructor. - * - * @param next next link. - */ - public AbstractClientEntitySet(final URI next) { - super(null); - this.next = next; - } - - @Override - public URI getNext() { - return next; - } - - @Override - public Integer getCount() { - return count; - } - - @Override - public void setCount(final int count) { - this.count = count; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((count == null) ? 0 : count.hashCode()); - result = prime * result + ((next == null) ? 0 : next.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof AbstractClientEntitySet)) { - return false; - } - AbstractClientEntitySet other = (AbstractClientEntitySet) obj; - if (count == null) { - if (other.count != null) { - return false; - } - } else if (!count.equals(other.count)) { - return false; - } - if (next == null) { - if (other.next != null) { - return false; - } - } else if (!next.equals(other.next)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "AbstractClientEntitySet [next=" + next + ", count=" + count + "super[" + super.toString() + "]]"; - } -} diff --git a/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientCollectionValueImpl.java b/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientCollectionValueImpl.java index c83fceb59..2a3aebc76 100644 --- a/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientCollectionValueImpl.java +++ b/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientCollectionValueImpl.java @@ -29,7 +29,7 @@ import org.apache.olingo.client.api.domain.ClientEnumValue; import org.apache.olingo.client.api.domain.ClientValue; public class ClientCollectionValueImpl extends AbstractClientValue - implements ClientCollectionValue, ClientValue { + implements ClientCollectionValue { /** * Constructor. diff --git a/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientEntitySetImpl.java b/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientEntitySetImpl.java index 29ede4ced..21e13b450 100644 --- a/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientEntitySetImpl.java +++ b/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientEntitySetImpl.java @@ -22,11 +22,24 @@ import java.net.URI; import java.util.ArrayList; import java.util.List; +import org.apache.olingo.client.api.domain.AbstractClientPayload; import org.apache.olingo.client.api.domain.ClientAnnotation; import org.apache.olingo.client.api.domain.ClientEntity; import org.apache.olingo.client.api.domain.ClientEntitySet; -public class ClientEntitySetImpl extends AbstractClientEntitySet implements ClientEntitySet { +public class ClientEntitySetImpl extends AbstractClientPayload implements ClientEntitySet { + + /** + * Link to the next page. + */ + private final URI next; + + /** + * Number of ODataEntities contained in this entity set. + *
+ * If $count was requested, this value comes from there. + */ + private Integer count; private URI deltaLink; @@ -35,11 +48,28 @@ public class ClientEntitySetImpl extends AbstractClientEntitySet implements Clie private final List annotations = new ArrayList(); public ClientEntitySetImpl() { - super(); + super(null); + next = null; } public ClientEntitySetImpl(final URI next) { - super(next); + super(null); + this.next = next; + } + + @Override + public URI getNext() { + return next; + } + + @Override + public Integer getCount() { + return count; + } + + @Override + public void setCount(final int count) { + this.count = count; } @Override @@ -66,6 +96,8 @@ public class ClientEntitySetImpl extends AbstractClientEntitySet implements Clie public int hashCode() { final int prime = 31; int result = super.hashCode(); + result = prime * result + ((count == null) ? 0 : count.hashCode()); + result = prime * result + ((next == null) ? 0 : next.hashCode()); result = prime * result + ((annotations == null) ? 0 : annotations.hashCode()); result = prime * result + ((deltaLink == null) ? 0 : deltaLink.hashCode()); result = prime * result + ((entities == null) ? 0 : entities.hashCode()); @@ -77,40 +109,20 @@ public class ClientEntitySetImpl extends AbstractClientEntitySet implements Clie if (this == obj) { return true; } - if (!super.equals(obj)) { + if (obj == null || !(obj instanceof ClientEntitySetImpl)) { return false; } - if (!(obj instanceof ClientEntitySetImpl)) { - return false; - } - ClientEntitySetImpl other = (ClientEntitySetImpl) obj; - if (annotations == null) { - if (other.annotations != null) { - return false; - } - } else if (!annotations.equals(other.annotations)) { - return false; - } - if (deltaLink == null) { - if (other.deltaLink != null) { - return false; - } - } else if (!deltaLink.equals(other.deltaLink)) { - return false; - } - if (entities == null) { - if (other.entities != null) { - return false; - } - } else if (!entities.equals(other.entities)) { - return false; - } - return true; + final ClientEntitySetImpl other = (ClientEntitySetImpl) obj; + return (count == null ? other.count == null : count.equals(other.count)) + && (next == null ? other.next == null : next.equals(other.next)) + && annotations.equals(other.annotations) + && (deltaLink == null ? other.deltaLink == null : deltaLink.equals(other.deltaLink)) + && entities.equals(other.entities); } @Override public String toString() { return "ClientEntitySetImpl [deltaLink=" + deltaLink + ", entities=" + entities + ", annotations=" + annotations - + "super[" + super.toString() + "]]"; + + ", next=" + next + ", count=" + count + "super[" + super.toString() + "]]"; } } diff --git a/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientPrimitiveValueImpl.java b/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientPrimitiveValueImpl.java index cdfe623bc..4824632bd 100644 --- a/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientPrimitiveValueImpl.java +++ b/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientPrimitiveValueImpl.java @@ -21,11 +21,10 @@ package org.apache.olingo.client.core.domain; import java.math.BigDecimal; import java.util.UUID; -import org.apache.olingo.commons.api.Constants; import org.apache.olingo.client.api.domain.AbstractClientValue; import org.apache.olingo.client.api.domain.ClientEnumValue; import org.apache.olingo.client.api.domain.ClientPrimitiveValue; -import org.apache.olingo.client.api.domain.ClientValue; +import org.apache.olingo.commons.api.Constants; import org.apache.olingo.commons.api.edm.EdmPrimitiveType; import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException; import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; @@ -33,7 +32,7 @@ import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.api.edm.constants.EdmTypeKind; import org.apache.olingo.commons.core.edm.primitivetype.EdmPrimitiveTypeFactory; -public class ClientPrimitiveValueImpl extends AbstractClientValue implements ClientValue, ClientPrimitiveValue { +public class ClientPrimitiveValueImpl extends AbstractClientValue implements ClientPrimitiveValue { public static class BuilderImpl implements Builder { diff --git a/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientPropertyImpl.java b/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientPropertyImpl.java index f78c506fa..8c8c3ee9c 100644 --- a/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientPropertyImpl.java +++ b/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientPropertyImpl.java @@ -18,30 +18,21 @@ */ package org.apache.olingo.client.core.domain; -import org.apache.olingo.client.api.domain.ClientAnnotatable; -import org.apache.olingo.client.api.domain.ClientAnnotation; -import org.apache.olingo.client.api.domain.ClientCollectionValue; -import org.apache.olingo.client.api.domain.ClientComplexValue; -import org.apache.olingo.client.api.domain.ClientEnumValue; -import org.apache.olingo.client.api.domain.ClientPrimitiveValue; -import org.apache.olingo.client.api.domain.ClientProperty; -import org.apache.olingo.client.api.domain.ClientValuable; -import org.apache.olingo.client.api.domain.ClientValue; - import java.util.ArrayList; import java.util.List; -public final class ClientPropertyImpl implements ClientProperty, ClientAnnotatable, ClientValuable { +import org.apache.olingo.client.api.domain.ClientAnnotation; +import org.apache.olingo.client.api.domain.ClientProperty; +import org.apache.olingo.client.api.domain.ClientValue; + +public final class ClientPropertyImpl extends ClientValuableImpl implements ClientProperty { private final List annotations = new ArrayList(); private final String name; - private final ClientValue value; - private final ClientValuable valuable; public ClientPropertyImpl(final String name, final ClientValue value) { + super(value); this.name = name; - this.value = value; - this.valuable = new ClientValuableImpl(value); } /** @@ -54,16 +45,6 @@ public final class ClientPropertyImpl implements ClientProperty, ClientAnnotatab return name; } - /** - * Returns property value. - * - * @return property value. - */ - @Override - public ClientValue getValue() { - return value; - } - /** * Checks if has null value. * @@ -74,87 +55,18 @@ public final class ClientPropertyImpl implements ClientProperty, ClientAnnotatab return value == null || value.isPrimitive() && value.asPrimitive().toValue() == null; } - /** - * Checks if has primitive value. - * - * @return 'TRUE' if has primitive value; 'FALSE' otherwise. - */ - @Override - public boolean hasPrimitiveValue() { - return !hasNullValue() && value.isPrimitive(); - } - - /** - * Gets primitive value. - * - * @return primitive value if exists; null otherwise. - */ - @Override - public ClientPrimitiveValue getPrimitiveValue() { - return hasPrimitiveValue() ? value.asPrimitive() : null; - } - - /** - * Checks if has complex value. - * - * @return 'TRUE' if has complex value; 'FALSE' otherwise. - */ - @Override - public boolean hasComplexValue() { - return !hasNullValue() && value.isComplex(); - } - - /** - * Checks if has collection value. - * - * @return 'TRUE' if has collection value; 'FALSE' otherwise. - */ - @Override - public boolean hasCollectionValue() { - return !hasNullValue() && value.isCollection(); - } - @Override public boolean equals(Object obj) { if (this == obj) { return true; } - if (obj == null) { + if (obj == null || !(obj instanceof ClientPropertyImpl)) { return false; } - if (!(obj instanceof ClientPropertyImpl)) { - return false; - } - ClientPropertyImpl other = (ClientPropertyImpl) obj; - if (annotations == null) { - if (other.annotations != null) { - return false; - } - } else if (!annotations.equals(other.annotations)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - if (valuable == null) { - if (other.valuable != null) { - return false; - } - } else if (!valuable.equals(other.valuable)) { - return false; - } - if (value == null) { - if (other.value != null) { - return false; - } - } else if (!value.equals(other.value)) { - return false; - } - return true; + final ClientPropertyImpl other = (ClientPropertyImpl) obj; + return annotations.equals(other.annotations) + && (name == null ? other.name == null : name.equals(other.name)) + && (value == null ? other.value == null : value.equals(other.value)); } @Override @@ -163,31 +75,10 @@ public final class ClientPropertyImpl implements ClientProperty, ClientAnnotatab int result = 1; result = prime * result + ((annotations == null) ? 0 : annotations.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((valuable == null) ? 0 : valuable.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } - @Override - public boolean hasEnumValue() { - return valuable.hasEnumValue(); - } - - @Override - public ClientEnumValue getEnumValue() { - return valuable.getEnumValue(); - } - - @Override - public ClientComplexValue getComplexValue() { - return valuable.getComplexValue(); - } - - @Override - public ClientCollectionValue getCollectionValue() { - return valuable.getCollectionValue(); - } - @Override public List getAnnotations() { return annotations; @@ -195,10 +86,6 @@ public final class ClientPropertyImpl implements ClientProperty, ClientAnnotatab @Override public String toString() { - return "ODataPropertyImpl{" - + "name=" + getName() - + ",valuable=" + valuable - + ", annotations=" + annotations - + '}'; + return "ClientPropertyImpl{" + "name=" + name + ", value=" + value + ", annotations=" + annotations + '}'; } } diff --git a/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientValuableImpl.java b/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientValuableImpl.java index 4a032ceed..4b94be6c6 100644 --- a/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientValuableImpl.java +++ b/lib/client-core/src/main/java/org/apache/olingo/client/core/domain/ClientValuableImpl.java @@ -25,9 +25,9 @@ import org.apache.olingo.client.api.domain.ClientPrimitiveValue; import org.apache.olingo.client.api.domain.ClientValuable; import org.apache.olingo.client.api.domain.ClientValue; -public final class ClientValuableImpl implements ClientValuable { +public class ClientValuableImpl implements ClientValuable { - private final ClientValue value; + protected final ClientValue value; public ClientValuableImpl(final ClientValue value) { this.value = value; @@ -60,9 +60,7 @@ public final class ClientValuableImpl implements ClientValuable { @Override public ClientCollectionValue getCollectionValue() { - return hasCollectionValue() - ? getValue(). asCollection() - : null; + return hasCollectionValue() ? getValue(). asCollection() : null; } @Override @@ -72,9 +70,7 @@ public final class ClientValuableImpl implements ClientValuable { @Override public ClientComplexValue getComplexValue() { - return hasComplexValue() - ? getValue().asComplex() - : null; + return hasComplexValue() ? getValue().asComplex() : null; } @Override @@ -84,9 +80,7 @@ public final class ClientValuableImpl implements ClientValuable { @Override public ClientEnumValue getEnumValue() { - return hasEnumValue() - ? getValue().asEnum() - : null; + return hasEnumValue() ? getValue().asEnum() : null; } @Override @@ -99,9 +93,7 @@ public final class ClientValuableImpl implements ClientValuable { } ClientValuableImpl that = (ClientValuableImpl) o; - return !(value != null ? !value.equals(that.value) : that.value != null); - } @Override @@ -111,8 +103,6 @@ public final class ClientValuableImpl implements ClientValuable { @Override public String toString() { - return "ClientValuableImpl{" + - "value=" + value + - '}'; + return "ClientValuableImpl{" + "value=" + value + '}'; } } diff --git a/lib/client-core/src/main/java/org/apache/olingo/client/core/serialization/ODataBinderImpl.java b/lib/client-core/src/main/java/org/apache/olingo/client/core/serialization/ODataBinderImpl.java index 33144ec64..f9f29e722 100644 --- a/lib/client-core/src/main/java/org/apache/olingo/client/core/serialization/ODataBinderImpl.java +++ b/lib/client-core/src/main/java/org/apache/olingo/client/core/serialization/ODataBinderImpl.java @@ -714,7 +714,7 @@ public class ODataBinderImpl implements ODataBinder { if (propertyType == null || propertyType.equals(EdmPrimitiveTypeKind.String.getFullQualifiedName().toString())) { typeInfo = new EdmTypeInfo.Builder().setTypeExpression(typeName.toString()).build(); } else if(isPrimiteveType(typeName)) { - // Inheritance is not allowed for primitve types, so we use the type given by the EDM + // Inheritance is not allowed for primitive types, so we use the type given by the EDM. typeInfo = new EdmTypeInfo.Builder().setTypeExpression(typeName.toString()).build(); } else { typeInfo = new EdmTypeInfo.Builder().setTypeExpression(propertyType).build(); diff --git a/lib/client-core/src/test/java/org/apache/olingo/client/core/AbstractTest.java b/lib/client-core/src/test/java/org/apache/olingo/client/core/AbstractTest.java index bc116a801..d03b6d91f 100644 --- a/lib/client-core/src/test/java/org/apache/olingo/client/core/AbstractTest.java +++ b/lib/client-core/src/test/java/org/apache/olingo/client/core/AbstractTest.java @@ -25,9 +25,7 @@ import org.junit.BeforeClass; public abstract class AbstractTest { - protected static ODataClient v4Client; - - protected abstract ODataClient getClient(); + protected static final ODataClient client = ODataClientFactory.getClient(); @BeforeClass public static void setUp() { @@ -38,11 +36,6 @@ public abstract class AbstractTest { XMLUnit.setCompareUnmatched(false); } - @BeforeClass - public static void setClientInstances() { - v4Client = ODataClientFactory.getClient(); - } - protected String getSuffix(final ContentType contentType) { return contentType.isCompatible(ContentType.APPLICATION_ATOM_SVC) || contentType.isCompatible(ContentType.APPLICATION_ATOM_XML) diff --git a/lib/client-core/src/test/java/org/apache/olingo/client/core/AtomTest.java b/lib/client-core/src/test/java/org/apache/olingo/client/core/AtomTest.java index 9d5346b23..ba2014446 100644 --- a/lib/client-core/src/test/java/org/apache/olingo/client/core/AtomTest.java +++ b/lib/client-core/src/test/java/org/apache/olingo/client/core/AtomTest.java @@ -30,17 +30,11 @@ import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.commons.io.IOUtils; -import org.apache.olingo.client.api.ODataClient; import org.apache.olingo.commons.api.format.ContentType; import org.custommonkey.xmlunit.Diff; public class AtomTest extends JSONTest { - @Override - protected ODataClient getClient() { - return v4Client; - } - @Override protected ContentType getODataPubFormat() { return ContentType.APPLICATION_ATOM_XML; diff --git a/lib/client-core/src/test/java/org/apache/olingo/client/core/EntitySetTest.java b/lib/client-core/src/test/java/org/apache/olingo/client/core/EntitySetTest.java index 199cd05c9..254e83f87 100644 --- a/lib/client-core/src/test/java/org/apache/olingo/client/core/EntitySetTest.java +++ b/lib/client-core/src/test/java/org/apache/olingo/client/core/EntitySetTest.java @@ -26,7 +26,6 @@ import java.io.IOException; import java.io.InputStream; import java.net.URI; -import org.apache.olingo.client.api.ODataClient; import org.apache.olingo.client.api.data.ResWrap; import org.apache.olingo.client.api.domain.ClientEntity; import org.apache.olingo.client.api.domain.ClientEntitySet; @@ -37,23 +36,18 @@ import org.junit.Test; public class EntitySetTest extends AbstractTest { - @Override - protected ODataClient getClient() { - return v4Client; - } - private void read(final ContentType contentType) throws IOException, ODataDeserializerException { final InputStream input = getClass().getResourceAsStream("Customers." + getSuffix(contentType)); - final ClientEntitySet entitySet = getClient().getBinder().getODataEntitySet( - getClient().getDeserializer(contentType).toEntitySet(input)); + final ClientEntitySet entitySet = client.getBinder().getODataEntitySet( + client.getDeserializer(contentType).toEntitySet(input)); assertNotNull(entitySet); assertEquals(2, entitySet.getEntities().size()); assertNull(entitySet.getNext()); final ClientEntitySet written = - getClient().getBinder().getODataEntitySet(new ResWrap((URI) null, null, - getClient().getBinder().getEntitySet(entitySet))); + client.getBinder().getODataEntitySet(new ResWrap((URI) null, null, + client.getBinder().getEntitySet(entitySet))); assertEquals(entitySet, written); } @@ -69,8 +63,8 @@ public class EntitySetTest extends AbstractTest { private void ref(final ContentType contentType) throws ODataDeserializerException { final InputStream input = getClass().getResourceAsStream("collectionOfEntityReferences." + getSuffix(contentType)); - final ClientEntitySet entitySet = getClient().getBinder().getODataEntitySet( - getClient().getDeserializer(contentType).toEntitySet(input)); + final ClientEntitySet entitySet = client.getBinder().getODataEntitySet( + client.getDeserializer(contentType).toEntitySet(input)); assertNotNull(entitySet); for (ClientEntity entity : entitySet.getEntities()) { @@ -79,8 +73,8 @@ public class EntitySetTest extends AbstractTest { entitySet.setCount(entitySet.getEntities().size()); final ClientEntitySet written = - getClient().getBinder().getODataEntitySet(new ResWrap((URI) null, null, - getClient().getBinder().getEntitySet(entitySet))); + client.getBinder().getODataEntitySet(new ResWrap((URI) null, null, + client.getBinder().getEntitySet(entitySet))); assertEquals(entitySet, written); } diff --git a/lib/client-core/src/test/java/org/apache/olingo/client/core/EntityTest.java b/lib/client-core/src/test/java/org/apache/olingo/client/core/EntityTest.java index 9f5d405ed..0d075a962 100644 --- a/lib/client-core/src/test/java/org/apache/olingo/client/core/EntityTest.java +++ b/lib/client-core/src/test/java/org/apache/olingo/client/core/EntityTest.java @@ -50,11 +50,6 @@ import org.junit.Test; public class EntityTest extends AbstractTest { - @Override - protected ODataClient getClient() { - return v4Client; - } - private EdmEnabledODataClient getEdmEnabledClient() { return new EdmEnabledODataClientImpl(null, null, null) { @@ -78,8 +73,8 @@ public class EntityTest extends AbstractTest { private void singleton(final ContentType contentType) throws Exception { final InputStream input = getClass().getResourceAsStream("VipCustomer." + getSuffix(contentType)); - final ClientEntity entity = getClient().getBinder().getODataEntity( - getClient().getDeserializer(contentType).toEntity(input)); + final ClientEntity entity = client.getBinder().getODataEntity( + client.getDeserializer(contentType).toEntity(input)); assertNotNull(entity); assertEquals("Microsoft.Test.OData.Services.ODataWCFService.Customer", entity.getTypeName().toString()); @@ -120,8 +115,8 @@ public class EntityTest extends AbstractTest { // operations won't get serialized entity.getOperations().clear(); - final ClientEntity written = getClient().getBinder().getODataEntity( - new ResWrap((URI) null, null, getClient().getBinder().getEntity(entity))); + final ClientEntity written = client.getBinder().getODataEntity( + new ResWrap((URI) null, null, client.getBinder().getEntity(entity))); assertEquals(entity, written); input.close(); } @@ -138,8 +133,8 @@ public class EntityTest extends AbstractTest { private void withEnums(final ContentType contentType) throws Exception { final InputStream input = getClass().getResourceAsStream("Products_5." + getSuffix(contentType)); - final ClientEntity entity = getClient().getBinder().getODataEntity( - getClient().getDeserializer(contentType).toEntity(input)); + final ClientEntity entity = client.getBinder().getODataEntity( + client.getDeserializer(contentType).toEntity(input)); assertNotNull(entity); final ClientProperty skinColor = entity.getProperty("SkinColor"); @@ -156,8 +151,8 @@ public class EntityTest extends AbstractTest { // operations won't get serialized entity.getOperations().clear(); - final ClientEntity written = getClient().getBinder().getODataEntity( - new ResWrap((URI) null, null, getClient().getBinder().getEntity(entity))); + final ClientEntity written = client.getBinder().getODataEntity( + new ResWrap((URI) null, null, client.getBinder().getEntity(entity))); assertEquals(entity, written); input.close(); } @@ -175,8 +170,8 @@ public class EntityTest extends AbstractTest { private void withInlineEntitySet(final ContentType contentType) throws Exception { final InputStream input = getClass().getResourceAsStream( "Accounts_101_expand_MyPaymentInstruments." + getSuffix(contentType)); - final ClientEntity entity = getClient().getBinder().getODataEntity( - getClient().getDeserializer(contentType).toEntity(input)); + final ClientEntity entity = client.getBinder().getODataEntity( + client.getDeserializer(contentType).toEntity(input)); assertNotNull(entity); final ClientLink instruments = entity.getNavigationLink("MyPaymentInstruments"); @@ -191,8 +186,8 @@ public class EntityTest extends AbstractTest { inline.getEntitySet().setCount(3); // operations won't get serialized entity.getOperations().clear(); - final ClientEntity written = getClient().getBinder().getODataEntity( - new ResWrap((URI) null, null, getClient().getBinder().getEntity(entity))); + final ClientEntity written = client.getBinder().getODataEntity( + new ResWrap((URI) null, null, client.getBinder().getEntity(entity))); assertEquals(entity, written); input.close(); } @@ -210,16 +205,16 @@ public class EntityTest extends AbstractTest { private void mediaEntity(final ContentType contentType) throws Exception { final InputStream input = getClass().getResourceAsStream( "Advertisements_f89dee73-af9f-4cd4-b330-db93c25ff3c7." + getSuffix(contentType)); - final ClientEntity entity = getClient().getBinder().getODataEntity( - getClient().getDeserializer(contentType).toEntity(input)); + final ClientEntity entity = client.getBinder().getODataEntity( + client.getDeserializer(contentType).toEntity(input)); assertNotNull(entity); assertTrue(entity.isMediaEntity()); assertNotNull(entity.getMediaContentSource()); assertEquals("\"8zOOKKvgOtptr4gt8IrnapX3jds=\"", entity.getMediaETag()); - final ClientEntity written = getClient().getBinder().getODataEntity( - new ResWrap((URI) null, null, getClient().getBinder().getEntity(entity))); + final ClientEntity written = client.getBinder().getODataEntity( + new ResWrap((URI) null, null, client.getBinder().getEntity(entity))); assertEquals(entity, written); input.close(); } @@ -236,8 +231,8 @@ public class EntityTest extends AbstractTest { private void withStream(final ContentType contentType) throws Exception { final InputStream input = getClass().getResourceAsStream("PersonDetails_1." + getSuffix(contentType)); - final ClientEntity entity = getClient().getBinder().getODataEntity( - getClient().getDeserializer(contentType).toEntity(input)); + final ClientEntity entity = client.getBinder().getODataEntity( + client.getDeserializer(contentType).toEntity(input)); assertNotNull(entity); assertFalse(entity.isMediaEntity()); @@ -245,8 +240,8 @@ public class EntityTest extends AbstractTest { final ClientLink editMedia = entity.getMediaEditLink("Photo"); assertNotNull(editMedia); - final ClientEntity written = getClient().getBinder().getODataEntity( - new ResWrap((URI) null, null, getClient().getBinder().getEntity(entity))); + final ClientEntity written = client.getBinder().getODataEntity( + new ResWrap((URI) null, null, client.getBinder().getEntity(entity))); assertEquals(entity, written); input.close(); } @@ -263,14 +258,14 @@ public class EntityTest extends AbstractTest { private void ref(final ContentType contentType) throws Exception { final InputStream input = getClass().getResourceAsStream("entityReference." + getSuffix(contentType)); - final ClientEntity entity = getClient().getBinder().getODataEntity( - getClient().getDeserializer(contentType).toEntity(input)); + final ClientEntity entity = client.getBinder().getODataEntity( + client.getDeserializer(contentType).toEntity(input)); assertNotNull(entity); assertNotNull(entity.getId()); - final ClientEntity written = getClient().getBinder().getODataEntity( - new ResWrap((URI) null, null, getClient().getBinder().getEntity(entity))); + final ClientEntity written = client.getBinder().getODataEntity( + new ResWrap((URI) null, null, client.getBinder().getEntity(entity))); assertEquals(entity, written); input.close(); } @@ -287,8 +282,8 @@ public class EntityTest extends AbstractTest { private void complexNavigationProperties(final ContentType contentType) throws Exception { final InputStream input = getClass().getResourceAsStream("entity.withcomplexnavigation." + getSuffix(contentType)); - final ClientEntity entity = getClient().getBinder().getODataEntity( - getClient().getDeserializer(contentType).toEntity(input)); + final ClientEntity entity = client.getBinder().getODataEntity( + client.getDeserializer(contentType).toEntity(input)); assertNotNull(entity); final ClientComplexValue addressValue = entity.getProperty("Address").getComplexValue(); @@ -297,8 +292,8 @@ public class EntityTest extends AbstractTest { // ETag is not serialized entity.setETag(null); - final ClientEntity written = getClient().getBinder().getODataEntity( - new ResWrap((URI) null, null, getClient().getBinder().getEntity(entity))); + final ClientEntity written = client.getBinder().getODataEntity( + new ResWrap((URI) null, null, client.getBinder().getEntity(entity))); assertEquals(entity, written); input.close(); } @@ -315,8 +310,8 @@ public class EntityTest extends AbstractTest { private void annotated(final ContentType contentType) throws EdmPrimitiveTypeException, Exception { final InputStream input = getClass().getResourceAsStream("annotated." + getSuffix(contentType)); - final ClientEntity entity = getClient().getBinder().getODataEntity( - getClient().getDeserializer(contentType).toEntity(input)); + final ClientEntity entity = client.getBinder().getODataEntity( + client.getDeserializer(contentType).toEntity(input)); assertNotNull(entity); assertFalse(entity.getAnnotations().isEmpty()); @@ -343,8 +338,8 @@ public class EntityTest extends AbstractTest { assertEquals(2, annotation.getValue().asComplex().get("order").getPrimitiveValue().toCastValue(Integer.class), 0); - final ClientEntity written = getClient().getBinder().getODataEntity( - new ResWrap((URI) null, null, getClient().getBinder().getEntity(entity))); + final ClientEntity written = client.getBinder().getODataEntity( + new ResWrap((URI) null, null, client.getBinder().getEntity(entity))); assertEquals(entity, written); input.close(); } @@ -374,7 +369,7 @@ public class EntityTest extends AbstractTest { @Test public void derivedFromAtom() throws Exception { - derived(getClient(), ContentType.APPLICATION_ATOM_XML); + derived(client, ContentType.APPLICATION_ATOM_XML); } @Test @@ -384,6 +379,6 @@ public class EntityTest extends AbstractTest { @Test public void derivedFromFullJSON() throws Exception { - derived(getClient(), ContentType.JSON_FULL_METADATA); + derived(client, ContentType.JSON_FULL_METADATA); } } diff --git a/lib/client-core/src/test/java/org/apache/olingo/client/core/ErrorTest.java b/lib/client-core/src/test/java/org/apache/olingo/client/core/ErrorTest.java index 8ced6a342..60bbcd047 100644 --- a/lib/client-core/src/test/java/org/apache/olingo/client/core/ErrorTest.java +++ b/lib/client-core/src/test/java/org/apache/olingo/client/core/ErrorTest.java @@ -21,7 +21,6 @@ package org.apache.olingo.client.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import org.apache.olingo.client.api.ODataClient; import org.apache.olingo.client.api.serialization.ODataDeserializerException; import org.apache.olingo.commons.api.ex.ODataError; import org.apache.olingo.commons.api.format.ContentType; @@ -29,13 +28,8 @@ import org.junit.Test; public class ErrorTest extends AbstractTest { - @Override - protected ODataClient getClient() { - return v4Client; - } - private ODataError error(final String name, final ContentType contentType) throws ODataDeserializerException { - final ODataError error = getClient().getDeserializer(contentType).toError( + final ODataError error = client.getDeserializer(contentType).toError( getClass().getResourceAsStream(name + "." + getSuffix(contentType))); assertNotNull(error); return error; diff --git a/lib/client-core/src/test/java/org/apache/olingo/client/core/JSONTest.java b/lib/client-core/src/test/java/org/apache/olingo/client/core/JSONTest.java index 92732297c..a276c4feb 100644 --- a/lib/client-core/src/test/java/org/apache/olingo/client/core/JSONTest.java +++ b/lib/client-core/src/test/java/org/apache/olingo/client/core/JSONTest.java @@ -30,7 +30,6 @@ import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; -import org.apache.olingo.client.api.ODataClient; import org.apache.olingo.client.api.domain.ClientCollectionValue; import org.apache.olingo.client.api.domain.ClientComplexValue; import org.apache.olingo.client.api.domain.ClientEntity; @@ -50,11 +49,6 @@ public class JSONTest extends AbstractTest { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - @Override - protected ODataClient getClient() { - return v4Client; - } - protected ContentType getODataPubFormat() { return ContentType.JSON; } @@ -129,7 +123,7 @@ public class JSONTest extends AbstractTest { protected void entitySet(final String filename, final ContentType contentType) throws Exception { final StringWriter writer = new StringWriter(); - getClient().getSerializer(contentType).write(writer, getClient().getDeserializer(contentType).toEntitySet( + client.getSerializer(contentType).write(writer, client.getDeserializer(contentType).toEntitySet( getClass().getResourceAsStream(filename + "." + getSuffix(contentType))).getPayload()); assertSimilar(filename + "." + getSuffix(contentType), writer.toString()); @@ -143,7 +137,7 @@ public class JSONTest extends AbstractTest { protected void entity(final String filename, final ContentType contentType) throws Exception { final StringWriter writer = new StringWriter(); - getClient().getSerializer(contentType).write(writer, getClient().getDeserializer(contentType).toEntity( + client.getSerializer(contentType).write(writer, client.getDeserializer(contentType).toEntity( getClass().getResourceAsStream(filename + "." + getSuffix(contentType))).getPayload()); assertSimilar(filename + "." + getSuffix(contentType), writer.toString()); } @@ -169,7 +163,7 @@ public class JSONTest extends AbstractTest { protected void property(final String filename, final ContentType contentType) throws Exception { final StringWriter writer = new StringWriter(); - getClient().getSerializer(contentType).write(writer, getClient().getDeserializer(contentType). + client.getSerializer(contentType).write(writer, client.getDeserializer(contentType). toProperty(getClass().getResourceAsStream(filename + "." + getSuffix(contentType))).getPayload()); assertSimilar(filename + "." + getSuffix(contentType), writer.toString()); @@ -185,12 +179,12 @@ public class JSONTest extends AbstractTest { @Test public void crossjoin() throws Exception { - assertNotNull(getClient().getDeserializer(ContentType.JSON_FULL_METADATA).toEntitySet( + assertNotNull(client.getDeserializer(ContentType.JSON_FULL_METADATA).toEntitySet( getClass().getResourceAsStream("crossjoin.json"))); } protected void delta(final String filename, final ContentType contentType) throws Exception { - final Delta delta = getClient().getDeserializer(contentType).toDelta( + final Delta delta = client.getDeserializer(contentType).toDelta( getClass().getResourceAsStream(filename + "." + getSuffix(contentType))).getPayload(); assertNotNull(delta); assertNotNull(delta.getDeltaLink()); @@ -223,30 +217,30 @@ public class JSONTest extends AbstractTest { @Test public void issueOLINGO390() throws Exception { - final ClientEntity message = getClient().getObjectFactory(). + final ClientEntity message = client.getObjectFactory(). newEntity(new FullQualifiedName("Microsoft.Exchange.Services.OData.Model.Message")); - final ClientComplexValue toRecipient = getClient().getObjectFactory(). + final ClientComplexValue toRecipient = client.getObjectFactory(). newComplexValue("Microsoft.Exchange.Services.OData.Model.Recipient"); - toRecipient.add(getClient().getObjectFactory().newPrimitiveProperty("Name", - getClient().getObjectFactory().newPrimitiveValueBuilder().buildString("challen_olingo_client"))); - toRecipient.add(getClient().getObjectFactory().newPrimitiveProperty("Address", - getClient().getObjectFactory().newPrimitiveValueBuilder().buildString("challenh@microsoft.com"))); - final ClientCollectionValue toRecipients = getClient().getObjectFactory(). + toRecipient.add(client.getObjectFactory().newPrimitiveProperty("Name", + client.getObjectFactory().newPrimitiveValueBuilder().buildString("challen_olingo_client"))); + toRecipient.add(client.getObjectFactory().newPrimitiveProperty("Address", + client.getObjectFactory().newPrimitiveValueBuilder().buildString("challenh@microsoft.com"))); + final ClientCollectionValue toRecipients = client.getObjectFactory(). newCollectionValue("Microsoft.Exchange.Services.OData.Model.Recipient"); toRecipients.add(toRecipient); - message.getProperties().add(getClient().getObjectFactory().newCollectionProperty("ToRecipients", toRecipients)); + message.getProperties().add(client.getObjectFactory().newCollectionProperty("ToRecipients", toRecipients)); final ClientComplexValue body = - getClient().getObjectFactory().newComplexValue("Microsoft.Exchange.Services.OData.Model.ItemBody"); - body.add(getClient().getObjectFactory().newPrimitiveProperty("Content", - getClient().getObjectFactory().newPrimitiveValueBuilder(). + client.getObjectFactory().newComplexValue("Microsoft.Exchange.Services.OData.Model.ItemBody"); + body.add(client.getObjectFactory().newPrimitiveProperty("Content", + client.getObjectFactory().newPrimitiveValueBuilder(). buildString("this is a simple email body content"))); - body.add(getClient().getObjectFactory().newEnumProperty("ContentType", - getClient().getObjectFactory().newEnumValue("Microsoft.Exchange.Services.OData.Model.BodyType", "text"))); - message.getProperties().add(getClient().getObjectFactory().newComplexProperty("Body", body)); + body.add(client.getObjectFactory().newEnumProperty("ContentType", + client.getObjectFactory().newEnumValue("Microsoft.Exchange.Services.OData.Model.BodyType", "text"))); + message.getProperties().add(client.getObjectFactory().newComplexProperty("Body", body)); - final String actual = IOUtils.toString(getClient().getWriter().writeEntity(message, ContentType.JSON)); + final String actual = IOUtils.toString(client.getWriter().writeEntity(message, ContentType.JSON)); final JsonNode expected = OBJECT_MAPPER.readTree(IOUtils.toString(getClass().getResourceAsStream("olingo390.json")). replace(Constants.JSON_NAVIGATION_LINK, Constants.JSON_BIND_LINK_SUFFIX)); diff --git a/lib/client-core/src/test/java/org/apache/olingo/client/core/MetadataTest.java b/lib/client-core/src/test/java/org/apache/olingo/client/core/MetadataTest.java index a24ca360a..c150e6482 100644 --- a/lib/client-core/src/test/java/org/apache/olingo/client/core/MetadataTest.java +++ b/lib/client-core/src/test/java/org/apache/olingo/client/core/MetadataTest.java @@ -26,7 +26,6 @@ import static org.junit.Assert.assertTrue; import java.io.InputStream; import java.util.List; -import org.apache.olingo.client.api.ODataClient; import org.apache.olingo.client.api.edm.xml.XMLMetadata; import org.apache.olingo.commons.api.Constants; import org.apache.olingo.commons.api.edm.Edm; @@ -72,14 +71,9 @@ import org.junit.Test; public class MetadataTest extends AbstractTest { - @Override - protected ODataClient getClient() { - return v4Client; - } - @Test public void parse() { - final Edm edm = getClient().getReader().readMetadata(getClass().getResourceAsStream("metadata.xml")); + final Edm edm = client.getReader().readMetadata(getClass().getResourceAsStream("metadata.xml")); assertNotNull(edm); // 1. Enum @@ -140,7 +134,7 @@ public class MetadataTest extends AbstractTest { @Test public void demo() { - final XMLMetadata metadata = getClient().getDeserializer(ContentType.APPLICATION_XML). + final XMLMetadata metadata = client.getDeserializer(ContentType.APPLICATION_XML). toMetadata(getClass().getResourceAsStream("demo-metadata.xml")); assertNotNull(metadata); @@ -154,7 +148,7 @@ public class MetadataTest extends AbstractTest { annots.getAnnotation("Org.OData.Publication.V1.PrivacyPolicyUrl").getExpression().asConstant().getValue()); // Now let's test some edm:Annotations - final Edm edm = getClient().getReader(). + final Edm edm = client.getReader(). readMetadata(getClass().getResourceAsStream("demo-metadata.xml")); assertNotNull(edm); @@ -181,7 +175,7 @@ public class MetadataTest extends AbstractTest { @Test public void multipleSchemas() { - final XMLMetadata metadata = getClient().getDeserializer(ContentType.APPLICATION_XML). + final XMLMetadata metadata = client.getDeserializer(ContentType.APPLICATION_XML). toMetadata(getClass().getResourceAsStream("northwind-metadata.xml")); assertNotNull(metadata); @@ -198,10 +192,10 @@ public class MetadataTest extends AbstractTest { @Test public void getContainerWithoutCallingGetSchemas() { - final XMLMetadata metadata = getClient().getDeserializer(ContentType.APPLICATION_XML). + final XMLMetadata metadata = client.getDeserializer(ContentType.APPLICATION_XML). toMetadata(getClass().getResourceAsStream("fromdoc1-metadata.xml")); - Edm edm = getClient().getReader().readMetadata(metadata.getSchemaByNsOrAlias()); + Edm edm = client.getReader().readMetadata(metadata.getSchemaByNsOrAlias()); assertNotNull(edm.getEntityContainer()); } @@ -211,7 +205,7 @@ public class MetadataTest extends AbstractTest { */ @Test public void fromdoc1() { - final XMLMetadata metadata = getClient().getDeserializer(ContentType.APPLICATION_XML). + final XMLMetadata metadata = client.getDeserializer(ContentType.APPLICATION_XML). toMetadata(getClass().getResourceAsStream("fromdoc1-metadata.xml")); assertNotNull(metadata); @@ -249,7 +243,7 @@ public class MetadataTest extends AbstractTest { functionImport.getFunction()); // Now let's go high-level - final Edm edm = getClient().getReader().readMetadata(getClass().getResourceAsStream("fromdoc1-metadata.xml")); + final Edm edm = client.getReader().readMetadata(getClass().getResourceAsStream("fromdoc1-metadata.xml")); assertNotNull(edm); List schemaList = edm.getSchemas(); @@ -291,7 +285,7 @@ public class MetadataTest extends AbstractTest { */ @Test public void fromdoc2() { - final XMLMetadata metadata = getClient().getDeserializer(ContentType.APPLICATION_XML) + final XMLMetadata metadata = client.getDeserializer(ContentType.APPLICATION_XML) .toMetadata(getClass().getResourceAsStream("fromdoc2-metadata.xml")); assertNotNull(metadata); @@ -336,7 +330,7 @@ public class MetadataTest extends AbstractTest { */ @Test public void fromdoc3() { - final Edm edm = getClient().getReader().readMetadata(getClass().getResourceAsStream("fromdoc3-metadata.xml")); + final Edm edm = client.getReader().readMetadata(getClass().getResourceAsStream("fromdoc3-metadata.xml")); assertNotNull(edm); final EdmAnnotations group = edm.getSchema("Annotations").getAnnotationGroups().get(0); @@ -354,7 +348,7 @@ public class MetadataTest extends AbstractTest { */ @Test public void fromdoc4() { - final XMLMetadata metadata = getClient().getDeserializer(ContentType.APPLICATION_XML). + final XMLMetadata metadata = client.getDeserializer(ContentType.APPLICATION_XML). toMetadata(getClass().getResourceAsStream("fromdoc4-metadata.xml")); assertNotNull(metadata); @@ -382,7 +376,7 @@ public class MetadataTest extends AbstractTest { assertTrue(urlRef.getValue().asDynamic().isApply()); // Now let's go high-level - final Edm edm = getClient().getReader().readMetadata(getClass().getResourceAsStream("fromdoc4-metadata.xml")); + final Edm edm = client.getReader().readMetadata(getClass().getResourceAsStream("fromdoc4-metadata.xml")); assertNotNull(edm); final EdmAnnotations edmGroup = edm.getSchemas().get(0).getAnnotationGroups().get(0); @@ -410,8 +404,7 @@ public class MetadataTest extends AbstractTest { @Test public void metadataWithCapabilities() throws Exception { InputStream input = getClass().getResourceAsStream("Metadata-With-Capabilities.xml"); - final XMLMetadata metadata = getClient().getDeserializer(ContentType.APPLICATION_XML). - toMetadata(input); + final XMLMetadata metadata = client.getDeserializer(ContentType.APPLICATION_XML).toMetadata(input); CsdlSchema schema = metadata.getSchema("Capabilities"); assertNotNull(schema); diff --git a/lib/client-core/src/test/java/org/apache/olingo/client/core/PrimitiveValueTest.java b/lib/client-core/src/test/java/org/apache/olingo/client/core/PrimitiveValueTest.java index f46f272a8..3c31b551a 100644 --- a/lib/client-core/src/test/java/org/apache/olingo/client/core/PrimitiveValueTest.java +++ b/lib/client-core/src/test/java/org/apache/olingo/client/core/PrimitiveValueTest.java @@ -18,31 +18,25 @@ */ package org.apache.olingo.client.core; -import org.apache.olingo.client.api.ODataClient; +import static org.junit.Assert.assertEquals; + +import java.util.Calendar; + import org.apache.olingo.client.api.domain.ClientValue; import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException; import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; import org.junit.Test; -import java.util.Calendar; - -import static org.junit.Assert.assertEquals; - public class PrimitiveValueTest extends AbstractTest { - @Override - protected ODataClient getClient() { - return v4Client; - } - @Test public void timeOfDay() throws EdmPrimitiveTypeException { final Calendar expected = Calendar.getInstance(); expected.clear(); expected.set(2013, 0, 10, 21, 45, 17); - final ClientValue value = getClient().getObjectFactory().newPrimitiveValueBuilder(). - setType(EdmPrimitiveTypeKind.TimeOfDay).setValue(expected).build(); + final ClientValue value = client.getObjectFactory().newPrimitiveValueBuilder() + .setType(EdmPrimitiveTypeKind.TimeOfDay).setValue(expected).build(); assertEquals(EdmPrimitiveTypeKind.TimeOfDay, value.asPrimitive().getTypeKind()); final Calendar actual = value.asPrimitive().toCastValue(Calendar.class); @@ -59,8 +53,8 @@ public class PrimitiveValueTest extends AbstractTest { expected.clear(); expected.set(2013, 0, 10); - final ClientValue value = getClient().getObjectFactory().newPrimitiveValueBuilder(). - setType(EdmPrimitiveTypeKind.Date).setValue(expected).build(); + final ClientValue value = client.getObjectFactory().newPrimitiveValueBuilder() + .setType(EdmPrimitiveTypeKind.Date).setValue(expected).build(); assertEquals(EdmPrimitiveTypeKind.Date, value.asPrimitive().getTypeKind()); final Calendar actual = value.asPrimitive().toCastValue(Calendar.class); diff --git a/lib/client-core/src/test/java/org/apache/olingo/client/core/PropertyTest.java b/lib/client-core/src/test/java/org/apache/olingo/client/core/PropertyTest.java index a545dc2ee..e7dc9ce56 100644 --- a/lib/client-core/src/test/java/org/apache/olingo/client/core/PropertyTest.java +++ b/lib/client-core/src/test/java/org/apache/olingo/client/core/PropertyTest.java @@ -25,35 +25,29 @@ import static org.junit.Assert.assertTrue; import java.io.InputStream; import java.util.Iterator; -import org.apache.olingo.client.api.ODataClient; import org.apache.olingo.client.api.domain.ClientCollectionValue; import org.apache.olingo.client.api.domain.ClientComplexValue; import org.apache.olingo.client.api.domain.ClientProperty; import org.apache.olingo.client.api.domain.ClientValue; -import org.apache.olingo.commons.api.format.ContentType; import org.apache.olingo.client.api.serialization.ODataDeserializerException; import org.apache.olingo.client.api.serialization.ODataSerializerException; +import org.apache.olingo.commons.api.format.ContentType; import org.junit.Test; public class PropertyTest extends AbstractTest { - @Override - protected ODataClient getClient() { - return v4Client; - } - private void _enum(final ContentType contentType) throws ODataDeserializerException, ODataSerializerException { final InputStream input = getClass().getResourceAsStream("Products_5_SkinColor." + getSuffix(contentType)); - final ClientProperty property = getClient().getReader().readProperty(input, contentType); + final ClientProperty property = client.getReader().readProperty(input, contentType); assertNotNull(property); assertTrue(property.hasEnumValue()); - final ClientProperty written = getClient().getReader().readProperty( - getClient().getWriter().writeProperty(property, contentType), contentType); + final ClientProperty written = client.getReader().readProperty( + client.getWriter().writeProperty(property, contentType), contentType); // This is needed because type information gets lost with serialization if (contentType.isCompatible(ContentType.APPLICATION_XML)) { - final ClientProperty comparable = getClient().getObjectFactory().newEnumProperty(property.getName(), - getClient().getObjectFactory(). + final ClientProperty comparable = client.getObjectFactory().newEnumProperty(property.getName(), + client.getObjectFactory(). newEnumValue(property.getEnumValue().getTypeName(), written.getEnumValue().getValue())); assertEquals(property, comparable); @@ -72,21 +66,21 @@ public class PropertyTest extends AbstractTest { private void complex(final ContentType contentType) throws ODataDeserializerException, ODataSerializerException { final InputStream input = getClass().getResourceAsStream("Employees_3_HomeAddress." + getSuffix(contentType)); - final ClientProperty property = getClient().getReader().readProperty(input, contentType); + final ClientProperty property = client.getReader().readProperty(input, contentType); assertNotNull(property); assertTrue(property.hasComplexValue()); assertEquals(3, property.getComplexValue().size()); - final ClientProperty written = getClient().getReader().readProperty( - getClient().getWriter().writeProperty(property, contentType), contentType); + final ClientProperty written = client.getReader().readProperty( + client.getWriter().writeProperty(property, contentType), contentType); // This is needed because type information gets lost with JSON serialization - final ClientComplexValue typedValue = getClient().getObjectFactory(). + final ClientComplexValue typedValue = client.getObjectFactory(). newComplexValue(property.getComplexValue().getTypeName()); for (final Iterator itor = written.getComplexValue().iterator(); itor.hasNext();) { final ClientProperty prop = itor.next(); typedValue.add(prop); } - final ClientProperty comparable = getClient().getObjectFactory(). + final ClientProperty comparable = client.getObjectFactory(). newComplexProperty(property.getName(), typedValue); assertEquals(property, comparable); @@ -104,22 +98,22 @@ public class PropertyTest extends AbstractTest { private void collection(final ContentType contentType) throws ODataDeserializerException, ODataSerializerException { final InputStream input = getClass().getResourceAsStream("Products_5_CoverColors." + getSuffix(contentType)); - final ClientProperty property = getClient().getReader().readProperty(input, contentType); + final ClientProperty property = client.getReader().readProperty(input, contentType); assertNotNull(property); assertTrue(property.hasCollectionValue()); assertEquals(3, property.getCollectionValue().size()); - final ClientProperty written = getClient().getReader().readProperty( - getClient().getWriter().writeProperty(property, contentType), contentType); + final ClientProperty written = client.getReader().readProperty( + client.getWriter().writeProperty(property, contentType), contentType); // This is needed because type information gets lost with JSON serialization if(contentType.isCompatible(ContentType.APPLICATION_XML)) { - final ClientCollectionValue typedValue = getClient().getObjectFactory(). + final ClientCollectionValue typedValue = client.getObjectFactory(). newCollectionValue(property.getCollectionValue().getTypeName()); for (final Iterator itor = written.getCollectionValue().iterator(); itor.hasNext();) { final ClientValue value = itor.next(); typedValue.add(value); } - final ClientProperty comparable = getClient().getObjectFactory(). + final ClientProperty comparable = client.getObjectFactory(). newCollectionProperty(property.getName(), typedValue); assertEquals(property, comparable); diff --git a/lib/client-core/src/test/java/org/apache/olingo/client/core/ServiceDocumentTest.java b/lib/client-core/src/test/java/org/apache/olingo/client/core/ServiceDocumentTest.java index ae06f9052..7a66facf0 100644 --- a/lib/client-core/src/test/java/org/apache/olingo/client/core/ServiceDocumentTest.java +++ b/lib/client-core/src/test/java/org/apache/olingo/client/core/ServiceDocumentTest.java @@ -24,7 +24,6 @@ import static org.junit.Assert.assertTrue; import java.net.URI; -import org.apache.olingo.client.api.ODataClient; import org.apache.olingo.client.api.data.ResWrap; import org.apache.olingo.client.api.data.ServiceDocument; import org.apache.olingo.client.api.domain.ClientServiceDocument; @@ -34,23 +33,14 @@ import org.junit.Test; public class ServiceDocumentTest extends AbstractTest { - @Override - protected ODataClient getClient() { - return v4Client; - } - - private String getFileExtension(final ContentType contentType) { - return contentType.isCompatible(ContentType.APPLICATION_XML) ? "xml" : "json"; - } - private ClientServiceDocument parse(final ContentType contentType) throws ODataDeserializerException { - ResWrap service = getClient().getDeserializer(contentType).toServiceDocument( - getClass().getResourceAsStream("serviceDocument." + getFileExtension(contentType))); + ResWrap service = client.getDeserializer(contentType).toServiceDocument( + getClass().getResourceAsStream("serviceDocument." + getSuffix(contentType))); assertEquals(URI.create("http://host/service/$metadata"), service.getContextURL()); assertEquals("W/\"MjAxMy0wNS0xM1QxNDo1NFo=\"", service.getMetadataETag()); - final ClientServiceDocument serviceDocument = getClient().getBinder().getODataServiceDocument(service.getPayload()); + final ClientServiceDocument serviceDocument = client.getBinder().getODataServiceDocument(service.getPayload()); assertNotNull(serviceDocument); assertTrue(serviceDocument.getEntitySetNames().contains("Order Details")); diff --git a/lib/client-core/src/test/java/org/apache/olingo/client/core/uri/FilterFactoryTest.java b/lib/client-core/src/test/java/org/apache/olingo/client/core/uri/FilterFactoryTest.java index 1d26f814d..3b2c29405 100644 --- a/lib/client-core/src/test/java/org/apache/olingo/client/core/uri/FilterFactoryTest.java +++ b/lib/client-core/src/test/java/org/apache/olingo/client/core/uri/FilterFactoryTest.java @@ -25,7 +25,6 @@ import java.net.URLEncoder; import java.util.Calendar; import java.util.TimeZone; -import org.apache.olingo.client.api.ODataClient; import org.apache.olingo.client.api.uri.FilterArgFactory; import org.apache.olingo.client.api.uri.FilterFactory; import org.apache.olingo.client.api.uri.URIFilter; @@ -39,13 +38,8 @@ import org.junit.Test; public class FilterFactoryTest extends AbstractTest { - @Override - protected ODataClient getClient() { - return v4Client; - } - private FilterFactory getFilterFactory() { - return getClient().getFilterFactory(); + return client.getFilterFactory(); } private FilterArgFactory getFilterArgFactory() { diff --git a/lib/client-core/src/test/java/org/apache/olingo/client/core/uri/URIBuilderTest.java b/lib/client-core/src/test/java/org/apache/olingo/client/core/uri/URIBuilderTest.java index 2af662f14..5f9cc8bba 100644 --- a/lib/client-core/src/test/java/org/apache/olingo/client/core/uri/URIBuilderTest.java +++ b/lib/client-core/src/test/java/org/apache/olingo/client/core/uri/URIBuilderTest.java @@ -26,32 +26,25 @@ import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; -import org.apache.olingo.client.api.ODataClient; import org.apache.olingo.client.api.uri.QueryOption; import org.apache.olingo.client.api.uri.URIBuilder; import org.apache.olingo.client.core.AbstractTest; -import org.apache.olingo.client.core.uri.ParameterAlias; import org.junit.Test; public class URIBuilderTest extends AbstractTest { private static final String SERVICE_ROOT = "http://host/service"; - @Override - protected ODataClient getClient() { - return v4Client; - } - @Test public void metadata() throws URISyntaxException { - final URI uri = getClient().newURIBuilder(SERVICE_ROOT).appendMetadataSegment().build(); + final URI uri = client.newURIBuilder(SERVICE_ROOT).appendMetadataSegment().build(); assertEquals(new org.apache.http.client.utils.URIBuilder(SERVICE_ROOT + "/$metadata").build(), uri); } @Test public void entity() throws URISyntaxException { - final URI uri = getClient().newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("AnEntitySet"). + final URI uri = client.newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("AnEntitySet"). appendKeySegment(11).build(); assertEquals(new org.apache.http.client.utils.URIBuilder(SERVICE_ROOT + "/AnEntitySet(11)").build(), uri); @@ -59,21 +52,21 @@ public class URIBuilderTest extends AbstractTest { final Map multiKey = new LinkedHashMap(); multiKey.put("OrderId", -10); multiKey.put("ProductId", -10); - URIBuilder uriBuilder = getClient().newURIBuilder(SERVICE_ROOT). + URIBuilder uriBuilder = client.newURIBuilder(SERVICE_ROOT). appendEntitySetSegment("OrderLine").appendKeySegment(multiKey). appendPropertySegment("Quantity").appendValueSegment(); assertEquals(new org.apache.http.client.utils.URIBuilder( SERVICE_ROOT + "/OrderLine(OrderId=-10,ProductId=-10)/Quantity/$value").build(), uriBuilder.build()); - uriBuilder = getClient().newURIBuilder(SERVICE_ROOT). + uriBuilder = client.newURIBuilder(SERVICE_ROOT). appendEntitySetSegment("Customer").appendKeySegment(-10). select("CustomerId", "Name", "Orders").expand("Orders"); assertEquals(new org.apache.http.client.utils.URIBuilder(SERVICE_ROOT + "/Customer(-10)"). addParameter("$select", "CustomerId,Name,Orders").addParameter("$expand", "Orders").build(), uriBuilder.build()); - uriBuilder = getClient().newURIBuilder(SERVICE_ROOT). + uriBuilder = client.newURIBuilder(SERVICE_ROOT). appendEntitySetSegment("Customer").appendKeySegment(-10).appendNavigationSegment("Orders").appendRefSegment(); assertEquals(new org.apache.http.client.utils.URIBuilder(SERVICE_ROOT + "/Customer(-10)/Orders/$ref").build(), uriBuilder.build()); @@ -81,7 +74,7 @@ public class URIBuilderTest extends AbstractTest { @Test public void expandWithOptions() throws URISyntaxException { - final URI uri = getClient().newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("Products").appendKeySegment(5). + final URI uri = client.newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("Products").appendKeySegment(5). expandWithOptions("ProductDetails", new LinkedHashMap() { private static final long serialVersionUID = 3109256773218160485L; @@ -96,7 +89,7 @@ public class URIBuilderTest extends AbstractTest { } public void expandWithLevels() throws URISyntaxException { - final URI uri = getClient().newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("Products").appendKeySegment(1). + final URI uri = client.newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("Products").appendKeySegment(1). expandWithOptions("Customer", Collections. singletonMap(QueryOption.LEVELS, 4)). build(); @@ -106,11 +99,11 @@ public class URIBuilderTest extends AbstractTest { @Test public void count() throws URISyntaxException { - URI uri = getClient().newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("Products").count().build(); + URI uri = client.newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("Products").count().build(); assertEquals(new org.apache.http.client.utils.URIBuilder(SERVICE_ROOT + "/Products/$count").build(), uri); - uri = getClient().newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("Products").count(true).build(); + uri = client.newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("Products").count(true).build(); assertEquals(new org.apache.http.client.utils.URIBuilder(SERVICE_ROOT + "/Products"). addParameter("$count", "true").build(), uri); @@ -118,34 +111,34 @@ public class URIBuilderTest extends AbstractTest { @Test public void filter() throws URISyntaxException { - final URIBuilder uriBuilder = getClient().newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("AnEntitySet"). - filter(getClient().getFilterFactory().lt("VIN", 16)); + final URIBuilder uriBuilder = client.newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("AnEntitySet"). + filter(client.getFilterFactory().lt("VIN", 16)); assertEquals("http://host/service/AnEntitySet?%24filter=%28VIN%20lt%2016%29", uriBuilder.build().toASCIIString()); -// assertEquals(new org.apache.http.client.utils.URIBuilder(SERVICE_ROOT + "/AnEntitySet"). -// addParameter("$filter", "(VIN lt 16)").build(), -// uriBuilder.build()); + // assertEquals(new org.apache.http.client.utils.URIBuilder(SERVICE_ROOT + "/AnEntitySet"). + // addParameter("$filter", "(VIN lt 16)").build(), + // uriBuilder.build()); } @Test public void filterWithParameter() throws URISyntaxException { // http://host/service.svc/Employees?$filter=Region eq @p1&@p1='WA' - final URIBuilder uriBuilder = getClient().newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("Employees"). - filter(getClient().getFilterFactory().eq("Region", new ParameterAlias("p1"))). + final URIBuilder uriBuilder = client.newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("Employees"). + filter(client.getFilterFactory().eq("Region", new ParameterAlias("p1"))). addParameterAlias("p1", "'WA'"); assertEquals("http://host/service/Employees?%24filter=%28Region%20eq%20%40p1%29&%40p1='WA'", uriBuilder.build() .toASCIIString()); -// assertEquals(new org.apache.http.client.utils.URIBuilder(SERVICE_ROOT + "/Employees"). -// addParameter("$filter", "(Region eq @p1)").addParameter("@p1", "'WA'").build(), -// uriBuilder.build()); + // assertEquals(new org.apache.http.client.utils.URIBuilder(SERVICE_ROOT + "/Employees"). + // addParameter("$filter", "(Region eq @p1)").addParameter("@p1", "'WA'").build(), + // uriBuilder.build()); } @Test public void expandMoreThenOnce() throws URISyntaxException { - URI uri = getClient().newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("Products").appendKeySegment(5). + URI uri = client.newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("Products").appendKeySegment(5). expand("Orders", "Customers").expand("Info").build(); assertEquals(new org.apache.http.client.utils.URIBuilder(SERVICE_ROOT + "/Products(5)"). @@ -154,7 +147,7 @@ public class URIBuilderTest extends AbstractTest { @Test public void selectMoreThenOnce() throws URISyntaxException { - URI uri = getClient().newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("Customers").appendKeySegment(5). + URI uri = client.newURIBuilder(SERVICE_ROOT).appendEntitySetSegment("Customers").appendKeySegment(5). select("Name", "Surname").expand("Info").select("Gender").build(); assertEquals(new org.apache.http.client.utils.URIBuilder(SERVICE_ROOT + "/Customers(5)"). @@ -163,7 +156,7 @@ public class URIBuilderTest extends AbstractTest { @Test public void singleton() throws URISyntaxException { - final URIBuilder uriBuilder = getClient().newURIBuilder(SERVICE_ROOT). + final URIBuilder uriBuilder = client.newURIBuilder(SERVICE_ROOT). appendSingletonSegment("BestProductEverCreated"); assertEquals(new org.apache.http.client.utils.URIBuilder( @@ -172,7 +165,7 @@ public class URIBuilderTest extends AbstractTest { @Test public void entityId() throws URISyntaxException { - final URIBuilder uriBuilder = getClient().newURIBuilder(SERVICE_ROOT). + final URIBuilder uriBuilder = client.newURIBuilder(SERVICE_ROOT). appendEntityIdSegment("Products(0)"); assertEquals(new org.apache.http.client.utils.URIBuilder( @@ -181,7 +174,7 @@ public class URIBuilderTest extends AbstractTest { @Test public void boundAction() throws URISyntaxException { - final URIBuilder uriBuilder = getClient().newURIBuilder(SERVICE_ROOT). + final URIBuilder uriBuilder = client.newURIBuilder(SERVICE_ROOT). appendEntitySetSegment("Categories").appendKeySegment(1). appendNavigationSegment("Products"). appendActionCallSegment("Model.AllOrders"); @@ -189,10 +182,10 @@ public class URIBuilderTest extends AbstractTest { assertEquals(new org.apache.http.client.utils.URIBuilder( SERVICE_ROOT + "/Categories(1)/Products/Model.AllOrders").build(), uriBuilder.build()); } - + @Test public void boundOperation() throws URISyntaxException { - final URIBuilder uriBuilder = getClient().newURIBuilder(SERVICE_ROOT). + final URIBuilder uriBuilder = client.newURIBuilder(SERVICE_ROOT). appendEntitySetSegment("Categories").appendKeySegment(1). appendNavigationSegment("Products"). appendOperationCallSegment("Model.AllOrders"); @@ -203,14 +196,14 @@ public class URIBuilderTest extends AbstractTest { @Test public void ref() throws URISyntaxException { - URIBuilder uriBuilder = getClient().newURIBuilder(SERVICE_ROOT). + URIBuilder uriBuilder = client.newURIBuilder(SERVICE_ROOT). appendEntitySetSegment("Categories").appendKeySegment(1). appendNavigationSegment("Products").appendRefSegment(); assertEquals(new org.apache.http.client.utils.URIBuilder( SERVICE_ROOT + "/Categories(1)/Products/$ref").build(), uriBuilder.build()); - uriBuilder = getClient().newURIBuilder(SERVICE_ROOT). + uriBuilder = client.newURIBuilder(SERVICE_ROOT). appendEntitySetSegment("Categories").appendKeySegment(1). appendNavigationSegment("Products").appendRefSegment().id("../../Products(0)"); @@ -221,7 +214,7 @@ public class URIBuilderTest extends AbstractTest { @Test public void derived() throws URISyntaxException { - final URIBuilder uriBuilder = getClient().newURIBuilder(SERVICE_ROOT). + final URIBuilder uriBuilder = client.newURIBuilder(SERVICE_ROOT). appendEntitySetSegment("Customers").appendDerivedEntityTypeSegment("Model.VipCustomer").appendKeySegment(1); assertEquals(new org.apache.http.client.utils.URIBuilder( @@ -230,7 +223,7 @@ public class URIBuilderTest extends AbstractTest { @Test public void crossjoin() throws URISyntaxException { - final URIBuilder uriBuilder = getClient().newURIBuilder(SERVICE_ROOT). + final URIBuilder uriBuilder = client.newURIBuilder(SERVICE_ROOT). appendCrossjoinSegment("Products", "Sales"); assertEquals(new org.apache.http.client.utils.URIBuilder( @@ -239,7 +232,7 @@ public class URIBuilderTest extends AbstractTest { @Test public void all() throws URISyntaxException { - final URIBuilder uriBuilder = getClient().newURIBuilder(SERVICE_ROOT).appendAllSegment(); + final URIBuilder uriBuilder = client.newURIBuilder(SERVICE_ROOT).appendAllSegment(); assertEquals(new org.apache.http.client.utils.URIBuilder( SERVICE_ROOT + "/$all").build(), uriBuilder.build()); @@ -247,7 +240,7 @@ public class URIBuilderTest extends AbstractTest { @Test public void search() throws URISyntaxException { - final URIBuilder uriBuilder = getClient().newURIBuilder(SERVICE_ROOT). + final URIBuilder uriBuilder = client.newURIBuilder(SERVICE_ROOT). appendEntitySetSegment("Products").search("blue OR green"); assertEquals(new URI("http://host/service/Products?%24search=blue%20OR%20green"), uriBuilder.build()); diff --git a/lib/commons-api/src/main/java/org/apache/olingo/commons/api/edm/geo/Geospatial.java b/lib/commons-api/src/main/java/org/apache/olingo/commons/api/edm/geo/Geospatial.java index 63d8b3fa7..860cbcca5 100644 --- a/lib/commons-api/src/main/java/org/apache/olingo/commons/api/edm/geo/Geospatial.java +++ b/lib/commons-api/src/main/java/org/apache/olingo/commons/api/edm/geo/Geospatial.java @@ -72,7 +72,6 @@ public abstract class Geospatial { * The OGIS geometry type number for feature collections. */ GEOSPATIALCOLLECTION - } protected final Dimension dimension; @@ -87,8 +86,8 @@ public abstract class Geospatial { /** * Constructor. * - * @param dimension dimension. - * @param type type. + * @param dimension dimension + * @param type type * @param srid SRID */ protected Geospatial(final Dimension dimension, final Type type, final SRID srid) { @@ -129,7 +128,7 @@ public abstract class Geospatial { /** * Returns the {@link EdmPrimitiveTypeKind} - * @return Edm primitve type kind + * @return EDM primitive type kind */ public abstract EdmPrimitiveTypeKind getEdmPrimitiveTypeKind(); } diff --git a/lib/commons-core/src/main/java/org/apache/olingo/commons/core/edm/EdmNavigationPropertyImpl.java b/lib/commons-core/src/main/java/org/apache/olingo/commons/core/edm/EdmNavigationPropertyImpl.java index bf5dbc66c..05abab9f1 100644 --- a/lib/commons-core/src/main/java/org/apache/olingo/commons/core/edm/EdmNavigationPropertyImpl.java +++ b/lib/commons-core/src/main/java/org/apache/olingo/commons/core/edm/EdmNavigationPropertyImpl.java @@ -23,7 +23,6 @@ import java.util.Collections; import java.util.List; import org.apache.olingo.commons.api.edm.Edm; -import org.apache.olingo.commons.api.edm.EdmElement; import org.apache.olingo.commons.api.edm.EdmEntityType; import org.apache.olingo.commons.api.edm.EdmException; import org.apache.olingo.commons.api.edm.EdmNavigationProperty; @@ -32,7 +31,7 @@ import org.apache.olingo.commons.api.edm.EdmStructuredType; import org.apache.olingo.commons.api.edm.provider.CsdlNavigationProperty; import org.apache.olingo.commons.api.edm.provider.CsdlReferentialConstraint; -public class EdmNavigationPropertyImpl extends AbstractEdmNamed implements EdmElement, EdmNavigationProperty { +public class EdmNavigationPropertyImpl extends AbstractEdmNamed implements EdmNavigationProperty { private final CsdlNavigationProperty navigationProperty; private List referentialConstraints; diff --git a/lib/commons-core/src/main/java/org/apache/olingo/commons/core/edm/EdmParameterImpl.java b/lib/commons-core/src/main/java/org/apache/olingo/commons/core/edm/EdmParameterImpl.java index 69af130be..2f6776118 100644 --- a/lib/commons-core/src/main/java/org/apache/olingo/commons/core/edm/EdmParameterImpl.java +++ b/lib/commons-core/src/main/java/org/apache/olingo/commons/core/edm/EdmParameterImpl.java @@ -19,7 +19,6 @@ package org.apache.olingo.commons.core.edm; import org.apache.olingo.commons.api.edm.Edm; -import org.apache.olingo.commons.api.edm.EdmElement; import org.apache.olingo.commons.api.edm.EdmException; import org.apache.olingo.commons.api.edm.EdmMapping; import org.apache.olingo.commons.api.edm.EdmParameter; @@ -27,7 +26,7 @@ import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.api.edm.geo.SRID; import org.apache.olingo.commons.api.edm.provider.CsdlParameter; -public class EdmParameterImpl extends AbstractEdmNamed implements EdmParameter, EdmElement { +public class EdmParameterImpl extends AbstractEdmNamed implements EdmParameter { private final CsdlParameter parameter; private EdmType typeImpl; diff --git a/lib/commons-core/src/main/java/org/apache/olingo/commons/core/edm/EdmPropertyImpl.java b/lib/commons-core/src/main/java/org/apache/olingo/commons/core/edm/EdmPropertyImpl.java index 5385d8a50..67d0a2110 100644 --- a/lib/commons-core/src/main/java/org/apache/olingo/commons/core/edm/EdmPropertyImpl.java +++ b/lib/commons-core/src/main/java/org/apache/olingo/commons/core/edm/EdmPropertyImpl.java @@ -19,7 +19,6 @@ package org.apache.olingo.commons.core.edm; import org.apache.olingo.commons.api.edm.Edm; -import org.apache.olingo.commons.api.edm.EdmElement; import org.apache.olingo.commons.api.edm.EdmException; import org.apache.olingo.commons.api.edm.EdmMapping; import org.apache.olingo.commons.api.edm.EdmProperty; @@ -27,7 +26,7 @@ import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.api.edm.geo.SRID; import org.apache.olingo.commons.api.edm.provider.CsdlProperty; -public class EdmPropertyImpl extends AbstractEdmNamed implements EdmProperty, EdmElement { +public class EdmPropertyImpl extends AbstractEdmNamed implements EdmProperty { private final CsdlProperty property; private EdmTypeInfo typeInfo; @@ -59,7 +58,7 @@ public class EdmPropertyImpl extends AbstractEdmNamed implements EdmProperty, Ed if (property.getType() == null) { throw new EdmException("Property " + property.getName() + " must hava a full qualified type."); } - typeInfo = new EdmTypeInfo.Builder().setEdm(edm).setTypeExpression(property.getType().toString()).build(); + typeInfo = new EdmTypeInfo.Builder().setEdm(edm).setTypeExpression(property.getType()).build(); } @Override diff --git a/lib/server-core/src/main/java/org/apache/olingo/server/core/batchhandler/BatchFacadeImpl.java b/lib/server-core/src/main/java/org/apache/olingo/server/core/batchhandler/BatchFacadeImpl.java index 9fe52c86f..98bf5638e 100644 --- a/lib/server-core/src/main/java/org/apache/olingo/server/core/batchhandler/BatchFacadeImpl.java +++ b/lib/server-core/src/main/java/org/apache/olingo/server/core/batchhandler/BatchFacadeImpl.java @@ -33,20 +33,26 @@ import org.apache.olingo.server.core.deserializer.batch.BatchParserCommon; public class BatchFacadeImpl implements BatchFacade { private final BatchPartHandler partHandler; - public BatchFacadeImpl(final ODataHandler oDataHandler, final ODataRequest request, - final BatchProcessor batchProcessor, final boolean isStrict) { + /** + * Creates a new BatchFacade. + * @param oDataHandler handler + * @param batchProcessor batch processor + * @param isStrict mode switch (currently not used) + */ + public BatchFacadeImpl(final ODataHandler oDataHandler, final BatchProcessor batchProcessor, + final boolean isStrict) { partHandler = new BatchPartHandler(oDataHandler, batchProcessor, this); } @Override - public ODataResponse handleODataRequest(final ODataRequest request) throws ODataApplicationException, - ODataLibraryException { + public ODataResponse handleODataRequest(final ODataRequest request) + throws ODataApplicationException, ODataLibraryException { return partHandler.handleODataRequest(request); } @Override - public ODataResponsePart handleBatchRequest(final BatchRequestPart request) throws ODataApplicationException, - ODataLibraryException { + public ODataResponsePart handleBatchRequest(final BatchRequestPart request) + throws ODataApplicationException, ODataLibraryException { return partHandler.handleBatchRequest(request); } diff --git a/lib/server-core/src/main/java/org/apache/olingo/server/core/batchhandler/BatchHandler.java b/lib/server-core/src/main/java/org/apache/olingo/server/core/batchhandler/BatchHandler.java index ca253dcce..121734ef2 100644 --- a/lib/server-core/src/main/java/org/apache/olingo/server/core/batchhandler/BatchHandler.java +++ b/lib/server-core/src/main/java/org/apache/olingo/server/core/batchhandler/BatchHandler.java @@ -46,7 +46,7 @@ public class BatchHandler { throws ODataApplicationException, ODataLibraryException { validateRequest(request); - final BatchFacade operation = new BatchFacadeImpl(oDataHandler, request, batchProcessor, isStrict); + final BatchFacade operation = new BatchFacadeImpl(oDataHandler, batchProcessor, isStrict); batchProcessor.processBatch(operation, request, response); }