summaryrefslogtreecommitdiffstatsabout
diff options
context:
space:
mode:
authorGul Onural2012-10-25 16:08:52 (EDT)
committer tware2012-10-26 11:37:13 (EDT)
commite50208bb8a9c2252d1287cc1d208298dd9e655c4 (patch)
tree7563c302476abfd39d92564c5eb01897dfcb949b
parent0611ddd6692d7dae38a9fe72a52ca657603e036b (diff)
downloadeclipselink.runtime-e50208bb8a9c2252d1287cc1d208298dd9e655c4.zip
eclipselink.runtime-e50208bb8a9c2252d1287cc1d208298dd9e655c4.tar.gz
eclipselink.runtime-e50208bb8a9c2252d1287cc1d208298dd9e655c4.tar.bz2
JPA-RS refactoring in service resources and bug fixes
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/AbstractResource.java528
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/EntityResource.java80
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceContext.java39
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceResource.java141
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceUnitResource.java117
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/ServiceBase.java773
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/ClassNotFoundExceptionMapper.java6
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/ConversionExceptionMapper.java22
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/EntityNotFoundExceptionMapper.java25
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/logging/i18n/LoggingLocalizationResource.java11
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/PreLoginMappingAdapter.java3
-rw-r--r--dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/ReferenceAdapter.java9
-rw-r--r--jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/AllJavaSETests.java4
-rw-r--r--jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/server/ServerCrudTest.java193
-rw-r--r--jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/service/MarshalUnmarshalTest.java (renamed from jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/server/UnmarshalTest.java)19
-rw-r--r--jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/service/TestService.java370
-rw-r--r--jpa/org.eclipse.persistence.jpars/src/org/eclipse/persistence/jpa/rs/service/JPARSApplication.java20
-rw-r--r--jpa/org.eclipse.persistence.jpars/src/org/eclipse/persistence/jpa/rs/service/Service.java37
-rw-r--r--jpa/org.eclipse.persistence.jpars/src/org/eclipse/persistence/jpa/rs/service/ServicePathDefinition.java28
19 files changed, 1279 insertions, 1146 deletions
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/AbstractResource.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/AbstractResource.java
new file mode 100644
index 0000000..99bb651
--- /dev/null
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/AbstractResource.java
@@ -0,0 +1,528 @@
+package org.eclipse.persistence.jpa.rs;
+
+import static org.eclipse.persistence.jpa.rs.util.StreamingOutputMarshaller.mediaType;
+
+import java.io.InputStream;
+import java.io.StringWriter;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.Map.Entry;
+
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.PathSegment;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import javax.ws.rs.core.Response.ResponseBuilder;
+import javax.ws.rs.core.Response.Status;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+
+import org.eclipse.persistence.descriptors.ClassDescriptor;
+import org.eclipse.persistence.internal.expressions.ConstantExpression;
+import org.eclipse.persistence.internal.expressions.MapEntryExpression;
+import org.eclipse.persistence.internal.helper.ClassConstants;
+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;
+import org.eclipse.persistence.internal.jpa.rs.metadata.model.LinkTemplate;
+import org.eclipse.persistence.internal.jpa.rs.metadata.model.PersistenceUnit;
+import org.eclipse.persistence.internal.jpa.rs.metadata.model.Query;
+import org.eclipse.persistence.internal.queries.MapContainerPolicy;
+import org.eclipse.persistence.internal.queries.ReportItem;
+import org.eclipse.persistence.jaxb.JAXBContext;
+import org.eclipse.persistence.jaxb.JAXBContextFactory;
+import org.eclipse.persistence.jaxb.MarshallerProperties;
+import org.eclipse.persistence.jpa.rs.PersistenceContext;
+import org.eclipse.persistence.jpa.rs.PersistenceFactoryBase;
+import org.eclipse.persistence.jpa.rs.util.IdHelper;
+import org.eclipse.persistence.jpa.rs.util.JPARSLogger;
+import org.eclipse.persistence.jpa.rs.util.StreamingOutputMarshaller;
+import org.eclipse.persistence.mappings.CollectionMapping;
+import org.eclipse.persistence.mappings.DatabaseMapping;
+import org.eclipse.persistence.mappings.ForeignReferenceMapping;
+import org.eclipse.persistence.mappings.foundation.AbstractDirectMapping;
+import org.eclipse.persistence.queries.DatabaseQuery;
+import org.eclipse.persistence.queries.ReportQuery;
+import org.eclipse.persistence.sessions.DatabaseRecord;
+
+/**
+ * @author gonural
+ *
+ */
+public class AbstractResource {
+ public static final String RELATIONSHIP_PARTNER = "partner";
+ protected PersistenceFactoryBase factory;
+
+ public void setPersistenceFactory(PersistenceFactoryBase factory) {
+ this.factory = factory;
+ }
+
+ public PersistenceFactoryBase getPersistenceFactory() {
+ if (factory == null) {
+ factory = new PersistenceFactoryBase();
+ }
+ return factory;
+ }
+
+ /**
+ * This method has been temporarily added to allow processing of either
+ * query or matrix parameters When the final protocol is worked out, it
+ * should be removed or altered.
+ *
+ * Here we check for query parameters and if they don't exist, we get the
+ * matrix parameters.
+ *
+ * @param info
+ * @return
+ */
+ protected static Map<String, String> getParameterMap(UriInfo info, String segment) {
+ Map<String, String> parameters = new HashMap<String, String>();
+ for (PathSegment pathSegment : info.getPathSegments()) {
+ if (pathSegment.getPath() != null && pathSegment.getPath().equals(segment)) {
+ for (Entry<String, List<String>> entry : pathSegment.getMatrixParameters().entrySet()) {
+ parameters.put(entry.getKey(), entry.getValue().get(0));
+ }
+ return parameters;
+ }
+ }
+ return parameters;
+ }
+
+ protected String marshallMetadata(Object metadata, String mediaType) throws JAXBException {
+ Class<?>[] jaxbClasses = new Class[] { Link.class, Attribute.class, Descriptor.class, LinkTemplate.class, PersistenceUnit.class, Query.class };
+ JAXBContext context = (JAXBContext) JAXBContextFactory.createContext(jaxbClasses, null);
+ Marshaller marshaller = context.createMarshaller();
+ marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, Boolean.FALSE);
+ marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, mediaType);
+ StringWriter writer = new StringWriter();
+ marshaller.marshal(metadata, writer);
+ return writer.toString();
+ }
+
+ protected Response findAttribute(String persistenceUnit, String type, String key, String attribute, HttpHeaders hh, UriInfo ui, URI baseURI) {
+ PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
+ if (app == null || app.getClass(type) == null) {
+ if (app == null) {
+ JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[] { persistenceUnit });
+ } else {
+ JPARSLogger.fine("jpars_could_not_find_class_in_persistence_unit", new Object[] { type, persistenceUnit });
+ }
+ return Response.status(Status.NOT_FOUND).build();
+ }
+ Map<String, String> discriminators = getParameterMap(ui, persistenceUnit);
+ Object id = IdHelper.buildId(app, type, key, discriminators);
+
+ Object entity = app.findAttribute(discriminators, type, id, getHintMap(ui), attribute);
+
+ if (entity == null) {
+ JPARSLogger.fine("jpars_could_not_entity_for_attribute", new Object[] { type, key, attribute, persistenceUnit });
+ return Response.status(Status.NOT_FOUND).build();
+ } else {
+ return Response.ok(new StreamingOutputMarshaller(app, entity, hh.getAcceptableMediaTypes())).build();
+ }
+ }
+
+ protected Response find(String persistenceUnit, String type, String key, HttpHeaders hh, UriInfo ui, URI baseURI) {
+ PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
+ if (app == null || app.getClass(type) == null) {
+ if (app == null) {
+ JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[] { persistenceUnit });
+ } else {
+ JPARSLogger.fine("jpars_could_not_find_class_in_persistence_unit", new Object[] { type, persistenceUnit });
+ }
+ return Response.status(Status.NOT_FOUND).build();
+ }
+ Map<String, String> discriminators = getParameterMap(ui, persistenceUnit);
+
+ Object id = IdHelper.buildId(app, type, key, discriminators);
+
+ Object entity = app.find(discriminators, type, id, getHintMap(ui));
+
+ if (entity == null) {
+ JPARSLogger.fine("jpars_could_not_entity_for_key", new Object[] { type, key, persistenceUnit });
+ return Response.status(Status.NOT_FOUND).build();
+ } else {
+ return Response.ok(new StreamingOutputMarshaller(app, entity, hh.getAcceptableMediaTypes())).build();
+ }
+ }
+
+ protected static Map<String, Object> getHintMap(UriInfo info) {
+ Map<String, Object> hints = new HashMap<String, Object>();
+ for (String key : info.getQueryParameters().keySet()) {
+ hints.put(key, info.getQueryParameters().getFirst(key));
+ }
+ return hints;
+ }
+
+ protected Response create(String persistenceUnit, String type, HttpHeaders hh, UriInfo uriInfo, URI baseURI, InputStream in) throws JAXBException {
+ PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
+ if (app == null) {
+ JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[] { persistenceUnit });
+ return Response.status(Status.NOT_FOUND).build();
+ }
+ ClassDescriptor descriptor = app.getDescriptor(type);
+ if (descriptor == null) {
+ JPARSLogger.fine("jpars_could_not_find_class_in_persistence_unit", new Object[] { type, persistenceUnit });
+ return Response.status(Status.NOT_FOUND).build();
+ }
+ Object entity = null;
+ try {
+ entity = app.unmarshalEntity(type, mediaType(hh.getAcceptableMediaTypes()), in);
+ } catch (JAXBException e) {
+ JPARSLogger.fine("exception_while_unmarhalling_entity", new Object[] { type, persistenceUnit, e.toString() });
+ return Response.status(Status.BAD_REQUEST).build();
+ }
+
+ // maintain idempotence on PUT by disallowing sequencing
+ AbstractDirectMapping sequenceMapping = descriptor.getObjectBuilder().getSequenceMapping();
+ if (sequenceMapping != null) {
+ Object value = sequenceMapping.getAttributeAccessor().getAttributeValueFromObject(entity);
+
+ if (descriptor.getObjectBuilder().isPrimaryKeyComponentInvalid(value, descriptor.getPrimaryKeyFields().indexOf(descriptor.getSequenceNumberField())) || descriptor.getSequence().shouldAlwaysOverrideExistingValue()) {
+ JPARSLogger.fine("jpars_put_not_idempotent", new Object[] { type, persistenceUnit });
+ return Response.status(Status.BAD_REQUEST).build();
+ }
+ }
+
+ app.create(getParameterMap(uriInfo, persistenceUnit), entity);
+ ResponseBuilder rb = Response.status(Status.CREATED);
+ rb.entity(new StreamingOutputMarshaller(app, entity, hh.getAcceptableMediaTypes()));
+ return rb.build();
+ }
+
+ protected Response delete(String persistenceUnit, String type, String key, HttpHeaders hh, UriInfo ui, URI baseURI) {
+ PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
+ if (app == null || app.getClass(type) == null) {
+ if (app == null) {
+ JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[] { persistenceUnit });
+ } else {
+ JPARSLogger.fine("jpars_could_not_find_class_in_persistence_unit", new Object[] { type, persistenceUnit });
+ }
+ return Response.status(Status.NOT_FOUND).build();
+ }
+ Map<String, String> discriminators = getParameterMap(ui, persistenceUnit);
+ Object id = IdHelper.buildId(app, type, key, discriminators);
+ app.delete(discriminators, type, id);
+ return Response.ok().build();
+ }
+
+ protected Response setOrAddAttribute(String persistenceUnit, String type, String key, String attribute, HttpHeaders hh, UriInfo ui, URI baseURI, InputStream in) {
+ PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
+ if (app == null || app.getClass(type) == null) {
+ if (app == null) {
+ JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[] { persistenceUnit });
+ } else {
+ JPARSLogger.fine("jpars_could_not_find_class_in_persistence_unit", new Object[] { type, persistenceUnit });
+ }
+ return Response.status(Status.NOT_FOUND).build();
+ }
+
+ Map<String, String> discriminators = getParameterMap(ui, persistenceUnit);
+ Object id = IdHelper.buildId(app, type, key, discriminators);
+
+ Object entity = null;
+ String partner = (String) getParameterMap(ui, attribute).get(RELATIONSHIP_PARTNER);
+ try {
+ ClassDescriptor descriptor = app.getDescriptor(type);
+ DatabaseMapping mapping = (DatabaseMapping) descriptor.getMappingForAttributeName(attribute);
+ if (!mapping.isForeignReferenceMapping()) {
+ JPARSLogger.fine("jpars_could_find_appropriate_mapping_for_update", new Object[] { attribute, type, key, persistenceUnit });
+ return Response.status(Status.NOT_FOUND).build();
+ }
+ entity = app.unmarshalEntity(((ForeignReferenceMapping) mapping).getReferenceDescriptor().getAlias(), mediaType(hh.getAcceptableMediaTypes()), in);
+ } catch (JAXBException e) {
+ JPARSLogger.fine("exception_while_unmarhalling_entity", new Object[] { type, persistenceUnit, e.toString() });
+ return Response.status(Status.BAD_REQUEST).build();
+ }
+
+ Object result = app.updateOrAddAttribute(getParameterMap(ui, persistenceUnit), type, id, getHintMap(ui), attribute, entity, partner);
+
+ if (result == null) {
+ JPARSLogger.fine("jpars_could_not_update_attribute", new Object[] { attribute, type, key, persistenceUnit });
+ return Response.status(Status.NOT_FOUND).build();
+ } else {
+ return Response.ok(new StreamingOutputMarshaller(app, result, hh.getAcceptableMediaTypes())).build();
+ }
+ }
+
+ protected Response removeAttribute(String persistenceUnit, String type, String key, String attribute, HttpHeaders hh, UriInfo ui, URI baseURI, InputStream in) {
+ PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
+ if (app == null || app.getClass(type) == null) {
+ if (app == null) {
+ JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[] { persistenceUnit });
+ } else {
+ JPARSLogger.fine("jpars_could_not_find_class_in_persistence_unit", new Object[] { type, persistenceUnit });
+ }
+ return Response.status(Status.NOT_FOUND).build();
+ }
+
+ Map<String, String> discriminators = getParameterMap(ui, persistenceUnit);
+ Object id = IdHelper.buildId(app, type, key, discriminators);
+
+ Object entity = null;
+ String partner = (String) getParameterMap(ui, attribute).get(RELATIONSHIP_PARTNER);
+ try {
+ ClassDescriptor descriptor = app.getDescriptor(type);
+ DatabaseMapping mapping = (DatabaseMapping) descriptor.getMappingForAttributeName(attribute);
+ if (!mapping.isForeignReferenceMapping()) {
+ JPARSLogger.fine("jpars_could_find_appropriate_mapping_for_update", new Object[] { attribute, type, key, persistenceUnit });
+ return Response.status(Status.NOT_FOUND).build();
+ }
+ entity = app.unmarshalEntity(((ForeignReferenceMapping) mapping).getReferenceDescriptor().getAlias(), mediaType(hh.getAcceptableMediaTypes()), in);
+ } catch (JAXBException e) {
+ JPARSLogger.fine("exception_while_unmarhalling_entity", new Object[] { type, persistenceUnit, e.toString() });
+ return Response.status(Status.BAD_REQUEST).build();
+ }
+
+ Object result = app.removeAttribute(getParameterMap(ui, persistenceUnit), type, id, getHintMap(ui), attribute, entity, partner);
+
+ if (result == null) {
+ JPARSLogger.fine("jpars_could_not_update_attribute", new Object[] { attribute, type, key, persistenceUnit });
+ return Response.status(Status.NOT_FOUND).build();
+ } else {
+ return Response.ok(new StreamingOutputMarshaller(app, result, hh.getAcceptableMediaTypes())).build();
+ }
+ }
+
+ protected Response update(String persistenceUnit, String type, HttpHeaders hh, UriInfo uriInfo, URI baseURI, InputStream in) {
+ PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
+ if (app == null || app.getClass(type) == null) {
+ if (app == null) {
+ JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[] { persistenceUnit });
+ } else {
+ JPARSLogger.fine("jpars_could_not_find_class_in_persistence_unit", new Object[] { type, persistenceUnit });
+ }
+ return Response.status(Status.NOT_FOUND).build();
+ }
+ MediaType contentType = mediaType(hh.getRequestHeader(HttpHeaders.CONTENT_TYPE));
+ Object entity = null;
+ try {
+ entity = app.unmarshalEntity(type, contentType, in);
+ } catch (JAXBException e) {
+ JPARSLogger.fine("exception_while_unmarhalling_entity", new Object[] { type, persistenceUnit, e.toString() });
+ return Response.status(Status.BAD_REQUEST).build();
+ }
+
+ entity = app.merge(getParameterMap(uriInfo, persistenceUnit), entity);
+ return Response.ok(new StreamingOutputMarshaller(app, entity, hh.getAcceptableMediaTypes())).build();
+ }
+
+ protected Response namedQueryUpdate(String persistenceUnit, String name, HttpHeaders hh, UriInfo ui, URI baseURI) {
+ PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
+ if (app == null) {
+ JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[] { persistenceUnit });
+ return Response.status(Status.NOT_FOUND).build();
+ }
+ Object result = app.query(getParameterMap(ui, persistenceUnit), name, getParameterMap(ui, name), getHintMap(ui), false, true);
+ return Response.ok(new StreamingOutputMarshaller(app, result.toString(), hh.getAcceptableMediaTypes())).build();
+ }
+
+ protected Response namedQuerySingleResult(String persistenceUnit, String name, HttpHeaders hh, UriInfo ui, URI baseURI) {
+ PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
+ if (app == null) {
+ JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[] { persistenceUnit });
+ return Response.status(Status.NOT_FOUND).build();
+ }
+ Object result = app.query(getParameterMap(ui, persistenceUnit), name, getParameterMap(ui, name), getHintMap(ui), true, false);
+ return Response.ok(new StreamingOutputMarshaller(app, result, hh.getAcceptableMediaTypes())).build();
+ }
+
+ protected Response getQueriesMetadata(String persistenceUnit, HttpHeaders hh, URI baseURI) {
+ PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
+ if (app == null) {
+ JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[] { persistenceUnit });
+ return Response.status(Status.NOT_FOUND).build();
+ } else {
+ List<Query> queries = new ArrayList<Query>();
+ addQueries(queries, app, null);
+ String mediaType = StreamingOutputMarshaller.mediaType(hh.getAcceptableMediaTypes()).toString();
+ String result = null;
+ try {
+ result = marshallMetadata(queries, mediaType);
+ } catch (JAXBException e) {
+ JPARSLogger.fine("exception_marshalling_query_metadata", new Object[] { persistenceUnit, e.toString() });
+ return Response.status(Status.INTERNAL_SERVER_ERROR).build();
+ }
+ return Response.ok(new StreamingOutputMarshaller(null, result, hh.getAcceptableMediaTypes())).build();
+ }
+ }
+
+ protected Response getQueryMetadata(String persistenceUnit, String queryName, HttpHeaders hh, URI baseURI) {
+ PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
+ if (app == null) {
+ JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[] { persistenceUnit });
+ return Response.status(Status.NOT_FOUND).build();
+ } else {
+ List<Query> returnQueries = new ArrayList<Query>();
+ Map<String, List<DatabaseQuery>> queries = app.getJpaSession().getQueries();
+ if (queries.get(queryName) != null) {
+ for (DatabaseQuery query : queries.get(queryName)) {
+ returnQueries.add(getQuery(query, app));
+ }
+ }
+ String mediaType = StreamingOutputMarshaller.mediaType(hh.getAcceptableMediaTypes()).toString();
+ String result = null;
+ try {
+ result = marshallMetadata(returnQueries, mediaType);
+ } catch (JAXBException e) {
+ JPARSLogger.fine("exception_marshalling_individual_query_metadata", new Object[] { queryName, persistenceUnit, e.toString() });
+ return Response.status(Status.INTERNAL_SERVER_ERROR).build();
+ }
+ return Response.ok(new StreamingOutputMarshaller(null, result, hh.getAcceptableMediaTypes())).build();
+ }
+ }
+
+ protected Response namedQuery(String persistenceUnit, String name, HttpHeaders hh, UriInfo ui, URI baseURI) {
+ PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
+ if (app == null) {
+ JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[] { persistenceUnit });
+ return Response.status(Status.NOT_FOUND).build();
+ }
+ Object result = app.query(getParameterMap(ui, persistenceUnit), name, getParameterMap(ui, name), getHintMap(ui), false, false);
+ return Response.ok(new StreamingOutputMarshaller(app, result, hh.getAcceptableMediaTypes())).build();
+ }
+
+ protected Query getQuery(DatabaseQuery query, PersistenceContext app) {
+ String method = query.isReadQuery() ? "get" : "post";
+ String jpql = query.getJPQLString() == null ? "" : query.getJPQLString();
+ StringBuffer parameterString = new StringBuffer();
+ Iterator<String> argumentsIterator = query.getArguments().iterator();
+ while (argumentsIterator.hasNext()) {
+ String argument = argumentsIterator.next();
+ parameterString.append(";");
+ parameterString.append(argument + "={" + argument + "}");
+ }
+ Query returnQuery = new Query(query.getName(), jpql, new LinkTemplate("execute", method, app.getBaseURI() + app.getName() + "/query/" + query.getName() + parameterString));
+ if (query.isReportQuery()) {
+ query.checkPrepare(app.getJpaSession(), new DatabaseRecord());
+ for (ReportItem item : ((ReportQuery) query).getItems()) {
+ if (item.getMapping() != null) {
+ if (item.getAttributeExpression() != null && item.getAttributeExpression().isMapEntryExpression()) {
+ if (((MapEntryExpression) item.getAttributeExpression()).shouldReturnMapEntry()) {
+ returnQuery.getReturnTypes().add(Map.Entry.class.getName());
+ } else {
+ returnQuery.getReturnTypes().add(((Class<?>) ((CollectionMapping) item.getMapping()).getContainerPolicy().getKeyType()).getName());
+ }
+ } else {
+ returnQuery.getReturnTypes().add(item.getMapping().getAttributeClassification().getName());
+ }
+ } else if (item.getResultType() != null) {
+ returnQuery.getReturnTypes().add(item.getResultType().getName());
+ } else if (item.getDescriptor() != null) {
+ returnQuery.getReturnTypes().add(item.getDescriptor().getJavaClass().getName());
+ } else if (item.getAttributeExpression() != null && item.getAttributeExpression().isConstantExpression()) {
+ returnQuery.getReturnTypes().add(((ConstantExpression) item.getAttributeExpression()).getValue().getClass().getName());
+ } else {
+ // Use Object.class by default.
+ returnQuery.getReturnTypes().add(ClassConstants.OBJECT.getName());
+ }
+ }
+ } else {
+ returnQuery.getReturnTypes().add(query.getReferenceClassName() == null ? "" : query.getReferenceClassName());
+ }
+ return returnQuery;
+ }
+
+ protected Response getDescriptorMetadata(String persistenceUnit, String descriptorAlias, HttpHeaders hh, URI baseURI) {
+ PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
+ if (app == null) {
+ JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[] { persistenceUnit });
+ return Response.status(Status.NOT_FOUND).build();
+ } else {
+ ClassDescriptor descriptor = app.getJpaSession().getDescriptorForAlias(descriptorAlias);
+ if (descriptor == null) {
+ JPARSLogger.fine("jpars_could_not_find_entity_type", new Object[] { descriptorAlias, persistenceUnit });
+ return Response.status(Status.NOT_FOUND).build();
+ } else {
+ String mediaType = StreamingOutputMarshaller.mediaType(hh.getAcceptableMediaTypes()).toString();
+ Descriptor returnDescriptor = buildDescriptor(app, persistenceUnit, descriptor, baseURI.toString());
+ String result = null;
+ try {
+ result = marshallMetadata(returnDescriptor, mediaType);
+ } catch (JAXBException e) {
+ JPARSLogger.fine("exception_marshalling_entity_metadata", new Object[] { descriptorAlias, persistenceUnit, e.toString() });
+ return Response.status(Status.INTERNAL_SERVER_ERROR).build();
+ }
+ return Response.ok(new StreamingOutputMarshaller(null, result, hh.getAcceptableMediaTypes())).build();
+ }
+ }
+ }
+
+ protected void addQueries(List<Query> queryList, PersistenceContext app, String javaClassName) {
+ Map<String, List<DatabaseQuery>> queries = app.getJpaSession().getQueries();
+ List<DatabaseQuery> returnQueries = new ArrayList<DatabaseQuery>();
+ for (String key : queries.keySet()) {
+ List<DatabaseQuery> keyQueries = queries.get(key);
+ Iterator<DatabaseQuery> queryIterator = keyQueries.iterator();
+ while (queryIterator.hasNext()) {
+ DatabaseQuery query = queryIterator.next();
+ if (javaClassName == null || (query.getReferenceClassName() != null && query.getReferenceClassName().equals(javaClassName))) {
+ returnQueries.add(query);
+ }
+ }
+ }
+ Iterator<DatabaseQuery> queryIterator = returnQueries.iterator();
+ while (queryIterator.hasNext()) {
+ queryList.add(getQuery(queryIterator.next(), app));
+ }
+ }
+
+ protected Descriptor buildDescriptor(PersistenceContext app, String persistenceUnit, ClassDescriptor descriptor, String baseUri) {
+ Descriptor returnDescriptor = new Descriptor();
+ returnDescriptor.setName(descriptor.getAlias());
+ returnDescriptor.setType(descriptor.getJavaClassName());
+ returnDescriptor.getLinkTemplates().add(new LinkTemplate("find", "get", baseUri + persistenceUnit + "/entity/" + descriptor.getAlias() + "/{primaryKey}"));
+ returnDescriptor.getLinkTemplates().add(new LinkTemplate("persist", "put", baseUri + persistenceUnit + "/entity/" + descriptor.getAlias()));
+ returnDescriptor.getLinkTemplates().add(new LinkTemplate("update", "post", baseUri + persistenceUnit + "/entity/" + descriptor.getAlias()));
+ returnDescriptor.getLinkTemplates().add(new LinkTemplate("delete", "delete", baseUri + persistenceUnit + "/entity/" + descriptor.getAlias() + "/{primaryKey}"));
+
+ if (!descriptor.getMappings().isEmpty()) {
+ Iterator<DatabaseMapping> mappingIterator = descriptor.getMappings().iterator();
+ while (mappingIterator.hasNext()) {
+ DatabaseMapping mapping = mappingIterator.next();
+ addMapping(returnDescriptor, mapping);
+ }
+ }
+ addQueries(returnDescriptor.getQueries(), app, descriptor.getJavaClassName());
+ return returnDescriptor;
+ }
+
+ protected void addMapping(Descriptor descriptor, DatabaseMapping mapping) {
+ String target = null;
+ if (mapping.isCollectionMapping()) {
+ CollectionMapping collectionMapping = (CollectionMapping) mapping;
+ String collectionType = collectionMapping.getContainerPolicy().getContainerClassName();
+ if (collectionMapping.getContainerPolicy().isMapPolicy()) {
+ String mapKeyType = ((MapContainerPolicy) collectionMapping.getContainerPolicy()).getKeyType().toString();
+ target = collectionType + "<" + mapKeyType + ", " + collectionMapping.getReferenceClassName() + ">";
+ } else {
+ target = collectionType + "<" + collectionMapping.getReferenceClassName() + ">";
+ }
+ } else if (mapping.isForeignReferenceMapping()) {
+ target = ((ForeignReferenceMapping) mapping).getReferenceClass().getName();
+ } else {
+ target = mapping.getAttributeClassification().getName();
+ }
+ descriptor.getAttributes().add(new Attribute(mapping.getAttributeName(), target));
+ }
+
+ protected Response getContexts(HttpHeaders hh, URI baseURI) throws JAXBException {
+ Set<String> contexts = getPersistenceFactory().getPersistenceContextNames();
+ Iterator<String> contextIterator = contexts.iterator();
+ List<Link> links = new ArrayList<Link>();
+ String mediaType = StreamingOutputMarshaller.mediaType(hh.getAcceptableMediaTypes()).toString();
+ while (contextIterator.hasNext()) {
+ String context = contextIterator.next();
+ links.add(new Link(context, mediaType, baseURI + context + "/metadata"));
+ }
+ String result = null;
+ result = marshallMetadata(links, mediaType);
+ return Response.ok(new StreamingOutputMarshaller(null, result, hh.getAcceptableMediaTypes())).build();
+ }
+}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/EntityResource.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/EntityResource.java
new file mode 100644
index 0000000..ac5bf1b
--- /dev/null
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/EntityResource.java
@@ -0,0 +1,80 @@
+/*******************************************************************************
+ * Copyright (c) 2012 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.
+ *
+ *
+ ******************************************************************************/
+
+package org.eclipse.persistence.jpa.rs;
+
+import java.io.InputStream;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+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 javax.xml.bind.JAXBException;
+
+@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
+@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
+@Path("/{context}/entity/")
+public class EntityResource extends AbstractResource {
+
+ @GET
+ @Path("{type}/{key}/{attribute}")
+ public Response findAttribute(@PathParam("context") String persistenceUnit, @PathParam("type") String type, @PathParam("key") String key, @PathParam("attribute") String attribute,
+ @Context HttpHeaders hh, @Context UriInfo ui) {
+ return findAttribute(persistenceUnit, type, key, attribute, hh, ui, ui.getBaseUri());
+ }
+
+ @GET
+ @Path("{type}/{key}")
+ public Response find(@PathParam("context") String persistenceUnit, @PathParam("type") String type, @PathParam("key") String key, @Context HttpHeaders hh, @Context UriInfo ui) {
+ return find(persistenceUnit, type, key, hh, ui, ui.getBaseUri());
+ }
+
+ @PUT
+ @Path("{type}")
+ public Response create(@PathParam("context") String persistenceUnit, @PathParam("type") String type, @Context HttpHeaders hh, @Context UriInfo uriInfo, InputStream in) throws JAXBException {
+ return create(persistenceUnit, type, hh, uriInfo, uriInfo.getBaseUri(), in);
+ }
+
+ @POST
+ @Path("{type}")
+ public Response update(@PathParam("context") String persistenceUnit, @PathParam("type") String type, @Context HttpHeaders hh, @Context UriInfo uriInfo, InputStream in) {
+ return update(persistenceUnit, type, hh, uriInfo, uriInfo.getBaseUri(), in);
+ }
+
+ @POST
+ @Path("{type}/{key}/{attribute}")
+ public Response setOrAddAttribute(@PathParam("context") String persistenceUnit, @PathParam("type") String type, @PathParam("key") String key, @PathParam("attribute") String attribute,
+ @Context HttpHeaders hh, @Context UriInfo ui, InputStream in) {
+ return setOrAddAttribute(persistenceUnit, type, key, attribute, hh, ui, ui.getBaseUri(), in);
+ }
+
+ @DELETE
+ @Path("{type}/{key}/{attribute}")
+ public Response removeAttribute(@PathParam("context") String persistenceUnit, @PathParam("type") String type, @PathParam("key") String key, @PathParam("attribute") String attribute,
+ @Context HttpHeaders hh, @Context UriInfo ui, InputStream in) {
+ return removeAttribute(persistenceUnit, type, key, attribute, hh, ui, ui.getBaseUri(), in);
+ }
+
+ @DELETE
+ @Path("{type}/{key}")
+ public Response delete(@PathParam("context") String persistenceUnit, @PathParam("type") String type, @PathParam("key") String key, @Context HttpHeaders hh, @Context UriInfo ui) {
+ return delete(persistenceUnit, type, key, hh, ui, ui.getBaseUri());
+ }
+}
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 84939df..101a09f 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
@@ -756,14 +756,9 @@ public class PersistenceContext {
}
});
- try {
- for (XmlAdapter adapter:getAdapters()) {
- unmarshaller.setAdapter(adapter);
- }
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
+ for (XmlAdapter adapter:getAdapters()) {
+ unmarshaller.setAdapter(adapter);
+ }
JAXBElement<?> element = unmarshaller.unmarshal(new StreamSource(in), type);
if (element.getValue() instanceof List<?>){
@@ -842,14 +837,9 @@ public class PersistenceContext {
marshaller.setAdapter(new LinkAdapter(getBaseURI().toString(), this));
marshaller.setAdapter(new RelationshipLinkAdapter(getBaseURI().toString(), this));
- try {
- for (XmlAdapter adapter:getAdapters()) {
- marshaller.setAdapter(adapter);
- }
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
+ for (XmlAdapter adapter:getAdapters()) {
+ marshaller.setAdapter(adapter);
+ }
if (mediaType == MediaType.APPLICATION_XML_TYPE && object instanceof List){
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
@@ -863,11 +853,10 @@ public class PersistenceContext {
marshaller.marshal(o, writer);
}
writer.writeEndDocument();
+ postMarshallEntity(object);
} catch (Exception e){
e.printStackTrace();
- throw new RuntimeException(e);
- } finally {
- postMarshallEntity(object);
+ throw new JPARSException(e.toString());
}
} else {
marshaller.marshal(object, output);
@@ -954,9 +943,12 @@ public class PersistenceContext {
return false;
}
- protected List<XmlAdapter> getAdapters() throws Exception {
- if (adapters == null) {
- adapters = new ArrayList<XmlAdapter>();
+ protected List<XmlAdapter> getAdapters() throws JPARSException {
+ if (adapters != null) {
+ return adapters;
+ }
+ adapters = new ArrayList<XmlAdapter>();
+ try {
for (ClassDescriptor desc : this.getJpaSession().getDescriptors().values()) {
// avoid embeddables
if (!desc.isAggregateCollectionDescriptor() && !desc.isAggregateDescriptor()) {
@@ -970,6 +962,9 @@ public class PersistenceContext {
adapters.add((XmlAdapter) referenceAdaptorConstructor.newInstance(args));
}
}
+ } catch(Exception ex) {
+ ex.printStackTrace();
+ throw new JPARSException(ex.getMessage());
}
return adapters;
}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceResource.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceResource.java
new file mode 100644
index 0000000..0c02806
--- /dev/null
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceResource.java
@@ -0,0 +1,141 @@
+/*******************************************************************************
+ * Copyright (c) 2011, 2012 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:
+ * dclarke/tware - initial
+ ******************************************************************************/
+package org.eclipse.persistence.jpa.rs;
+
+import java.io.InputStream;
+import java.io.StringWriter;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.net.URI;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.core.UriInfo;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.transform.stream.StreamSource;
+
+import org.eclipse.persistence.internal.helper.ConversionManager;
+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;
+import org.eclipse.persistence.internal.jpa.rs.metadata.model.LinkTemplate;
+import org.eclipse.persistence.internal.jpa.rs.metadata.model.Parameter;
+import org.eclipse.persistence.internal.jpa.rs.metadata.model.PersistenceUnit;
+import org.eclipse.persistence.internal.jpa.rs.metadata.model.Query;
+import org.eclipse.persistence.internal.jpa.rs.metadata.model.SessionBeanCall;
+import org.eclipse.persistence.jaxb.JAXBContext;
+import org.eclipse.persistence.jaxb.JAXBContextFactory;
+import org.eclipse.persistence.jaxb.MarshallerProperties;
+import org.eclipse.persistence.jaxb.UnmarshallerProperties;
+import org.eclipse.persistence.jpa.rs.util.JPARSLogger;
+import org.eclipse.persistence.jpa.rs.util.StreamingOutputMarshaller;
+
+/**
+ * PersistenceResource
+ * @author tware
+ *
+ */
+@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
+@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
+public class PersistenceResource extends AbstractResource {
+
+ @GET
+ public Response getContexts(@Context HttpHeaders hh, @Context UriInfo uriInfo) throws JAXBException {
+ return getContexts(hh, uriInfo.getBaseUri());
+ }
+
+ @POST
+ @Produces(MediaType.WILDCARD)
+ public Response callSessionBean(@Context HttpHeaders hh, @Context UriInfo ui, @Context UriInfo uriInfo, InputStream is) throws JAXBException, ClassNotFoundException, NamingException,
+ NoSuchMethodException, InvocationTargetException, IllegalAccessException {
+ return callSessionBean(hh, ui, ui.getBaseUri(), is);
+ }
+
+ @SuppressWarnings("rawtypes")
+ public Response callSessionBean(HttpHeaders hh, UriInfo ui, URI baseURI, InputStream is) throws JAXBException, ClassNotFoundException, NamingException, NoSuchMethodException,
+ InvocationTargetException, IllegalAccessException {
+ SessionBeanCall call = null;
+ call = unmarshallSessionBeanCall(is);
+
+ String jndiName = call.getJndiName();
+ javax.naming.Context ctx = new InitialContext();
+ Object ans = ctx.lookup(jndiName);
+ if (ans == null) {
+ JPARSLogger.fine("jpars_could_not_find_session_bean", new Object[] { jndiName });
+ return Response.status(Status.NOT_FOUND).build();
+ }
+
+ PersistenceContext context = null;
+ if (call.getContext() != null) {
+ context = getPersistenceFactory().get(call.getContext(), baseURI, null);
+ if (context == null) {
+ JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[] { call.getContext() });
+ return Response.status(Status.NOT_FOUND).build();
+ }
+ }
+
+ Class[] parameters = new Class[call.getParameters().size()];
+ Object[] args = new Object[call.getParameters().size()];
+ int i = 0;
+ for (Parameter param : call.getParameters()) {
+ Class parameterClass = null;
+ Object parameterValue = null;
+ if (context != null) {
+ parameterClass = context.getClass(param.getTypeName());
+ }
+ if (parameterClass != null) {
+ parameterValue = context.unmarshalEntity(param.getTypeName(), hh.getMediaType(), is);
+ } else {
+ parameterClass = Thread.currentThread().getContextClassLoader().loadClass(param.getTypeName());
+ parameterValue = ConversionManager.getDefaultManager().convertObject(param.getValue(), parameterClass);
+ }
+ parameters[i] = parameterClass;
+ args[i] = parameterValue;
+ i++;
+ }
+ Method method = ans.getClass().getMethod(call.getMethodName(), parameters);
+ Object returnValue = method.invoke(ans, args);
+ return Response.ok(new StreamingOutputMarshaller(null, returnValue, hh.getAcceptableMediaTypes())).build();
+ }
+
+ protected String marshallMetadata(Object metadata, String mediaType) throws JAXBException {
+ Class<?>[] jaxbClasses = new Class[] { Link.class, Attribute.class, Descriptor.class, LinkTemplate.class, PersistenceUnit.class, Query.class };
+ JAXBContext context = (JAXBContext) JAXBContextFactory.createContext(jaxbClasses, null);
+ Marshaller marshaller = context.createMarshaller();
+ marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, Boolean.FALSE);
+ marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, mediaType);
+ StringWriter writer = new StringWriter();
+ marshaller.marshal(metadata, writer);
+ return writer.toString();
+ }
+
+ protected SessionBeanCall unmarshallSessionBeanCall(InputStream data) throws JAXBException {
+ Class<?>[] jaxbClasses = new Class[] { SessionBeanCall.class };
+ JAXBContext context = (JAXBContext) JAXBContextFactory.createContext(jaxbClasses, null);
+ Unmarshaller unmarshaller = context.createUnmarshaller();
+ unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, Boolean.FALSE);
+ unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
+ StreamSource ss = new StreamSource(data);
+ return unmarshaller.unmarshal(ss, SessionBeanCall.class).getValue();
+ }
+}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceUnitResource.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceUnitResource.java
new file mode 100644
index 0000000..1bdde63
--- /dev/null
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/PersistenceUnitResource.java
@@ -0,0 +1,117 @@
+/*******************************************************************************
+ * Copyright (c) 2012 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.
+ *
+ *
+ ******************************************************************************/
+package org.eclipse.persistence.jpa.rs;
+
+import java.net.URI;
+import java.util.Iterator;
+import java.util.Map;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+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 javax.ws.rs.core.Response.ResponseBuilder;
+import javax.ws.rs.core.Response.Status;
+import javax.xml.bind.JAXBException;
+
+import org.eclipse.persistence.descriptors.ClassDescriptor;
+import org.eclipse.persistence.internal.jpa.rs.metadata.model.Link;
+import org.eclipse.persistence.internal.jpa.rs.metadata.model.PersistenceUnit;
+import org.eclipse.persistence.jpa.rs.PersistenceContext;
+import org.eclipse.persistence.jpa.rs.util.JPARSLogger;
+import org.eclipse.persistence.jpa.rs.util.StreamingOutputMarshaller;
+
+@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
+@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
+@Path("/{context}/")
+public class PersistenceUnitResource extends AbstractResource {
+
+ @GET
+ @Path("metadata/entity/{descriptorAlias}")
+ public Response getDescriptorMetadata(@PathParam("context") String persistenceUnit, @PathParam("descriptorAlias") String descriptorAlias, @Context HttpHeaders hh, @Context UriInfo uriInfo) {
+ return getDescriptorMetadata(persistenceUnit, descriptorAlias, hh, uriInfo.getBaseUri());
+ }
+
+ @GET
+ @Path("metadata")
+ public Response getTypes(@PathParam("context") String persistenceUnit, @Context HttpHeaders hh, @Context UriInfo uriInfo) {
+ return getTypes(persistenceUnit, hh, uriInfo.getBaseUri());
+ }
+
+ @POST
+ @Path("query/{name}")
+ @Produces({ MediaType.APPLICATION_OCTET_STREAM })
+ public Response namedQueryUpdate(@PathParam("context") String persistenceUnit, @PathParam("name") String name, @Context HttpHeaders hh, @Context UriInfo ui) {
+ return namedQueryUpdate(persistenceUnit, name, hh, ui, ui.getBaseUri());
+ }
+
+ @GET
+ @Path("metadata/query/")
+ public Response getQueriesMetadata(@PathParam("context") String persistenceUnit, @Context HttpHeaders hh, @Context UriInfo uriInfo) {
+ return getQueriesMetadata(persistenceUnit, hh, uriInfo.getBaseUri());
+ }
+
+ @GET
+ @Path("singleResultQuery/{name}")
+ @Produces(MediaType.WILDCARD)
+ public Response namedQuerySingleResult(@PathParam("context") String persistenceUnit, @PathParam("name") String name, @Context HttpHeaders hh, @Context UriInfo ui) {
+ return namedQuerySingleResult(persistenceUnit, name, hh, ui, ui.getBaseUri());
+ }
+
+ @GET
+ @Path("metadata/query/{queryName}")
+ public Response getQueryMetadata(@PathParam("context") String persistenceUnit, @PathParam("queryName") String queryName, @Context HttpHeaders hh, @Context UriInfo uriInfo) {
+ return getQueryMetadata(persistenceUnit, queryName, hh, uriInfo.getBaseUri());
+ }
+
+ @GET
+ @Path("query/{name}")
+ public Response namedQuery(@PathParam("context") String persistenceUnit, @PathParam("name") String name, @Context HttpHeaders hh, @Context UriInfo ui) {
+ return namedQuery(persistenceUnit, name, hh, ui, ui.getBaseUri());
+ }
+
+ @SuppressWarnings("rawtypes")
+ public Response getTypes(String persistenceUnit, HttpHeaders hh, URI baseURI) {
+ PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
+ if (app == null) {
+ JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[] { persistenceUnit });
+ return Response.status(Status.NOT_FOUND).build();
+ } else {
+ PersistenceUnit pu = new PersistenceUnit();
+ pu.setPersistenceUnitName(persistenceUnit);
+ Map<Class, ClassDescriptor> descriptors = app.getJpaSession().getDescriptors();
+ String mediaType = StreamingOutputMarshaller.mediaType(hh.getAcceptableMediaTypes()).toString();
+ Iterator<Class> contextIterator = descriptors.keySet().iterator();
+ while (contextIterator.hasNext()) {
+ ClassDescriptor descriptor = descriptors.get(contextIterator.next());
+ pu.getTypes().add(new Link(descriptor.getAlias(), mediaType, baseURI + persistenceUnit + "/metadata/entity/" + descriptor.getAlias()));
+ }
+ String result = null;
+ try {
+ result = marshallMetadata(pu, mediaType);
+ } catch (JAXBException e) {
+ JPARSLogger.fine("exception_marshalling_persitence_unit", new Object[] { persistenceUnit, e.toString() });
+ return Response.status(Status.INTERNAL_SERVER_ERROR).build();
+ }
+ ResponseBuilder rb = Response.ok(new StreamingOutputMarshaller(null, result, hh.getAcceptableMediaTypes()));
+ rb.header("Content-Type", MediaType.APPLICATION_JSON);
+ return rb.build();
+ }
+ }
+}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/ServiceBase.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/ServiceBase.java
deleted file mode 100644
index 11860b8..0000000
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/ServiceBase.java
+++ /dev/null
@@ -1,773 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2011, 2012 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:
- * dclarke/tware - initial
- ******************************************************************************/
-package org.eclipse.persistence.jpa.rs;
-
-import static org.eclipse.persistence.jpa.rs.util.StreamingOutputMarshaller.mediaType;
-
-import java.io.InputStream;
-import java.io.StringWriter;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.PathSegment;
-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 javax.xml.bind.JAXBException;
-import javax.xml.bind.Marshaller;
-import javax.xml.bind.Unmarshaller;
-import javax.xml.transform.stream.StreamSource;
-
-import org.eclipse.persistence.descriptors.ClassDescriptor;
-import org.eclipse.persistence.exceptions.ConversionException;
-import org.eclipse.persistence.internal.expressions.ConstantExpression;
-import org.eclipse.persistence.internal.expressions.MapEntryExpression;
-import org.eclipse.persistence.internal.helper.ClassConstants;
-import org.eclipse.persistence.internal.helper.ConversionManager;
-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;
-import org.eclipse.persistence.internal.jpa.rs.metadata.model.LinkTemplate;
-import org.eclipse.persistence.internal.jpa.rs.metadata.model.Parameter;
-import org.eclipse.persistence.internal.jpa.rs.metadata.model.PersistenceUnit;
-import org.eclipse.persistence.internal.jpa.rs.metadata.model.Query;
-import org.eclipse.persistence.internal.jpa.rs.metadata.model.SessionBeanCall;
-import org.eclipse.persistence.internal.queries.MapContainerPolicy;
-import org.eclipse.persistence.internal.queries.ReportItem;
-import org.eclipse.persistence.jaxb.JAXBContext;
-import org.eclipse.persistence.jaxb.JAXBContextFactory;
-import org.eclipse.persistence.jaxb.MarshallerProperties;
-import org.eclipse.persistence.jaxb.UnmarshallerProperties;
-import org.eclipse.persistence.jpa.rs.util.IdHelper;
-import org.eclipse.persistence.jpa.rs.util.JPARSLogger;
-import org.eclipse.persistence.jpa.rs.util.StreamingOutputMarshaller;
-import org.eclipse.persistence.mappings.CollectionMapping;
-import org.eclipse.persistence.mappings.DatabaseMapping;
-import org.eclipse.persistence.mappings.ForeignReferenceMapping;
-import org.eclipse.persistence.mappings.foundation.AbstractDirectMapping;
-import org.eclipse.persistence.queries.DatabaseQuery;
-import org.eclipse.persistence.queries.ReportQuery;
-import org.eclipse.persistence.sessions.DatabaseRecord;
-
-/**
- * Provides all the base JPA-RS Rest functionality.
- * @author tware
- *
- */
-@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
-@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
-public class ServiceBase {
-
- public static final String RELATIONSHIP_PARTNER = "partner";
- protected PersistenceFactoryBase factory;
-
- public PersistenceFactoryBase getPersistenceFactory() {
- if (factory == null){
- factory = new PersistenceFactoryBase();
- }
- return factory;
- }
-
- @GET
- public Response getContexts(@Context HttpHeaders hh, @Context UriInfo uriInfo) throws JAXBException {
- return getContexts(hh, uriInfo.getBaseUri());
- }
-
- public Response getContexts(HttpHeaders hh, URI baseURI) throws JAXBException {
- Set<String> contexts = getPersistenceFactory().getPersistenceContextNames();
- Iterator<String> contextIterator = contexts.iterator();
- List<Link> links = new ArrayList<Link>();
- String mediaType = StreamingOutputMarshaller.mediaType(hh.getAcceptableMediaTypes()).toString();
- while (contextIterator.hasNext()){
- String context = contextIterator.next();
- links.add(new Link(context, mediaType, baseURI + context + "/metadata\""));
- }
- String result = null;
- result = marshallMetadata(links, mediaType);
- return Response.ok(new StreamingOutputMarshaller(null, result, hh.getAcceptableMediaTypes())).build();
- }
-
-
- @POST
- @Produces(MediaType.WILDCARD)
- public Response callSessionBean(@Context HttpHeaders hh, @Context UriInfo ui, @Context UriInfo uriInfo, InputStream is) throws JAXBException, ClassNotFoundException, NamingException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
- return callSessionBean(hh, ui, ui.getBaseUri(), is);
- }
-
- @SuppressWarnings("rawtypes")
- public Response callSessionBean(HttpHeaders hh, UriInfo ui, URI baseURI, InputStream is) throws JAXBException, ClassNotFoundException, NamingException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
- SessionBeanCall call = null;
- call = unmarshallSessionBeanCall(is);
-
- String jndiName = call.getJndiName();
- javax.naming.Context ctx = new InitialContext();
- Object ans = ctx.lookup(jndiName);
- if (ans == null){
- JPARSLogger.fine("jpars_could_not_find_session_bean", new Object[]{jndiName});
- return Response.status(Status.NOT_FOUND).build();
- }
-
- PersistenceContext context = null;
- if (call.getContext() != null){
- context = getPersistenceFactory().get(call.getContext(), baseURI, null);
- if (context == null){
- JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[]{call.getContext()});
- return Response.status(Status.NOT_FOUND).build();
- }
- }
-
- Class[] parameters = new Class[call.getParameters().size()];
- Object[] args = new Object[call.getParameters().size()];
- int i = 0;
- for (Parameter param: call.getParameters()){
- Class parameterClass = null;
- Object parameterValue = null;
- if (context != null){
- parameterClass = context.getClass(param.getTypeName());
- }
- if (parameterClass != null){
- parameterValue = context.unmarshalEntity(param.getTypeName(), hh.getMediaType(), is);
- } else {
- parameterClass = Thread.currentThread().getContextClassLoader().loadClass(param.getTypeName());
- parameterValue = ConversionManager.getDefaultManager().convertObject(param.getValue(), parameterClass);
- }
- parameters[i] = parameterClass;
- args[i] = parameterValue;
- i++;
- }
- Method method = ans.getClass().getMethod(call.getMethodName(), parameters);
- Object returnValue = method.invoke(ans, args);
- return Response.ok(new StreamingOutputMarshaller(null, returnValue, hh.getAcceptableMediaTypes())).build();
- }
-
- @GET
- @Path("{context}/metadata")
- public Response getTypes(@PathParam("context") String persistenceUnit, @Context HttpHeaders hh, @Context UriInfo uriInfo) {
- return getTypes(persistenceUnit, hh, uriInfo.getBaseUri());
- }
-
- @SuppressWarnings("rawtypes")
- public Response getTypes(String persistenceUnit, HttpHeaders hh, URI baseURI) {
- PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
- if (app == null){
- JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[]{persistenceUnit});
- return Response.status(Status.NOT_FOUND).build();
- } else {
- PersistenceUnit pu = new PersistenceUnit();
- pu.setPersistenceUnitName(persistenceUnit);
- Map<Class, ClassDescriptor> descriptors = app.getJpaSession().getDescriptors();
- String mediaType = StreamingOutputMarshaller.mediaType(hh.getAcceptableMediaTypes()).toString();
- Iterator<Class> contextIterator = descriptors.keySet().iterator();
- while (contextIterator.hasNext()){
- ClassDescriptor descriptor = descriptors.get(contextIterator.next());
- pu.getTypes().add(new Link(descriptor.getAlias(), mediaType, baseURI + persistenceUnit + "/metadata/entity/" + descriptor.getAlias()));
- }
- String result = null;
- try {
- result = marshallMetadata(pu, mediaType);
- } catch (JAXBException e){
- JPARSLogger.fine("exception_marshalling_persitence_unit", new Object[]{persistenceUnit, e.toString()});
- return Response.status(Status.INTERNAL_SERVER_ERROR).build();
- }
- ResponseBuilder rb = Response.ok(new StreamingOutputMarshaller(null , result, hh.getAcceptableMediaTypes()));
- rb.header("Content-Type", MediaType.APPLICATION_JSON);
- return rb.build();
- }
- }
-
-
- @GET
- @Path("{context}/metadata/entity/{descriptorAlias}")
- public Response getDescriptorMetadata(@PathParam("context") String persistenceUnit, @PathParam("descriptorAlias") String descriptorAlias, @Context HttpHeaders hh, @Context UriInfo uriInfo) {
- return getDescriptorMetadata(persistenceUnit, descriptorAlias, hh, uriInfo.getBaseUri());
- }
-
- public Response getDescriptorMetadata(String persistenceUnit, String descriptorAlias, HttpHeaders hh, URI baseURI) {
- PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
- if (app == null){
- JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[]{persistenceUnit});
- return Response.status(Status.NOT_FOUND).build();
- } else {
- ClassDescriptor descriptor = app.getJpaSession().getDescriptorForAlias(descriptorAlias);
- if (descriptor == null){
- JPARSLogger.fine("jpars_could_not_find_entity_type", new Object[]{descriptorAlias, persistenceUnit});
- return Response.status(Status.NOT_FOUND).build();
- } else {
- String mediaType = StreamingOutputMarshaller.mediaType(hh.getAcceptableMediaTypes()).toString();
- Descriptor returnDescriptor = buildDescriptor(app, persistenceUnit, descriptor, baseURI.toString());
- String result = null;
- try {
- result = marshallMetadata(returnDescriptor, mediaType);
- } catch (JAXBException e){
- JPARSLogger.fine("exception_marshalling_entity_metadata", new Object[]{descriptorAlias, persistenceUnit, e.toString()});
- return Response.status(Status.INTERNAL_SERVER_ERROR).build();
- }
- return Response.ok(new StreamingOutputMarshaller(null , result, hh.getAcceptableMediaTypes())).build();
- }
- }
- }
-
- @GET
- @Path("{context}/metadata/query/")
- public Response getQueriesMetadata(@PathParam("context") String persistenceUnit, @Context HttpHeaders hh, @Context UriInfo uriInfo) {
- return getQueriesMetadata(persistenceUnit, hh, uriInfo.getBaseUri());
- }
-
- public Response getQueriesMetadata(String persistenceUnit, HttpHeaders hh, URI baseURI) {
- PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
- if (app == null){
- JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[]{persistenceUnit});
- return Response.status(Status.NOT_FOUND).build();
- } else {
- List<Query> queries = new ArrayList<Query>();
- addQueries(queries, app, null);
- String mediaType = StreamingOutputMarshaller.mediaType(hh.getAcceptableMediaTypes()).toString();
- String result = null;
- try {
- result = marshallMetadata(queries, mediaType);
- } catch (JAXBException e){
- JPARSLogger.fine("exception_marshalling_query_metadata", new Object[]{persistenceUnit, e.toString()});
- return Response.status(Status.INTERNAL_SERVER_ERROR).build();
- }
- return Response.ok(new StreamingOutputMarshaller(null , result, hh.getAcceptableMediaTypes())).build();
- }
- }
-
- @GET
- @Path("{context}/metadata/query/{queryName}")
- public Response getQueryMetadata(@PathParam("context") String persistenceUnit, @PathParam("queryName") String queryName, @Context HttpHeaders hh, @Context UriInfo uriInfo) {
- return getQueryMetadata(persistenceUnit, queryName, hh, uriInfo.getBaseUri());
- }
-
- public Response getQueryMetadata(String persistenceUnit, String queryName, HttpHeaders hh, URI baseURI) {
- PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
- if (app == null){
- JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[]{persistenceUnit});
- return Response.status(Status.NOT_FOUND).build();
- } else {
- List<Query> returnQueries = new ArrayList<Query>();
- Map<String, List<DatabaseQuery>> queries = app.getJpaSession().getQueries();
- if (queries.get(queryName) != null){
- for (DatabaseQuery query :queries.get(queryName)){
- returnQueries.add(getQuery(query, app));
- }
- }
- String mediaType = StreamingOutputMarshaller.mediaType(hh.getAcceptableMediaTypes()).toString();
- String result = null;
- try {
- result = marshallMetadata(returnQueries, mediaType);
- } catch (JAXBException e){
- JPARSLogger.fine("exception_marshalling_individual_query_metadata", new Object[]{queryName, persistenceUnit, e.toString()});
- return Response.status(Status.INTERNAL_SERVER_ERROR).build();
- }
- return Response.ok(new StreamingOutputMarshaller(null , result, hh.getAcceptableMediaTypes())).build();
- }
- }
-
- @GET
- @Path("{context}/entity/{type}/{key}")
- public Response find(@PathParam("context") String persistenceUnit, @PathParam("type") String type, @PathParam("key") String key, @Context HttpHeaders hh, @Context UriInfo ui) {
- return find(persistenceUnit, type, key, hh, ui, ui.getBaseUri());
- }
-
- public Response find(String persistenceUnit, String type, String key, HttpHeaders hh, UriInfo ui, URI baseURI) {
- PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
- if (app == null || app.getClass(type) == null){
- if (app == null){
- JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[]{persistenceUnit});
- } else {
- JPARSLogger.fine("jpars_could_not_find_class_in_persistence_unit", new Object[]{type, persistenceUnit});
- }
- return Response.status(Status.NOT_FOUND).build();
- }
- Map<String, String> discriminators = getParameterMap(ui, persistenceUnit);
-
- Object id = IdHelper.buildId(app, type, key, discriminators);
-
- Object entity = app.find(discriminators, type, id, ServiceBase.getHintMap(ui));
-
- if (entity == null) {
- JPARSLogger.fine("jpars_could_not_entity_for_key", new Object[]{type, key, persistenceUnit});
- return Response.status(Status.NOT_FOUND).build();
- } else {
- return Response.ok(new StreamingOutputMarshaller(app, entity, hh.getAcceptableMediaTypes())).build();
- }
- }
-
- @GET
- @Path("{context}/entity/{type}/{key}/{attribute}")
- public Response findAttribute(@PathParam("context") String persistenceUnit, @PathParam("type") String type, @PathParam("key") String key, @PathParam("attribute") String attribute, @Context HttpHeaders hh, @Context UriInfo ui) {
- return findAttribute(persistenceUnit, type, key, attribute, hh, ui, ui.getBaseUri());
- }
-
- public Response findAttribute(String persistenceUnit, String type, String key, String attribute, HttpHeaders hh, UriInfo ui, URI baseURI) {
- PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
- if (app == null || app.getClass(type) == null){
- if (app == null){
- JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[]{persistenceUnit});
- } else {
- JPARSLogger.fine("jpars_could_not_find_class_in_persistence_unit", new Object[]{type, persistenceUnit});
- }
- return Response.status(Status.NOT_FOUND).build();
- }
- Map<String, String> discriminators = getParameterMap(ui, persistenceUnit);
- Object id = IdHelper.buildId(app, type, key, discriminators);
-
- Object entity = app.findAttribute(discriminators, type, id, ServiceBase.getHintMap(ui), attribute);
-
- if (entity == null) {
- JPARSLogger.fine("jpars_could_not_entity_for_attribute", new Object[]{type, key, attribute, persistenceUnit});
- return Response.status(Status.NOT_FOUND).build();
- } else {
- return Response.ok(new StreamingOutputMarshaller(app, entity, hh.getAcceptableMediaTypes())).build();
- }
- }
-
- @POST
- @Path("{context}/entity/{type}/{key}/{attribute}")
- public Response setOrAddAttribute(@PathParam("context") String persistenceUnit, @PathParam("type") String type, @PathParam("key") String key, @PathParam("attribute") String attribute, @Context HttpHeaders hh, @Context UriInfo ui, InputStream in) {
- return setOrAddAttribute(persistenceUnit, type, key, attribute, hh, ui, ui.getBaseUri(), in);
- }
-
- public Response setOrAddAttribute(String persistenceUnit, String type, String key, String attribute, HttpHeaders hh, UriInfo ui, URI baseURI, InputStream in) {
- PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
- if (app == null || app.getClass(type) == null){
- if (app == null){
- JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[]{persistenceUnit});
- } else {
- JPARSLogger.fine("jpars_could_not_find_class_in_persistence_unit", new Object[]{type, persistenceUnit});
- }
- return Response.status(Status.NOT_FOUND).build();
- }
-
- Map<String, String> discriminators = getParameterMap(ui, persistenceUnit);
- Object id = IdHelper.buildId(app, type, key, discriminators);
-
- Object entity = null;
- String partner = (String)ServiceBase.getParameterMap(ui, attribute).get(RELATIONSHIP_PARTNER);
- try{
- ClassDescriptor descriptor = app.getDescriptor(type);
- DatabaseMapping mapping = (DatabaseMapping)descriptor.getMappingForAttributeName(attribute);
- if (!mapping.isForeignReferenceMapping()){
- JPARSLogger.fine("jpars_could_find_appropriate_mapping_for_update", new Object[]{attribute, type, key, persistenceUnit});
- return Response.status(Status.NOT_FOUND).build();
- }
- entity = app.unmarshalEntity(((ForeignReferenceMapping)mapping).getReferenceDescriptor().getAlias(), mediaType(hh.getAcceptableMediaTypes()), in);
- } catch (JAXBException e){
- JPARSLogger.fine("exception_while_ummarhalling_entity", new Object[]{type, persistenceUnit, e.toString()});
- return Response.status(Status.BAD_REQUEST).build();
- } catch (ConversionException e) {
- // unmarshaller might also throw ConversionException if it cannot
- // unmarshal input stream
- JPARSLogger.fine("exception_while_ummarhalling_entity",
- new Object[] { type, persistenceUnit, e.toString() });
- return Response.status(Status.BAD_REQUEST).build();
- }
-
- Object result = app.updateOrAddAttribute(getParameterMap(ui, persistenceUnit), type, id, ServiceBase.getHintMap(ui), attribute, entity, partner);
-
- if (result == null) {
- JPARSLogger.fine("jpars_could_not_update_attribute", new Object[]{attribute, type, key, persistenceUnit});
- return Response.status(Status.NOT_FOUND).build();
- } else {
- return Response.ok(new StreamingOutputMarshaller(app, result, hh.getAcceptableMediaTypes())).build();
- }
- }
-
- @DELETE
- @Path("{context}/entity/{type}/{key}/{attribute}")
- public Response removeAttribute(@PathParam("context") String persistenceUnit, @PathParam("type") String type, @PathParam("key") String key, @PathParam("attribute") String attribute, @Context HttpHeaders hh, @Context UriInfo ui, InputStream in) {
- return removeAttribute(persistenceUnit, type, key, attribute, hh, ui, ui.getBaseUri(), in);
- }
-
- public Response removeAttribute(String persistenceUnit, String type, String key, String attribute, HttpHeaders hh, UriInfo ui, URI baseURI, InputStream in) {
- PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
- if (app == null || app.getClass(type) == null){
- if (app == null){
- JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[]{persistenceUnit});
- } else {
- JPARSLogger.fine("jpars_could_not_find_class_in_persistence_unit", new Object[]{type, persistenceUnit});
- }
- return Response.status(Status.NOT_FOUND).build();
- }
-
- Map<String, String> discriminators = getParameterMap(ui, persistenceUnit);
- Object id = IdHelper.buildId(app, type, key, discriminators);
-
- Object entity = null;
- String partner = (String)ServiceBase.getParameterMap(ui, attribute).get(RELATIONSHIP_PARTNER);
- try{
- ClassDescriptor descriptor = app.getDescriptor(type);
- DatabaseMapping mapping = (DatabaseMapping)descriptor.getMappingForAttributeName(attribute);
- if (!mapping.isForeignReferenceMapping()){
- JPARSLogger.fine("jpars_could_find_appropriate_mapping_for_update", new Object[]{attribute, type, key, persistenceUnit});
- return Response.status(Status.NOT_FOUND).build();
- }
- entity = app.unmarshalEntity(((ForeignReferenceMapping)mapping).getReferenceDescriptor().getAlias(), mediaType(hh.getAcceptableMediaTypes()), in);
- } catch (JAXBException e){
- JPARSLogger.fine("exception_while_ummarhalling_entity", new Object[]{type, persistenceUnit, e.toString()});
- return Response.status(Status.BAD_REQUEST).build();
- } catch (ConversionException e) {
- // unmarshaller might also throw ConversionException if it cannot
- // unmarshal input stream
- JPARSLogger.fine("exception_while_ummarhalling_entity",
- new Object[] { type, persistenceUnit, e.toString() });
- return Response.status(Status.BAD_REQUEST).build();
- }
-
- Object result = app.removeAttribute(getParameterMap(ui, persistenceUnit), type, id, ServiceBase.getHintMap(ui), attribute, entity, partner);
- if (result == null) {
- JPARSLogger.fine("jpars_could_not_update_attribute", new Object[]{attribute, type, key, persistenceUnit});
- return Response.status(Status.NOT_FOUND).build();
- } else {
- return Response.ok(new StreamingOutputMarshaller(app, result, hh.getAcceptableMediaTypes())).build();
- }
- }
-
- @PUT
- @Path("{context}/entity/{type}")
- public Response create(@PathParam("context") String persistenceUnit, @PathParam("type") String type, @Context HttpHeaders hh, @Context UriInfo uriInfo, InputStream in) throws JAXBException {
- return create(persistenceUnit, type, hh, uriInfo, uriInfo.getBaseUri(), in);
- }
-
- public Response create(String persistenceUnit, String type, HttpHeaders hh, UriInfo uriInfo, URI baseURI, InputStream in) throws JAXBException {
- PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
- if (app == null){
- JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[]{persistenceUnit});
- return Response.status(Status.NOT_FOUND).build();
- }
- ClassDescriptor descriptor = app.getDescriptor(type);
- if (descriptor == null){
- JPARSLogger.fine("jpars_could_not_find_class_in_persistence_unit", new Object[]{type, persistenceUnit});
- return Response.status(Status.NOT_FOUND).build();
- }
- Object entity = null;
- try{
- entity = app.unmarshalEntity(type, mediaType(hh.getAcceptableMediaTypes()), in);
- } catch (JAXBException e){
- JPARSLogger.fine("exception_while_ummarhalling_entity", new Object[]{type, persistenceUnit, e.toString()});
- return Response.status(Status.BAD_REQUEST).build();
- } catch (ConversionException e){
- // unmarshaller might also throw ConversionException if it cannot unmarshal input stream
- JPARSLogger.fine("exception_while_ummarhalling_entity", new Object[]{type, persistenceUnit, e.toString()});
- return Response.status(Status.BAD_REQUEST).build();
- }
-
- // maintain idempotence on PUT by disallowing sequencing
- AbstractDirectMapping sequenceMapping = descriptor.getObjectBuilder().getSequenceMapping();
- if (sequenceMapping != null){
- Object value = sequenceMapping.getAttributeAccessor().getAttributeValueFromObject(entity);
-
- if (descriptor.getObjectBuilder().isPrimaryKeyComponentInvalid(value, descriptor.getPrimaryKeyFields().indexOf(descriptor.getSequenceNumberField())) || descriptor.getSequence().shouldAlwaysOverrideExistingValue()){
- JPARSLogger.fine("jpars_put_not_itempotent", new Object[]{type, persistenceUnit});
- return Response.status(Status.BAD_REQUEST).build();
- }
- }
-
- app.create(getParameterMap(uriInfo, persistenceUnit), entity);
- ResponseBuilder rb = Response.status(Status.CREATED);
- rb.entity(new StreamingOutputMarshaller(app, entity, hh.getAcceptableMediaTypes()));
- return rb.build();
- }
-
- @POST
- @Path("{context}/entity/{type}")
- public Response update(@PathParam("context") String persistenceUnit, @PathParam("type") String type, @Context HttpHeaders hh, @Context UriInfo uriInfo, InputStream in) {
- return update(persistenceUnit, type, hh, uriInfo, uriInfo.getBaseUri(), in);
- }
-
- public Response update(@PathParam("context") String persistenceUnit, @PathParam("type") String type, @Context HttpHeaders hh, @Context UriInfo uriInfo, URI baseURI, InputStream in) {
- PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
- if (app == null || app.getClass(type) == null){
- if (app == null){
- JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[]{persistenceUnit});
- } else {
- JPARSLogger.fine("jpars_could_not_find_class_in_persistence_unit", new Object[]{type, persistenceUnit});
- }
- return Response.status(Status.NOT_FOUND).build();
- }
- MediaType contentType = mediaType(hh.getRequestHeader(HttpHeaders.CONTENT_TYPE));
- Object entity = null;
- try {
- entity = app.unmarshalEntity(type, contentType, in);
- } catch (JAXBException e){
- JPARSLogger.fine("exception_while_ummarhalling_entity", new Object[]{type, persistenceUnit, e.toString()});
- return Response.status(Status.BAD_REQUEST).build();
- } catch (ConversionException e) {
- // unmarshaller might also throw ConversionException if it cannot
- // unmarshal input stream
- JPARSLogger.fine("exception_while_ummarhalling_entity",
- new Object[] { type, persistenceUnit, e.toString() });
- return Response.status(Status.BAD_REQUEST).build();
- }
-
- entity = app.merge(getParameterMap(uriInfo, persistenceUnit), entity);
- return Response.ok(new StreamingOutputMarshaller(app, entity, hh.getAcceptableMediaTypes())).build();
- }
-
- @DELETE
- @Path("{context}/entity/{type}/{key}")
- public Response delete(@PathParam("context") String persistenceUnit, @PathParam("type") String type, @PathParam("key") String key, @Context HttpHeaders hh, @Context UriInfo ui) {
- return delete(persistenceUnit, type, key, hh, ui, ui.getBaseUri());
- }
-
- public Response delete(String persistenceUnit, String type, String key, HttpHeaders hh, UriInfo ui, URI baseURI) {
- PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
- if (app == null || app.getClass(type) == null){
- if (app == null){
- JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[]{persistenceUnit});
- } else {
- JPARSLogger.fine("jpars_could_not_find_class_in_persistence_unit", new Object[]{type, persistenceUnit});
- }
- return Response.status(Status.NOT_FOUND).build();
- }
- Map<String, String> discriminators = getParameterMap(ui, persistenceUnit);
- Object id = IdHelper.buildId(app, type, key, discriminators);
- app.delete(discriminators, type, id);
- return Response.ok().build();
- }
-
- @GET
- @Path("{context}/query/{name}")
- public Response namedQuery(@PathParam("context") String persistenceUnit, @PathParam("name") String name, @Context HttpHeaders hh, @Context UriInfo ui) {
- return namedQuery(persistenceUnit, name, hh, ui, ui.getBaseUri());
- }
-
- public Response namedQuery(String persistenceUnit, String name, HttpHeaders hh, UriInfo ui, URI baseURI) {
- PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
- if (app == null){
- JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[]{persistenceUnit});
- return Response.status(Status.NOT_FOUND).build();
- }
- Object result = app.query(getParameterMap(ui, persistenceUnit), name, ServiceBase.getParameterMap(ui, name), ServiceBase.getHintMap(ui), false, false);
- return Response.ok(new StreamingOutputMarshaller(app, result, hh.getAcceptableMediaTypes())).build();
- }
-
- @POST
- @Path("{context}/query/{name}")
- @Produces({ MediaType.APPLICATION_OCTET_STREAM})
- public Response namedQueryUpdate(@PathParam("context") String persistenceUnit, @PathParam("name") String name, @Context HttpHeaders hh, @Context UriInfo ui) {
- return namedQueryUpdate(persistenceUnit, name, hh, ui, ui.getBaseUri());
- }
-
- public Response namedQueryUpdate(String persistenceUnit, String name, HttpHeaders hh, UriInfo ui, URI baseURI) {
- PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
- if (app == null){
- JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[]{persistenceUnit});
- return Response.status(Status.NOT_FOUND).build();
- }
- Object result = app.query(getParameterMap(ui, persistenceUnit), name, ServiceBase.getParameterMap(ui, name), ServiceBase.getHintMap(ui), false, true);
- return Response.ok(new StreamingOutputMarshaller(app, result.toString(), hh.getAcceptableMediaTypes())).build();
- }
-
- @GET
- @Path("{context}/singleResultQuery/{name}")
- @Produces(MediaType.WILDCARD)
- public Response namedQuerySingleResult(@PathParam("context") String persistenceUnit, @PathParam("name") String name, @Context HttpHeaders hh, @Context UriInfo ui) {
- return namedQuerySingleResult(persistenceUnit, name, hh, ui, ui.getBaseUri());
- }
-
- public Response namedQuerySingleResult(String persistenceUnit, String name, HttpHeaders hh, UriInfo ui, URI baseURI) {
- PersistenceContext app = getPersistenceFactory().get(persistenceUnit, baseURI, null);
- if (app == null){
- JPARSLogger.fine("jpars_could_not_find_persistence_context", new Object[]{persistenceUnit});
- return Response.status(Status.NOT_FOUND).build();
- }
- Object result = app.query(getParameterMap(ui, persistenceUnit), name, ServiceBase.getParameterMap(ui, name), ServiceBase.getHintMap(ui), true, false);
- return Response.ok(new StreamingOutputMarshaller(app, result, hh.getAcceptableMediaTypes())).build();
- }
-
- protected Descriptor buildDescriptor(PersistenceContext app, String persistenceUnit, ClassDescriptor descriptor, String baseUri){
- Descriptor returnDescriptor = new Descriptor();
- returnDescriptor.setName(descriptor.getAlias());
- returnDescriptor.setType(descriptor.getJavaClassName());
- returnDescriptor.getLinkTemplates().add(new LinkTemplate("find", "get", baseUri + persistenceUnit + "/entity/" + descriptor.getAlias() + "/{primaryKey}"));
- returnDescriptor.getLinkTemplates().add(new LinkTemplate("persist", "put", baseUri + persistenceUnit + "/entity/" + descriptor.getAlias()));
- returnDescriptor.getLinkTemplates().add(new LinkTemplate("update", "post", baseUri + persistenceUnit + "/entity/" + descriptor.getAlias()));
- returnDescriptor.getLinkTemplates().add(new LinkTemplate("delete", "delete", baseUri + persistenceUnit + "/entity/" + descriptor.getAlias() + "/{primaryKey}"));
-
- if (!descriptor.getMappings().isEmpty()){
- Iterator<DatabaseMapping> mappingIterator = descriptor.getMappings().iterator();
- while (mappingIterator.hasNext()){
- DatabaseMapping mapping = mappingIterator.next();
- addMapping(returnDescriptor, mapping);
- }
- }
- addQueries(returnDescriptor.getQueries(), app, descriptor.getJavaClassName());
- return returnDescriptor;
- }
-
- protected void addMapping(Descriptor descriptor, DatabaseMapping mapping){
- String target = null;
- if (mapping.isCollectionMapping()){
- CollectionMapping collectionMapping = (CollectionMapping)mapping;
- String collectionType = collectionMapping.getContainerPolicy().getContainerClassName();
- if (collectionMapping.getContainerPolicy().isMapPolicy()){
- String mapKeyType = ((MapContainerPolicy)collectionMapping.getContainerPolicy()).getKeyType().toString();
- target = collectionType + "<" + mapKeyType + ", " + collectionMapping.getReferenceClassName() + ">";
- } else {
- target = collectionType + "<" + collectionMapping.getReferenceClassName() + ">";
- }
- } else if (mapping.isForeignReferenceMapping()){
- target = ((ForeignReferenceMapping)mapping).getReferenceClass().getName();
- } else {
- target = mapping.getAttributeClassification().getName();
- }
- descriptor.getAttributes().add(new Attribute(mapping.getAttributeName(), target));
- }
-
- protected void addQueries(List<Query> queryList, PersistenceContext app, String javaClassName){
- Map<String, List<DatabaseQuery>> queries = app.getJpaSession().getQueries();
- List<DatabaseQuery> returnQueries = new ArrayList<DatabaseQuery>();
- for (String key: queries.keySet()){
- List<DatabaseQuery> keyQueries = queries.get(key);
- Iterator<DatabaseQuery> queryIterator = keyQueries.iterator();
- while (queryIterator.hasNext()){
- DatabaseQuery query= queryIterator.next();
- if (javaClassName == null || (query.getReferenceClassName() != null && query.getReferenceClassName().equals(javaClassName))){
- returnQueries.add(query);
- }
- }
- }
- Iterator<DatabaseQuery> queryIterator = returnQueries.iterator();
- while(queryIterator.hasNext()){
- queryList.add(getQuery(queryIterator.next(), app));
- }
- }
-
- protected Query getQuery(DatabaseQuery query, PersistenceContext app){
- String method = query.isReadQuery() ? "get" : "post";
- String jpql = query.getJPQLString() == null? "" : query.getJPQLString();
- StringBuffer parameterString = new StringBuffer();
- Iterator<String> argumentsIterator = query.getArguments().iterator();
- while (argumentsIterator.hasNext()){
- String argument = argumentsIterator.next();
- parameterString.append(";");
- parameterString.append(argument + "={" + argument + "}");
- }
- Query returnQuery = new Query(query.getName(), jpql, new LinkTemplate("execute", method, app.getBaseURI() + app.getName() + "/query/" + query.getName() + parameterString));
- if (query.isReportQuery()){
- query.checkPrepare(app.getJpaSession(), new DatabaseRecord());
- for (ReportItem item: ((ReportQuery)query).getItems()){
- if (item.getMapping() != null) {
- if (item.getAttributeExpression() != null && item.getAttributeExpression().isMapEntryExpression()){
- if (((MapEntryExpression)item.getAttributeExpression()).shouldReturnMapEntry()){
- returnQuery.getReturnTypes().add(Map.Entry.class.getName());
- } else {
- returnQuery.getReturnTypes().add(((Class<?>)((CollectionMapping)item.getMapping()).getContainerPolicy().getKeyType()).getName());
- }
- } else {
- returnQuery.getReturnTypes().add(item.getMapping().getAttributeClassification().getName());
- }
- } else if (item.getResultType() != null) {
- returnQuery.getReturnTypes().add(item.getResultType().getName());
- } else if (item.getDescriptor() != null) {
- returnQuery.getReturnTypes().add(item.getDescriptor().getJavaClass().getName());
- } else if (item.getAttributeExpression() != null && item.getAttributeExpression().isConstantExpression()){
- returnQuery.getReturnTypes().add(((ConstantExpression)item.getAttributeExpression()).getValue().getClass().getName());
- } else {
- // Use Object.class by default.
- returnQuery.getReturnTypes().add(ClassConstants.OBJECT.getName());
- }
- }
- } else {
- returnQuery.getReturnTypes().add(query.getReferenceClassName() == null ? "" : query.getReferenceClassName());
- }
- return returnQuery;
- }
-
- protected static Map<String, Object> getHintMap(UriInfo info){
- Map<String, Object> hints = new HashMap<String, Object>();
- for(String key : info.getQueryParameters().keySet()) {
- hints.put(key, info.getQueryParameters().getFirst(key));
- }
- return hints;
- }
-
- /**
- * This method has been temporarily added to allow processing of either query or matrix parameters
- * When the final protocol is worked out, it should be removed or altered.
- *
- * Here we check for query parameters and if they don't exist, we get the matrix parameters.
- * @param info
- * @return
- */
- protected static Map<String, String> getParameterMap(UriInfo info, String segment){
- Map<String, String> parameters = new HashMap<String, String>();
- for (PathSegment pathSegment: info.getPathSegments()){
- if (pathSegment.getPath() != null && pathSegment.getPath().equals(segment)){
- for(Entry<String, List<String>> entry : pathSegment.getMatrixParameters().entrySet()) {
- parameters.put(entry.getKey(), entry.getValue().get(0));
- }
- return parameters;
- }
- }
- return parameters;
- }
-
- protected String getSingleHeader(String parameterName, HttpHeaders hh){
- List<String> params = hh.getRequestHeader(parameterName);
- if (params == null || params.isEmpty()) {
- return null;
- }
- if (params.size() != 1) {
- throw new WebApplicationException(Status.BAD_REQUEST);
- }
- return params.get(0);
- }
-
-
- protected String marshallMetadata(Object metadata, String mediaType) throws JAXBException {
- Class<?>[] jaxbClasses = new Class[]{Link.class, Attribute.class, Descriptor.class, LinkTemplate.class, PersistenceUnit.class, Query.class};
- JAXBContext context = (JAXBContext)JAXBContextFactory.createContext(jaxbClasses, null);
- Marshaller marshaller = context.createMarshaller();
- marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, Boolean.FALSE);
- marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, mediaType);
- StringWriter writer = new StringWriter();
- marshaller.marshal(metadata, writer);
- return writer.toString();
- }
-
- protected SessionBeanCall unmarshallSessionBeanCall(InputStream data) throws JAXBException {
- Class<?>[] jaxbClasses = new Class[]{SessionBeanCall.class};
- JAXBContext context = (JAXBContext)JAXBContextFactory.createContext(jaxbClasses, null);
- Unmarshaller unmarshaller = context.createUnmarshaller();
- unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, Boolean.FALSE);
- unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
- StreamSource ss = new StreamSource(data);
- return unmarshaller.unmarshal(ss, SessionBeanCall.class).getValue();
- }
-}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/ClassNotFoundExceptionMapper.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/ClassNotFoundExceptionMapper.java
index 65bb286..64ef795 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/ClassNotFoundExceptionMapper.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/ClassNotFoundExceptionMapper.java
@@ -13,4 +13,10 @@ public class ClassNotFoundExceptionMapper implements ExceptionMapper<ClassNotFou
JPARSLogger.exception("jpars_caught_exception", new Object[]{}, exception);
return Response.status(Status.BAD_REQUEST).build();
}
+ /*
+ public Response toResponse(ClassNotFoundException exception, MediaType mediaType){
+ JPARSLogger.exception("jpars_caught_exception", new Object[]{}, exception);
+ return Response.status(Response.Status.BAD_REQUEST).
+ entity(new ErrorResponse(1234, exception.getMessage())).type(mediaType).build();
+ }*/
}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/ConversionExceptionMapper.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/ConversionExceptionMapper.java
new file mode 100644
index 0000000..27c6597
--- /dev/null
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/ConversionExceptionMapper.java
@@ -0,0 +1,22 @@
+package org.eclipse.persistence.jpa.rs.exceptions;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+
+import org.eclipse.persistence.exceptions.ConversionException;
+import org.eclipse.persistence.jpa.rs.util.JPARSLogger;
+
+/**
+ * @author gonural
+ *
+ */
+@Provider
+public class ConversionExceptionMapper implements ExceptionMapper<ConversionException> {
+
+ public Response toResponse(ConversionException exception) {
+ JPARSLogger.exception("jpars_caught_exception", new Object[] {}, exception);
+ return Response.status(Status.BAD_REQUEST).build();
+ }
+}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/EntityNotFoundExceptionMapper.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/EntityNotFoundExceptionMapper.java
new file mode 100644
index 0000000..cd0c05c
--- /dev/null
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/exceptions/EntityNotFoundExceptionMapper.java
@@ -0,0 +1,25 @@
+/**
+ *
+ */
+package org.eclipse.persistence.jpa.rs.exceptions;
+
+import javax.persistence.EntityNotFoundException;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+
+import org.eclipse.persistence.jpa.rs.util.JPARSLogger;
+
+/**
+ * @author gonural
+ *
+ */
+@Provider
+public class EntityNotFoundExceptionMapper implements ExceptionMapper<EntityNotFoundException> {
+
+ public Response toResponse(EntityNotFoundException exception) {
+ JPARSLogger.exception("jpars_caught_exception", new Object[] {}, exception);
+ return Response.status(Status.NOT_FOUND).build();
+ }
+}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/logging/i18n/LoggingLocalizationResource.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/logging/i18n/LoggingLocalizationResource.java
index 2999196..55553af 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/logging/i18n/LoggingLocalizationResource.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/logging/i18n/LoggingLocalizationResource.java
@@ -27,15 +27,15 @@ public class LoggingLocalizationResource extends ListResourceBundle {
{ "exception_marshalling_entity_metadata", "An exception was caught while marshalling the metadata for entity [{0}] in persistence unit [{1}]: [{2}]"},
{ "exception_creating_persistence_context", "An Exception was thrown while creating a JPA persistence context for persistence unit: [{0}]: [{1}]"},
{ "exception_while_updating_attribute", "An Exception was thrown while updating an entity of type [{0}] on persistence unit [{1}]: [{2}]"},
- { "exception_while_ummarhalling_entity", "An Exception was thrown while unmarshalling an entity of type [{0}] in persitence unit [{1}]: [{2}]"},
+ { "exception_while_unmarhalling_entity", "An Exception was thrown while unmarshalling an entity of type [{0}] in persitence unit [{1}]: [{2}]" },
{ "exception_creating_jaxb_context", "An Exception was thrown while creating a JAXBContext for persistence unit [{0}]: [{1}]"},
- { "exception_thrown_while_creating_dynamic_entity", "An Exception was thrown creating a dyamic entity of type [{0}]: [{1}]"},
+ { "exception_thrown_while_creating_dynamic_entity", "An Exception was thrown creating a dynamic entity of type [{0}]: [{1}]"},
{ "jpars_could_not_find_entity_type", "Entity type [{0}] could not be found in persistence unit: [{1}]."},
{ "jpars_could_not_entity_for_key", "Entity of type [{0}] and id [{1}] could not be found in persistence unit: [{2}]."},
{ "jpars_could_not_entity_for_attribute", "Attribute [{0}] for entity of type [{1}] and id [{2}] could not be found in persistence unit: [{3}]."},
{ "jpars_could_find_appropriate_mapping_for_update", "Attribute [{0}] for entity of type [{1}] in persistence unit: [{2}] is not the appropriate type for an update or delete."},
{ "jpars_could_not_update_attribute", "Attribute [{0}] for entity of type [{1}] with key [{2}] in persistence unit: [{3}] could not be updated or deleted."},
- { "jpars_put_not_itempotent", "An Entity of type [{0}] in persistence unit [{1}] is being created with a PUT, but the Entity is not itempotent due to either sequence generation or cascading."},
+ { "jpars_put_not_idempotent", "An Entity of type [{0}] in persistence unit [{1}] is being created with a PUT, but the Entity is not idempotent due to either sequence generation or cascading."},
{ "jpars_could_not_marshal_serializing", "JPARS is serializing an object because it was unable to marshal it."},
{ "jaxb_exception_while_marshalling", "JPARS got a JAXBException while marshalling."},
{ "jpars_could_not_find_descriptor", "JPARS could not find the descriptor for [{0}] while subscribing for event notification."},
@@ -45,9 +45,10 @@ public class LoggingLocalizationResource extends ListResourceBundle {
{ "jersey.container.cant.load", "Unable to instantiate Jersey ServletContainer."},
{ "jersey.not.available", "No Jersey runtime found on the application classpath"},
{ "jpars_could_marshal_requested_result_to_requested_type", "JPA RS could not marshall object [{0}] to the requested type."},
- { "jpars_requested_type", "You are requesting types [{0}] from JPA RS."}
+ { "jpars_requested_type", "You are requesting types [{0}] from JPA RS."},
+ { "object_referred_by_link_does_not_exist", "Entity referred by link does not exist, entity type:[{0}], id:[{1}]."}
};
-
+
@Override
protected Object[][] getContents() {
// TODO Auto-generated method stub
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/PreLoginMappingAdapter.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/PreLoginMappingAdapter.java
index 9407c91..c305ea3 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/PreLoginMappingAdapter.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/PreLoginMappingAdapter.java
@@ -25,6 +25,7 @@ import org.eclipse.persistence.internal.jpa.weaving.RestAdapterClassWriter;
import org.eclipse.persistence.internal.queries.CollectionContainerPolicy;
import org.eclipse.persistence.internal.sessions.AbstractSession;
import org.eclipse.persistence.internal.weaving.PersistenceWeavedRest;
+import org.eclipse.persistence.jpa.rs.exceptions.JPARSException;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.mappings.ForeignReferenceMapping;
import org.eclipse.persistence.oxm.XMLField;
@@ -225,7 +226,7 @@ public class PreLoginMappingAdapter extends SessionEventListener {
jaxbDescriptor.addMapping(xmlChoiceMapping);
}
} catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
+ throw new JPARSException(e.toString());
}
}
}
diff --git a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/ReferenceAdapter.java b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/ReferenceAdapter.java
index f54ab8b..f78e657 100644
--- a/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/ReferenceAdapter.java
+++ b/dbws/org.eclipse.persistence.dbws/src/org/eclipse/persistence/jpa/rs/util/ReferenceAdapter.java
@@ -20,6 +20,8 @@ import org.eclipse.persistence.internal.jpa.rs.metadata.model.Link;
import org.eclipse.persistence.internal.weaving.PersistenceWeavedRest;
import org.eclipse.persistence.jpa.JpaHelper;
import org.eclipse.persistence.jpa.rs.PersistenceContext;
+import org.eclipse.persistence.jpa.rs.exceptions.JPARSException;
+import org.eclipse.persistence.jpa.rs.logging.LoggingLocalization;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.oxm.mappings.XMLInverseReferenceMapping;
import org.eclipse.persistence.queries.FetchGroup;
@@ -28,7 +30,7 @@ import org.eclipse.persistence.queries.FetchGroupTracker;
public class ReferenceAdapter<T extends PersistenceWeavedRest> extends XmlAdapter<Object, Object> {
private String baseURI = null;
private PersistenceContext context = null;
-
+
/**
* Instantiates a new reference adapter.
*/
@@ -61,7 +63,7 @@ public class ReferenceAdapter<T extends PersistenceWeavedRest> extends XmlAdapte
if (o == null) {
return null;
}
-
+
ClassDescriptor descriptor = context.getJAXBDescriptorForClass(o.getClass());
T t = (T) descriptor.getObjectBuilder().buildNewInstance();
Link link = new Link();
@@ -132,7 +134,6 @@ public class ReferenceAdapter<T extends PersistenceWeavedRest> extends XmlAdapte
}
// It is an error if the object referred by a link in unmarshal doesn't
// exist, so throw exception
- throw new RuntimeException("Entity " + entityType + " with id " + id
- + " does not exist.");
+ throw new JPARSException(LoggingLocalization.buildMessage("object_referred_by_link_does_not_exist", new Object[]{entityType, id}));
}
} \ No newline at end of file
diff --git a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/AllJavaSETests.java b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/AllJavaSETests.java
index 087c19b..bfa73e7 100644
--- a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/AllJavaSETests.java
+++ b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/AllJavaSETests.java
@@ -13,14 +13,14 @@
package org.eclipse.persistence.jpars.test;
import org.eclipse.persistence.jpars.test.crud.StaticCrudTests;
-import org.eclipse.persistence.jpars.test.server.UnmarshalTest;
+import org.eclipse.persistence.jpars.test.service.MarshalUnmarshalTest;
import org.eclipse.persistence.jpars.test.service.TestService;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
-@SuiteClasses({TestService.class, StaticCrudTests.class, UnmarshalTest.class})
+@SuiteClasses({ TestService.class, StaticCrudTests.class, MarshalUnmarshalTest.class })
public class AllJavaSETests {
}
diff --git a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/server/ServerCrudTest.java b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/server/ServerCrudTest.java
index cf00d51..bc88423 100644
--- a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/server/ServerCrudTest.java
+++ b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/server/ServerCrudTest.java
@@ -25,6 +25,7 @@ import org.eclipse.persistence.config.QueryHints;
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.StaticAddress;
import org.eclipse.persistence.jpars.test.model.StaticAuction;
import org.eclipse.persistence.jpars.test.model.StaticBid;
import org.eclipse.persistence.jpars.test.model.StaticUser;
@@ -41,14 +42,14 @@ import com.sun.jersey.api.client.ClientResponse.Status;
import com.sun.jersey.api.client.WebResource;
public class ServerCrudTest {
-
+
private static final String SERVER_URI_BASE = "server.uri.base";
private static final String DEFAULT_SERVER_URI_BASE = "http://localhost:8080";
private static final String APPLICATION_LOCATION = "/eclipselink.jpars.test/persistence/";
private static final String DEFAULT_PU = "auction-static";
private static Client client = null;
private static PersistenceContext context = null;
-
+
public static ByteArrayOutputStream sampleUserJSONForId(Integer userId, Integer addressId) throws IOException{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
StringBuffer json = new StringBuffer();
@@ -67,7 +68,7 @@ public class ServerCrudTest {
stream.write(json.toString().getBytes());
return stream;
}
-
+
@BeforeClass
public static void setup() throws URISyntaxException{
Map<String, Object> properties = new HashMap<String, Object>();
@@ -80,45 +81,45 @@ public class ServerCrudTest {
PersistenceFactoryBase factory = new PersistenceFactoryBase();
EntityManagerFactory emf = Persistence.createEntityManagerFactory(DEFAULT_PU, properties);
context = factory.bootstrapPersistenceContext("auction-static", emf, new URI(DEFAULT_SERVER_URI_BASE + "/JPA-RS/"), false);
-
+
StaticModelDatabasePopulator.populateDB(emf);
client = Client.create();
}
-
+
@AfterClass
public static void teardown() {
- StaticModelDatabasePopulator.cleanupDB(context.getEmf());
+ StaticModelDatabasePopulator.cleanupDB(context.getEmf());
}
-
+
@Test
public void testRead(){
StaticBid bid = restRead(StaticModelDatabasePopulator.BID1_ID, "StaticBid", StaticBid.class);
StaticBid bid2 = dbRead(StaticModelDatabasePopulator.BID1_ID, StaticBid.class);
assertTrue("Wrong bid in DB.", bid.getAmount() == bid2.getAmount());
}
-
+
@Test
public void testReadXML(){
StaticBid bid = restRead(StaticModelDatabasePopulator.BID1_ID, "StaticBid", StaticBid.class, DEFAULT_PU, null, MediaType.APPLICATION_XML_TYPE);
StaticBid bid2 = dbRead(StaticModelDatabasePopulator.BID1_ID, StaticBid.class);
assertTrue("Wrong big in DB.", bid.getAmount() == bid2.getAmount());
}
-
+
@Test(expected = RestCallFailedException.class)
public void testReadNonExistant(){
restRead(0, "StaticBid", StaticBid.class);
}
-
+
@Test(expected = RestCallFailedException.class)
public void testReadNonExistantType(){
restRead(1, "NonExistant", StaticBid.class);
}
-
+
@Test(expected = RestCallFailedException.class)
public void testReadNonExistantPU(){
restRead(1, "StaticBid", StaticBid.class, "non-existant", null, MediaType.APPLICATION_JSON_TYPE);
}
-
+
@Test
public void testUpdate(){
StaticBid bid = restRead(StaticModelDatabasePopulator.BID1_ID, "StaticBid", StaticBid.class);
@@ -131,7 +132,7 @@ public class ServerCrudTest {
bid.setAmount(110);
bid = restUpdate(bid, "StaticBid", StaticBid.class, true);
}
-
+
@Test
public void testCreateDelete(){
StaticUser user = new StaticUser();
@@ -145,7 +146,7 @@ public class ServerCrudTest {
dbUser = dbRead(user.getId(), StaticUser.class);
assertTrue("User was not deleted.", dbUser == null);
}
-
+
@Test
public void testCreateXML(){
StaticUser user = new StaticUser();
@@ -159,14 +160,14 @@ public class ServerCrudTest {
dbUser = dbRead(user.getId(), StaticUser.class);
assertTrue("User was not deleted.", dbUser == null);
}
-
+
@Test(expected = RestCallFailedException.class)
public void testCreateSequenced(){
StaticAuction auction = new StaticAuction();
auction.setName("Laptop");
auction = restCreate(auction, "StaticAuction", StaticAuction.class);
}
-
+
@Test(expected = RestCallFailedException.class)
public void testCreateNonExistant(){
StaticUser user = new StaticUser();
@@ -174,7 +175,7 @@ public class ServerCrudTest {
user.setId(102);
user = restCreate(user, "NonExistant", StaticUser.class);
}
-
+
@Test(expected = RestCallFailedException.class)
public void testCreateNonExistantPersistenceUnit(){
StaticUser user = new StaticUser();
@@ -182,14 +183,14 @@ public class ServerCrudTest {
user.setId(103);
user = restCreate(user, "StaticUser", StaticUser.class, "non-existant", null, MediaType.APPLICATION_XML_TYPE, MediaType.APPLICATION_XML_TYPE);
}
-
+
/**
* Removed. Requires a JSON parsing feature to detect incorrect data
* @throws IOException
@Test
public void testCreateWrongType(){
-
+
WebResource webResource = client.resource(SERVER_URI + DEFAULT_PU + "/entity/" + "StaticUser");
ByteArrayOutputStream os = new ByteArrayOutputStream();
try{
@@ -201,8 +202,8 @@ public class ServerCrudTest {
Status status = response.getClientResponseStatus();
assertTrue("Wrong exception thrown for non-existant object read.", status.equals(Status.NOT_FOUND));
}
- */
-
+ */
+
@Test
public void testCreateGarbage() throws IOException{
WebResource webResource = client.resource(getServerURI() + DEFAULT_PU + "/entity/" + "StaticUser");
@@ -213,7 +214,7 @@ public class ServerCrudTest {
Status status = response.getClientResponseStatus();
assertTrue("Wrong exception garbage write. " + status, status.equals(Status.BAD_REQUEST));
}
-
+
@Test
public void testUpdateXML(){
StaticBid bid = restRead(StaticModelDatabasePopulator.BID1_ID, "StaticBid", StaticBid.class, DEFAULT_PU, null, MediaType.APPLICATION_XML_TYPE);
@@ -225,7 +226,7 @@ public class ServerCrudTest {
bid.setAmount(110);
bid = restUpdate(bid, "StaticBid", StaticBid.class, true);
}
-
+
@Test
public void testPostNewEntity(){
StaticAuction auction = new StaticAuction();
@@ -237,21 +238,21 @@ public class ServerCrudTest {
assertTrue("Wrong user retrieved in db.", auction.getName().equals(dbAuction.getName()));
restDelete(auction.getId(), "StaticAuction", StaticAuction.class);
}
-
+
@Test(expected = RestCallFailedException.class)
public void testUpdateNonExistant() {
StaticUser user = new StaticUser();
user.setName("Joe");
user = restUpdate(user, "NonExistant", StaticUser.class, true);
}
-
+
@Test(expected = RestCallFailedException.class)
public void testUpdateNonExistantPersistenceUnit(){
StaticUser user = new StaticUser();
user.setName("Joe");
user = restUpdate(user, "StaticUser", StaticUser.class, "non-existant", null, MediaType.APPLICATION_XML_TYPE, MediaType.APPLICATION_XML_TYPE, true);
}
-
+
@Test
public void testUpdateGarbage() throws IOException{
WebResource webResource = client.resource(getServerURI() + DEFAULT_PU + "/entity/" + "StaticUser");
@@ -262,7 +263,7 @@ public class ServerCrudTest {
Status status = response.getClientResponseStatus();
assertTrue("Wrong exception garbage write. " + status, status.equals(Status.BAD_REQUEST));
}
-
+
@Test
public void testUpdateRelationship(){
StaticBid bid = dbRead(StaticModelDatabasePopulator.BID1_ID, StaticBid.class);
@@ -279,28 +280,28 @@ public class ServerCrudTest {
assertTrue("Wrong user.", bid.getUser().getName().equals(bid.getUser().getName()));
dbDelete(newUser);
}
-
+
@Test
public void testDeleteNonExistant(){
restDelete(1000, "StaticUser", StaticUser.class);
}
-
+
@Test(expected = RestCallFailedException.class)
public void testDeleteNonExistantType(){
restDelete(1000, "NonExistant", StaticUser.class);
}
-
+
@Test(expected = RestCallFailedException.class)
public void testDeleteNonExistantPersistenceUnit(){
restDelete(1000, "StaticUser", StaticUser.class, "non-existant", null);
}
-
+
@Test
public void testNamedQuery(){
List<StaticUser> users = (List<StaticUser>)restNamedQuery("User.all", "StaticUser", null, null);
assertTrue("Incorrect Number of users found.", users.size() == 3);
}
-
+
@Test
public void testNamedQueryParameter(){
Map<String, Object> parameters = new HashMap<String, Object>();
@@ -309,7 +310,7 @@ public class ServerCrudTest {
assertTrue("Incorrect Number of users found.", users.size() == 1);
assertTrue("Wrong user returned", users.get(0).getId() == StaticModelDatabasePopulator.USER1_ID);
}
-
+
@Test
public void testNamedQueryParameters(){
Map<String, Object> parameters = new HashMap<String, Object>();
@@ -318,21 +319,21 @@ public class ServerCrudTest {
List<StaticUser> users = (List<StaticUser>)restNamedQuery("User.byNameOrId", "StaticUser", parameters, null);
assertTrue("Incorrect Number of users found.", users.size() == 2);
}
-
+
@Test(expected = RestCallFailedException.class)
public void testNamedQueryWrongParameter(){
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("wrong", StaticModelDatabasePopulator.USER1_ID);
restNamedQuery("User.byId", "StaticUser", parameters, null);
}
-
+
@Test(expected = RestCallFailedException.class)
public void testNamedQueryWrongNumberOfParameters(){
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("id", StaticModelDatabasePopulator.USER1_ID);
restNamedQuery("User.byNameOrId", "StaticUser", parameters, null);
}
-
+
@Test
public void testNamedQueryNoResults(){
Map<String, Object> parameters = new HashMap<String, Object>();
@@ -340,21 +341,21 @@ public class ServerCrudTest {
List<StaticUser> users = (List<StaticUser>)restNamedQuery("User.byId", "StaticUser", parameters, null);
assertTrue("Incorrect Number of users found.", users.size() == 0);
}
-
+
@Test(expected = RestCallFailedException.class)
public void testNonExistantNamedQuery(){
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("id", StaticModelDatabasePopulator.USER1_ID);
restNamedQuery("User.nonExistant", "StaticUser", parameters, null);
}
-
+
@Test(expected = RestCallFailedException.class)
public void testNonExistantPersistenceUnitNamedQuery(){
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("id", StaticModelDatabasePopulator.USER1_ID);
restNamedQuery("User.all", "StatisUser", "nonExistant", parameters, null, MediaType.APPLICATION_JSON_TYPE);
}
-
+
@Test
public void testNamedQueryHint(){
// load the cache
@@ -380,7 +381,7 @@ public class ServerCrudTest {
hints.put(QueryHints.REFRESH, "true");
users = (List<StaticUser>)restNamedQuery("User.all", "StaticUser", null, hints);
}
-
+
@Test
public void testNamedQueryParameterHint(){
Map<String, Object> parameters = new HashMap<String, Object>();
@@ -400,13 +401,13 @@ public class ServerCrudTest {
user1 = dbRead(user1.getId(), StaticUser.class);
user1.setName(oldName);
dbUpdate(user1);
-
+
// refresh cache
hints = new HashMap<String, String>();
hints.put(QueryHints.REFRESH, "true");
users = (List<StaticUser>)restNamedQuery("User.all", "StaticUser", null, hints);
}
-
+
@Test
public void testNamedQuerySingleResult(){
Map<String, Object> parameters = new HashMap<String, Object>();
@@ -415,7 +416,7 @@ public class ServerCrudTest {
assertTrue("user was not returned", user != null);
assertTrue("incorrect user returned", user.getName().equals("user1"));
}
-
+
@Test(expected = RestCallFailedException.class)
public void testNamedQuerySingleResultNoResult(){
Map<String, Object> parameters = new HashMap<String, Object>();
@@ -423,7 +424,7 @@ public class ServerCrudTest {
StaticUser user = (StaticUser)restNamedSingleResultQuery("User.byId", "StaticUser", DEFAULT_PU, parameters, null, MediaType.APPLICATION_JSON_TYPE);
assertTrue("user shoudl not have been returned", user == null);
}
-
+
@Test
public void testUpdateQuery(){
Map<String, Object> parameters = new HashMap<String, Object>();
@@ -437,7 +438,7 @@ public class ServerCrudTest {
user1.setName(StaticModelDatabasePopulator.user1().getName());
dbUpdate(user1);
}
-
+
@Test(expected = RestCallFailedException.class)
public void testMultitenant(){
Account account = new Account();
@@ -447,12 +448,12 @@ public class ServerCrudTest {
account = restUpdate(account, "Account", Account.class, DEFAULT_PU, tenantId, MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE, true);
assertTrue("account not created.", account != null);
-
+
account = restRead(account.getId(), "Account", Account.class, DEFAULT_PU, tenantId, MediaType.APPLICATION_JSON_TYPE);
-
+
assertTrue("account not read.", account != null);
assertTrue("account not completely read.", account.getAccoutNumber().equals("AAA1"));
-
+
Map<String, String> tenantId2 = new HashMap<String, String>();
tenantId2.put("tenant.id", "AcctHolder2");
try{
@@ -461,10 +462,10 @@ public class ServerCrudTest {
restDelete(account.getId(), "Account", Account.class, DEFAULT_PU, tenantId);
}
}
-
+
//@Test
public void testCreateObjectGraphPut() throws RestCallFailedException,
- JAXBException {
+ JAXBException {
// Create a bid without auction and user first
StaticBid bid = new StaticBid();
bid.setId(777);
@@ -481,7 +482,7 @@ public class ServerCrudTest {
auction.setEndPrice(1000);
auction.setDescription("Lego auction");
auction = restCreate(auction, "StaticAuction", StaticAuction.class);
-
+
StaticUser user = null;
try{
user = restCreate(sampleUserJSONForId(466, 123456), "StaticUser", StaticUser.class, DEFAULT_PU, null, MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE);
@@ -513,7 +514,7 @@ public class ServerCrudTest {
assertTrue("Wrong user, could not update bid with a user.", userByLink.getName().equals(user.getName()));
assertTrue("Wrong auction, could not update bid with an auction.", auctionByLink.getName().equals(auction.getName()));
-
+
dbDelete(bid);
dbDelete(user);
dbDelete(auction);
@@ -521,7 +522,7 @@ public class ServerCrudTest {
//@Test
public void testCreateObjectGraphPost() throws RestCallFailedException,
- JAXBException {
+ JAXBException {
// Create a bid without auction and user first (no id)
StaticBid bid = new StaticBid();
bid.setAmount(810);
@@ -567,12 +568,35 @@ public class ServerCrudTest {
assertTrue("Wrong user, could not update bid with a user.", userByLink.getName().equals(user.getName()));
assertTrue("Wrong auction, could not update bid with an auction.", auctionByLink.getName().equals(auction.getName()));
-
+
dbDelete(bid);
dbDelete(user);
dbDelete(auction);
}
-
+
+ @Test
+ public void testReadCompositePK() {
+ StaticAddress address = new StaticAddress();
+ address.setId(10012090);
+ address.setType("home");
+ address.setCity("Ottawa");
+ dbCreate(address);
+
+ String id = "10012090+home";
+ StaticAddress addr = restRead(id, "StaticAddress", StaticAddress.class);
+
+ assertTrue("Wrong address", addr.getId() == 10012090);
+
+ dbDelete(address);
+ }
+
+ @Test(expected = RestCallFailedException.class)
+ public void testReadNonExistingCompositePK() {
+ String id = "home+10012090";
+ restRead(id, "StaticAddress", StaticAddress.class);
+ }
+
+
private static ByteArrayOutputStream getJSONMessage(String inputFile) throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
InputStream is = Thread.currentThread().getContextClassLoader()
@@ -590,19 +614,26 @@ public class ServerCrudTest {
}
}
+ private static void dbCreate(Object object) {
+ EntityManager em = context.getEmf().createEntityManager();
+ em.getTransaction().begin();
+ em.persist(object);
+ em.getTransaction().commit();
+ }
+
private static <T> T dbRead(Object id, Class<T> resultClass){
context.getEmf().getCache().evictAll();
EntityManager em = context.getEmf().createEntityManager();
return em.find(resultClass, id);
}
-
+
private static void dbUpdate(Object object){
EntityManager em = context.getEmf().createEntityManager();
em.getTransaction().begin();
em.merge(object);
em.getTransaction().commit();
}
-
+
private static void dbDelete(Object object){
EntityManager em = context.getEmf().createEntityManager();
em.getTransaction().begin();
@@ -610,11 +641,11 @@ public class ServerCrudTest {
em.remove(merged);
em.getTransaction().commit();
}
-
+
private static <T> T restCreate(Object object, String type, Class<T> resultClass) throws RestCallFailedException {
return restCreate(object, type, resultClass, DEFAULT_PU, null, MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE);
}
-
+
private static <T> T restCreate(Object object, String type, Class<T> resultClass, String persistenceUnit, Map<String, String> tenantId, MediaType inputMediaType, MediaType outputMediaType) throws RestCallFailedException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
@@ -625,7 +656,7 @@ public class ServerCrudTest {
return restCreate(os, type, resultClass, persistenceUnit, null, inputMediaType, outputMediaType);
}
-
+
private static <T> T restCreate(OutputStream os, String type, Class<T> resultClass, String persistenceUnit, Map<String, String> tenantId, MediaType inputMediaType, MediaType outputMediaType) throws RestCallFailedException {
StringBuffer uri = new StringBuffer();
uri.append(getServerURI() + persistenceUnit);
@@ -650,11 +681,11 @@ public class ServerCrudTest {
}
return resultObject;
}
-
+
private static <T> void restDelete(Object id, String type, Class<T> resultClass) throws RestCallFailedException {
restDelete(id, type, resultClass, DEFAULT_PU, null);
}
-
+
private static <T> void restDelete(Object id, String type, Class<T> resultClass, String persistenceUnit, Map<String, String> tenantId) throws RestCallFailedException {
StringBuffer uri = new StringBuffer();
uri.append(getServerURI() + persistenceUnit);
@@ -671,11 +702,11 @@ public class ServerCrudTest {
throw new RestCallFailedException(status);
}
}
-
+
private static Object restNamedQuery(String queryName, String returnType, Map<String, Object> parameters, Map<String, String> hints){
return restNamedQuery(queryName, returnType, DEFAULT_PU, parameters, hints, MediaType.APPLICATION_JSON_TYPE);
}
-
+
private static Object restNamedQuery(String queryName, String returnType, String persistenceUnit, Map<String, Object> parameters, Map<String, String> hints, MediaType outputMediaType){
StringBuffer resourceURL = new StringBuffer();
resourceURL.append(getServerURI() + persistenceUnit + "/query/" + queryName);
@@ -694,12 +725,12 @@ public class ServerCrudTest {
}
return null;
}
-
+
private static Object restNamedSingleResultQuery(String queryName, String returnType, String persistenceUnit, Map<String, Object> parameters, Map<String, String> hints, MediaType outputMediaType){
StringBuffer resourceURL = new StringBuffer();
resourceURL.append(getServerURI() + persistenceUnit + "/singleResultQuery/" + queryName);
appendParametersAndHints(resourceURL, parameters, hints);
-
+
WebResource webResource = client.resource(resourceURL.toString());
ClientResponse response = webResource.accept(outputMediaType).get(ClientResponse.class);
Status status = response.getClientResponseStatus();
@@ -714,12 +745,12 @@ public class ServerCrudTest {
}
return null;
}
-
+
private static Object restUpdateQuery(String queryName, String returnType, String persistenceUnit, Map<String, Object> parameters, Map<String, String> hints){
StringBuffer resourceURL = new StringBuffer();
resourceURL.append(getServerURI() + persistenceUnit + "/query/" + queryName);
appendParametersAndHints(resourceURL, parameters, hints);
-
+
WebResource webResource = client.resource(resourceURL.toString());
ClientResponse response = webResource.post(ClientResponse.class);
Status status = response.getClientResponseStatus();
@@ -728,7 +759,7 @@ public class ServerCrudTest {
}
return response.getEntity(String.class);
}
-
+
private static void appendParametersAndHints(StringBuffer resourceURL, Map<String, Object> parameters, Map<String, String> hints){
if (parameters != null && !parameters.isEmpty()){
for (String key: parameters.keySet()){
@@ -737,7 +768,7 @@ public class ServerCrudTest {
}
if (hints != null && !hints.isEmpty()){
boolean firstElement = true;
-
+
for (String key: hints.keySet()){
if (firstElement){
resourceURL.append("?");
@@ -748,11 +779,11 @@ public class ServerCrudTest {
}
}
}
-
+
private static <T> T restRead(Object id, String type, Class<T> resultClass) throws RestCallFailedException {
return restRead(id, type, resultClass, DEFAULT_PU, null, MediaType.APPLICATION_JSON_TYPE);
}
-
+
private static <T> T restRead(Object id, String type, Class<T> resultClass, String persistenceUnit, Map<String, String> tenantId, MediaType outputMediaType) throws RestCallFailedException {
StringBuffer uri = new StringBuffer();
uri.append(getServerURI() + persistenceUnit);
@@ -777,8 +808,8 @@ public class ServerCrudTest {
}
return resultObject;
}
-
-
+
+
private static <T> T restUpdate(Object object, String type, Class<T> resultClass, boolean sendLinks) throws RestCallFailedException {
return restUpdate(object, type, resultClass, DEFAULT_PU, null, MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE, sendLinks);
}
@@ -797,7 +828,7 @@ public class ServerCrudTest {
return restUpdate(os, type, resultClass, persistenceUnit, tenantId, inputMediaType, outputMediaType, sendLinks);
}
-
+
private static <T> T restUpdate(OutputStream os, String type, Class<T> resultClass, String persistenceUnit, Map<String, String> tenantId, MediaType inputMediaType, MediaType outputMediaType, boolean sendLinks) throws RestCallFailedException {
StringBuffer uri = new StringBuffer();
uri.append(getServerURI() + persistenceUnit);
@@ -814,7 +845,7 @@ public class ServerCrudTest {
throw new RestCallFailedException(status);
}
String result = response.getEntity(String.class);
-
+
T resultObject = null;
try {
resultObject = (T)context.unmarshalEntity(type, outputMediaType, new ByteArrayInputStream(result.getBytes()));
@@ -823,13 +854,13 @@ public class ServerCrudTest {
}
return resultObject;
}
-
+
private static <T> T restUpdateRelationship(String objectId, String type, String relationshipName, Object newValue, Class<T> resultClass, String persistenceUnit, MediaType inputMediaType, MediaType outputMediaType) throws RestCallFailedException {
WebResource webResource = client.resource(getServerURI() + persistenceUnit + "/entity/" + type + "/" + objectId + "/" + relationshipName);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try{
context.marshallEntity(newValue, inputMediaType, os);
-
+
} catch (JAXBException e){
fail("Exception thrown unmarshalling: " + e);
}
@@ -839,7 +870,7 @@ public class ServerCrudTest {
throw new RestCallFailedException(status);
}
String result = response.getEntity(String.class);
-
+
T resultObject = null;
try {
resultObject = (T)context.unmarshalEntity(type, outputMediaType, new ByteArrayInputStream(result.getBytes()));
@@ -848,7 +879,7 @@ public class ServerCrudTest {
}
return resultObject;
}
-
+
private static <T> T restReadByHref(String href, String type, MediaType outputMediaType) throws RestCallFailedException, JAXBException {
WebResource webResource = client.resource(href);
ClientResponse response = webResource.accept(outputMediaType).get(
@@ -866,7 +897,7 @@ public class ServerCrudTest {
String type, String relationshipName, Object newValue,
String persistenceUnit, MediaType inputMediaType,
MediaType outputMediaType, String partner, boolean sendLinks)
- throws RestCallFailedException, JAXBException {
+ throws RestCallFailedException, JAXBException {
String url = getServerURI() + persistenceUnit + "/entity/" + type + "/"
+ objectId + "/" + relationshipName;
diff --git a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/server/UnmarshalTest.java b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/service/MarshalUnmarshalTest.java
index 1f7d4bf..93867fc 100644
--- a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/server/UnmarshalTest.java
+++ b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/service/MarshalUnmarshalTest.java
@@ -1,4 +1,4 @@
-package org.eclipse.persistence.jpars.test.server;
+package org.eclipse.persistence.jpars.test.service;
import static org.junit.Assert.assertTrue;
@@ -28,11 +28,12 @@ import org.eclipse.persistence.jpars.test.model.StaticAddress;
import org.eclipse.persistence.jpars.test.model.StaticAuction;
import org.eclipse.persistence.jpars.test.model.StaticBid;
import org.eclipse.persistence.jpars.test.model.StaticUser;
+import org.eclipse.persistence.jpars.test.server.RestCallFailedException;
import org.eclipse.persistence.jpars.test.util.ExamplePropertiesLoader;
import org.junit.BeforeClass;
import org.junit.Test;
-public class UnmarshalTest {
+public class MarshalUnmarshalTest {
private static final String DEFAULT_SERVER_URI_BASE = "http://localhost:8080";
private static final String DEFAULT_PU = "auction-static";
@@ -150,7 +151,7 @@ public class UnmarshalTest {
*/
@Test
public void testMarshal() throws RestCallFailedException,
- UnsupportedEncodingException, JAXBException {
+ UnsupportedEncodingException, JAXBException {
StaticBid bid = new StaticBid();
bid.setId(20);
bid.setAmount(100.0);
@@ -191,9 +192,9 @@ public class UnmarshalTest {
bid.setUser(user);
em.persist(bid);
em.getTransaction().commit();
-
+
marshal(bid);
-
+
String xmlMessage = getXMLMessage("bid-UserByRef.xml");
StaticBid bidUnmarshalled = unmarshal(xmlMessage,
StaticBid.class.getSimpleName(), MediaType.APPLICATION_XML_TYPE);
@@ -204,8 +205,8 @@ public class UnmarshalTest {
dbDelete(bid);
}
-
-
+
+
@SuppressWarnings("unchecked")
private static <T> T unmarshal(String msg, String type)
throws JAXBException {
@@ -224,7 +225,7 @@ public class UnmarshalTest {
new ByteArrayInputStream(msg.getBytes()));
return resultObject;
}
-
+
private static <T> String marshal(Object object)
throws RestCallFailedException, JAXBException,
UnsupportedEncodingException {
@@ -246,7 +247,7 @@ public class UnmarshalTest {
.getResourceAsStream(XML_REST_MESSAGE_FOLDER + inputFile);
return convertStreamToString(is);
}
-
+
private static String convertStreamToString(InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
diff --git a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/service/TestService.java b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/service/TestService.java
index a10cfc6..5ad6a0f 100644
--- a/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/service/TestService.java
+++ b/jpa/eclipselink.jpars.test/src/org/eclipse/persistence/jpars/test/service/TestService.java
@@ -40,9 +40,11 @@ import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.eclipse.persistence.descriptors.FetchGroupManager;
import org.eclipse.persistence.dynamic.DynamicClassLoader;
import org.eclipse.persistence.dynamic.DynamicEntity;
+import org.eclipse.persistence.jpa.rs.EntityResource;
import org.eclipse.persistence.jpa.rs.PersistenceContext;
import org.eclipse.persistence.jpa.rs.PersistenceFactoryBase;
-import org.eclipse.persistence.jpa.rs.service.Service;
+import org.eclipse.persistence.jpa.rs.PersistenceResource;
+import org.eclipse.persistence.jpa.rs.PersistenceUnitResource;
import org.eclipse.persistence.jpa.rs.util.LinkAdapter;
import org.eclipse.persistence.jpa.rs.util.StreamingOutputMarshaller;
import org.eclipse.persistence.jpars.test.model.StaticAuction;
@@ -59,7 +61,7 @@ import org.junit.BeforeClass;
import org.junit.Test;
/**
- * Tests for the JPA RS service class
+ * Tests for the JPA RS resource classes
* @author tware
*
*/
@@ -67,7 +69,7 @@ public class TestService {
private static PersistenceFactoryBase factory;
public static URI BASE_URI;
-
+
public static PersistenceContext getAuctionPersistenceContext(Map<String, Object> additionalProperties){
Map<String, Object> properties = new HashMap<String, Object>();
if (additionalProperties != null){
@@ -77,7 +79,7 @@ public class TestService {
PersistenceContext context = factory.get("auction", BASE_URI, properties);
return context;
}
-
+
public static PersistenceContext getPhoneBookPersistenceContext(Map<String, Object> additionalProperties){
Map<String, Object> properties = new HashMap<String, Object>();
if (additionalProperties != null){
@@ -87,7 +89,7 @@ public class TestService {
PersistenceContext context = factory.get("phonebook", BASE_URI, properties);
return context;
}
-
+
@BeforeClass
public static void setup(){
Map<String, Object> properties = new HashMap<String, Object>();
@@ -96,7 +98,7 @@ public class TestService {
try{
BASE_URI = new URI("http://localhost:8080/JPA-RS/");
factory = new PersistenceFactoryBase();
-
+
properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, null);
properties.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.DROP_AND_CREATE);
properties.put(PersistenceUnitProperties.DEPLOY_ON_STARTUP, "true");
@@ -105,7 +107,7 @@ public class TestService {
getAuctionPersistenceContext(properties);
getPhoneBookPersistenceContext(properties);
-
+
EntityManagerFactory emf = Persistence.createEntityManagerFactory("auction-static-local", properties);
factory.bootstrapPersistenceContext("auction-static-local", emf, BASE_URI, false);
@@ -117,9 +119,9 @@ public class TestService {
}
@AfterClass
public static void teardown(){
- // clearData();
+ // clearData();
}
-
+
protected static void clearData(){
EntityManager em = getAuctionPersistenceContext(null).getEmf().createEntityManager();
em.getTransaction().begin();
@@ -133,30 +135,30 @@ public class TestService {
em.createQuery("delete from Person p").executeUpdate();
em.getTransaction().commit();
}
-
+
@Test
public void testUpdateUserList(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ EntityResource resource = new EntityResource();
+ resource.setPersistenceFactory(factory);
PersistenceContext context = TestService.getAuctionPersistenceContext(null);
-
+
DynamicEntity entity = (DynamicEntity)context.newEntity("User");
entity.set("name", "Jim");
context.create(null, entity);
-
+
entity.set("name", "James");
-
+
DynamicEntity entity2 = (DynamicEntity)context.newEntity("User");
entity2.set("name", "Jill");
context.create(null, entity2);
-
+
entity2.set("name", "Gillian");
-
+
List<DynamicEntity> entities = new ArrayList<DynamicEntity>();
entities.add(entity);
entities.add(entity2);
- StreamingOutput output = (StreamingOutput)service.update("auction", "User", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo(), TestService.serializeListToStream(entities, context, MediaType.APPLICATION_JSON_TYPE)).getEntity();
+ StreamingOutput output = (StreamingOutput) resource.update("auction", "User", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo(), TestService.serializeListToStream(entities, context, MediaType.APPLICATION_JSON_TYPE)).getEntity();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try{
@@ -181,36 +183,36 @@ public class TestService {
values.remove(value.get("name"));
}
assertTrue("Incorrent set of names.", values.isEmpty());
-
+
clearData();
}
-
+
@Test
public void testUpdatePhoneNumberList(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ EntityResource resource = new EntityResource();
+ resource.setPersistenceFactory(factory);
PersistenceContext context = getPhoneBookPersistenceContext(null);
-
+
DynamicEntity entity = (DynamicEntity)context.newEntity("Person");
entity.set("firstName", "Jim");
entity.set("lastName", "Jones");
entity.set("phoneNumber", "1234567");
context.create(null, entity);
-
+
entity.set("firstName", "James");
-
+
DynamicEntity entity2 = (DynamicEntity)context.newEntity("Person");
entity2.set("firstName", "Jill");
entity2.set("lastName", "Jones");
context.create(null, entity2);
-
+
entity2.set("firstName", "Gillian");
-
+
List<DynamicEntity> entities = new ArrayList<DynamicEntity>();
entities.add(entity);
entities.add(entity2);
- StreamingOutput output = (StreamingOutput)service.update("phonebook", "Person", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo(), serializeListToStream(entities, context, MediaType.APPLICATION_JSON_TYPE)).getEntity();
+ StreamingOutput output = (StreamingOutput) resource.update("phonebook", "Person", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo(), serializeListToStream(entities, context, MediaType.APPLICATION_JSON_TYPE)).getEntity();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try{
@@ -236,29 +238,29 @@ public class TestService {
values.remove(value.get("firstName"));
}
assertTrue("Incorrent set of names.", values.isEmpty());
-
+
clearData();
}
-
+
@Test
public void testMarshallBid(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ PersistenceResource resource = new PersistenceResource();
+ resource.setPersistenceFactory(factory);
PersistenceContext context = getAuctionPersistenceContext(null);
-
+
DynamicEntity entity1 = (DynamicEntity)context.newEntity("Auction");
entity1.set("name", "Computer");
-
+
DynamicEntity entity2 = (DynamicEntity)context.newEntity("User");
entity2.set("name", "Bob");
context.create(null, entity2);
-
+
DynamicEntity entity3 = (DynamicEntity)context.newEntity("Bid");
entity3.set("amount", 200d);
entity3.set("user", entity2);
entity3.set("auction", entity1);
context.create(null, entity3);
-
+
InputStream stream = serializeToStream(entity3, context, MediaType.APPLICATION_JSON_TYPE);
try{
@@ -271,30 +273,30 @@ public class TestService {
assertNotNull("Name of auction is null.", entity1.get("name"));
assertTrue("Name of auction is incorrect.", entity1.get("name").equals("Computer"));
-
+
}
-
+
@Test
public void testNamedQuery(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ PersistenceUnitResource resource = new PersistenceUnitResource();
+ resource.setPersistenceFactory(factory);
PersistenceContext context = getAuctionPersistenceContext(null);
-
+
DynamicEntity entity1 = (DynamicEntity)context.newEntity("Auction");
entity1.set("name", "Computer");
context.create(null, entity1);
-
+
DynamicEntity entity2 = (DynamicEntity)context.newEntity("Auction");
entity2.set("name", "Word Processor");
context.create(null, entity2);
-
+
TestHttpHeaders headers = new TestHttpHeaders();
headers.getAcceptableMediaTypes().add(MediaType.APPLICATION_JSON_TYPE);
List<String> mediaTypes = new ArrayList<String>();
mediaTypes.add(MediaType.APPLICATION_JSON);
TestURIInfo ui = new TestURIInfo();
- StreamingOutput output = (StreamingOutput)service.namedQuery("auction", "Auction.all", headers, ui).getEntity();
-
+ StreamingOutput output = (StreamingOutput) resource.namedQuery("auction", "Auction.all", headers, ui).getEntity();
+
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try{
output.write(outputStream);
@@ -302,75 +304,75 @@ public class TestService {
fail(ex.toString());
}
String resultString = outputStream.toString();
-
+
assertTrue("Computer was not in results.", resultString.contains("\"name\":\"Computer\""));
assertTrue("Word Processor was not in restuls.", resultString.contains("\"name\":\"Word Processor\""));
clearData();
}
-
+
@Test
public void testNamedQuerySingleResult(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ PersistenceUnitResource resource = new PersistenceUnitResource();
+ resource.setPersistenceFactory(factory);
PersistenceContext context = getAuctionPersistenceContext(null);
-
+
DynamicEntity entity1 = (DynamicEntity)context.newEntity("Auction");
entity1.set("name", "Computer");
context.create(null, entity1);
-
+
DynamicEntity entity2 = (DynamicEntity)context.newEntity("Auction");
entity2.set("name", "Word Processor");
context.create(null, entity2);
-
+
TestHttpHeaders headers = new TestHttpHeaders();
headers.getAcceptableMediaTypes().add(MediaType.APPLICATION_JSON_TYPE);
List<String> mediaTypes = new ArrayList<String>();
mediaTypes.add(MediaType.APPLICATION_JSON);
TestURIInfo ui = new TestURIInfo();
ui.addMatrixParameter("Auction.forName", "name", "Computer");
- StreamingOutput output = (StreamingOutput)service.namedQuerySingleResult("auction", "Auction.forName", headers, ui).getEntity();
-
+ StreamingOutput output = (StreamingOutput) resource.namedQuerySingleResult("auction", "Auction.forName", headers, ui).getEntity();
+
String resultString = stringifyResults(output);
-
+
assertTrue("Computer was not in results.", resultString.contains("\"name\":\"Computer\""));
assertFalse("Word Processor was in results.", resultString.contains("\"name\":\"Word Processor\""));
-
+
clearData();
}
-
+
@Test
public void testUpdate(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ EntityResource resource = new EntityResource();
+ resource.setPersistenceFactory(factory);
PersistenceContext context = getAuctionPersistenceContext(null);
-
+
DynamicEntity entity1 = (DynamicEntity)context.newEntity("Auction");
entity1.set("name", "Computer");
context.create(null, entity1);
entity1.set("name", "Laptop");
entity1.set("description", "Speedy");
- StreamingOutput output = (StreamingOutput)service.update("auction", "Auction", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo(), serializeToStream(entity1, context, MediaType.APPLICATION_JSON_TYPE)).getEntity();
+ StreamingOutput output = (StreamingOutput) resource.update("auction", "Auction", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo(), serializeToStream(entity1, context, MediaType.APPLICATION_JSON_TYPE)).getEntity();
String resultString = stringifyResults(output);
-
+
assertTrue("Laptop was not in results.", resultString.contains("\"name\":\"Laptop\""));
assertTrue("Laptop was not in results.", resultString.contains("\"description\":\"Speedy\""));
}
-
+
@Test
public void testUpdateRelationship(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ EntityResource resource = new EntityResource();
+ resource.setPersistenceFactory(factory);
PersistenceContext context = getAuctionPersistenceContext(null);
-
+
DynamicEntity entity1 = (DynamicEntity)context.newEntity("Auction");
entity1.set("name", "Computer");
-
+
DynamicEntity entity2 = (DynamicEntity)context.newEntity("User");
entity2.set("name", "Bob");
context.create(null, entity2);
-
+
DynamicEntity entity3 = (DynamicEntity)context.newEntity("Bid");
entity3.set("amount", 200d);
entity3.set("user", entity2);
@@ -382,84 +384,89 @@ public class TestService {
entity3.set("amount", 201d);
entity1 = entity3.get("auction");
entity1.set("name", "Laptop");
- StreamingOutput output = (StreamingOutput)service.update("auction", "Bid", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo(), serializeToStream(entity3, context, MediaType.APPLICATION_JSON_TYPE)).getEntity();
+ StreamingOutput output = (StreamingOutput) resource.update("auction", "Bid", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo(), serializeToStream(entity3, context, MediaType.APPLICATION_JSON_TYPE)).getEntity();
String resultString = stringifyResults(output);
-
+
assertTrue("amount was not in results.", resultString.replace(" ","").contains("\"amount\":201.0"));
assertTrue("link was not in results.", resultString.replace(" ","").contains("http://localhost:8080/JPA-RS/auction/entity/Bid/"));
assertTrue("rel was not in results.", resultString.replace(" ","").contains("\"rel\":\"user\""));
assertTrue("Laptop was not a link in results.", !resultString.replace(" ","").contains("\"name\":\"Laptop\""));
-
+
}
-
- @Test
+
+ @Test
public void testMetadataQuery(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ PersistenceResource resource = new PersistenceResource();
+ resource.setPersistenceFactory(factory);
StreamingOutput output = null;
try{
- output = (StreamingOutput)service.getContexts(generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo()).getEntity();
+ output = (StreamingOutput) resource.getContexts(generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo()).getEntity();
} catch (JAXBException e){
fail("Exception: " + e);
}
String result = stringifyResults(output);
assertTrue("auction was not in the results", result.contains("auction"));
assertTrue("phonebook was not in the results", result.contains("phonebook"));
-
- output = (StreamingOutput)service.getTypes("auction", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo()).getEntity();
- result = stringifyResults(output);
-
+ }
+
+ @Test
+ public void testTypes() {
+ PersistenceUnitResource resource = new PersistenceUnitResource();
+ resource.setPersistenceFactory(factory);
+ StreamingOutput output = null;
+ output = (StreamingOutput) resource.getTypes("auction", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo()).getEntity();
+ String result = stringifyResults(output);
+
assertTrue("Bid was not in the results", result.contains("Bid"));
assertTrue("Auction was not in the results", result.contains("Auction"));
assertTrue("User was not in the results", result.contains("User"));
-
}
-
+
@Test
public void testDelete(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ EntityResource resource = new EntityResource();
+ resource.setPersistenceFactory(factory);
PersistenceContext context = getAuctionPersistenceContext(null);
-
+
DynamicEntity entity1 = (DynamicEntity)context.newEntity("Auction");
entity1.set("name", "Computer1");
context.create(null, entity1);
TestURIInfo ui = new TestURIInfo();
- service.delete("auction", "Auction", entity1.get("id").toString(), generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), ui);
+ resource.delete("auction", "Auction", entity1.get("id").toString(), generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), ui);
entity1 = (DynamicEntity)context.find("Auction", entity1.get("id"));
-
+
assertTrue("Entity was not deleted.", entity1 == null);
}
-
+
@Test
public void testWriteQuery(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ PersistenceUnitResource resource = new PersistenceUnitResource();
+ resource.setPersistenceFactory(factory);
PersistenceContext context = getAuctionPersistenceContext(null);
-
+
DynamicEntity entity = (DynamicEntity)context.newEntity("User");
entity.set("name", "Bob");
context.create(null, entity);
-
+
TestURIInfo ui = new TestURIInfo();
ui.addMatrixParameter("User.updateName", "name", "Robert");
ui.addMatrixParameter("User.updateName", "id", entity.get("id").toString());
-
- service.namedQueryUpdate("auction", "User.updateName", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), ui);
+
+ resource.namedQueryUpdate("auction", "User.updateName", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), ui);
entity = (DynamicEntity)context.find("User", entity.get("id"));
-
+
assertTrue("Entity was not updated.", entity.get("name").equals("Robert"));
}
-
+
@Test
public void testDynamicCompositeKey(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ EntityResource resource = new EntityResource();
+ resource.setPersistenceFactory(factory);
PersistenceContext context = getAuctionPersistenceContext(null);
DynamicEntity user = (DynamicEntity)context.newEntity("User");
user.set("name", "Wes");
@@ -470,97 +477,97 @@ public class TestService {
address.set("type", "Home");
user.set("address", address);
context.create(null, user);
-
- Response output = service.find("auction", "Address", address.get("id") + "+" + address.get("type"), generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo());
+
+ Response output = resource.find("auction", "Address", address.get("id") + "+" + address.get("type"), generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo());
String result = stringifyResults((StreamingOutputMarshaller)output.getEntity());
assertTrue("Type was not in the result", result.contains("Home"));
assertTrue("Id was not in the result", result.contains(address.get("id").toString()));
}
-
+
@Test
public void testStaticCompositeKey(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ EntityResource resource = new EntityResource();
+ resource.setPersistenceFactory(factory);
- Response output = service.find("auction-static-local", "StaticAddress", StaticModelDatabasePopulator.ADDRESS1_ID + "+" + StaticModelDatabasePopulator.address1().getType(), generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo());
+ Response output = resource.find("auction-static-local", "StaticAddress", StaticModelDatabasePopulator.ADDRESS1_ID + "+" + StaticModelDatabasePopulator.address1().getType(), generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo());
String result = stringifyResults((StreamingOutputMarshaller)output.getEntity());
assertTrue("home was not in the result", result.contains("home"));
assertTrue("user was not in the result", result.contains("\"rel\":\"user\""));
}
-
+
@Test
public void testStaticRelationships(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
-
- Response output = service.find("auction-static-local", "StaticBid", String.valueOf(StaticModelDatabasePopulator.BID1_ID), generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo());
+ EntityResource resource = new EntityResource();
+ resource.setPersistenceFactory(factory);
+
+ Response output = resource.find("auction-static-local", "StaticBid", String.valueOf(StaticModelDatabasePopulator.BID1_ID), generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo());
String result = stringifyResults((StreamingOutputMarshaller)output.getEntity());
assertTrue("Auction was not in the result", result.contains("\"rel\":\"auction\""));
assertTrue("User link was not in the result", result.contains("\"rel\":\"user\""));
}
-
+
@Test
public void testUpdateStaticRelationship(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ EntityResource resource = new EntityResource();
+ resource.setPersistenceFactory(factory);
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, null);
PersistenceContext context = factory.get("auction-static-local", BASE_URI, properties);
-
+
StaticUser initialUser = (StaticUser)((StaticBid)context.find("StaticBid", StaticModelDatabasePopulator.BID1_ID)).getUser();
StaticUser user2 = (StaticUser)context.find("StaticUser", StaticModelDatabasePopulator.USER2_ID);
-
+
try{
- Response output = service.setOrAddAttribute("auction-static-local", "StaticBid", String.valueOf(StaticModelDatabasePopulator.BID1_ID), "user", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo(), serializeToStream(user2, context, MediaType.APPLICATION_JSON_TYPE));
-
+ Response output = resource.setOrAddAttribute("auction-static-local", "StaticBid", String.valueOf(StaticModelDatabasePopulator.BID1_ID), "user", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo(), serializeToStream(user2, context, MediaType.APPLICATION_JSON_TYPE));
+
String result = stringifyResults((StreamingOutputMarshaller)output.getEntity());
context.getJpaSession().getIdentityMapAccessor().initializeAllIdentityMaps();
-
+
StaticBid bid = (StaticBid)context.find("StaticBid", StaticModelDatabasePopulator.BID1_ID);
-
+
assertTrue(bid.getUser().equals(user2));
} finally {
-
+
context.updateOrAddAttribute(null, "StaticBid", StaticModelDatabasePopulator.BID1_ID, null, "user", initialUser, null);
}
}
-
+
@Test
public void testDeleteStaticRelationship(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ EntityResource resource = new EntityResource();
+ resource.setPersistenceFactory(factory);
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, null);
PersistenceContext context = factory.get("auction-static-local", BASE_URI, properties);
-
+
StaticBid bid = (StaticBid)context.find("StaticBid", StaticModelDatabasePopulator.BID1_ID);
StaticUser user = bid.getUser();
-
+
try{
- Response output = service.removeAttribute("auction-static-local", "StaticBid", String.valueOf(StaticModelDatabasePopulator.BID1_ID), "user", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo(), serializeToStream(user, context, MediaType.APPLICATION_JSON_TYPE));
-
+ Response output = resource.removeAttribute("auction-static-local", "StaticBid", String.valueOf(StaticModelDatabasePopulator.BID1_ID), "user", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo(), serializeToStream(user, context, MediaType.APPLICATION_JSON_TYPE));
+
String result = stringifyResults((StreamingOutputMarshaller)output.getEntity());
context.getJpaSession().getIdentityMapAccessor().initializeAllIdentityMaps();
-
+
bid = (StaticBid)context.find("StaticBid", StaticModelDatabasePopulator.BID1_ID);
-
+
assertTrue(bid.getUser() == null);
} finally {
context.updateOrAddAttribute(null, "StaticBid", StaticModelDatabasePopulator.BID1_ID, null, "user", user, null);
}
- }
-
+ }
+
@Test
public void testUpdateAndRemoveStaticCollectionRelationship(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ EntityResource resource = new EntityResource();
+ resource.setPersistenceFactory(factory);
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, null);
PersistenceContext context = factory.get("auction-static-local", BASE_URI, properties);
-
+
StaticAuction auction = (StaticAuction)context.find("StaticAuction", StaticModelDatabasePopulator.AUCTION1_ID);
StaticBid bid = new StaticBid();
bid.setAmount(100);
@@ -569,25 +576,25 @@ public class TestService {
TestURIInfo ui = new TestURIInfo();
ui.addMatrixParameter("bids", "partner", "auction");
- service.setOrAddAttribute("auction-static-local", "StaticAuction", String.valueOf(StaticModelDatabasePopulator.AUCTION1_ID), "bids", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), ui, serializeToStream(bid, context, MediaType.APPLICATION_JSON_TYPE));
+ resource.setOrAddAttribute("auction-static-local", "StaticAuction", String.valueOf(StaticModelDatabasePopulator.AUCTION1_ID), "bids", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), ui, serializeToStream(bid, context, MediaType.APPLICATION_JSON_TYPE));
context.getJpaSession().getIdentityMapAccessor().initializeAllIdentityMaps();
-
+
auction = (StaticAuction)context.find("StaticAuction", StaticModelDatabasePopulator.AUCTION1_ID);
-
+
boolean found = false;
for (StaticBid sbid: auction.getBids()){
if (sbid.getId() == bid.getId()){
found = true;
}
}
-
+
assertTrue("The new bid was not found", found);
-
+
context.getJpaSession().getIdentityMapAccessor().initializeAllIdentityMaps();
bid = (StaticBid)context.find("StaticBid", bid.getId());
- service.removeAttribute("auction-static-local", "StaticAuction", String.valueOf(StaticModelDatabasePopulator.AUCTION1_ID), "bids", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), ui, serializeToStream(bid, context, MediaType.APPLICATION_JSON_TYPE));
+ resource.removeAttribute("auction-static-local", "StaticAuction", String.valueOf(StaticModelDatabasePopulator.AUCTION1_ID), "bids", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), ui, serializeToStream(bid, context, MediaType.APPLICATION_JSON_TYPE));
context.getJpaSession().getIdentityMapAccessor().initializeAllIdentityMaps();
-
+
auction = (StaticAuction)context.find("StaticAuction", StaticModelDatabasePopulator.AUCTION1_ID);
found = false;
for (StaticBid sbid: auction.getBids()){
@@ -598,24 +605,24 @@ public class TestService {
assertFalse("The removed bid was found", found);
}
-
+
@Test
public void testStaticReportQuery(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ PersistenceUnitResource resource = new PersistenceUnitResource();
+ resource.setPersistenceFactory(factory);
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, null);
PersistenceContext context = factory.get("auction-static-local", BASE_URI, properties);
-
+
Long count = (Long)((List)context.query(null, "User.count", null)).get(0);
-
+
TestHttpHeaders headers = new TestHttpHeaders();
headers.getAcceptableMediaTypes().add(MediaType.APPLICATION_JSON_TYPE);
List<String> mediaTypes = new ArrayList<String>();
mediaTypes.add(MediaType.APPLICATION_JSON);
TestURIInfo ui = new TestURIInfo();
- StreamingOutput output = (StreamingOutput)service.namedQuery("auction-static-local", "User.count", headers, ui).getEntity();
-
+ StreamingOutput output = (StreamingOutput) resource.namedQuery("auction-static-local", "User.count", headers, ui).getEntity();
+
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try{
output.write(outputStream);
@@ -623,15 +630,15 @@ public class TestService {
fail(ex.toString());
}
String resultString = outputStream.toString();
-
+
assertTrue("Incorrect result", resultString.contains("[{\"value\":" + count.toString() + "}]"));
clearData();
}
-
+
@Test
public void testUnmarshallNonExistantLink(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ PersistenceResource resource = new PersistenceResource();
+ resource.setPersistenceFactory(factory);
PersistenceContext context = getAuctionPersistenceContext(null);
LinkAdapter adapter = new LinkAdapter("http://localhost:9090/JPA-RS/", context);
DynamicEntity entity1 = null;
@@ -650,55 +657,58 @@ public class TestService {
assertTrue("id for Address was missing", entity2.get("id").equals(1));
assertTrue("type for Address was missing", entity2.get("type").equals("Home"));
}
-
+
@Test
- public void testMetadata(){
- Service service = new Service();
- service.setPersistenceFactory(factory);
- Object result = null;
- try{
- result = service.getContexts(generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo());
- } catch (JAXBException e){
- fail("Exception: " + e);
+ public void testMetadata() {
+ PersistenceResource resource = new PersistenceResource();
+ resource.setPersistenceFactory(factory);
+ try {
+ resource.getContexts(generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo());
+ } catch (JAXBException e) {
+ fail(e.toString());
}
- result = service.getTypes("auction", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo());
+ }
- result = service.getDescriptorMetadata("auction", "Bid", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo());
-
- result = service.getQueriesMetadata("auction", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo());
+ @Test
+ public void testMetadataTypes() {
+ PersistenceUnitResource resource = new PersistenceUnitResource();
+ resource.setPersistenceFactory(factory);
+ resource.getTypes("auction", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo());
+ resource.getDescriptorMetadata("auction", "Bid", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo());
+ resource.getQueriesMetadata("auction", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), new TestURIInfo());
}
-
+
@Test
public void testMultitenant() throws JAXBException {
- Service service = new Service();
- service.setPersistenceFactory(factory);
+ EntityResource resource = new EntityResource();
+ resource.setPersistenceFactory(factory);
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(PersistenceUnitProperties.NON_JTA_DATASOURCE, null);
PersistenceContext context = factory.get("auction-static-local", BASE_URI, properties);
-
+
Account account = new Account();
account.setAccoutNumber("AAA111");
TestURIInfo ui = new TestURIInfo();
ui.addMatrixParameter("auction-static-local", "tenant.id", "AcctOwner1");
- StreamingOutput output = (StreamingOutput)service.update("auction-static-local", "Account", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), ui, serializeToStream(account, context, MediaType.APPLICATION_JSON_TYPE)).getEntity();
-
+ StreamingOutput output = (StreamingOutput) resource.update("auction-static-local", "Account", generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), ui, serializeToStream(account, context, MediaType.APPLICATION_JSON_TYPE)).getEntity();
+
String result = stringifyResults(output);
-
+
account = (Account)context.unmarshalEntity(Account.class, MediaType.APPLICATION_JSON_TYPE, new ByteArrayInputStream(result.getBytes()));
-
- output = (StreamingOutput)service.find("auction-static-local", "Account", String.valueOf(account.getId()), generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), ui).getEntity();
+
+ output = (StreamingOutput) resource.find("auction-static-local", "Account", String.valueOf(account.getId()), generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), ui).getEntity();
result = stringifyResults(output);
account = (Account)context.unmarshalEntity(Account.class, MediaType.APPLICATION_JSON_TYPE, new ByteArrayInputStream(result.getBytes()));
assertTrue("account is null", account != null);
TestURIInfo ui2 = new TestURIInfo();
ui2.addMatrixParameter("auction-static-local", "tenant.id", "AcctOwner2");
-
- output = (StreamingOutput)service.find("auction-static-local", "Account", String.valueOf(account.getId()), generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), ui2).getEntity();
+
+ output = (StreamingOutput) resource.find("auction-static-local", "Account", String.valueOf(account.getId()), generateHTTPHeader(MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON), ui2).getEntity();
assertTrue("output should be null", output == null);
}
-
+
public static String stringifyResults(StreamingOutput output){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try{
@@ -708,7 +718,7 @@ public class TestService {
}
return outputStream.toString();
}
-
+
public static InputStream serializeToStream(Object object, PersistenceContext context, MediaType mediaType){
ByteArrayOutputStream os = new ByteArrayOutputStream();
try{
@@ -720,7 +730,7 @@ public class TestService {
ByteArrayInputStream stream = new ByteArrayInputStream(os.toByteArray());
return stream;
}
-
+
public static InputStream serializeListToStream(List<DynamicEntity> object, PersistenceContext context, MediaType mediaType){
ByteArrayOutputStream os = new ByteArrayOutputStream();
try{
@@ -732,7 +742,7 @@ public class TestService {
ByteArrayInputStream stream = new ByteArrayInputStream(os.toByteArray());
return stream;
}
-
+
public static HttpHeaders generateHTTPHeader(MediaType acceptableMedia, String mediaTypeString){
TestHttpHeaders headers = new TestHttpHeaders();
headers.getAcceptableMediaTypes().add(acceptableMedia);
@@ -742,6 +752,4 @@ public class TestService {
headers.getRequestHeaders().put(HttpHeaders.CONTENT_TYPE, mediaTypes);
return headers;
}
-
-
}
diff --git a/jpa/org.eclipse.persistence.jpars/src/org/eclipse/persistence/jpa/rs/service/JPARSApplication.java b/jpa/org.eclipse.persistence.jpars/src/org/eclipse/persistence/jpa/rs/service/JPARSApplication.java
index 3b6c46e..5d07cad 100644
--- a/jpa/org.eclipse.persistence.jpars/src/org/eclipse/persistence/jpa/rs/service/JPARSApplication.java
+++ b/jpa/org.eclipse.persistence.jpars/src/org/eclipse/persistence/jpa/rs/service/JPARSApplication.java
@@ -20,7 +20,12 @@ import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
+import org.eclipse.persistence.jpa.rs.EntityResource;
+import org.eclipse.persistence.jpa.rs.PersistenceResource;
+import org.eclipse.persistence.jpa.rs.PersistenceUnitResource;
import org.eclipse.persistence.jpa.rs.exceptions.ClassNotFoundExceptionMapper;
+import org.eclipse.persistence.jpa.rs.exceptions.ConversionExceptionMapper;
+import org.eclipse.persistence.jpa.rs.exceptions.EntityNotFoundExceptionMapper;
import org.eclipse.persistence.jpa.rs.exceptions.IOExceptionMapper;
import org.eclipse.persistence.jpa.rs.exceptions.IllegalAccessExceptionMapper;
import org.eclipse.persistence.jpa.rs.exceptions.IllegalArgumentExceptionMapper;
@@ -45,12 +50,20 @@ import org.eclipse.persistence.jpa.rs.exceptions.NonUniqueResultExceptionExcepti
@ApplicationPath("/persistence/")
public class JPARSApplication extends Application {
-private final Set<Class<?>> classes;
+ private final Set<Class<?>> classes;
public JPARSApplication() {
HashSet<Class<?>> c = new HashSet<Class<?>>();
- c.add(Service.class);
+
+ // Resources
+ c.add(PersistenceResource.class);
+ c.add(PersistenceUnitResource.class);
+ c.add(EntityResource.class);
+
+ // Exception Mapping
c.add(ClassNotFoundExceptionMapper.class);
+ c.add(ConversionExceptionMapper.class);
+ c.add(EntityNotFoundExceptionMapper.class);
c.add(IllegalAccessExceptionMapper.class);
c.add(IllegalArgumentExceptionMapper.class);
c.add(IllegalStateExceptionMapper.class);
@@ -63,9 +76,10 @@ private final Set<Class<?>> classes;
c.add(NonUniqueResultExceptionExceptionMapper.class);
c.add(NoResultExceptionMapper.class);
c.add(NoSuchMethodExceptionMapper.class);
+
classes = Collections.unmodifiableSet(c);
}
-
+
@Override
public Set<Class<?>> getClasses() {
return classes;
diff --git a/jpa/org.eclipse.persistence.jpars/src/org/eclipse/persistence/jpa/rs/service/Service.java b/jpa/org.eclipse.persistence.jpars/src/org/eclipse/persistence/jpa/rs/service/Service.java
deleted file mode 100644
index 9e2ae1e..0000000
--- a/jpa/org.eclipse.persistence.jpars/src/org/eclipse/persistence/jpa/rs/service/Service.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2011, 2012 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:
- * dclarke/tware - initial
- ******************************************************************************/
-package org.eclipse.persistence.jpa.rs.service;
-
-import javax.ejb.LocalBean;
-import javax.ejb.Singleton;
-
-import org.eclipse.persistence.jpa.rs.ServiceBase;
-import org.eclipse.persistence.jpa.rs.PersistenceFactoryBase;
-
-/**
- * JAX-RS application interface JPA-RS
- *
- * @author tware
- * @since EclipseLink 2.4.0
- */
-@Singleton
-@LocalBean
-public class Service extends ServiceBase implements ServicePathDefinition {
-
-
- public void setPersistenceFactory(PersistenceFactoryBase factory) {
- this.factory = factory;
- }
-
-}
-
diff --git a/jpa/org.eclipse.persistence.jpars/src/org/eclipse/persistence/jpa/rs/service/ServicePathDefinition.java b/jpa/org.eclipse.persistence.jpars/src/org/eclipse/persistence/jpa/rs/service/ServicePathDefinition.java
deleted file mode 100644
index d9f47d4..0000000
--- a/jpa/org.eclipse.persistence.jpars/src/org/eclipse/persistence/jpa/rs/service/ServicePathDefinition.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2011, 2012 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:
- * tware - initial
- ******************************************************************************/
-package org.eclipse.persistence.jpa.rs.service;
-
-import javax.ws.rs.Path;
-
-/**
- * This interface is provided as a means to provide the base path for the JPA-RS REST service
- * in a manner that is portable between Jersey 1.x and Jersey 2.x.
- *
- * @see JPARSApplication
- * @author tware
- *
- */
-@Path("/")
-public interface ServicePathDefinition {
-
-}