Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (c) 2011, 2013 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.resources.common;
 
 import static org.eclipse.persistence.jpa.rs.util.StreamingOutputMarshaller.mediaType;
 
 import java.net.URI;
 import java.util.List;
 import java.util.Map;
 
 import  javax.ws.rs.core.HttpHeaders;
 import  javax.ws.rs.core.Response;
 import  javax.ws.rs.core.Response.ResponseBuilder;
 import  javax.ws.rs.core.Response.Status;
 import  javax.ws.rs.core.UriInfo;
 

Author(s):
gonural
 
 public abstract class AbstractEntityResource extends AbstractResource {
 
     @SuppressWarnings({ "rawtypes" })
     protected Response findAttribute(String versionString persistenceUnitString typeString keyString attribute, HttpHeaders hh, UriInfo uiURI baseURI) {
         PersistenceContext app = getPersistenceContext(persistenceUnitbaseURIversionnull);
         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[] { typepersistenceUnit });
             }
             return Response.status(Status.NOT_FOUND).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
         }
         Map<StringStringdiscriminators = getMatrixParameters(uipersistenceUnit);
         Object id = IdHelper.buildId(apptypekey);
 
         Object entity = app.findAttribute(discriminatorstypeidgetQueryParameters(ui), attribute);
 
         if (entity == null) {
             JPARSLogger.fine("jpars_could_not_entity_for_attribute"new Object[] { typekeyattributepersistenceUnit });
             return Response.status(Status.NOT_FOUND).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
         }
 
         Boolean collectionContainsDomainObjects = collectionContainsDomainObjects(entity);
         if (collectionContainsDomainObjects != null) {
             if (collectionContainsDomainObjects.booleanValue()) {
                 return Response.ok(new StreamingOutputMarshaller(appentityhh.getAcceptableMediaTypes())).build();
             } else {
                 // Classes derived from PersistenceWeavedRest class are already in the JAXB context and marshalled properly.
                 // Here, we will only need to deal with collection of classes that are not in the JAXB context, such as String, Integer...
                 //
                 // Jersey 1.2 introduced a new api JResponse to support this better, but in order to be able to work with 
                 // older versions of Jersey, we will use our own wrapper.
                 return Response.ok(new StreamingOutputMarshaller(apppopulateSimpleHomogeneousList((Collectionentityattribute), hh.getAcceptableMediaTypes())).build();
             }
         }
         return Response.ok(new StreamingOutputMarshaller(appentityhh.getAcceptableMediaTypes())).build();
     }
 
     protected Response find(String versionString persistenceUnitString typeString key, HttpHeaders hh, UriInfo uiURI baseURI) {
         PersistenceContext app = getPersistenceContext(persistenceUnitbaseURIversionnull);
         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[] { typepersistenceUnit });
             }
             return Response.status(Status.NOT_FOUND).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
        }
        Map<StringStringdiscriminators = getMatrixParameters(uipersistenceUnit);
        Object id = IdHelper.buildId(apptypekey);
        Object entity = app.find(discriminatorstypeidgetQueryParameters(ui));
        if (entity == null) {
            JPARSLogger.fine("jpars_could_not_entity_for_key"new Object[] { typekeypersistenceUnit });
            return Response.status(Status.NOT_FOUND).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
        } else {
            return Response.ok(new StreamingOutputMarshaller(appentityhh.getAcceptableMediaTypes())).build();
        }
    }
    @SuppressWarnings("rawtypes")
    protected Response create(String versionString persistenceUnitString type, HttpHeaders hh, UriInfo uriInfoURI baseURIInputStream inthrows JAXBException {
        PersistenceContext app = getPersistenceContext(persistenceUnitbaseURIversionnull);
        if (app == null) {
            JPARSLogger.fine("jpars_could_not_find_persistence_context"new Object[] { persistenceUnit });
            return Response.status(Status.NOT_FOUND).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
        }
        ClassDescriptor descriptor = app.getDescriptor(type);
        if (descriptor == null) {
            JPARSLogger.fine("jpars_could_not_find_class_in_persistence_unit"new Object[] { typepersistenceUnit });
            return Response.status(Status.NOT_FOUND).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
        }
        Object entity = null;
        try {
            entity = app.unmarshalEntity(typemediaType(hh.getAcceptableMediaTypes()), in);
        } catch (JAXBException e) {
            JPARSLogger.fine("exception_while_unmarhalling_entity"new Object[] { typepersistenceUnite.toString() });
            return Response.status(Status.BAD_REQUEST).type(StreamingOutputMarshaller.getResponseMediaType(hh)).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(valuedescriptor.getPrimaryKeyFields().indexOf(descriptor.getSequenceNumberField()))
                    || descriptor.getSequence().shouldAlwaysOverrideExistingValue()) {
                JPARSLogger.fine("jpars_put_not_idempotent"new Object[] { typepersistenceUnit });
                return Response.status(Status.BAD_REQUEST).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
            }
        }
        
        // maintain idempotence on PUT by disallowing sequencing in relationships
        List<DatabaseMappingmappings = descriptor.getMappings();
        if ((mappings != null) && (!mappings.isEmpty())) {
            for (DatabaseMapping mapping : mappings) {
                if (mapping instanceof ForeignReferenceMapping) {
                    ForeignReferenceMapping fkMapping = (ForeignReferenceMappingmapping;
                    if ((fkMapping.isCascadePersist()) || (fkMapping.isCascadeMerge())) {
                        ClassDescriptor referenceDescriptor = fkMapping.getReferenceDescriptor();
                        if (referenceDescriptor != null) {
                            if (referenceDescriptor instanceof RelationalDescriptor) {
                                RelationalDescriptor relDesc = (RelationalDescriptorreferenceDescriptor;
                                AbstractDirectMapping relSequenceMapping = relDesc.getObjectBuilder().getSequenceMapping();
                                if (relSequenceMapping != null) {
                                    Object value = mapping.getAttributeAccessor().getAttributeValueFromObject(entity);
                                    if (value != null) {
                                        if (value instanceof ValueHolder) {
                                            ValueHolder holder = (ValueHoldervalue;
                                            if (holder != null) {
                                                Object obj = holder.getValue();
                                                if (obj != null) {
                                                    JPARSLogger.fine("jpars_put_not_idempotent"new Object[] { typepersistenceUnit });
                                                    return Response.status(Status.BAD_REQUEST).build();
                                                }
                                            }
                                        } else if (value instanceof Collection) {
                                            if (!(((Collectionvalue).isEmpty())) {
                                                JPARSLogger.fine("jpars_put_not_idempotent"new Object[] { typepersistenceUnit });
                                                return Response.status(Status.BAD_REQUEST).build();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // No sequencing in relationships, we can create the object now...
        app.create(getMatrixParameters(uriInfopersistenceUnit), entity);
        ResponseBuilder rb = Response.status(Status.CREATED);
        rb.entity(new StreamingOutputMarshaller(appentityhh.getAcceptableMediaTypes()));
        return rb.build();
    }
    protected Response update(String versionString persistenceUnitString type, HttpHeaders hh, UriInfo uriInfoURI baseURIInputStream in) {
        PersistenceContext app = getPersistenceContext(persistenceUnitbaseURIversionnull);
        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[] { typepersistenceUnit });
            }
            return Response.status(Status.NOT_FOUND).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
        }
        Object entity = null;
        try {
            entity = app.unmarshalEntity(typemediaType(hh.getAcceptableMediaTypes()), in);
        } catch (JAXBException e) {
            JPARSLogger.fine("exception_while_unmarhalling_entity"new Object[] { typepersistenceUnite.toString() });
            return Response.status(Status.BAD_REQUEST).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
        }
        entity = app.merge(getMatrixParameters(uriInfopersistenceUnit), entity);
        return Response.ok(new StreamingOutputMarshaller(appentityhh.getAcceptableMediaTypes())).build();
    }
    protected Response setOrAddAttribute(String versionString persistenceUnitString typeString keyString attribute, HttpHeaders hh, UriInfo uiURI baseURIInputStream in) {
        PersistenceContext app = getPersistenceContext(persistenceUnitbaseURIversionnull);
        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[] { typepersistenceUnit });
            }
            return Response.status(Status.NOT_FOUND).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
        }
        Object id = IdHelper.buildId(apptypekey);
        Object entity = null;
        String partner = getRelationshipPartner(getMatrixParameters(uiattribute), getQueryParameters(ui));
        try {
            ClassDescriptor descriptor = app.getDescriptor(type);
            DatabaseMapping mapping = (DatabaseMappingdescriptor.getMappingForAttributeName(attribute);
            if (!mapping.isForeignReferenceMapping()) {
                JPARSLogger.fine("jpars_could_find_appropriate_mapping_for_update"new Object[] { attributetypekeypersistenceUnit });
                return Response.status(Status.NOT_FOUND).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
            }
            entity = app.unmarshalEntity(((ForeignReferenceMappingmapping).getReferenceDescriptor().getAlias(), mediaType(hh.getAcceptableMediaTypes()), in);
        } catch (JAXBException e) {
            JPARSLogger.fine("exception_while_unmarhalling_entity"new Object[] { typepersistenceUnite.toString() });
            return Response.status(Status.BAD_REQUEST).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
        }
        Object result = app.updateOrAddAttribute(getMatrixParameters(uipersistenceUnit), typeidgetQueryParameters(ui), attributeentitypartner);
        if (result == null) {
            JPARSLogger.fine("jpars_could_not_update_attribute"new Object[] { attributetypekeypersistenceUnit });
            return Response.status(Status.NOT_FOUND).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
        } else {
            return Response.ok(new StreamingOutputMarshaller(appresulthh.getAcceptableMediaTypes())).build();
        }
    }
    protected Response removeAttributeInternal(String versionString persistenceUnitString typeString keyString attribute, HttpHeaders hh, UriInfo ui) {
        String listItemId = null;
        Map<StringStringmatrixParams = getMatrixParameters(uiattribute);
        Map<StringObjectqueryParams = getQueryParameters(ui);
        if ((queryParams != null) && (!queryParams.isEmpty())) {
            listItemId = (StringqueryParams.get(.);
        }
        String partner = getRelationshipPartner(matrixParamsqueryParams);
        PersistenceContext app = getPersistenceContext(persistenceUnitui.getBaseUri(), versionnull);
        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[] { typepersistenceUnit });
            }
            return Response.status(Status.BAD_REQUEST).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
        }
        if ((attribute == null) && (listItemId == null)) {
            return Response.status(Status.BAD_REQUEST).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
        }
        Object id = IdHelper.buildId(apptypekey);
        ClassDescriptor descriptor = app.getDescriptor(type);
        DatabaseMapping mapping = (DatabaseMappingdescriptor.getMappingForAttributeName(attribute);
        if (!mapping.isForeignReferenceMapping()) {
            JPARSLogger.fine("jpars_could_find_appropriate_mapping_for_update"new Object[] { attributetypekeypersistenceUnit });
            return Response.status(Status.NOT_FOUND).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
        }
        Map<StringStringdiscriminators = getMatrixParameters(uipersistenceUnit);
        Object entity = app.find(discriminatorstypeidgetQueryParameters(ui));
        Object result = app.removeAttribute(getMatrixParameters(uipersistenceUnit), typeidattributelistItemIdentitypartner);
        if (result == null) {
            JPARSLogger.fine("jpars_could_not_update_attribute"new Object[] { attributetypekeypersistenceUnit });
            return Response.status(Status.NOT_FOUND).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
        } else {
            return Response.ok(new StreamingOutputMarshaller(appresulthh.getAcceptableMediaTypes())).build();
        }
    }
    protected Response delete(String versionString persistenceUnitString typeString key, UriInfo ui, HttpHeaders hhURI baseURI) {
        PersistenceContext app = getPersistenceContext(persistenceUnitbaseURIversionnull);
        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[] { typepersistenceUnit });
            }
            return Response.status(Status.NOT_FOUND).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
        }
        Map<StringStringdiscriminators = getMatrixParameters(uipersistenceUnit);
        Object id = IdHelper.buildId(apptypekey);
        app.delete(discriminatorstypeid);
        return Response.ok().build();
    }
    @SuppressWarnings("rawtypes")
    private Boolean collectionContainsDomainObjects(Object object) {
        if (!(object instanceof Collection)) {
            return null;
        }
        Collection collection = (Collectionobject;
        for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
            Object collectionItem = iterator.next();
            if (PersistenceWeavedRest.class.isAssignableFrom(collectionItem.getClass())) {
                return true;
            }
        }
        return false;
    }
    @SuppressWarnings({ "rawtypes""unchecked" })
    private SimpleHomogeneousList populateSimpleHomogeneousList(Collection collectionString attributeName) {
        SimpleHomogeneousList simpleList = new SimpleHomogeneousList();
        List<JAXBElementitems = new ArrayList<JAXBElement>();
        for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
            Object collectionItem = iterator.next();
            if (!(PersistenceWeavedRest.class.isAssignableFrom(collectionItem.getClass()))) {
                JAXBElement jaxbElement = new JAXBElement(new QName(attributeName), collectionItem.getClass(), collectionItem);
                items.add(jaxbElement);
            }
        }
        simpleList.setItems(items);
        return simpleList;
    }
New to GrepCode? Check out our FAQ X