aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDmitry Kornilov2014-07-08 12:47:06 (EDT)
committerLukas Jungmann2014-07-28 08:11:10 (EDT)
commitbbc3a38aeb5aa2bc359e1d26b4c081b2c11b8c9c (patch)
tree4aa44d4c810ed46d1d3ababd45f6a4c1732a8265
parentd24fa6f0b6f4663629dab0142bb97a56d65bce44 (diff)
downloadeclipselink.runtime-bbc3a38aeb5aa2bc359e1d26b4c081b2c11b8c9c.zip
eclipselink.runtime-bbc3a38aeb5aa2bc359e1d26b4c081b2c11b8c9c.tar.gz
eclipselink.runtime-bbc3a38aeb5aa2bc359e1d26b4c081b2c11b8c9c.tar.bz2
Bug #440531: Pageable resources implementation.
Signed-off-by: Dmitry Kornilov <dmitry.kornilov@oracle.com>
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/internal/dbws/ProviderHelper.java82
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceContext.java334
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceFactoryBase.java37
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/annotations/RestPageable.java33
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/annotations/RestPageableQueries.java34
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/annotations/RestPageableQuery.java38
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/AbstractExceptionMapper.java37
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/JPARSException.java36
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureRequestValidator.java38
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureRequestValidatorImpl.java33
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureSet.java23
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureSetPreV2.java26
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureSetV2.java29
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/ServiceVersion.java111
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/clientinitiated/paging/PagingRequestValidator.java132
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/paging/AbstractPagingValidator.java108
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/paging/PageableFieldValidator.java84
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/paging/PageableQueryValidator.java65
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/paging/PagingResponseBuilder.java (renamed from dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/clientinitiated/paging/PagingResponseBuilder.java)59
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractEntityResource.java109
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractPersistenceUnitResource.java33
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractQueryResource.java84
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractResource.java46
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/IdHelper.java18
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/JPARSLogger.java19
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/MethodExitLogData.java4
-rw-r--r--foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/JPARSErrorCodes.java3
-rw-r--r--foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/i18n/JPARSExceptionResource.java5
-rw-r--r--jpa/eclipselink.jpars.test/antbuild.xml7
-rw-r--r--jpa/eclipselink.jpars.test/src/META-INF/persistence.xml12
-rw-r--r--jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/AllJavaEETests.java8
-rw-r--r--jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/basket/Basket.java79
-rw-r--r--jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/basket/BasketItem.java90
-rw-r--r--jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/employee/Employee.java35
-rw-r--r--jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/weaving/PersistenceWeaverBean.java7
-rw-r--r--jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/server/ServerPageableTest.java391
-rw-r--r--jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/util/RestUtils.java41
37 files changed, 1601 insertions, 729 deletions
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/internal/dbws/ProviderHelper.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/internal/dbws/ProviderHelper.java
index 9c5764f..61a143a 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/internal/dbws/ProviderHelper.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/internal/dbws/ProviderHelper.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2014 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -14,48 +14,11 @@
package org.eclipse.persistence.internal.dbws;
//javase imports
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Vector;
-import java.util.List;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-// Java extension imports
-import javax.activation.DataHandler;
-import javax.servlet.ServletContext;
-import javax.xml.namespace.QName;
-import javax.xml.soap.SOAPBodyElement;
-import javax.xml.soap.SOAPElement;
-import javax.xml.soap.SOAPEnvelope;
-import javax.xml.soap.SOAPException;
-import javax.xml.soap.SOAPFactory;
-import javax.xml.soap.SOAPFault;
-import javax.xml.soap.SOAPMessage;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.stream.StreamResult;
-import javax.xml.transform.stream.StreamSource;
-import javax.xml.ws.WebServiceException;
-import javax.xml.ws.handler.MessageContext;
-import javax.xml.ws.soap.SOAPFaultException;
-import static javax.xml.soap.SOAPConstants.SOAP_1_2_PROTOCOL;
-import static javax.xml.soap.SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE;
-import static javax.xml.soap.SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE;
-import static javax.xml.ws.handler.MessageContext.INBOUND_MESSAGE_ATTACHMENTS;
-
-// EclipseLink imports
import org.eclipse.persistence.dbws.DBWSModelProject;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.exceptions.DBWSException;
import org.eclipse.persistence.exceptions.XMLMarshalException;
-import org.eclipse.persistence.internal.dbws.DBWSAdapter;
import org.eclipse.persistence.internal.oxm.XMLConversionManager;
import org.eclipse.persistence.internal.oxm.schema.SchemaModelProject;
import org.eclipse.persistence.internal.oxm.schema.model.ComplexType;
@@ -78,6 +41,43 @@ import org.eclipse.persistence.oxm.attachment.XMLAttachmentUnmarshaller;
import org.eclipse.persistence.oxm.mappings.XMLAnyCollectionMapping;
import org.eclipse.persistence.oxm.schema.XMLSchemaReference;
import org.eclipse.persistence.sessions.Project;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+import javax.activation.DataHandler;
+import javax.servlet.ServletContext;
+import javax.xml.namespace.QName;
+import javax.xml.soap.SOAPBodyElement;
+import javax.xml.soap.SOAPElement;
+import javax.xml.soap.SOAPEnvelope;
+import javax.xml.soap.SOAPException;
+import javax.xml.soap.SOAPFactory;
+import javax.xml.soap.SOAPFault;
+import javax.xml.soap.SOAPMessage;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.ws.WebServiceException;
+import javax.xml.ws.handler.MessageContext;
+import javax.xml.ws.soap.SOAPFaultException;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import static javax.xml.soap.SOAPConstants.SOAP_1_2_PROTOCOL;
+import static javax.xml.soap.SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE;
+import static javax.xml.soap.SOAPConstants.URI_NS_SOAP_1_2_ENVELOPE;
+import static javax.xml.ws.handler.MessageContext.INBOUND_MESSAGE_ATTACHMENTS;
+import static org.eclipse.persistence.internal.dbws.SOAPResponseWriter.RECEIVER_QNAME;
+import static org.eclipse.persistence.internal.dbws.SOAPResponseWriter.SERVER_QNAME;
import static org.eclipse.persistence.internal.xr.Util.DBWS_SCHEMA_XML;
import static org.eclipse.persistence.internal.xr.Util.DBWS_SERVICE_XML;
import static org.eclipse.persistence.internal.xr.Util.DBWS_WSDL;
@@ -88,8 +88,8 @@ import static org.eclipse.persistence.internal.xr.Util.WEB_INF_DIR;
import static org.eclipse.persistence.internal.xr.Util.WSDL_DIR;
import static org.eclipse.persistence.oxm.mappings.UnmarshalKeepAsElementPolicy.KEEP_UNKNOWN_AS_ELEMENT;
-import static org.eclipse.persistence.internal.dbws.SOAPResponseWriter.RECEIVER_QNAME;
-import static org.eclipse.persistence.internal.dbws.SOAPResponseWriter.SERVER_QNAME;
+// Java extension imports
+// EclipseLink imports
/**
* <p>
@@ -390,7 +390,7 @@ public class ProviderHelper extends XRServiceFactory {
else {
// cant use e.getTextContent() - some DOM impls dont support it :-(
//String val = e.getTextContent();
- StringBuffer sb = new StringBuffer();
+ StringBuilder sb = new StringBuilder();
NodeList childNodes = e.getChildNodes();
for(int idx=0; idx < childNodes.getLength(); idx++ ) {
if (childNodes.item(idx).getNodeType() == Node.TEXT_NODE ) {
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceContext.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceContext.java
index 5eebb68..bcbdc94 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceContext.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceContext.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -8,48 +8,11 @@
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
- * dclarke/tware - initial
+ * dclarke/tware - initial
+ * Dmitry Kornilov - Pagination related changes
******************************************************************************/
package org.eclipse.persistence.jpa.rs;
-import java.beans.BeanInfo;
-import java.beans.Introspector;
-import java.beans.PropertyDescriptor;
-import java.io.BufferedInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.net.URI;
-import java.security.AccessController;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.Query;
-import javax.persistence.RollbackException;
-import javax.persistence.spi.PersistenceUnitInfo;
-import javax.ws.rs.core.MediaType;
-import javax.xml.bind.JAXBElement;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Marshaller;
-import javax.xml.bind.Unmarshaller;
-import javax.xml.bind.ValidationEvent;
-import javax.xml.bind.ValidationEventHandler;
-import javax.xml.bind.annotation.adapters.XmlAdapter;
-import javax.xml.stream.XMLOutputFactory;
-import javax.xml.stream.XMLStreamWriter;
-import javax.xml.transform.stream.StreamSource;
-
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.descriptors.FetchGroupManager;
@@ -71,12 +34,14 @@ import org.eclipse.persistence.jaxb.JAXBContextProperties;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory;
-import org.eclipse.persistence.jpa.JpaEntityManager;
import org.eclipse.persistence.jpa.JpaHelper;
import org.eclipse.persistence.jpa.PersistenceProvider;
import org.eclipse.persistence.jpa.dynamic.JPADynamicHelper;
+import org.eclipse.persistence.jpa.rs.annotations.RestPageableQueries;
+import org.eclipse.persistence.jpa.rs.annotations.RestPageableQuery;
import org.eclipse.persistence.jpa.rs.exceptions.JPARSException;
import org.eclipse.persistence.jpa.rs.features.FeatureSet;
+import org.eclipse.persistence.jpa.rs.features.ServiceVersion;
import org.eclipse.persistence.jpa.rs.util.IdHelper;
import org.eclipse.persistence.jpa.rs.util.JPARSLogger;
import org.eclipse.persistence.jpa.rs.util.JTATransactionWrapper;
@@ -115,6 +80,43 @@ import org.eclipse.persistence.sessions.DatabaseSession;
import org.eclipse.persistence.sessions.Session;
import org.eclipse.persistence.sessions.UnitOfWork;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Query;
+import javax.persistence.RollbackException;
+import javax.persistence.spi.PersistenceUnitInfo;
+import javax.ws.rs.core.MediaType;
+import javax.xml.bind.JAXBElement;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.bind.ValidationEvent;
+import javax.xml.bind.ValidationEventHandler;
+import javax.xml.bind.annotation.adapters.XmlAdapter;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamWriter;
+import javax.xml.transform.stream.StreamSource;
+import java.beans.BeanInfo;
+import java.beans.Introspector;
+import java.beans.PropertyDescriptor;
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.net.URI;
+import java.security.AccessController;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
/**
* A wrapper around the JPA and JAXB artifacts used to persist an application.
*
@@ -153,9 +155,21 @@ public class PersistenceContext {
private Boolean weavingEnabled = null;
- private String version = null;
-
- private FeatureSet supportedFeatureSet;
+ private ServiceVersion version = ServiceVersion.NO_VERSION;
+
+ /**
+ * JPARS pageable queries map.
+ * Key: named query name
+ * Value: corresponding RestPageableQuery annotation
+ */
+ private Map<String, RestPageableQuery> pageableQueries;
+
+ /**
+ * JPARS pageable queries map.
+ * Key: named query name
+ * Value: corresponding RestPageableQuery annotation
+ */
+ private Map<String, RestPageableQuery> pageableQueries;
protected PersistenceContext() {
}
@@ -171,6 +185,8 @@ public class PersistenceContext {
super();
this.emf = emf;
this.name = emfName;
+ this.baseURI = defaultURI;
+
if (getServerSession().hasExternalTransactionController()) {
transaction = new JTATransactionWrapper();
} else {
@@ -185,7 +201,19 @@ public class PersistenceContext {
JPARSLogger.exception("exception_creating_jaxb_context", new Object[] { emfName, e.toString() }, e);
emf.close();
}
- setBaseURI(defaultURI);
+ }
+
+ /**
+ * Instantiates a new persistence context.
+ *
+ * @param emfName the emf name
+ * @param emf the emf
+ * @param defaultURI the default uri
+ * @param version REST service version
+ */
+ public PersistenceContext(String emfName, EntityManagerFactoryImpl emf, URI defaultURI, ServiceVersion version) {
+ this(emfName, emf, defaultURI);
+ this.version = version;
}
/**
@@ -201,21 +229,12 @@ public class PersistenceContext {
}
/**
- * Gets the version.
+ * Gets the version as it appears in URI.
*
- * @return the version
+ * @return The version.
*/
public String getVersion() {
- return version;
- }
-
- /**
- * Sets the version.
- *
- * @param version the new version
- */
- public void setVersion(String version) {
- this.version = version;
+ return version.getCode();
}
/**
@@ -223,20 +242,17 @@ public class PersistenceContext {
*
* For each package in the EntityManagerFactory, a MetadataSource that is capable of building a JAXBContext
* that creates the same mappings in JAXB is created. These MetadataSources are used to constuct the JAXContext
- * that is used for JSON and XML translation
+ * that is used for JSON and XML translation.
* @param metadataSources
- * @param persistenceUnitName
* @param session
*/
- @SuppressWarnings("rawtypes")
protected void addDynamicXMLMetadataSources(List<Object> metadataSources, AbstractSession session) {
Set<String> packages = new HashSet<String>();
- Iterator<Class> i = session.getDescriptors().keySet().iterator();
- while (i.hasNext()) {
- Class<?> descriptorClass = i.next();
+ for (Class descriptorClass : session.getDescriptors().keySet()) {
String packageName = "";
- if (descriptorClass.getName().lastIndexOf('.') > 0) {
- packageName = descriptorClass.getName().substring(0, descriptorClass.getName().lastIndexOf('.'));
+ int lastDotIndex = descriptorClass.getName().lastIndexOf('.');
+ if (lastDotIndex > 0) {
+ packageName = descriptorClass.getName().substring(0, lastDotIndex);
}
if (!packages.contains(packageName)) {
packages.add(packageName);
@@ -249,8 +265,8 @@ public class PersistenceContext {
}
/**
- * A part of the facade over the JPA API
- * Persist an entity in JPA and commit
+ * A part of the facade over the JPA API.
+ * Persist an entity in JPA and commit.
* @param tenantId
* @param entity
* @throws Exception
@@ -272,7 +288,7 @@ public class PersistenceContext {
}
/**
- * Create a JAXBContext based on the EntityManagerFactory for this PersistenceContext
+ * Create a JAXBContext based on the EntityManagerFactory for this PersistenceContext.
* @param session
* @return
*/
@@ -293,8 +309,8 @@ public class PersistenceContext {
}
/**
- * A part of the facade over the JPA API
- * Create an EntityManagerFactory using the given PersistenceUnitInfo and properties
+ * A part of the facade over the JPA API.
+ * Create an EntityManagerFactory using the given PersistenceUnitInfo and properties.
* @param info
* @param properties
* @return
@@ -318,7 +334,6 @@ public class PersistenceContext {
/**
* Build the set of properties used to create the JAXBContext based on the EntityManagerFactory that
* this PersistenceContext wraps
- * @param persistenceUnitName
* @param session
* @return
* @throws IOException
@@ -360,7 +375,7 @@ public class PersistenceContext {
metadataLocations.add(new ErrorResponseMetadataSource());
properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, metadataLocations);
- properties.put(JAXBContextProperties.SESSION_EVENT_LISTENER, new PreLoginMappingAdapter((AbstractSession) session));
+ properties.put(JAXBContextProperties.SESSION_EVENT_LISTENER, new PreLoginMappingAdapter(session));
// Bug 410095 - JSON_WRAPPER_AS_ARRAY_NAME property doesn't work when jaxb context is created using DynamicJAXBContextFactory
//properties.put(JAXBContextProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
@@ -474,13 +489,13 @@ public class PersistenceContext {
try {
ClassDescriptor descriptor = getServerSession().getClassDescriptor(getClass(entityName));
DatabaseMapping mapping = descriptor.getMappingForAttributeName(attribute);
- Object object = null;
+ Object object;
if (mapping == null) {
return null;
} else if (mapping.isObjectReferenceMapping() || mapping.isCollectionMapping()) {
DatabaseMapping partnerMapping = null;
if (partner != null) {
- ClassDescriptor referenceDescriptor = ((ForeignReferenceMapping) mapping).getReferenceDescriptor();
+ ClassDescriptor referenceDescriptor = mapping.getReferenceDescriptor();
partnerMapping = referenceDescriptor.getMappingForAttributeName(partner);
if (partnerMapping == null) {
return null;
@@ -518,9 +533,9 @@ public class PersistenceContext {
* @param tenantId the tenant id
* @param entityName the entity name
* @param id the id
- * @param properties the properties
* @param attribute the attribute
- * @param attributeValue the attribute value
+ * @param listItemId
+ * @param entity
* @param partner the partner
* @return the object
*
@@ -540,22 +555,21 @@ public class PersistenceContext {
} else if (mapping.isObjectReferenceMapping() || mapping.isCollectionMapping()) {
DatabaseMapping partnerMapping = null;
Object originalAttributeValue = null;
- ClassDescriptor referenceDescriptor = ((ForeignReferenceMapping) mapping).getReferenceDescriptor();
+ ClassDescriptor referenceDescriptor = mapping.getReferenceDescriptor();
if (partner != null) {
partnerMapping = referenceDescriptor.getMappingForAttributeName(partner);
if (partnerMapping == null) {
return null;
}
}
- Field[] fields = null;
+ Field[] fields;
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
fields = AccessController.doPrivileged(new PrivilegedGetDeclaredFields(clazz));
} else {
fields = PrivilegedAccessHelper.getDeclaredFields(clazz);
}
- for (int i = 0; i < fields.length; i++) {
- Field field = fields[i];
+ for (Field field : fields) {
fieldName = field.getName();
if (fieldName.equals(attribute)) {
try {
@@ -571,10 +585,6 @@ public class PersistenceContext {
Object member = this.find(referenceDescriptor.getAlias(), realListItemId);
((Collection) attributeValue).remove(member);
}
- } else if (attributeValue instanceof Object) {
- attributeValue = null;
- } else {
- attributeValue = 0;
}
break;
} catch (Exception e) {
@@ -609,7 +619,7 @@ public class PersistenceContext {
String name = pd.getName();
if (propertyName.equals(name)) {
Method getter = pd.getReadMethod();
- Object value = null;
+ Object value;
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()) {
value = AccessController.doPrivileged(new PrivilegedMethodInvoker(getter, entity));
} else {
@@ -672,8 +682,7 @@ public class PersistenceContext {
*/
public DatabaseSession getServerSession() {
// Fix for bug 390786 - JPA-RS: ClassCastException retrieving metadata for Composite Persistence Unit
- DatabaseSession dbSession = JpaHelper.getDatabaseSession(emf);
- return dbSession;
+ return JpaHelper.getDatabaseSession(emf);
}
/**
@@ -683,7 +692,7 @@ public class PersistenceContext {
* @return the client session
*/
public AbstractSession getClientSession(EntityManager em) {
- UnitOfWork uow = ((JpaEntityManager) JpaHelper.getEntityManager(em)).getUnitOfWork();
+ UnitOfWork uow = JpaHelper.getEntityManager(em).getUnitOfWork();
return (AbstractSession) uow;
}
@@ -699,7 +708,7 @@ public class PersistenceContext {
DatabaseSession session = getServerSession();
ClassDescriptor descriptor = session.getDescriptorForAlias(entityName);
if (descriptor == null) {
- for (Object ajaxBSession : ((JAXBContext) getJAXBContext()).getXMLContext().getSessions()) {
+ for (Object ajaxBSession : getJAXBContext().getXMLContext().getSessions()) {
descriptor = ((Session) ajaxBSession).getClassDescriptorForAlias(entityName);
if (descriptor != null) {
break;
@@ -734,8 +743,7 @@ public class PersistenceContext {
@SuppressWarnings("rawtypes")
public ClassDescriptor getJAXBDescriptorForClass(Class clazz) {
ClassDescriptor descriptor = null;
- for (Object ajaxBSession : ((JAXBContext) getJAXBContext())
- .getXMLContext().getSessions()) {
+ for (Object ajaxBSession : getJAXBContext().getXMLContext().getSessions()) {
descriptor = ((Session) ajaxBSession).getClassDescriptor(clazz);
if (descriptor != null) {
break;
@@ -784,7 +792,7 @@ public class PersistenceContext {
@SuppressWarnings("rawtypes")
public Object merge(Map<String, String> tenantId, Object entity) {
EntityManager em = getEmf().createEntityManager(tenantId);
- Object mergedEntity = null;
+ Object mergedEntity;
try {
transaction.beginTransaction(em);
if (entity instanceof List) {
@@ -825,7 +833,7 @@ public class PersistenceContext {
*/
public DynamicEntity newEntity(Map<String, String> tenantId, String type) {
JPADynamicHelper helper = new JPADynamicHelper(getEmf());
- DynamicEntity entity = null;
+ DynamicEntity entity;
try {
entity = helper.newDynamicEntity(type);
} catch (IllegalArgumentException e) {
@@ -955,15 +963,6 @@ public class PersistenceContext {
return query;
}
- /**
- * Sets the base uri.
- *
- * @param baseURI the new base uri
- */
- public void setBaseURI(URI baseURI) {
- this.baseURI = baseURI;
- }
-
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void setMappingValueInObject(Object object, Object attributeValue, DatabaseMapping mapping, DatabaseMapping partner) {
if (mapping.isObjectReferenceMapping()) {
@@ -1050,7 +1049,7 @@ public class PersistenceContext {
if (event.getSeverity() != ValidationEvent.WARNING) {
// ValidationEventLocator eventLocator = event.getLocator();
// Throwable throwable = event.getLinkedException();
- // nothing is really useful to check for us in eventLocator
+ // nothing is really useful to check for us in eventLocator
// and linked exception, just return false;
return false;
}
@@ -1174,7 +1173,7 @@ public class PersistenceContext {
if (mediaType == MediaType.APPLICATION_XML_TYPE && object instanceof List) {
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
- XMLStreamWriter writer = null;
+ XMLStreamWriter writer;
try {
writer = outputFactory.createXMLStreamWriter(output);
writer.writeStartDocument();
@@ -1202,9 +1201,8 @@ public class PersistenceContext {
@SuppressWarnings("rawtypes")
protected void preMarshallEntity(Object object) {
if (object instanceof List) {
- Iterator i = ((List) object).iterator();
- while (i.hasNext()) {
- preMarshallIndividualEntity(i.next());
+ for (Object o : ((List) object)) {
+ preMarshallIndividualEntity(o);
}
} else {
preMarshallIndividualEntity(object);
@@ -1220,38 +1218,32 @@ public class PersistenceContext {
protected void preMarshallIndividualEntity(Object entity) {
if (entity instanceof ReportQueryResultListItem) {
ReportQueryResultListItem item = (ReportQueryResultListItem) entity;
- List<JAXBElement> fields = item.getFields();
- for (int i = 0; i < fields.size(); i++) {
+ for (JAXBElement field : item.getFields()) {
// one or more fields in the MultiResultQueryListItem might be a domain object,
// so, we need to set the relationshipInfo for those domain objects.
- setRelationshipInfo(fields.get(i).getValue());
+ setRelationshipInfo(field.getValue());
}
} else if (entity instanceof SingleResultQueryList) {
SingleResultQueryList item = (SingleResultQueryList) entity;
- List<JAXBElement> fields = item.getFields();
- for (int i = 0; i < fields.size(); i++) {
+ for (JAXBElement field : item.getFields()) {
// one or more fields in the SingleResultQueryList might be a domain object,
// so, we need to set the relationshipInfo for those domain objects.
- setRelationshipInfo(fields.get(i).getValue());
+ setRelationshipInfo(field.getValue());
}
} else if (entity instanceof ReportQueryResultList) {
ReportQueryResultList list = (ReportQueryResultList) entity;
- List<ReportQueryResultListItem> items = list.getItems();
- for (int i = 0; i < items.size(); i++) {
- ReportQueryResultListItem item = items.get(i);
- List<JAXBElement> fields = item.getFields();
- for (int index = 0; index < fields.size(); index++) {
+ for (ReportQueryResultListItem item : list.getItems()) {
+ for (JAXBElement field : item.getFields()) {
// one or more fields in the MultiResultQueryList might be a domain object,
// so, we need to set the relationshipInfo for those domain objects.
- setRelationshipInfo(fields.get(index).getValue());
+ setRelationshipInfo(field.getValue());
}
}
} else if (entity instanceof ReadAllQueryResultCollection) {
ReadAllQueryResultCollection list = (ReadAllQueryResultCollection) entity;
List<Object> items = list.getItems();
if ((items != null) && (!items.isEmpty())) {
- for (int i = 0; i < items.size(); i++) {
- Object item = items.get(i);
+ for (Object item : items) {
setRelationshipInfo(item);
}
}
@@ -1259,8 +1251,7 @@ public class PersistenceContext {
ReportQueryResultCollection list = (ReportQueryResultCollection) entity;
List<ReportQueryResultListItem> items = list.getItems();
if ((items != null) && (!items.isEmpty())) {
- for (int i = 0; i < items.size(); i++) {
- ReportQueryResultListItem item = items.get(i);
+ for (ReportQueryResultListItem item : items) {
setRelationshipInfo(item);
}
}
@@ -1302,9 +1293,7 @@ public class PersistenceContext {
@SuppressWarnings("rawtypes")
protected void postMarshallEntity(Object object) {
if (object instanceof List) {
- Iterator i = ((List) object).iterator();
- while (i.hasNext()) {
- Object entity = i.next();
+ for (Object entity : ((List) object)) {
if (entity instanceof PersistenceWeavedRest) {
((PersistenceWeavedRest) entity)._persistence_setRelationships(new ArrayList<RelationshipInfo>());
}
@@ -1375,46 +1364,83 @@ public class PersistenceContext {
}
/**
- * Checks if is version greater or equal to.
+ * Gets the supported feature set.
*
- * @param version the version
- * @return true, if is version greater or equal to
+ * @return the supported feature set.
*/
- public boolean isVersionGreaterOrEqualTo(String version) {
- String currentVersion = this.version;
- if ((currentVersion != null) && (!currentVersion.isEmpty())) {
- if ((version != null) && (!version.isEmpty())) {
- try {
- int current = new Integer(currentVersion.replace("v", "").replace(".", "")).intValue();
- int requested = new Integer(version.replace("v", "").replace(".", "")).intValue();
- if (current >= requested) {
- return true;
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- return false;
- }
- }
- }
- return false;
+ public FeatureSet getSupportedFeatureSet() {
+ return version.getFeatureSet();
}
/**
- * Gets the supported feature set.
+ * Finds out is given query pageable or not.
*
- * @return the supported feature set
+ * @param queryName named query to check.
+ * @return true if pageable, false if not.
*/
- public FeatureSet getSupportedFeatureSet() {
- return supportedFeatureSet;
+ public boolean isQueryPageable(String queryName) {
+ return getPageableQueries().get(queryName) != null;
+ }
+
+ /**
+ * Gets REST pageable query details by query name.
+ *
+ * @param queryName named query name.
+ * @return RestPageableQuery or null if query couldn't be found.
+ */
+ public RestPageableQuery getPageableQuery(String queryName) {
+ return getPageableQueries().get(queryName);
}
/**
- * Sets the supported feature set.
+ * Sets the version.
*
- * @param supportedFeatureSet the new supported feature set
+ * @param version the new version.
*/
- public void setSupportedFeatureSet(FeatureSet supportedFeatureSet) {
- this.supportedFeatureSet = supportedFeatureSet;
+ public void setVersion(String version) {
+ this.version = ServiceVersion.fromCode(version);
+ }
+
+ /**
+ * Sets the base uri.
+ *
+ * @param baseURI the new base uri
+ */
+ public void setBaseURI(URI baseURI) {
+ this.baseURI = baseURI;
+ }
+
+ /**
+ * Getter for pageableQueries property with lazy initialization.
+ *
+ * @return The initialized pageableQueries property.
+ */
+ private Map<String, RestPageableQuery> getPageableQueries() {
+ // Lazy initialization
+ if (pageableQueries == null) {
+ initPageableQueries();
+ }
+
+ return pageableQueries;
+ }
+
+ /**
+ * Initializes pageableQueries map by reading RestPageableQueries entity annotations.
+ */
+ private void initPageableQueries() {
+ pageableQueries = new HashMap<String, RestPageableQuery>();
+
+ // Iterate on all entity classes
+ for (Class clazz : getServerSession().getProject().getDescriptors().keySet()) {
+ if (clazz.isAnnotationPresent(RestPageableQueries.class)) {
+ final RestPageableQueries restPageableQueries = (RestPageableQueries) clazz.getAnnotation(RestPageableQueries.class);
+
+ // Process each RestPageableQuery annotation in the list
+ for (RestPageableQuery restPageableQuery : restPageableQueries.value()) {
+ pageableQueries.put(restPageableQuery.queryName(), restPageableQuery);
+ }
+ }
+ }
}
/* (non-Javadoc)
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceFactoryBase.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceFactoryBase.java
index c4dc565..1954f32 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceFactoryBase.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceFactoryBase.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -13,16 +13,6 @@
******************************************************************************/
package org.eclipse.persistence.jpa.rs;
-import java.net.URI;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.Persistence;
-
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.eclipse.persistence.dynamic.DynamicClassLoader;
import org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl;
@@ -31,11 +21,18 @@ import org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor;
import org.eclipse.persistence.internal.jpa.deployment.SEPersistenceUnitInfo;
import org.eclipse.persistence.jpa.Archive;
import org.eclipse.persistence.jpa.rs.exceptions.JPARSException;
-import org.eclipse.persistence.jpa.rs.features.FeatureSetPreV2;
-import org.eclipse.persistence.jpa.rs.features.FeatureSetV2;
-import org.eclipse.persistence.jpa.rs.resources.common.AbstractResource;
+import org.eclipse.persistence.jpa.rs.features.ServiceVersion;
import org.eclipse.persistence.jpa.rs.util.JPARSLogger;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+import java.net.URI;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
/**
* Manages the PersistenceContexts that are used by a JPA-RS deployment. Provides a single point to bootstrap
* and look up PersistenceContexts
@@ -54,19 +51,11 @@ public class PersistenceFactoryBase implements PersistenceContextFactory {
* @return
*/
public PersistenceContext bootstrapPersistenceContext(String name, EntityManagerFactory emf, URI baseURI, String version, boolean replace) {
- PersistenceContext persistenceContext = new PersistenceContext(name, (EntityManagerFactoryImpl) emf, baseURI);
- persistenceContext.setBaseURI(baseURI);
- persistenceContext.setVersion(version);
- if (persistenceContext.isVersionGreaterOrEqualTo(AbstractResource.SERVICE_VERSION_2_0)) {
- persistenceContext.setSupportedFeatureSet(new FeatureSetV2());
- } else {
- persistenceContext.setSupportedFeatureSet(new FeatureSetPreV2());
- }
- return persistenceContext;
+ return new PersistenceContext(name, (EntityManagerFactoryImpl) emf, baseURI, ServiceVersion.fromCode(version));
}
/**
- * Stop the factory. Remove all the PersistenceContexts.
+ * Stop the factory. Remove all the PersistenceContexts.
*/
public void close() {
synchronized (this) {
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/annotations/RestPageable.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/annotations/RestPageable.java
new file mode 100644
index 0000000..57996de
--- /dev/null
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/annotations/RestPageable.java
@@ -0,0 +1,33 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Dmitry Kornilov - initial implementation
+ ******************************************************************************/
+package org.eclipse.persistence.jpa.rs.annotations;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Collection fields annotated by this annotation support pagination in JPARS service.
+ *
+ * @author Dmitry Kornilov
+ */
+@Target(value= ElementType.FIELD)
+@Retention(value= RetentionPolicy.RUNTIME)
+public @interface RestPageable {
+
+ /**
+ * Specified the default limit.
+ */
+ int limit() default 100;
+}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/annotations/RestPageableQueries.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/annotations/RestPageableQueries.java
new file mode 100644
index 0000000..86f345c
--- /dev/null
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/annotations/RestPageableQueries.java
@@ -0,0 +1,34 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Dmitry Kornilov - initial implementation
+ ******************************************************************************/
+package org.eclipse.persistence.jpa.rs.annotations;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * This annotation annotation allows the definition of multiple
+ * RestPageableQuery.
+ *
+ * @author Dmitry Kornilov
+ */
+@Target(value= ElementType.TYPE)
+@Retention(value= RetentionPolicy.RUNTIME)
+public @interface RestPageableQueries {
+
+ /**
+ * (Required) An array of REST pageable queries.
+ */
+ RestPageableQuery[] value();
+}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/annotations/RestPageableQuery.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/annotations/RestPageableQuery.java
new file mode 100644
index 0000000..cb0d5fd
--- /dev/null
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/annotations/RestPageableQuery.java
@@ -0,0 +1,38 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Dmitry Kornilov - initial implementation
+ ******************************************************************************/
+package org.eclipse.persistence.jpa.rs.annotations;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Defines a pageable query.
+ *
+ * @author Dmitry Kornilov
+ */
+@Target(value= ElementType.TYPE)
+@Retention(value= RetentionPolicy.RUNTIME)
+public @interface RestPageableQuery {
+
+ /**
+ * Named query name for pagination.
+ */
+ String queryName();
+
+ /**
+ * Specified the default limit.
+ */
+ int limit() default 100;
+}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/AbstractExceptionMapper.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/AbstractExceptionMapper.java
index 0ed7172..642d746 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/AbstractExceptionMapper.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/AbstractExceptionMapper.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2013 Oracle. All rights reserved.
+ * Copyright (c) 2013, 2014 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -12,14 +12,14 @@
******************************************************************************/
package org.eclipse.persistence.jpa.rs.exceptions;
-import java.io.IOException;
-import java.io.StringWriter;
-import java.lang.reflect.InvocationTargetException;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
+import org.eclipse.persistence.exceptions.ConversionException;
+import org.eclipse.persistence.exceptions.DatabaseException;
+import org.eclipse.persistence.jaxb.JAXBContext;
+import org.eclipse.persistence.jaxb.JAXBContextFactory;
+import org.eclipse.persistence.jaxb.MarshallerProperties;
+import org.eclipse.persistence.jpa.rs.DataStorage;
+import org.eclipse.persistence.jpa.rs.features.ServiceVersion;
+import org.eclipse.persistence.jpa.rs.util.StreamingOutputMarshaller;
import javax.naming.NamingException;
import javax.persistence.EntityExistsException;
@@ -39,15 +39,14 @@ import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
-
-import org.eclipse.persistence.exceptions.ConversionException;
-import org.eclipse.persistence.exceptions.DatabaseException;
-import org.eclipse.persistence.jaxb.JAXBContext;
-import org.eclipse.persistence.jaxb.JAXBContextFactory;
-import org.eclipse.persistence.jaxb.MarshallerProperties;
-import org.eclipse.persistence.jpa.rs.DataStorage;
-import org.eclipse.persistence.jpa.rs.resources.common.AbstractResource;
-import org.eclipse.persistence.jpa.rs.util.StreamingOutputMarshaller;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.lang.reflect.InvocationTargetException;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
public abstract class AbstractExceptionMapper {
@Context
@@ -99,7 +98,7 @@ public abstract class AbstractExceptionMapper {
}
}
- if ((path != null) && (path.contains(AbstractResource.SERVICE_VERSION_2_0))) {
+ if ((path != null) && (path.contains(ServiceVersion.VERSION_2_0.getCode()))) {
ErrorResponse errorResponse = new ErrorResponse(PROBLEM_TYPE, exception.getMessage(), String.valueOf(exception.getErrorCode()));
errorResponse.setRequestId((String) DataStorage.get(DataStorage.REQUEST_ID));
errorResponse.setHttpStatus(exception.getHttpStatusCode().getStatusCode());
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/JPARSException.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/JPARSException.java
index fc4fd4b..70f589d 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/JPARSException.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/JPARSException.java
@@ -12,12 +12,12 @@
******************************************************************************/
package org.eclipse.persistence.jpa.rs.exceptions;
-import javax.ws.rs.core.Response.Status;
-
import org.eclipse.persistence.exceptions.EclipseLinkException;
import org.eclipse.persistence.exceptions.JPARSErrorCodes;
import org.eclipse.persistence.exceptions.i18n.ExceptionMessageGenerator;
+import javax.ws.rs.core.Response.Status;
+
public class JPARSException extends EclipseLinkException {
private Status httpStatusCode;
@@ -65,7 +65,6 @@ public class JPARSException extends EclipseLinkException {
/**
* Entity not found.
*
- * @param httpStatusCode the http status code
* @param entityType the entity type
* @param entityId the entity id
* @param persistenceUnit the persistence unit
@@ -84,7 +83,6 @@ public class JPARSException extends EclipseLinkException {
/**
* Class descriptor could not be found for entity.
*
- * @param httpStatusCode the http status code
* @param entityType the entity type
* @param persistenceUnit the persistence unit
* @return the JPARS exception
@@ -103,7 +101,6 @@ public class JPARSException extends EclipseLinkException {
/**
* Attribute could not be found for entity.
*
- * @param httpStatusCode the http status code
* @param attributeName the attribute name
* @param entityType the entity type
* @param entityId the entity id
@@ -124,7 +121,6 @@ public class JPARSException extends EclipseLinkException {
/**
* Selection query for attribute could not be found for entity.
*
- * @param httpStatusCode the http status code
* @param attributeName the attribute name
* @param entityType the entity type
* @param entityId the entity id
@@ -145,7 +141,6 @@ public class JPARSException extends EclipseLinkException {
/**
* Invalid paging request.
*
- * @param httpStatusCode the http status code
* @return the JPARS exception
*/
public static JPARSException invalidPagingRequest() {
@@ -160,9 +155,24 @@ public class JPARSException extends EclipseLinkException {
}
/**
+ * Invalid paging request.
+ *
+ * @return the JPARS exception
+ */
+ public static JPARSException paginationParameterForNotPageableResource() {
+ Object[] args = {};
+
+ String msg = ExceptionMessageGenerator.buildMessage(JPARSException.class, JPARSErrorCodes.PAGINATION_PARAMETER_USED_FOR_NOT_PAGEABLE_RESOURCE, args);
+ JPARSException exception = new JPARSException(msg);
+ exception.setErrorCode(JPARSErrorCodes.PAGINATION_PARAMETER_USED_FOR_NOT_PAGEABLE_RESOURCE);
+ exception.setHttpStatusCode(Status.BAD_REQUEST);
+
+ return exception;
+ }
+
+ /**
* Database mapping could not be found for entity attribute.
*
- * @param httpStatusCode the http status code
* @param attributeName the attribute name
* @param entityType the entity type
* @param entityId the entity id
@@ -183,7 +193,6 @@ public class JPARSException extends EclipseLinkException {
/**
* Attribute could not be updated.
*
- * @param httpStatusCode the http status code
* @param attributeName the attribute name
* @param entityType the entity type
* @param entityId the entity id
@@ -204,7 +213,6 @@ public class JPARSException extends EclipseLinkException {
/**
* Invalid service version.
*
- * @param httpStatusCode the http status code
* @param serviceVersion the service version
* @return the JPARS exception
*/
@@ -222,7 +230,6 @@ public class JPARSException extends EclipseLinkException {
/**
* Invalid remove attribute request.
*
- * @param httpStatusCode the http status code
* @param attributeName the attribute name
* @param entityType the entity type
* @param entityId the entity id
@@ -243,7 +250,6 @@ public class JPARSException extends EclipseLinkException {
/**
* Response could not be built for find attribute request.
*
- * @param httpStatusCode the http status code
* @param attributeName the attribute name
* @param entityType the entity type
* @param entityId the entity id
@@ -264,7 +270,6 @@ public class JPARSException extends EclipseLinkException {
/**
* Response could not be built for named query request.
*
- * @param httpStatusCode the http status code
* @param query the query
* @param persistenceUnit the persistence unit
* @return the JPARS exception
@@ -283,7 +288,6 @@ public class JPARSException extends EclipseLinkException {
/**
* Object referred by link does not exist.
*
- * @param httpStatusCode the http status code
* @param entityType the entity type
* @param entityId the entity id
* @return the JPARS exception
@@ -302,7 +306,6 @@ public class JPARSException extends EclipseLinkException {
/**
* Session bean lookup failed.
*
- * @param httpStatusCode the http status code
* @param jndiName the jndi name
* @return the JPARS exception
*/
@@ -320,7 +323,6 @@ public class JPARSException extends EclipseLinkException {
/**
* Invalid configuration.
*
- * @param httpStatusCode the http status code
* @return the JPARS exception
*/
public static JPARSException invalidConfiguration() {
@@ -337,7 +339,6 @@ public class JPARSException extends EclipseLinkException {
/**
* Entity is not idempotent.
*
- * @param httpStatusCode the http status code
* @param entityType the entity type
* @param persistenceUnit the persistence unit
* @return the JPARS exception
@@ -356,7 +357,6 @@ public class JPARSException extends EclipseLinkException {
/**
* Persistence context could not be bootstrapped.
*
- * @param httpStatusCode the http status code
* @param persistenceUnit the persistence unit
* @return the JPARS exception
*/
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureRequestValidator.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureRequestValidator.java
deleted file mode 100644
index b779af8..0000000
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureRequestValidator.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2013 Oracle. All rights reserved.
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
- * which accompanies this distribution.
- * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
- * and the Eclipse Distribution License is available at
- * http://www.eclipse.org/org/documents/edl-v10.php.
- *
- * Contributors:
- * gonural - initial implementation
- ******************************************************************************/
-package org.eclipse.persistence.jpa.rs.features;
-
-import java.util.Map;
-
-import javax.ws.rs.core.UriInfo;
-
-public interface FeatureRequestValidator {
-
- /**
- * Checks if feature is requested.
- *
- * @param uri the uri
- * @param additionalParams the additional params
- * @return true, if is requested
- */
- boolean isRequested(UriInfo uri, Map<String, Object> additionalParams);
-
- /**
- * Checks if request parameters are valid.
- *
- * @param uri the uri
- * @param additionalParams the additional params
- * @return true, if is request valid
- */
- boolean isRequestValid(UriInfo uri, Map<String, Object> additionalParams);
-} \ No newline at end of file
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureRequestValidatorImpl.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureRequestValidatorImpl.java
deleted file mode 100644
index 5b26b06..0000000
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureRequestValidatorImpl.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package org.eclipse.persistence.jpa.rs.features;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.ws.rs.core.UriInfo;
-
-public class FeatureRequestValidatorImpl implements FeatureRequestValidator {
-
- /* (non-Javadoc)
- * @see org.eclipse.persistence.jpa.rs.features.FeatureRequestValidator#isRequested(javax.ws.rs.core.UriInfo, java.util.Map)
- */
- @Override
- public boolean isRequested(UriInfo uri, Map<String, Object> additionalParams) {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.persistence.jpa.rs.features.FeatureRequestValidator#isRequestValid(javax.ws.rs.core.UriInfo, java.util.Map)
- */
- @Override
- public boolean isRequestValid(UriInfo uri, Map<String, Object> additionalParams) {
- return true;
- }
-
- protected Map<String, Object> getQueryParameters(UriInfo info) {
- Map<String, Object> queryParameters = new HashMap<String, Object>();
- for (String key : info.getQueryParameters().keySet()) {
- queryParameters.put(key, info.getQueryParameters().getFirst(key));
- }
- return queryParameters;
- }
-}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureSet.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureSet.java
index d67549d..7bb153b 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureSet.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureSet.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2013 Oracle. All rights reserved.
+ * Copyright (c) 2013, 2014 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -12,14 +12,29 @@
******************************************************************************/
package org.eclipse.persistence.jpa.rs.features;
+/**
+ * This interface represents one feature of the JPARS. Features can be supported or not
+ * supported by different versions of the service.
+ */
public interface FeatureSet {
public enum Feature {
- NO_PAGING, PAGING
+ NO_PAGING, /* not pageable resurces */
+ PAGING /* pageable resources */
}
+ /**
+ * Returns true if given feature is supported.
+ *
+ * @param feature Feature to check.
+ * @return true if feature is supported, false if not supported.
+ */
boolean isSupported(Feature feature);
- FeatureRequestValidator getRequestValidator(Feature feature);
-
+ /**
+ * Returns an instance of {@link FeatureResponseBuilder} for given feature.
+ *
+ * @param feature feature to get response builder for.
+ * @return {@link FeatureResponseBuilder}
+ */
FeatureResponseBuilder getResponseBuilder(Feature feature);
} \ No newline at end of file
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureSetPreV2.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureSetPreV2.java
index 0e18345..2513674 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureSetPreV2.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureSetPreV2.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2013 Oracle. All rights reserved.
+ * Copyright (c) 2013, 2014 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -12,10 +12,13 @@
******************************************************************************/
package org.eclipse.persistence.jpa.rs.features;
+/**
+ * The legacy initial feature set. Used if version number is not present.
+ */
public class FeatureSetPreV2 implements FeatureSet {
- /* (non-Javadoc)
- * @see org.eclipse.persistence.jpa.rs.features.FeatureSet#isSupported(org.eclipse.persistence.jpa.rs.features.FeatureSet.Feature)
+ /**
+ * {@inheritDoc}
*/
@Override
public boolean isSupported(Feature feature) {
@@ -28,21 +31,8 @@ public class FeatureSetPreV2 implements FeatureSet {
}
}
- /* (non-Javadoc)
- * @see org.eclipse.persistence.jpa.rs.features.FeatureSet#getRequestValidator(org.eclipse.persistence.jpa.rs.features.FeatureSet.Feature)
- */
- @Override
- public FeatureRequestValidator getRequestValidator(Feature feature) {
- switch (feature) {
- case NO_PAGING:
- case PAGING:
- default:
- return new FeatureRequestValidatorImpl();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.persistence.jpa.rs.features.FeatureSet#getResponseBuilder(org.eclipse.persistence.jpa.rs.features.FeatureSet.Feature)
+ /**
+ * {@inheritDoc}
*/
@Override
public FeatureResponseBuilder getResponseBuilder(Feature feature) {
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureSetV2.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureSetV2.java
index 280eec5..7fadd96 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureSetV2.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/FeatureSetV2.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2013 Oracle. All rights reserved.
+ * Copyright (c) 2013, 2014 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -12,14 +12,16 @@
******************************************************************************/
package org.eclipse.persistence.jpa.rs.features;
-import org.eclipse.persistence.jpa.rs.features.clientinitiated.paging.PagingRequestValidator;
-import org.eclipse.persistence.jpa.rs.features.clientinitiated.paging.PagingResponseBuilder;
import org.eclipse.persistence.jpa.rs.features.core.selflinks.SelfLinksResponseBuilder;
+import org.eclipse.persistence.jpa.rs.features.paging.PagingResponseBuilder;
+/**
+ * Feature set for service version 2.0.
+ */
public class FeatureSetV2 implements FeatureSet {
- /* (non-Javadoc)
- * @see org.eclipse.persistence.jpa.rs.features.FeatureSet#isSupported(org.eclipse.persistence.jpa.rs.features.FeatureSet.Feature)
+ /**
+ * {@inheritDoc}
*/
@Override
public boolean isSupported(Feature feature) {
@@ -32,21 +34,8 @@ public class FeatureSetV2 implements FeatureSet {
}
}
- /* (non-Javadoc)
- * @see org.eclipse.persistence.jpa.rs.features.FeatureSet#getRequestValidator(org.eclipse.persistence.jpa.rs.features.FeatureSet.Feature)
- */
- @Override
- public FeatureRequestValidator getRequestValidator(Feature feature) {
- switch (feature) {
- case PAGING:
- return new PagingRequestValidator();
- default:
- return new FeatureRequestValidatorImpl();
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.persistence.jpa.rs.features.FeatureSet#getResponseBuilder(org.eclipse.persistence.jpa.rs.features.FeatureSet.Feature)
+ /**
+ * {@inheritDoc}
*/
@Override
public FeatureResponseBuilder getResponseBuilder(Feature feature) {
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/ServiceVersion.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/ServiceVersion.java
new file mode 100644
index 0000000..ab1c9c9
--- /dev/null
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/ServiceVersion.java
@@ -0,0 +1,111 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Dmitry Kornilov - initial implementation
+ ******************************************************************************/
+
+package org.eclipse.persistence.jpa.rs.features;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * JPARS service version.
+ *
+ * @author Dmitry Kornilov
+ */
+public enum ServiceVersion {
+ /**
+ * Added only for legacy reasons. In early versions version number was not supported.
+ */
+ NO_VERSION(null),
+
+ /**
+ * The same as NO_VERSION, but v1.0 is specified in the URL.
+ */
+ VERSION_1_0("v1.0"),
+
+ /**
+ * The latest version at the moment, supports pagination and other new features.
+ */
+ VERSION_2_0("v2.0");
+
+ /**
+ * This constant defines a keywork used to access the latest service version.
+ */
+ public static final String LATEST_VERSION = "latest";
+
+ private final String version;
+
+ private static final Map<String, ServiceVersion> values;
+
+ static {
+ values = new HashMap<String, ServiceVersion>();
+ for (final ServiceVersion e : ServiceVersion.values()) {
+ values.put(e.getCode(), e);
+ }
+ }
+
+ private ServiceVersion(final String version) {
+ this.version = version;
+ }
+
+ /**
+ * Returns the version as in appears in URI.
+ *
+ * @return the version.
+ */
+ public String getCode() {
+ return version;
+ }
+
+ /**
+ * Returns enumeration value by version number as it appears in URI.
+ *
+ * @param version version as it appears in URI.
+ * @return ServiceVersion.
+ * @throws IllegalArgumentException in case that the passed code does not match any enumeration value.
+ */
+ public static ServiceVersion fromCode(final String version) throws IllegalArgumentException {
+ // 'latest' keyword check
+ if (version != null && version.equalsIgnoreCase(LATEST_VERSION)) {
+ return VERSION_2_0;
+ }
+
+ final ServiceVersion e = values.get(version);
+ if (e == null) {
+ throw new IllegalArgumentException("Unsupported version " + version);
+ }
+ return e;
+ }
+
+ /**
+ * Gets a {@link FeatureSet} related to this service version.
+ *
+ * @return {@link FeatureSet} related to this version.
+ */
+ public FeatureSet getFeatureSet() {
+ if (this.equals(VERSION_2_0))
+ return new FeatureSetV2();
+ else {
+ return new FeatureSetPreV2();
+ }
+ }
+
+ /**
+ * Checks if ServiceVersion with given code exists.
+ *
+ * @param code Code to check.
+ * @return true if exists, false if not.
+ */
+ public static boolean hasCode(String code) {
+ return values.containsKey(code);
+ }
+}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/clientinitiated/paging/PagingRequestValidator.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/clientinitiated/paging/PagingRequestValidator.java
deleted file mode 100644
index 59ce1d8..0000000
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/clientinitiated/paging/PagingRequestValidator.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2013 Oracle. All rights reserved.
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
- * which accompanies this distribution.
- * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
- * and the Eclipse Distribution License is available at
- * http://www.eclipse.org/org/documents/edl-v10.php.
- *
- * Contributors:
- * gonural - initial implementation
- ******************************************************************************/
-
-package org.eclipse.persistence.jpa.rs.features.clientinitiated.paging;
-
-import java.util.List;
-import java.util.Map;
-
-import javax.persistence.Query;
-import javax.ws.rs.core.UriInfo;
-
-import org.eclipse.persistence.expressions.Expression;
-import org.eclipse.persistence.jpa.rs.QueryParameters;
-import org.eclipse.persistence.jpa.rs.SystemDefaults;
-import org.eclipse.persistence.jpa.rs.features.FeatureRequestValidatorImpl;
-import org.eclipse.persistence.jpa.rs.util.JPARSLogger;
-import org.eclipse.persistence.queries.ObjectLevelReadQuery;
-import org.eclipse.persistence.queries.ReadAllQuery;
-import org.eclipse.persistence.queries.ReadQuery;
-
-public class PagingRequestValidator extends FeatureRequestValidatorImpl {
- private String offset = null;
- private String limit = null;
- public static String DB_QUERY = "dbQuery";
- public static String QUERY = "query";
-
- /* (non-Javadoc)
- * @see org.eclipse.persistence.jpa.rs.features.FeatureRequestValidatorImpl#isRequestValid(javax.ws.rs.core.UriInfo, java.util.Map)
- */
- @Override
- public boolean isRequestValid(UriInfo uri, Map<String, Object> additionalParams) {
- Query query = null;
- ReadQuery dbQuery = null;
-
- if ((additionalParams != null) && (!additionalParams.isEmpty())) {
- dbQuery = (ReadQuery) additionalParams.get(DB_QUERY);
- query = (Query) additionalParams.get(QUERY);
-
- if ((dbQuery != null) && (query != null) && ((dbQuery instanceof ObjectLevelReadQuery) || (dbQuery instanceof ReadAllQuery))) {
- List<Expression> orderBy = null;
- if (dbQuery instanceof ReadAllQuery) {
- orderBy = ((ReadAllQuery) dbQuery).getOrderByExpressions();
- } else if (dbQuery instanceof ObjectLevelReadQuery) {
- orderBy = ((ObjectLevelReadQuery) dbQuery).getOrderByExpressions();
- }
-
- if ((orderBy == null) || (orderBy.isEmpty())) {
- JPARSLogger.warning("no_orderby_clause_for_paging", new Object[] { query.toString() });
- }
- }
- }
-
- Map<String, Object> queryParameters = getQueryParameters(uri);
-
- String paramLimit = (String) queryParameters.get(QueryParameters.JPARS_PAGING_LIMIT);
- String paramOffset = (String) queryParameters.get(QueryParameters.JPARS_PAGING_OFFSET);
-
- if ((paramLimit == null) && (paramOffset == null)) {
- return false;
- }
-
- if (paramOffset != null) {
- offset = paramOffset;
- } else {
- offset = Integer.toString(SystemDefaults.JPARS_DEFAULT_PAGE_OFFSET);
- }
-
- if (paramLimit != null) {
- limit = paramLimit;
- } else {
- limit = Integer.toString(SystemDefaults.JPARS_DEFAULT_PAGE_LIMIT);
- }
-
- try {
- if ((offset != null) && (limit != null)) {
- int intOffset = Integer.parseInt(offset);
- int intLimit = Integer.parseInt(limit);
- if ((intOffset >= 0) && (intLimit > 0)) {
- if (query != null) {
- setOfsetAndLimit(query, intOffset, intLimit);
- return true;
- }
-
- if (dbQuery != null) {
- setOfsetAndLimit(dbQuery, intOffset, intLimit);
- return true;
- }
- }
- return false;
- }
- } catch (NumberFormatException ex) {
- //TODO: Log it!
- }
- return false;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.persistence.jpa.rs.features.FeatureRequestValidatorImpl#isRequested(javax.ws.rs.core.UriInfo, java.util.Map)
- */
- @Override
- public boolean isRequested(UriInfo uri, Map<String, Object> additionalParams) {
- Map<String, Object> queryParameters = getQueryParameters(uri);
- String paramLimit = (String) queryParameters.get(QueryParameters.JPARS_PAGING_LIMIT);
- String paramOffset = (String) queryParameters.get(QueryParameters.JPARS_PAGING_OFFSET);
-
- if ((paramLimit != null) || (paramOffset != null)) {
- return true;
- }
- return false;
- }
-
- private void setOfsetAndLimit(Query query, int offset, int limit) {
- query.setFirstResult(offset);
- query.setMaxResults(limit);
- }
-
- private void setOfsetAndLimit(ReadQuery query, int offset, int limit) {
- query.setFirstResult(offset);
- int maxRows = limit + ((offset >= 0) ? offset : 0);
- query.setMaxRows(maxRows);
- }
-} \ No newline at end of file
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/paging/AbstractPagingValidator.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/paging/AbstractPagingValidator.java
new file mode 100644
index 0000000..4aa8dc9
--- /dev/null
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/paging/AbstractPagingValidator.java
@@ -0,0 +1,108 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Dmitry Kornilov - initial implementation
+ ******************************************************************************/
+
+package org.eclipse.persistence.jpa.rs.features.paging;
+
+import org.eclipse.persistence.jpa.rs.QueryParameters;
+import org.eclipse.persistence.jpa.rs.exceptions.JPARSException;
+import org.eclipse.persistence.jpa.rs.resources.common.AbstractResource;
+
+import javax.ws.rs.core.UriInfo;
+import java.util.Map;
+
+/**
+ * Base class for all pageable request validators.
+ *
+ * @author Dmitry Kornilov
+ */
+abstract class AbstractPagingValidator {
+ private int offset;
+ private int limit;
+
+ private final UriInfo uri;
+
+ final Map<String, Object> queryParameters;
+
+ /**
+ * Creates the validator.
+ *
+ * @param uri request URI.
+ */
+ AbstractPagingValidator(UriInfo uri) {
+ queryParameters = AbstractResource.getQueryParameters(uri);
+ this.uri = uri;
+ }
+
+ /**
+ * Checks if request is valid.
+ *
+ * @return true if request is valid and supports pagination, false if request is valid but doesn't support pagination.
+ * @throws org.eclipse.persistence.jpa.rs.exceptions.JPARSException in case of any validation errors.
+ */
+ abstract boolean isFeatureApplicable() throws JPARSException;
+
+ /**
+ * Checks pagination query parameters. Initializes 'limit' and 'offset' class properties.
+ * Throws {@link java.lang.IllegalArgumentException} in case of errors.
+ *
+ * @param defaultLimit The value of limit if no 'limit' query parameter is present.
+ */
+ void checkParameters(int defaultLimit) {
+ // Read query parameters
+ String paramLimit = (String) queryParameters.get(QueryParameters.JPARS_PAGING_LIMIT);
+ String paramOffset = (String) queryParameters.get(QueryParameters.JPARS_PAGING_OFFSET);
+
+ // Check limit
+ try {
+ if (paramLimit != null) {
+ int intLimit = Integer.parseInt(paramLimit);
+ if (intLimit > defaultLimit) {
+ limit = defaultLimit;
+ } else {
+ limit = intLimit;
+ }
+ } else {
+ limit = defaultLimit;
+ }
+ } catch (NumberFormatException ex) {
+ throw new IllegalArgumentException(String.format("Invalid 'limit' parameter value (limit=%s).", paramLimit));
+ }
+
+ // Check offset
+ try {
+ if (paramOffset != null) {
+ offset = Integer.parseInt(paramOffset);
+ }
+ } catch (NumberFormatException ex) {
+ throw new IllegalArgumentException(String.format("Invalid 'offset' parameter value (offset=%s).", paramOffset));
+ }
+ }
+
+ /**
+ * Returns a value of Offset paging parameter. The value is available only after calling checkParameters method.
+ *
+ * @return the Offset value.
+ */
+ public int getOffset() {
+ return offset;
+ }
+
+ /**
+ * Returns a value of Limit paging parameter. The value is available only after calling checkParameters method.
+ *
+ * @return the Limit value.
+ */
+ public int getLimit() {
+ return limit;
+ }
+}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/paging/PageableFieldValidator.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/paging/PageableFieldValidator.java
new file mode 100644
index 0000000..36dd620
--- /dev/null
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/paging/PageableFieldValidator.java
@@ -0,0 +1,84 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Dmitry Kornilov - initial implementation
+ ******************************************************************************/
+
+package org.eclipse.persistence.jpa.rs.features.paging;
+
+import org.eclipse.persistence.jpa.rs.QueryParameters;
+import org.eclipse.persistence.jpa.rs.annotations.RestPageable;
+import org.eclipse.persistence.jpa.rs.exceptions.JPARSException;
+
+import javax.ws.rs.core.UriInfo;
+import java.lang.reflect.Field;
+
+/**
+ * Finds out if an entity field is pageable and validates paging parameters.
+ *
+ * @author Dmitry Kornilov
+ */
+public final class PageableFieldValidator extends AbstractPagingValidator {
+ private final Class entityClass;
+ private final String fieldName;
+
+ /**
+ * Creates the validator.
+ *
+ * @param entityClass entity class containing a field to validate.
+ * @param fieldName field name to validate.
+ * @param uri request URI.
+ */
+ public PageableFieldValidator(Class entityClass, String fieldName, UriInfo uri) {
+ super(uri);
+ this.entityClass = entityClass;
+ this.fieldName = fieldName;
+ }
+
+ /**
+ * Checks if request is valid.
+ *
+ * @return true if request is valid and supports pagination, false if request is valid but doesn't support pagination.
+ * @throws org.eclipse.persistence.jpa.rs.exceptions.JPARSException in case of any validation errors.
+ */
+ @Override
+ public boolean isFeatureApplicable() throws JPARSException {
+ final RestPageable paginationData = getPaginationData();
+ if (paginationData != null) {
+ // Field supports pagination, do parameters check
+ checkParameters(paginationData.limit());
+ return true;
+ } else {
+ // Pagination is not supported by query. Check that there are no pagination related query parameters.
+ if (queryParameters.containsKey(QueryParameters.JPARS_PAGING_LIMIT)
+ || queryParameters.containsKey(QueryParameters.JPARS_PAGING_OFFSET)) {
+ throw JPARSException.paginationParameterForNotPageableResource();
+ }
+ return false;
+ }
+ }
+
+ /**
+ * Returns {@link RestPageable} annotation of entityClass.fieldName field or null if it doesn't exist.
+ *
+ * @return RestPageable or null if it doesn't exist.
+ */
+ private RestPageable getPaginationData() {
+ try {
+ final Field fld = entityClass.getDeclaredField(fieldName);
+ if (fld.isAnnotationPresent(RestPageable.class)) {
+ return fld.getAnnotation(RestPageable.class);
+ }
+ return null;
+ } catch (NoSuchFieldException e) {
+ return null;
+ }
+ }
+}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/paging/PageableQueryValidator.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/paging/PageableQueryValidator.java
new file mode 100644
index 0000000..5947766
--- /dev/null
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/paging/PageableQueryValidator.java
@@ -0,0 +1,65 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Dmitry Kornilov - initial implementation
+ ******************************************************************************/
+
+package org.eclipse.persistence.jpa.rs.features.paging;
+
+import org.eclipse.persistence.jpa.rs.PersistenceContext;
+import org.eclipse.persistence.jpa.rs.QueryParameters;
+import org.eclipse.persistence.jpa.rs.exceptions.JPARSException;
+
+import javax.ws.rs.core.UriInfo;
+
+/**
+ * Finds out if a named query is pageable and validates paging parameters.
+ *
+ * @author Dmitry Kornilov
+ */
+public final class PageableQueryValidator extends AbstractPagingValidator {
+ private final PersistenceContext context;
+ private final String queryName;
+
+ /**
+ * Creates a validator.
+ *
+ * @param context persistence context
+ * @param queryName query name to validate
+ * @param uri request uri
+ */
+ public PageableQueryValidator(PersistenceContext context, String queryName, UriInfo uri) {
+ super(uri);
+ this.context = context;
+ this.queryName = queryName;
+ }
+
+ /**
+ * Checks if request is valid.
+ *
+ * @return true if request is valid and supports pagination, false if request is valid but doesn't support pagination
+ * @throws org.eclipse.persistence.jpa.rs.exceptions.JPARSException in case of any validation errors
+ */
+ @Override
+ public boolean isFeatureApplicable() throws JPARSException {
+ if (context.isQueryPageable(queryName)) {
+ // Query supports pagination, do parameters check
+ checkParameters(context.getPageableQuery(queryName).limit());
+ return true;
+ } else {
+ // Pagination is not supported by query. Check that there are no pagination related query parameters.
+ if (queryParameters.containsKey(QueryParameters.JPARS_PAGING_LIMIT)
+ || queryParameters.containsKey(QueryParameters.JPARS_PAGING_OFFSET)) {
+ throw JPARSException.paginationParameterForNotPageableResource();
+ }
+ return false;
+ }
+ }
+}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/clientinitiated/paging/PagingResponseBuilder.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/paging/PagingResponseBuilder.java
index 93424bd..3139c0e 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/clientinitiated/paging/PagingResponseBuilder.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/features/paging/PagingResponseBuilder.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2013 Oracle. All rights reserved.
+ * Copyright (c) 2013, 2014 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -10,17 +10,7 @@
* Contributors:
* gonural - initial implementation
******************************************************************************/
-package org.eclipse.persistence.jpa.rs.features.clientinitiated.paging;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.ws.rs.core.UriBuilder;
-import javax.ws.rs.core.UriInfo;
-import javax.xml.bind.JAXBElement;
+package org.eclipse.persistence.jpa.rs.features.paging;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.internal.jpa.rs.metadata.model.ItemLinks;
@@ -37,8 +27,17 @@ import org.eclipse.persistence.jpa.rs.util.list.ReadAllQueryResultCollection;
import org.eclipse.persistence.jpa.rs.util.list.ReportQueryResultCollection;
import org.eclipse.persistence.jpa.rs.util.list.ReportQueryResultListItem;
+import javax.ws.rs.core.UriBuilder;
+import javax.ws.rs.core.UriInfo;
+import javax.xml.bind.JAXBElement;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
public class PagingResponseBuilder extends FeatureResponseBuilderImpl {
- private static String NO_PREVIOUS_CHUNK = "-1";
+ private static final String NO_PREVIOUS_CHUNK = "-1";
/* (non-Javadoc)
* @see org.eclipse.persistence.jpa.rs.features.FeatureResponseBuilderImpl#buildReadAllQueryResponse(org.eclipse.persistence.jpa.rs.PersistenceContext, java.util.Map, java.util.List, javax.ws.rs.core.UriInfo)
@@ -69,15 +68,12 @@ public class PagingResponseBuilder extends FeatureResponseBuilderImpl {
public Object buildAttributeResponse(PersistenceContext context, Map<String, Object> queryParams, String attribute, Object results, UriInfo uriInfo) {
if (results instanceof Collection) {
if (containsDomainObjects(results)) {
- ReadAllQueryResultCollection collection = (ReadAllQueryResultCollection) results;
- if (collection != null) {
- List<Object> items = collection.getItems();
- if ((items != null) && (!items.isEmpty())) {
- ReadAllQueryResultCollection response = new ReadAllQueryResultCollection();
- response.setItems(items);
- response.setCount(collection.getItems().size());
- return populatePagedCollectionLinks(queryParams, uriInfo, response);
- }
+ List<Object> items = (Vector)results;
+ if ((items != null) && (!items.isEmpty())) {
+ ReadAllQueryResultCollection response = new ReadAllQueryResultCollection();
+ response.setItems(items);
+ response.setCount(items.size());
+ return populatePagedCollectionLinks(queryParams, uriInfo, response);
}
}
}
@@ -87,8 +83,7 @@ public class PagingResponseBuilder extends FeatureResponseBuilderImpl {
@SuppressWarnings("rawtypes")
private boolean containsDomainObjects(Object object) {
Collection collection = (Collection) object;
- for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
- Object collectionItem = iterator.next();
+ for (Object collectionItem : collection) {
if (PersistenceWeavedRest.class.isAssignableFrom(collectionItem.getClass())) {
return true;
}
@@ -103,8 +98,12 @@ public class PagingResponseBuilder extends FeatureResponseBuilderImpl {
ItemLinks itemLinks = new ItemLinks();
PersistenceWeavedRest entity = (PersistenceWeavedRest) result;
String entityId = IdHelper.stringifyId(result, descriptor.getAlias(), context);
- String href = context.getBaseURI() + context.getVersion() + "/" + context.getName() + "/entity/" + descriptor.getAlias() + "/" + entityId;
- itemLinks.addItem(new LinkV2(ReservedWords.JPARS_REL_SELF, href));
+
+ StringBuilder href = new StringBuilder(context.getBaseURI().toString());
+ href.append(context.getVersion()).append("/").append(context.getName()).append("/entity/")
+ .append(descriptor.getAlias()).append("/").append(entityId);
+
+ itemLinks.addItem(new LinkV2(ReservedWords.JPARS_REL_SELF, href.toString()));
entity._persistence_setLinks(itemLinks);
return entity;
}
@@ -116,15 +115,13 @@ public class PagingResponseBuilder extends FeatureResponseBuilderImpl {
List<LinkV2> links = new ArrayList<LinkV2>();
int limit = Integer.parseInt((String) queryParams.get(QueryParameters.JPARS_PAGING_LIMIT));
int offset = Integer.parseInt((String) queryParams.get(QueryParameters.JPARS_PAGING_OFFSET));
- String nextOffset = null;
- String prevOffset = null;
+
+ String nextOffset;
+ String prevOffset;
if (limit > offset) {
nextOffset = String.valueOf(limit);
prevOffset = NO_PREVIOUS_CHUNK;
} else {
- if (limit == offset) {
- prevOffset = "0";
- }
nextOffset = String.valueOf(limit + offset);
prevOffset = String.valueOf(offset - limit);
}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractEntityResource.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractEntityResource.java
index 0eba590..055a8ae 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractEntityResource.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractEntityResource.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -7,26 +7,12 @@
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
- *
+ * Contributors:
+ * Dmitry Kornilov - pagination related changes
******************************************************************************/
package org.eclipse.persistence.jpa.rs.resources.common;
-import static org.eclipse.persistence.jpa.rs.util.StreamingOutputMarshaller.mediaType;
-
-import java.io.InputStream;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.persistence.EntityManager;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
-import javax.ws.rs.core.Response.Status;
-import javax.ws.rs.core.UriInfo;
-
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.descriptors.RelationalDescriptor;
import org.eclipse.persistence.expressions.Expression;
@@ -35,11 +21,10 @@ import org.eclipse.persistence.internal.sessions.AbstractSession;
import org.eclipse.persistence.jpa.rs.PersistenceContext;
import org.eclipse.persistence.jpa.rs.QueryParameters;
import org.eclipse.persistence.jpa.rs.exceptions.JPARSException;
-import org.eclipse.persistence.jpa.rs.features.FeatureRequestValidator;
import org.eclipse.persistence.jpa.rs.features.FeatureResponseBuilder;
import org.eclipse.persistence.jpa.rs.features.FeatureSet;
import org.eclipse.persistence.jpa.rs.features.FeatureSet.Feature;
-import org.eclipse.persistence.jpa.rs.features.clientinitiated.paging.PagingRequestValidator;
+import org.eclipse.persistence.jpa.rs.features.paging.PageableFieldValidator;
import org.eclipse.persistence.jpa.rs.util.IdHelper;
import org.eclipse.persistence.jpa.rs.util.JPARSLogger;
import org.eclipse.persistence.jpa.rs.util.StreamingOutputMarshaller;
@@ -51,9 +36,23 @@ import org.eclipse.persistence.queries.ReadAllQuery;
import org.eclipse.persistence.queries.ReadQuery;
import org.eclipse.persistence.sessions.DatabaseSession;
+import javax.persistence.EntityManager;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.ResponseBuilder;
+import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.core.UriInfo;
+import java.io.InputStream;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+
+import static org.eclipse.persistence.jpa.rs.util.StreamingOutputMarshaller.mediaType;
+
/**
- * @author gonural
+ * Base class for entity resource.
*
+ * @author gonural
*/
public abstract class AbstractEntityResource extends AbstractResource {
private static final String CLASS_NAME = AbstractEntityResource.class.getName();
@@ -67,9 +66,7 @@ public abstract class AbstractEntityResource extends AbstractResource {
Object entityId = IdHelper.buildId(context, type, id);
em = context.getEmf().createEntityManager(getMatrixParameters(uriInfo, persistenceUnit));
- Object entity = null;
-
- entity = em.find(context.getClass(type), entityId, getQueryParameters(uriInfo));
+ Object entity = em.find(context.getClass(type), entityId, getQueryParameters(uriInfo));
DatabaseSession serverSession = context.getServerSession();
ClassDescriptor descriptor = serverSession.getClassDescriptor(context.getClass(type));
if (descriptor == null) {
@@ -81,15 +78,13 @@ public abstract class AbstractEntityResource extends AbstractResource {
throw JPARSException.databaseMappingCouldNotBeFoundForEntityAttribute(attribute, type, id, persistenceUnit);
}
- Object result = null;
-
if (!attributeMapping.isCollectionMapping()) {
- result = attributeMapping.getRealAttributeValueFromAttribute(attributeMapping.getAttributeValueFromObject(entity), entity, (AbstractSession) serverSession);
+ Object result = attributeMapping.getRealAttributeValueFromAttribute(attributeMapping.getAttributeValueFromObject(entity), entity, (AbstractSession) serverSession);
if (result == null) {
JPARSLogger.error("jpars_could_not_find_entity_for_attribute", new Object[] { attribute, type, id, persistenceUnit });
throw JPARSException.attributeCouldNotBeFoundForEntity(attribute, type, id, persistenceUnit);
}
- return findAttributeResponse(context, attribute, type, id, persistenceUnit, result, headers, uriInfo, context.getSupportedFeatureSet().getResponseBuilder(Feature.NO_PAGING));
+ return findAttributeResponse(context, attribute, type, id, persistenceUnit, result, getQueryParameters(uriInfo), headers, uriInfo, context.getSupportedFeatureSet().getResponseBuilder(Feature.NO_PAGING));
}
ReadQuery query = (ReadQuery) ((((ForeignReferenceMapping) attributeMapping).getSelectionQuery()).clone());
@@ -100,21 +95,25 @@ public abstract class AbstractEntityResource extends AbstractResource {
FeatureSet featureSet = context.getSupportedFeatureSet();
AbstractSession clientSession = context.getClientSession(em);
if (featureSet.isSupported(Feature.PAGING)) {
- FeatureRequestValidator requestValidator = featureSet.getRequestValidator(Feature.PAGING);
- Map<String, Object> map = new HashMap<String, Object>();
- map.put(PagingRequestValidator.DB_QUERY, query);
- if (requestValidator.isRequested(uriInfo, null)) {
- if (!requestValidator.isRequestValid(uriInfo, map)) {
- throw JPARSException.invalidPagingRequest();
- }
- // check orderBy, and generate a warning if there is none
+ PageableFieldValidator validator = new PageableFieldValidator(entity.getClass(), attribute, uriInfo);
+ if (validator.isFeatureApplicable()) {
+ query.setMaxRows(validator.getLimit());
+ query.setFirstResult(validator.getOffset());
+
+ // We need to add limit and offset to query parameters because request builder reads it from there
+ Map<String, Object> queryParams = getQueryParameters(uriInfo);
+ queryParams.put(QueryParameters.JPARS_PAGING_LIMIT, String.valueOf(validator.getLimit()));
+ queryParams.put(QueryParameters.JPARS_PAGING_OFFSET, String.valueOf(validator.getOffset()));
+
+ // check orderBy, and generate a warning if there is none
checkOrderBy(query);
- result = clientSession.executeQuery(query, descriptor.getObjectBuilder().buildRow(entity, clientSession, WriteType.INSERT));
- return findAttributeResponse(context, attribute, type, id, persistenceUnit, result, headers, uriInfo, context.getSupportedFeatureSet().getResponseBuilder(Feature.PAGING));
+
+ Object result = clientSession.executeQuery(query, descriptor.getObjectBuilder().buildRow(entity, clientSession, WriteType.INSERT));
+ return findAttributeResponse(context, attribute, type, id, persistenceUnit, result, queryParams, headers, uriInfo, context.getSupportedFeatureSet().getResponseBuilder(Feature.PAGING));
}
}
- result = clientSession.executeQuery(query, descriptor.getObjectBuilder().buildRow(entity, clientSession, WriteType.INSERT));
- return findAttributeResponse(context, attribute, type, id, persistenceUnit, result, headers, uriInfo, context.getSupportedFeatureSet().getResponseBuilder(Feature.NO_PAGING));
+ Object result = clientSession.executeQuery(query, descriptor.getObjectBuilder().buildRow(entity, clientSession, WriteType.INSERT));
+ return findAttributeResponse(context, attribute, type, id, persistenceUnit, result, getQueryParameters(uriInfo), headers, uriInfo, context.getSupportedFeatureSet().getResponseBuilder(Feature.NO_PAGING));
} catch (Exception ex) {
throw JPARSException.exceptionOccurred(ex);
} finally {
@@ -145,7 +144,7 @@ public abstract class AbstractEntityResource extends AbstractResource {
}
@SuppressWarnings("rawtypes")
- protected Response createInternal(String version, String persistenceUnit, String type, HttpHeaders headers, UriInfo uriInfo, InputStream in) throws Exception {
+ protected Response createInternal(String version, String persistenceUnit, String type, HttpHeaders headers, UriInfo uriInfo, InputStream in) {
JPARSLogger.entering(CLASS_NAME, "createInternal", new Object[] { "PUT", headers.getMediaType(), version, persistenceUnit, type, uriInfo.getRequestUri().toASCIIString() });
try {
PersistenceContext context = getPersistenceContext(persistenceUnit, type, uriInfo.getBaseUri(), version, null);
@@ -186,12 +185,10 @@ public abstract class AbstractEntityResource extends AbstractResource {
if (value != null) {
if (value instanceof ValueHolder) {
ValueHolder holder = (ValueHolder) value;
- if (holder != null) {
- Object obj = holder.getValue();
- if (obj != null) {
- JPARSLogger.error("jpars_put_not_idempotent", new Object[] { type, persistenceUnit });
- throw JPARSException.entityIsNotIdempotent(type, persistenceUnit);
- }
+ Object obj = holder.getValue();
+ if (obj != null) {
+ JPARSLogger.error("jpars_put_not_idempotent", new Object[] { type, persistenceUnit });
+ throw JPARSException.entityIsNotIdempotent(type, persistenceUnit);
}
} else if (value instanceof Collection) {
if (!(((Collection) value).isEmpty())) {
@@ -220,8 +217,7 @@ public abstract class AbstractEntityResource extends AbstractResource {
JPARSLogger.entering(CLASS_NAME, "updateInternal", new Object[] { "POST", headers.getMediaType(), version, persistenceUnit, type, uriInfo.getRequestUri().toASCIIString() });
try {
PersistenceContext context = getPersistenceContext(persistenceUnit, type, uriInfo.getBaseUri(), version, null);
- Object entity = null;
- entity = context.unmarshalEntity(type, mediaType(headers.getAcceptableMediaTypes()), in);
+ Object entity = context.unmarshalEntity(type, mediaType(headers.getAcceptableMediaTypes()), in);
entity = context.merge(getMatrixParameters(uriInfo, persistenceUnit), entity);
return Response.ok(new StreamingOutputMarshaller(context, singleEntityResponse(context, entity, uriInfo), headers.getAcceptableMediaTypes())).build();
} catch (Exception ex) {
@@ -234,15 +230,14 @@ public abstract class AbstractEntityResource extends AbstractResource {
try {
PersistenceContext context = getPersistenceContext(persistenceUnit, type, uriInfo.getBaseUri(), version, null);
Object entityId = IdHelper.buildId(context, type, id);
- Object entity = null;
String partner = getRelationshipPartner(getMatrixParameters(uriInfo, attribute), getQueryParameters(uriInfo));
ClassDescriptor descriptor = context.getDescriptor(type);
- DatabaseMapping mapping = (DatabaseMapping) descriptor.getMappingForAttributeName(attribute);
+ DatabaseMapping mapping = descriptor.getMappingForAttributeName(attribute);
if (!mapping.isForeignReferenceMapping()) {
JPARSLogger.error("jpars_could_not_find_appropriate_mapping_for_update", new Object[] { attribute, type, id, persistenceUnit });
throw JPARSException.databaseMappingCouldNotBeFoundForEntityAttribute(attribute, type, id, persistenceUnit);
}
- entity = context.unmarshalEntity(((ForeignReferenceMapping) mapping).getReferenceDescriptor().getAlias(), mediaType(headers.getAcceptableMediaTypes()), in);
+ Object entity = context.unmarshalEntity(mapping.getReferenceDescriptor().getAlias(), mediaType(headers.getAcceptableMediaTypes()), in);
Object result = context.updateOrAddAttribute(getMatrixParameters(uriInfo, persistenceUnit), type, entityId, getQueryParameters(uriInfo), attribute, entity, partner);
if (result == null) {
JPARSLogger.error("jpars_could_not_update_attribute", new Object[] { attribute, type, id, persistenceUnit });
@@ -266,14 +261,14 @@ public abstract class AbstractEntityResource extends AbstractResource {
}
if ((attribute == null) && (listItemId == null)) {
- JPARSException.invalidRemoveAttributeRequest(attribute, type, id, persistenceUnit);
+ JPARSException.invalidRemoveAttributeRequest(null, type, id, persistenceUnit);
}
String partner = getRelationshipPartner(matrixParams, queryParams);
PersistenceContext context = getPersistenceContext(persistenceUnit, type, uriInfo.getBaseUri(), version, null);
Object entityId = IdHelper.buildId(context, type, id);
ClassDescriptor descriptor = context.getDescriptor(type);
- DatabaseMapping mapping = (DatabaseMapping) descriptor.getMappingForAttributeName(attribute);
+ DatabaseMapping mapping = descriptor.getMappingForAttributeName(attribute);
if (!mapping.isForeignReferenceMapping()) {
JPARSLogger.error("jpars_could_not_find_appropriate_mapping_for_update", new Object[] { attribute, type, id, persistenceUnit });
throw JPARSException.databaseMappingCouldNotBeFoundForEntityAttribute(attribute, type, id, persistenceUnit);
@@ -307,8 +302,7 @@ public abstract class AbstractEntityResource extends AbstractResource {
}
}
- private Response findAttributeResponse(PersistenceContext context, String attribute, String entityType, String id, String persistenceUnit, Object queryResults, HttpHeaders headers, UriInfo uriInfo, FeatureResponseBuilder responseBuilder) {
- Map<String, Object> queryParams = getQueryParameters(uriInfo);
+ private Response findAttributeResponse(PersistenceContext context, String attribute, String entityType, String id, String persistenceUnit, Object queryResults, Map<String, Object> queryParams, HttpHeaders headers, UriInfo uriInfo, FeatureResponseBuilder responseBuilder) {
if (queryResults != null) {
Object results = responseBuilder.buildAttributeResponse(context, queryParams, attribute, queryResults, uriInfo);
if (results != null) {
@@ -318,14 +312,13 @@ public abstract class AbstractEntityResource extends AbstractResource {
throw JPARSException.responseCouldNotBeBuiltForFindAttributeRequest(attribute, entityType, id, persistenceUnit);
}
}
- return Response.ok(new StreamingOutputMarshaller(context, queryResults, headers.getAcceptableMediaTypes())).build();
+ return Response.ok(new StreamingOutputMarshaller(context, null, headers.getAcceptableMediaTypes())).build();
}
private void checkOrderBy(ReadQuery query) {
- List<Expression> orderBy = null;
if (query.isReadAllQuery()) {
ReadAllQuery readAllQuery = (ReadAllQuery) query;
- orderBy = readAllQuery.getOrderByExpressions();
+ List<Expression> orderBy = readAllQuery.getOrderByExpressions();
if ((orderBy == null) || (orderBy.isEmpty())) {
JPARSLogger.warning("no_orderby_clause_for_paging", new Object[] { query.toString() });
}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractPersistenceUnitResource.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractPersistenceUnitResource.java
index 974014d..23dbaed 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractPersistenceUnitResource.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractPersistenceUnitResource.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -11,20 +11,6 @@
******************************************************************************/
package org.eclipse.persistence.jpa.rs.resources.common;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.eis.mappings.EISCompositeCollectionMapping;
import org.eclipse.persistence.internal.expressions.ConstantExpression;
@@ -51,6 +37,19 @@ import org.eclipse.persistence.queries.DatabaseQuery;
import org.eclipse.persistence.queries.ReportQuery;
import org.eclipse.persistence.sessions.DatabaseRecord;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
/**
* @author gonural
*
@@ -266,12 +265,12 @@ public class AbstractPersistenceUnitResource extends AbstractResource {
private Query getQuery(DatabaseQuery query, PersistenceContext context) {
String method = query.isReadQuery() ? "get" : "post";
String jpql = query.getJPQLString() == null ? "" : query.getJPQLString();
- StringBuffer parameterString = new StringBuffer();
+ StringBuilder parameterString = new StringBuilder();
Iterator<String> argumentsIterator = query.getArguments().iterator();
while (argumentsIterator.hasNext()) {
String argument = argumentsIterator.next();
parameterString.append(";");
- parameterString.append(argument + "={" + argument + "}");
+ parameterString.append(argument).append("={").append(argument).append("}");
}
String version = context.getVersion();
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractQueryResource.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractQueryResource.java
index bd5f298..c0aafa7 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractQueryResource.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractQueryResource.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -7,39 +7,41 @@
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
- *
+ * Contributors:
+ * Dmitry Kornilov - pagination related changes
******************************************************************************/
package org.eclipse.persistence.jpa.rs.resources.common;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.persistence.Query;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-import javax.xml.bind.JAXBElement;
-import javax.xml.namespace.QName;
-
import org.eclipse.persistence.internal.jpa.EJBQueryImpl;
import org.eclipse.persistence.internal.queries.ReportItem;
import org.eclipse.persistence.jpa.rs.PersistenceContext;
+import org.eclipse.persistence.jpa.rs.QueryParameters;
import org.eclipse.persistence.jpa.rs.ReservedWords;
import org.eclipse.persistence.jpa.rs.exceptions.JPARSException;
-import org.eclipse.persistence.jpa.rs.features.FeatureRequestValidator;
import org.eclipse.persistence.jpa.rs.features.FeatureResponseBuilder;
import org.eclipse.persistence.jpa.rs.features.FeatureSet;
import org.eclipse.persistence.jpa.rs.features.FeatureSet.Feature;
-import org.eclipse.persistence.jpa.rs.features.clientinitiated.paging.PagingRequestValidator;
+import org.eclipse.persistence.jpa.rs.features.core.selflinks.SelfLinksResponseBuilder;
+import org.eclipse.persistence.jpa.rs.features.paging.PageableQueryValidator;
+import org.eclipse.persistence.jpa.rs.features.paging.PagingResponseBuilder;
import org.eclipse.persistence.jpa.rs.util.JPARSLogger;
import org.eclipse.persistence.jpa.rs.util.StreamingOutputMarshaller;
import org.eclipse.persistence.queries.DatabaseQuery;
import org.eclipse.persistence.queries.ReportQuery;
+import javax.persistence.Query;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import javax.xml.bind.JAXBElement;
+import javax.xml.namespace.QName;
+import java.util.List;
+import java.util.Map;
+
/**
- * @author gonural
+ * Base class for query resource.
*
+ * @author gonural
*/
public abstract class AbstractQueryResource extends AbstractResource {
private static final String CLASS_NAME = AbstractQueryResource.class.getName();
@@ -49,7 +51,7 @@ public abstract class AbstractQueryResource extends AbstractResource {
*
* @param version the version
* @param persistenceUnit the persistence unit
- * @param name the name
+ * @param queryName the name
* @param headers the http headers
* @param uriInfo the uri info
* @return the response
@@ -68,11 +70,11 @@ public abstract class AbstractQueryResource extends AbstractResource {
}
/**
- * Named query internal.
+ * Executes given named query.
*
* @param version the version
* @param persistenceUnit the persistence unit
- * @param name the name
+ * @param queryName named query to execute
* @param headers the http headers
* @param uriInfo the uri info
* @return the response
@@ -80,33 +82,45 @@ public abstract class AbstractQueryResource extends AbstractResource {
protected Response namedQueryInternal(String version, String persistenceUnit, String queryName, HttpHeaders headers, UriInfo uriInfo) {
JPARSLogger.entering(CLASS_NAME, "namedQueryInternal", new Object[] { "GET", version, persistenceUnit, queryName, uriInfo.getRequestUri().toASCIIString() });
try {
- PersistenceContext context = getPersistenceContext(persistenceUnit, null, uriInfo.getBaseUri(), version, null);
- Query query = context.buildQuery(getMatrixParameters(uriInfo, persistenceUnit), queryName, getMatrixParameters(uriInfo, queryName), getQueryParameters(uriInfo));
- DatabaseQuery dbQuery = ((EJBQueryImpl<?>) query).getDatabaseQuery();
+ final PersistenceContext context = getPersistenceContext(persistenceUnit, null, uriInfo.getBaseUri(), version, null);
+ final Query query = context.buildQuery(getMatrixParameters(uriInfo, persistenceUnit), queryName, getMatrixParameters(uriInfo, queryName), getQueryParameters(uriInfo));
+ final DatabaseQuery dbQuery = ((EJBQueryImpl<?>) query).getDatabaseQuery();
+ final FeatureSet featureSet = context.getSupportedFeatureSet();
- FeatureSet featureSet = context.getSupportedFeatureSet();
+ final Response response;
if (featureSet.isSupported(Feature.PAGING)) {
- FeatureRequestValidator requestValidator = featureSet.getRequestValidator(Feature.PAGING);
- if (requestValidator.isRequested(uriInfo, null)) {
- Map<String, Object> map = new HashMap<String, Object>();
- map.put(PagingRequestValidator.DB_QUERY, dbQuery);
- map.put(PagingRequestValidator.QUERY, query);
- if (!requestValidator.isRequestValid(uriInfo, map)) {
- // some query parameters for paging are invalid
- throw JPARSException.invalidPagingRequest();
- }
- return namedQueryResponse(context, queryName, dbQuery, query, headers, uriInfo, featureSet.getResponseBuilder(Feature.PAGING));
- }
+ response = processPageableQuery(context, queryName, dbQuery, query, headers, uriInfo);
+ } else {
+ response = namedQueryResponse(context, queryName, dbQuery, query, headers, uriInfo, featureSet.getResponseBuilder(Feature.NO_PAGING));
}
- return namedQueryResponse(context, queryName, dbQuery, query, headers, uriInfo, featureSet.getResponseBuilder(Feature.NO_PAGING));
+
+ return response;
} catch (Exception ex) {
throw JPARSException.exceptionOccurred(ex);
}
}
+ private Response processPageableQuery(PersistenceContext context, String queryName, DatabaseQuery dbQuery, Query query, HttpHeaders headers, UriInfo uriInfo) {
+ final PageableQueryValidator validator = new PageableQueryValidator(context, queryName, uriInfo);
+ if (validator.isFeatureApplicable()) {
+ // Do pagination
+ query.setFirstResult(validator.getOffset());
+ query.setMaxResults(validator.getLimit());
+ return namedQueryResponse(context, queryName, dbQuery, query, headers, uriInfo, new PagingResponseBuilder());
+ } else {
+ // No pagination
+ return namedQueryResponse(context, queryName, dbQuery, query, headers, uriInfo, new SelfLinksResponseBuilder());
+ }
+ }
+
@SuppressWarnings("unchecked")
private Response namedQueryResponse(PersistenceContext context, String queryName, DatabaseQuery dbQuery, Query query, HttpHeaders headers, UriInfo uriInfo, FeatureResponseBuilder responseBuilder) {
+ // We need to add limit and offset to query parameters because request builder reads it from there
Map<String, Object> queryParams = getQueryParameters(uriInfo);
+ if (query.getMaxResults() != -1) {
+ queryParams.put(QueryParameters.JPARS_PAGING_LIMIT, String.valueOf(query.getMaxResults()));
+ queryParams.put(QueryParameters.JPARS_PAGING_OFFSET, String.valueOf(query.getFirstResult()));
+ }
if (dbQuery instanceof ReportQuery) {
// simple types selected : select u.name, u.age from employee
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractResource.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractResource.java
index f642535..e5ead67 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractResource.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/resources/common/AbstractResource.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -11,23 +11,6 @@
******************************************************************************/
package org.eclipse.persistence.jpa.rs.resources.common;
-import java.io.StringWriter;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.net.URLDecoder;
-import java.net.URLEncoder;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.ServiceLoader;
-import java.util.UUID;
-
-import javax.ws.rs.core.PathSegment;
-import javax.ws.rs.core.UriInfo;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Marshaller;
-
import org.eclipse.persistence.internal.jpa.rs.metadata.model.Attribute;
import org.eclipse.persistence.internal.jpa.rs.metadata.model.Descriptor;
import org.eclipse.persistence.internal.jpa.rs.metadata.model.Link;
@@ -44,10 +27,27 @@ import org.eclipse.persistence.jpa.rs.PersistenceContextFactory;
import org.eclipse.persistence.jpa.rs.PersistenceContextFactoryProvider;
import org.eclipse.persistence.jpa.rs.QueryParameters;
import org.eclipse.persistence.jpa.rs.exceptions.JPARSException;
+import org.eclipse.persistence.jpa.rs.features.ServiceVersion;
import org.eclipse.persistence.jpa.rs.util.JPARSLogger;
import org.eclipse.persistence.jpa.rs.util.list.LinkList;
import org.eclipse.persistence.jpa.rs.util.list.QueryList;
+import javax.ws.rs.core.PathSegment;
+import javax.ws.rs.core.UriInfo;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+import java.io.StringWriter;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.ServiceLoader;
+import java.util.UUID;
+
/**
* @author gonural
*
@@ -57,9 +57,6 @@ public abstract class AbstractResource {
public static final String SERVICE_VERSION_FORMAT = "v\\d\\.\\d";
protected PersistenceContextFactory factory;
- public static final String SERVICE_VERSION_1_0 = "v1.0";
- public static final String SERVICE_VERSION_2_0 = "v2.0";
-
/**
* Sets the persistence factory.
*
@@ -144,7 +141,7 @@ public abstract class AbstractResource {
* @return the query parameters
*
*/
- protected static Map<String, Object> getQueryParameters(UriInfo info) {
+ public static Map<String, Object> getQueryParameters(UriInfo info) {
Map<String, Object> queryParameters = new HashMap<String, Object>();
for (String key : info.getQueryParameters().keySet()) {
queryParameters.put(key, info.getQueryParameters().getFirst(key));
@@ -159,10 +156,7 @@ public abstract class AbstractResource {
* @return true, if is valid version
*/
protected static boolean isValidVersion(String version) {
- if ((version == null) || (SERVICE_VERSION_1_0.equals(version)) || (SERVICE_VERSION_2_0.equals(version))) {
- return true;
- }
- return false;
+ return ServiceVersion.hasCode(version);
}
/**
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/IdHelper.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/IdHelper.java
index bb5e2d0..d073340 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/IdHelper.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/IdHelper.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -12,13 +12,6 @@
******************************************************************************/
package org.eclipse.persistence.jpa.rs.util;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.StringTokenizer;
-
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.internal.descriptors.PersistenceEntity;
@@ -33,6 +26,13 @@ import org.eclipse.persistence.mappings.OneToOneMapping;
import org.eclipse.persistence.queries.FetchGroupTracker;
import org.eclipse.persistence.sessions.DatabaseSession;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.StringTokenizer;
+
/**
* EclipseLink helper class used for converting composite key values passed into
* JAX-RS calls as query or matrix parameters into a value that can be used in a
@@ -112,7 +112,7 @@ public class IdHelper {
index++;
}
Collections.sort(pkIndices);
- StringBuffer key = new StringBuffer();
+ StringBuilder key = new StringBuilder();
Iterator<SortableKey> sortableKeys = pkIndices.iterator();
List<DatabaseField> refObjectdbFields = null;
while (sortableKeys.hasNext()) {
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/JPARSLogger.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/JPARSLogger.java
index 2cd641a..f0b6760 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/JPARSLogger.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/JPARSLogger.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2014 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -12,6 +12,12 @@
******************************************************************************/
package org.eclipse.persistence.jpa.rs.util;
+import org.eclipse.persistence.internal.weaving.PersistenceWeavedRest;
+import org.eclipse.persistence.jpa.rs.DataStorage;
+import org.eclipse.persistence.jpa.rs.PersistenceContext;
+import org.eclipse.persistence.jpa.rs.logging.LoggingLocalization;
+
+import javax.ws.rs.core.MediaType;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -21,13 +27,6 @@ import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
-import javax.ws.rs.core.MediaType;
-
-import org.eclipse.persistence.internal.weaving.PersistenceWeavedRest;
-import org.eclipse.persistence.jpa.rs.DataStorage;
-import org.eclipse.persistence.jpa.rs.PersistenceContext;
-import org.eclipse.persistence.jpa.rs.logging.LoggingLocalization;
-
public class JPARSLogger {
static final Logger logger = Logger.getLogger("org.eclipse.persistence.jpars");
@@ -188,9 +187,7 @@ public class JPARSLogger {
if (params != null) {
Object[] paramsWithRequestId = new Object[params.length + 1];
paramsWithRequestId[0] = requestId;
- for (int i = 0; i < params.length; i++) {
- paramsWithRequestId[i + 1] = params[i];
- }
+ System.arraycopy(params, 0, paramsWithRequestId, 1, params.length);
return paramsWithRequestId;
}
return new Object[] { requestId };
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/MethodExitLogData.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/MethodExitLogData.java
index aa32485..b51b1f5 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/MethodExitLogData.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/MethodExitLogData.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -30,7 +30,7 @@ public class MethodExitLogData {
*/
@Override
public String toString() {
- StringBuffer message = new StringBuffer();
+ StringBuilder message = new StringBuilder();
if (result != null) {
for (int i = 0; i < result.length; i++) {
Object object = result[i];
diff --git a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/JPARSErrorCodes.java b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/JPARSErrorCodes.java
index 6d9a8d2..dc4d49b 100644
--- a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/JPARSErrorCodes.java
+++ b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/JPARSErrorCodes.java
@@ -1,5 +1,5 @@
/*******************************************************************************
-* Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
+* Copyright (c) 2013, 2014 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -31,6 +31,7 @@ public class JPARSErrorCodes {
public static final int SESSION_BEAN_COULD_NOT_BE_FOUND = 61013;
public static final int RESPONSE_COULD_NOT_BE_BUILT_FOR_NAMED_QUERY_REQUEST = 61014;
public static final int INVALID_SERVICE_VERSION = 61015;
+ public static final int PAGINATION_PARAMETER_USED_FOR_NOT_PAGEABLE_RESOURCE = 61016;
//
public static final int AN_EXCEPTION_OCCURRED = 61999;
diff --git a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/i18n/JPARSExceptionResource.java b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/i18n/JPARSExceptionResource.java
index dc5e3d2..6dbc63f 100644
--- a/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/i18n/JPARSExceptionResource.java
+++ b/foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/exceptions/i18n/JPARSExceptionResource.java
@@ -12,10 +12,10 @@
******************************************************************************/
package org.eclipse.persistence.exceptions.i18n;
-import java.util.ListResourceBundle;
-
import org.eclipse.persistence.exceptions.JPARSErrorCodes;
+import java.util.ListResourceBundle;
+
/*
* English resource bundle for JPARSException
*
@@ -39,6 +39,7 @@ public class JPARSExceptionResource extends ListResourceBundle {
{ String.valueOf(JPARSErrorCodes.SESSION_BEAN_COULD_NOT_BE_FOUND), "Session bean lookup with JNDI name {0} has failed." },
{ String.valueOf(JPARSErrorCodes.RESPONSE_COULD_NOT_BE_BUILT_FOR_NAMED_QUERY_REQUEST), "Response for find named query request for query {0} in persistence unit {1} could not be built successfully." },
{ String.valueOf(JPARSErrorCodes.AN_EXCEPTION_OCCURRED), "{0} occurred." },
+ { String.valueOf(JPARSErrorCodes.PAGINATION_PARAMETER_USED_FOR_NOT_PAGEABLE_RESOURCE), "Pagination query parameter (limit or offset) used for non-pageable resource." },
};
@Override
diff --git a/jpa/eclipselink.jpars.test/antbuild.xml b/jpa/eclipselink.jpars.test/antbuild.xml
index 509bffe..33589d7 100644
--- a/jpa/eclipselink.jpars.test/antbuild.xml
+++ b/jpa/eclipselink.jpars.test/antbuild.xml
@@ -245,7 +245,7 @@
<!-- Run targets -->
<target name="test" depends="compile-jpars-tests" description="run jpars tests">
- <property name="SERVER_URL" value="http://localhost:8080"/>
+ <property name="SERVER_URL" value="http://localhost:7001"/>
<property name="JPARS_VERSION" value="v1.0"/>
<echo message="Server url is ${SERVER_URL}"/>
<echo message="jpars version is ${JPARS_VERSION}"/>
@@ -263,6 +263,7 @@
<mkdir dir="${eclipselink.jpars.test}/stage/WEB-INF/lib"/>
<mkdir dir="${eclipselink.jpars.test}/stage/WEB-INF/classes/org/eclipse/persistence/jpars/test/model"/>
<mkdir dir="${eclipselink.jpars.test}/stage/WEB-INF/classes/org/eclipse/persistence/jpars/test/model/auction"/>
+ <mkdir dir="${eclipselink.jpars.test}/stage/WEB-INF/classes/org/eclipse/persistence/jpars/test/model/basket"/>
<mkdir dir="${eclipselink.jpars.test}/stage/WEB-INF/classes/org/eclipse/persistence/jpars/test/model/dynamic"/>
<mkdir dir="${eclipselink.jpars.test}/stage/WEB-INF/classes/org/eclipse/persistence/jpars/test/model/employee"/>
<mkdir dir="${eclipselink.jpars.test}/stage/WEB-INF/classes/org/eclipse/persistence/jpars/test/model/traveler"/>
@@ -280,6 +281,9 @@
<copy todir="${eclipselink.jpars.test}/stage/WEB-INF/classes/org/eclipse/persistence/jpars/test/model/auction">
<fileset dir="${eclipselink.jpars.test}/classes/org/eclipse/persistence/jpars/test/model/auction" includes="*.class"/>
</copy>
+ <copy todir="${eclipselink.jpars.test}/stage/WEB-INF/classes/org/eclipse/persistence/jpars/test/model/basket">
+ <fileset dir="${eclipselink.jpars.test}/classes/org/eclipse/persistence/jpars/test/model/basket" includes="*.class"/>
+ </copy>
<copy todir="${eclipselink.jpars.test}/stage/WEB-INF/classes/org/eclipse/persistence/jpars/test/model/multitenant">
<fileset dir="${eclipselink.jpars.test}/classes/org/eclipse/persistence/jpars/test/model/multitenant" includes="*.class"/>
</copy>
@@ -322,6 +326,7 @@
<jvmarg value="-Ddb.user=${db.user}"/>
<jvmarg value="-Ddb.pwd=${db.pwd}"/>
<jvmarg value="-javaagent:../${jparstest.2.base.dir}/${eclipselink.jar}"/>
+ <!--jvmarg value="-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=8787"/-->
<sysproperty key="loggingLevelFinest" value="false"/>
<sysproperty key="tempFileDir" value="${tmp.dir}"/>
<sysproperty key="ignoreCRLF" value="true"/>
diff --git a/jpa/eclipselink.jpars.test/src/META-INF/persistence.xml b/jpa/eclipselink.jpars.test/src/META-INF/persistence.xml
index c5ac349..9c59bb4 100644
--- a/jpa/eclipselink.jpars.test/src/META-INF/persistence.xml
+++ b/jpa/eclipselink.jpars.test/src/META-INF/persistence.xml
@@ -87,6 +87,18 @@
</properties>
</persistence-unit>
+ <persistence-unit name="jpars_basket-static" transaction-type="RESOURCE_LOCAL">
+ <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
+ <class>org.eclipse.persistence.jpars.test.model.basket.Basket</class>
+ <class>org.eclipse.persistence.jpars.test.model.basket.BasketItem</class>
+ <exclude-unlisted-classes/>
+ <properties>
+ <property name="javax.persistence.nonJtaDataSource" value="jdbc/ELNonJTADS"/>
+ <property name="eclipselink.logging.level" value="SEVERE"/>
+ <property name="eclipselink.logging.parameters" value="true"/>
+ </properties>
+ </persistence-unit>
+
<persistence-unit name="jpars_traveler-static" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>org.eclipse.persistence.jpars.test.model.traveler.Traveler</class>
diff --git a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/AllJavaEETests.java b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/AllJavaEETests.java
index 4c382e3..8aed030 100644
--- a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/AllJavaEETests.java
+++ b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/AllJavaEETests.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -8,19 +8,21 @@
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
- * gonural - initial
+ * gonural - initial
+ * Dmitry Kornilov - paging tests added
******************************************************************************/
package org.eclipse.persistence.jpars.test;
import org.eclipse.persistence.jpars.test.server.ServerCrudTest;
import org.eclipse.persistence.jpars.test.server.ServerEmployeeTest;
import org.eclipse.persistence.jpars.test.server.ServerEmployeeTestV2;
+import org.eclipse.persistence.jpars.test.server.ServerPageableTest;
import org.eclipse.persistence.jpars.test.server.ServerTravelerTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(VersionedTestSuite.class)
-@SuiteClasses({ ServerEmployeeTestV2.class, ServerCrudTest.class, ServerEmployeeTest.class, ServerTravelerTest.class })
+@SuiteClasses({ ServerEmployeeTestV2.class, ServerCrudTest.class, ServerEmployeeTest.class, ServerTravelerTest.class, ServerPageableTest.class })
public class AllJavaEETests {
}
diff --git a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/basket/Basket.java b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/basket/Basket.java
new file mode 100644
index 0000000..d09ab7a
--- /dev/null
+++ b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/basket/Basket.java
@@ -0,0 +1,79 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Dmitry Kornilov - initial
+ ******************************************************************************/
+package org.eclipse.persistence.jpars.test.model.basket;
+
+import org.eclipse.persistence.jpa.rs.annotations.RestPageable;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.NamedQueries;
+import javax.persistence.NamedQuery;
+import javax.persistence.OneToMany;
+import javax.persistence.Table;
+import java.util.ArrayList;
+import java.util.List;
+
+@Entity
+@Table(name = "JPARS_BASKET")
+@NamedQueries({
+ @NamedQuery(
+ name = "Basket.deleteAll",
+ query = "DELETE FROM Basket b")
+})
+public class Basket {
+
+ @Id
+ @Column(name = "BASKET_ID")
+ private Integer id;
+
+ @Column(name = "BASKET_NAME")
+ private String name;
+
+ @OneToMany(mappedBy = "basket", cascade = CascadeType.ALL)
+ @RestPageable(limit = 2)
+ private List<BasketItem> basketItems = new ArrayList<BasketItem>();
+
+ public Basket() {
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public List<BasketItem> getBasketItems() {
+ return basketItems;
+ }
+
+ public void setBasketItems(List<BasketItem> basketItems) {
+ this.basketItems = basketItems;
+ }
+
+ @Override
+ public String toString() {
+ return "id=" + id + ", name=" + name;
+ }
+}
diff --git a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/basket/BasketItem.java b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/basket/BasketItem.java
new file mode 100644
index 0000000..c30dc32
--- /dev/null
+++ b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/basket/BasketItem.java
@@ -0,0 +1,90 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Dmitry Kornilov - initial
+ ******************************************************************************/
+package org.eclipse.persistence.jpars.test.model.basket;
+
+import org.eclipse.persistence.jpa.rs.annotations.RestPageableQueries;
+import org.eclipse.persistence.jpa.rs.annotations.RestPageableQuery;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.NamedQueries;
+import javax.persistence.NamedQuery;
+import javax.persistence.Table;
+
+@Entity
+@Table(name = "JPARS_BASKET_ITEM")
+@NamedQueries({
+ @NamedQuery(
+ name = "BasketItem.findAll",
+ query = "SELECT bi FROM BasketItem bi ORDER BY bi.id"),
+ @NamedQuery(
+ name = "BasketItem.findAllPageable",
+ query = "SELECT bi FROM BasketItem bi ORDER BY bi.id"),
+ @NamedQuery(
+ name = "BasketItem.deleteAll",
+ query = "DELETE FROM BasketItem bi")
+})
+@RestPageableQueries({
+ @RestPageableQuery(queryName = "BasketItem.findAllPageable", limit = 20)
+})
+public class BasketItem {
+
+ @Id
+ @Column(name = "ITEM_ID")
+ private Integer id;
+
+ @ManyToOne
+ @JoinColumn(name = "BASKET_ID")
+ private Basket basket;
+
+ @Column(name = "ITEM_NAME")
+ private String name;
+
+ @Column(name = "ITEM_QTY")
+ private Integer qty;
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Basket getBasket() {
+ return basket;
+ }
+
+ public void setBasket(Basket basket) {
+ this.basket = basket;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Integer getQty() {
+ return qty;
+ }
+
+ public void setQty(Integer qty) {
+ this.qty = qty;
+ }
+}
diff --git a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/employee/Employee.java b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/employee/Employee.java
index d17de06..639ad33 100644
--- a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/employee/Employee.java
+++ b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/employee/Employee.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2011, 2013 Oracle. All rights reserved.
+ * Copyright (c) 2011, 2014 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -10,14 +10,13 @@
******************************************************************************/
package org.eclipse.persistence.jpars.test.model.employee;
-import static javax.persistence.CascadeType.ALL;
-import static javax.persistence.CascadeType.PERSIST;
-import static javax.persistence.FetchType.LAZY;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
+import org.eclipse.persistence.annotations.ConversionValue;
+import org.eclipse.persistence.annotations.Convert;
+import org.eclipse.persistence.annotations.ObjectTypeConverter;
+import org.eclipse.persistence.annotations.PrivateOwned;
+import org.eclipse.persistence.jpa.rs.annotations.RestPageable;
+import org.eclipse.persistence.jpa.rs.annotations.RestPageableQueries;
+import org.eclipse.persistence.jpa.rs.annotations.RestPageableQuery;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
@@ -41,11 +40,14 @@ import javax.persistence.OneToOne;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;
import javax.persistence.Version;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
-import org.eclipse.persistence.annotations.ConversionValue;
-import org.eclipse.persistence.annotations.Convert;
-import org.eclipse.persistence.annotations.ObjectTypeConverter;
-import org.eclipse.persistence.annotations.PrivateOwned;
+import static javax.persistence.CascadeType.ALL;
+import static javax.persistence.CascadeType.PERSIST;
+import static javax.persistence.FetchType.LAZY;
@NamedQueries({
@NamedQuery(
@@ -67,6 +69,9 @@ import org.eclipse.persistence.annotations.PrivateOwned;
name = "Employee.findAll",
query = "SELECT e FROM Employee e ORDER BY e.id"),
@NamedQuery(
+ name = "Employee.findAllPageable",
+ query = "SELECT e FROM Employee e ORDER BY e.id"),
+ @NamedQuery(
name = "Employee.deleteAll",
query = "DELETE FROM Employee e")
})
@@ -76,6 +81,9 @@ import org.eclipse.persistence.annotations.PrivateOwned;
@ObjectTypeConverter(name = "gender", objectType = Gender.class, dataType = String.class, conversionValues = {
@ConversionValue(dataValue = "M", objectValue = "Male"),
@ConversionValue(dataValue = "F", objectValue = "Female") })
+@RestPageableQueries({
+ @RestPageableQuery(queryName = "Employee.findAllPageable", limit = 20)
+})
public class Employee {
@Id
@@ -136,6 +144,7 @@ public class Employee {
private List<String> responsibilities = new ArrayList<String>();
@OneToMany(mappedBy = "employee", cascade = CascadeType.ALL)
+ @RestPageable(limit = 2)
private Set<Expertise> expertiseAreas = new HashSet<Expertise>();
@ManyToOne(cascade = PERSIST, fetch = LAZY)
diff --git a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/weaving/PersistenceWeaverBean.java b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/weaving/PersistenceWeaverBean.java
index 2c03678..7b6fc2a 100644
--- a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/weaving/PersistenceWeaverBean.java
+++ b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/model/weaving/PersistenceWeaverBean.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2011, 2013 Oracle. All rights reserved.
+ * Copyright (c) 2011, 2014 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -37,4 +37,9 @@ public class PersistenceWeaverBean {
@SuppressWarnings("unused")
@PersistenceUnit(unitName = "jpars_traveler-static")
private EntityManagerFactory emf3;
+
+ @SuppressWarnings("unused")
+ @PersistenceUnit(unitName = "jpars_basket-static")
+ private EntityManagerFactory emf4;
+
}
diff --git a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/server/ServerPageableTest.java b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/server/ServerPageableTest.java
new file mode 100644
index 0000000..3e84287
--- /dev/null
+++ b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/server/ServerPageableTest.java
@@ -0,0 +1,391 @@
+/*******************************************************************************
+ * Copyright (c) 2014 Oracle. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Dmitry Kornilov - initial implementation
+ ******************************************************************************/
+package org.eclipse.persistence.jpars.test.server;
+
+import org.eclipse.persistence.config.PersistenceUnitProperties;
+import org.eclipse.persistence.dynamic.DynamicClassLoader;
+import org.eclipse.persistence.jpa.rs.PersistenceContext;
+import org.eclipse.persistence.jpa.rs.PersistenceFactoryBase;
+import org.eclipse.persistence.jpars.test.model.basket.Basket;
+import org.eclipse.persistence.jpars.test.model.basket.BasketItem;
+import org.eclipse.persistence.jpars.test.util.ExamplePropertiesLoader;
+import org.eclipse.persistence.jpars.test.util.RestUtils;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import javax.persistence.Persistence;
+import javax.ws.rs.core.MediaType;
+import java.net.URISyntaxException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.Logger;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * This class tests paging feature introduced in V2.
+ *
+ * @author Dmitry Kornilov
+ */
+public class ServerPageableTest {
+ private static final Logger logger = Logger.getLogger("org.eclipse.persistence.jpars.test.server");
+
+ private static final String JPA_RS_VERSION_STRING = "jpars.version.string";
+ private static final String DEFAULT_PU = "jpars_basket-static";
+
+ private static PersistenceContext context = null;
+ private static PersistenceFactoryBase factory = null;
+
+ @BeforeClass
+ public static void setup() throws Exception {
+ final Map<String, Object> properties = new HashMap<String, Object>();
+ ExamplePropertiesLoader.loadProperties(properties);
+ properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, null);
+ properties.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.DROP_AND_CREATE);
+ properties.put(PersistenceUnitProperties.CLASSLOADER, new DynamicClassLoader(Thread.currentThread().getContextClassLoader()));
+ System.setProperty(JPA_RS_VERSION_STRING, "v2.0");
+ factory = new PersistenceFactoryBase();
+ context = factory.bootstrapPersistenceContext(DEFAULT_PU, Persistence.createEntityManagerFactory(DEFAULT_PU, properties), RestUtils.getServerURI(), null, true);
+ initData();
+ }
+
+ @AfterClass
+ public static void cleanup() throws Exception {
+ try {
+ RestUtils.restUpdateQuery(context, "BasketItem.deleteAll", "BasketItem", null, null, MediaType.APPLICATION_JSON_TYPE);
+ RestUtils.restUpdateQuery(context, "Basket.deleteAll", "Basket", null, null, MediaType.APPLICATION_JSON_TYPE);
+ } catch (URISyntaxException e) {
+ }
+ }
+
+ private static void initData() throws Exception {
+ // Create a basket
+ Basket basket = new Basket();
+ basket.setId(1);
+ basket.setName("Basket1");
+ basket = RestUtils.restCreate(context, basket, Basket.class.getSimpleName(), Basket.class, null, MediaType.APPLICATION_XML_TYPE, true);
+ assertNotNull("Basket create failed.", basket);
+
+ // Add items
+ for (int j=1; j<=5; j++) {
+ BasketItem basketItem = new BasketItem();
+ basketItem.setId(j);
+ basketItem.setName("BasketItem" + j);
+ RestUtils.restUpdate(context, basketItem, BasketItem.class.getSimpleName(), BasketItem.class, null, MediaType.APPLICATION_XML_TYPE, false);
+ RestUtils.restUpdateBidirectionalRelationship(context, String.valueOf(basket.getId()), Basket.class.getSimpleName(), "basketItems", basketItem, MediaType.APPLICATION_XML_TYPE, "basket", true);
+ }
+ }
+
+ @Test
+ public void testPageableQueryLimitJson() throws URISyntaxException {
+ // Run pageable query with limit = 2
+ final Map<String, String> hints = new HashMap<String, String>(1);
+ hints.put("limit", "2");
+
+ final String queryResult = RestUtils.restNamedMultiResultQuery(context, "BasketItem.findAllPageable", null, hints, MediaType.APPLICATION_JSON_TYPE);
+ logger.info(queryResult);
+ assertNotNull("Query all basket items failed.", queryResult);
+
+ // First 2 items must be in the response
+ assertTrue(basketItemExists(queryResult, 1));
+ assertTrue(basketItemExists(queryResult, 2));
+
+ // Last 3 must not be in the response
+ assertFalse(basketItemExists(queryResult, 3));
+ assertFalse(basketItemExists(queryResult, 4));
+ assertFalse(basketItemExists(queryResult, 5));
+
+ // Check next link
+ final String nextLink = "{\"href\":\"" + RestUtils.getServerURI() + context.getName() + "/query/BasketItem.findAllPageable?offset=2&limit=2\",\"rel\":\"next\"}";
+ assertTrue(queryResult.contains(nextLink));
+
+ // Check previous link
+ assertFalse(queryResult.contains("\"rel\": \"prev\""));
+
+ // Check self link
+ final String selfLink = "{\"href\":\"" + RestUtils.getServerURI() + context.getName() + "/query/BasketItem.findAllPageable?limit=2\",\"rel\":\"self\"}";
+ assertTrue(queryResult.contains(selfLink));
+
+ // Check items (limit = 2, offset = 0, count = 2, hasMore = true)
+ checkItemsJson(queryResult, 2, 0, 2, true);
+ }
+
+ @Test
+ public void testPageableQueryLimitXml() throws URISyntaxException {
+ // Run pageable query with limit = 2
+ final Map<String, String> hints = new HashMap<String, String>(1);
+ hints.put("limit", "2");
+
+ final String queryResult = RestUtils.restNamedMultiResultQuery(context, "BasketItem.findAllPageable", null, hints, MediaType.APPLICATION_XML_TYPE);
+ logger.info(queryResult);
+ assertNotNull("Query all basket items failed.", queryResult);
+
+ // First 2 items must be in the response
+ assertTrue(basketItemExists(queryResult, 1));
+ assertTrue(basketItemExists(queryResult, 2));
+
+ // Last 3 must not be in the response
+ assertFalse(basketItemExists(queryResult, 3));
+ assertFalse(basketItemExists(queryResult, 4));
+ assertFalse(basketItemExists(queryResult, 5));
+
+ // Check next link
+ final String nextLink = "<link><href>" + RestUtils.getServerURI() + context.getName() + "/query/BasketItem.findAllPageable?offset=2&amp;limit=2" + "</href><rel>next</rel></link>";
+ assertTrue(queryResult.contains(nextLink));
+
+ // Check previous link
+ assertFalse(queryResult.contains("<rel>prev</rel>"));
+
+ // Check self link
+ final String selfLink = "<link><href>" + RestUtils.getServerURI() + context.getName() + "/query/BasketItem.findAllPageable?limit=2" + "</href><rel>self</rel></link>";
+ assertTrue(queryResult.contains(selfLink));
+
+ // Check items (limit = 2, offset = 0, count = 2, hasMore = true)
+ checkItemsXml(queryResult, 2, 0, 2, true);
+ }
+
+ @Test
+ public void testPageableQueryOffsetJson() throws URISyntaxException {
+ // Run pageable query with limit = 2 and offset = 2
+ final Map<String, String> hints = new HashMap<String, String>(1);
+ hints.put("limit", "2");
+ hints.put("offset", "2");
+
+ final String queryResult = RestUtils.restNamedMultiResultQuery(context, "BasketItem.findAllPageable", null, hints, MediaType.APPLICATION_JSON_TYPE);
+ logger.info(queryResult);
+ assertNotNull("Query all basket items failed.", queryResult);
+
+ // First 2 items must not be in the response
+ assertFalse(basketItemExists(queryResult, 1));
+ assertFalse(basketItemExists(queryResult, 2));
+
+ // The following 2 must be there
+ assertTrue(basketItemExists(queryResult, 3));
+ assertTrue(basketItemExists(queryResult, 4));
+
+ // And the last one not
+ assertFalse(basketItemExists(queryResult, 5));
+
+ // Check next link
+ final String nextLink = "{\"href\":\"" + RestUtils.getServerURI() + context.getName() + "/query/BasketItem.findAllPageable?offset=4&limit=2\",\"rel\":\"next\"}";
+ assertTrue(queryResult.contains(nextLink));
+
+ // Check previous link
+ final String prevLink = "{\"href\":\"" + RestUtils.getServerURI() + context.getName() + "/query/BasketItem.findAllPageable?offset=0&limit=2\",\"rel\":\"prev\"}";
+ assertTrue(queryResult.contains(prevLink));
+
+ // Check self link
+ final String selfLink = "{\"href\":\"" + RestUtils.getServerURI() + context.getName() + "/query/BasketItem.findAllPageable?limit=2&offset=2\",\"rel\":\"self\"}";
+ assertTrue(queryResult.contains(selfLink));
+
+ // Check items (limit = 2, offset = 2, count = 2, hasMore = true)
+ checkItemsJson(queryResult, 2, 2, 2, true);
+ }
+
+ @Test
+ public void testPageableQueryOffsetXml() throws URISyntaxException {
+ // Run pageable query with limit = 2 and offset = 2
+ final Map<String, String> hints = new HashMap<String, String>(1);
+ hints.put("limit", "2");
+ hints.put("offset", "2");
+
+ final String queryResult = RestUtils.restNamedMultiResultQuery(context, "BasketItem.findAllPageable", null, hints, MediaType.APPLICATION_XML_TYPE);
+ logger.info(queryResult);
+ assertNotNull("Query all basket items failed.", queryResult);
+
+ // First 2 items must not be in the response
+ assertFalse(basketItemExists(queryResult, 1));
+ assertFalse(basketItemExists(queryResult, 2));
+
+ // The following 2 must be there
+ assertTrue(basketItemExists(queryResult, 3));
+ assertTrue(basketItemExists(queryResult, 4));
+
+ // And the last one not
+ assertFalse(basketItemExists(queryResult, 5));
+
+ // Check next link
+ final String nextLink = "<link><href>" + RestUtils.getServerURI() + context.getName() + "/query/BasketItem.findAllPageable?offset=4&amp;limit=2</href><rel>next</rel></link>";
+ assertTrue(queryResult.contains(nextLink));
+
+ // Check previous link
+ final String prevLink = "<link><href>" + RestUtils.getServerURI() + context.getName() + "/query/BasketItem.findAllPageable?offset=0&amp;limit=2</href><rel>prev</rel></link>";
+ assertTrue(queryResult.contains(prevLink));
+
+ // Check self link
+ final String selfLink = "<link><href>" + RestUtils.getServerURI() + context.getName() + "/query/BasketItem.findAllPageable?limit=2&amp;offset=2</href><rel>self</rel></link>";
+ assertTrue(queryResult.contains(selfLink));
+
+ // Check items (limit = 2, offset = 2, count = 2, hasMore = true)
+ checkItemsXml(queryResult, 2, 2, 2, true);
+ }
+
+ @Test
+ public void testNoLimitJson() throws URISyntaxException {
+ final String queryResult = RestUtils.restNamedMultiResultQuery(context, "BasketItem.findAllPageable", null, null, MediaType.APPLICATION_JSON_TYPE);
+ logger.info(queryResult);
+ assertNotNull("Query all basket items failed.", queryResult);
+
+ // All items must be in the response
+ assertTrue(basketItemExists(queryResult, 1));
+ assertTrue(basketItemExists(queryResult, 2));
+ assertTrue(basketItemExists(queryResult, 3));
+ assertTrue(basketItemExists(queryResult, 4));
+ assertTrue(basketItemExists(queryResult, 5));
+
+ // Check next link
+ assertFalse(queryResult.contains("\"rel\": \"next\""));
+
+ // Check previous link
+ assertFalse(queryResult.contains("\"rel\": \"prev\""));
+
+ // Check self link
+ final String selfLink = "{\"href\":\"" + RestUtils.getServerURI() + context.getName() + "/query/BasketItem.findAllPageable\",\"rel\":\"self\"}";
+ assertTrue(queryResult.contains(selfLink));
+
+ // Check items (limit = 20, offset = 0, count = 5, hasMore = false)
+ checkItemsJson(queryResult, 20, 0, 5, false);
+ }
+
+ @Test
+ public void testNoLimitXml() throws URISyntaxException {
+ final String queryResult = RestUtils.restNamedMultiResultQuery(context, "BasketItem.findAllPageable", null, null, MediaType.APPLICATION_XML_TYPE);
+ logger.info(queryResult);
+ assertNotNull("Query all basket items failed.", queryResult);
+
+ // All items must be in the response
+ assertTrue(basketItemExists(queryResult, 1));
+ assertTrue(basketItemExists(queryResult, 2));
+ assertTrue(basketItemExists(queryResult, 3));
+ assertTrue(basketItemExists(queryResult, 4));
+ assertTrue(basketItemExists(queryResult, 5));
+
+ // Check next link
+ assertFalse(queryResult.contains("<rel>next</rel>"));
+
+ // Check previous link
+ assertFalse(queryResult.contains("<rel>prev</rel>"));
+
+ // Check self link
+ final String selfLink = "<link><href>" + RestUtils.getServerURI() + context.getName() + "/query/BasketItem.findAllPageable</href><rel>self</rel></link>";
+ assertTrue(queryResult.contains(selfLink));
+
+ // Check items (limit = 20, offset = 0, count = 5, hasMore = false)
+ checkItemsXml(queryResult, 20, 0, 5, false);
+ }
+
+ @Test
+ public void testCountXml() throws URISyntaxException {
+ // Run pageable query with limit = 2 and offset = 2
+ final Map<String, String> hints = new HashMap<String, String>(1);
+ hints.put("limit", "2");
+ hints.put("offset", "4");
+
+ final String queryResult = RestUtils.restNamedMultiResultQuery(context, "BasketItem.findAllPageable", null, hints, MediaType.APPLICATION_XML_TYPE);
+ logger.info(queryResult);
+ assertNotNull("Query all basket items failed.", queryResult);
+
+ // First 4 items shouldn't be in the response
+ assertFalse(basketItemExists(queryResult, 1));
+ assertFalse(basketItemExists(queryResult, 2));
+ assertFalse(basketItemExists(queryResult, 3));
+ assertFalse(basketItemExists(queryResult, 4));
+
+ // The last one have to be there
+ assertTrue(basketItemExists(queryResult, 5));
+
+ // Check next link
+ assertFalse(queryResult.contains("<rel>next</rel>"));
+
+ // Check previous link
+ final String prevLink = "<link><href>" + RestUtils.getServerURI() + context.getName() + "/query/BasketItem.findAllPageable?offset=2&amp;limit=2</href><rel>prev</rel></link>";
+ assertTrue(queryResult.contains(prevLink));
+
+ // Check self link
+ final String selfLink = "<link><href>" + RestUtils.getServerURI() + context.getName() + "/query/BasketItem.findAllPageable?limit=2&amp;offset=4</href><rel>self</rel></link>";
+ assertTrue(queryResult.contains(selfLink));
+
+ // Check items (limit = 1, offset = 4, count = 1, hasMore = false)
+ checkItemsXml(queryResult, 2, 4, 1, false);
+ }
+
+ @Test(expected = Exception.class)
+ public void testIncorrectLimitUsage() throws URISyntaxException {
+ // Run pageable query with limit = 2
+ final Map<String, String> hints = new HashMap<String, String>(1);
+ hints.put("limit", "2");
+
+ // Call not pageable query with limit parameter. It suppose to throw an exception.
+ RestUtils.restNamedMultiResultQuery(context, "BasketItem.findAll", null, hints, MediaType.APPLICATION_XML_TYPE);
+ }
+
+ @Test(expected = Exception.class)
+ public void testIncorrectOffsetUsage() throws URISyntaxException {
+ // Run pageable query with offset = 2
+ final Map<String, String> hints = new HashMap<String, String>(1);
+ hints.put("offset", "2");
+
+ // Call not pageable query with limit parameter. It suppose to throw an exception.
+ RestUtils.restNamedMultiResultQuery(context, "BasketItem.findAll", null, hints, MediaType.APPLICATION_XML_TYPE);
+ }
+
+ @Test
+ public void testPageableField() throws URISyntaxException {
+ // Run pageable query with limit = 2
+ final Map<String, String> hints = new HashMap<String, String>(1);
+ hints.put("limit", "2");
+
+ final String queryResult = RestUtils.restFindAttribute(context, 1, Basket.class.getSimpleName(), "basketItems", null, hints, MediaType.APPLICATION_XML_TYPE);
+ logger.info(queryResult);
+
+ // First 2 items must be in the response
+ assertTrue(queryResult.contains("Item1"));
+ assertTrue(queryResult.contains("Item2"));
+
+ // Last 3 must not be in the response
+ assertFalse(queryResult.contains("Item3"));
+ assertFalse(queryResult.contains("Item4"));
+ assertFalse(queryResult.contains("Item5"));
+
+ // Check next link
+ final String nextLink = "<link><href>" + RestUtils.getServerURI() + context.getName() + "/entity/Basket/1/basketItems?offset=2&amp;limit=2</href><rel>next</rel></link>";
+ assertTrue(queryResult.contains(nextLink));
+
+ // Check previous link
+ assertFalse(queryResult.contains("<rel>prev</rel>"));
+
+ // Check items (limit = 2, offset = 0, count = 2, hasMore = true)
+ checkItemsXml(queryResult, 2, 0, 2, true);
+ }
+
+ private boolean basketItemExists(String response, int id) {
+ return response.contains("BasketItem" + id);
+ }
+
+ private void checkItemsXml(String response, int limit, int offset, int count, boolean hasMore) {
+ assertTrue(response.contains("<limit>" + limit + "</limit>"));
+ assertTrue(response.contains("<offset>" + offset + "</offset>"));
+ assertTrue(response.contains("<count>" + count + "</count>"));
+ assertTrue(response.contains("<hasMore>" + hasMore + "</hasMore>"));
+ }
+
+ private void checkItemsJson(String response, int limit, int offset, int count, boolean hasMore) {
+ assertTrue(response.contains("\"limit\":" + limit));
+ assertTrue(response.contains("\"offset\":" + offset));
+ assertTrue(response.contains("\"count\":" + count));
+ assertTrue(response.contains("\"hasMore\":" + hasMore));
+ }
+}
diff --git a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/util/RestUtils.java b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/util/RestUtils.java
index d9caeb7..0c297aa 100644
--- a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/util/RestUtils.java
+++ b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/util/RestUtils.java
@@ -1,5 +1,5 @@
/*******************************************************************************
- * Copyright (c) 2011, 2013 Oracle. All rights reserved.
+ * Copyright (c) 2011, 2014 Oracle. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
@@ -12,8 +12,19 @@
******************************************************************************/
package org.eclipse.persistence.jpars.test.util;
-import static org.junit.Assert.fail;
+import com.sun.jersey.api.client.Client;
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.api.client.ClientResponse.Status;
+import com.sun.jersey.api.client.WebResource;
+import org.eclipse.persistence.jpa.rs.MatrixParameters;
+import org.eclipse.persistence.jpa.rs.PersistenceContext;
+import org.eclipse.persistence.jpa.rs.QueryParameters;
+import org.eclipse.persistence.jpa.rs.exceptions.ErrorResponse;
+import org.eclipse.persistence.jpars.test.server.RestCallFailedException;
+import javax.imageio.ImageIO;
+import javax.ws.rs.core.MediaType;
+import javax.xml.bind.JAXBException;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
@@ -26,23 +37,13 @@ import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
+import java.util.logging.Logger;
-import javax.imageio.ImageIO;
-import javax.ws.rs.core.MediaType;
-import javax.xml.bind.JAXBException;
-
-import org.eclipse.persistence.jpa.rs.MatrixParameters;
-import org.eclipse.persistence.jpa.rs.PersistenceContext;
-import org.eclipse.persistence.jpa.rs.QueryParameters;
-import org.eclipse.persistence.jpa.rs.exceptions.ErrorResponse;
-import org.eclipse.persistence.jpars.test.server.RestCallFailedException;
-
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.ClientResponse.Status;
-import com.sun.jersey.api.client.WebResource;
+import static org.junit.Assert.fail;
public class RestUtils {
+ private static final Logger logger = Logger.getLogger("org.eclipse.persistence.jpars.test.server");
+
private static final String APPLICATION_LOCATION = "/eclipselink.jpars.test/persistence/";
private static final String SERVER_URI_BASE = "server.uri.base";
private static final String JPA_RS_VERSION_STRING = "jpars.version.string";
@@ -295,6 +296,10 @@ public class RestUtils {
}
}
uri.append("/entity/" + type);
+
+ logger.info(os.toString());
+ logger.info(uri.toString());
+
WebResource webResource = client.resource(uri.toString());
ClientResponse response = null;
if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
@@ -739,7 +744,7 @@ public class RestUtils {
}
/**
- * Rest paged find attribute.
+ * Rest find attribute query.
*
* @param context the context
* @param id the id
@@ -752,7 +757,7 @@ public class RestUtils {
* @throws RestCallFailedException the rest call failed exception
* @throws URISyntaxException the URI syntax exception
*/
- public static String restPagedFindAttribute(PersistenceContext context, Object id, String type, String attribute, Map<String, Object> parameters, Map<String, String> hints, MediaType outputMediaType) throws RestCallFailedException, URISyntaxException {
+ public static String restFindAttribute(PersistenceContext context, Object id, String type, String attribute, Map<String, Object> parameters, Map<String, String> hints, MediaType outputMediaType) throws RestCallFailedException, URISyntaxException {
StringBuilder resourceURL = new StringBuilder();
resourceURL.append(RestUtils.getServerURI() + context.getName() + "/entity/" + type + "/" + id + "/" + attribute);
appendParametersAndHints(resourceURL, parameters, hints);