From: Sanjay Dalal Date: Tue, 29 Sep 2009 23:29:20 +0000 (+0000) Subject: CSPACE-418 relation entity schema is flatten X-Git-Url: https://git.aero2k.de/?a=commitdiff_plain;h=6a864464bbc494d9571c909f56c913b3bba2a123;p=tmp%2Fjakarta-migration.git CSPACE-418 relation entity schema is flatten CSPACE-81,394 schema extension supported between consumer and service using multipart messaging, between service and repository using nuxeo repository. relationship service is refactored to use repository client and document handler. tenant binding updated for the relationship service. service context and document handler are further refactored to accommodate the use case of "local" service-service interaction and "remote" interaction. All remotely accessible services now use RemoteServiceContext and RemoteDocumentHandler. Removed unused RepresentationHandlers from all the services where applicable. TEST: services/trunk mvn test passes M services/collectionobject/service/src/main/java/org/collectionspace/services/collectionobject/CollectionObjectResource.java D services/collectionobject/service/src/main/java/org/collectionspace/services/collectionobject/nuxeo/CollectionObjectRepresenationHandler.java M services/collectionobject/service/src/main/java/org/collectionspace/services/collectionobject/nuxeo/CollectionObjectDocumentModelHandler.java M services/collectionobject/service/src/main/java/org/collectionspace/services/collectionobject/nuxeo/CollectionObjectHandlerFactory.java M services/JaxRsServiceProvider/src/main/java/org/collectionspace/services/jaxrs/CollectionSpaceJaxRsApplication.java M services/JaxRsServiceProvider/pom.xml M services/common/src/main/java/org/collectionspace/services/common/repository/RepositoryClientFactory.java M services/common/src/main/java/org/collectionspace/services/common/repository/DocumentHandler.java M services/common/src/main/java/org/collectionspace/services/common/CollectionSpaceResource.java M services/common/src/main/java/org/collectionspace/services/common/AbstractCollectionSpaceResource.java A services/common/src/main/java/org/collectionspace/services/common/context/RemoteServiceContext.java A + services/common/src/main/java/org/collectionspace/services/common/context/RemoteServiceContextImpl.java M services/common/src/main/java/org/collectionspace/services/common/context/ServiceContext.java D services/common/src/main/java/org/collectionspace/services/common/context/ServiceContextImpl.java A services/common/src/main/java/org/collectionspace/services/common/context/AbstractServiceContext.java R services/common/src/main/java/org/collectionspace/services/common/relation/RelationJAXBSchema.java R services/common/src/main/java/org/collectionspace/services/common/relation/IRelationsManager.java D services/common/src/main/java/org/collectionspace/services/common/relation/RelationsManager.java A services/common/src/main/java/org/collectionspace/services/common/relation/nuxeo/RelationsUtils.java A services/common/src/main/java/org/collectionspace/services/common/relation/nuxeo/RelationConstants.java D services/common/src/main/java/org/collectionspace/services/common/relation/nuxeo/RelationsManagerNuxeoImpl.java D services/common/src/main/java/org/collectionspace/services/nuxeo/CollectionSpaceServiceNuxeoImpl.java M services/common/src/main/java/org/collectionspace/services/nuxeo/util/NuxeoUtils.java A services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/RemoteDocumentModelHandler.java M services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/DocumentModelHandler.java M services/common/src/main/config/tenant-bindings.xml A + services/common/src/main/resources/relations-common.xsd D services/common/src/main/resources/relation.xsd M services/acquisition/service/src/main/java/org/collectionspace/services/acquisition/AcquisitionResource.java M services/acquisition/service/src/main/java/org/collectionspace/services/acquisition/nuxeo/AcquisitionDocumentModelHandler.java M services/pom.xml M services/intake/service/src/main/java/org/collectionspace/services/intake/IntakeResource.java M services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeHandlerFactory.java D services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeRepresenationHandler.java M services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeDocumentModelHandler.java M services/relation/service/src/main/java/org/collectionspace/services/relation/NewRelationResource.java D services/relation/service/src/main/java/org/collectionspace/services/relation/RelationResource.java D services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationServiceNuxeoImpl.java M services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationHandlerFactory.java D services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationNuxeoConstants.java M services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationDocumentModelHandler.java D services/relation/service/src/main/java/org/collectionspace/services/relation/RelationService.java A + services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/schemas/relations-common.xsd D services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/schemas/relation.xsd M services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/OSGI-INF/core-types-contrib.xml M services/relation/client/src/test/java/org/collectionspace/services/client/test/RelationServiceTest.java A services/relation/client/src/test/resources/log4j.properties D services/relation/client/src/test/resources/log4j.xml M services/relation/client/src/main/java/org/collectionspace/services/client/RelationProxy.java M services/relation/client/src/main/java/org/collectionspace/services/client/RelationClient.java M services/relation/client/pom.xml --- diff --git a/services/JaxRsServiceProvider/pom.xml b/services/JaxRsServiceProvider/pom.xml index a5137dd18..66e6c6fff 100644 --- a/services/JaxRsServiceProvider/pom.xml +++ b/services/JaxRsServiceProvider/pom.xml @@ -42,12 +42,12 @@ org.collectionspace.services.acquisition.service 1.0 - nuxeo-java - nuxeo-java - + + + nuxeo-java + + + + + + + + + + + + + + + + diff --git a/services/common/src/main/java/org/collectionspace/services/common/AbstractCollectionSpaceResource.java b/services/common/src/main/java/org/collectionspace/services/common/AbstractCollectionSpaceResource.java index ad2fef0dc..e66ea566d 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/AbstractCollectionSpaceResource.java +++ b/services/common/src/main/java/org/collectionspace/services/common/AbstractCollectionSpaceResource.java @@ -23,8 +23,9 @@ */ package org.collectionspace.services.common; +import org.collectionspace.services.common.context.RemoteServiceContext; import org.collectionspace.services.common.context.ServiceContext; -import org.collectionspace.services.common.context.ServiceContextImpl; +import org.collectionspace.services.common.context.RemoteServiceContextImpl; import org.collectionspace.services.common.repository.DocumentHandler; import org.collectionspace.services.common.repository.RepositoryClient; import org.collectionspace.services.common.repository.RepositoryClientFactory; @@ -59,12 +60,12 @@ public abstract class AbstractCollectionSpaceResource } @Override - public ServiceContext createServiceContext(MultipartInput input) throws Exception { - ServiceContext ctx = new ServiceContextImpl(getServiceName()); + public RemoteServiceContext createServiceContext(MultipartInput input) throws Exception { + RemoteServiceContext ctx = new RemoteServiceContextImpl(getServiceName()); ctx.setInput(input); return ctx; } @Override - abstract public DocumentHandler createDocumentHandler(ServiceContext ctx) throws Exception ; + abstract public DocumentHandler createDocumentHandler(RemoteServiceContext ctx) throws Exception ; } diff --git a/services/common/src/main/java/org/collectionspace/services/common/CollectionSpaceResource.java b/services/common/src/main/java/org/collectionspace/services/common/CollectionSpaceResource.java index 2f601c334..11062548f 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/CollectionSpaceResource.java +++ b/services/common/src/main/java/org/collectionspace/services/common/CollectionSpaceResource.java @@ -24,6 +24,7 @@ package org.collectionspace.services.common; +import org.collectionspace.services.common.context.RemoteServiceContext; import org.collectionspace.services.common.context.ServiceContext; import org.collectionspace.services.common.repository.DocumentHandler; import org.collectionspace.services.common.repository.RepositoryClient; @@ -59,7 +60,7 @@ public interface CollectionSpaceResource { * @param input * @return */ - public ServiceContext createServiceContext(MultipartInput input) throws Exception; + public RemoteServiceContext createServiceContext(MultipartInput input) throws Exception; /** * createDocumentHandler creates a document handler and populates it with given @@ -69,5 +70,5 @@ public interface CollectionSpaceResource { * @param ctx * @return */ - public DocumentHandler createDocumentHandler(ServiceContext ctx) throws Exception ; + public DocumentHandler createDocumentHandler(RemoteServiceContext ctx) throws Exception ; } diff --git a/services/common/src/main/java/org/collectionspace/services/common/context/ServiceContextImpl.java b/services/common/src/main/java/org/collectionspace/services/common/context/AbstractServiceContext.java similarity index 67% rename from services/common/src/main/java/org/collectionspace/services/common/context/ServiceContextImpl.java rename to services/common/src/main/java/org/collectionspace/services/common/context/AbstractServiceContext.java index b88a6a7e0..fdebfe5d4 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/context/ServiceContextImpl.java +++ b/services/common/src/main/java/org/collectionspace/services/common/context/AbstractServiceContext.java @@ -23,57 +23,34 @@ */ package org.collectionspace.services.common.context; -import java.io.ByteArrayOutputStream; -import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.ws.rs.core.MediaType; import org.collectionspace.services.common.ClientType; import org.collectionspace.services.common.ServiceMain; import org.collectionspace.services.common.config.TenantBindingConfigReader; -import org.collectionspace.services.common.repository.DocumentUtils; import org.collectionspace.services.common.service.ObjectPartType; import org.collectionspace.services.common.service.ServiceBindingType; import org.collectionspace.services.common.service.ServiceObjectType; import org.collectionspace.services.common.tenant.TenantBindingType; -import org.jboss.resteasy.plugins.providers.multipart.InputPart; -import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; -import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; -import org.jboss.resteasy.plugins.providers.multipart.OutputPart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; /** - * ServiceContextImpl + * AbstractServiceContext * * $LastChangedRevision: $ * $LastChangedDate: $ */ -public class ServiceContextImpl - implements ServiceContext { +public abstract class AbstractServiceContext + implements ServiceContext { - final Logger logger = LoggerFactory.getLogger(ServiceContextImpl.class); - private TenantBindingType tenantBinding; - private ServiceBindingType serviceBinding; - //input stores original content as received over the wire - private MultipartInput input; - private MultipartOutput output; + final Logger logger = LoggerFactory.getLogger(AbstractServiceContext.class); Map objectPartMap = new HashMap(); + private ServiceBindingType serviceBinding; + private TenantBindingType tenantBinding; - @Override - public String toString() { - return "ServiceContextImpl [" + - "service name=" + serviceBinding.getName() + " " + - "service version=" + serviceBinding.getVersion() + " " + - "tenant id=" + tenantBinding.getId() + " " + - "tenant name=" + tenantBinding.getName() + " " + tenantBinding.getDisplayName() + " " + - "tenant repository domain=" + tenantBinding.getRepositoryDomain() + " " + - "]"; - } - - public ServiceContextImpl(String serviceName) { + public AbstractServiceContext(String serviceName) { TenantBindingConfigReader tReader = ServiceMain.getInstance().getTenantBindingConfigReader(); //TODO: get tenant binding from security context (Subject.g @@ -97,38 +74,36 @@ public class ServiceContextImpl logger.debug("tenantId=" + tenantId + " service binding=" + serviceBinding.getName()); } - output = new MultipartOutput(); - } - - @Override - public String getTenantId() { - return tenantBinding.getId(); - } - - @Override - public String getTenantName() { - return tenantBinding.getName(); } + /** + * getCommonPartLabel get common part label + * @return + */ @Override - public ServiceBindingType getServiceBinding() { - return serviceBinding; + public String getCommonPartLabel() { + return getServiceName().toLowerCase() + "-common"; } @Override - public String getServiceName() { - return serviceBinding.getName(); + public Map getPartsMetadata() { + if(objectPartMap.size() != 0){ + return objectPartMap; + } + ServiceBindingType serviceBinding = getServiceBinding(); + List objectTypes = serviceBinding.getObject(); + for(ServiceObjectType objectType : objectTypes){ + List objectPartTypes = objectType.getPart(); + for(ObjectPartType objectPartType : objectPartTypes){ + objectPartMap.put(objectPartType.getLabel(), objectPartType); + } + } + return objectPartMap; } @Override public String getQualifiedServiceName() { - return TenantBindingConfigReader.getTenantQualifiedServiceName( - getTenantId(), getServiceName()); - } - - @Override - public String getRepositoryDomainName() { - return tenantBinding.getRepositoryDomain(); + return TenantBindingConfigReader.getTenantQualifiedServiceName(getTenantId(), getServiceName()); } @Override @@ -143,97 +118,63 @@ public class ServiceContextImpl } @Override - public String getRepositoryWorkspaceName() { - //service name is workspace name by convention - return serviceBinding.getName(); + public String getRepositoryDomainName() { + return tenantBinding.getRepositoryDomain(); } @Override public String getRepositoryWorkspaceId() { - TenantBindingConfigReader tbConfigReader = - ServiceMain.getInstance().getTenantBindingConfigReader(); + TenantBindingConfigReader tbConfigReader = ServiceMain.getInstance().getTenantBindingConfigReader(); return tbConfigReader.getWorkspaceId(getTenantId(), getServiceName()); } @Override - public MultipartInput getInput() { - return input; + public String getRepositoryWorkspaceName() { + //service name is workspace name by convention + return serviceBinding.getName(); } @Override - public MultipartOutput getOutput() { - return output; + public ServiceBindingType getServiceBinding() { + return serviceBinding; } @Override - public Object getInputPart(String label, Class clazz) throws IOException { - Object obj = null; - if(getInput() != null){ - MultipartInput fdip = getInput(); - - for(InputPart part : fdip.getParts()){ - String partLabel = part.getHeaders().getFirst("label"); - if(label.equalsIgnoreCase(partLabel)){ - if(logger.isDebugEnabled()){ - logger.debug("received part label=" + partLabel + - "\npayload=" + part.getBodyAsString()); - } - obj = part.getBody(clazz, null); - break; - } - } - } - return obj; + public String getServiceName() { + return serviceBinding.getName(); } @Override - public void addOutputPart(String label, Document doc, String contentType) throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try{ - DocumentUtils.writeDocument(doc, baos); - baos.close(); - OutputPart part = output.addPart(new String(baos.toByteArray()), - MediaType.valueOf(contentType)); - part.getHeaders().add("label", label); - }finally{ - if(baos != null){ - try{ - baos.close(); - }catch(Exception e){ - } - } - } + public String getTenantId() { + return tenantBinding.getId(); } @Override - public void setInput(MultipartInput input) throws IOException { - this.input = input; + public String getTenantName() { + return tenantBinding.getName(); } @Override - public Map getPartsMetadata() { - if(objectPartMap.size() != 0){ - return objectPartMap; - } + public abstract T1 getInput(); - ServiceBindingType serviceBinding = getServiceBinding(); - List objectTypes = serviceBinding.getObject(); - for(ServiceObjectType objectType : objectTypes){ - List objectPartTypes = objectType.getPart(); - for(ObjectPartType objectPartType : objectPartTypes){ - objectPartMap.put(objectPartType.getLabel(), objectPartType); - } + @Override + public abstract void setInput(T1 input) throws Exception; - } - return objectPartMap; - } + @Override + public abstract T2 getOutput(); - /** - * getCommonPartLabel get common part label - * @return - */ @Override - public String getCommonPartLabel() { - return getServiceName().toLowerCase() + "-common"; + public abstract void setOutput(T2 output) throws Exception; + + @Override + public String toString() { + return "AbstractServiceContext [" + + "service name=" + serviceBinding.getName() + " " + + "service version=" + serviceBinding.getVersion() + " " + + "tenant id=" + tenantBinding.getId() + " " + + "tenant name=" + tenantBinding.getName() + " " + + tenantBinding.getDisplayName() + " " + + "tenant repository domain=" + tenantBinding.getRepositoryDomain() + " " + + "]"; } } diff --git a/services/common/src/main/java/org/collectionspace/services/common/context/RemoteServiceContext.java b/services/common/src/main/java/org/collectionspace/services/common/context/RemoteServiceContext.java new file mode 100644 index 000000000..9ec071da8 --- /dev/null +++ b/services/common/src/main/java/org/collectionspace/services/common/context/RemoteServiceContext.java @@ -0,0 +1,91 @@ +/** + * This document is a part of the source code and related artifacts + * for CollectionSpace, an open source collections management system + * for museums and related institutions: + + * http://www.collectionspace.org + * http://wiki.collectionspace.org + + * Copyright 2009 University of California at Berkeley + + * Licensed under the Educational Community License (ECL), Version 2.0. + * You may not use this file except in compliance with this License. + + * You may obtain a copy of the ECL 2.0 License at + + * https://source.collectionspace.org/collection-space/LICENSE.txt + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.collectionspace.services.common.context; + +import java.io.IOException; +import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; +import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; +import org.w3c.dom.Document; + +/** + * RemoteServiceContext is used to encapsulate the service context of a + * remotely invokable service + */ +public interface RemoteServiceContext + extends ServiceContext { + + /** + * Get input parts as received over the wire from service consumer + * @return the input + */ + @Override + public MultipartInput getInput(); + + /** + * setInput is used to set request input before starting to + * process input data + * @param input + * @exception IOException + */ + @Override + public void setInput(MultipartInput input) throws Exception; + + /** + * Get output parts to send over the wire to service consumer + * @return the output + */ + @Override + public MultipartOutput getOutput(); + + /** + * Set output parts to send over the wire to service consumer + * @return the output + */ + @Override + public void setOutput(MultipartOutput output) throws Exception; + + /** + * getInputPart returns part for given label from input + * @param label + * @param clazz class of the object + * @return part + */ + public Object getInputPart(String label, Class clazz) throws IOException; + + /** + * addOutputPart adds given XML part with given label and content type to output + * @param label + * @param document + * @param contentType media type + */ + public void addOutputPart(String label, Document doc, String contentType) throws Exception; + + /** + * getLocalContext clones the remote context minus remote messaging data parts + * this method is useful to object a local service context to invoke a service locally + * @param local context class namee + * @return local service context + */ + public ServiceContext getLocalContext(String localContextClassName) throws Exception; +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/context/RemoteServiceContextImpl.java b/services/common/src/main/java/org/collectionspace/services/common/context/RemoteServiceContextImpl.java new file mode 100644 index 000000000..af6f5b492 --- /dev/null +++ b/services/common/src/main/java/org/collectionspace/services/common/context/RemoteServiceContextImpl.java @@ -0,0 +1,132 @@ +/** + * This document is a part of the source code and related artifacts + * for CollectionSpace, an open source collections management system + * for museums and related institutions: + + * http://www.collectionspace.org + * http://wiki.collectionspace.org + + * Copyright 2009 University of California at Berkeley + + * Licensed under the Educational Community License (ECL), Version 2.0. + * You may not use this file except in compliance with this License. + + * You may obtain a copy of the ECL 2.0 License at + + * https://source.collectionspace.org/collection-space/LICENSE.txt + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.collectionspace.services.common.context; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.Constructor; +import javax.ws.rs.core.MediaType; +import org.collectionspace.services.common.repository.DocumentUtils; +import org.jboss.resteasy.plugins.providers.multipart.InputPart; +import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; +import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; +import org.jboss.resteasy.plugins.providers.multipart.OutputPart; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; + +/** + * RemoteServiceContextImpl + * + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public class RemoteServiceContextImpl + extends AbstractServiceContext + implements RemoteServiceContext { + + final Logger logger = LoggerFactory.getLogger(RemoteServiceContextImpl.class); + //input stores original content as received over the wire + private MultipartInput input; + private MultipartOutput output; + + public RemoteServiceContextImpl(String serviceName) { + super(serviceName); + output = new MultipartOutput(); + } + + @Override + public MultipartInput getInput() { + return input; + } + + @Override + public void setInput(MultipartInput input) throws IOException { + this.input = input; + } + + @Override + public MultipartOutput getOutput() { + return output; + } + + @Override + public void setOutput(MultipartOutput output) throws Exception { + this.output = output; + } + + @Override + public Object getInputPart(String label, Class clazz) throws IOException { + Object obj = null; + if(getInput() != null){ + MultipartInput fdip = getInput(); + + for(InputPart part : fdip.getParts()){ + String partLabel = part.getHeaders().getFirst("label"); + if(label.equalsIgnoreCase(partLabel)){ + if(logger.isDebugEnabled()){ + logger.debug("received part label=" + partLabel + + "\npayload=" + part.getBodyAsString()); + } + obj = part.getBody(clazz, null); + break; + } + } + } + return obj; + } + + @Override + public void addOutputPart(String label, Document doc, String contentType) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try{ + DocumentUtils.writeDocument(doc, baos); + baos.close(); + OutputPart part = output.addPart(new String(baos.toByteArray()), + MediaType.valueOf(contentType)); + part.getHeaders().add("label", label); + }finally{ + if(baos != null){ + try{ + baos.close(); + }catch(Exception e){ + } + } + } + } + + @Override + public ServiceContext getLocalContext(String localContextClassName) throws Exception { + ClassLoader cloader = Thread.currentThread().getContextClassLoader(); + Class ctxClass = cloader.loadClass(localContextClassName); + if(!ServiceContext.class.isAssignableFrom(ctxClass)) { + throw new IllegalArgumentException("getLocalContext requires " + + " implementation of " + ServiceContext.class.getName()); + } + + Constructor ctor = ctxClass.getConstructor(java.lang.String.class); + ServiceContext ctx = (ServiceContext)ctor.newInstance(getServiceName()); + return ctx; + } +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/context/ServiceContext.java b/services/common/src/main/java/org/collectionspace/services/common/context/ServiceContext.java index a74d5561d..ab63c0e11 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/context/ServiceContext.java +++ b/services/common/src/main/java/org/collectionspace/services/common/context/ServiceContext.java @@ -23,14 +23,10 @@ */ package org.collectionspace.services.common.context; -import java.io.IOException; import java.util.Map; import org.collectionspace.services.common.ClientType; import org.collectionspace.services.common.service.ObjectPartType; import org.collectionspace.services.common.service.ServiceBindingType; -import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; -import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; -import org.w3c.dom.Document; /** * @@ -38,7 +34,7 @@ import org.w3c.dom.Document; * between various components of the service framework while processing * a service request. */ -public interface ServiceContext { +public interface ServiceContext { /** * getTenantId get tenant id @@ -108,41 +104,31 @@ public interface ServiceContext { */ public String getRepositoryWorkspaceId(); - /** - * setInput is used to set (multipart) request input before starting to - * process input data - * @param input multipart data input - * @exception IOException - */ - public void setInput(MultipartInput input) throws IOException; - /** * Get input parts as received over the wire from service consumer * @return the input */ - public MultipartInput getInput(); + public T1 getInput(); /** - * Get output parts to send over the wire to service consumer - * @return the output + * setInput is used to set request input before starting to + * process input data + * @param input + * @exception Exception */ - public MultipartOutput getOutput(); + public void setInput(T1 input) throws Exception; /** - * getInputPart returns part for given label from input - * @param label - * @param clazz class of the object - * @return part + * Get output parts to send over the wire to service consumer + * @return the output */ - public Object getInputPart(String label, Class clazz) throws IOException; + public T2 getOutput(); /** - * addOutputPart adds given XML part with given label and content type to output - * @param label - * @param document - * @param contentType media type + * setOutput set output + * @param output */ - public void addOutputPart(String label, Document doc, String contentType) throws Exception; + public void setOutput(T2 output) throws Exception; /** * getPartsMetadata returns metadata for object parts used by the service diff --git a/services/common/src/main/java/org/collectionspace/services/common/relation/IRelationsManager.java b/services/common/src/main/java/org/collectionspace/services/common/relation/IRelationsManager.java index 07e17b35b..e6345719a 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/relation/IRelationsManager.java +++ b/services/common/src/main/java/org/collectionspace/services/common/relation/IRelationsManager.java @@ -1,5 +1,5 @@ /** - * RelationUtils.java + * IRelationsManager.java * * {Purpose of This Class} * @@ -26,101 +26,96 @@ */ package org.collectionspace.services.common.relation; -import java.io.IOException; import java.util.List; + import org.collectionspace.services.common.repository.DocumentException; -import org.collectionspace.services.relation.Relation; -import org.dom4j.Document; +import org.collectionspace.services.relation.RelationsCommon; import org.nuxeo.ecm.core.api.DocumentModel; /** - * The Interface RelationUtils. + * The Interface IRelationsManager. */ public interface IRelationsManager { - /** - * Gets the relationships. - * - * @param repoSession the repo session - * - * @return the relationships - * - * @throws DocumentException the document exception - */ - public List getRelationships(Object repoSession) - throws DocumentException; + /** The Constant SUBJECT. */ + static public final String SUBJECT = "subjectCsid"; + /** The Constant PREDICATE. */ + static public final String PREDICATE = "predicate"; + /** The Constant OBJECT. */ + static public final String OBJECT = "objectCsid"; + + + /** + * Gets the relationships for the entity corresponding to the CSID=csid. + * The csid refers to either the subject *OR* the object. + * + * @param nuxeoRepoSession the nuxeo repo session + * @param csid the csid + * + * @return the relationships + * + * @throws DocumentException the document exception + */ + public List getRelationships(Object nuxeoRepoSession, String csid) + throws DocumentException; + + /** + * Gets the relationships. + * + * @param repoSession the repo session + * @param subjectCsid the subject csid + * @param relationType the relation type + * @param objectCsid the object csid + * + * @return the relationships + * + * @throws DocumentException the document exception + */ + public List getRelationships(Object repoSession, + String subjectCsid, + String relationType, + String objectCsid) + throws DocumentException; + + /** + * Creates the relationship. + * + * @param repoSession the repo session + * @param subjectCsid the subject csid + * @param predicate the predicate + * @param objectCsid the object csid + * + * @return the relation + * + * @throws DocumentException the document exception + */ + public RelationsCommon createRelationship(Object repoSession, String subjectCsid, + String predicate, String objectCsid) throws DocumentException; - /** - * Gets the relationships for the entity corresponding to the CSID=csid. - * The csid refers to either the subject *OR* the object. - * - * @param nuxeoRepoSession the nuxeo repo session - * @param csid the csid - * - * @return the relationships - * - * @throws DocumentException the document exception - */ - public List getRelationships(Object nuxeoRepoSession, String csid) - throws DocumentException; - - /** - * Gets the relationships. - * - * @param repoSession the repo session - * @param subjectCsid the subject csid - * @param relationType the relation type - * @param objectCsid the object csid - * - * @return the relationships - * - * @throws DocumentException the document exception - */ - public List getRelationships(Object repoSession, - String subjectCsid, - String relationType, - String objectCsid) - throws DocumentException; + /** + * Gets the q property name. + * + * @param propertyName the property name + * + * @return the q property name + */ + public String getQPropertyName(String propertyName); - /** - * Creates the relationship. - * - * @param repoSession the repo session - * @param subjectCsid the subject csid - * @param predicate the predicate - * @param objectCsid the object csid - * - * @return the relation - * - * @throws DocumentException the document exception - */ - public Relation createRelationship(Object repoSession, String subjectCsid, - String predicate, String objectCsid) throws DocumentException; - - /** - * Gets the q property name. - * - * @param propertyName the property name - * - * @return the q property name - */ - public String getQPropertyName(String propertyName); - - /** - * Checks if is query match. - * - * @param documentModel the document model - * @param subjectCsid the subject csid - * @param predicate the predicate - * @param objectCsid the object csid - * - * @return true, if is query match - * - * @throws DocumentException the document exception - */ - public boolean isQueryMatch(DocumentModel documentModel, - String subjectCsid, - String predicate, - String objectCsid) throws DocumentException; -} \ No newline at end of file + /** + * Checks if is query match. + * + * @param documentModel the document model + * @param subjectCsid the subject csid + * @param predicate the predicate + * @param objectCsid the object csid + * + * @return true, if is query match + * + * @throws DocumentException the document exception + */ + public boolean isQueryMatch(DocumentModel documentModel, + String subjectCsid, + String predicate, + String objectCsid) throws DocumentException; +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/relation/RelationsManager.java b/services/common/src/main/java/org/collectionspace/services/common/relation/RelationsManager.java deleted file mode 100644 index 4658e85ce..000000000 --- a/services/common/src/main/java/org/collectionspace/services/common/relation/RelationsManager.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * RelationsManager.java - * - * {Purpose of This Class} - * - * {Other Notes Relating to This Class (Optional)} - * - * $LastChangedBy: $ - * $LastChangedRevision: $ - * $LastChangedDate: $ - * - * This document is a part of the source code and related artifacts - * for CollectionSpace, an open source collections management system - * for museums and related institutions: - * - * http://www.collectionspace.org - * http://wiki.collectionspace.org - * - * Copyright © 2009 {Contributing Institution} - * - * Licensed under the Educational Community License (ECL), Version 2.0. - * You may not use this file except in compliance with this License. - * - * You may obtain a copy of the ECL 2.0 License at - * https://source.collectionspace.org/collection-space/LICENSE.txt - */ -package org.collectionspace.services.common.relation; - -import java.io.IOException; -import java.util.List; - -import org.collectionspace.services.common.repository.DocumentException; -import org.collectionspace.services.common.relation.nuxeo.RelationsManagerNuxeoImpl; -import org.collectionspace.services.relation.Relation; -import org.collectionspace.services.common.relation.IRelationsManager; - -import org.dom4j.Document; -import org.nuxeo.ecm.core.api.DocumentModel; - -/** - * The Class RelationsManager. - */ -public class RelationsManager { - - /** The Constant SUBJECT. */ - static public final String SUBJECT = "subjectCsid"; - - /** The Constant PREDICATE. */ - static public final String PREDICATE = "predicate"; - - /** The Constant OBJECT. */ - static public final String OBJECT = "objectCsid"; - - /** The relation utils. */ - static private IRelationsManager relationUtils = new RelationsManagerNuxeoImpl(); - - /** - * Gets the relationships. - * - * @param repoSession the repo session - * - * @return the relationships - * - * @throws DocumentException the document exception - */ - static public List getRelationships(Object repoSession) - throws DocumentException { - return relationUtils.getRelationships(repoSession); - } - - /** - * Gets the relationships. - * - * @param repoSession the repo session - * @param subjectCsid the subject csid - * @param predicate the predicate - * @param objectCsid the object csid - * - * @return the relationships - * - * @throws DocumentException the document exception - */ - static public List getRelationships(Object repoSession, String subjectCsid, String predicate, String objectCsid) - throws DocumentException { - return relationUtils.getRelationships(repoSession, subjectCsid, predicate, objectCsid); - } - - /** - * Gets the relationships. - * - * @param repoSession the repo session - * @param csid the csid - * - * @return the relationships - * - * @throws DocumentException the document exception - */ - static public List getRelationships(Object repoSession, - String csid) throws DocumentException { - return relationUtils.getRelationships(repoSession, csid); - } - - /** - * Creates the relationship. - * - * @param repoSession the repo session - * @param subjectCsid the subject csid - * @param predicate the predicate - * @param objectCsid the object csid - * - * @return the relation - * - * @throws DocumentException the document exception - */ - static public Relation createRelationship(Object repoSession, - String subjectCsid, - String predicate, - String objectCsid) throws DocumentException { - return relationUtils.createRelationship(repoSession, subjectCsid, - predicate, objectCsid); - } - - /** - * Gets the q property name. - * - * @param propertyName the property name - * - * @return the q property name - */ - static public String getQPropertyName(String propertyName) { - return relationUtils.getQPropertyName(propertyName); - } - - /** - * Checks if is query match. - * - * @param documentModel the document model - * @param subjectCsid the subject csid - * @param predicate the predicate - * @param objectCsid the object csid - * - * @return true, if is query match - * - * @throws DocumentException the document exception - */ - static public boolean isQueryMatch(DocumentModel documentModel, - String subjectCsid, String predicate, String objectCsid) - throws DocumentException { - return relationUtils.isQueryMatch(documentModel, subjectCsid, - predicate, objectCsid); - } - -} diff --git a/services/common/src/main/java/org/collectionspace/services/common/relation/nuxeo/RelationConstants.java b/services/common/src/main/java/org/collectionspace/services/common/relation/nuxeo/RelationConstants.java new file mode 100644 index 000000000..69455525e --- /dev/null +++ b/services/common/src/main/java/org/collectionspace/services/common/relation/nuxeo/RelationConstants.java @@ -0,0 +1,37 @@ +/** + * This document is a part of the source code and related artifacts + * for CollectionSpace, an open source collections management system + * for museums and related institutions: + + * http://www.collectionspace.org + * http://wiki.collectionspace.org + + * Copyright 2009 University of California at Berkeley + + * Licensed under the Educational Community License (ECL), Version 2.0. + * You may not use this file except in compliance with this License. + + * You may obtain a copy of the ECL 2.0 License at + + * https://source.collectionspace.org/collection-space/LICENSE.txt + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.collectionspace.services.common.relation.nuxeo; + +/** + * CollectionObjectConstants processes CollectionObject document + * + */ +public class RelationConstants { + + public final static String NUXEO_DOCTYPE = "Relation"; + public final static String NUXEO_SCHEMA_NAME = "relation"; + public final static String NUXEO_DC_TITLE = "CollectionSpace-Relation"; + /** The Constant REL_NUXEO_SCHEMA_ROOT_ELEMENT. */ + final public static String NUXEO_SCHEMA_ROOT_ELEMENT = "relationtype"; +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/relation/nuxeo/RelationsManagerNuxeoImpl.java b/services/common/src/main/java/org/collectionspace/services/common/relation/nuxeo/RelationsManagerNuxeoImpl.java deleted file mode 100644 index aa3effef6..000000000 --- a/services/common/src/main/java/org/collectionspace/services/common/relation/nuxeo/RelationsManagerNuxeoImpl.java +++ /dev/null @@ -1,633 +0,0 @@ -/** - * RelationUtilsNuxeoImpl.java - * - * {Purpose of This Class} - * - * {Other Notes Relating to This Class (Optional)} - * - * $LastChangedBy: $ - * $LastChangedRevision: $ - * $LastChangedDate: $ - * - * This document is a part of the source code and related artifacts - * for CollectionSpace, an open source collections management system - * for museums and related institutions: - * - * http://www.collectionspace.org - * http://wiki.collectionspace.org - * - * Copyright © 2009 {Contributing Institution} - * - * Licensed under the Educational Community License (ECL), Version 2.0. - * You may not use this file except in compliance with this License. - * - * You may obtain a copy of the ECL 2.0 License at - * https://source.collectionspace.org/collection-space/LICENSE.txt - */ -package org.collectionspace.services.common.relation.nuxeo; - -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.collectionspace.services.common.relation.RelationJAXBSchema; -import org.collectionspace.services.common.relation.RelationListItemJAXBSchema; -import org.collectionspace.services.common.relation.IRelationsManager; - -import org.collectionspace.services.relation.Relation; -import org.collectionspace.services.relation.RelationList; -import org.collectionspace.services.relation.RelationshipType; -import org.collectionspace.services.relation.RelationList.RelationListItem; -import org.collectionspace.services.nuxeo.util.NuxeoUtils; -import org.collectionspace.services.common.repository.DocumentException; - -import org.dom4j.Document; -import org.dom4j.Element; -import org.dom4j.dom.DOMElement; -import org.dom4j.dom.DOMDocument; -import org.dom4j.dom.DOMDocumentFactory; -//import org.dom4j.DocumentException; - -import org.nuxeo.common.utils.IdUtils; -import org.nuxeo.ecm.core.api.ClientException; -import org.nuxeo.ecm.core.api.DocumentModel; -import org.nuxeo.ecm.core.api.DocumentModelList; -import org.nuxeo.ecm.core.api.model.DocumentPart; -import org.nuxeo.ecm.core.api.repository.RepositoryInstance; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -//import org.w3c.dom.DOMException; -//import org.w3c.dom.Element; - -/** - * The Class RelationUtilsNuxeoImpl. - */ -public class RelationsManagerNuxeoImpl implements IRelationsManager { - - /** The C s_ relatio n_ servic e_ name. */ - static public String CS_RELATION_SERVICE_NAME = "relations"; - - /** The C s_ empt y_ string. */ - static public String CS_EMPTY_STRING = ""; - - /** The Constant REL_NUXEO_DOCTYPE. */ - final public static String REL_NUXEO_DOCTYPE = "Relation"; - - /** The Constant REL_NUXEO_SCHEMA_NAME. */ - final public static String REL_NUXEO_SCHEMA_NAME = "relation"; - - /** The Constant REL_NUXEO_SCHEMA_ROOT_ELEMENT. */ - final public static String REL_NUXEO_SCHEMA_ROOT_ELEMENT = "relationtype"; - - /** The Constant REL_NUXEO_DC_TITLE. */ - final public static String REL_NUXEO_DC_TITLE = "CollectionSpace-Relation"; - - /** The logger. */ - private static Logger logger = LoggerFactory - .getLogger(RelationsManagerNuxeoImpl.class); - - - /** - * Fill relation from doc model. - * - * @param relation the relation - * @param relDocModel the rel doc model - * - * @throws ClientException the client exception - */ - static public void fillRelationFromDocModel(Relation relation, DocumentModel relDocModel) - throws ClientException { - String xpathRoot = "/" + REL_NUXEO_SCHEMA_ROOT_ELEMENT + "/"; - Object valueObject = null; - - relation.setCsid(relDocModel.getId()); - - valueObject = relDocModel.getProperty(REL_NUXEO_SCHEMA_NAME, xpathRoot - + RelationJAXBSchema.DOCUMENT_ID_1); - relation.setDocumentId1((String) valueObject); - - valueObject = relDocModel.getProperty(REL_NUXEO_SCHEMA_NAME, xpathRoot - + RelationJAXBSchema.DOCUMENT_TYPE_1); - relation.setDocumentType1((String) valueObject); - - valueObject = relDocModel.getProperty(REL_NUXEO_SCHEMA_NAME, xpathRoot - + RelationJAXBSchema.DOCUMENT_ID_2); - relation.setDocumentId2((String) valueObject); - - valueObject = relDocModel.getProperty(REL_NUXEO_SCHEMA_NAME, xpathRoot - + RelationJAXBSchema.DOCUMENT_TYPE_2); - relation.setDocumentType2((String) valueObject); - - valueObject = relDocModel.getProperty(REL_NUXEO_SCHEMA_NAME, xpathRoot - + RelationJAXBSchema.RELATIONSHIP_TYPE); - relation.setRelationshipType(RelationshipType - .fromValue((String) valueObject)); - - if (logger.isDebugEnabled() == true) { - System.out.println("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv"); - System.out.println(relation.toString()); - System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"); - } - } - - /** - * Fill relation list item from doc model. - * - * @param relationListItem the relation list item - * @param relDocModel the rel doc model - * - * @throws DocumentException the document exception - */ - static public void fillRelationListItemFromDocModel(RelationListItem relationListItem, - DocumentModel relDocModel) - throws DocumentException { - - try { - relationListItem.setCsid( - relDocModel.getId()); - relationListItem.setUri( - getRelURL(CS_RELATION_SERVICE_NAME, relDocModel.getId())); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Caught exception in fillRelationListItemFromDocModel", e); - } - throw new DocumentException(e); - } - } - - /** - * Fill doc model list from relation list. - * - * @param relationList the relation list - * @param relDocModelList the rel doc model list - * - * @throws Exception the exception - */ - static public void fillDocModelListFromRelationList(RelationList relationList, - DocumentModelList relDocModelList) - throws Exception { - } - - /** - * Fill doc model from relation. - * - * @param p the p - * @param relDocModel the rel doc model - * - * @throws Exception the exception - */ - static public void fillDocModelFromRelation(Relation p, DocumentModel relDocModel) - throws Exception { - - // set the DublinCore title (this works) - relDocModel.setPropertyValue("dublincore:title", "default title"); - - // // set value for element - // try { - // relDocModel.setProperty("relation", "/relationtype/documentId1", - // "docId1"); - // } catch (Exception x) { - // x.printStackTrace(); - // } - - String xpathRoot = "/" + REL_NUXEO_SCHEMA_ROOT_ELEMENT + "/"; - if (p.getDocumentId1() != null) { - String property = xpathRoot + RelationJAXBSchema.DOCUMENT_ID_1; - relDocModel.setProperty(REL_NUXEO_SCHEMA_NAME, property, p - .getDocumentId1()); - } - if (p.getDocumentType1() != null) { - String property = xpathRoot + RelationJAXBSchema.DOCUMENT_TYPE_1; - relDocModel.setProperty(REL_NUXEO_SCHEMA_NAME, property, p - .getDocumentType1()); - } - if (p.getDocumentId2() != null) { - String property = xpathRoot + RelationJAXBSchema.DOCUMENT_ID_2; - relDocModel.setProperty(REL_NUXEO_SCHEMA_NAME, property, p - .getDocumentId2()); - } - if (p.getDocumentType2() != null) { - String property = xpathRoot + "/" - + RelationJAXBSchema.DOCUMENT_TYPE_2; - relDocModel.setProperty(REL_NUXEO_SCHEMA_NAME, property, p - .getDocumentType2()); - } - - if (p.getRelationshipType() != null) { - String property = xpathRoot + RelationJAXBSchema.RELATIONSHIP_TYPE; - relDocModel.setProperty(REL_NUXEO_SCHEMA_NAME, property, p - .getRelationshipType().value()); - } - } - - /** - * Prints the document model. - * - * @param documentModel the document model - */ - static public void printDocumentModel(DocumentModel documentModel) { - System.out.println(documentModel); - } - - /** - * Describe document model. - * - * @param docModel the doc model - * - * @throws Exception the exception - */ - static private void describeDocumentModel(DocumentModel docModel) throws Exception { - String[] schemas = docModel.getDeclaredSchemas(); - for (int i = 0; schemas != null && i < schemas.length; i++) { - System.out.println("Schema-" + i + "=" + schemas[i]); - } - - DocumentPart[] parts = docModel.getParts(); - Map propertyValues = null; - for (int i = 0; parts != null && i < parts.length; i++) { - System.out.println("Part-" + i + " name =" + parts[i].getName()); - System.out.println("Part-" + i + " path =" + parts[i].getPath()); - System.out.println("Part-" + i + " schema =" + parts[i].getSchema().getName()); - propertyValues = parts[i].exportValues(); - } - - } - - /** - * Creates the relationship. - * - * @param nuxeoRepoSession the nuxeo repo session - * @param newRelation the new relation - * - * @return the document model - * - * @throws DocumentException the document exception - */ - static public DocumentModel createRelationship(Object nuxeoRepoSession, Relation newRelation) - throws DocumentException { - DocumentModel result = null; - RepositoryInstance repoSession = (RepositoryInstance)nuxeoRepoSession; - - try { - // get the Nuxeo 'Relations' workspace - DocumentModel workspaceModel = NuxeoUtils.getWorkspaceModel(repoSession, - CS_RELATION_SERVICE_NAME); - - String docType = REL_NUXEO_DOCTYPE; - String id = IdUtils.generateId("New " + docType); - - //create document model - String workspacePath = workspaceModel.getPathAsString(); - DocumentModel newRelDocModel = repoSession.createDocumentModel(workspacePath, id, docType); - - newRelation.setCsid(newRelDocModel.getId()); - fillDocModelFromRelation(newRelation, newRelDocModel); - - //create document with the new DocumentModel - result = repoSession.createDocument(newRelDocModel); - repoSession.save(); - } catch (Exception e) { - e.printStackTrace(); - throw new DocumentException(e); - } - - return result; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.common.RelationUtils#createRelationship(java.lang.Object, java.lang.String, java.lang.String, java.lang.String) - */ - public Relation createRelationship(Object nuxeoRepoSession, String subjectCsid, String predicate, - String objectCsid) throws DocumentException { - Relation result = null; - RepositoryInstance repoSession = (RepositoryInstance)nuxeoRepoSession; - - Relation temp = new Relation(); - temp.setDocumentId1(subjectCsid); - temp.setRelationshipType(null); - temp.setDocumentId2(objectCsid); - createRelationship(repoSession, temp); - - return result; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.common.RelationUtils#getRelationships(java.lang.Object) - */ - public List getRelationships(Object nuxeoRepoSession) - throws DocumentException { - List result = null; - RepositoryInstance repoSession = (RepositoryInstance)nuxeoRepoSession; - - try { - DocumentModel relationWorkspace = NuxeoUtils.getWorkspaceModel( - repoSession, CS_RELATION_SERVICE_NAME); - DocumentModelList children = repoSession.getChildren(relationWorkspace - .getRef()); - - result = new ArrayList(); - Relation relation = null; - for (DocumentModel child : children) { - relation = new Relation(); - fillRelationFromDocModel(relation, child); - result.add(relation); - } - } catch (Exception e) { - e.printStackTrace(); - throw new DocumentException(e); - } - - return result; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.common.RelationUtils#getRelationships(java.lang.Object, java.lang.String) - */ - public List getRelationships(Object nuxeoRepoSession, String csid) - throws DocumentException { - List result = null; - RepositoryInstance repoSession = (RepositoryInstance)nuxeoRepoSession; - - try { - DocumentModel relationWorkspace = NuxeoUtils.getWorkspaceModel( - repoSession, CS_RELATION_SERVICE_NAME); - DocumentModelList children = repoSession.getChildren(relationWorkspace - .getRef()); - - result = new ArrayList(); - Relation relation = null; - for (DocumentModel child : children) { - if ((isSubjectOfRelation(csid, child) == true) || - (isObjectOfRelation(csid, child) == true)) { - relation = new Relation(); - fillRelationFromDocModel(relation, child); - result.add(relation); - } - } - } catch (Exception e) { - e.printStackTrace(); - throw new DocumentException(e); - } - - return result; - } - - - /* (non-Javadoc) - * @see org.collectionspace.services.common.RelationUtils#getRelationships(java.lang.Object, java.lang.String, java.lang.String, java.lang.String) - */ - public List getRelationships(Object nuxeoRepoSession, - String subjectCsid, - String predicate, - String objectCsid) throws DocumentException { - List result = null; - RepositoryInstance repoSession = (RepositoryInstance)nuxeoRepoSession; - - try { - DocumentModel relationWorkspace = NuxeoUtils.getWorkspaceModel( - repoSession, CS_RELATION_SERVICE_NAME); - DocumentModelList children = repoSession.getChildren(relationWorkspace - .getRef()); - - result = new ArrayList(); - Relation relation = null; - for (DocumentModel child : children) { - if (isQueryMatch(child, subjectCsid, predicate, objectCsid) == true) { - relation = new Relation(); - fillRelationFromDocModel(relation, child); - result.add(relation); } - } - } catch (Exception e) { - e.printStackTrace(); - throw new DocumentException(e); - } - - return result; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.common.relation.RelationUtils#getQPropertyName(java.lang.String) - */ - public String getQPropertyName(String propertyName) { - return "/" + REL_NUXEO_SCHEMA_ROOT_ELEMENT + "/" + propertyName; - } - - /** - * Checks if is subject of relation. - * - * @param csid the csid - * @param documentModel the document model - * - * @return true, if is subject of relation - * - * @throws ClientException the client exception - */ - private boolean isSubjectOfRelation(String csid, DocumentModel documentModel) - throws ClientException { - boolean result = false; - String xpathRoot = "/" + REL_NUXEO_SCHEMA_ROOT_ELEMENT + "/"; - - Object valueObject = documentModel.getProperty(REL_NUXEO_SCHEMA_NAME, xpathRoot - + RelationJAXBSchema.DOCUMENT_ID_1); - if (valueObject != null && csid != null) { - String subjectID = (String) valueObject; - result = subjectID.equals(csid); - } - - return result; - } - - /** - * Checks if is object of relation. - * - * @param csid the csid - * @param documentModel the document model - * - * @return true, if is object of relation - * - * @throws ClientException the client exception - */ - private boolean isObjectOfRelation(String csid, DocumentModel documentModel) - throws ClientException { - boolean result = false; - String xpathRoot = "/" + REL_NUXEO_SCHEMA_ROOT_ELEMENT + "/"; - - Object valueObject = documentModel.getProperty(REL_NUXEO_SCHEMA_NAME, - xpathRoot + RelationJAXBSchema.DOCUMENT_ID_2); - if (valueObject != null && csid != null) { - String subjectID = (String) valueObject; - result = subjectID.equals(csid); - } - - return result; - } - - /** - * Checks if is predicate of relation. - * - * @param predicate the predicate - * @param documentModel the document model - * - * @return true, if is predicate of relation - * - * @throws ClientException the client exception - */ - private boolean isPredicateOfRelation(String predicate, - DocumentModel documentModel) throws ClientException { - boolean result = false; - String xpathRoot = "/" + REL_NUXEO_SCHEMA_ROOT_ELEMENT + "/"; - - Object valueObject = documentModel.getProperty(REL_NUXEO_SCHEMA_NAME, - xpathRoot + RelationJAXBSchema.RELATIONSHIP_TYPE); - if (valueObject != null && predicate != null) { - String relationType = (String) valueObject; - result = predicate.equalsIgnoreCase(relationType); - } - - return result; - } - - /** - * Gets the object from subject. - * - * @param csid the csid - * @param documentModel the document model - * - * @return the object from subject - * - * @throws ClientException the client exception - */ - private String getObjectFromSubject(String csid, DocumentModel documentModel) - throws ClientException { - String result = null; - String xpathRoot = "/" + REL_NUXEO_SCHEMA_ROOT_ELEMENT + "/"; - - Object valueObject = documentModel.getProperty(REL_NUXEO_SCHEMA_NAME, - xpathRoot + RelationJAXBSchema.DOCUMENT_ID_1); - if (valueObject != null) { - String subjectID = (String) valueObject; - if (subjectID.equals(csid) == true) { - valueObject = documentModel.getProperty(REL_NUXEO_SCHEMA_NAME, - xpathRoot + RelationJAXBSchema.DOCUMENT_ID_2); - if (valueObject != null) { - result = (String) valueObject; - } - } - } - - return result; - } - - /** - * Gets the document. - * - * @param relationList the relation list - * - * @return the document - * - * @throws DocumentException the document exception - */ - static public Document getDocument(List relationList) - throws DocumentException { - DOMDocumentFactory domfactory = new DOMDocumentFactory(); - DOMDocument result = (DOMDocument) domfactory.createDocument(); - - try { - // setup the root element - DOMElement root = (DOMElement) result - .createElement(RelationListItemJAXBSchema.REL_ROOT_ELEM_NAME); - result.setRootElement((org.dom4j.Element) root); - - // populate the document with child elements - for (Relation child : relationList) { - DOMElement el = (DOMElement) result.createElement(RelationJAXBSchema.REL_ROOT_ELEM_NAME); - el.setAttribute(RelationListItemJAXBSchema.CSID, child - .getCsid()); - el.setAttribute(RelationListItemJAXBSchema.URI, getRelURL( - CS_RELATION_SERVICE_NAME, child.getCsid())); - - if (logger.isDebugEnabled() == true) { - System.out.println(el.asXML()); - } - - root.appendChild(el); - } - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Caught exception ", e); - } - throw new DocumentException(e); - } - - if (logger.isDebugEnabled() == true) { - System.out.println(result.asXML()); - } - - return result; - } - - /** - * Checks if is query match. - * - * @param documentModel the document model - * @param subjectCsid the subject csid - * @param predicate the predicate - * @param objectCsid the object csid - * - * @return true, if is query match - * - * @throws ClientException the client exception - */ - public boolean isQueryMatch(DocumentModel documentModel, - String subjectCsid, - String predicate, - String objectCsid) throws DocumentException { - boolean result = true; - - try { - block: { - if (subjectCsid != null) { - if (isSubjectOfRelation(subjectCsid, documentModel) == false) { - result = false; - break block; - } - } - if (predicate != null) { - if (isPredicateOfRelation(predicate, documentModel) == false) { - result = false; - break block; - } - } - if (objectCsid != null) { - if (isObjectOfRelation(objectCsid, documentModel) == false) { - result = false; - break block; - } - } - } - } catch (ClientException e) { - if (logger.isDebugEnabled() == true) { - e.printStackTrace(); - } - throw new DocumentException(e); - } - - return result; - } - - /** - * Gets the rel url. - * - * @param repo the repo - * @param uuid the uuid - * - * @return the rel url - */ - private static String getRelURL(String repo, String uuid) { - return '/' + repo + '/' + uuid; - } - -} diff --git a/services/common/src/main/java/org/collectionspace/services/common/relation/nuxeo/RelationsUtils.java b/services/common/src/main/java/org/collectionspace/services/common/relation/nuxeo/RelationsUtils.java new file mode 100644 index 000000000..9a2684e3f --- /dev/null +++ b/services/common/src/main/java/org/collectionspace/services/common/relation/nuxeo/RelationsUtils.java @@ -0,0 +1,248 @@ +/** + * This document is a part of the source code and related artifacts + * for CollectionSpace, an open source collections management system + * for museums and related institutions: + + * http://www.collectionspace.org + * http://wiki.collectionspace.org + + * Copyright 2009 University of California at Berkeley + + * Licensed under the Educational Community License (ECL), Version 2.0. + * You may not use this file except in compliance with this License. + + * You may obtain a copy of the ECL 2.0 License at + + * https://source.collectionspace.org/collection-space/LICENSE.txt + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.collectionspace.services.common.relation.nuxeo; + +import java.util.Iterator; +import java.util.List; + +import org.collectionspace.services.common.relation.RelationJAXBSchema; +import org.collectionspace.services.common.repository.DocumentException; +import org.collectionspace.services.common.repository.DocumentWrapper; +import org.collectionspace.services.relation.RelationsCommonList; +import org.collectionspace.services.relation.RelationsCommonList.RelationListItem; +import org.nuxeo.ecm.core.api.ClientException; +import org.nuxeo.ecm.core.api.DocumentModel; +import org.nuxeo.ecm.core.api.DocumentModelList; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * RelationsUtils + * + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public class RelationsUtils { + + private static final Logger logger = LoggerFactory.getLogger(RelationsUtils.class); + + public static RelationsCommonList extractCommonPartList(DocumentWrapper wrapDoc, + String serviceContextPath) + throws Exception { + DocumentModelList docList = (DocumentModelList) wrapDoc.getWrappedObject(); + + RelationsCommonList relList = new RelationsCommonList(); + List list = relList.getRelationListItem(); + + //FIXME: iterating over a long list of documents is not a long term + //strategy...need to change to more efficient iterating in future + Iterator iter = docList.iterator(); + while(iter.hasNext()){ + DocumentModel docModel = iter.next(); + RelationListItem relationListItem = getRelationListItem(docModel, + serviceContextPath); + list.add(relationListItem); + } + return relList; + } + + public static RelationListItem getRelationListItem(DocumentModel docModel, + String serviceContextPath) throws Exception { + RelationListItem relationListItem = new RelationListItem(); + relationListItem.setUri(serviceContextPath + docModel.getId()); + relationListItem.setCsid(docModel.getId()); + return relationListItem; + } + + public static void fillDublinCoreObject(DocumentWrapper wrapDoc) throws Exception { + DocumentModel docModel = (DocumentModel) wrapDoc.getWrappedObject(); + //FIXME property setter should be dynamically set using schema inspection + //so it does not require hard coding + // a default title for the Dublin Core schema + docModel.setPropertyValue("dublincore:title", RelationConstants.NUXEO_DC_TITLE); + } + + /** + * Checks if is subject of relation. + * + * @param csid the csid + * @param documentModel the document model + * + * @return true, if is subject of relation + * + * @throws Exception + */ + private static boolean isSubjectOfRelation(String csid, DocumentModel documentModel) + throws Exception { + boolean result = false; + Object valueObject = documentModel.getProperty(RelationConstants.NUXEO_SCHEMA_NAME, RelationJAXBSchema.DOCUMENT_ID_1); + if(valueObject != null && csid != null){ + String subjectID = (String) valueObject; + result = subjectID.equals(csid); + } + + return result; + } + + /** + * Checks if is object of relation. + * + * @param csid the csid + * @param documentModel the document model + * + * @return true, if is object of relation + * + * @throws Exception + */ + private static boolean isObjectOfRelation(String csid, DocumentModel documentModel) + throws Exception { + boolean result = false; + + Object valueObject = documentModel.getProperty(RelationConstants.NUXEO_SCHEMA_NAME, + RelationJAXBSchema.DOCUMENT_ID_2); + if(valueObject != null && csid != null){ + String subjectID = (String) valueObject; + result = subjectID.equals(csid); + } + + return result; + } + + /** + * Checks if is predicate of relation. + * + * @param predicate the predicate + * @param documentModel the document model + * + * @return true, if is predicate of relation + * + * @throws Exception + */ + private static boolean isPredicateOfRelation(String predicate, + DocumentModel documentModel) throws Exception { + boolean result = false; + + Object valueObject = documentModel.getProperty(RelationConstants.NUXEO_SCHEMA_NAME, + RelationJAXBSchema.RELATIONSHIP_TYPE); + if(valueObject != null && predicate != null){ + String relationType = (String) valueObject; + result = predicate.equalsIgnoreCase(relationType); + } + + return result; + } + + /** + * Gets the object from subject. + * + * @param csid the csid + * @param documentModel the document model + * + * @return the object from subject + * + * @throws Exception + */ + private static String getObjectFromSubject(String csid, DocumentModel documentModel) + throws Exception { + String result = null; + + Object valueObject = documentModel.getProperty(RelationConstants.NUXEO_SCHEMA_NAME, + RelationJAXBSchema.DOCUMENT_ID_1); + if(valueObject != null){ + String subjectID = (String) valueObject; + if(subjectID.equals(csid) == true){ + valueObject = documentModel.getProperty(RelationConstants.NUXEO_SCHEMA_NAME, + RelationJAXBSchema.DOCUMENT_ID_2); + if(valueObject != null){ + result = (String) valueObject; + } + } + } + + return result; + } + + /** + * Checks if is query match. + * + * @param documentModel the document model + * @param subjectCsid the subject csid + * @param predicate the predicate + * @param objectCsid the object csid + * + * @return true, if is query match + * + * @throws ClientException the client exception + */ + public static boolean isQueryMatch(DocumentModel documentModel, + String subjectCsid, + String predicate, + String objectCsid) throws DocumentException { + boolean result = true; + + try{ + block: + { + if(subjectCsid != null){ + if(isSubjectOfRelation(subjectCsid, documentModel) == false){ + result = false; + break block; + } + } + if(predicate != null){ + if(isPredicateOfRelation(predicate, documentModel) == false){ + result = false; + break block; + } + } + if(objectCsid != null){ + if(isObjectOfRelation(objectCsid, documentModel) == false){ + result = false; + break block; + } + } + } + }catch(Exception e){ + if(logger.isDebugEnabled() == true){ + e.printStackTrace(); + } + throw new DocumentException(e); + } + + return result; + } + + /** + * Gets the rel url. + * + * @param repo the repo + * @param uuid the uuid + * + * @return the rel url + */ + private static String getRelURL(String repo, String uuid) { + return '/' + repo + '/' + uuid; + } +} + diff --git a/services/common/src/main/java/org/collectionspace/services/common/repository/DocumentHandler.java b/services/common/src/main/java/org/collectionspace/services/common/repository/DocumentHandler.java index 5afe00bcb..50774375a 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/repository/DocumentHandler.java +++ b/services/common/src/main/java/org/collectionspace/services/common/repository/DocumentHandler.java @@ -17,12 +17,8 @@ */ package org.collectionspace.services.common.repository; -import java.io.IOException; import java.util.Map; import org.collectionspace.services.common.context.ServiceContext; -import org.w3c.dom.Document; -import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; -import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; /** * diff --git a/services/common/src/main/java/org/collectionspace/services/common/repository/RepositoryClientFactory.java b/services/common/src/main/java/org/collectionspace/services/common/repository/RepositoryClientFactory.java index 0159fc0e8..5d8083cca 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/repository/RepositoryClientFactory.java +++ b/services/common/src/main/java/org/collectionspace/services/common/repository/RepositoryClientFactory.java @@ -23,7 +23,6 @@ */ package org.collectionspace.services.common.repository; -import java.lang.ClassLoader; import java.util.Hashtable; import org.collectionspace.services.common.RepositoryClientConfigType; import org.collectionspace.services.common.ServiceMain; diff --git a/services/common/src/main/java/org/collectionspace/services/nuxeo/CollectionSpaceServiceNuxeoImpl.java b/services/common/src/main/java/org/collectionspace/services/nuxeo/CollectionSpaceServiceNuxeoImpl.java deleted file mode 100644 index 4b49abc02..000000000 --- a/services/common/src/main/java/org/collectionspace/services/nuxeo/CollectionSpaceServiceNuxeoImpl.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright 2009 University of California at Berkeley - */ -package org.collectionspace.services.nuxeo; - -import java.io.IOException; - -import org.collectionspace.services.common.ServiceMain; -import org.collectionspace.services.common.repository.DocumentNotFoundException; -import org.collectionspace.services.nuxeo.client.rest.NuxeoRESTClient; -import org.collectionspace.services.nuxeo.client.java.NuxeoConnector; -import org.collectionspace.services.nuxeo.util.NuxeoUtils; - -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.dom.DOMDocument; -import org.dom4j.dom.DOMDocumentFactory; - -import org.w3c.dom.DOMException; -import org.w3c.dom.Element; - -import org.nuxeo.ecm.core.api.DocumentModel; -import org.nuxeo.ecm.core.api.DocumentModelList; -import org.nuxeo.ecm.core.api.DocumentRef; -import org.nuxeo.ecm.core.api.IdRef; -import org.nuxeo.ecm.core.api.ClientException; -import org.nuxeo.ecm.core.api.repository.RepositoryInstance; -import org.nuxeo.ecm.core.client.NuxeoClient; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author remillet - * - */ -public abstract class CollectionSpaceServiceNuxeoImpl { - - - protected Logger logger = LoggerFactory - .getLogger(CollectionSpaceServiceNuxeoImpl.class); - -// public NuxeoRESTClient getClient() { -// NuxeoRESTClient nxClient = new NuxeoRESTClient(CS_NUXEO_URI); -// -// nxClient.setAuthType(NuxeoRESTClient.AUTH_TYPE_BASIC); -// nxClient.setBasicAuthentication("Administrator", "Administrator"); -// -// return nxClient; -// } - - - protected RepositoryInstance getRepositorySession() throws Exception { - // FIXME: is it possible to reuse repository session? - // Authentication failures happen while trying to reuse the session - NuxeoClient client = NuxeoConnector.getInstance().getClient(); - RepositoryInstance repoSession = client.openRepository(); - if (logger.isDebugEnabled()) { - logger.debug("getRepository() repository root: " - + repoSession.getRootDocument()); - } - return repoSession; - } - - protected void releaseRepositorySession(RepositoryInstance repoSession) { - try { - NuxeoClient client = NuxeoConnector.getInstance().getClient(); - // release session - client.releaseRepository(repoSession); - } catch (Exception e) { - logger.error("Could not close the repository session", e); - // no need to throw this service specific exception - } - } - -} diff --git a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/DocumentModelHandler.java b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/DocumentModelHandler.java index 977d31b31..4c57ab22a 100644 --- a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/DocumentModelHandler.java +++ b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/DocumentModelHandler.java @@ -23,26 +23,12 @@ */ package org.collectionspace.services.nuxeo.client.java; -import java.io.InputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import javax.ws.rs.core.MediaType; import org.collectionspace.services.common.repository.DocumentWrapper; import org.collectionspace.services.common.repository.AbstractDocumentHandler; -import org.collectionspace.services.common.repository.BadRequestException; -import org.collectionspace.services.common.repository.DocumentUtils; -import org.collectionspace.services.common.service.ObjectPartType; import org.collectionspace.services.nuxeo.client.*; -import org.jboss.resteasy.plugins.providers.multipart.InputPart; -import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; -import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.repository.RepositoryInstance; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; /** * DocumentModelHandler is a base abstract Nuxeo document handler @@ -95,76 +81,16 @@ public abstract class DocumentModelHandler } @Override - public void completeUpdate(DocumentWrapper wrapDoc) throws Exception { - DocumentModel docModel = (DocumentModel) wrapDoc.getWrappedObject(); - //return at least those document part(s) that were received - Map partsMetaMap = getServiceContext().getPartsMetadata(); - List inputParts = getServiceContext().getInput().getParts(); - for(InputPart part : inputParts){ - String partLabel = part.getHeaders().getFirst("label"); - ObjectPartType partMeta = partsMetaMap.get(partLabel); - extractObject(docModel, partLabel, partMeta); - } - } + public abstract void completeUpdate(DocumentWrapper wrapDoc) throws Exception; @Override - public void extractAllParts(DocumentWrapper wrapDoc) throws Exception { - - DocumentModel docModel = (DocumentModel) wrapDoc.getWrappedObject(); - String[] schemas = docModel.getDeclaredSchemas(); - Map partsMetaMap = getServiceContext().getPartsMetadata(); - for(String schema : schemas){ - ObjectPartType partMeta = partsMetaMap.get(schema); - if(partMeta == null){ - continue; //unknown part, ignore - } - extractObject(docModel, schema, partMeta); - } - } + public abstract void extractAllParts(DocumentWrapper wrapDoc) throws Exception; @Override public abstract T extractCommonPart(DocumentWrapper wrapDoc) throws Exception; @Override - public void fillAllParts(DocumentWrapper wrapDoc) throws Exception { - - //TODO filling extension parts should be dynamic - //Nuxeo APIs lack to support stream/byte[] input, get/setting properties is - //not an ideal way of populating objects. - DocumentModel docModel = (DocumentModel) wrapDoc.getWrappedObject(); - MultipartInput input = getServiceContext().getInput(); - if(input.getParts().isEmpty()){ - String msg = "No payload found!"; - logger.error(msg + "Ctx=" + getServiceContext().toString()); - throw new BadRequestException(msg); - } - - Map partsMetaMap = getServiceContext().getPartsMetadata(); - - //iterate over parts received and fill those parts - List inputParts = input.getParts(); - for(InputPart part : inputParts){ - - String partLabel = part.getHeaders().getFirst("label"); - //skip if the part is not in metadata - if(!partsMetaMap.containsKey(partLabel)){ - continue; - } - InputStream payload = part.getBody(InputStream.class, null); - - //check if this is an xml part - if(part.getMediaType().equals(MediaType.APPLICATION_XML_TYPE)){ - if(payload != null){ - Document document = DocumentUtils.parseDocument(payload); - //TODO: callback to handler if registered to validate the - //document - Map objectProps = DocumentUtils.parseProperties(document); - docModel.setProperties(partLabel, objectProps); - } - } - }//rof - - } + public abstract void fillAllParts(DocumentWrapper wrapDoc) throws Exception; @Override public abstract void fillCommonPart(T obj, DocumentWrapper wrapDoc) throws Exception; @@ -190,32 +116,4 @@ public abstract class DocumentModelHandler @Override public abstract String getDocumentType(); - /** - * extractObject extracts an XML object from given DocumentModel - * @param docModel - * @param schema of the object to extract - * @param partMeta metadata for the object to extract - * @throws Exception - */ - protected void extractObject(DocumentModel docModel, String schema, ObjectPartType partMeta) - throws Exception { - MediaType mt = MediaType.valueOf(partMeta.getContent().getContentType()); - if(mt.equals(MediaType.APPLICATION_XML_TYPE)){ - Map objectProps = docModel.getProperties(schema); - //unqualify properties before sending the doc over the wire (to save bandwidh) - //FIXME: is there a better way to avoid duplication of a collection? - Map unQObjectProperties = new HashMap(); - Set> qualifiedEntries = objectProps.entrySet(); - for(Entry entry : qualifiedEntries){ - String unqProp = getUnQProperty(entry.getKey()); - unQObjectProperties.put(unqProp, entry.getValue()); - } - Document doc = DocumentUtils.buildDocument(partMeta, schema, unQObjectProperties); - if(logger.isDebugEnabled()){ - DocumentUtils.writeDocument(doc, System.out); - } - getServiceContext().addOutputPart(schema, doc, partMeta.getContent().getContentType()); - } //TODO: handle other media types - } - } diff --git a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/RemoteDocumentModelHandler.java b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/RemoteDocumentModelHandler.java new file mode 100644 index 000000000..5c2fb152c --- /dev/null +++ b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/RemoteDocumentModelHandler.java @@ -0,0 +1,169 @@ +/** + * This document is a part of the source code and related artifacts + * for CollectionSpace, an open source collections management system + * for museums and related institutions: + + * http://www.collectionspace.org + * http://wiki.collectionspace.org + + * Copyright 2009 University of California at Berkeley + + * Licensed under the Educational Community License (ECL), Version 2.0. + * You may not use this file except in compliance with this License. + + * You may obtain a copy of the ECL 2.0 License at + + * https://source.collectionspace.org/collection-space/LICENSE.txt + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.collectionspace.services.nuxeo.client.java; + +import java.io.InputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import javax.ws.rs.core.MediaType; +import org.collectionspace.services.common.context.RemoteServiceContext; +import org.collectionspace.services.common.context.ServiceContext; +import org.collectionspace.services.common.repository.BadRequestException; +import org.collectionspace.services.common.repository.DocumentUtils; +import org.collectionspace.services.common.repository.DocumentWrapper; +import org.collectionspace.services.common.service.ObjectPartType; +import org.jboss.resteasy.plugins.providers.multipart.InputPart; +import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; +import org.nuxeo.ecm.core.api.DocumentModel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; + +/** + * RemoteDocumentModelHandler + * + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public abstract class RemoteDocumentModelHandler + extends DocumentModelHandler { + + private final Logger logger = LoggerFactory.getLogger(RemoteDocumentModelHandler.class); + + @Override + public void setServiceContext(ServiceContext ctx) { + if(ctx instanceof RemoteServiceContext){ + super.setServiceContext(ctx); + } else { + throw new IllegalArgumentException("setServiceContext requires instance of " + + RemoteServiceContext.class.getName()); + } + } + + @Override + public abstract String getDocumentType(); + + @Override + public void completeUpdate(DocumentWrapper wrapDoc) throws Exception { + DocumentModel docModel = (DocumentModel) wrapDoc.getWrappedObject(); + //return at least those document part(s) that were received + Map partsMetaMap = getServiceContext().getPartsMetadata(); + RemoteServiceContext ctx = (RemoteServiceContext) getServiceContext(); + List inputParts = ctx.getInput().getParts(); + for(InputPart part : inputParts){ + String partLabel = part.getHeaders().getFirst("label"); + ObjectPartType partMeta = partsMetaMap.get(partLabel); + extractPart(docModel, partLabel, partMeta); + } + } + + @Override + public void extractAllParts(DocumentWrapper wrapDoc) throws Exception { + + DocumentModel docModel = (DocumentModel) wrapDoc.getWrappedObject(); + String[] schemas = docModel.getDeclaredSchemas(); + Map partsMetaMap = getServiceContext().getPartsMetadata(); + for(String schema : schemas){ + ObjectPartType partMeta = partsMetaMap.get(schema); + if(partMeta == null){ + continue; //unknown part, ignore + } + extractPart(docModel, schema, partMeta); + } + } + + @Override + public void fillAllParts(DocumentWrapper wrapDoc) throws Exception { + + //TODO filling extension parts should be dynamic + //Nuxeo APIs lack to support stream/byte[] input, get/setting properties is + //not an ideal way of populating objects. + DocumentModel docModel = (DocumentModel) wrapDoc.getWrappedObject(); + RemoteServiceContext ctx = (RemoteServiceContext) getServiceContext(); + MultipartInput input = ctx.getInput(); + if(input.getParts().isEmpty()){ + String msg = "No payload found!"; + logger.error(msg + "Ctx=" + getServiceContext().toString()); + throw new BadRequestException(msg); + } + + Map partsMetaMap = getServiceContext().getPartsMetadata(); + + //iterate over parts received and fill those parts + List inputParts = input.getParts(); + for(InputPart part : inputParts){ + + String partLabel = part.getHeaders().getFirst("label"); + //skip if the part is not in metadata + if(!partsMetaMap.containsKey(partLabel)){ + continue; + } + InputStream payload = part.getBody(InputStream.class, null); + + //check if this is an xml part + if(part.getMediaType().equals(MediaType.APPLICATION_XML_TYPE)){ + if(payload != null){ + Document document = DocumentUtils.parseDocument(payload); + //TODO: callback to handler if registered to validate the + //document + Map objectProps = DocumentUtils.parseProperties(document); + docModel.setProperties(partLabel, objectProps); + } + } + }//rof + + } + + /** + * extractPart extracts an XML object from given DocumentModel + * @param docModel + * @param schema of the object to extract + * @param partMeta metadata for the object to extract + * @throws Exception + */ + protected void extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta) + throws Exception { + MediaType mt = MediaType.valueOf(partMeta.getContent().getContentType()); + if(mt.equals(MediaType.APPLICATION_XML_TYPE)){ + Map objectProps = docModel.getProperties(schema); + //unqualify properties before sending the doc over the wire (to save bandwidh) + //FIXME: is there a better way to avoid duplication of a collection? + Map unQObjectProperties = new HashMap(); + Set> qualifiedEntries = objectProps.entrySet(); + for(Entry entry : qualifiedEntries){ + String unqProp = getUnQProperty(entry.getKey()); + unQObjectProperties.put(unqProp, entry.getValue()); + } + Document doc = DocumentUtils.buildDocument(partMeta, schema, unQObjectProperties); + if(logger.isDebugEnabled()){ + DocumentUtils.writeDocument(doc, System.out); + } + RemoteServiceContext ctx = (RemoteServiceContext) getServiceContext(); + ctx.addOutputPart(schema, doc, partMeta.getContent().getContentType()); + } //TODO: handle other media types + } +} diff --git a/services/common/src/main/java/org/collectionspace/services/nuxeo/util/NuxeoUtils.java b/services/common/src/main/java/org/collectionspace/services/nuxeo/util/NuxeoUtils.java index d27869ea7..90b1935b8 100644 --- a/services/common/src/main/java/org/collectionspace/services/nuxeo/util/NuxeoUtils.java +++ b/services/common/src/main/java/org/collectionspace/services/nuxeo/util/NuxeoUtils.java @@ -21,8 +21,9 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.Serializable; +import java.util.Map; import org.collectionspace.services.common.repository.DocumentException; -import org.collectionspace.services.common.ServiceMain; import org.dom4j.Document; import org.dom4j.io.SAXReader; @@ -32,6 +33,7 @@ import org.nuxeo.ecm.core.api.ClientException; import org.nuxeo.ecm.core.api.repository.RepositoryInstance; import org.nuxeo.ecm.core.api.DocumentRef; import org.nuxeo.ecm.core.api.IdRef; +import org.nuxeo.ecm.core.api.model.DocumentPart; import org.nuxeo.ecm.core.io.DocumentPipe; import org.nuxeo.ecm.core.io.DocumentReader; import org.nuxeo.ecm.core.io.DocumentWriter; @@ -175,4 +177,21 @@ public class NuxeoUtils { return result; } + + public static void printDocumentModel(DocumentModel docModel) throws Exception { + String[] schemas = docModel.getDeclaredSchemas(); + for(int i = 0; schemas != null && i < schemas.length; i++){ + logger.debug("Schema-" + i + "=" + schemas[i]); + } + + DocumentPart[] parts = docModel.getParts(); + Map propertyValues = null; + for(int i = 0; parts != null && i < parts.length; i++){ + logger.debug("Part-" + i + " name =" + parts[i].getName()); + logger.debug("Part-" + i + " path =" + parts[i].getPath()); + logger.debug("Part-" + i + " schema =" + parts[i].getSchema().getName()); + propertyValues = parts[i].exportValues(); + } + + } } diff --git a/services/common/src/main/resources/relation.xsd b/services/common/src/main/resources/relations-common.xsd similarity index 89% rename from services/common/src/main/resources/relation.xsd rename to services/common/src/main/resources/relations-common.xsd index a1da1ecf1..8bbc6587c 100644 --- a/services/common/src/main/resources/relation.xsd +++ b/services/common/src/main/resources/relations-common.xsd @@ -15,13 +15,13 @@ --> - + @@ -48,7 +48,7 @@ - + diff --git a/services/intake/service/src/main/java/org/collectionspace/services/intake/IntakeResource.java b/services/intake/service/src/main/java/org/collectionspace/services/intake/IntakeResource.java index 3a1dd56e3..0c7d425e1 100644 --- a/services/intake/service/src/main/java/org/collectionspace/services/intake/IntakeResource.java +++ b/services/intake/service/src/main/java/org/collectionspace/services/intake/IntakeResource.java @@ -43,6 +43,7 @@ import org.collectionspace.services.intake.IntakesCommonList.*; import org.collectionspace.services.intake.nuxeo.IntakeHandlerFactory; import org.collectionspace.services.common.ClientType; import org.collectionspace.services.common.ServiceMain; +import org.collectionspace.services.common.context.RemoteServiceContext; import org.collectionspace.services.common.context.ServiceContext; import org.collectionspace.services.common.repository.DocumentNotFoundException; import org.collectionspace.services.common.repository.DocumentHandler; @@ -72,7 +73,7 @@ public class IntakeResource extends AbstractCollectionSpaceResource { } @Override - public DocumentHandler createDocumentHandler(ServiceContext ctx) throws Exception { + public DocumentHandler createDocumentHandler(RemoteServiceContext ctx) throws Exception { DocumentHandler docHandler = IntakeHandlerFactory.getInstance().getHandler( ctx.getRepositoryClientType().toString()); docHandler.setServiceContext(ctx); @@ -88,7 +89,7 @@ public class IntakeResource extends AbstractCollectionSpaceResource { @POST public Response createIntake(MultipartInput input) { try{ - ServiceContext ctx = createServiceContext(input); + RemoteServiceContext ctx = createServiceContext(input); DocumentHandler handler = createDocumentHandler(ctx); String csid = getRepositoryClient(ctx).create(ctx, handler); //intakeObject.setCsid(csid); @@ -122,7 +123,7 @@ public class IntakeResource extends AbstractCollectionSpaceResource { } MultipartOutput result = null; try{ - ServiceContext ctx = createServiceContext(null); + RemoteServiceContext ctx = createServiceContext(null); DocumentHandler handler = createDocumentHandler(ctx); getRepositoryClient(ctx).get(ctx, csid, handler); result = ctx.getOutput(); @@ -156,7 +157,7 @@ public class IntakeResource extends AbstractCollectionSpaceResource { public IntakesCommonList getIntakeList(@Context UriInfo ui) { IntakesCommonList intakeObjectList = new IntakesCommonList(); try{ - ServiceContext ctx = createServiceContext(null); + RemoteServiceContext ctx = createServiceContext(null); DocumentHandler handler = createDocumentHandler(ctx); getRepositoryClient(ctx).getAll(ctx, handler); intakeObjectList = (IntakesCommonList) handler.getCommonPartList(); @@ -188,7 +189,7 @@ public class IntakeResource extends AbstractCollectionSpaceResource { } MultipartOutput result = null; try{ - ServiceContext ctx = createServiceContext(theUpdate); + RemoteServiceContext ctx = createServiceContext(theUpdate); DocumentHandler handler = createDocumentHandler(ctx); getRepositoryClient(ctx).update(ctx, csid, handler); result = ctx.getOutput(); diff --git a/services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeDocumentModelHandler.java b/services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeDocumentModelHandler.java index 71f44b007..78e5834fb 100644 --- a/services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeDocumentModelHandler.java +++ b/services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeDocumentModelHandler.java @@ -27,12 +27,13 @@ import java.util.Iterator; import java.util.List; import org.collectionspace.services.IntakeJAXBSchema; +import org.collectionspace.services.common.repository.DocumentHandler.Action; import org.collectionspace.services.common.repository.DocumentWrapper; import org.collectionspace.services.intake.IntakesCommon; import org.collectionspace.services.intake.IntakesCommonList; import org.collectionspace.services.intake.IntakesCommonList.IntakeListItem; -import org.collectionspace.services.nuxeo.client.java.DocumentModelHandler; +import org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandler; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.DocumentModelList; import org.slf4j.Logger; @@ -45,7 +46,7 @@ import org.slf4j.LoggerFactory; * $LastChangedDate: $ */ public class IntakeDocumentModelHandler - extends DocumentModelHandler { + extends RemoteDocumentModelHandler { private final Logger logger = LoggerFactory.getLogger(IntakeDocumentModelHandler.class); /** diff --git a/services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeHandlerFactory.java b/services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeHandlerFactory.java index aaa4374e1..077b226a9 100644 --- a/services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeHandlerFactory.java +++ b/services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeHandlerFactory.java @@ -47,9 +47,7 @@ public class IntakeHandlerFactory { public DocumentHandler getHandler(String clientType) { if(ClientType.JAVA.toString().equals(clientType)){ return new IntakeDocumentModelHandler(); - } else if(ClientType.REST.toString().equals(clientType)) { - return new IntakeRepresenationHandler(); - } + } throw new IllegalArgumentException("Not supported client=" + clientType); } } diff --git a/services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeRepresenationHandler.java b/services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeRepresenationHandler.java deleted file mode 100644 index 628114c52..000000000 --- a/services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeRepresenationHandler.java +++ /dev/null @@ -1,264 +0,0 @@ -/** - * This document is a part of the source code and related artifacts - * for CollectionSpace, an open source collections management system - * for museums and related institutions: - - * http://www.collectionspace.org - * http://wiki.collectionspace.org - - * Copyright 2009 University of California at Berkeley - - * Licensed under the Educational Community License (ECL), Version 2.0. - * You may not use this file except in compliance with this License. - - * You may obtain a copy of the ECL 2.0 License at - - * https://source.collectionspace.org/collection-space/LICENSE.txt - - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.collectionspace.services.intake.nuxeo; - -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.collectionspace.services.IntakeJAXBSchema; -import org.collectionspace.services.common.repository.DocumentWrapper; -import org.collectionspace.services.intake.IntakesCommon; -import org.collectionspace.services.intake.IntakesCommonList; -import org.collectionspace.services.intake.IntakesCommonList.IntakeListItem; -import org.collectionspace.services.nuxeo.client.rest.RepresentationHandler; -import org.dom4j.Document; -import org.dom4j.Element; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * IntakeDocumentModelHandler - * - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ -public class IntakeRepresenationHandler - extends RepresentationHandler { - - private final Logger logger = LoggerFactory.getLogger(IntakeRepresenationHandler.class); - /** - * intakeObj is used to stash JAXB object to use when handle is called - * for Action.CREATE, Action.UPDATE or Action.GET - */ - private IntakesCommon intake; - /** - * intakeListObject is stashed when handle is called - * for ACTION.GET_ALL - */ - private IntakesCommonList intakeList; - - @Override - public void prepare(Action action) throws Exception { - switch(action){ - case CREATE: - case UPDATE: - prepare(); - } - } - - private void prepare() { - Map queryParams = getQueryParams(); - IntakesCommon intakeObject = getCommonPart(); - if(intakeObject.getCurrentOwner() != null){ - queryParams.put(IntakeConstants.NUXEO_SCHEMA_NAME + ":" + - IntakeJAXBSchema.CURRENT_OWNER, intakeObject.getCurrentOwner()); - } - - if(intakeObject.getDepositor() != null){ - queryParams.put(IntakeConstants.NUXEO_SCHEMA_NAME + ":" + - IntakeJAXBSchema.DEPOSITOR, intakeObject.getDepositor()); - } - - if(intakeObject.getDepositorsRequirements() != null){ - queryParams.put(IntakeConstants.NUXEO_SCHEMA_NAME + ":" + - IntakeJAXBSchema.DEPOSITORS_REQUIREMENTS, intakeObject.getDepositorsRequirements()); - } - - if(intakeObject.getEntryDate() != null){ - queryParams.put(IntakeConstants.NUXEO_SCHEMA_NAME + ":" + - IntakeJAXBSchema.ENTRY_DATE, intakeObject.getEntryDate()); - } - - if(intakeObject.getEntryMethod() != null){ - queryParams.put(IntakeConstants.NUXEO_SCHEMA_NAME + ":" + - IntakeJAXBSchema.ENTRY_METHOD, intakeObject.getEntryMethod()); - } - - if(intakeObject.getEntryNote() != null){ - queryParams.put(IntakeConstants.NUXEO_SCHEMA_NAME + ":" + - IntakeJAXBSchema.ENTRY_NOTE, intakeObject.getEntryNote()); - } - - if(intakeObject.getEntryNumber() != null){ - queryParams.put(IntakeConstants.NUXEO_SCHEMA_NAME + ":" + - IntakeJAXBSchema.ENTRY_NUMBER, intakeObject.getEntryNumber()); - } - - if(intakeObject.getEntryReason() != null){ - queryParams.put(IntakeConstants.NUXEO_SCHEMA_NAME + ":" + - IntakeJAXBSchema.ENTRY_REASON, intakeObject.getEntryReason()); - } - - if(intakeObject.getPackingNote() != null){ - queryParams.put(IntakeConstants.NUXEO_SCHEMA_NAME + ":" + - IntakeJAXBSchema.PACKING_NOTE, intakeObject.getPackingNote()); - } - - if(intakeObject.getReturnDate() != null){ - queryParams.put(IntakeConstants.NUXEO_SCHEMA_NAME + ":" + - IntakeJAXBSchema.RETURN_DATE, intakeObject.getReturnDate()); - } - } - - @Override - public IntakesCommon extractCommonPart(DocumentWrapper wrapDoc) - throws Exception { - Document document = (Document) wrapDoc.getWrappedObject(); - IntakesCommon intakeObj = new IntakesCommon(); - - //FIXME property get should be dynamically set using schema inspection - //so it does not require hard coding - Element root = document.getRootElement(); - - // TODO: recognize schema thru namespace uri - // Namespace ns = new Namespace("intakeObj", - // "http://collectionspace.org/intakeObj"); - - Iterator siter = root.elementIterator("schema"); - while(siter.hasNext()){ - - Element schemaElement = siter.next(); - if(logger.isDebugEnabled()){ - logger.debug("getCommonObject() populating Common Object"); - } - // TODO: recognize schema thru namespace uri - if(IntakeConstants.NUXEO_SCHEMA_NAME.equals(schemaElement.attribute("name").getValue())){ - Element ele = schemaElement.element(IntakeJAXBSchema.CURRENT_OWNER); - if(ele != null){ - intakeObj.setCurrentOwner((String) ele.getData()); - } - ele = schemaElement.element(IntakeJAXBSchema.DEPOSITOR); - if(ele != null){ - intakeObj.setDepositor((String) ele.getData()); - } - ele = schemaElement.element(IntakeJAXBSchema.DEPOSITORS_REQUIREMENTS); - if(ele != null){ - intakeObj.setDepositorsRequirements((String) ele.getData()); - } - ele = schemaElement.element(IntakeJAXBSchema.ENTRY_DATE); - if(ele != null){ - intakeObj.setEntryDate((String) ele.getData()); - } - ele = schemaElement.element(IntakeJAXBSchema.ENTRY_METHOD); - if(ele != null){ - intakeObj.setEntryMethod((String) ele.getData()); - } - ele = schemaElement.element(IntakeJAXBSchema.ENTRY_NOTE); - if(ele != null){ - intakeObj.setEntryNote((String) ele.getData()); - } - ele = schemaElement.element(IntakeJAXBSchema.ENTRY_NUMBER); - if(ele != null){ - intakeObj.setEntryNumber((String) ele.getData()); - } - ele = schemaElement.element(IntakeJAXBSchema.ENTRY_REASON); - if(ele != null){ - intakeObj.setEntryReason((String) ele.getData()); - } - ele = schemaElement.element(IntakeJAXBSchema.PACKING_NOTE); - if(ele != null){ - intakeObj.setPackingNote((String) ele.getData()); - } - ele = schemaElement.element(IntakeJAXBSchema.RETURN_DATE); - if(ele != null){ - intakeObj.setReturnDate((String) ele.getData()); - } - } - } - return intakeObj; - } - - @Override - public void fillCommonPart(IntakesCommon co, DocumentWrapper wrapDoc) - throws Exception { - //Nuxeo REST takes create/update through queryParams, nothing to do here - } - - @Override - public IntakesCommonList extractCommonPartList(DocumentWrapper wrapDoc) throws Exception { - Document document = (Document) wrapDoc.getWrappedObject(); - if(logger.isDebugEnabled()){ - logger.debug(document.asXML()); - } - IntakesCommonList intakeListObject = new IntakesCommonList(); - List list = intakeListObject.getIntakeListItem(); - Element root = document.getRootElement(); - for(Iterator i = root.elementIterator(); i.hasNext();){ - - Element element = (Element) i.next(); - if(logger.isDebugEnabled()){ - logger.debug(element.asXML()); - } - // set the intakeObj list item entity elements - IntakeListItem ilistItem = new IntakeListItem(); - ilistItem.setEntryNumber(element.attributeValue("entryNumber")); - String id = element.attributeValue("id"); - ilistItem.setCsid(id); - ilistItem.setUri("/intakes/" + id); - list.add(ilistItem); - } - return intakeListObject; - } - - - @Override - public IntakesCommon getCommonPart() { - return intake; - } - - @Override - public void setCommonPart(IntakesCommon obj) { - this.intake = obj; - } - - @Override - public IntakesCommonList getCommonPartList() { - return intakeList; - } - - @Override - public void setCommonPartList(IntakesCommonList obj) { - this.intakeList = obj; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getDocumentType() - */ - @Override - public String getDocumentType() { - return IntakeConstants.NUXEO_DOCTYPE; - } - - /** - * getQProperty converts the given property to qualified schema property - * @param prop - * @return - */ - @Override - public String getQProperty(String prop) { - return IntakeConstants.NUXEO_SCHEMA_NAME + ":" + prop; - } -} - diff --git a/services/pom.xml b/services/pom.xml index ec406fe07..8ee2b2af5 100644 --- a/services/pom.xml +++ b/services/pom.xml @@ -18,7 +18,7 @@ common authentication - + relation acquisition vocabulary diff --git a/services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/OSGI-INF/core-types-contrib.xml b/services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/OSGI-INF/core-types-contrib.xml index 2fe513f95..151b2c157 100644 --- a/services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/OSGI-INF/core-types-contrib.xml +++ b/services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/OSGI-INF/core-types-contrib.xml @@ -16,13 +16,13 @@ --> - + - + diff --git a/services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/schemas/relation.xsd b/services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/schemas/relations-common.xsd similarity index 76% rename from services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/schemas/relation.xsd rename to services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/schemas/relations-common.xsd index cbd7d0cd9..78e5fb47f 100644 --- a/services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/schemas/relation.xsd +++ b/services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/schemas/relations-common.xsd @@ -21,10 +21,6 @@ targetNamespace="http://collectionspace.org/relation/" version="0.1"> - - - - @@ -41,15 +37,14 @@ - - - - + + + + - - - + + diff --git a/services/relation/client/pom.xml b/services/relation/client/pom.xml index f05cbae5d..c1265e90c 100644 --- a/services/relation/client/pom.xml +++ b/services/relation/client/pom.xml @@ -33,11 +33,6 @@ 1.0 - - org.collectionspace.services - org.collectionspace.services.relation.service - 1.0 - org.testng @@ -93,7 +88,7 @@ log4j.configuration - log4j.xml + file:target/test-classes/log4j.properties diff --git a/services/relation/client/src/main/java/org/collectionspace/services/client/RelationClient.java b/services/relation/client/src/main/java/org/collectionspace/services/client/RelationClient.java index 952c0fa56..1014fb9cc 100644 --- a/services/relation/client/src/main/java/org/collectionspace/services/client/RelationClient.java +++ b/services/relation/client/src/main/java/org/collectionspace/services/client/RelationClient.java @@ -1,16 +1,14 @@ package org.collectionspace.services.client; -import javax.ws.rs.PathParam; -import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; -import org.collectionspace.services.relation.Relation; -import org.collectionspace.services.relation.RelationList; +import org.collectionspace.services.relation.RelationsCommonList; import org.jboss.resteasy.client.ProxyFactory; import org.jboss.resteasy.plugins.providers.RegisterBuiltin; import org.jboss.resteasy.client.ClientResponse; +import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; +import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; import org.jboss.resteasy.spi.ResteasyProviderFactory; /** @@ -53,11 +51,11 @@ public class RelationClient extends BaseServiceClient implements RelationProxy { * @return * @see org.collectionspace.hello.client.RelationProxy#getRelation() */ - public ClientResponse readList() { + public ClientResponse readList() { return relationProxy.readList(); } - public ClientResponse readList_SPO(String subjectCsid, + public ClientResponse readList_SPO(String subjectCsid, String predicate, String objectCsid) { return relationProxy.readList_SPO(subjectCsid, predicate, objectCsid); @@ -68,7 +66,7 @@ public class RelationClient extends BaseServiceClient implements RelationProxy { * @return * @see org.collectionspace.hello.client.RelationProxy#getRelation(java.lang.String) */ - public ClientResponse read(String csid) { + public ClientResponse read(String csid) { return relationProxy.read(csid); } @@ -77,8 +75,8 @@ public class RelationClient extends BaseServiceClient implements RelationProxy { * @return * @see org.collectionspace.hello.client.RelationProxy#createRelation(org.collectionspace.hello.Relation) */ - public ClientResponse create(Relation relation) { - return relationProxy.create(relation); + public ClientResponse create(MultipartOutput multipart) { + return relationProxy.create(multipart); } /** @@ -87,8 +85,8 @@ public class RelationClient extends BaseServiceClient implements RelationProxy { * @return * @see org.collectionspace.hello.client.RelationProxy#updateRelation(java.lang.Long, org.collectionspace.hello.Relation) */ - public ClientResponse update(String csid, Relation relation) { - return relationProxy.update(csid, relation); + public ClientResponse update(String csid, MultipartOutput multipart) { + return relationProxy.update(csid, multipart); } /** diff --git a/services/relation/client/src/main/java/org/collectionspace/services/client/RelationProxy.java b/services/relation/client/src/main/java/org/collectionspace/services/client/RelationProxy.java index 9a4d8fcde..d6e75f977 100644 --- a/services/relation/client/src/main/java/org/collectionspace/services/client/RelationProxy.java +++ b/services/relation/client/src/main/java/org/collectionspace/services/client/RelationProxy.java @@ -8,47 +8,48 @@ 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.Response; -import javax.ws.rs.core.UriInfo; -import org.collectionspace.services.relation.Relation; -import org.collectionspace.services.relation.RelationList; +import org.collectionspace.services.relation.RelationsCommonList; import org.jboss.resteasy.client.ClientResponse; +import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; +import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; /** * @version $Revision:$ */ @Path("/relations/") -@Produces({"application/xml"}) -@Consumes({"application/xml"}) +@Produces({"multipart/mixed"}) +@Consumes({"multipart/mixed"}) public interface RelationProxy { @GET - ClientResponse readList(); - - @GET - @Path("subject/{subjectCsid}/type/{predicate}/object/{objectCsid}") - ClientResponse readList_SPO(@PathParam("subjectCsid") String subjectCsid, - @PathParam("predicate") String predicate, - @PathParam("objectCsid") String objectCsid); + @Produces({"application/xml"}) + ClientResponse readList(); + + @GET + @Produces({"application/xml"}) + @Path("subject/{subjectCsid}/type/{predicate}/object/{objectCsid}") + ClientResponse readList_SPO(@PathParam("subjectCsid") String subjectCsid, + @PathParam("predicate") String predicate, + @PathParam("objectCsid") String objectCsid); //(C)reate @POST - ClientResponse create(Relation co); + ClientResponse create(MultipartOutput multipart); //(R)ead @GET @Path("/{csid}") - ClientResponse read(@PathParam("csid") String csid); + ClientResponse read(@PathParam("csid") String csid); //(U)pdate @PUT @Path("/{csid}") - ClientResponse update(@PathParam("csid") String csid, Relation co); + ClientResponse update(@PathParam("csid") String csid, MultipartOutput multipart); //(D)elete @DELETE @Path("/{csid}") ClientResponse delete(@PathParam("csid") String csid); -} \ No newline at end of file +} diff --git a/services/relation/client/src/test/java/org/collectionspace/services/client/test/RelationServiceTest.java b/services/relation/client/src/test/java/org/collectionspace/services/client/test/RelationServiceTest.java index 43fa7d9e0..26147f1d1 100644 --- a/services/relation/client/src/test/java/org/collectionspace/services/client/test/RelationServiceTest.java +++ b/services/relation/client/src/test/java/org/collectionspace/services/client/test/RelationServiceTest.java @@ -20,22 +20,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.collectionspace.services.client.test; import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; import org.collectionspace.services.client.RelationClient; -import org.collectionspace.services.client.test.ServiceRequestType; -import org.collectionspace.services.relation.Relation; -import org.collectionspace.services.relation.RelationList; +import org.collectionspace.services.relation.RelationsCommon; +import org.collectionspace.services.relation.RelationsCommonList; import org.collectionspace.services.relation.RelationshipType; import org.jboss.resteasy.client.ClientResponse; +import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; +import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; +import org.jboss.resteasy.plugins.providers.multipart.OutputPart; import org.testng.Assert; import org.testng.annotations.Test; @@ -50,14 +50,12 @@ public class RelationServiceTest extends AbstractServiceTest { private RelationClient client = new RelationClient(); final String SERVICE_PATH_COMPONENT = "relations"; - private String knownResourceId = null; + private String knownResourceId = null; // --------------------------------------------------------------- // CRUD tests : CREATE tests // --------------------------------------------------------------- - // Success outcomes - @Override @Test public void create() { @@ -69,8 +67,8 @@ public class RelationServiceTest extends AbstractServiceTest { // Submit the request to the service and store the response. String identifier = createIdentifier(); - Relation relation = createRelationInstance(identifier); - ClientResponse res = client.create(relation); + MultipartOutput multipart = createRelationInstance(identifier); + ClientResponse res = client.create(multipart); int statusCode = res.getStatus(); // Check the status code of the response: does it match @@ -80,12 +78,13 @@ public class RelationServiceTest extends AbstractServiceTest { // Does it exactly match the expected status code? verbose("create: status = " + statusCode); Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), - invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); // Store the ID returned from this create operation for // additional tests below. knownResourceId = extractId(res); + verbose("create: knownResourceId=" + knownResourceId); } @Override @@ -97,313 +96,323 @@ public class RelationServiceTest extends AbstractServiceTest { } // Failure outcomes - // Placeholders until the three tests below can be uncommented. // See Issue CSPACE-401. - public void createWithEmptyEntityBody() {} - public void createWithMalformedXml() {} - public void createWithWrongXmlSchema() {} + public void createWithEmptyEntityBody() { + } + + public void createWithMalformedXml() { + } -/* + public void createWithWrongXmlSchema() { + } + + /* @Override @Test(dependsOnMethods = {"create", "testSubmitRequest"}) public void createWithEmptyEntityBody() { - // Perform setup. - setupCreateWithEmptyEntityBody(); - - // Submit the request to the service and store the response. - String method = REQUEST_TYPE.httpMethodName(); - String url = getServiceRootURL(); - String mediaType = MediaType.APPLICATION_XML; - final String entity = ""; - int statusCode = submitRequest(method, url, mediaType, entity); - - // Check the status code of the response: does it match - // the expected response(s)? - verbose("createWithEmptyEntityBody url=" + url + " status=" + statusCode); - Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), - invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); + // Perform setup. + setupCreateWithEmptyEntityBody(); + + // Submit the request to the service and store the response. + String method = REQUEST_TYPE.httpMethodName(); + String url = getServiceRootURL(); + String mediaType = MediaType.APPLICATION_XML; + final String entity = ""; + int statusCode = submitRequest(method, url, mediaType, entity); + + // Check the status code of the response: does it match + // the expected response(s)? + verbose("createWithEmptyEntityBody url=" + url + " status=" + statusCode); + Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), + invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } @Override @Test(dependsOnMethods = {"create", "testSubmitRequest"}) public void createWithMalformedXml() { - // Perform setup. - setupCreateWithMalformedXml(); - - // Submit the request to the service and store the response. - String method = REQUEST_TYPE.httpMethodName(); - String url = getServiceRootURL(); - String mediaType = MediaType.APPLICATION_XML; - final String entity = MALFORMED_XML_DATA; // Constant from base class. - int statusCode = submitRequest(method, url, mediaType, entity); - - // Check the status code of the response: does it match - // the expected response(s)? - verbose("createWithMalformedXml url=" + url + " status=" + statusCode); - Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), - invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); + // Perform setup. + setupCreateWithMalformedXml(); + + // Submit the request to the service and store the response. + String method = REQUEST_TYPE.httpMethodName(); + String url = getServiceRootURL(); + String mediaType = MediaType.APPLICATION_XML; + final String entity = MALFORMED_XML_DATA; // Constant from base class. + int statusCode = submitRequest(method, url, mediaType, entity); + + // Check the status code of the response: does it match + // the expected response(s)? + verbose("createWithMalformedXml url=" + url + " status=" + statusCode); + Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), + invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } @Override @Test(dependsOnMethods = {"create", "testSubmitRequest"}) public void createWithWrongXmlSchema() { - // Perform setup. - setupCreateWithWrongXmlSchema(); - - // Submit the request to the service and store the response. - String method = REQUEST_TYPE.httpMethodName(); - String url = getServiceRootURL(); - String mediaType = MediaType.APPLICATION_XML; - final String entity = WRONG_XML_SCHEMA_DATA; - int statusCode = submitRequest(method, url, mediaType, entity); - - // Check the status code of the response: does it match - // the expected response(s)? - verbose("createWithWrongSchema url=" + url + " status=" + statusCode); - Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), - invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); + // Perform setup. + setupCreateWithWrongXmlSchema(); + + // Submit the request to the service and store the response. + String method = REQUEST_TYPE.httpMethodName(); + String url = getServiceRootURL(); + String mediaType = MediaType.APPLICATION_XML; + final String entity = WRONG_XML_SCHEMA_DATA; + int statusCode = submitRequest(method, url, mediaType, entity); + + // Check the status code of the response: does it match + // the expected response(s)? + verbose("createWithWrongSchema url=" + url + " status=" + statusCode); + Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), + invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } -*/ - - + */ // --------------------------------------------------------------- // CRUD tests : READ tests // --------------------------------------------------------------- - // Success outcomes - @Override @Test(dependsOnMethods = {"create"}) public void read() { - + // Perform setup. setupRead(); // Submit the request to the service and store the response. - ClientResponse res = client.read(knownResourceId); + ClientResponse res = client.read(knownResourceId); int statusCode = res.getStatus(); - + // Check the status code of the response: does it match // the expected response(s)? verbose("read: status = " + statusCode); Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), - invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); // Verify that the resource identifier - Relation returnedRelation = res.getEntity(); - Assert.assertEquals(returnedRelation.getCsid(), knownResourceId); + //FIXME: remove the following try catch once Aron fixes signatures + try{ + MultipartInput input = (MultipartInput) res.getEntity(); + RelationsCommon relation = (RelationsCommon) extractPart(input, + getCommonPartName(), RelationsCommon.class); + Assert.assertNotNull(relation); + }catch(Exception e){ + throw new RuntimeException(e); + } } // Failure outcomes - @Override @Test(dependsOnMethods = {"read"}) public void readNonExistent() { // Perform setup. setupReadNonExistent(); - + // Submit the request to the service and store the response. - ClientResponse res = client.read(NON_EXISTENT_ID); + ClientResponse res = client.read(NON_EXISTENT_ID); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? verbose("readNonExistent: status = " + res.getStatus()); Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), - invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } - // --------------------------------------------------------------- // CRUD tests : READ_LIST tests // --------------------------------------------------------------- - // Success outcomes - @Override - @Test(dependsOnMethods = {"createList"}) + @Test(dependsOnMethods = {"createList", "read"}) public void readList() { - + // Perform setup. setupReadList(); // Submit the request to the service and store the response. - ClientResponse res = client.readList(); - RelationList list = res.getEntity(); + ClientResponse res = client.readList(); + RelationsCommonList list = res.getEntity(); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? verbose("readList: status = " + res.getStatus()); Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), - invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); // Optionally output additional data about list members for debugging. boolean iterateThroughList = false; - if (iterateThroughList && logger.isDebugEnabled()) { - List items = - list.getRelationListItem(); + if(iterateThroughList && logger.isDebugEnabled()){ + List items = + list.getRelationListItem(); int i = 0; - for(RelationList.RelationListItem item : items){ + for(RelationsCommonList.RelationListItem item : items){ verbose("readList: list-item[" + i + "] csid=" + - item.getCsid()); + item.getCsid()); verbose("readList: list-item[" + i + "] URI=" + - item.getUri()); + item.getUri()); i++; } } - + } // Failure outcomes - // None at present. - - // --------------------------------------------------------------- // CRUD tests : UPDATE tests // --------------------------------------------------------------- - // Success outcomes - @Override - @Test(dependsOnMethods = {"create"}) + @Test(dependsOnMethods = {"read"}) public void update() { - + // Perform setup. setupUpdate(); - - // Retrieve an existing resource that we can update. - ClientResponse res = client.read(knownResourceId); - verbose("read: status = " + res.getStatus()); - Assert.assertEquals(res.getStatus(), EXPECTED_STATUS_CODE); - Relation relation = res.getEntity(); - verbose("Got object to update with ID: " + knownResourceId, - relation, Relation.class); - - // Update the content of this resource. - relation.setDocumentId1("updated-" + relation.getDocumentId1()); - relation.setDocumentType1("updated-" + relation.getDocumentType1()); - relation.setDocumentId2("updated-" + relation.getDocumentId2()); - relation.setDocumentType2("updated-" + relation.getDocumentType2()); - - // Submit the request to the service and store the response. - res = client.update(knownResourceId, relation); - int statusCode = res.getStatus(); - Relation updatedObject = res.getEntity(); - - // Check the status code of the response: does it match - // the expected response(s)? - verbose("update: status = " + res.getStatus()); - Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), - invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); - - // Check the contents of the response: does it match - // what was submitted? - verbose("update: ", updatedObject, Relation.class); - final String msg = - "Data in updated object did not match submitted data."; - Assert.assertEquals( - updatedObject.getDocumentId1(), relation.getDocumentId1(), msg); - Assert.assertEquals( - updatedObject.getDocumentType1(), relation.getDocumentType1(), msg); - Assert.assertEquals( - updatedObject.getDocumentId2(), relation.getDocumentId2(), msg); - Assert.assertEquals( - updatedObject.getDocumentType2(), relation.getDocumentType2(), msg); + try{ + // Retrieve an existing resource that we can update. + ClientResponse res = + client.read(knownResourceId); + verbose("update: read status = " + res.getStatus()); + Assert.assertEquals(res.getStatus(), EXPECTED_STATUS_CODE); + verbose("Got object to update with ID: " + knownResourceId); + MultipartInput input = (MultipartInput) res.getEntity(); + RelationsCommon relation = (RelationsCommon) extractPart(input, + getCommonPartName(), RelationsCommon.class); + Assert.assertNotNull(relation); + + // Update the content of this resource. + relation.setDocumentId1("updated-" + relation.getDocumentId1()); + relation.setDocumentType1("updated-" + relation.getDocumentType1()); + relation.setDocumentId2("updated-" + relation.getDocumentId2()); + relation.setDocumentType2("updated-" + relation.getDocumentType2()); + verbose("updated object", relation, RelationsCommon.class); + + // Submit the request to the service and store the response. + MultipartOutput output = new MultipartOutput(); + OutputPart commonPart = output.addPart(relation, MediaType.APPLICATION_XML_TYPE); + commonPart.getHeaders().add("label", getCommonPartName()); + res = client.update(knownResourceId, output); + int statusCode = res.getStatus(); + // Check the status code of the response: does it match the expected response(s)? + verbose("update: status = " + res.getStatus()); + Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), + invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); + + input = (MultipartInput) res.getEntity(); + RelationsCommon updatedObject = + (RelationsCommon) extractPart(input, + getCommonPartName(), RelationsCommon.class); + Assert.assertNotNull(updatedObject); + + final String msg = + "Data in updated object did not match submitted data."; + Assert.assertEquals( + updatedObject.getDocumentId1(), relation.getDocumentId1(), msg); + Assert.assertEquals( + updatedObject.getDocumentType1(), relation.getDocumentType1(), msg); + Assert.assertEquals( + updatedObject.getDocumentId2(), relation.getDocumentId2(), msg); + Assert.assertEquals( + updatedObject.getDocumentType2(), relation.getDocumentType2(), msg); + }catch(Exception e){ + e.printStackTrace(); + } } - - // Failure outcomes + // Failure outcomes // Placeholders until the three tests below can be uncommented. // See Issue CSPACE-401. - public void updateWithEmptyEntityBody() {} - public void updateWithMalformedXml() {} - public void updateWithWrongXmlSchema() {} + public void updateWithEmptyEntityBody() { + } + + public void updateWithMalformedXml() { + } -/* + public void updateWithWrongXmlSchema() { + } + + /* @Override @Test(dependsOnMethods = {"create", "update", "testSubmitRequest"}) public void updateWithEmptyEntityBody() { - // Perform setup. - setupUpdateWithEmptyEntityBody(); - - // Submit the request to the service and store the response. - String method = REQUEST_TYPE.httpMethodName(); - String url = getResourceURL(knownResourceId); - String mediaType = MediaType.APPLICATION_XML; - final String entity = ""; - int statusCode = submitRequest(method, url, mediaType, entity); - - // Check the status code of the response: does it match - // the expected response(s)? - verbose("updateWithEmptyEntityBody url=" + url + " status=" + statusCode); - Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), - invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); + // Perform setup. + setupUpdateWithEmptyEntityBody(); + + // Submit the request to the service and store the response. + String method = REQUEST_TYPE.httpMethodName(); + String url = getResourceURL(knownResourceId); + String mediaType = MediaType.APPLICATION_XML; + final String entity = ""; + int statusCode = submitRequest(method, url, mediaType, entity); + + // Check the status code of the response: does it match + // the expected response(s)? + verbose("updateWithEmptyEntityBody url=" + url + " status=" + statusCode); + Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), + invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } @Override @Test(dependsOnMethods = {"create", "update", "testSubmitRequest"}) public void updateWithMalformedXml() { - // Perform setup. - setupUpdateWithMalformedXml(); - - // Submit the request to the service and store the response. - String method = REQUEST_TYPE.httpMethodName(); - String url = getResourceURL(knownResourceId); - String mediaType = MediaType.APPLICATION_XML; - final String entity = MALFORMED_XML_DATA; // Constant from abstract base class. - int statusCode = submitRequest(method, url, mediaType, entity); - - // Check the status code of the response: does it match - // the expected response(s)? - verbose("updateWithMalformedXml: url=" + url + " status=" + statusCode); - Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), - invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); + // Perform setup. + setupUpdateWithMalformedXml(); + + // Submit the request to the service and store the response. + String method = REQUEST_TYPE.httpMethodName(); + String url = getResourceURL(knownResourceId); + String mediaType = MediaType.APPLICATION_XML; + final String entity = MALFORMED_XML_DATA; // Constant from abstract base class. + int statusCode = submitRequest(method, url, mediaType, entity); + + // Check the status code of the response: does it match + // the expected response(s)? + verbose("updateWithMalformedXml: url=" + url + " status=" + statusCode); + Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), + invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } @Override @Test(dependsOnMethods = {"create", "update", "testSubmitRequest"}) public void updateWithWrongXmlSchema() { - // Perform setup. - setupUpdateWithWrongXmlSchema(); - - // Submit the request to the service and store the response. - String method = REQUEST_TYPE.httpMethodName(); - String url = getResourceURL(knownResourceId); - String mediaType = MediaType.APPLICATION_XML; - final String entity = WRONG_XML_SCHEMA_DATA; // Constant from abstract base class. - int statusCode = submitRequest(method, url, mediaType, entity); - - // Check the status code of the response: does it match - // the expected response(s)? - verbose("updateWithWrongSchema: url=" + url + " status=" + statusCode); - Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), - invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); + // Perform setup. + setupUpdateWithWrongXmlSchema(); + + // Submit the request to the service and store the response. + String method = REQUEST_TYPE.httpMethodName(); + String url = getResourceURL(knownResourceId); + String mediaType = MediaType.APPLICATION_XML; + final String entity = WRONG_XML_SCHEMA_DATA; // Constant from abstract base class. + int statusCode = submitRequest(method, url, mediaType, entity); + + // Check the status code of the response: does it match + // the expected response(s)? + verbose("updateWithWrongSchema: url=" + url + " status=" + statusCode); + Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), + invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } -*/ - - + */ @Override @Test(dependsOnMethods = {"update", "testSubmitRequest"}) public void updateNonExistent() { @@ -414,28 +423,25 @@ public class RelationServiceTest extends AbstractServiceTest { // Submit the request to the service and store the response. // Note: The ID used in this 'create' call may be arbitrary. // The only relevant ID may be the one used in update(), below. - Relation relation = createRelationInstance(NON_EXISTENT_ID); - ClientResponse res = - client.update(NON_EXISTENT_ID, relation); + MultipartOutput multipart = createRelationInstance(NON_EXISTENT_ID); + ClientResponse res = + client.update(NON_EXISTENT_ID, multipart); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? verbose("updateNonExistent: status = " + res.getStatus()); Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), - invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } - // --------------------------------------------------------------- // CRUD tests : DELETE tests // --------------------------------------------------------------- - // Success outcomes - @Override - @Test(dependsOnMethods = {"create", "read", "update"}) + @Test(dependsOnMethods = {"create", "readList", "testSubmitRequest", "update"}) public void delete() { // Perform setup. @@ -449,12 +455,11 @@ public class RelationServiceTest extends AbstractServiceTest { // the expected response(s)? verbose("delete: status = " + res.getStatus()); Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), - invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } // Failure outcomes - @Override @Test(dependsOnMethods = {"delete"}) public void deleteNonExistent() { @@ -470,24 +475,20 @@ public class RelationServiceTest extends AbstractServiceTest { // the expected response(s)? verbose("deleteNonExistent: status = " + res.getStatus()); Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), - invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } - // --------------------------------------------------------------- // RELATE_OBJECT tests // --------------------------------------------------------------- - @Test(dependsOnMethods = {"create"}) public void relateObjects() { } - // --------------------------------------------------------------- // Utility tests : tests of code used in tests above // --------------------------------------------------------------- - /** * Tests the code for manually submitting data that is used by several * of the methods above. @@ -502,31 +503,34 @@ public class RelationServiceTest extends AbstractServiceTest { String method = ServiceRequestType.READ.httpMethodName(); String url = getResourceURL(knownResourceId); int statusCode = submitRequest(method, url); - + // Check the status code of the response: does it match // the expected response(s)? verbose("testSubmitRequest: url=" + url + " status=" + statusCode); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); - } - + } // --------------------------------------------------------------- // Utility methods used by tests above // --------------------------------------------------------------- - @Override public String getServicePathComponent() { return SERVICE_PATH_COMPONENT; } - private Relation createRelationInstance(String identifier) { - String result = null; - Relation relation = new Relation(); + private MultipartOutput createRelationInstance(String identifier) { + RelationsCommon relation = new RelationsCommon(); fillRelation(relation, identifier); - return relation; + + MultipartOutput multipart = new MultipartOutput(); + OutputPart commonPart = multipart.addPart(relation, MediaType.APPLICATION_XML_TYPE); + commonPart.getHeaders().add("label", getCommonPartName()); + verbose("to be created, relation common ", relation, RelationsCommon.class); + + return multipart; } - + /** * Fills the relation. * @@ -534,12 +538,12 @@ public class RelationServiceTest extends AbstractServiceTest { * * @return the relation */ - private void fillRelation(Relation relation, String identifier) { + private void fillRelation(RelationsCommon relation, String identifier) { fillRelation(relation, "Subject-" + identifier, - "SubjectType-" + identifier + "-type", - "Object-" + identifier, - "ObjectType-" + identifier + "-type", - RelationshipType.COLLECTIONOBJECT_INTAKE); + "SubjectType-" + identifier + "-type", + "Object-" + identifier, + "ObjectType-" + identifier + "-type", + RelationshipType.COLLECTIONOBJECT_INTAKE); } /** @@ -553,17 +557,15 @@ public class RelationServiceTest extends AbstractServiceTest { * * @return the relation */ - private void fillRelation(Relation relation, - String documentId1, String documentType1, - String documentId2, String documentType2, - RelationshipType rt) - { + private void fillRelation(RelationsCommon relation, + String documentId1, String documentType1, + String documentId2, String documentType2, + RelationshipType rt) { relation.setDocumentId1(documentId1); relation.setDocumentType1(documentType1); relation.setDocumentId2(documentId2); relation.setDocumentType2(documentType2); - + relation.setRelationshipType(rt); } - } diff --git a/services/relation/client/src/test/resources/log4j.properties b/services/relation/client/src/test/resources/log4j.properties new file mode 100644 index 000000000..18c510350 --- /dev/null +++ b/services/relation/client/src/test/resources/log4j.properties @@ -0,0 +1,23 @@ +log4j.rootLogger=debug, stdout, R + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout + +# Pattern to output the caller's file name and line number. +log4j.appender.stdout.layout.ConversionPattern=%d %-5p [%t] [%c:%L] %m%n + +log4j.appender.R=org.apache.log4j.RollingFileAppender +log4j.appender.R.File=target/test-client.log + +log4j.appender.R.MaxFileSize=100KB +# Keep one backup file +log4j.appender.R.MaxBackupIndex=1 + +log4j.appender.R.layout=org.apache.log4j.PatternLayout +log4j.appender.R.layout.ConversionPattern=%d %-5p [%t] [%c:%L] %m%n + +#packages +log4j.logger.org.collectionspace=DEBUG +log4j.logger.org.apache=INFO +log4j.logger.httpclient=INFO +log4j.logger.org.jboss.resteasy=INFO diff --git a/services/relation/client/src/test/resources/log4j.xml b/services/relation/client/src/test/resources/log4j.xml deleted file mode 100644 index b26abaa9b..000000000 --- a/services/relation/client/src/test/resources/log4j.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/services/relation/service/src/main/java/org/collectionspace/services/relation/NewRelationResource.java b/services/relation/service/src/main/java/org/collectionspace/services/relation/NewRelationResource.java index 4dfc50536..a68481761 100644 --- a/services/relation/service/src/main/java/org/collectionspace/services/relation/NewRelationResource.java +++ b/services/relation/service/src/main/java/org/collectionspace/services/relation/NewRelationResource.java @@ -41,16 +41,17 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; import org.collectionspace.services.common.AbstractCollectionSpaceResource; -import org.collectionspace.services.common.NuxeoClientType; +import org.collectionspace.services.common.context.RemoteServiceContext; import org.collectionspace.services.common.context.ServiceContext; -import org.collectionspace.services.common.relation.RelationsManager; +import org.collectionspace.services.common.relation.IRelationsManager; import org.collectionspace.services.common.repository.DocumentNotFoundException; import org.collectionspace.services.common.repository.DocumentHandler; +import org.collectionspace.services.relation.nuxeo.RelationHandlerFactory; +import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; +import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; import org.jboss.resteasy.util.HttpResponseCodes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -60,9 +61,8 @@ import org.slf4j.LoggerFactory; @Produces("multipart/mixed") public class NewRelationResource extends AbstractCollectionSpaceResource { - public final static String serviceName = "relations"; - final Logger logger = LoggerFactory.getLogger(NewRelationResource.class); - + public final static String serviceName = "relations"; + final Logger logger = LoggerFactory.getLogger(NewRelationResource.class); @Override public String getServiceName() { @@ -70,326 +70,276 @@ public class NewRelationResource extends AbstractCollectionSpaceResource { } @Override - public DocumentHandler createDocumentHandler(ServiceContext ctx) throws Exception { + public DocumentHandler createDocumentHandler(RemoteServiceContext ctx) throws Exception { DocumentHandler docHandler = RelationHandlerFactory.getInstance().getHandler( ctx.getRepositoryClientType().toString()); docHandler.setServiceContext(ctx); if(ctx.getInput() != null){ - Object obj = ctx.getInputPart(ctx.getCommonPartLabel(), CollectionobjectsCommon.class); + Object obj = ctx.getInputPart(ctx.getCommonPartLabel(), RelationsCommon.class); if(obj != null){ - docHandler.setCommonPart((CollectionobjectsCommon) obj); + docHandler.setCommonPart((RelationsCommon) obj); } } return docHandler; } - -// public NewRelationResource() { -// } + @POST + public Response createRelation(MultipartInput input) { - @POST - public Response createRelation(Relation relation) { - - String csid = null; - try { - getDefaultHandler().setCommonObject(relation); - csid = getDefaultClient().create(SERVICE_NAME, getDefaultHandler()); - relation.setCsid(csid); - if (logger.isDebugEnabled()) { - verbose("createRelation: ", relation); - } - UriBuilder path = UriBuilder.fromResource(RelationResource.class); - path.path("" + csid); - Response response = Response.created(path.build()).build(); - return response; - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Caught exception in createRelation", e); - } - Response response = Response.status( - Response.Status.INTERNAL_SERVER_ERROR).entity( - "Create failed").type("text/plain").build(); - throw new WebApplicationException(response); - } - } - - /* - * Prototype for using NXQL -will move away from here once protyping is finished. - */ - @GET - @Path("query/{queryValue}") - public Response getQuery(@PathParam("queryValue") String queryString) { - - Response result = null; - - if (logger.isDebugEnabled() == true) { - logger.debug("Query string is: " + queryString); - } - - //getDefaultClient(). - - result = Response.status(Response.Status.ACCEPTED).entity( - "Query performed. Look in $JBOSS_HOME/server/cspace/log/" + - "directory for results ").type("text/plain").build(); - - return result; - } + try{ + RemoteServiceContext ctx = createServiceContext(input); + DocumentHandler handler = createDocumentHandler(ctx); + String csid = getRepositoryClient(ctx).create(ctx, handler); + UriBuilder path = UriBuilder.fromResource(NewRelationResource.class); + path.path("" + csid); + Response response = Response.created(path.build()).build(); + return response; + }catch(Exception e){ + if(logger.isDebugEnabled()){ + logger.debug("Caught exception in createRelation", e); + } + Response response = Response.status( + Response.Status.INTERNAL_SERVER_ERROR).entity( + "Create failed").type("text/plain").build(); + throw new WebApplicationException(response); + } + } - @GET - @Path("{csid}") - public Relation getRelation(@PathParam("csid") String csid) { - if (logger.isDebugEnabled()) { - verbose("getRelation with csid=" + csid); - } - if (csid == null || "".equals(csid)) { - logger.error("getRelation: missing csid!"); - Response response = Response.status(Response.Status.BAD_REQUEST) - .entity("get failed on Relation csid=" + csid).type( - "text/plain").build(); - throw new WebApplicationException(response); - } - Relation relation = null; - try { - getDefaultClient().get(csid, getDefaultHandler()); - relation = (Relation) getDefaultHandler().getCommonObject(); - } catch (DocumentNotFoundException dnfe) { - if (logger.isDebugEnabled()) { - logger.debug("getRelation", dnfe); - } - Response response = Response.status(Response.Status.NOT_FOUND) - .entity("Get failed on Relation csid=" + csid).type( - "text/plain").build(); - throw new WebApplicationException(response); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("getRelation", e); - } - Response response = Response.status( - Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed") - .type("text/plain").build(); - throw new WebApplicationException(response); - } + @GET + @Path("{csid}") + public MultipartOutput getRelation(@PathParam("csid") String csid) { + if(logger.isDebugEnabled()){ + logger.debug("getRelation with csid=" + csid); + } + if(csid == null || "".equals(csid)){ + logger.error("getRelation: missing csid!"); + Response response = Response.status(Response.Status.BAD_REQUEST).entity("get failed on Relation csid=" + csid).type( + "text/plain").build(); + throw new WebApplicationException(response); + } + MultipartOutput result = null; + try{ + RemoteServiceContext ctx = createServiceContext(null); + DocumentHandler handler = createDocumentHandler(ctx); + getRepositoryClient(ctx).get(ctx, csid, handler); + result = ctx.getOutput(); + }catch(DocumentNotFoundException dnfe){ + if(logger.isDebugEnabled()){ + logger.debug("getRelation", dnfe); + } + Response response = Response.status(Response.Status.NOT_FOUND).entity("Get failed on Relation csid=" + csid).type( + "text/plain").build(); + throw new WebApplicationException(response); + }catch(Exception e){ + if(logger.isDebugEnabled()){ + logger.debug("getRelation", e); + } + Response response = Response.status( + Response.Status.INTERNAL_SERVER_ERROR).entity("Get failed").type("text/plain").build(); + throw new WebApplicationException(response); + } - if (relation == null) { - Response response = Response.status(Response.Status.NOT_FOUND) - .entity( - "Get failed, the requested Relation CSID:" + csid - + ": was not found.").type("text/plain") - .build(); - throw new WebApplicationException(response); - } - if (logger.isDebugEnabled()) { - verbose("getRelation: ", relation); - } - return relation; - } - - /* - * BEGIN OF GET LIST - */ + if(result == null){ + Response response = Response.status(Response.Status.NOT_FOUND).entity( + "Get failed, the requested Relation CSID:" + csid + ": was not found.").type("text/plain").build(); + throw new WebApplicationException(response); + } + return result; + } - @GET - public RelationList getRelationList(@Context UriInfo ui) { - return this.getRelationListRequest(null, null, null); - } + /* + * BEGIN OF GET LIST + */ + @GET + @Produces("application/xml") + public RelationsCommonList getRelationList(@Context UriInfo ui) { + return this.getRelationList(null, null, null); + } - @GET - @Path("subject/{subjectCsid}") - public RelationList getRelationList_S(@Context UriInfo ui, - @PathParam("subjectCsid") String subjectCsid) { - return this.getRelationListRequest(subjectCsid, null, null); - } - - @GET - @Path("type/{predicate}") - public RelationList getRelationList_P(@Context UriInfo ui, - @PathParam("predicate") String predicate) { - return this.getRelationListRequest(null, predicate, null); - } + @GET + @Path("subject/{subjectCsid}") + @Produces("application/xml") + public RelationsCommonList getRelationList_S(@Context UriInfo ui, + @PathParam("subjectCsid") String subjectCsid) { + return this.getRelationList(subjectCsid, null, null); + } - @GET - @Path("object/{objectCsid}") - public RelationList getRelationList_O(@Context UriInfo ui, - @PathParam("objectCsid") String objectCsid) { - return this.getRelationListRequest(null, null, objectCsid); - } + @GET + @Path("type/{predicate}") + @Produces("application/xml") + public RelationsCommonList getRelationList_P(@Context UriInfo ui, + @PathParam("predicate") String predicate) { + return this.getRelationList(null, predicate, null); + } - @GET - @Path("type/{predicate}/subject/{subjectCsid}") - public RelationList getRelationList_PS(@Context UriInfo ui, - @PathParam("predicate") String predicate, - @PathParam("subjectCsid") String subjectCsid) { - return this.getRelationListRequest(subjectCsid, predicate, null); - } - - @GET - @Path("subject/{subjectCsid}/type/{predicate}") - public RelationList getRelationList_SP(@Context UriInfo ui, - @PathParam("subjectCsid") String subjectCsid, - @PathParam("predicate") String predicate) { - return this.getRelationListRequest(subjectCsid, predicate, null); - } - - @GET - @Path("type/{predicate}/object/{objectCsid}") - public RelationList getRelationList_PO(@Context UriInfo ui, - @PathParam("predicate") String predicate, - @PathParam("objectCsid") String objectCsid) { - return this.getRelationListRequest(null, predicate, objectCsid); - } - - @GET - @Path("object/{objectCsid}/type/{predicate}") - public RelationList getRelationList_OP(@Context UriInfo ui, - @PathParam("objectCsid") String objectCsid, - @PathParam("predicate") String predicate) { - return this.getRelationListRequest(null, predicate, objectCsid); - } - - @GET - @Path("type/{predicate}/subject/{subjectCsid}/object/{objectCsid}") - public RelationList getRelationList_PSO(@Context UriInfo ui, - @PathParam("predicate") String predicate, - @PathParam("subjectCsid") String subjectCsid, - @PathParam("objectCsid") String objectCsid) { - return this.getRelationListRequest(subjectCsid, predicate, objectCsid); - } + @GET + @Path("object/{objectCsid}") + @Produces("application/xml") + public RelationsCommonList getRelationList_O(@Context UriInfo ui, + @PathParam("objectCsid") String objectCsid) { + return this.getRelationList(null, null, objectCsid); + } - @GET - @Path("subject/{subjectCsid}/type/{predicate}/object/{objectCsid}") - public RelationList getRelationList_SPO(@Context UriInfo ui, - @PathParam("subjectCsid") String subjectCsid, - @PathParam("predicate") String predicate, - @PathParam("objectCsid") String objectCsid) { - return this.getRelationListRequest(subjectCsid, predicate, objectCsid); - } - - /* - * END OF GET LIST - */ - - @PUT - @Path("{csid}") - public Relation updateRelation(@PathParam("csid") String csid, - Relation theUpdate) { - if (logger.isDebugEnabled()) { - verbose("updateRelation with csid=" + csid); - } - if (csid == null || "".equals(csid)) { - logger.error("updateRelation: missing csid!"); - Response response = Response.status(Response.Status.BAD_REQUEST) - .entity("update failed on Relation csid=" + csid).type( - "text/plain").build(); - throw new WebApplicationException(response); - } - if (logger.isDebugEnabled()) { - verbose("updateRelation with input: ", theUpdate); - } - try { - getDefaultHandler().setCommonObject(theUpdate); - getDefaultClient().update(csid, getDefaultHandler()); - } catch (DocumentNotFoundException dnfe) { - if (logger.isDebugEnabled()) { - logger.debug("caugth exception in updateRelation", dnfe); - } - Response response = Response.status(Response.Status.NOT_FOUND) - .entity("Update failed on Relation csid=" + csid).type( - "text/plain").build(); - throw new WebApplicationException(response); - } catch (Exception e) { - Response response = Response.status( - Response.Status.INTERNAL_SERVER_ERROR).entity( - "Update failed").type("text/plain").build(); - throw new WebApplicationException(response); - } - return theUpdate; - } + @GET + @Path("type/{predicate}/subject/{subjectCsid}") + @Produces("application/xml") + public RelationsCommonList getRelationList_PS(@Context UriInfo ui, + @PathParam("predicate") String predicate, + @PathParam("subjectCsid") String subjectCsid) { + return this.getRelationList(subjectCsid, predicate, null); + } - @DELETE - @Path("{csid}") - public Response deleteRelation(@PathParam("csid") String csid) { + @GET + @Path("subject/{subjectCsid}/type/{predicate}") + @Produces("application/xml") + public RelationsCommonList getRelationList_SP(@Context UriInfo ui, + @PathParam("subjectCsid") String subjectCsid, + @PathParam("predicate") String predicate) { + return this.getRelationList(subjectCsid, predicate, null); + } - if (logger.isDebugEnabled()) { - verbose("deleteRelation with csid=" + csid); - } - if (csid == null || "".equals(csid)) { - logger.error("deleteRelation: missing csid!"); - Response response = Response.status(Response.Status.BAD_REQUEST) - .entity("delete failed on Relation csid=" + csid).type( - "text/plain").build(); - throw new WebApplicationException(response); - } - try { - getDefaultClient().delete(csid); - return Response.status(HttpResponseCodes.SC_OK).build(); - } catch (DocumentNotFoundException dnfe) { - if (logger.isDebugEnabled()) { - logger.debug("caught exception in deleteRelation", dnfe); - } - Response response = Response.status(Response.Status.NOT_FOUND) - .entity("Delete failed on Relation csid=" + csid).type( - "text/plain").build(); - throw new WebApplicationException(response); - } catch (Exception e) { - Response response = Response.status( - Response.Status.INTERNAL_SERVER_ERROR).entity( - "Delete failed").type("text/plain").build(); - throw new WebApplicationException(response); - } + @GET + @Path("type/{predicate}/object/{objectCsid}") + @Produces("application/xml") + public RelationsCommonList getRelationList_PO(@Context UriInfo ui, + @PathParam("predicate") String predicate, + @PathParam("objectCsid") String objectCsid) { + return this.getRelationList(null, predicate, objectCsid); + } - } + @GET + @Path("object/{objectCsid}/type/{predicate}") + @Produces("application/xml") + public RelationsCommonList getRelationList_OP(@Context UriInfo ui, + @PathParam("objectCsid") String objectCsid, + @PathParam("predicate") String predicate) { + return this.getRelationList(null, predicate, objectCsid); + } - /* - * Private Methods - */ + @GET + @Path("type/{predicate}/subject/{subjectCsid}/object/{objectCsid}") + @Produces("application/xml") + public RelationsCommonList getRelationList_PSO(@Context UriInfo ui, + @PathParam("predicate") String predicate, + @PathParam("subjectCsid") String subjectCsid, + @PathParam("objectCsid") String objectCsid) { + return this.getRelationList(subjectCsid, predicate, objectCsid); + } - /** - * Gets the relation list request. - * - * @return the relation list request - * - * @throws WebApplicationException the web application exception - */ - private RelationList getRelationListRequest(String subjectCsid, - String predicate, - String objectCsid) - throws WebApplicationException { - RelationList relationList = new RelationList(); - try { - Map propsFromPath = getDefaultHandler().getProperties(); - propsFromPath.put(RelationsManager.SUBJECT, subjectCsid); - propsFromPath.put(RelationsManager.PREDICATE, predicate); - propsFromPath.put(RelationsManager.OBJECT, objectCsid); + @GET + @Path("subject/{subjectCsid}/type/{predicate}/object/{objectCsid}") + @Produces("application/xml") + public RelationsCommonList getRelationList_SPO(@Context UriInfo ui, + @PathParam("subjectCsid") String subjectCsid, + @PathParam("predicate") String predicate, + @PathParam("objectCsid") String objectCsid) { + return this.getRelationList(subjectCsid, predicate, objectCsid); + } + /* + * END OF GET LIST + */ - getDefaultClient().getAll(SERVICE_NAME, getDefaultHandler()); - relationList = (RelationList) getDefaultHandler().getCommonObjectList(); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Caught exception in getRelationList", e); - } - Response response = Response.status( - Response.Status.INTERNAL_SERVER_ERROR).entity( - "Index failed").type("text/plain").build(); - throw new WebApplicationException(response); - } - return relationList; - } + @PUT + @Path("{csid}") + public MultipartOutput updateRelation(@PathParam("csid") String csid, + MultipartInput theUpdate) { + if(logger.isDebugEnabled()){ + logger.debug("updateRelation with csid=" + csid); + } + if(csid == null || "".equals(csid)){ + logger.error("updateRelation: missing csid!"); + Response response = Response.status(Response.Status.BAD_REQUEST).entity("update failed on Relation csid=" + csid).type( + "text/plain").build(); + throw new WebApplicationException(response); + } + MultipartOutput result = null; + try{ + RemoteServiceContext ctx = createServiceContext(theUpdate); + DocumentHandler handler = createDocumentHandler(ctx); + getRepositoryClient(ctx).update(ctx, csid, handler); + result = ctx.getOutput(); + }catch(DocumentNotFoundException dnfe){ + if(logger.isDebugEnabled()){ + logger.debug("caugth exception in updateRelation", dnfe); + } + Response response = Response.status(Response.Status.NOT_FOUND).entity("Update failed on Relation csid=" + csid).type( + "text/plain").build(); + throw new WebApplicationException(response); + }catch(Exception e){ + Response response = Response.status( + Response.Status.INTERNAL_SERVER_ERROR).entity( + "Update failed").type("text/plain").build(); + throw new WebApplicationException(response); + } + return result; + } - private void verbose(String msg, Relation relation) { - try { - verbose(msg); - JAXBContext jc = JAXBContext.newInstance(Relation.class); + @DELETE + @Path("{csid}") + public Response deleteRelation(@PathParam("csid") String csid) { - Marshaller m = jc.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - m.marshal(relation, System.out); - } catch (Exception e) { - e.printStackTrace(); - } + if(logger.isDebugEnabled()){ + logger.debug("deleteRelation with csid=" + csid); + } + if(csid == null || "".equals(csid)){ + logger.error("deleteRelation: missing csid!"); + Response response = Response.status(Response.Status.BAD_REQUEST).entity("delete failed on Relation csid=" + csid).type( + "text/plain").build(); + throw new WebApplicationException(response); + } + try{ + ServiceContext ctx = createServiceContext(null); + getRepositoryClient(ctx).delete(ctx, csid); + return Response.status(HttpResponseCodes.SC_OK).build(); + }catch(DocumentNotFoundException dnfe){ + if(logger.isDebugEnabled()){ + logger.debug("caught exception in deleteRelation", dnfe); + } + Response response = Response.status(Response.Status.NOT_FOUND).entity("Delete failed on Relation csid=" + csid).type( + "text/plain").build(); + throw new WebApplicationException(response); + }catch(Exception e){ + Response response = Response.status( + Response.Status.INTERNAL_SERVER_ERROR).entity( + "Delete failed").type("text/plain").build(); + throw new WebApplicationException(response); + } - } + } - private void verbose(String msg) { - System.out.println("RelationResource. " + msg); - } + /* + * Private Methods + */ + /** + * Gets the relation list request. + * + * @return the relation list request + * + * @throws WebApplicationException the web application exception + */ + private RelationsCommonList getRelationList(String subjectCsid, + String predicate, + String objectCsid) + throws WebApplicationException { + RelationsCommonList relationList = new RelationsCommonList(); + try{ + RemoteServiceContext ctx = createServiceContext(null); + DocumentHandler handler = createDocumentHandler(ctx); + Map propsFromPath = handler.getProperties(); + propsFromPath.put(IRelationsManager.SUBJECT, subjectCsid); + propsFromPath.put(IRelationsManager.PREDICATE, predicate); + propsFromPath.put(IRelationsManager.OBJECT, objectCsid); + getRepositoryClient(ctx).getAll(ctx, handler); + relationList = (RelationsCommonList) handler.getCommonPartList(); + }catch(Exception e){ + if(logger.isDebugEnabled()){ + logger.debug("Caught exception in getRelationList", e); + } + Response response = Response.status( + Response.Status.INTERNAL_SERVER_ERROR).entity( + "Index failed").type("text/plain").build(); + throw new WebApplicationException(response); + } + return relationList; + } } diff --git a/services/relation/service/src/main/java/org/collectionspace/services/relation/RelationResource.java b/services/relation/service/src/main/java/org/collectionspace/services/relation/RelationResource.java deleted file mode 100644 index 3ab53cc72..000000000 --- a/services/relation/service/src/main/java/org/collectionspace/services/relation/RelationResource.java +++ /dev/null @@ -1,653 +0,0 @@ -/** - * RelationResource.java - * - * {Purpose of This Class} - * - * {Other Notes Relating to This Class (Optional)} - * - * $LastChangedBy: $ - * $LastChangedRevision: $ - * $LastChangedDate: $ - * - * This document is a part of the source code and related artifacts - * for CollectionSpace, an open source collections management system - * for museums and related institutions: - * - * http://www.collectionspace.org - * http://wiki.collectionspace.org - * - * Copyright © 2009 {Contributing Institution} - * - * Licensed under the Educational Community License (ECL), Version 2.0. - * You may not use this file except in compliance with this License. - * - * You may obtain a copy of the ECL 2.0 License at - * https://source.collectionspace.org/collection-space/LICENSE.txt - */ -package org.collectionspace.services.relation; - -import java.util.Iterator; -import java.util.List; -import java.net.URI; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.PathParam; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; -import javax.ws.rs.core.UriInfo; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; - -import org.collectionspace.services.relation.RelationService; -import org.collectionspace.services.relation.*; -import org.collectionspace.services.relation.RelationList.*; - -import org.collectionspace.services.relation.nuxeo.RelationServiceNuxeoImpl; -import org.collectionspace.services.common.relation.RelationJAXBSchema; -import org.collectionspace.services.common.relation.RelationListItemJAXBSchema; - -import org.collectionspace.services.common.ServiceMain; -import org.collectionspace.services.common.repository.DocumentException; -import org.collectionspace.services.common.repository.DocumentNotFoundException; - -import org.dom4j.Document; -import org.dom4j.Element; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The Class RelationResource. - */ -@Path("/relations") -@Consumes("application/xml") -@Produces("application/xml") -public class RelationResource { - - /** The logger. */ - final Logger logger = LoggerFactory.getLogger(RelationResource.class); - - // This should be a DI wired by a container like Spring, Seam, or EJB3 - /** The Constant service. */ - final static RelationService service = new RelationServiceNuxeoImpl(); - - /** - * Instantiates a new relation resource. - */ - public RelationResource() { - // do nothing - } - - /** - * Returns a list of *all* relation entities. - * - * @param ui - * the ui - * - * @return the relation list - */ - @GET - public RelationList getRelationList(@Context UriInfo ui) { - RelationList relationList = this.getRequestedRelationList(ui, null, - null, null); - - return relationList; - } - - /** - * Gets a list of relations with the subject= - * - * @param ui - * the ui - * @param subjectCsid - * the subject == subjectCsid - * - * @return the relation list_ s - */ - @GET - @Path("subject/{subjectCsid}") - public RelationList getRelationList_S(@Context UriInfo ui, - @PathParam("subjectCsid") String subjectCsid) { - RelationList relationList = this.getRequestedRelationList(ui, - subjectCsid, null, null); - - return relationList; - } - - /** - * Gets a list of relations with predicate == predicate. - * - * @param ui - * the ui - * @param predicate - * the predicate - * - * @return the relation list of type - */ - @GET - @Path("type/{predicate}") - public RelationList getRelationList_P(@Context UriInfo ui, - @PathParam("predicate") String predicate) { - RelationList relationList = this.getRequestedRelationList(ui, null, - predicate, null); - - return relationList; - } - - /** - * Gets a list of relations with object == objectCsid - * - * @param ui - * the ui - * @param objectCsid - * the object csid - * - * @return the relation list_ o - */ - @GET - @Path("object/{objectCsid}") - public RelationList getRelationList_O(@Context UriInfo ui, - @PathParam("objectCsid") String objectCsid) { - RelationList relationList = this.getRequestedRelationList(ui, null, - null, objectCsid); - - return relationList; - } - - /** - * Gets a list of relations with predicate == predicate *and* subject == - * subjectCsid - * - * @param ui - * the ui - * @param predicate - * the predicate - * @param subjectCsid - * the subject subjectCsid - * - * @return the relation list of type with subject - */ - @GET - @Path("type/{predicate}/subject/{subjectCsid}") - public RelationList getRelationList_PS(@Context UriInfo ui, - @PathParam("predicate") String predicate, - @PathParam("subjectCsid") String subjectCsid) { - RelationList relationList = this.getRequestedRelationList(ui, - subjectCsid, predicate, null); - - return relationList; - } - - /** - * Gets a list of relations with subject == subjectCsid *and* predicate == - * predicate - * - * @param ui - * the ui - * @param subjectCsid - * the subject csid - * @param predicate - * the predicate - * - * @return the relation list_ sp - */ - @GET - @Path("subject/{subjectCsid}/type/{predicate}") - public RelationList getRelationList_SP(@Context UriInfo ui, - @PathParam("subjectCsid") String subjectCsid, - @PathParam("predicate") String predicate) { - RelationList relationList = this.getRequestedRelationList(ui, - subjectCsid, predicate, null); - - return relationList; - } - - /** - * Gets a list of relations with predicate == predicate *and* object == - * objectCsid - * - * @param ui - * the ui - * @param predicate - * the predicate - * @param objectCsid - * the object csid - * - * @return the relation list of type with object - */ - @GET - @Path("type/{predicate}/object/{objectCsid}") - public RelationList getRelationList_PO(@Context UriInfo ui, - @PathParam("predicate") String predicate, - @PathParam("objectCsid") String objectCsid) { - RelationList relationList = this.getRequestedRelationList(ui, null, - predicate, objectCsid); - - return relationList; - } - - /** - * Gets a list of relations with object == objectCsid *and* predicate == - * predicate - * - * @param ui - * the ui - * @param objectCsid - * the object csid - * @param predicate - * the predicate - * - * @return the relation list_ op - */ - @GET - @Path("object/{objectCsid}/type/{predicate}") - public RelationList getRelationList_OP(@Context UriInfo ui, - @PathParam("objectCsid") String objectCsid, - @PathParam("predicate") String predicate) { - RelationList relationList = this.getRequestedRelationList(ui, null, - predicate, objectCsid); - - return relationList; - } - - /** - * Gets a list of relations with predicate == predicate *and* subject == - * subjectCsid *and* object == objectCsid - * - * @param ui - * the ui - * @param predicate - * the predicate - * @param subjectCsid - * the subject csid - * @param objectCsid - * the object csid - * - * @return the relation list - */ - @GET - @Path("type/{predicate}/subject/{subjectCsid}/object/{objectCsid}") - public RelationList getRelationList_PSO(@Context UriInfo ui, - @PathParam("predicate") String predicate, - @PathParam("subjectCsid") String subjectCsid, - @PathParam("objectCsid") String objectCsid) { - RelationList relationList = this.getRequestedRelationList(ui, - predicate, subjectCsid, objectCsid); - - return relationList; - } - - /** - * Gets a list of relations with subject == subjectCsid *and* predicate == - * predicate *and* object == objectCsid - * - * @param ui - * the ui - * @param subjectCsid - * the subject csid - * @param predicate - * the predicate - * @param objectCsid - * the object csid - * - * @return the relation list_ spo - */ - @GET - @Path("subject/{subjectCsid}/type/{predicate}/object/{objectCsid}") - public RelationList getRelationList_SPO(@Context UriInfo ui, - @PathParam("subjectCsid") String subjectCsid, - @PathParam("predicate") String predicate, - @PathParam("objectCsid") String objectCsid) { - RelationList relationList = this.getRequestedRelationList(ui, - subjectCsid, predicate, objectCsid); - - return relationList; - } - - /** - * Creates the relation. - * - * @param ui - * the ui - * @param co - * the co - * - * @return the response - */ - @POST - public Response createRelation(@Context UriInfo ui, Relation co) { - String csid = null; - - try { - Document document = service.postRelation(co); - Element root = document.getRootElement(); - csid = root.attributeValue("id"); - co.setCsid(csid); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Caught exception in createRelation", e); - } - Response response = Response.status( - Response.Status.INTERNAL_SERVER_ERROR).entity( - "Index failed").type("text/plain").build(); - throw new WebApplicationException(response); - } - - UriBuilder uriBuilder = ui.getAbsolutePathBuilder(); - uriBuilder.path(csid); - URI uri = uriBuilder.build(); - - Response response = Response.created(uri).build(); - return response; - } - - /** - * Gets the relation. - * - * @param csid - * the csid - * - * @return the relation - */ - @GET - @Path("{csid}") - public Relation getRelation(@PathParam("csid") String csid) { - - Relation co = null; - try { - Document document = service.getRelation(csid); - Element root = document.getRootElement(); - co = new Relation(); - - // TODO: recognize schema thru namespace uri - // Namespace ns = new Namespace("relation", - // "http://collectionspace.org/relation"); - - Iterator siter = root.elementIterator("schema"); - while (siter.hasNext()) { - Element schemaElement = siter.next(); - System.err.println("Relation.getRelation() called."); - - // TODO: recognize schema thru namespace uri - if (RelationService.REL_SCHEMA_NAME.equals(schemaElement - .attribute("name").getValue())) { - Iterator relIter = schemaElement - .elementIterator(RelationJAXBSchema.REL_ROOT_ELEM_NAME); - Iterator relIter2 = schemaElement - .elementIterator("rel:" - + RelationJAXBSchema.REL_ROOT_ELEM_NAME); - - while (relIter.hasNext()) { - Element relElement = relIter.next(); - - Element ele = relElement - .element(RelationJAXBSchema.DOCUMENT_ID_1); - if (ele != null) { - co.setDocumentId1((String) ele.getData()); - } - ele = relElement - .element(RelationJAXBSchema.DOCUMENT_TYPE_1); - if (ele != null) { - co.setDocumentType1((String) ele.getData()); - } - ele = relElement - .element(RelationJAXBSchema.DOCUMENT_ID_2); - if (ele != null) { - co.setDocumentId2((String) ele.getData()); - } - ele = relElement - .element(RelationJAXBSchema.DOCUMENT_TYPE_2); - if (ele != null) { - co.setDocumentType2((String) ele.getData()); - } - ele = relElement - .element(RelationJAXBSchema.RELATIONSHIP_TYPE); - if (ele != null) { - RelationshipType rt = RelationshipType - .fromValue((String) ele.getData()); - co.setRelationshipType(rt); - } - } - } - } - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Caught exception in getRelation", e); - } - Response response = Response.status( - Response.Status.INTERNAL_SERVER_ERROR).entity( - "Index failed").type("text/plain").build(); - throw new WebApplicationException(response); - } - if (co == null) { - Response response = Response.status(Response.Status.NOT_FOUND) - .entity( - "Get failed, the requested Relation CSID:" + csid - + ": was not found.").type("text/plain") - .build(); - throw new WebApplicationException(response); - } - - if (logger.isDebugEnabled() == true) { - verbose("getRelation: ", co); - } - - return co; - } - - /** - * Update relation. - * - * @param csid - * the csid - * @param theUpdate - * the the update - * - * @return the relation - */ - @PUT - @Path("{csid}") - public Relation updateRelation(@PathParam("csid") String csid, - Relation theUpdate) { - - if (logger.isDebugEnabled() == true) { - verbose("updateRelation with input: ", theUpdate); - } - - String status = null; - try { - - Document document = service.putRelation(csid, theUpdate); - Element root = document.getRootElement(); - for (Iterator i = root.elementIterator(); i.hasNext();) { - Element element = (Element) i.next(); - if ("docRef".equals(element.getName())) { - status = (String) element.getData(); - verbose("updateRelation response: " + status); - } - } - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Caught exception in updateRelation", e); - } - Response response = Response.status( - Response.Status.INTERNAL_SERVER_ERROR).entity( - "Index failed").type("text/plain").build(); - throw new WebApplicationException(response); - } - - return theUpdate; - } - - /** - * Delete relation. - * - * @param csid - * the csid - */ - @DELETE - @Path("{csid}") - public void deleteRelation(@PathParam("csid") String csid) { - - verbose("deleteRelation with csid=" + csid); - try { - service.deleteRelation(csid); - } catch (DocumentNotFoundException dnfe) { - if (logger.isDebugEnabled()) { - logger.debug("caught exception in deleteRelation", dnfe); - } - Response response = Response.status(Response.Status.NOT_FOUND) - .entity("Delete failed on Relation csid=" + csid) - .type("text/plain").build(); - throw new WebApplicationException(response); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Caught exception in deleteRelation", e); - } - Response response = Response.status( - Response.Status.INTERNAL_SERVER_ERROR).entity( - "Index failed").type("text/plain").build(); - throw new WebApplicationException(response); - } - } - - /* - * Private Methods - */ - - /** - * Gets the relation list common. - * - * @param ui - * the ui - * @param subjectCsid - * the subject csid - * @param predicate - * the predicate - * @param objectCsid - * the object csid - * - * @return the relation list common - * - * @throws WebApplicationException - * the web application exception - */ - private RelationList getRequestedRelationList(@Context UriInfo ui, - String subjectCsid, String predicate, String objectCsid) - throws WebApplicationException { - - URI absoluteURI = ui.getAbsolutePath(); - String uriString = absoluteURI.toString(); - - RelationList relationList = null; - try { - relationList = this.getRelationList(subjectCsid, predicate, - objectCsid); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Caught exception in getRelationList", e); - } - Response response = Response.status( - Response.Status.INTERNAL_SERVER_ERROR).entity( - "Index failed").type("text/plain").build(); - throw new WebApplicationException(response); - } - - return relationList; - } - - /** - * Gets the relation list. - * - * @param subjectCsid - * the subject csid - * @param predicate - * the predicate - * @param objectCsid - * the object csid - * - * @return the relation list - * - * @throws DocumentException - * the document exception - */ - private RelationList getRelationList(String subjectCsid, String predicate, - String objectCsid) throws DocumentException { - RelationList relationList = new RelationList(); - try { - Document document = service.getRelationList(subjectCsid, predicate, - objectCsid); - if (logger.isDebugEnabled() == true) { - System.err.println(document.asXML()); - } - - Element root = document.getRootElement(); - List list = relationList - .getRelationListItem(); - Element node = null; - for (Iterator i = root.elementIterator(); i.hasNext();) { - node = (Element) i.next(); - if (logger.isDebugEnabled() == true) { - System.out.println(); - node.asXML(); - } - - // set the Relation list item entity elements - RelationListItem listItem = new RelationListItem(); - listItem.setUri(node - .attributeValue(RelationListItemJAXBSchema.URI)); - listItem.setCsid(node - .attributeValue(RelationListItemJAXBSchema.CSID)); - list.add(listItem); - } - - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Caught exception in getRelationListOfType", e); - } - throw new DocumentException(e); - } - - return relationList; - } - - /** - * Verbose. - * - * @param msg - * the msg - * @param co - * the co - */ - private void verbose(String msg, Relation co) { - try { - verbose(msg); - JAXBContext jc = JAXBContext.newInstance(Relation.class); - - Marshaller m = jc.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - m.marshal(co, System.out); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Verbose. - * - * @param msg - * the msg - */ - private void verbose(String msg) { - System.out.println("RelationResource. " + msg); - } - -} diff --git a/services/relation/service/src/main/java/org/collectionspace/services/relation/RelationService.java b/services/relation/service/src/main/java/org/collectionspace/services/relation/RelationService.java deleted file mode 100644 index 4f2291157..000000000 --- a/services/relation/service/src/main/java/org/collectionspace/services/relation/RelationService.java +++ /dev/null @@ -1,129 +0,0 @@ -/** - * RelationService.java - * - * {Purpose of This Class} - * - * {Other Notes Relating to This Class (Optional)} - * - * $LastChangedBy: $ - * $LastChangedRevision: $ - * $LastChangedDate: $ - * - * This document is a part of the source code and related artifacts - * for CollectionSpace, an open source collections management system - * for museums and related institutions: - * - * http://www.collectionspace.org - * http://wiki.collectionspace.org - * - * Copyright © 2009 {Contributing Institution} - * - * Licensed under the Educational Community License (ECL), Version 2.0. - * You may not use this file except in compliance with this License. - * - * You may obtain a copy of the ECL 2.0 License at - * https://source.collectionspace.org/collection-space/LICENSE.txt - */ -package org.collectionspace.services.relation; - -import java.io.IOException; -import org.dom4j.Document; -//import org.dom4j.DocumentException; -import org.collectionspace.services.common.repository.DocumentException; - - -import org.collectionspace.services.relation.Relation; - -/** - * @author remillet - * - */ -public interface RelationService { - - /** The Constant REL_SCHEMA_NAME. */ - public final static String REL_SCHEMA_NAME = "relation"; - - // Create - /** - * Post relation. - * - * @param co the co - * - * @return the document - * - * @throws DocumentException the document exception - * @throws IOException Signals that an I/O exception has occurred. - */ - Document postRelation(Relation co) - throws DocumentException, IOException; - - // Read single object - /** - * Gets the relation. - * - * @param csid the csid - * - * @return the relation - * - * @throws DocumentException the document exception - * @throws IOException Signals that an I/O exception has occurred. - */ - Document getRelation(String csid) throws DocumentException, - IOException; - - // Read a list of objects - /** - * Gets the relation list. - * - * @return the relation list - * - * @throws DocumentException the document exception - * @throws IOException Signals that an I/O exception has occurred. - */ - Document getRelationList() throws DocumentException, IOException; - - /** - * Gets the relation list of type. - * - * @param subjectCsid the subject csid - * @param predicate the predicate - * @param objectCsid the object csid - * - * @return the relation list of type - * - * @throws DocumentException the document exception - * @throws IOException Signals that an I/O exception has occurred. - */ - Document getRelationList(String subjectCsid, - String predicate, String objectCsid) - throws DocumentException, IOException; - - // Update - /** - * Put relation. - * - * @param csid the csid - * @param theUpdate the the update - * - * @return the document - * - * @throws DocumentException the document exception - * @throws IOException Signals that an I/O exception has occurred. - */ - Document putRelation(String csid, Relation theUpdate) - throws DocumentException, IOException; - - // Delete - /** - * Delete relation. - * - * @param csid the csid - * - * @return the document - * - * @throws DocumentException the document exception - * @throws IOException Signals that an I/O exception has occurred. - */ - Document deleteRelation(String csid) throws DocumentException, - IOException; -} diff --git a/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationDocumentModelHandler.java b/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationDocumentModelHandler.java index 0db9aa602..48d8bb419 100644 --- a/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationDocumentModelHandler.java +++ b/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationDocumentModelHandler.java @@ -27,17 +27,17 @@ import java.util.Iterator; import java.util.List; import java.util.Map; -import org.collectionspace.services.common.relation.RelationJAXBSchema; -import org.collectionspace.services.common.relation.nuxeo.RelationsManagerNuxeoImpl; -import org.collectionspace.services.common.relation.RelationsManager; -import org.collectionspace.services.relation.Relation; -import org.collectionspace.services.relation.RelationList; -import org.collectionspace.services.relation.RelationList.RelationListItem; +import org.collectionspace.services.common.relation.IRelationsManager; +import org.collectionspace.services.common.relation.nuxeo.RelationConstants; +import org.collectionspace.services.common.relation.nuxeo.RelationsUtils; +import org.collectionspace.services.common.repository.DocumentHandler.Action; +import org.collectionspace.services.relation.RelationsCommon; +import org.collectionspace.services.relation.RelationsCommonList; +import org.collectionspace.services.relation.RelationsCommonList.RelationListItem; -import org.collectionspace.services.relation.nuxeo.RelationNuxeoConstants; import org.collectionspace.services.common.repository.DocumentWrapper; -import org.collectionspace.services.nuxeo.client.java.DocumentModelHandler; +import org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandler; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.DocumentModelList; import org.slf4j.Logger; @@ -50,32 +50,31 @@ import org.slf4j.LoggerFactory; * $LastChangedDate: $ */ public class RelationDocumentModelHandler - extends DocumentModelHandler { + extends RemoteDocumentModelHandler { private final Logger logger = LoggerFactory.getLogger(RelationDocumentModelHandler.class); /** * relation is used to stash JAXB object to use when handle is called * for Action.CREATE, Action.UPDATE or Action.GET */ - private Relation relation; + private RelationsCommon relation; /** * relationList is stashed when handle is called * for ACTION.GET_ALL */ - private RelationList relationList; + private RelationsCommonList relationList; @Override public void prepare(Action action) throws Exception { //no specific action needed } - /** * getCommonObject get associated Relation * @return */ @Override - public Relation getCommonObject() { + public RelationsCommon getCommonPart() { return relation; } @@ -84,7 +83,7 @@ public class RelationDocumentModelHandler * @param relation */ @Override - public void setCommonObject(Relation relation) { + public void setCommonPart(RelationsCommon relation) { this.relation = relation; } @@ -93,78 +92,77 @@ public class RelationDocumentModelHandler * @return */ @Override - public RelationList getCommonObjectList() { + public RelationsCommonList getCommonPartList() { return relationList; } @Override - public void setCommonObjectList(RelationList relationList) { + public void setCommonPartList(RelationsCommonList relationList) { this.relationList = relationList; } @Override - public Relation extractCommonObject(DocumentWrapper wrapDoc) + public RelationsCommon extractCommonPart(DocumentWrapper wrapDoc) throws Exception { - DocumentModel docModel = (DocumentModel) wrapDoc.getWrappedObject(); - Relation theRelation = new Relation(); - - RelationsManagerNuxeoImpl.fillRelationFromDocModel(theRelation, docModel); - - return theRelation; + throw new UnsupportedOperationException(); } @Override - public void fillCommonObject(Relation relation, DocumentWrapper wrapDoc) throws Exception { - DocumentModel docModel = (DocumentModel) wrapDoc.getWrappedObject(); - - RelationsManagerNuxeoImpl.fillDocModelFromRelation(relation, docModel); + public void fillCommonPart(RelationsCommon relation, DocumentWrapper wrapDoc) throws Exception { + throw new UnsupportedOperationException(); } @Override - public RelationList extractCommonObjectList(DocumentWrapper wrapDoc) throws Exception { + public RelationsCommonList extractCommonPartList(DocumentWrapper wrapDoc) throws Exception { DocumentModelList docList = (DocumentModelList) wrapDoc.getWrappedObject(); Map propsFromResource = this.getProperties(); - String subjectCsid = (String)propsFromResource.get(RelationsManager.SUBJECT); - String predicate = (String)propsFromResource.get(RelationsManager.PREDICATE); - String objectCsid = (String)propsFromResource.get(RelationsManager.OBJECT); + String subjectCsid = (String) propsFromResource.get(IRelationsManager.SUBJECT); + String predicate = (String) propsFromResource.get(IRelationsManager.PREDICATE); + String objectCsid = (String) propsFromResource.get(IRelationsManager.OBJECT); - RelationList coList = new RelationList(); - List list = coList.getRelationListItem(); + RelationsCommonList relList = new RelationsCommonList(); + List itemList = relList.getRelationListItem(); - //FIXME: iterating over a long list of documents is not a long term + //FIXME: iterating over a long itemList of documents is not a long term //strategy...need to change to more efficient iterating in future Iterator iter = docList.iterator(); while(iter.hasNext()){ DocumentModel docModel = iter.next(); - if (RelationsManager.isQueryMatch(docModel, subjectCsid, - predicate, objectCsid) == true) { - RelationListItem coListItem = new RelationListItem(); - RelationsManagerNuxeoImpl.fillRelationListItemFromDocModel( - coListItem, docModel); - list.add(coListItem); - } + if(RelationsUtils.isQueryMatch(docModel, subjectCsid, + predicate, objectCsid) == true){ + RelationListItem relListItem = RelationsUtils.getRelationListItem( + docModel, getServiceContextPath()); + itemList.add(relListItem); + } } + return relList; + } - return coList; + + + @Override + public void fillAllParts(DocumentWrapper wrapDoc) throws Exception { + super.fillAllParts(wrapDoc); + fillDublinCoreObject(wrapDoc); //dublincore might not be needed in future } - - public String getDocumentType() { - return RelationNuxeoConstants.NUXEO_DOCTYPE; + + private void fillDublinCoreObject(DocumentWrapper wrapDoc) throws Exception { + DocumentModel docModel = (DocumentModel) wrapDoc.getWrappedObject(); + //FIXME property setter should be dynamically set using schema inspection + //so it does not require hard coding + // a default title for the Dublin Core schema + docModel.setPropertyValue("dublincore:title", RelationConstants.NUXEO_DC_TITLE); } @Override - public void fillCommonObjectList(RelationList obj, DocumentWrapper wrapDoc) throws Exception { - throw new UnsupportedOperationException(); + public String getDocumentType() { + return RelationConstants.NUXEO_DOCTYPE; } - /** - * getQProperty converts the given property to qualified schema property - * @param prop - * @return - */ - private String getQProperty(String property) { - return RelationsManager.getQPropertyName(property); + @Override + public String getQProperty(String prop) { + return "/" + RelationConstants.NUXEO_SCHEMA_ROOT_ELEMENT + "/" + prop; } } diff --git a/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationHandlerFactory.java b/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationHandlerFactory.java index b2f1a5b60..53ac92ff3 100644 --- a/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationHandlerFactory.java +++ b/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationHandlerFactory.java @@ -23,7 +23,7 @@ */ package org.collectionspace.services.relation.nuxeo; -import org.collectionspace.services.common.NuxeoClientType; +import org.collectionspace.services.common.ClientType; import org.collectionspace.services.common.repository.DocumentHandler; import org.collectionspace.services.common.CollectionSpaceHandlerFactory; @@ -46,9 +46,9 @@ public class RelationHandlerFactory implements CollectionSpaceHandlerFactory { } public DocumentHandler getHandler(String clientType) { - if(NuxeoClientType.JAVA.toString().equals(clientType)){ + if(ClientType.JAVA.toString().equals(clientType)){ return new RelationDocumentModelHandler(); - } else if(NuxeoClientType.REST.toString().equals(clientType)) { +// } else if(ClientType.REST.toString().equals(clientType)) { // return new RelationRepresenationHandler(); } throw new IllegalArgumentException("Not supported client=" + clientType); diff --git a/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationNuxeoConstants.java b/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationNuxeoConstants.java deleted file mode 100644 index ca09458d8..000000000 --- a/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationNuxeoConstants.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.collectionspace.services.relation.nuxeo; - -import org.collectionspace.services.common.relation.nuxeo.RelationsManagerNuxeoImpl; - -public class RelationNuxeoConstants { - static String NUXEO_DOCTYPE = RelationsManagerNuxeoImpl.REL_NUXEO_DOCTYPE; -} \ No newline at end of file diff --git a/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationServiceNuxeoImpl.java b/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationServiceNuxeoImpl.java deleted file mode 100644 index f1e5a9ccb..000000000 --- a/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationServiceNuxeoImpl.java +++ /dev/null @@ -1,260 +0,0 @@ -/** - * RelationServiceNuxeoImpl.java - * - * {Purpose of This Class} - * - * {Other Notes Relating to This Class (Optional)} - * - * $LastChangedBy: $ - * $LastChangedRevision: $ - * $LastChangedDate: $ - * - * This document is a part of the source code and related artifacts - * for CollectionSpace, an open source collections management system - * for museums and related institutions: - * - * http://www.collectionspace.org - * http://wiki.collectionspace.org - * - * Copyright © 2009 {Contributing Institution} - * - * Licensed under the Educational Community License (ECL), Version 2.0. - * You may not use this file except in compliance with this License. - * - * You may obtain a copy of the ECL 2.0 License at - * https://source.collectionspace.org/collection-space/LICENSE.txt - */ -package org.collectionspace.services.relation.nuxeo; - -//import java.io.ByteArrayInputStream; -import java.io.IOException; -//import java.io.Serializable; -//import java.util.ArrayList; -//import java.util.Arrays; -//import java.util.HashMap; -import java.util.List; -//import java.util.Map; -//import java.util.Iterator; - -import org.collectionspace.services.common.repository.DocumentException; -//import org.collectionspace.services.nuxeo.NuxeoRESTClient; -import org.collectionspace.services.nuxeo.CollectionSpaceServiceNuxeoImpl; -import org.collectionspace.services.common.relation.nuxeo.RelationsManagerNuxeoImpl; -import org.collectionspace.services.relation.Relation; -import org.collectionspace.services.relation.RelationService; -//import org.collectionspace.services.relation.RelationList; -//import org.collectionspace.services.relation.RelationshipType; -//import org.collectionspace.services.RelationJAXBSchema; -import org.collectionspace.services.nuxeo.util.NuxeoUtils; -import org.collectionspace.services.common.relation.RelationsManager; -//import org.collectionspace.services.common.ServiceMain; - -import org.dom4j.Document; -//import org.dom4j.Element; -//import org.dom4j.dom.DOMDocument; -//import org.dom4j.DocumentException; -//import org.dom4j.io.SAXReader; -//import org.restlet.resource.Representation; - -import org.nuxeo.common.utils.IdUtils; -//import org.nuxeo.ecm.core.api.ClientException; -import org.nuxeo.ecm.core.api.IdRef; -import org.nuxeo.ecm.core.api.repository.RepositoryInstance; -import org.nuxeo.ecm.core.api.DocumentModel; -//import org.nuxeo.ecm.core.api.DocumentModelList; -//import org.nuxeo.ecm.core.api.model.DocumentPart; -import org.nuxeo.ecm.core.api.DocumentRef; - - - -/** - * The Class RelationServiceNuxeoImpl. - */ -public class RelationServiceNuxeoImpl extends - CollectionSpaceServiceNuxeoImpl implements RelationService { - - // replace WORKSPACE_UID for resource workspace - // static String CS_RELATION_WORKSPACE_UID = "55f99358-5dbe-4462-8000-c5c3c2063919"; - - /* (non-Javadoc) - * @see org.collectionspace.services.relation.RelationService#deleteRelation(java.lang.String) - */ - public Document deleteRelation(String csid) throws DocumentException { - Document result = null; - -// RepositoryInstance repoSession = null; -// try { -// repoSession = getRepositorySession(); -// result = deleteDocument(repoSession, csid); -// } catch (Exception e) { -// if (logger.isDebugEnabled()) { -// logger.debug("Caught exception ", e); -// } -// throw new DocumentException(e); -// } finally { -// if (repoSession != null) { -// releaseRepositorySession(repoSession); -// } -// } - - return result; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.relation.RelationService#getRelation(java.lang.String) - */ - public Document getRelation(String csid) - throws DocumentException, IOException { - Document result = null; - RepositoryInstance repoSession = null; - - try { - repoSession = getRepositorySession(); - result = NuxeoUtils.getDocument(repoSession, csid); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Caught exception ", e); - } - throw new DocumentException(e); - } finally { - if (repoSession != null) { - releaseRepositorySession(repoSession); - } - } - - // Dump out the contents of the result - if (logger.isDebugEnabled() == true) { - System.out.println(result.asXML()); - } - - return result; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.relation.RelationService#getRelationList() - */ - public Document getRelationList() - throws DocumentException, IOException { - Document result = null; - RepositoryInstance repoSession = null; - - try { - repoSession = getRepositorySession(); - List relationList = RelationsManager.getRelationships(repoSession); - - result = RelationsManagerNuxeoImpl.getDocument(relationList); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Caught exception ", e); - } - throw new DocumentException(e); - } finally { - if (repoSession != null) { - releaseRepositorySession(repoSession); - } - } - - if (logger.isDebugEnabled() == true) { - System.out.println(result.asXML()); - } - - return result; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.RelationService#getRelationList(java.lang.String, java.lang.String, java.lang.String) - */ - public Document getRelationList(String subjectCsid, - String predicate, String objectCsid) - throws DocumentException, IOException { - Document result = null; - RepositoryInstance repoSession = null; - - try { - repoSession = getRepositorySession(); - List relationList = RelationsManager.getRelationships(repoSession, - subjectCsid, predicate, objectCsid); - - result = RelationsManagerNuxeoImpl.getDocument(relationList); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Caught exception ", e); - } - throw new DocumentException(e); - } finally { - if (repoSession != null) { - releaseRepositorySession(repoSession); - } - } - - if (logger.isDebugEnabled() == true) { - System.out.println(result.asXML()); - } - - return result; - } - - // Create a new relation document - /* (non-Javadoc) - * @see org.collectionspace.services.relation.RelationService#postRelation(org.collectionspace.services.relation.Relation) - */ - public Document postRelation(Relation co) throws DocumentException, - IOException { - Document result = null; - RepositoryInstance repoSession = null; - - try { - repoSession = getRepositorySession(); - DocumentModel resultDocModel = RelationsManagerNuxeoImpl.createRelationship(repoSession, co); - repoSession.save(); - result = NuxeoUtils.getDocument(repoSession, resultDocModel); - } catch (Exception e) { - if (logger.isDebugEnabled() == true) { - logger.debug("Caught exception ", e); - } - throw new DocumentException(e); - } finally { - if (repoSession != null) { - releaseRepositorySession(repoSession); - } - } - - // Dump out the contents of the result - if (logger.isDebugEnabled() == true) { - System.out.println(result.asXML()); - } - - return result; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.relation.RelationService#putRelation(java.lang.String, org.collectionspace.services.relation.Relation) - */ - public Document putRelation(String csid, Relation theUpdate) - throws DocumentException, IOException { - - Document result = null; - RepositoryInstance repoSession = null; - try{ - repoSession = getRepositorySession(); - DocumentRef documentRef = new IdRef(csid); - DocumentModel documentModel = repoSession.getDocument(documentRef); - RelationsManagerNuxeoImpl.fillDocModelFromRelation(theUpdate, documentModel); - repoSession.saveDocument(documentModel); - repoSession.save(); - result = NuxeoUtils.getDocument(repoSession, documentModel); - } catch(Exception e){ - if (logger.isDebugEnabled()) { - logger.debug("Caught exception ", e); - } - throw new DocumentException(e); - } finally{ - if(repoSession != null){ - releaseRepositorySession(repoSession); - } - } - - return result; - } - -}