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 java.net.URI;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 import  javax.ws.rs.core.HttpHeaders;
 import  javax.ws.rs.core.MediaType;
 import  javax.ws.rs.core.Response;
 import  javax.ws.rs.core.Response.ResponseBuilder;
 import  javax.ws.rs.core.Response.Status;
 

Author(s):
gonural
 
     protected Response getDescriptorMetadata(String versionString persistenceUnitString descriptorAlias, HttpHeaders hhURI baseURI) {
         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();
         } else {
             ClassDescriptor descriptor = app.getJpaSession().getDescriptorForAlias(descriptorAlias);
             if (descriptor == null) {
                 JPARSLogger.fine("jpars_could_not_find_entity_type"new Object[] { descriptorAliaspersistenceUnit });
                 return Response.status(Status.NOT_FOUND).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
             } else {
                 String mediaType = StreamingOutputMarshaller.mediaType(hh.getAcceptableMediaTypes()).toString();
                 Descriptor returnDescriptor = buildDescriptor(apppersistenceUnitdescriptorbaseURI.toString());
                 String result = null;
                 try {
                     result = marshallMetadata(returnDescriptormediaType);
                 } catch (JAXBException e) {
                     JPARSLogger.fine("exception_marshalling_entity_metadata"new Object[] { descriptorAliaspersistenceUnite.toString() });
                     return Response.status(Status.INTERNAL_SERVER_ERROR).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
                 }
                 return Response.ok(new StreamingOutputMarshaller(nullresulthh.getAcceptableMediaTypes())).build();
             }
         }
     }
 
     protected Response getQueriesMetadata(String versionString persistenceUnit, HttpHeaders hhURI baseURI) {
         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();
         } else {
             List<Queryqueries = new ArrayList<Query>();
             addQueries(queriesappnull);
             String mediaType = StreamingOutputMarshaller.mediaType(hh.getAcceptableMediaTypes()).toString();
             QueryList queryList = new QueryList();
             queryList.setList(queries);
             String result = null;
             try {
                 if (mediaType.equals(MediaType.APPLICATION_JSON)) {
                     result = marshallMetadata(queryList.getList(), mediaType);
                } else {
                    result = marshallMetadata(queryListmediaType);
                }
            } catch (JAXBException e) {
                JPARSLogger.fine("exception_marshalling_query_metadata"new Object[] { persistenceUnite.toString() });
                return Response.status(Status.INTERNAL_SERVER_ERROR).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
            }
            return Response.ok(new StreamingOutputMarshaller(nullresulthh.getAcceptableMediaTypes())).build();
        }
    }
    protected Response getQueryMetadata(String versionString persistenceUnitString queryName, HttpHeaders hhURI baseURI) {
        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();
        } else {
            List<QueryreturnQueries = new ArrayList<Query>();
            Map<StringList<DatabaseQuery>> queries = app.getJpaSession().getQueries();
            if (queries.get(queryName) != null) {
                for (DatabaseQuery query : queries.get(queryName)) {
                    returnQueries.add(getQuery(queryapp));
                }
            }
            String mediaType = StreamingOutputMarshaller.mediaType(hh.getAcceptableMediaTypes()).toString();
            QueryList queryList = new QueryList();
            queryList.setList(returnQueries);
            String result = null;
            try {
                if (mediaType.equals(MediaType.APPLICATION_JSON)) {
                    result = marshallMetadata(queryList.getList(), mediaType);
                } else {
                    result = marshallMetadata(queryListmediaType);
                }
            } catch (JAXBException e) {
                JPARSLogger.fine("exception_marshalling_individual_query_metadata"new Object[] { queryNamepersistenceUnite.toString() });
                return Response.status(Status.INTERNAL_SERVER_ERROR).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
            }
            return Response.ok(new StreamingOutputMarshaller(nullresulthh.getAcceptableMediaTypes())).build();
        }
    }
    @SuppressWarnings("rawtypes")
    public Response getTypes(String versionString persistenceUnit, HttpHeaders hhURI baseURI) {
        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();
        } else {
            PersistenceUnit pu = new PersistenceUnit();
            pu.setPersistenceUnitName(persistenceUnit);
            Map<ClassClassDescriptordescriptors = app.getJpaSession().getDescriptors();
            String mediaType = StreamingOutputMarshaller.mediaType(hh.getAcceptableMediaTypes()).toString();
            Iterator<ClasscontextIterator = descriptors.keySet().iterator();
            while (contextIterator.hasNext()) {
                ClassDescriptor descriptor = descriptors.get(contextIterator.next());
                String alias = descriptor.getAlias();
                if (descriptor.isAggregateDescriptor()) {
                    // skip embeddables
                    continue;
                }
                if (version != null) {
                    pu.getTypes().add(new Link(aliasmediaTypebaseURI + version + "/" + persistenceUnit + "/metadata/entity/" + alias));
                } else {
                    pu.getTypes().add(new Link(aliasmediaTypebaseURI + persistenceUnit + "/metadata/entity/" + alias));
                }
            }
            String result = null;
            try {
                result = marshallMetadata(pumediaType);
            } catch (JAXBException e) {
                JPARSLogger.fine("exception_marshalling_persitence_unit"new Object[] { persistenceUnite.toString() });
                return Response.status(Status.INTERNAL_SERVER_ERROR).type(StreamingOutputMarshaller.getResponseMediaType(hh)).build();
            }
            ResponseBuilder rb = Response.ok(new StreamingOutputMarshaller(nullresulthh.getAcceptableMediaTypes()));
            rb.header("Content-Type", MediaType.APPLICATION_JSON);
            return rb.build();
        }
    }
    @SuppressWarnings("rawtypes")
    protected void addMapping(Descriptor descriptorDatabaseMapping mapping) {
        String target = null;
        String collectionName = null;
        if (mapping.isCollectionMapping()) {
            if (mapping.isEISMapping()) {
                EISCompositeCollectionMapping collectionMapping = (EISCompositeCollectionMappingmapping;
                Class collectionClass = collectionMapping.getContainerPolicy().getContainerClass();
                String collectionType = getSimplePublicCollectionTypeName(collectionClass);
                if (collectionType == null) {
                    collectionType = collectionClass.getSimpleName();
                }
                if (collectionMapping.getReferenceClass() != null) {
                    collectionName = collectionMapping.getReferenceClass().getSimpleName();
                } 
                if ((collectionName == null) && (collectionMapping.getAttributeClassification() != null)) {
                    collectionName = collectionMapping.getAttributeClassification().getSimpleName();
                }
                if (collectionMapping.getContainerPolicy().isMapPolicy()) {
                    String mapKeyType = ((MapContainerPolicycollectionMapping.getContainerPolicy()).getKeyType().getClass().getSimpleName();
                    target = collectionType + "<" + mapKeyType + ", " + collectionName + ">";
                } else {
                    target = collectionType + "<" + collectionName + ">";
                }
            } else {
                CollectionMapping collectionMapping = (CollectionMappingmapping;
                Class collectionClass = collectionMapping.getContainerPolicy().getContainerClass();
                String collectionType = getSimplePublicCollectionTypeName(collectionClass);
                if (collectionType == null) {
                    collectionType = collectionClass.getSimpleName();
                }
               if (collectionMapping.getReferenceClass() != null) {
                    collectionName = collectionMapping.getReferenceClass().getSimpleName();
                }
                if ((collectionName == null) && (collectionMapping.getAttributeClassification() != null)) {
                    collectionName = collectionMapping.getAttributeClassification().getSimpleName();
                }
                if (collectionMapping.getContainerPolicy().isMapPolicy()) {
                    String mapKeyType = ((MapContainerPolicycollectionMapping.getContainerPolicy()).getKeyType().getClass().getSimpleName();
                    target = collectionType + "<" + mapKeyType + ", " + collectionName + ">";
                } else {
                    target = collectionType + "<" + collectionName + ">";
                }
            }
        } else if (mapping.isForeignReferenceMapping()) {
            target = ((ForeignReferenceMappingmapping).getReferenceClass().getSimpleName();
        } else {
            target = mapping.getAttributeClassification().getSimpleName();
        }
        
        descriptor.getAttributes().add(new Attribute(mapping.getAttributeName(), target));
    }
    
    protected void addQueries(List<QueryqueryListPersistenceContext appString javaClassName) {
        Map<StringList<DatabaseQuery>> queries = app.getJpaSession().getQueries();
        List<DatabaseQueryreturnQueries = new ArrayList<DatabaseQuery>();
        for (String key : queries.keySet()) {
            List<DatabaseQuerykeyQueries = queries.get(key);
            Iterator<DatabaseQueryqueryIterator = keyQueries.iterator();
            while (queryIterator.hasNext()) {
                DatabaseQuery query = queryIterator.next();
                if (javaClassName == null || (query.getReferenceClassName() != null && query.getReferenceClassName().equals(javaClassName))) {
                    returnQueries.add(query);
                }
            }
        }
        Iterator<DatabaseQueryqueryIterator = returnQueries.iterator();
        while (queryIterator.hasNext()) {
            queryList.add(getQuery(queryIterator.next(), app));
        }
    }
    protected Descriptor buildDescriptor(PersistenceContext appString persistenceUnitClassDescriptor descriptorString baseUri) {
        Descriptor returnDescriptor = new Descriptor();
        String name = descriptor.getAlias();
        returnDescriptor.setName(name);
        String version = app.getVersion();
        if (version != null) {
            version = version + "/";
            returnDescriptor.getLinkTemplates().add(new LinkTemplate("find""get"baseUri + version + persistenceUnit + "/entity/" + descriptor.getAlias() + "/{primaryKey}"));
            returnDescriptor.getLinkTemplates().add(new LinkTemplate("persist""put"baseUri + version + persistenceUnit + "/entity/" + descriptor.getAlias()));
            returnDescriptor.getLinkTemplates().add(new LinkTemplate("update""post"baseUri + version + persistenceUnit + "/entity/" + descriptor.getAlias()));
            returnDescriptor.getLinkTemplates().add(new LinkTemplate("delete""delete"baseUri + version + persistenceUnit + "/entity/" + descriptor.getAlias() + "/{primaryKey}"));
        } else {
            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<DatabaseMappingmappingIterator = descriptor.getMappings().iterator();
            while (mappingIterator.hasNext()) {
                DatabaseMapping mapping = mappingIterator.next();
                addMapping(returnDescriptormapping);
            }
        }
        addQueries(returnDescriptor.getQueries(), appdescriptor.getJavaClassName());
        return returnDescriptor;
    }
    protected Query getQuery(DatabaseQuery queryPersistenceContext app) {
        String method = query.isReadQuery() ? "get" : "post";
        String jpql = query.getJPQLString() == null ? "" : query.getJPQLString();
        StringBuffer parameterString = new StringBuffer();
        Iterator<StringargumentsIterator = query.getArguments().iterator();
        while (argumentsIterator.hasNext()) {
            String argument = argumentsIterator.next();
            parameterString.append(";");
            parameterString.append(argument + "={" + argument + "}");
        }
        
        String version = app.getVersion();
        Query returnQuery = null;
        if (version != null) {
            returnQuery = new Query(query.getName(), jpqlnew LinkTemplate("execute"methodapp.getBaseURI() + version + "/" + app.getName() + "/query/" + query.getName() + parameterString));
        } else {
            returnQuery = new Query(query.getName(), jpqlnew LinkTemplate("execute"methodapp.getBaseURI() + app.getName() + "/query/" + query.getName() + parameterString));
        }
        if (query.isReportQuery()) { 
            query.checkPrepare((AbstractSessionapp.getJpaSession(), new DatabaseRecord());
            for (ReportItem item : ((ReportQueryquery).getItems()) {
                if (item.getMapping() != null) {
                    if (item.getAttributeExpression() != null && item.getAttributeExpression().isMapEntryExpression()) {
                        if (((MapEntryExpressionitem.getAttributeExpression()).shouldReturnMapEntry()) {
                            returnQuery.getReturnTypes().add(Map.Entry.class.getSimpleName());
                        } else {
                            returnQuery.getReturnTypes().add(((Class<?>) ((CollectionMappingitem.getMapping()).getContainerPolicy().getKeyType()).getSimpleName());
                        }
                    } else {
                        returnQuery.getReturnTypes().add(item.getMapping().getAttributeClassification().getSimpleName());
                    }
                } else if (item.getResultType() != null) {
                    returnQuery.getReturnTypes().add(item.getResultType().getSimpleName());
                } else if (item.getDescriptor() != null) {
                    returnQuery.getReturnTypes().add(item.getDescriptor().getJavaClass().getSimpleName());
                } else if (item.getAttributeExpression() != null && item.getAttributeExpression().isConstantExpression()) {
                    returnQuery.getReturnTypes().add(((ConstantExpressionitem.getAttributeExpression()).getValue().getClass().getSimpleName());
                } else {
                    // Use Object.class by default.
                    returnQuery.getReturnTypes().add(..getSimpleName());
                }
            }
        } else {
            returnQuery.getReturnTypes().add(query.getReferenceClassName() == null ? "" : query.getReferenceClass().getSimpleName());
        }
        return returnQuery;
    }
    
    private String getSimplePublicCollectionTypeName(Class<?> clazz) {
        if (clazz == null) {
            return null;
        }
        LinkedHashSet<Class<?>> all = new LinkedHashSet<Class<?>>();
        getInterfaces(clazzall);
        ArrayList<Class<?>> list =  new ArrayList<Class<?>>(all);
        for (int i=0; i<all.size(); i++) {
            Class<?> clas =  list.get(i);
            if (clas.getName().equals(List.class.getName())) {
                return List.class.getSimpleName();
            }
            if (clas.getName().equals(Map.class.getName())) {
                return Map.class.getSimpleName();
            }
            if (clas.getName().equals(Set.class.getName())) {
                return Set.class.getSimpleName();
            }
        }
        return null;
    }
    private void getInterfaces(Class<?> clazzHashSet<Class<?>> interfaceList) {
        // java.lang.Class.getInterfaces returns all directly implemented interfaces 
        // and it doesn't walk the hierarchy to get all interfaces of all parent types. 
        // we walk through the hierarchy here
        while (clazz != null) {
            Class<?>[] interfaces = clazz.getInterfaces();
            for (Class<?> i : interfaces) {
                if (interfaceList.add(i)) {
                    getInterfaces(iinterfaceList);
                }
            }
            clazz = clazz.getSuperclass();
        }
    }
New to GrepCode? Check out our FAQ X