From 98c282a1f87bee659b77ad5884ac38a09810d506 Mon Sep 17 00:00:00 2001 From: remillet Date: Tue, 16 Dec 2014 11:25:52 -0800 Subject: [PATCH] Normalizing LF vs CRLF in all files. Normalizing LF vs CRLF in all files. --- .classpath | 20 +- .gitattributes | 22 + .project | 34 +- 3rdparty/.classpath | 12 +- 3rdparty/.project | 34 +- 3rdparty/build.xml | 268 +- 3rdparty/nuxeo/.classpath | 12 +- 3rdparty/nuxeo/.project | 34 +- 3rdparty/nuxeo/build.xml | 322 +- .../src/main/resources/META-INF/MANIFEST.MF | 36 +- .../src/main/resources/META-INF/MANIFEST.MF | 36 +- .../OSGI-INF/deployment-fragment.xml | 20 +- .../nuxeo-platform-collectionspace/pom.xml | 66 +- .../src/main/resources/META-INF/MANIFEST.MF | 38 +- .../OSGI-INF/deployment-fragment.xml | 20 +- .../resources/OSGI-INF/querymodel-contrib.xml | 40 +- .../src/main/resources/schemas/subitem.xsd | 44 +- .../nuxeo/nuxeo-platform-quote-api/pom.xml | 100 +- 3rdparty/nuxeo/nuxeo-platform-quote/LGPL.txt | 1008 +++--- 3rdparty/nuxeo/nuxeo-platform-quote/pom.xml | 304 +- 3rdparty/nuxeo/nuxeo-server/Bundle List.txt | 72 +- build.properties | 352 +- build.xml | 692 ++-- installer/build.xml | 212 +- nbproject/project.xml | 132 +- pom.xml | 934 +++--- services/.classpath | 12 +- services/.project | 34 +- services/IntegrationTests/pom.xml | 372 +-- .../xmlreplay/PayloadLogger.java | 1084 +++---- .../xmlreplay/ServiceResult.java | 654 ++-- .../xmlreplay/TreeWalkResults.java | 460 +-- .../xmlreplay/XmlCompareJdom.java | 684 ++-- .../IntegrationTests/xmlreplay/XmlReplay.java | 1746 +++++----- .../xmlreplay/XmlReplayEval.java | 304 +- .../xmlreplay/XmlReplayTest.java | 400 +-- .../xmlreplay/XmlReplayTransport.java | 668 ++-- .../test/CollectionSpaceIntegrationTest.java | 454 +-- .../test/XmlCompareJdomRepeatingTest.java | 204 +- .../test/XmlCompareJdomTest.java | 440 +-- .../test/XmlReplayMasterTest.java | 46 +- .../test/XmlReplaySelfTest.java | 340 +- .../src/test/resources/log4j.properties | 46 +- .../test-data/xmlreplay/acquisitions/ac1.xml | 44 +- .../test-data/xmlreplay/acquisitions/ac2.xml | 44 +- .../xmlreplay/acquisitions/acquisitions.xml | 148 +- .../xmlreplay/acquisitions/res/ac1.res.xml | 40 +- .../xmlreplay/acquisitions/res/ac2.res.xml | 42 +- .../xmlreplay/acquisitions/res/ac3.res.xml | 42 +- .../acquisitions/res/ac3list.res.xml | 58 +- .../xmlreplay/authority/personauthority.xml | 22 +- .../xmlreplay/authority/personitem.xml | 26 +- .../authority/res/locationItems.res.xml | 14 +- .../res/locationItemsWithShortID.res.xml | 16 +- .../authority/res/personItems.res.xml | 14 +- .../res/personItemsContainingWord1.res.xml | 54 +- .../res/personItemsContainingWord2.res.xml | 48 +- .../res/personItemsOnlyWord1.res.xml | 18 +- .../test-data/xmlreplay/authrefs/authrefs.xml | 430 +-- .../xmlreplay/authrefs/authrefsComplex.xml | 48 +- .../xmlreplay/authrefs/authrefsSimple.xml | 196 +- .../xmlreplay/authrefs/authrefsSimple2.xml | 124 +- .../test-data/xmlreplay/authrefs/loanin.xml | 30 +- .../xmlreplay/authrefs/newPerson.xml | 40 +- .../xmlreplay/authrefs/newPerson1.xml | 36 +- .../xmlreplay/authrefs/newPerson2.xml | 36 +- .../xmlreplay/authrefs/newPersonAuthority.xml | 16 +- .../authrefs/organizations_common.xml | 92 +- .../authrefs/orgauthorities_common.xml | 22 +- .../xmlreplay/authrefs/res/refObjs.res.xml | 12 +- .../xmlreplay/authrefs/updatePerson1.xml | 36 +- .../xmlreplay/authrefs/updatePerson2.xml | 36 +- .../batch-create-updateobjloc-nocontext.xml | 34 +- .../batch/batch-create-updateobjloc.xml | 34 +- .../batch/batch-invoke-updateobjloc-group.xml | 26 +- .../batch/batch-invoke-updateobjloc-list.xml | 42 +- .../batch-invoke-updateobjloc-nocontext.xml | 26 +- .../batch-invoke-updateobjloc-single.xml | 26 +- .../batch/batch-update-object-loc.xml | 2078 ++++++------ .../test-data/xmlreplay/batch/batch.xml | 158 +- .../test-data/xmlreplay/batch/batch1.xml | 32 +- .../xmlreplay/batch/batch1InvContext.xml | 20 +- .../xmlreplay/batch/batchBadInvContext.xml | 24 +- .../batch/batchBadInvContextList.xml | 22 +- .../xmlreplay/batch/batchInvContextList.xml | 24 +- .../xmlreplay/batch/batchInvContextSingle.xml | 20 +- .../xmlreplay/bugs/nonlatin/non-latin-3.txt | 2 +- .../bugs/nonlatin/non-latin-notes.txt | 54 +- .../xmlreplay/bugs/nonlatin/non-latin.xml | 38 +- .../xmlreplay/bugs/nonlatin/utf-8-bug.txt | 54 +- .../collectionobject/AuthRefsCollObj.xml | 70 +- .../collectionobject/nh-collectionobject.xml | 94 +- .../xmlreplay/collectionobject/nh-part.xml | 12 +- .../resources/test-data/xmlreplay/dev-all.xml | 192 +- .../xmlreplay/dev-master-example.xml | 96 +- .../test-data/xmlreplay/dimension-master.xml | 46 +- .../test-data/xmlreplay/dimension.xml | 152 +- .../test-data/xmlreplay/dimension/1.xml | 22 +- .../test-data/xmlreplay/dimension/2-put.xml | 20 +- .../res/import-objectexit-utf8.res.xml | 28 +- .../test-data/xmlreplay/loanin/li1.xml | 50 +- .../test-data/xmlreplay/loanin/loanin.xml | 56 +- .../3-locations_w_relations_CSID.xml | 172 +- .../4-locations_w_relations_mixed.xml | 88 +- .../5-locations_w_relations_RefNames.xml | 122 +- .../test-data/xmlreplay/media/media.xml | 78 +- .../test-data/xmlreplay/media/oe11.xml | 28 +- .../test-data/xmlreplay/media/oe15.xml | 20 +- .../test-data/xmlreplay/media/oe9.xml | 20 +- .../objectexit/object-exit-display.xml | 106 +- .../xmlreplay/objectexit/object-exit.xml | 810 ++--- .../test-data/xmlreplay/objectexit/oe1.xml | 20 +- .../test-data/xmlreplay/objectexit/oe11.xml | 4 +- .../test-data/xmlreplay/objectexit/oe13.xml | 4 +- .../test-data/xmlreplay/objectexit/oe15.xml | 4 +- .../test-data/xmlreplay/objectexit/oe23.xml | 4 +- .../test-data/xmlreplay/objectexit/oe3.xml | 4 +- .../test-data/xmlreplay/objectexit/oe35.xml | 20 +- .../test-data/xmlreplay/objectexit/oe4.xml | 4 +- .../test-data/xmlreplay/objectexit/oe5.xml | 4 +- .../test-data/xmlreplay/objectexit/oe9.xml | 4 +- .../xmlreplay/objectexit/oeObject.xml | 18 +- .../objectexit/oePersonDisplayOnly.xml | 30 +- .../objectexit/oePersonauthority.xml | 24 +- .../xmlreplay/objectexit/oeRepeat.xml | 22 +- .../xmlreplay/objectexit/res/oe10.res.xml | 18 +- .../xmlreplay/objectexit/res/oe12.res.xml | 36 +- .../xmlreplay/objectexit/res/oe14.res.xml | 36 +- .../xmlreplay/objectexit/res/oe16.res.xml | 14 +- .../xmlreplay/objectexit/res/oe17.res.xml | 28 +- .../xmlreplay/objectexit/res/oe2.res.xml | 28 +- .../xmlreplay/objectexit/res/oe22.res.xml | 12 +- .../xmlreplay/objectexit/res/oe23.res.xml | 12 +- .../xmlreplay/objectexit/res/oe27.res.xml | 4 +- .../xmlreplay/objectexit/res/oe28.res.xml | 4 +- .../xmlreplay/objectexit/res/oe29.res.xml | 4 +- .../xmlreplay/objectexit/res/oe30.res.xml | 4 +- .../xmlreplay/objectexit/res/oe6.res.xml | 72 +- .../xmlreplay/objectexit/res/oe8.res.xml | 12 +- .../test-data/xmlreplay/organization.xml | 74 +- .../hierarchy/3-organizations_w_relations.xml | 166 +- .../organization/organizations_common.xml | 68 +- .../organization/organizations_ucb.xml | 38 +- .../organization/organizations_ucbist.xml | 26 +- .../organization/orgauthorities_common.xml | 24 +- .../orgauthorities_testorgauth.xml | 24 +- .../xmlreplay/organization/repeatables.xml | 22 +- .../test-data/xmlreplay/person/person.xml | 1002 +++--- .../person/personTermStatusSearch.xml | 166 +- .../xmlreplay/person/person_pmadry.xml | 34 +- .../xmlreplay/person/person_pschmitz.xml | 40 +- .../person/personauthorities_common.xml | 26 +- .../personauthorities_testpersonauth.xml | 24 +- .../xmlreplay/person/persons_common.xml | 68 +- ...ersons_common_delete_all_relations_PUT.xml | 74 +- .../persons_common_delete_relations_PUT.xml | 106 +- .../person/persons_common_w_relations.xml | 158 +- .../person/persons_common_w_relations_2.xml | 120 +- .../person/persons_common_w_relations_3.xml | 158 +- .../persons_common_w_relations_POST.xml | 214 +- .../person/res/personlistActive.res.xml | 22 +- .../person/res/personlistAll.res.xml | 28 +- .../person/res/personlistNone.res.xml | 16 +- .../test-data/xmlreplay/relation/oe1.xml | 20 +- .../test-data/xmlreplay/relation/relation.xml | 708 ++-- .../relation/res/workflowState.res.xml | 12 +- .../test-data/xmlreplay/report/report.xml | 134 +- .../report/report1InvContextStandalone.xml | 20 +- .../test-data/xmlreplay/security.xml | 882 ++--- .../security/1-bigbird-permission.xml | 36 +- .../security/10-permissionroles-elmo.xml | 26 +- .../security/11-bigbird-permission-CRU.xml | 32 +- .../11-permissionroles-bigbird-CRU.xml | 26 +- .../security/12-bigbird-permission-R.xml | 20 +- .../security/12-permissionroles-bigbird-R.xml | 26 +- .../security/13-permissionroles-bigbird.xml | 26 +- .../xmlreplay/security/2-elmo-permission.xml | 16 +- .../xmlreplay/security/3-role-test-cm.xml | 12 +- .../xmlreplay/security/4-role-intern.xml | 10 +- .../xmlreplay/security/5-account-bigbird.xml | 30 +- .../xmlreplay/security/6-account-elmo.xml | 32 +- .../security/7-accountroles-bigbird.xml | 30 +- .../security/8-account-roles-elmo.xml | 30 +- .../security/9-permissionroles-bigbird.xml | 26 +- .../security/Base64-authentication-notes.txt | 88 +- .../xmlreplay/xml-replay-master-self-test.xml | 32 +- .../test-data/xmlreplay/xml-replay-master.xml | 188 +- .../xmlreplay/xml-replay-self-test.xml | 78 +- services/JaxRsServiceProvider/pom.xml | 1540 ++++----- .../jaxrs/CSpaceResteasyBootstrap.java | 72 +- .../main/resources/META-INF/persistence.xml | 64 +- .../src/main/resources/log4j.properties | 166 +- .../src/main/webapp/WEB-INF/jboss-web.xml | 30 +- .../src/main/webapp/WEB-INF/login.conf | 64 +- .../src/main/webapp/WEB-INF/web.xml | 308 +- services/PerformanceTests/pom.xml | 262 +- .../test/CollectionSpacePerformanceTest.java | 480 +-- .../src/test/resources/log4j.properties | 46 +- services/account/.classpath | 12 +- services/account/.project | 34 +- services/account/build.xml | 270 +- services/account/client/build.xml | 276 +- services/account/client/pom.xml | 248 +- .../src/test/resources/log4j.properties | 50 +- .../jaxb/src/test/resources/log4j.properties | 48 +- services/account/pom.xml | 46 +- services/account/pstore/build.xml | 418 +-- services/account/pstore/pom.xml | 314 +- .../main/resources/db/postgresql/README.txt | 64 +- .../src/test/resources/log4j.properties | 50 +- services/account/service/pom.xml | 242 +- services/acquisition/.classpath | 12 +- services/acquisition/.project | 34 +- services/acquisition/3rdparty/.classpath | 12 +- services/acquisition/3rdparty/.project | 34 +- services/acquisition/3rdparty/build.xml | 262 +- services/acquisition/3rdparty/pom.xml | 48 +- services/acquisition/build.xml | 248 +- services/acquisition/client/pom.xml | 206 +- .../src/test/resources/log4j.properties | 46 +- .../services/AcquisitionJAXBSchema.java | 28 +- .../AcquisitionListItemJAXBSchema.java | 28 +- services/acquisition/pom.xml | 56 +- services/acquisition/service/pom.xml | 92 +- .../nuxeo/AcquisitionValidatorHandler.java | 36 +- services/authentication/.classpath | 12 +- services/authentication/.project | 34 +- services/authentication/build.xml | 276 +- services/authentication/client/build.xml | 278 +- services/authentication/client/pom.xml | 134 +- .../src/test/resources/log4j.properties | 46 +- services/authentication/nb-configuration.xml | 20 +- services/authentication/pom.xml | 52 +- services/authentication/pstore/build.xml | 430 +-- services/authentication/pstore/pom.xml | 296 +- .../main/resources/db/postgresql/README.txt | 22 +- services/authentication/service/build.xml | 302 +- .../jaas/CSpaceJBossDBLoginModule.java | 310 +- .../src/test/resources/log4j.properties | 46 +- services/authority/build.xml | 264 +- .../vocabulary/AuthorityItemJAXBSchema.java | 96 +- .../AuthorityItemListItemJAXBSchema.java | 66 +- .../vocabulary/AuthorityJAXBSchema.java | 76 +- .../AuthorityListItemJAXBSchema.java | 66 +- services/authority/pom.xml | 536 ++-- services/authority/service/pom.xml | 602 ++-- .../common/vocabulary/IVocabManager.java | 14 +- .../common/vocabulary/VocabManager.java | 18 +- .../common/vocabulary/VocabManagerImpl.java | 44 +- services/authorization-mgt/.classpath | 12 +- services/authorization-mgt/.project | 34 +- services/authorization-mgt/build.xml | 276 +- services/authorization-mgt/client/build.xml | 252 +- services/authorization-mgt/client/pom.xml | 368 +-- .../src/test/resources/log4j.properties | 50 +- services/authorization-mgt/import/build.xml | 330 +- services/authorization-mgt/import/pom.xml | 474 +-- .../src/main/resources/log4j.properties | 78 +- services/authorization-mgt/service/build.xml | 268 +- services/authorization-mgt/service/pom.xml | 400 +-- services/authorization/.classpath | 12 +- services/authorization/.project | 34 +- services/authorization/build.xml | 276 +- services/authorization/jaxb/pom.xml | 160 +- .../main/resources/accounts_permissions.xsd | 90 +- .../jaxb/src/test/resources/log4j.properties | 48 +- services/authorization/pstore/build.xml | 454 +-- services/authorization/pstore/pom.xml | 284 +- .../main/resources/db/postgresql/README.txt | 64 +- services/authorization/service/build.xml | 264 +- .../authorization/PermissionActionUtil.java | 10 +- .../src/test/resources/log4j.properties | 46 +- services/batch/.project | 34 +- services/batch/3rdparty/.project | 34 +- .../src/main/resources/META-INF/MANIFEST.MF | 46 +- .../main/resources/schemas/batch_common.xsd | 82 +- .../src/test/resources/log4j.properties | 46 +- .../services/batch/BatchInvocable.java | 36 +- services/blob/.project | 34 +- services/blob/3rdparty/.project | 34 +- .../services/client/test/BlobScaleTest.java | 338 +- .../src/test/resources/log4j.properties | 50 +- services/blob/jaxb/.classpath | 60 +- services/build.xml | 696 ++-- services/citation/.classpath | 10 +- services/citation/.project | 58 +- services/citation/3rdparty/.classpath | 10 +- services/citation/3rdparty/.project | 58 +- .../services/CitationJAXBSchema.java | 28 +- services/client/pom.xml | 240 +- ...bstractCommonListPoxServiceClientImpl.java | 36 +- .../client/AbstractCommonListUtils.java | 92 +- .../client/AbstractPoxServiceClientImpl.java | 120 +- .../client/AbstractServiceClientImpl.java | 938 +++--- .../services/client/AuthorityClient.java | 302 +- .../services/client/AuthorityClientImpl.java | 410 +-- .../services/client/AuthorityProxy.java | 314 +- .../client/CollectionSpaceClientUtils.java | 604 ++-- .../CollectionSpaceCommonListPoxProxy.java | 68 +- .../client/CollectionSpacePoxClient.java | 54 +- .../client/CollectionSpacePoxProxy.java | 132 +- .../services/client/CollectionSpaceProxy.java | 216 +- .../services/client/IClientQueryParams.java | 72 +- .../services/client/IQueryManager.java | 326 +- .../services/client/PayloadInputPart.java | 72 +- .../services/client/PayloadOutputPart.java | 96 +- .../services/client/PayloadPart.java | 164 +- .../services/client/PoxPayload.java | 618 ++-- .../services/client/PoxPayloadIn.java | 160 +- .../services/client/PoxPayloadOut.java | 368 +-- .../services/client/Profiler.java | 598 ++-- .../services/client/TestServiceProxy.java | 14 +- .../test/AbstractAuthorityServiceTest.java | 1080 +++---- .../test/AbstractPoxServiceTestImpl.java | 160 +- .../services/client/test/BaseServiceTest.java | 1808 +++++------ .../client/test/ServiceTestUtils.java | 12 +- .../collectionspace-client.properties | 34 +- .../src/test/resources/log4j.properties | 46 +- services/collectionobject/.classpath | 12 +- services/collectionobject/.project | 34 +- services/collectionobject/3rdparty/.classpath | 12 +- services/collectionobject/3rdparty/.project | 34 +- services/collectionobject/3rdparty/build.xml | 286 +- .../build.xml | 332 +- .../build.xml | 338 +- services/collectionobject/3rdparty/pom.xml | 68 +- services/collectionobject/build.xml | 272 +- .../collectionobject/client/nbactions.xml | 32 +- services/collectionobject/client/pom.xml | 218 +- .../src/test/resources/log4j.properties | 46 +- services/collectionobject/installer/build.xml | 108 +- .../services/CollectionObjectJAXBSchema.java | 40 +- .../CollectionObjectListItemJAXBSchema.java | 24 +- services/collectionobject/nbactions.xml | 32 +- services/collectionobject/pom.xml | 72 +- services/collectionobject/sample/.classpath | 10 +- services/collectionobject/sample/.project | 34 +- .../collectionobject/sample/sample/.project | 46 +- .../collectionspace-client.properties | 10 +- services/collectionobject/service/pom.xml | 334 +- .../CollectionObjectValidatorHandler.java | 276 +- services/common-api/pom.xml | 84 +- .../services/common/api/CommonAPI.java | 46 +- .../services/common/api/FileTools.java | 572 ++-- .../services/common/api/RefName.java | 640 ++-- .../services/common/api/Tools.java | 516 +-- .../services/common/api/ZipTools.java | 312 +- .../services/common/api/test/RefNameTest.java | 348 +- .../src/test/resources/log4j.properties | 46 +- services/common/pom.xml | 820 ++--- .../AbstractCollectionSpaceResourceImpl.java | 1022 +++--- ...tMultiPartCollectionSpaceResourceImpl.java | 558 ++-- .../common/ConfigurationException.java | 130 +- .../services/common/Download.java | 564 ++-- .../services/common/FileUtils.java | 478 +-- .../services/common/IFragmentHandler.java | 112 +- .../services/common/ReflectionMapper.java | 252 +- .../services/common/ResourceBase.java | 1258 ++++---- .../services/common/ResourceMap.java | 20 +- .../services/common/ResourceMapHolder.java | 10 +- .../services/common/ResourceMapImpl.java | 14 +- .../services/common/ServiceMain.java | 1980 ++++++------ .../services/common/ServletTools.java | 768 ++--- .../services/common/UriTemplate.java | 236 +- .../services/common/UriTemplateFactory.java | 198 +- .../services/common/UriTemplateRegistry.java | 128 +- .../services/common/XmlSaxFragmenter.java | 618 ++-- .../AuthorizationCommon.java | 2354 +++++++------- .../AuthorizationRoleRel.java | 142 +- .../services/common/blob/BlobInput.java | 460 +-- .../services/common/blob/BlobOutput.java | 58 +- .../services/common/blob/BlobUtil.java | 72 +- .../common/config/ServiceConfigUtils.java | 288 +- .../common/config/TenantBindingUtils.java | 230 +- .../services/common/context/JaxRsContext.java | 44 +- .../context/RemoteServiceContextFactory.java | 224 +- .../common/context/ServiceBindingUtils.java | 472 +-- .../common/document/DocumentFilter.java | 914 +++--- .../common/document/DocumentListWrapper.java | 80 +- .../document/DocumentListWrapperImpl.java | 108 +- .../common/document/ValidatorHandlerImpl.java | 302 +- .../common/imaging/nuxeo/NuxeoBlobUtils.java | 2836 ++++++++--------- .../services/common/init/AddIndices.java | 492 +-- .../services/common/init/IInitHandler.java | 44 +- .../services/common/init/InitHandler.java | 158 +- .../common/invocable/InvocableUtils.java | 64 +- .../profile/BufferedServletInputStream.java | 56 +- .../profile/BufferedServletOutputStream.java | 76 +- .../services/common/profile/CSpaceFilter.java | 262 +- .../common/profile/PayloadFilter.java | 230 +- .../common/profile/RequestWrapper.java | 196 +- .../common/profile/ResponseWrapper.java | 350 +- .../services/common/query/QueryContext.java | 338 +- .../services/common/query/QueryManager.java | 236 +- .../common/query/QueryResultList.java | 108 +- .../query/nuxeo/QueryManagerNuxeoImpl.java | 714 ++--- .../common/relation/RelationJAXBSchema.java | 128 +- .../relation/RelationListItemJAXBSchema.java | 98 +- .../services/common/storage/JDBCTools.java | 1542 ++++----- .../storage/jpa/JpaDocumentHandler.java | 148 +- .../vocabulary/RefNameServiceUtils.java | 1966 ++++++------ .../nuxeo/client/java/CommonList.java | 330 +- .../nuxeo/client/java/DocHandlerBase.java | 788 ++--- .../client/java/NuxeoClientEmbedded.java | 588 ++-- .../client/java/NuxeoConnectorEmbedded.java | 684 ++-- .../nuxeo/client/java/ObjectFactory.java | 106 +- ...RemoteSubItemDocumentModelHandlerImpl.java | 264 +- .../nuxeo/client/java/package-info.java | 6 +- .../common/src/main/resources/version.xsd | 52 +- .../common/test/UriTemplateRegistryTest.java | 198 +- .../services/common/test/UriTemplateTest.java | 336 +- .../test-data/XmlSaxFragmenter-sample.xml | 22 +- .../common/config/PropertyItemUtils.java | 320 +- services/contact/.classpath | 10 +- services/contact/.project | 34 +- services/contact/3rdparty/.classpath | 10 +- services/contact/3rdparty/.project | 34 +- .../client/AuthorityWithContactsClient.java | 532 ++-- .../AuthorityWithContactsClientImpl.java | 650 ++-- .../client/AuthorityWithContactsProxy.java | 312 +- services/dimension/.classpath | 12 +- services/dimension/.project | 34 +- services/dimension/3rdparty/.classpath | 12 +- services/dimension/3rdparty/.project | 34 +- services/dimension/3rdparty/build.xml | 250 +- .../resources/schemas/dimensions_common.xsd | 66 +- services/dimension/3rdparty/pom.xml | 46 +- services/dimension/build.xml | 244 +- services/dimension/client/pom.xml | 172 +- .../client/test/DimensionXmlReplayTest.java | 84 +- .../src/test/resources/log4j.properties | 46 +- .../test-data/xmlreplay/dimension-master.xml | 32 +- .../test-data/xmlreplay/dimension.xml | 72 +- .../test-data/xmlreplay/dimension/1.xml | 18 +- .../dimension/DimensionJAXBSchema.java | 38 +- .../DimensionListItemJAXBSchema.java | 14 +- services/dimension/pom.xml | 72 +- services/dimension/service/pom.xml | 212 +- services/group/.classpath | 12 +- services/group/.project | 34 +- services/group/3rdparty/.classpath | 12 +- services/group/3rdparty/.project | 34 +- .../src/test/resources/log4j.properties | 46 +- services/hyperjaxb/pom.xml | 158 +- services/id/.classpath | 12 +- services/id/.project | 34 +- services/id/3rdparty/.classpath | 12 +- .../3rdparty/nuxeo-platform-cs-id/.classpath | 16 +- services/id/build.xml | 274 +- services/id/jaxb/.classpath | 20 +- .../src/test/resources/log4j.properties | 46 +- services/imports/.project | 34 +- services/imports/3rdparty/.project | 34 +- .../src/main/resources/META-INF/MANIFEST.MF | 44 +- .../main/resources/schemas/imports_common.xsd | 36 +- .../services/imports/nuxeo/ImportCommand.java | 260 +- .../resources/templates/service-document.xml | 98 +- .../resources/requests/authority-request.xml | 36 +- .../requests/collectionobject-request.xml | 552 ++-- services/installer/build.xml | 158 +- services/intake/.classpath | 12 +- services/intake/.project | 34 +- services/intake/3rdparty/.classpath | 12 +- services/intake/3rdparty/.project | 34 +- services/intake/3rdparty/build.xml | 258 +- services/intake/3rdparty/pom.xml | 50 +- services/intake/build.xml | 248 +- services/intake/client/pom.xml | 202 +- .../test/OrganizationAuthRefDocsTest.java | 740 ++--- .../src/test/resources/log4j.properties | 46 +- .../services/IntakeJAXBSchema.java | 46 +- .../services/IntakeListItemJAXBSchema.java | 16 +- services/intake/pom.xml | 48 +- services/intake/service/pom.xml | 222 +- .../intake/nuxeo/IntakeValidatorHandler.java | 132 +- services/jaxb/pom.xml | 98 +- .../src/main/resources/relations_common.xsd | 254 +- services/loanin/.classpath | 12 +- services/loanin/.project | 34 +- services/loanin/3rdparty/.classpath | 12 +- services/loanin/3rdparty/.project | 34 +- .../src/test/resources/log4j.properties | 46 +- services/loanout/.project | 34 +- services/loanout/3rdparty/.project | 34 +- .../src/test/resources/log4j.properties | 46 +- services/location/.classpath | 12 +- services/location/.project | 34 +- services/location/3rdparty/.classpath | 12 +- services/location/3rdparty/.project | 34 +- services/location/3rdparty/build.xml | 270 +- services/location/3rdparty/pom.xml | 46 +- services/location/build.xml | 264 +- services/location/client/pom.xml | 186 +- .../client/LocationAuthorityClientUtils.java | 638 ++-- .../src/test/resources/log4j.properties | 46 +- services/location/installer/build.xml | 122 +- .../services/LocationJAXBSchema.java | 46 +- services/location/pom.xml | 70 +- services/location/service/pom.xml | 266 +- services/media/.project | 34 +- services/media/3rdparty/.project | 34 +- .../src/test/resources/log4j.properties | 52 +- .../services/media/MediaBlobInput.java | 54 +- services/movement/.project | 34 +- services/movement/3rdparty/.project | 34 +- .../src/test/resources/log4j.properties | 46 +- services/note/.classpath | 12 +- services/note/.project | 34 +- services/note/3rdparty/.classpath | 12 +- services/note/3rdparty/.project | 34 +- services/note/3rdparty/build.xml | 258 +- .../3rdparty/nuxeo-platform-cs-note/build.xml | 280 +- .../3rdparty/nuxeo-platform-cs-note/pom.xml | 86 +- .../src/main/resources/META-INF/MANIFEST.MF | 46 +- .../resources/OSGI-INF/core-types-contrib.xml | 30 +- .../OSGI-INF/deployment-fragment.xml | 20 +- .../resources/OSGI-INF/ecm-types-contrib.xml | 60 +- .../resources/OSGI-INF/layouts-contrib.xml | 122 +- .../main/resources/schemas/notes_common.xsd | 52 +- services/note/3rdparty/pom.xml | 48 +- services/note/build.xml | 244 +- services/note/client/pom.xml | 174 +- .../services/client/NoteClient.java | 136 +- .../services/client/NoteClientUtils.java | 112 +- .../services/client/NoteProxy.java | 126 +- .../services/client/test/NoteServiceTest.java | 232 +- .../src/test/resources/log4j.properties | 46 +- services/note/jaxb/pom.xml | 78 +- .../services/note/NoteJAXBSchema.java | 40 +- .../services/note/NoteListItemJAXBSchema.java | 14 +- .../jaxb/src/main/resources/notes-common.xsd | 148 +- services/note/pom.xml | 48 +- services/note/service/pom.xml | 186 +- services/note/service/profiles.xml | 6 +- .../services/note/NoteResource.java | 116 +- .../services/note/nuxeo/NoteConstants.java | 70 +- .../note/nuxeo/NoteDocumentModelHandler.java | 332 +- .../services/test/NoteServiceTest.java | 22 +- .../note/service/src/test/resources/log4j.xml | 90 +- services/objectexit/.project | 34 +- services/objectexit/3rdparty/.project | 34 +- .../src/test/resources/log4j.properties | 46 +- services/organization/.classpath | 10 +- services/organization/.project | 34 +- services/organization/3rdparty/.classpath | 10 +- services/organization/3rdparty/.project | 34 +- services/organization/3rdparty/build.xml | 270 +- services/organization/3rdparty/pom.xml | 46 +- services/organization/build.xml | 264 +- services/organization/client/pom.xml | 180 +- .../client/OrgAuthorityClientUtils.java | 832 ++--- .../src/test/resources/log4j.properties | 46 +- services/organization/installer/build.xml | 122 +- .../services/OrganizationJAXBSchema.java | 52 +- services/organization/pom.xml | 86 +- services/organization/sample/.classpath | 10 +- services/organization/sample/.project | 34 +- services/organization/sample/pom.xml | 28 +- services/organization/sample/sample/.project | 46 +- services/organization/sample/sample/pom.xml | 224 +- .../organization/client/sample/Sample.java | 1020 +++--- .../collectionspace-client.properties | 10 +- .../sample/src/main/resources/log4j.xml | 76 +- services/organization/service/pom.xml | 264 +- services/person/.classpath | 10 +- services/person/.project | 34 +- services/person/3rdparty/.classpath | 10 +- services/person/3rdparty/.project | 34 +- services/person/3rdparty/build.xml | 278 +- services/person/3rdparty/pom.xml | 50 +- services/person/build.xml | 264 +- services/person/client/pom.xml | 182 +- .../client/PersonAuthorityClientUtils.java | 948 +++--- .../src/test/resources/log4j.properties | 50 +- services/person/installer/build.xml | 122 +- .../services/PersonJAXBSchema.java | 64 +- services/person/pom.xml | 86 +- services/person/sample/.classpath | 10 +- services/person/sample/.project | 34 +- services/person/sample/pom.xml | 28 +- services/person/sample/sample/.classpath | 64 +- services/person/sample/sample/.project | 46 +- services/person/sample/sample/pom.xml | 222 +- .../services/person/client/sample/Sample.java | 1186 +++---- .../collectionspace-client.properties | 10 +- .../sample/src/main/resources/log4j.xml | 76 +- services/person/service/pom.xml | 266 +- services/query/.classpath | 12 +- services/query/.project | 34 +- services/query/pom.xml | 56 +- services/query/service/pom.xml | 182 +- services/relation/.classpath | 12 +- services/relation/.project | 34 +- services/relation/3rdparty/.classpath | 12 +- services/relation/3rdparty/.project | 34 +- services/relation/3rdparty/build.xml | 256 +- .../nuxeo-platform-cs-relation/build.xml | 274 +- .../nuxeo-platform-cs-relation/pom.xml | 84 +- .../src/main/resources/META-INF/MANIFEST.MF | 46 +- .../resources/schemas/relations_common.xsd | 142 +- services/relation/build.xml | 250 +- services/relation/client/pom.xml | 176 +- .../src/test/resources/log4j.properties | 46 +- services/relation/pom.xml | 44 +- services/relation/service/pom.xml | 268 +- .../nuxeo/RelationValidatorHandler.java | 238 +- services/report/.classpath | 12 +- services/report/.project | 34 +- services/report/3rdparty/.classpath | 12 +- services/report/3rdparty/.project | 34 +- services/report/3rdparty/build.xml | 284 +- .../src/main/resources/META-INF/MANIFEST.MF | 46 +- .../main/resources/schemas/reports_common.xsd | 80 +- services/report/3rdparty/pom.xml | 48 +- services/report/build.xml | 248 +- services/report/client/pom.xml | 206 +- .../src/test/resources/log4j.properties | 46 +- .../services/ReportJAXBSchema.java | 38 +- services/report/pom.xml | 126 +- services/report/service/pom.xml | 232 +- .../report/nuxeo/ReportPostInitHandler.java | 164 +- .../report/nuxeo/ReportValidatorHandler.java | 36 +- services/sdk/.classpath | 12 +- services/sdk/pom.xml | 66 +- services/sdk/sample/.classpath | 20 +- services/sdk/sample/pom.xml | 120 +- .../services/sdk/sample/Sample.java | 458 +-- .../collectionspace-client.properties | 10 +- services/security/.classpath | 12 +- services/security/.project | 34 +- services/security/build.xml | 254 +- services/security/client/build.xml | 282 +- services/security/client/pom.xml | 230 +- .../src/test/resources/log4j.properties | 46 +- services/security/pom.xml | 46 +- services/vocabulary/.classpath | 12 +- services/vocabulary/.project | 34 +- services/vocabulary/3rdparty/.classpath | 12 +- services/vocabulary/3rdparty/.project | 34 +- services/vocabulary/3rdparty/build.xml | 270 +- .../src/main/resources/schemas/README.txt | 30 +- services/vocabulary/3rdparty/pom.xml | 48 +- services/vocabulary/build.xml | 264 +- services/vocabulary/client/pom.xml | 156 +- .../client/VocabularyClientUtils.java | 294 +- .../src/test/resources/log4j.properties | 46 +- services/vocabulary/installer/build.xml | 122 +- services/vocabulary/pom.xml | 90 +- services/vocabulary/sample/.classpath | 12 +- services/vocabulary/sample/.project | 34 +- services/vocabulary/sample/pom.xml | 28 +- services/vocabulary/sample/sample/.project | 46 +- services/vocabulary/sample/sample/pom.xml | 268 +- .../vocabulary/client/sample/Sample.java | 938 +++--- .../collectionspace-client.properties | 10 +- services/vocabulary/service/pom.xml | 262 +- .../src/main/resources/META-INF/MANIFEST.MF | 40 +- .../resources/schemas/workflow_common.xsd | 60 +- .../src/test/resources/log4j.properties | 46 +- 659 files changed, 57198 insertions(+), 57176 deletions(-) create mode 100644 .gitattributes diff --git a/.classpath b/.classpath index 505c7192a..ff1a8fa3c 100644 --- a/.classpath +++ b/.classpath @@ -1,10 +1,10 @@ - - - - - - - - - - + + + + + + + + + + diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..412eeda78 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,22 @@ +# Auto detect text files and perform LF normalization +* text=auto + +# Custom for Visual Studio +*.cs diff=csharp +*.sln merge=union +*.csproj merge=union +*.vbproj merge=union +*.fsproj merge=union +*.dbproj merge=union + +# Standard to msysgit +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain diff --git a/.project b/.project index 5cd13a441..8eb9f9890 100644 --- a/.project +++ b/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/3rdparty/.classpath b/3rdparty/.classpath index d7501e2c4..b8a2888f8 100644 --- a/3rdparty/.classpath +++ b/3rdparty/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/3rdparty/.project b/3rdparty/.project index 85949a7f9..f58362786 100644 --- a/3rdparty/.project +++ b/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/3rdparty/build.xml b/3rdparty/build.xml index 3c91e03e9..f0c117043 100644 --- a/3rdparty/build.xml +++ b/3rdparty/build.xml @@ -1,134 +1,134 @@ - - - - collectionspace 3rdparty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + collectionspace 3rdparty + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/3rdparty/nuxeo/.classpath b/3rdparty/nuxeo/.classpath index d7501e2c4..b8a2888f8 100644 --- a/3rdparty/nuxeo/.classpath +++ b/3rdparty/nuxeo/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/3rdparty/nuxeo/.project b/3rdparty/nuxeo/.project index 8fb749d17..a3f1889bc 100644 --- a/3rdparty/nuxeo/.project +++ b/3rdparty/nuxeo/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.3rdparty.nuxeo - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.3rdparty.nuxeo + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/3rdparty/nuxeo/build.xml b/3rdparty/nuxeo/build.xml index 71eb3207d..5ec4bb01e 100644 --- a/3rdparty/nuxeo/build.xml +++ b/3rdparty/nuxeo/build.xml @@ -1,161 +1,161 @@ - - collectionspace nuxeo - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + collectionspace nuxeo + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/3rdparty/nuxeo/nuxeo-doctype-custom/src/main/resources/META-INF/MANIFEST.MF b/3rdparty/nuxeo/nuxeo-doctype-custom/src/main/resources/META-INF/MANIFEST.MF index 8fa6e5589..fb636d6b2 100644 --- a/3rdparty/nuxeo/nuxeo-doctype-custom/src/main/resources/META-INF/MANIFEST.MF +++ b/3rdparty/nuxeo/nuxeo-doctype-custom/src/main/resources/META-INF/MANIFEST.MF @@ -1,18 +1,18 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 1 -Bundle-Name: org.collectionspace.${ServiceName}.${TenantLabel} -Bundle-SymbolicName: org.collectionspace.${ServiceName}.${TenantLabel};singleton:=true -Bundle-Version: 1.0.0 -Bundle-Localization: plugin -Bundle-Vendor: Nuxeo -Require-Bundle: org.nuxeo.runtime, - org.nuxeo.ecm.core.api, - org.nuxeo.ecm.core, - org.nuxeo.ecm.webapp.core, - org.collectionspace.collectionspace_core, - org.collectionspace.${ServiceName} -Provide-Package: org.collectionspace.${ServiceName}.${TenantLabel} -Nuxeo-Component: OSGI-INF/core-types-contrib.xml, - OSGI-INF/life-cycle-contrib.xml, - OSGI-INF/ecm-types-contrib.xml, - OSGI-INF/layouts-contrib.xml +Manifest-Version: 1.0 +Bundle-ManifestVersion: 1 +Bundle-Name: org.collectionspace.${ServiceName}.${TenantLabel} +Bundle-SymbolicName: org.collectionspace.${ServiceName}.${TenantLabel};singleton:=true +Bundle-Version: 1.0.0 +Bundle-Localization: plugin +Bundle-Vendor: Nuxeo +Require-Bundle: org.nuxeo.runtime, + org.nuxeo.ecm.core.api, + org.nuxeo.ecm.core, + org.nuxeo.ecm.webapp.core, + org.collectionspace.collectionspace_core, + org.collectionspace.${ServiceName} +Provide-Package: org.collectionspace.${ServiceName}.${TenantLabel} +Nuxeo-Component: OSGI-INF/core-types-contrib.xml, + OSGI-INF/life-cycle-contrib.xml, + OSGI-INF/ecm-types-contrib.xml, + OSGI-INF/layouts-contrib.xml diff --git a/3rdparty/nuxeo/nuxeo-doctype/src/main/resources/META-INF/MANIFEST.MF b/3rdparty/nuxeo/nuxeo-doctype/src/main/resources/META-INF/MANIFEST.MF index d9ab43c87..2a1f5c469 100644 --- a/3rdparty/nuxeo/nuxeo-doctype/src/main/resources/META-INF/MANIFEST.MF +++ b/3rdparty/nuxeo/nuxeo-doctype/src/main/resources/META-INF/MANIFEST.MF @@ -1,18 +1,18 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 1 -Bundle-Name: org.collectionspace.${ServiceName} -Bundle-SymbolicName: org.collectionspace.${ServiceName};singleton:=true -Bundle-Version: 1.0.0 -Bundle-Localization: plugin -Bundle-Vendor: Nuxeo -Require-Bundle: org.nuxeo.runtime, - org.nuxeo.ecm.core.api, - org.nuxeo.ecm.core, - org.nuxeo.ecm.webapp.core, - org.collectionspace.collectionspace_core -Provide-Package: org.collectionspace.${ServiceName} -Nuxeo-Component: OSGI-INF/core-types-contrib.xml, - OSGI-INF/life-cycle-contrib.xml, - OSGI-INF/ecm-types-contrib.xml, - OSGI-INF/layouts-contrib.xml - +Manifest-Version: 1.0 +Bundle-ManifestVersion: 1 +Bundle-Name: org.collectionspace.${ServiceName} +Bundle-SymbolicName: org.collectionspace.${ServiceName};singleton:=true +Bundle-Version: 1.0.0 +Bundle-Localization: plugin +Bundle-Vendor: Nuxeo +Require-Bundle: org.nuxeo.runtime, + org.nuxeo.ecm.core.api, + org.nuxeo.ecm.core, + org.nuxeo.ecm.webapp.core, + org.collectionspace.collectionspace_core +Provide-Package: org.collectionspace.${ServiceName} +Nuxeo-Component: OSGI-INF/core-types-contrib.xml, + OSGI-INF/life-cycle-contrib.xml, + OSGI-INF/ecm-types-contrib.xml, + OSGI-INF/layouts-contrib.xml + diff --git a/3rdparty/nuxeo/nuxeo-doctype/src/main/resources/OSGI-INF/deployment-fragment.xml b/3rdparty/nuxeo/nuxeo-doctype/src/main/resources/OSGI-INF/deployment-fragment.xml index 226075b98..270abbd5f 100644 --- a/3rdparty/nuxeo/nuxeo-doctype/src/main/resources/OSGI-INF/deployment-fragment.xml +++ b/3rdparty/nuxeo/nuxeo-doctype/src/main/resources/OSGI-INF/deployment-fragment.xml @@ -1,10 +1,10 @@ - - - - - - ${bundle.fileName} - - - - + + + + + + ${bundle.fileName} + + + + diff --git a/3rdparty/nuxeo/nuxeo-platform-collectionspace/pom.xml b/3rdparty/nuxeo/nuxeo-platform-collectionspace/pom.xml index 70a7a9b93..f9c689c3c 100644 --- a/3rdparty/nuxeo/nuxeo-platform-collectionspace/pom.xml +++ b/3rdparty/nuxeo/nuxeo-platform-collectionspace/pom.xml @@ -1,33 +1,33 @@ - - - - org.collectionspace.services - org.collectionspace.services.3rdparty.nuxeo - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.3rdparty.nuxeo.collectionspace_core - Nuxeo CollectionSpace core extension - Nuxeo Enterprise Platform: CS extensions - - - - - org.apache.maven.plugins - maven-jar-plugin - - - src/main/resources/META-INF/MANIFEST.MF - - ${eclipseVersion} - 2 - - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.3rdparty.nuxeo + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.3rdparty.nuxeo.collectionspace_core + Nuxeo CollectionSpace core extension + Nuxeo Enterprise Platform: CS extensions + + + + + org.apache.maven.plugins + maven-jar-plugin + + + src/main/resources/META-INF/MANIFEST.MF + + ${eclipseVersion} + 2 + + + + + + + diff --git a/3rdparty/nuxeo/nuxeo-platform-collectionspace/src/main/resources/META-INF/MANIFEST.MF b/3rdparty/nuxeo/nuxeo-platform-collectionspace/src/main/resources/META-INF/MANIFEST.MF index 7d63efb52..e5cac9795 100644 --- a/3rdparty/nuxeo/nuxeo-platform-collectionspace/src/main/resources/META-INF/MANIFEST.MF +++ b/3rdparty/nuxeo/nuxeo-platform-collectionspace/src/main/resources/META-INF/MANIFEST.MF @@ -1,19 +1,19 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 1 -Bundle-Name: org.collectionspace.shared -Bundle-SymbolicName: org.collectionspace.shared;singleton:=true -Bundle-Version: 1.0.0 -Bundle-Localization: plugin -Bundle-Vendor: Nuxeo -Require-Bundle: org.nuxeo.runtime, - org.nuxeo.ecm.core.api, - org.nuxeo.ecm.core, - org.nuxeo.ecm.webapp.core -Provide-Package: org.collectionspace.shared -Nuxeo-Component: OSGI-INF/core-types-contrib.xml, - OSGI-INF/default-life-cycle-contrib.xml, - OSGI-INF/ecm-types-contrib.xml, - OSGI-INF/layouts-contrib.xml, - OSGI-INF/querymodel-contrib.xml - - +Manifest-Version: 1.0 +Bundle-ManifestVersion: 1 +Bundle-Name: org.collectionspace.shared +Bundle-SymbolicName: org.collectionspace.shared;singleton:=true +Bundle-Version: 1.0.0 +Bundle-Localization: plugin +Bundle-Vendor: Nuxeo +Require-Bundle: org.nuxeo.runtime, + org.nuxeo.ecm.core.api, + org.nuxeo.ecm.core, + org.nuxeo.ecm.webapp.core +Provide-Package: org.collectionspace.shared +Nuxeo-Component: OSGI-INF/core-types-contrib.xml, + OSGI-INF/default-life-cycle-contrib.xml, + OSGI-INF/ecm-types-contrib.xml, + OSGI-INF/layouts-contrib.xml, + OSGI-INF/querymodel-contrib.xml + + diff --git a/3rdparty/nuxeo/nuxeo-platform-collectionspace/src/main/resources/OSGI-INF/deployment-fragment.xml b/3rdparty/nuxeo/nuxeo-platform-collectionspace/src/main/resources/OSGI-INF/deployment-fragment.xml index 226075b98..270abbd5f 100644 --- a/3rdparty/nuxeo/nuxeo-platform-collectionspace/src/main/resources/OSGI-INF/deployment-fragment.xml +++ b/3rdparty/nuxeo/nuxeo-platform-collectionspace/src/main/resources/OSGI-INF/deployment-fragment.xml @@ -1,10 +1,10 @@ - - - - - - ${bundle.fileName} - - - - + + + + + + ${bundle.fileName} + + + + diff --git a/3rdparty/nuxeo/nuxeo-platform-collectionspace/src/main/resources/OSGI-INF/querymodel-contrib.xml b/3rdparty/nuxeo/nuxeo-platform-collectionspace/src/main/resources/OSGI-INF/querymodel-contrib.xml index 34e84b3d4..b2cf492a6 100644 --- a/3rdparty/nuxeo/nuxeo-platform-collectionspace/src/main/resources/OSGI-INF/querymodel-contrib.xml +++ b/3rdparty/nuxeo/nuxeo-platform-collectionspace/src/main/resources/OSGI-INF/querymodel-contrib.xml @@ -1,20 +1,20 @@ - - - - org.nuxeo.ecm.webapp.querymodel.DefaultQueryModels - - - - SELECT * FROM Document WHERE ecm:parentId = ? AND - ecm:isCheckedInVersion = 0 AND ecm:mixinType != 'HiddenInNavigation' - AND ecm:currentLifeCycleState != 'deleted' AND ecm:isProxy = 0 - - - 50 - - - - + + + + org.nuxeo.ecm.webapp.querymodel.DefaultQueryModels + + + + SELECT * FROM Document WHERE ecm:parentId = ? AND + ecm:isCheckedInVersion = 0 AND ecm:mixinType != 'HiddenInNavigation' + AND ecm:currentLifeCycleState != 'deleted' AND ecm:isProxy = 0 + + + 50 + + + + diff --git a/3rdparty/nuxeo/nuxeo-platform-collectionspace/src/main/resources/schemas/subitem.xsd b/3rdparty/nuxeo/nuxeo-platform-collectionspace/src/main/resources/schemas/subitem.xsd index 75b6087cf..085c73a7a 100644 --- a/3rdparty/nuxeo/nuxeo-platform-collectionspace/src/main/resources/schemas/subitem.xsd +++ b/3rdparty/nuxeo/nuxeo-platform-collectionspace/src/main/resources/schemas/subitem.xsd @@ -1,22 +1,22 @@ - - - - - - - - - - - - + + + + + + + + + + + + diff --git a/3rdparty/nuxeo/nuxeo-platform-quote-api/pom.xml b/3rdparty/nuxeo/nuxeo-platform-quote-api/pom.xml index 9f61b74b9..470c60518 100644 --- a/3rdparty/nuxeo/nuxeo-platform-quote-api/pom.xml +++ b/3rdparty/nuxeo/nuxeo-platform-quote-api/pom.xml @@ -1,50 +1,50 @@ - - 4.0.0 - - org.collectionspace.services - org.collectionspace.services.3rdparty.nuxeo - 4.2-SNAPSHOT - - - org.collectionspace.services - org.collectionspace.services.3rdparty.nuxeo.quote-api - org.collectionspace.services.3rdparty.nuxeo.quote-api - - Nuxeo Enterprise Platform: CollectionSpace's Nuxeo Quote Service API. - - - - - org.nuxeo.ecm.core - nuxeo-core-api - ${nuxeo.core.version} - - - - - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-jar-plugin - - - src/main/resources/META-INF/MANIFEST.MF - - ${eclipseVersion} - 2 - - - - - - - - + + 4.0.0 + + org.collectionspace.services + org.collectionspace.services.3rdparty.nuxeo + 4.2-SNAPSHOT + + + org.collectionspace.services + org.collectionspace.services.3rdparty.nuxeo.quote-api + org.collectionspace.services.3rdparty.nuxeo.quote-api + + Nuxeo Enterprise Platform: CollectionSpace's Nuxeo Quote Service API. + + + + + org.nuxeo.ecm.core + nuxeo-core-api + ${nuxeo.core.version} + + + + + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-jar-plugin + + + src/main/resources/META-INF/MANIFEST.MF + + ${eclipseVersion} + 2 + + + + + + + + diff --git a/3rdparty/nuxeo/nuxeo-platform-quote/LGPL.txt b/3rdparty/nuxeo/nuxeo-platform-quote/LGPL.txt index cbee875ba..b1e3f5a26 100644 --- a/3rdparty/nuxeo/nuxeo-platform-quote/LGPL.txt +++ b/3rdparty/nuxeo/nuxeo-platform-quote/LGPL.txt @@ -1,504 +1,504 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Libraries - - If you develop a new library, and you want it to be of the greatest -possible use to the public, we recommend making it free software that -everyone can redistribute and change. You can do so by permitting -redistribution under these terms (or, alternatively, under the terms of the -ordinary General Public License). - - To apply these terms, attach the following notices to the library. It is -safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least the -"copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -Also add information on how to contact you by electronic and paper mail. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the library, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the - library `Frob' (a library for tweaking knobs) written by James Random Hacker. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! - - + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/3rdparty/nuxeo/nuxeo-platform-quote/pom.xml b/3rdparty/nuxeo/nuxeo-platform-quote/pom.xml index dde8be705..45c294801 100644 --- a/3rdparty/nuxeo/nuxeo-platform-quote/pom.xml +++ b/3rdparty/nuxeo/nuxeo-platform-quote/pom.xml @@ -1,152 +1,152 @@ - - 4.0.0 - - - org.collectionspace.services - org.collectionspace.services.3rdparty.nuxeo - 4.2-SNAPSHOT - - - org.collectionspace.services - org.collectionspace.services.3rdparty.nuxeo.quote - org.collectionspace.services.3rdparty.nuxeo.quote - - Nuxeo Enterprise Platform: CollectionSpace's Nuxeo Quote Service. - - - - - - org.collectionspace.services - org.collectionspace.services.3rdparty.nuxeo.quote-api - ${project.version} - - - - org.nuxeo.ecm.core - nuxeo-core-api - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-event - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-schema - ${nuxeo.core.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-relations-api - ${nuxeo.platform.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-api - ${nuxeo.platform.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-usermanager-api - ${nuxeo.platform.version} - - - - javax.ejb - ejb-api - - - javax.annotation - jsr250-api - - - jboss - jboss-annotations-ejb3 - - - javax.jms - jms - - - org.jboss.javaee - jboss-javaee - - - - commons-logging - commons-logging - 1.1.1 - - - log4j - log4j - 1.2.14 - provided - - - - - - javax.transaction - jta - test - - - org.nuxeo.ecm.core - nuxeo-core-jcr-connector - 1.6.2 - test - - - org.nuxeo.ecm.core - nuxeo-core-jcr-connector-test - 1.6.2 - test - - - org.nuxeo.ecm.platform - nuxeo-platform-relations-core - ${nuxeo.platform.version} - test - - - org.nuxeo.ecm.platform - nuxeo-platform-relations-jena-plugin - ${nuxeo.platform.version} - test - - - org.nuxeo.ecm.platform - nuxeo-platform-comment-core - ${nuxeo.platform.version} - test - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - src/main/resources/META-INF/MANIFEST.MF - - ${eclipseVersion} - 2 - - - - - - - - - + + 4.0.0 + + + org.collectionspace.services + org.collectionspace.services.3rdparty.nuxeo + 4.2-SNAPSHOT + + + org.collectionspace.services + org.collectionspace.services.3rdparty.nuxeo.quote + org.collectionspace.services.3rdparty.nuxeo.quote + + Nuxeo Enterprise Platform: CollectionSpace's Nuxeo Quote Service. + + + + + + org.collectionspace.services + org.collectionspace.services.3rdparty.nuxeo.quote-api + ${project.version} + + + + org.nuxeo.ecm.core + nuxeo-core-api + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-event + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-schema + ${nuxeo.core.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-relations-api + ${nuxeo.platform.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-api + ${nuxeo.platform.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-usermanager-api + ${nuxeo.platform.version} + + + + javax.ejb + ejb-api + + + javax.annotation + jsr250-api + + + jboss + jboss-annotations-ejb3 + + + javax.jms + jms + + + org.jboss.javaee + jboss-javaee + + + + commons-logging + commons-logging + 1.1.1 + + + log4j + log4j + 1.2.14 + provided + + + + + + javax.transaction + jta + test + + + org.nuxeo.ecm.core + nuxeo-core-jcr-connector + 1.6.2 + test + + + org.nuxeo.ecm.core + nuxeo-core-jcr-connector-test + 1.6.2 + test + + + org.nuxeo.ecm.platform + nuxeo-platform-relations-core + ${nuxeo.platform.version} + test + + + org.nuxeo.ecm.platform + nuxeo-platform-relations-jena-plugin + ${nuxeo.platform.version} + test + + + org.nuxeo.ecm.platform + nuxeo-platform-comment-core + ${nuxeo.platform.version} + test + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + src/main/resources/META-INF/MANIFEST.MF + + ${eclipseVersion} + 2 + + + + + + + + + diff --git a/3rdparty/nuxeo/nuxeo-server/Bundle List.txt b/3rdparty/nuxeo/nuxeo-server/Bundle List.txt index 7e8513e34..5f57a4cf8 100644 --- a/3rdparty/nuxeo/nuxeo-server/Bundle List.txt +++ b/3rdparty/nuxeo/nuxeo-server/Bundle List.txt @@ -1,36 +1,36 @@ - -nuxeo-common-${version}.jar -nuxeo-core-${version}.jar -nuxeo-core-api-${version}.jar -nuxeo-core-client-${version}.jar -nuxeo-core-convert-api-${version}.jar -nuxeo-core-event-${version}.jar -nuxeo-core-io-${version}.jar -nuxeo-core-query-${version}.jar -nuxeo-core-schema-${version}.jar -nuxeo-core-storage-sql-${version}.jar -nuxeo-core-storage-sql-extensions-${version}.jar -nuxeo-core-storage-sql-ra-${version}.jar -nuxeo-platform-api-${version}.jar -nuxeo-platform-audit-api-${version}.jar -nuxeo-platform-directory-api-${version}.jar -nuxeo-platform-filemanager-api-${version}.jar -nuxeo-platform-filemanager-core-${version}.jar -nuxeo-platform-imaging-api-${version}.jar -nuxeo-platform-imaging-core-${version}.jar -nuxeo-platform-imaging-preview-${version}.jar -nuxeo-platform-login-${version}.jar -nuxeo-platform-mimetype-api-${version}.jar -nuxeo-platform-mimetype-core-${version}.jar -nuxeo-platform-query-api-${version}.jar -nuxeo-platform-search-api-${version}.jar -nuxeo-platform-types-api-${version}.jar -nuxeo-platform-types-core-${version}.jar -nuxeo-platform-usermanager-api-${version}.jar -nuxeo-runtime-${version}.jar -nuxeo-runtime-datasource-${version}.jar -nuxeo-runtime-jtajca-${version}.jar -nuxeo-runtime-management-${version}.jar -nuxeo-runtime-osgi-${version}.jar -nuxeo-runtime-remoting-${version}.jar -nuxeo-runtime-scripting-${version}.jar + +nuxeo-common-${version}.jar +nuxeo-core-${version}.jar +nuxeo-core-api-${version}.jar +nuxeo-core-client-${version}.jar +nuxeo-core-convert-api-${version}.jar +nuxeo-core-event-${version}.jar +nuxeo-core-io-${version}.jar +nuxeo-core-query-${version}.jar +nuxeo-core-schema-${version}.jar +nuxeo-core-storage-sql-${version}.jar +nuxeo-core-storage-sql-extensions-${version}.jar +nuxeo-core-storage-sql-ra-${version}.jar +nuxeo-platform-api-${version}.jar +nuxeo-platform-audit-api-${version}.jar +nuxeo-platform-directory-api-${version}.jar +nuxeo-platform-filemanager-api-${version}.jar +nuxeo-platform-filemanager-core-${version}.jar +nuxeo-platform-imaging-api-${version}.jar +nuxeo-platform-imaging-core-${version}.jar +nuxeo-platform-imaging-preview-${version}.jar +nuxeo-platform-login-${version}.jar +nuxeo-platform-mimetype-api-${version}.jar +nuxeo-platform-mimetype-core-${version}.jar +nuxeo-platform-query-api-${version}.jar +nuxeo-platform-search-api-${version}.jar +nuxeo-platform-types-api-${version}.jar +nuxeo-platform-types-core-${version}.jar +nuxeo-platform-usermanager-api-${version}.jar +nuxeo-runtime-${version}.jar +nuxeo-runtime-datasource-${version}.jar +nuxeo-runtime-jtajca-${version}.jar +nuxeo-runtime-management-${version}.jar +nuxeo-runtime-osgi-${version}.jar +nuxeo-runtime-remoting-${version}.jar +nuxeo-runtime-scripting-${version}.jar diff --git a/build.properties b/build.properties index e42358834..5177f9d47 100644 --- a/build.properties +++ b/build.properties @@ -1,177 +1,177 @@ -host=127.0.0.1 -#cspace -# Instance IDs help identify the databases and database users that belong to -# a particular CollectionSpace server instance, in a configuration where -# multiple CollectionSpace servers all share a single database server. -# The instance ID is blank by default. If it is added, by convention, -# instance IDs should begin with an underscore (_). E.g.: _trs80 -cspace.instance.id= -release.version=4.2 -cspace.release=${release.version}-SNAPSHOT -cspace.services.release=cspace-services-${cspace.release} -domain.cspace=cspace-services -cspace.services.context=${domain.cspace} -cspace.services.war=${cspace.services.context}.war -domain.nuxeo=nuxeo-server - -#nuxeo -nuxeo.release=5.5-HF07 -nuxeo.ear=nuxeo.ear -nuxeo.system=bundles - -## #old# nuxeo.plugins=${nuxeo.ear}/plugins -nuxeo.plugins=plugins - -## #old# -nuxeo.templates=templates - -## #old# distribution -dist=dist -dist.cspace=${dist}/cspace -dist.nuxeo=${dist}/nuxeo -dist.installer=${dist}/installer -dist.installer.services=${dist.installer}/services - -## #old# dist cspace domain -dist.domain.cspace=${domain.cspace} -dist.server.cspace=${dist.cspace}/server/${jee.domain.cspace} -dist.deploy.cspace=${dist.server.cspace}/deploy -dist.lib.cspace=${dist.server.cspace}/lib - -## #old# dist nuxeo domain -dist.domain.nuxeo=${domain.nuxeo} -dist.server.nuxeo=${dist.nuxeo}/server/${jee.domain.nuxeo} -dist.deploy.nuxeo=${dist.server.nuxeo}/deploy -dist.lib.nuxeo=${dist.server.nuxeo}/lib -dist.deploy.nuxeo.system=${dist.deploy.nuxeo}/${nuxeo.system} -dist.deploy.nuxeo.plugins=${dist.deploy.nuxeo}/${nuxeo.plugins} - -#JEE Application Server -jee.release=apache-tomcat-6.0.33 -jee.dir=${env.CSPACE_JEESERVER_HOME} -jee.home=${jee.dir} -jee.bin=${jee.home}/bin - -#JEE Application Server cspace domain -jee.domain.cspace=${domain.cspace} -jee.domain.cspace.port=8180 -jee.server.cspace=${jee.home} -jee.deploy.cspace=${jee.server.cspace}/webapps -jee.lib.cspace=${jee.server.cspace}/lib -jee.deploy.cspace.services=${jee.deploy.cspace}/${cspace.services.war} - -#JEE Application Server nuxeo domain -jee.domain.nuxeo=${domain.nuxeo} -##old# #jee.domain.nuxeo.port=8080 -jee.server.nuxeo=${jee.home}/${jee.domain.nuxeo} -jee.deploy.nuxeo=${jee.server.nuxeo} -jee.lib.nuxeo=${jee.server.nuxeo}/lib -jee.deploy.nuxeo.system=${jee.deploy.nuxeo}/${nuxeo.system} -jee.deploy.nuxeo.plugins=${jee.deploy.nuxeo}/${nuxeo.plugins} - -# Apache Tomcat specific variables -catalina.engine=Catalina -catalina.hostname=localhost -catalina.base=${jee.dir} -catalina.context.cspace=${jee.dir}/conf/${catalina.engine}/${catalina.hostname}/${cspace.services.context}.xml - -#nuxeo database templates directory -##old# nuxeo.templates.dir=${jboss.home}/${nuxeo.templates} - -#nuxeo main config file -nuxeo.main.config.file=${jee.bin}/nuxeo.conf -#nuxeo database templates directory -nuxeo.templates.dir=${jee.home}/${nuxeo.templates} - -db.base.dir=${jee.server.cspace}/cspace/services/db - -#database - select one or the other (not both!), and then uncomment the -# appropriate section below the common settings -#db=mysql|postgresql -# db=mysql -db=postgresql - -#For mysql, uncomment this, and comment out postgres section -# db.port=3306 -# db.driver.jar=${db.base.dir}/jdbc_drivers/mysql-connector-java-5.1.7.jar -# db.jdbc.driver.class=com.mysql.jdbc.Driver -# db.dialect=org.hibernate.dialect.MySQLDialect -# db.typemapping=mySQL -# db.exceptionsorter=org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter -# db.spring.acl.classIdentityQuery=SELECT @@IDENTITY -# db.spring.acl.sidIdentityQuery=SELECT @@IDENTITY -# db.xaDataSource=com.mysql.jdbc.jdbc2.optional.MysqlXADataSource - -#For postgresql, uncomment this, and comment out mysql section -db.port=5432 -db.driver.jar=${db.base.dir}/jdbc_drivers/postgresql-9.1-901.jdbc4.jar -db.jdbc.driver.class=org.postgresql.Driver -db.dialect=org.hibernate.dialect.PostgreSQLDialect -db.typemapping=PostgreSQL 8.0 -# Should be org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLExceptionSorter -# but current JBoss does not seem to include it... -db.exceptionsorter= -db.spring.acl.classIdentityQuery=select currval(pg_get_serial_sequence('acl_class', 'id')) -db.spring.acl.sidIdentityQuery=select currval(pg_get_serial_sequence('acl_sid', 'id')) -db.xaDataSource=org.postgresql.xa.PGXADataSource - -#Hibernate properties for Ant and Maven plugins -hibernate.dialect=${db.dialect} - -#database common settings -db.script.dir=${jee.server.cspace}/cspace/services/db/${db} - -db.csadmin.name=postgres -db.csadmin.user=csadmin -db.csadmin.user.password=${env.DB_CSADMIN_PASSWORD} - -db.nuxeo.name=nuxeo${cspace.instance.id} -db.nuxeo.user=${db.nuxeo.name} -db.nuxeo.user.password=${env.DB_NUXEO_PASSWORD} - -db.cspace.name=cspace${cspace.instance.id} -db.cspace.user=${db.cspace.name} -db.cspace.user.password=${env.DB_CSPACE_PASSWORD} - -db.reader.user=reader${cspace.instance.id} -db.reader.user.password=${env.DB_READER_PASSWORD} - -db.host=localhost -db.jdbc.baseurl=jdbc:${db}://${db.host}:${db.port} - -# -# JDBC options that can be added to the database URL. We need to supply an "encoded" version -# of the options for cases where the URL is processed inside of XML scripts/files -# - -# Use the following JDBC options to enable CSpace to establish SSL -# connections with the database server. -# -# ssl=true ;means we can talk SSL to the database server -# sslfactory ;set this to the SSL factory class. The default is to perform validation. Use NonValidatingFactory class to skip validation -# foo=true ;an extra "throw way" options seems to be needed to prevent parsing errors for some tools/code. - -# -# Here is an example of how to set the JDBC options for connecting to an SSL enabled -# PostgreSQL server. -# -#db.jdbc.urloptions=ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory&foo=true -#db.jdbc.urloptions.encoded=ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory&foo=true - -# -# By default, as placeholders, we'll supply meaningless JDBC options -both encoded and non-encode forms. -# -db.jdbc.urloptions=foo=true&bar=false -db.jdbc.urloptions.encoded=foo=true&bar=false - -# -# JDBC urls that CollectionSpace needs to talk to the "admin" database, Nuxeo databases, and the "cspace" database (i.e., the AuthN/AuthZ database) -# -db.jdbc.csadmin.url=${db.jdbc.baseurl}/${db.csadmin.name}?${db.jdbc.urloptions} -db.jdbc.csadmin.url.encoded=${db.jdbc.baseurl}/${db.csadmin.name}?${db.jdbc.urloptions.encoded} - -db.jdbc.nuxeo.url=${db.jdbc.baseurl}/${DatabaseName}?${db.jdbc.urloptions} -db.jdbc.nuxeo.url.encoded=${db.jdbc.baseurl}/${DatabaseName}?${db.jdbc.urloptions.encoded} - -db.jdbc.cspace.url=${db.jdbc.baseurl}/${db.cspace.name}?${db.jdbc.urloptions} +host=127.0.0.1 +#cspace +# Instance IDs help identify the databases and database users that belong to +# a particular CollectionSpace server instance, in a configuration where +# multiple CollectionSpace servers all share a single database server. +# The instance ID is blank by default. If it is added, by convention, +# instance IDs should begin with an underscore (_). E.g.: _trs80 +cspace.instance.id= +release.version=4.2 +cspace.release=${release.version}-SNAPSHOT +cspace.services.release=cspace-services-${cspace.release} +domain.cspace=cspace-services +cspace.services.context=${domain.cspace} +cspace.services.war=${cspace.services.context}.war +domain.nuxeo=nuxeo-server + +#nuxeo +nuxeo.release=5.5-HF07 +nuxeo.ear=nuxeo.ear +nuxeo.system=bundles + +## #old# nuxeo.plugins=${nuxeo.ear}/plugins +nuxeo.plugins=plugins + +## #old# +nuxeo.templates=templates + +## #old# distribution +dist=dist +dist.cspace=${dist}/cspace +dist.nuxeo=${dist}/nuxeo +dist.installer=${dist}/installer +dist.installer.services=${dist.installer}/services + +## #old# dist cspace domain +dist.domain.cspace=${domain.cspace} +dist.server.cspace=${dist.cspace}/server/${jee.domain.cspace} +dist.deploy.cspace=${dist.server.cspace}/deploy +dist.lib.cspace=${dist.server.cspace}/lib + +## #old# dist nuxeo domain +dist.domain.nuxeo=${domain.nuxeo} +dist.server.nuxeo=${dist.nuxeo}/server/${jee.domain.nuxeo} +dist.deploy.nuxeo=${dist.server.nuxeo}/deploy +dist.lib.nuxeo=${dist.server.nuxeo}/lib +dist.deploy.nuxeo.system=${dist.deploy.nuxeo}/${nuxeo.system} +dist.deploy.nuxeo.plugins=${dist.deploy.nuxeo}/${nuxeo.plugins} + +#JEE Application Server +jee.release=apache-tomcat-6.0.33 +jee.dir=${env.CSPACE_JEESERVER_HOME} +jee.home=${jee.dir} +jee.bin=${jee.home}/bin + +#JEE Application Server cspace domain +jee.domain.cspace=${domain.cspace} +jee.domain.cspace.port=8180 +jee.server.cspace=${jee.home} +jee.deploy.cspace=${jee.server.cspace}/webapps +jee.lib.cspace=${jee.server.cspace}/lib +jee.deploy.cspace.services=${jee.deploy.cspace}/${cspace.services.war} + +#JEE Application Server nuxeo domain +jee.domain.nuxeo=${domain.nuxeo} +##old# #jee.domain.nuxeo.port=8080 +jee.server.nuxeo=${jee.home}/${jee.domain.nuxeo} +jee.deploy.nuxeo=${jee.server.nuxeo} +jee.lib.nuxeo=${jee.server.nuxeo}/lib +jee.deploy.nuxeo.system=${jee.deploy.nuxeo}/${nuxeo.system} +jee.deploy.nuxeo.plugins=${jee.deploy.nuxeo}/${nuxeo.plugins} + +# Apache Tomcat specific variables +catalina.engine=Catalina +catalina.hostname=localhost +catalina.base=${jee.dir} +catalina.context.cspace=${jee.dir}/conf/${catalina.engine}/${catalina.hostname}/${cspace.services.context}.xml + +#nuxeo database templates directory +##old# nuxeo.templates.dir=${jboss.home}/${nuxeo.templates} + +#nuxeo main config file +nuxeo.main.config.file=${jee.bin}/nuxeo.conf +#nuxeo database templates directory +nuxeo.templates.dir=${jee.home}/${nuxeo.templates} + +db.base.dir=${jee.server.cspace}/cspace/services/db + +#database - select one or the other (not both!), and then uncomment the +# appropriate section below the common settings +#db=mysql|postgresql +# db=mysql +db=postgresql + +#For mysql, uncomment this, and comment out postgres section +# db.port=3306 +# db.driver.jar=${db.base.dir}/jdbc_drivers/mysql-connector-java-5.1.7.jar +# db.jdbc.driver.class=com.mysql.jdbc.Driver +# db.dialect=org.hibernate.dialect.MySQLDialect +# db.typemapping=mySQL +# db.exceptionsorter=org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter +# db.spring.acl.classIdentityQuery=SELECT @@IDENTITY +# db.spring.acl.sidIdentityQuery=SELECT @@IDENTITY +# db.xaDataSource=com.mysql.jdbc.jdbc2.optional.MysqlXADataSource + +#For postgresql, uncomment this, and comment out mysql section +db.port=5432 +db.driver.jar=${db.base.dir}/jdbc_drivers/postgresql-9.1-901.jdbc4.jar +db.jdbc.driver.class=org.postgresql.Driver +db.dialect=org.hibernate.dialect.PostgreSQLDialect +db.typemapping=PostgreSQL 8.0 +# Should be org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLExceptionSorter +# but current JBoss does not seem to include it... +db.exceptionsorter= +db.spring.acl.classIdentityQuery=select currval(pg_get_serial_sequence('acl_class', 'id')) +db.spring.acl.sidIdentityQuery=select currval(pg_get_serial_sequence('acl_sid', 'id')) +db.xaDataSource=org.postgresql.xa.PGXADataSource + +#Hibernate properties for Ant and Maven plugins +hibernate.dialect=${db.dialect} + +#database common settings +db.script.dir=${jee.server.cspace}/cspace/services/db/${db} + +db.csadmin.name=postgres +db.csadmin.user=csadmin +db.csadmin.user.password=${env.DB_CSADMIN_PASSWORD} + +db.nuxeo.name=nuxeo${cspace.instance.id} +db.nuxeo.user=${db.nuxeo.name} +db.nuxeo.user.password=${env.DB_NUXEO_PASSWORD} + +db.cspace.name=cspace${cspace.instance.id} +db.cspace.user=${db.cspace.name} +db.cspace.user.password=${env.DB_CSPACE_PASSWORD} + +db.reader.user=reader${cspace.instance.id} +db.reader.user.password=${env.DB_READER_PASSWORD} + +db.host=localhost +db.jdbc.baseurl=jdbc:${db}://${db.host}:${db.port} + +# +# JDBC options that can be added to the database URL. We need to supply an "encoded" version +# of the options for cases where the URL is processed inside of XML scripts/files +# + +# Use the following JDBC options to enable CSpace to establish SSL +# connections with the database server. +# +# ssl=true ;means we can talk SSL to the database server +# sslfactory ;set this to the SSL factory class. The default is to perform validation. Use NonValidatingFactory class to skip validation +# foo=true ;an extra "throw way" options seems to be needed to prevent parsing errors for some tools/code. + +# +# Here is an example of how to set the JDBC options for connecting to an SSL enabled +# PostgreSQL server. +# +#db.jdbc.urloptions=ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory&foo=true +#db.jdbc.urloptions.encoded=ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory&foo=true + +# +# By default, as placeholders, we'll supply meaningless JDBC options -both encoded and non-encode forms. +# +db.jdbc.urloptions=foo=true&bar=false +db.jdbc.urloptions.encoded=foo=true&bar=false + +# +# JDBC urls that CollectionSpace needs to talk to the "admin" database, Nuxeo databases, and the "cspace" database (i.e., the AuthN/AuthZ database) +# +db.jdbc.csadmin.url=${db.jdbc.baseurl}/${db.csadmin.name}?${db.jdbc.urloptions} +db.jdbc.csadmin.url.encoded=${db.jdbc.baseurl}/${db.csadmin.name}?${db.jdbc.urloptions.encoded} + +db.jdbc.nuxeo.url=${db.jdbc.baseurl}/${DatabaseName}?${db.jdbc.urloptions} +db.jdbc.nuxeo.url.encoded=${db.jdbc.baseurl}/${DatabaseName}?${db.jdbc.urloptions.encoded} + +db.jdbc.cspace.url=${db.jdbc.baseurl}/${db.cspace.name}?${db.jdbc.urloptions} db.jdbc.cspace.url.encoded=${db.jdbc.baseurl}/${db.cspace.name}?${db.jdbc.urloptions.encoded} \ No newline at end of file diff --git a/build.xml b/build.xml index b65637f62..41c0ba0b6 100644 --- a/build.xml +++ b/build.xml @@ -1,346 +1,346 @@ - - Collectionspace Services - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + Collectionspace Services + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/installer/build.xml b/installer/build.xml index 20ac2d6f8..9e8bc943a 100644 --- a/installer/build.xml +++ b/installer/build.xml @@ -1,106 +1,106 @@ - - - collectionspace services - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + collectionspace services + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/nbproject/project.xml b/nbproject/project.xml index 174e90fb5..d72cfac40 100644 --- a/nbproject/project.xml +++ b/nbproject/project.xml @@ -1,66 +1,66 @@ - - - org.netbeans.modules.ant.freeform - - - Services - - - - Services - - - - - . - UTF-8 - - - - java - src - UTF-8 - - - - - package - - - clean - - - dist - - - clean - package - - - - - - - src - - - build.xml - - - - - - - - - - - - - - src - 1.5 - - - - + + + org.netbeans.modules.ant.freeform + + + Services + + + + Services + + + + + . + UTF-8 + + + + java + src + UTF-8 + + + + + package + + + clean + + + dist + + + clean + package + + + + + + + src + + + build.xml + + + + + + + + + + + + + + src + 1.5 + + + + diff --git a/pom.xml b/pom.xml index 2c7dc57c8..4c8680664 100644 --- a/pom.xml +++ b/pom.xml @@ -1,467 +1,467 @@ - - - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services - 4.2-SNAPSHOT - pom - services - - - UTF-8 - 4.2-SNAPSHOT - 4.2-SNAPSHOT - 5.5.0-HF07 - ${nuxeo.general.release} - ${nuxeo.general.release} - ${nuxeo.general.release} - 3.0.5.RELEASE - 3.0.5.RELEASE - - - - - libs-release-local - libs-release-local - http://nightly.collectionspace.org:8081/artifactory/libs-release-local - - - libs-snapshot-local - libs-snapshot-local - http://nightly.collectionspace.org:8081/artifactory/libs-snapshot-local - - - - - 3rdparty - services - - - - - collectionspace-remote-repos - collectionspace-remote-repos - http://nightly.collectionspace.org:8081/artifactory/remote-repos - - false - - - - libs-release-local - libs-release-local - http://nightly.collectionspace.org:8081/artifactory/libs-release-local - - false - - - - repo1 - Maven repo1 - http://repo1.maven.org/maven2 - - false - - - - repo2 - Maven repo2 - http://repo2.maven.org/maven2 - - false - - - - maven2-repository.dev.java.net - Java.net Maven 2 Repository - http://download.java.net/maven/2 - - false - - - - - - jboss.org - https://repository.jboss.org/nexus - - false - - - - - jboss.com - http://repository.jboss.org/nexus/content/groups/public-jboss - - false - - - - - codehaus repo - codehaus repo - http://repository.codehaus.org - - false - - - - - nuxeo-public - nuxeo-public - http://nightly.collectionspace.org:8081/artifactory/nuxeo-public - - true - - - false - - - - - public-snapshot - http://maven.nuxeo.org/public-snapshot - - - false - - - false - - - - - - public - http://maven.nuxeo.org/public - - - true - - - false - - - - - - false - - - true - - el4jReleaseRepositoryExternal - External release repository of the EL4J project - http://public-el4.elca-services.ch/el4j/maven2repository - - - - - false - - - true - - Apache - External release repository of the Apache projects - https://repository.apache.org/content/groups/public/ - - - - - - - collectionspace-remote-repos - collectionspace-remote-repos - http://nightly.collectionspace.org:8081/artifactory/remote-repos - - false - - - - repo1 - Maven repo1 - http://repo1.maven.org/maven2 - - false - - - - maven repo - maven repo - http://repo2.maven.org/maven2 - - false - - - - maven2-repository.dev.java.net - http://download.java.net/maven/2 - - false - - - - Codehaus Repository - http://repository.codehaus.org/ - - true - - - false - - - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.6.1 - - public - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3 - - 1.7 - 1.7 - - - - org.apache.maven.plugins - maven-assembly-plugin - - - - - - org.apache.maven.plugins - maven-war-plugin - 2.1.1 - - WEB-INF/lib/*.jar - - - true - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.2 - - - - org.apache.maven.plugins - maven-dependency-plugin - - - classpath - - build-classpath - - - classpath - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.jvnet.hyperjaxb3 - maven-hyperjaxb3-plugin - [0.5.6,) - - generate - - - - - - - - - - org.apache.maven.plugins - - - maven-antrun-plugin - - - [1.3,) - - - run - - - - - - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - maven-antrun-plugin - - - check-environment-vars - validate - - run - - - - - - - - - - - - - - - - - - - - - - - - - org.slf4j - slf4j-api - 1.6.1 - - - org.slf4j - slf4j-log4j12 - 1.6.1 - - - org.testng - testng - 6.1.1 - - test - - - javax.ejb - ejb - ${jboss.ejb.version} - provided - - - javax.annotation - jsr250-api - 1.0 - provided - - - javax.jms - jms - 1.1 - provided - - - javax.transaction - jta - 1.1 - - - - - org.jboss.remoting - jboss-remoting - 2.5.1 - provided - - - jboss - jboss-annotations-ejb3 - 3.0-RC8 - provided - - - org.jboss.javaee - jboss-javaee - 5.0.1.GA - provided - - - - javax.ejb - ejb-api - 3.0 - provided - - - - - - - - org.apache.maven.plugins - maven-project-info-reports-plugin - 2.6 - - - - - - dependencies - - - - - - - - - + + + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services + 4.2-SNAPSHOT + pom + services + + + UTF-8 + 4.2-SNAPSHOT + 4.2-SNAPSHOT + 5.5.0-HF07 + ${nuxeo.general.release} + ${nuxeo.general.release} + ${nuxeo.general.release} + 3.0.5.RELEASE + 3.0.5.RELEASE + + + + + libs-release-local + libs-release-local + http://nightly.collectionspace.org:8081/artifactory/libs-release-local + + + libs-snapshot-local + libs-snapshot-local + http://nightly.collectionspace.org:8081/artifactory/libs-snapshot-local + + + + + 3rdparty + services + + + + + collectionspace-remote-repos + collectionspace-remote-repos + http://nightly.collectionspace.org:8081/artifactory/remote-repos + + false + + + + libs-release-local + libs-release-local + http://nightly.collectionspace.org:8081/artifactory/libs-release-local + + false + + + + repo1 + Maven repo1 + http://repo1.maven.org/maven2 + + false + + + + repo2 + Maven repo2 + http://repo2.maven.org/maven2 + + false + + + + maven2-repository.dev.java.net + Java.net Maven 2 Repository + http://download.java.net/maven/2 + + false + + + + + + jboss.org + https://repository.jboss.org/nexus + + false + + + + + jboss.com + http://repository.jboss.org/nexus/content/groups/public-jboss + + false + + + + + codehaus repo + codehaus repo + http://repository.codehaus.org + + false + + + + + nuxeo-public + nuxeo-public + http://nightly.collectionspace.org:8081/artifactory/nuxeo-public + + true + + + false + + + + + public-snapshot + http://maven.nuxeo.org/public-snapshot + + + false + + + false + + + + + + public + http://maven.nuxeo.org/public + + + true + + + false + + + + + + false + + + true + + el4jReleaseRepositoryExternal + External release repository of the EL4J project + http://public-el4.elca-services.ch/el4j/maven2repository + + + + + false + + + true + + Apache + External release repository of the Apache projects + https://repository.apache.org/content/groups/public/ + + + + + + + collectionspace-remote-repos + collectionspace-remote-repos + http://nightly.collectionspace.org:8081/artifactory/remote-repos + + false + + + + repo1 + Maven repo1 + http://repo1.maven.org/maven2 + + false + + + + maven repo + maven repo + http://repo2.maven.org/maven2 + + false + + + + maven2-repository.dev.java.net + http://download.java.net/maven/2 + + false + + + + Codehaus Repository + http://repository.codehaus.org/ + + true + + + false + + + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.6.1 + + public + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3 + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-assembly-plugin + + + + + + org.apache.maven.plugins + maven-war-plugin + 2.1.1 + + WEB-INF/lib/*.jar + + + true + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + org.apache.maven.plugins + maven-dependency-plugin + + + classpath + + build-classpath + + + classpath + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + org.jvnet.hyperjaxb3 + maven-hyperjaxb3-plugin + [0.5.6,) + + generate + + + + + + + + + + org.apache.maven.plugins + + + maven-antrun-plugin + + + [1.3,) + + + run + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + maven-antrun-plugin + + + check-environment-vars + validate + + run + + + + + + + + + + + + + + + + + + + + + + + + + org.slf4j + slf4j-api + 1.6.1 + + + org.slf4j + slf4j-log4j12 + 1.6.1 + + + org.testng + testng + 6.1.1 + + test + + + javax.ejb + ejb + ${jboss.ejb.version} + provided + + + javax.annotation + jsr250-api + 1.0 + provided + + + javax.jms + jms + 1.1 + provided + + + javax.transaction + jta + 1.1 + + + + + org.jboss.remoting + jboss-remoting + 2.5.1 + provided + + + jboss + jboss-annotations-ejb3 + 3.0-RC8 + provided + + + org.jboss.javaee + jboss-javaee + 5.0.1.GA + provided + + + + javax.ejb + ejb-api + 3.0 + provided + + + + + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.6 + + + + + + dependencies + + + + + + + + + diff --git a/services/.classpath b/services/.classpath index 046988541..25df93560 100644 --- a/services/.classpath +++ b/services/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/.project b/services/.project index 62e96255f..78d6efb7d 100644 --- a/services/.project +++ b/services/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.main - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.main + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/IntegrationTests/pom.xml b/services/IntegrationTests/pom.xml index 4f0c76dd2..741d64810 100644 --- a/services/IntegrationTests/pom.xml +++ b/services/IntegrationTests/pom.xml @@ -1,186 +1,186 @@ - - - - org.collectionspace.services - org.collectionspace.services.main - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.IntegrationTests - services.IntegrationTests - jar - - - - org.slf4j - slf4j-api - test - - - org.slf4j - slf4j-log4j12 - test - - - - org.collectionspace.services - org.collectionspace.services.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.collectionobject.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.collectionobject.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.intake.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.intake.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.dimension.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.dimension.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.relation.client - ${project.version} - - - - commons-cli - commons-cli - - - org.testng - testng - compile - - - org.jboss.resteasy - resteasy-jaxrs - - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - commons-httpclient - commons-httpclient - - - javax.security - jaas - 1.0.01 - provided - - - dom4j - dom4j - 1.6.1 - provided - - - jaxen - jaxen - 1.1.1 - provided - - - org.apache.commons - commons-jexl - 2.0.1 - - - jdom - jdom - 1.0 - provided - - - - - collectionspace-services-IntegrationTests - - - org.apache.maven.plugins - maven-jar-plugin - - - - test-jar - - - - - - - org.codehaus.mojo - exec-maven-plugin - - - - java - - - - - org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplay - - -xmlReplayBaseDir - ${basedir}/src/test/resources/test-data/xmlreplay - - - - - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.main + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.IntegrationTests + services.IntegrationTests + jar + + + + org.slf4j + slf4j-api + test + + + org.slf4j + slf4j-log4j12 + test + + + + org.collectionspace.services + org.collectionspace.services.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.collectionobject.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.collectionobject.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.intake.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.intake.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.dimension.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.dimension.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.relation.client + ${project.version} + + + + commons-cli + commons-cli + + + org.testng + testng + compile + + + org.jboss.resteasy + resteasy-jaxrs + + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + commons-httpclient + commons-httpclient + + + javax.security + jaas + 1.0.01 + provided + + + dom4j + dom4j + 1.6.1 + provided + + + jaxen + jaxen + 1.1.1 + provided + + + org.apache.commons + commons-jexl + 2.0.1 + + + jdom + jdom + 1.0 + provided + + + + + collectionspace-services-IntegrationTests + + + org.apache.maven.plugins + maven-jar-plugin + + + + test-jar + + + + + + + org.codehaus.mojo + exec-maven-plugin + + + + java + + + + + org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplay + + -xmlReplayBaseDir + ${basedir}/src/test/resources/test-data/xmlreplay + + + + + + + + + + diff --git a/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/PayloadLogger.java b/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/PayloadLogger.java index 905abb1a6..2d3ab5cac 100644 --- a/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/PayloadLogger.java +++ b/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/PayloadLogger.java @@ -1,543 +1,543 @@ -/** - * 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 (c) 2009 Regents of the University of California - * - * 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.IntegrationTests.xmlreplay; - -import org.collectionspace.services.common.api.Tools; - -import java.io.*; -import java.util.ArrayList; -import java.util.List; - -public class PayloadLogger{ - - public static void saveReport(){ - reporter.writeTable(); - } - - private static Reporter reporter = new Reporter(); - - private static volatile int ID = 1000; - public String getID(){ - return ""+ID; - } - - private static String DD = "--"; - private static String LABEL="LABEL: "; - - static class Reporter { - public Reporter(){ - table.append("\r\n"); - } - public static final String START = ""; - - public void writeTable(){ - table.append("
"; - public static final String SEP = ""; - public static final String END = "
"); - saveFile("./xml/", "results.html", table.toString()); - } - - private StringBuffer table = new StringBuffer(); - - public synchronized void finished(HttpTraffic traffic){ - String direction = traffic.isRequest ? - "==>" - : - " <=="; - table.append(START) - .append(direction) - .append(SEP) - .append(traffic==null ? "null" : traffic.toRow(SEP, this)) - .append(END); - } - - public synchronized void finished(List trafficList){ - for (HttpTraffic traffic: trafficList){ - finished(traffic); - } - } - - public static String link(String desc, String url){ - return ""+desc+""; - } - public static final String newline = "
\r\n"; - - } - - - static class HttpTraffic { - public HttpTraffic(){ - payloads = new ArrayList(); - } - public List payloads; - public String method = ""; - public String url = ""; - public String queryParams = ""; - public String message = ""; - public int responseCode = 0; - public String boundary = ""; - public String location = ""; - public long contentLength = -1; - public boolean isRequest = true; - public boolean extra = false; - public String ID = "0"; - public int nexti = 0; - - public Part getPart(String label){ - for (Part part : payloads){ - if (part.label.equalsIgnoreCase(label)){ - return part; - } - } - return null; - } - - public String toRow(String sep, Reporter reporter){ - StringBuffer b = new StringBuffer(); - for (Part part : payloads){ - String name = part.label; - if (part.filename.length()==0){ - continue; - } - if (name.trim().length()<=0){ - name = ID; - } - name = name+" ("+part.filetype+')'; - String link = reporter.link(name, part.filename); - b.append(link) - .append(reporter.newline); - } - String parts = b.toString(); - if (isRequest){ - return ID+sep - +method+sep - +url+sep - +queryParams+sep - +sep - +parts; - } else { - return ID+sep - +responseCode+sep - +message+sep - +location+sep - +contentLength+sep - +url - +parts; - } - } - } - - static class Part { - public Part(String boundary){ - this.boundary = boundary; - } - public boolean isMultipart(){ - return boundary.length()>0; - } - public String toString(){ - return "Part:"+label+";"; - } - public String filename = ""; - public String filetype = ""; - public String boundary; - public StringBuffer buffer = new StringBuffer(); - public String getContent(){ - return buffer.toString(); - } - public String label = ""; - public int readPart(String[]lines, int i){ - String line = ""; - boolean readingPartHeaders = true; - while(readingPartHeaders){ - line = killTrailingWS(lines[i]); - if (line.toUpperCase().startsWith(LABEL)){ - this.label = line.substring(LABEL.length()).trim(); - } else if (line.trim().length()==0){ - readingPartHeaders = false; - } - i++; - } - while (i 2) { - System.err.println("WARNING: too many tokens after boundary= on Content-Type: header line: " + headerLine); - } - } - return boundary; - } - - /** places the boundary on the HttpTraffic in parameter object if boundary found in header "Content-Type:". - * @return the index of the NEXT line the caller should read. */ - protected static int readHeaders(HttpTraffic traffic, String[]lines, int i){ - int lineCount = lines.length; - String line, lineUP; - // Now read headers until we are ready for payload or parts. - while (i 2){ - System.err.println("WARNING: too many tokens after boundary= on Content-Type: header line: "+line); - } - } else if (lineUP.startsWith("LOCATION: ")){ - traffic.location = killTrailingWS(line.substring("LOCATION: ".length())); - } else if (lineUP.startsWith("CONTENT-LENGTH: ")){ - traffic.contentLength = Integer.parseInt(killTrailingWS(line.substring("CONTENT-LENGTH: ".length()))); - } - i++; - } - } - return i; - } - - - // 0 1 2 3 - // a b c \r - - private static String killTrailingWS(String s){ - int i = s.length(); - while (i>0){ - char c = s.charAt(i-1); - if (c=='\r' || c=='\n' || c==' '){ - i--; - continue; - } else { - break; - } - } - return s.substring(0, i); - } - - public static HttpTraffic readPayloads(String fullPayload, String boundary, long contentLength){ - HttpTraffic traffic = new HttpTraffic(); - traffic.contentLength = contentLength; - traffic.boundary = boundary; - String [] lines = fullPayload.split("\\n", -1); - readPayloads(traffic, lines, 0); - return traffic; - } - - protected static int readPayloads(HttpTraffic traffic, String[]lines, int i){ - if (traffic.boundary.length()<=0){ //END of headers, and no boundary, so read remaining and return. - if (traffic.contentLength == 0){ - return i; - } - Part part = new Part(""); - traffic.payloads.add(part); - i = part.readRemaining(lines, i, traffic.contentLength); - return i; - } - int lineCount = lines.length; - String line; - while (i0){ - // System.err.println("********** Skipping line: "+line); //either parser error, or something is outside of a boundary. - //} - //i++; - } - } - return i; - } - - - private HttpTraffic parseForward(String forward, int nexti){ - HttpTraffic forwardTraffic = new HttpTraffic(); - forwardTraffic.isRequest = true; - forwardTraffic.ID = getID(); - //String[] lines = forward.split("\\r\\n", -1); - String[] lines = forward.split("\\n", -1); - int lineCount = lines.length; - String line; - int i = nexti; - - // Read the first line, and figure out if GET, POST, etc., and the URI - line = lines[i]; - while (line.trim().length()==0){ - i++; - if (i>=lineCount-1){ - return null; - } - line = lines[i]; - } - String[] tokens = line.split(" ", -1); - forwardTraffic.method = tokens[0]; - String urlString = tokens[1]; - String[] urlHalves = urlString.split("\\?", -1); //look for a query string of the form /foo/bar?param=baz and break on question mark. - forwardTraffic.url = urlHalves[0]; - if (urlHalves.length > 1){ - forwardTraffic.queryParams = urlHalves[1]; - } - i++; - - //if (forwardTraffic.method.equals("GET")|| forwardTraffic.method.equals("DELETE")){ - // return forwardTraffic; - //} - // Now read headers until we are ready for payload or parts. - i = readHeaders(forwardTraffic, lines, i); - - /* - if ( (i=lineCount){ - return null; - } - line = lines[i]; - - // Read the first line, and figure out response code, message. - while (i=lineCount){ - reverseTraffic.nexti = -1; - } - return reverseTraffic; - } - - private List handleTcpDump(String dump){ - int i = 0; - int trafficID = 0; - List trafficList = new ArrayList(); - while (i>-1){ - trafficID++; - HttpTraffic forward = parseForward(dump, i); - if (forward==null) break; - i = forward.nexti; - forward.ID = ""+trafficID; - if (forward.payloads.size()>0){ - saveForwardFiles(forward); - } - trafficList.add(forward); - - HttpTraffic reverse = parseReverse(dump, i); - if (reverse==null) break; - reverse.ID = ""+trafficID; - i = reverse.nexti; - if (reverse.payloads.size()>0){ - saveReverseFiles(reverse); - } - trafficList.add(reverse); - } - return trafficList; - } - - public static File saveFile(String dir, String relativeName, String content){ - File result = null; - PrintWriter writer; - try{ - result = new File(dir, relativeName); - writer = new PrintWriter(new FileOutputStream(result)); - }catch (Exception e){ - System.out.println("Can't write to file in saveFile: " + relativeName + " \r\n" + e); - return null; - } - writer.write(content); - writer.close(); - return result; - } - - private void saveForwardFiles(HttpTraffic fr){ - for (Part part : fr.payloads){ - String body = part.buffer.toString(); - if (body.trim().length()==0){ - continue; - } - String filename = fr.ID+'_'+fr.method+'_'+fr.url.replaceAll("/", "_")+'_'+part.label+".xml"; - filename = filename.replaceAll("/", "_"); - System.out.println("trying to save file: "+filename+" :: "+fr); - part.filename = filename; - saveFile("./xml", filename, body); - } - } - - private void saveReverseFiles(HttpTraffic fr){ - for (Part part : fr.payloads){ - String body = part.buffer.toString(); - if (body.trim().length()==0){ - continue; - } - String filename = fr.ID+'_'+fr.method+'_'+fr.url.replaceAll("/", "_"); - if (part.label.length()==0){ - if (body.trim().startsWith(" process(String httpSessionTraffic){ - PayloadLogger pll = new PayloadLogger(); - List trafficList = pll.handleTcpDump(httpSessionTraffic); - return trafficList; - } - - public static void main(String[]args) throws Exception { - String dump = readFile(".", args[0]); - PayloadLogger pll = new PayloadLogger(); - List trafficList = pll.handleTcpDump(dump); - reporter.finished(trafficList); - saveReport(); - } - - +/** + * 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 (c) 2009 Regents of the University of California + * + * 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.IntegrationTests.xmlreplay; + +import org.collectionspace.services.common.api.Tools; + +import java.io.*; +import java.util.ArrayList; +import java.util.List; + +public class PayloadLogger{ + + public static void saveReport(){ + reporter.writeTable(); + } + + private static Reporter reporter = new Reporter(); + + private static volatile int ID = 1000; + public String getID(){ + return ""+ID; + } + + private static String DD = "--"; + private static String LABEL="LABEL: "; + + static class Reporter { + public Reporter(){ + table.append("\r\n"); + } + public static final String START = ""; + + public void writeTable(){ + table.append("
"; + public static final String SEP = ""; + public static final String END = "
"); + saveFile("./xml/", "results.html", table.toString()); + } + + private StringBuffer table = new StringBuffer(); + + public synchronized void finished(HttpTraffic traffic){ + String direction = traffic.isRequest ? + "==>" + : + " <=="; + table.append(START) + .append(direction) + .append(SEP) + .append(traffic==null ? "null" : traffic.toRow(SEP, this)) + .append(END); + } + + public synchronized void finished(List trafficList){ + for (HttpTraffic traffic: trafficList){ + finished(traffic); + } + } + + public static String link(String desc, String url){ + return ""+desc+""; + } + public static final String newline = "
\r\n"; + + } + + + static class HttpTraffic { + public HttpTraffic(){ + payloads = new ArrayList(); + } + public List payloads; + public String method = ""; + public String url = ""; + public String queryParams = ""; + public String message = ""; + public int responseCode = 0; + public String boundary = ""; + public String location = ""; + public long contentLength = -1; + public boolean isRequest = true; + public boolean extra = false; + public String ID = "0"; + public int nexti = 0; + + public Part getPart(String label){ + for (Part part : payloads){ + if (part.label.equalsIgnoreCase(label)){ + return part; + } + } + return null; + } + + public String toRow(String sep, Reporter reporter){ + StringBuffer b = new StringBuffer(); + for (Part part : payloads){ + String name = part.label; + if (part.filename.length()==0){ + continue; + } + if (name.trim().length()<=0){ + name = ID; + } + name = name+" ("+part.filetype+')'; + String link = reporter.link(name, part.filename); + b.append(link) + .append(reporter.newline); + } + String parts = b.toString(); + if (isRequest){ + return ID+sep + +method+sep + +url+sep + +queryParams+sep + +sep + +parts; + } else { + return ID+sep + +responseCode+sep + +message+sep + +location+sep + +contentLength+sep + +url + +parts; + } + } + } + + static class Part { + public Part(String boundary){ + this.boundary = boundary; + } + public boolean isMultipart(){ + return boundary.length()>0; + } + public String toString(){ + return "Part:"+label+";"; + } + public String filename = ""; + public String filetype = ""; + public String boundary; + public StringBuffer buffer = new StringBuffer(); + public String getContent(){ + return buffer.toString(); + } + public String label = ""; + public int readPart(String[]lines, int i){ + String line = ""; + boolean readingPartHeaders = true; + while(readingPartHeaders){ + line = killTrailingWS(lines[i]); + if (line.toUpperCase().startsWith(LABEL)){ + this.label = line.substring(LABEL.length()).trim(); + } else if (line.trim().length()==0){ + readingPartHeaders = false; + } + i++; + } + while (i 2) { + System.err.println("WARNING: too many tokens after boundary= on Content-Type: header line: " + headerLine); + } + } + return boundary; + } + + /** places the boundary on the HttpTraffic in parameter object if boundary found in header "Content-Type:". + * @return the index of the NEXT line the caller should read. */ + protected static int readHeaders(HttpTraffic traffic, String[]lines, int i){ + int lineCount = lines.length; + String line, lineUP; + // Now read headers until we are ready for payload or parts. + while (i 2){ + System.err.println("WARNING: too many tokens after boundary= on Content-Type: header line: "+line); + } + } else if (lineUP.startsWith("LOCATION: ")){ + traffic.location = killTrailingWS(line.substring("LOCATION: ".length())); + } else if (lineUP.startsWith("CONTENT-LENGTH: ")){ + traffic.contentLength = Integer.parseInt(killTrailingWS(line.substring("CONTENT-LENGTH: ".length()))); + } + i++; + } + } + return i; + } + + + // 0 1 2 3 + // a b c \r + + private static String killTrailingWS(String s){ + int i = s.length(); + while (i>0){ + char c = s.charAt(i-1); + if (c=='\r' || c=='\n' || c==' '){ + i--; + continue; + } else { + break; + } + } + return s.substring(0, i); + } + + public static HttpTraffic readPayloads(String fullPayload, String boundary, long contentLength){ + HttpTraffic traffic = new HttpTraffic(); + traffic.contentLength = contentLength; + traffic.boundary = boundary; + String [] lines = fullPayload.split("\\n", -1); + readPayloads(traffic, lines, 0); + return traffic; + } + + protected static int readPayloads(HttpTraffic traffic, String[]lines, int i){ + if (traffic.boundary.length()<=0){ //END of headers, and no boundary, so read remaining and return. + if (traffic.contentLength == 0){ + return i; + } + Part part = new Part(""); + traffic.payloads.add(part); + i = part.readRemaining(lines, i, traffic.contentLength); + return i; + } + int lineCount = lines.length; + String line; + while (i0){ + // System.err.println("********** Skipping line: "+line); //either parser error, or something is outside of a boundary. + //} + //i++; + } + } + return i; + } + + + private HttpTraffic parseForward(String forward, int nexti){ + HttpTraffic forwardTraffic = new HttpTraffic(); + forwardTraffic.isRequest = true; + forwardTraffic.ID = getID(); + //String[] lines = forward.split("\\r\\n", -1); + String[] lines = forward.split("\\n", -1); + int lineCount = lines.length; + String line; + int i = nexti; + + // Read the first line, and figure out if GET, POST, etc., and the URI + line = lines[i]; + while (line.trim().length()==0){ + i++; + if (i>=lineCount-1){ + return null; + } + line = lines[i]; + } + String[] tokens = line.split(" ", -1); + forwardTraffic.method = tokens[0]; + String urlString = tokens[1]; + String[] urlHalves = urlString.split("\\?", -1); //look for a query string of the form /foo/bar?param=baz and break on question mark. + forwardTraffic.url = urlHalves[0]; + if (urlHalves.length > 1){ + forwardTraffic.queryParams = urlHalves[1]; + } + i++; + + //if (forwardTraffic.method.equals("GET")|| forwardTraffic.method.equals("DELETE")){ + // return forwardTraffic; + //} + // Now read headers until we are ready for payload or parts. + i = readHeaders(forwardTraffic, lines, i); + + /* + if ( (i=lineCount){ + return null; + } + line = lines[i]; + + // Read the first line, and figure out response code, message. + while (i=lineCount){ + reverseTraffic.nexti = -1; + } + return reverseTraffic; + } + + private List handleTcpDump(String dump){ + int i = 0; + int trafficID = 0; + List trafficList = new ArrayList(); + while (i>-1){ + trafficID++; + HttpTraffic forward = parseForward(dump, i); + if (forward==null) break; + i = forward.nexti; + forward.ID = ""+trafficID; + if (forward.payloads.size()>0){ + saveForwardFiles(forward); + } + trafficList.add(forward); + + HttpTraffic reverse = parseReverse(dump, i); + if (reverse==null) break; + reverse.ID = ""+trafficID; + i = reverse.nexti; + if (reverse.payloads.size()>0){ + saveReverseFiles(reverse); + } + trafficList.add(reverse); + } + return trafficList; + } + + public static File saveFile(String dir, String relativeName, String content){ + File result = null; + PrintWriter writer; + try{ + result = new File(dir, relativeName); + writer = new PrintWriter(new FileOutputStream(result)); + }catch (Exception e){ + System.out.println("Can't write to file in saveFile: " + relativeName + " \r\n" + e); + return null; + } + writer.write(content); + writer.close(); + return result; + } + + private void saveForwardFiles(HttpTraffic fr){ + for (Part part : fr.payloads){ + String body = part.buffer.toString(); + if (body.trim().length()==0){ + continue; + } + String filename = fr.ID+'_'+fr.method+'_'+fr.url.replaceAll("/", "_")+'_'+part.label+".xml"; + filename = filename.replaceAll("/", "_"); + System.out.println("trying to save file: "+filename+" :: "+fr); + part.filename = filename; + saveFile("./xml", filename, body); + } + } + + private void saveReverseFiles(HttpTraffic fr){ + for (Part part : fr.payloads){ + String body = part.buffer.toString(); + if (body.trim().length()==0){ + continue; + } + String filename = fr.ID+'_'+fr.method+'_'+fr.url.replaceAll("/", "_"); + if (part.label.length()==0){ + if (body.trim().startsWith(" process(String httpSessionTraffic){ + PayloadLogger pll = new PayloadLogger(); + List trafficList = pll.handleTcpDump(httpSessionTraffic); + return trafficList; + } + + public static void main(String[]args) throws Exception { + String dump = readFile(".", args[0]); + PayloadLogger pll = new PayloadLogger(); + List trafficList = pll.handleTcpDump(dump); + reporter.finished(trafficList); + saveReport(); + } + + } \ No newline at end of file diff --git a/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/ServiceResult.java b/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/ServiceResult.java index b9e879a37..548a9b4d8 100644 --- a/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/ServiceResult.java +++ b/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/ServiceResult.java @@ -1,327 +1,327 @@ -/** - * 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 (c) 2009 Regents of the University of California - * - * 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.IntegrationTests.xmlreplay; - -import org.apache.commons.httpclient.Header; -import org.collectionspace.services.common.api.Tools; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * User: laramie - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ -public class ServiceResult { - public String testID = ""; - public String testGroupID = ""; - public String fullURL = ""; - public String deleteURL = ""; - public String location = ""; - public String CSID = ""; - public String subresourceCSID = ""; - public String requestPayload = ""; //just like requestPayloadRaw, but may have multipart boundary and headers. - public String requestPayloadsRaw = ""; - public String result = ""; - public int responseCode = 0; - public String responseMessage = ""; - public String method = ""; - public String error = ""; - public String fromTestID = ""; - public String auth = ""; - public String boundary = ""; - public String payloadStrictness = ""; - public long contentLength = 0; - public String failureReason = ""; - public String expectedContentExpanded = ""; - public Header[] responseHeaders = new Header[0]; - public List expectedCodes = new ArrayList(); - public Map vars = new HashMap(); - public void addVars(Map newVars){ - vars.putAll(newVars); - } - private Map partSummaries = new HashMap(); - public void addPartSummary(String label, TreeWalkResults list){ - partSummaries.put(label, list); - } - public String partsSummary(boolean detailed){ - StringBuffer buf = new StringBuffer(); - if (!isDomWalkOK()){ - if (detailed) buf.append("\r\nDOM CHECK FAILED:\r\n"); - else buf.append("; DOM CHECK FAILED:"); - } - for (Map.Entry entry : partSummaries.entrySet()) { - String key = entry.getKey(); - TreeWalkResults value = entry.getValue(); - buf.append(" label:"+key+": "); - if (detailed){ - buf.append("\r\n"); - buf.append(value.fullSummary()); - } else { - buf.append(value.miniSummary()); - } - - } - return buf.toString(); - } - public boolean codeInSuccessRange(int code){ - if (0<=code && code<200){ - return false; - } else if (400<=code) { - return false; - } - return true; - } - - public boolean isDomWalkOK(){ - if (Tools.isEmpty(payloadStrictness)){ - return true; - } - PAYLOAD_STRICTNESS strictness = PAYLOAD_STRICTNESS.valueOf(payloadStrictness); - for (Map.Entry entry : partSummaries.entrySet()) { - String key = entry.getKey(); - TreeWalkResults value = entry.getValue(); - if (value.hasDocErrors()){ - failureReason = " : DOM DOC_ERROR; "; - return false; - } - switch (strictness){ - case STRICT: - if (!value.isStrictMatch()) { - failureReason = " : DOM NOT STRICT; "; - return false; - } - break; - case ADDOK: - if (value.countFor(TreeWalkResults.TreeWalkEntry.STATUS.TEXT_DIFFERENT)>0) { - failureReason = " : DOM TEXT_DIFFERENT; "; - return false; - } - if (value.countFor(TreeWalkResults.TreeWalkEntry.STATUS.R_MISSING)>0){ - failureReason = " : DOM R_MISSING; "; - return false; - } - break; - case TEXT: - if (value.countFor(TreeWalkResults.TreeWalkEntry.STATUS.TEXT_DIFFERENT)>0) { - failureReason = " : DOM TEXT_DIFFERENT; "; - return false; - } - break; - case TREE: - if (!value.treesMatch()) { - failureReason = " : DOM TREE MISMATCH; "; - return false; - } - break; - case TREE_TEXT: - if (value.countFor(TreeWalkResults.TreeWalkEntry.STATUS.TEXT_DIFFERENT)>0) { - failureReason = " : DOM TEXT_DIFFERENT; "; - return false; - } - if (!value.treesMatch()) { - failureReason = " : DOM TREE MISMATCH; "; - return false; - } - break; - case ZERO: - break; - } - } - return true; - } - - private boolean overrideExpectedResult = false; - - /** Call this method to create a ServiceResult mock object, for when you are doing autoDelete, and you come - * across a GET : GETs don't have a DELETE url, so they don't need to be autoDeleted, so an empty ServiceResult object - * signifies this. - */ - public void overrideGotExpectedResult(){ - overrideExpectedResult = true; - } - - public boolean gotExpectedResult(){ - if (overrideExpectedResult){ - return true; - } - //if (Tools.notEmpty(failureReason)){ - // return false; - //} - for (Integer oneExpected : expectedCodes){ - if (responseCode == oneExpected){ - failureReason = ""; - return isDomWalkOK(); - } - } - if ( expectedCodes.size()>0 && codeInSuccessRange(responseCode)){ //none found, but result expected. - for (Integer oneExpected : expectedCodes){ - if ( ! codeInSuccessRange(oneExpected)){ - failureReason = ""; - return isDomWalkOK(); - } - } - } - boolean ok = codeInSuccessRange(responseCode); - if (ok) { - failureReason = ""; - return isDomWalkOK(); - } - failureReason = " : STATUS CODE UNEXPECTED; "; - return false; - } - - //public static final String[] DUMP_OPTIONS = {"minimal", "detailed", "full"}; - public static enum DUMP_OPTIONS {minimal, detailed, full, auto}; - - public static enum PAYLOAD_STRICTNESS {ZERO, ADDOK, TREE, TEXT, TREE_TEXT, STRICT}; - - public String toString(){ - return detail(true); - - } - - private static final String LINE = "\r\n=================================="; - private static final String CRLF = "\r\n"; - - public String detail(boolean includePayloads){ - String res = "{" - + ( gotExpectedResult() ? "SUCCESS" : "FAILURE" ) - + failureReason - +"; "+method - +"; "+responseCode - + ( (expectedCodes.size()>0) ? "; expectedCodes:"+expectedCodes : "" ) - + ( Tools.notEmpty(testID) ? "; testID:"+testID : "" ) - + ( Tools.notEmpty(testGroupID) ? "; testGroupID:"+testGroupID : "" ) - + ( Tools.notEmpty(fromTestID) ? "; fromTestID:"+fromTestID : "" ) - + ( Tools.notEmpty(responseMessage) ? "; msg:"+responseMessage : "" ) - +"; URL:"+fullURL - +"; auth: "+auth - + ( Tools.notEmpty(deleteURL) ? "; deleteURL:"+deleteURL : "" ) - + ( Tools.notEmpty(location) ? "; location.CSID:"+location : "" ) - + ( Tools.notEmpty(error) ? "; ERROR:"+error : "" ) - + "; gotExpected:"+gotExpectedResult() - //+";result:"+result+";" - + ( partsSummary(true)) - +"}" - + ( includePayloads && Tools.notBlank(requestPayload) ? LINE+"requestPayload:"+LINE+CRLF+requestPayload+LINE : "" ) - + ( includePayloads && Tools.notBlank(result) ? LINE+"result:"+LINE+CRLF+result : "" ); - return res; - } - - public String minimal(){ - return minimal(false); - } - - public String minimal(boolean verbosePartsSummary){ - return "{" - + ( gotExpectedResult() ? "SUCCESS" : "FAILURE" ) - + failureReason - + ( Tools.notEmpty(testID) ? "; "+testID : "" ) - +"; "+method - +"; "+responseCode - + (expectedCodes.size()>0 ? "; expected:"+expectedCodes : "") - + ( Tools.notEmpty(responseMessage) ? "; msg:"+responseMessage : "" ) - +"; URL:"+fullURL - //for auth, see detail() +"; auth: "+auth - + ( Tools.notEmpty(error) ? "; ERROR:"+error : "" ) - + (verbosePartsSummary ? partsSummary(true) : partsSummary(false) ) - +"}"; - } - public String dump(ServiceResult.DUMP_OPTIONS opt, boolean hasError){ - switch (opt){ - case minimal: - return minimal(false); - case detailed: - return detail(false); - case full: - return detail(true); - case auto: - return minimal(hasError); - default: - return toString(); - } - } - - /** This method may be called from a test case, using a syntax like ${testID3.resValue("persons_common", "//refName")} */ - public String got(String xpath) throws Exception { - try { - //PayloadLogger.HttpTraffic traffic = PayloadLogger.readPayloads(this.result, this.boundary, this.contentLength); - //PayloadLogger.Part partFromServer = traffic.getPart(partName); - //String source = partFromServer.getContent(); - String source = this.result; - if (Tools.isBlank(source)){ - return ""; - } - org.jdom.Element element = (org.jdom.Element) XmlCompareJdom.selectSingleNode(source, xpath, null); //todo: passing null for namespace may not work. - String sr = element != null ? element.getText() : ""; - return sr; - } catch (Exception e){ - return "ERROR reading response value: "+e; - } - } - - /** This method may be called from a test case, using a syntax like ${oe9.reqValue("personauthorities_common","//shortIdentifier")} */ - public String sent(String xpath) throws Exception { - try { - String source = this.requestPayload; // REM - 5/9/2012 : Changing to requestPayload from requestPayloadsRaw to get actual sent payload - if (source == null){ - return "ERROR:null:requestPayloadsRaw"; - } - org.jdom.Element element = (org.jdom.Element) XmlCompareJdom.selectSingleNode(source, xpath, null); //e.g. "//shortIdentifier"); //todo: passing null for namespace may not work. - String sr = element != null ? element.getText() : ""; - return sr; - } catch (Exception e){ - return "ERROR reading request value: "+e; - } - } - - public String get(String what){ - if ("CSID".equals(what)){ - return CSID; - } else if ("location".equals(what)){ - return location; - } else if ("testID".equals(what)){ - return testID; - } else if ("testGroupID".equals(what)){ - return testGroupID; - } else if ("fullURL".equals(what)){ - return fullURL; - } else if ("deleteURL".equals(what)){ - return deleteURL; - } else if ("responseCode".equals(what)){ - return ""+responseCode; - } else if ("method".equals(what)){ - return method; - } - if (vars.containsKey(what)){ - return vars.get(what); - } - return ""; - } - -} +/** + * 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 (c) 2009 Regents of the University of California + * + * 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.IntegrationTests.xmlreplay; + +import org.apache.commons.httpclient.Header; +import org.collectionspace.services.common.api.Tools; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * User: laramie + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public class ServiceResult { + public String testID = ""; + public String testGroupID = ""; + public String fullURL = ""; + public String deleteURL = ""; + public String location = ""; + public String CSID = ""; + public String subresourceCSID = ""; + public String requestPayload = ""; //just like requestPayloadRaw, but may have multipart boundary and headers. + public String requestPayloadsRaw = ""; + public String result = ""; + public int responseCode = 0; + public String responseMessage = ""; + public String method = ""; + public String error = ""; + public String fromTestID = ""; + public String auth = ""; + public String boundary = ""; + public String payloadStrictness = ""; + public long contentLength = 0; + public String failureReason = ""; + public String expectedContentExpanded = ""; + public Header[] responseHeaders = new Header[0]; + public List expectedCodes = new ArrayList(); + public Map vars = new HashMap(); + public void addVars(Map newVars){ + vars.putAll(newVars); + } + private Map partSummaries = new HashMap(); + public void addPartSummary(String label, TreeWalkResults list){ + partSummaries.put(label, list); + } + public String partsSummary(boolean detailed){ + StringBuffer buf = new StringBuffer(); + if (!isDomWalkOK()){ + if (detailed) buf.append("\r\nDOM CHECK FAILED:\r\n"); + else buf.append("; DOM CHECK FAILED:"); + } + for (Map.Entry entry : partSummaries.entrySet()) { + String key = entry.getKey(); + TreeWalkResults value = entry.getValue(); + buf.append(" label:"+key+": "); + if (detailed){ + buf.append("\r\n"); + buf.append(value.fullSummary()); + } else { + buf.append(value.miniSummary()); + } + + } + return buf.toString(); + } + public boolean codeInSuccessRange(int code){ + if (0<=code && code<200){ + return false; + } else if (400<=code) { + return false; + } + return true; + } + + public boolean isDomWalkOK(){ + if (Tools.isEmpty(payloadStrictness)){ + return true; + } + PAYLOAD_STRICTNESS strictness = PAYLOAD_STRICTNESS.valueOf(payloadStrictness); + for (Map.Entry entry : partSummaries.entrySet()) { + String key = entry.getKey(); + TreeWalkResults value = entry.getValue(); + if (value.hasDocErrors()){ + failureReason = " : DOM DOC_ERROR; "; + return false; + } + switch (strictness){ + case STRICT: + if (!value.isStrictMatch()) { + failureReason = " : DOM NOT STRICT; "; + return false; + } + break; + case ADDOK: + if (value.countFor(TreeWalkResults.TreeWalkEntry.STATUS.TEXT_DIFFERENT)>0) { + failureReason = " : DOM TEXT_DIFFERENT; "; + return false; + } + if (value.countFor(TreeWalkResults.TreeWalkEntry.STATUS.R_MISSING)>0){ + failureReason = " : DOM R_MISSING; "; + return false; + } + break; + case TEXT: + if (value.countFor(TreeWalkResults.TreeWalkEntry.STATUS.TEXT_DIFFERENT)>0) { + failureReason = " : DOM TEXT_DIFFERENT; "; + return false; + } + break; + case TREE: + if (!value.treesMatch()) { + failureReason = " : DOM TREE MISMATCH; "; + return false; + } + break; + case TREE_TEXT: + if (value.countFor(TreeWalkResults.TreeWalkEntry.STATUS.TEXT_DIFFERENT)>0) { + failureReason = " : DOM TEXT_DIFFERENT; "; + return false; + } + if (!value.treesMatch()) { + failureReason = " : DOM TREE MISMATCH; "; + return false; + } + break; + case ZERO: + break; + } + } + return true; + } + + private boolean overrideExpectedResult = false; + + /** Call this method to create a ServiceResult mock object, for when you are doing autoDelete, and you come + * across a GET : GETs don't have a DELETE url, so they don't need to be autoDeleted, so an empty ServiceResult object + * signifies this. + */ + public void overrideGotExpectedResult(){ + overrideExpectedResult = true; + } + + public boolean gotExpectedResult(){ + if (overrideExpectedResult){ + return true; + } + //if (Tools.notEmpty(failureReason)){ + // return false; + //} + for (Integer oneExpected : expectedCodes){ + if (responseCode == oneExpected){ + failureReason = ""; + return isDomWalkOK(); + } + } + if ( expectedCodes.size()>0 && codeInSuccessRange(responseCode)){ //none found, but result expected. + for (Integer oneExpected : expectedCodes){ + if ( ! codeInSuccessRange(oneExpected)){ + failureReason = ""; + return isDomWalkOK(); + } + } + } + boolean ok = codeInSuccessRange(responseCode); + if (ok) { + failureReason = ""; + return isDomWalkOK(); + } + failureReason = " : STATUS CODE UNEXPECTED; "; + return false; + } + + //public static final String[] DUMP_OPTIONS = {"minimal", "detailed", "full"}; + public static enum DUMP_OPTIONS {minimal, detailed, full, auto}; + + public static enum PAYLOAD_STRICTNESS {ZERO, ADDOK, TREE, TEXT, TREE_TEXT, STRICT}; + + public String toString(){ + return detail(true); + + } + + private static final String LINE = "\r\n=================================="; + private static final String CRLF = "\r\n"; + + public String detail(boolean includePayloads){ + String res = "{" + + ( gotExpectedResult() ? "SUCCESS" : "FAILURE" ) + + failureReason + +"; "+method + +"; "+responseCode + + ( (expectedCodes.size()>0) ? "; expectedCodes:"+expectedCodes : "" ) + + ( Tools.notEmpty(testID) ? "; testID:"+testID : "" ) + + ( Tools.notEmpty(testGroupID) ? "; testGroupID:"+testGroupID : "" ) + + ( Tools.notEmpty(fromTestID) ? "; fromTestID:"+fromTestID : "" ) + + ( Tools.notEmpty(responseMessage) ? "; msg:"+responseMessage : "" ) + +"; URL:"+fullURL + +"; auth: "+auth + + ( Tools.notEmpty(deleteURL) ? "; deleteURL:"+deleteURL : "" ) + + ( Tools.notEmpty(location) ? "; location.CSID:"+location : "" ) + + ( Tools.notEmpty(error) ? "; ERROR:"+error : "" ) + + "; gotExpected:"+gotExpectedResult() + //+";result:"+result+";" + + ( partsSummary(true)) + +"}" + + ( includePayloads && Tools.notBlank(requestPayload) ? LINE+"requestPayload:"+LINE+CRLF+requestPayload+LINE : "" ) + + ( includePayloads && Tools.notBlank(result) ? LINE+"result:"+LINE+CRLF+result : "" ); + return res; + } + + public String minimal(){ + return minimal(false); + } + + public String minimal(boolean verbosePartsSummary){ + return "{" + + ( gotExpectedResult() ? "SUCCESS" : "FAILURE" ) + + failureReason + + ( Tools.notEmpty(testID) ? "; "+testID : "" ) + +"; "+method + +"; "+responseCode + + (expectedCodes.size()>0 ? "; expected:"+expectedCodes : "") + + ( Tools.notEmpty(responseMessage) ? "; msg:"+responseMessage : "" ) + +"; URL:"+fullURL + //for auth, see detail() +"; auth: "+auth + + ( Tools.notEmpty(error) ? "; ERROR:"+error : "" ) + + (verbosePartsSummary ? partsSummary(true) : partsSummary(false) ) + +"}"; + } + public String dump(ServiceResult.DUMP_OPTIONS opt, boolean hasError){ + switch (opt){ + case minimal: + return minimal(false); + case detailed: + return detail(false); + case full: + return detail(true); + case auto: + return minimal(hasError); + default: + return toString(); + } + } + + /** This method may be called from a test case, using a syntax like ${testID3.resValue("persons_common", "//refName")} */ + public String got(String xpath) throws Exception { + try { + //PayloadLogger.HttpTraffic traffic = PayloadLogger.readPayloads(this.result, this.boundary, this.contentLength); + //PayloadLogger.Part partFromServer = traffic.getPart(partName); + //String source = partFromServer.getContent(); + String source = this.result; + if (Tools.isBlank(source)){ + return ""; + } + org.jdom.Element element = (org.jdom.Element) XmlCompareJdom.selectSingleNode(source, xpath, null); //todo: passing null for namespace may not work. + String sr = element != null ? element.getText() : ""; + return sr; + } catch (Exception e){ + return "ERROR reading response value: "+e; + } + } + + /** This method may be called from a test case, using a syntax like ${oe9.reqValue("personauthorities_common","//shortIdentifier")} */ + public String sent(String xpath) throws Exception { + try { + String source = this.requestPayload; // REM - 5/9/2012 : Changing to requestPayload from requestPayloadsRaw to get actual sent payload + if (source == null){ + return "ERROR:null:requestPayloadsRaw"; + } + org.jdom.Element element = (org.jdom.Element) XmlCompareJdom.selectSingleNode(source, xpath, null); //e.g. "//shortIdentifier"); //todo: passing null for namespace may not work. + String sr = element != null ? element.getText() : ""; + return sr; + } catch (Exception e){ + return "ERROR reading request value: "+e; + } + } + + public String get(String what){ + if ("CSID".equals(what)){ + return CSID; + } else if ("location".equals(what)){ + return location; + } else if ("testID".equals(what)){ + return testID; + } else if ("testGroupID".equals(what)){ + return testGroupID; + } else if ("fullURL".equals(what)){ + return fullURL; + } else if ("deleteURL".equals(what)){ + return deleteURL; + } else if ("responseCode".equals(what)){ + return ""+responseCode; + } else if ("method".equals(what)){ + return method; + } + if (vars.containsKey(what)){ + return vars.get(what); + } + return ""; + } + +} diff --git a/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/TreeWalkResults.java b/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/TreeWalkResults.java index 021dfe66e..fe2495654 100644 --- a/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/TreeWalkResults.java +++ b/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/TreeWalkResults.java @@ -1,231 +1,231 @@ -/** - * 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 (c) 2009 Regents of the University of California - * - * 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.IntegrationTests.xmlreplay; - -import org.collectionspace.services.common.api.Tools; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * User: laramie - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ -public class TreeWalkResults extends ArrayList { - public String toString(String LEAD){ - StringBuffer res = new StringBuffer(); - for (TreeWalkResults.TreeWalkEntry entry: this) { - res.append(entry.toString(LEAD)); - } - return res.toString(); - } - - /** This cllass has two public Lists: you can construct your own to set the acceptable and unacceptable STATUS codes. - * They are defaulted to R_ADDED being acceptable. */ - public static class MatchSpec { - public static final TreeWalkEntry.STATUS[] defaultAcceptableStatiArray = {TreeWalkEntry.STATUS.INFO, - TreeWalkEntry.STATUS.MATCHED, - TreeWalkEntry.STATUS.R_ADDED}; - - public static final TreeWalkEntry.STATUS[] defaultErrorStatiArray = {TreeWalkEntry.STATUS.R_MISSING, - TreeWalkEntry.STATUS.NESTED_ERROR, - TreeWalkEntry.STATUS.TEXT_DIFFERENT, - TreeWalkEntry.STATUS.DOC_ERROR}; - public List errorStati; - - public static MatchSpec createDefault(){ - MatchSpec result = new MatchSpec(); - result.errorStati = Arrays.asList(defaultErrorStatiArray); - return result; - } - public static MatchSpec create(TreeWalkEntry.STATUS[] statiArray){ - MatchSpec result = new MatchSpec(); - result.errorStati = Arrays.asList(statiArray); - return result; - } - public void removeErrorFromSpec(TreeWalkEntry.STATUS status){ - ArrayList arrayList = new ArrayList(errorStati); - arrayList.remove(status); - errorStati = arrayList; - } - public String toString(){ - StringBuffer buff = new StringBuffer("{"); - int i = 0; - for (TreeWalkEntry.STATUS status : errorStati){ - if (i>0) buff.append(","); - String foo = status.toString(); - buff.append(foo); - i++; - } - buff.append("}"); - return buff.toString(); - } - - } - - public static class TreeWalkEntry { - public String lpath = ""; - public String rpath = ""; - public String ltextTrimmed = ""; - public String rtextTrimmed = ""; - public String expected = ""; - public String actual = ""; - public String message = ""; - public String errmessage = ""; - public TreeWalkResults nested; - public static enum STATUS {INFO, MATCHED, R_MISSING, R_ADDED, DOC_ERROR, TEXT_DIFFERENT, NESTED_ERROR}; - public STATUS status; - public String toString(){ - return toString("\r\n"); - } - public String toString(String LEAD){ - String INDENT = " "; - return - LEAD + "{" - +status.name() - +(Tools.notEmpty(lpath) ? ", L.path:"+lpath : "") - +(Tools.notEmpty(rpath) ? ", R.path:"+rpath : "") - +(Tools.notEmpty(message) ? ", message:"+message : "") - +(Tools.notEmpty(errmessage) ? ", errmessage:"+errmessage : "") - +", status:"+status - +((status != STATUS.MATCHED) && Tools.notEmpty(ltextTrimmed) ? ","+LEAD+" L.trimmed:"+ltextTrimmed : "") - +((status != STATUS.MATCHED) && Tools.notEmpty(rtextTrimmed) ? ","+LEAD+" R.trimmed:"+rtextTrimmed : "") - +((status != STATUS.MATCHED) && Tools.notEmpty(expected) ? LEAD+"EXPECTED:"+LEAD+"------------------"+LEAD+expected.trim()+LEAD+"------------------" : "") - +((status != STATUS.MATCHED) && Tools.notEmpty(actual) ? LEAD+"ACTUAL:"+LEAD+"------------------"+LEAD+actual.trim()+LEAD+"------------------"+LEAD : "") - +((status != STATUS.MATCHED) && (nested != null) ? LEAD+"NESTED:"+LEAD+"------------------"+LEAD+nested.toString(LEAD+INDENT)+LEAD+"------------------"+LEAD : "") - +"}"; - } - } - - public boolean hasDocErrors(){ - for (TreeWalkEntry entry : this){ - if (entry.status == TreeWalkEntry.STATUS.DOC_ERROR){ - return true; - } - } - return false; - } - - public String getErrorMessages(){ - StringBuffer buf = new StringBuffer(); - boolean first = true; - for (TreeWalkEntry entry : this){ - if ( Tools.notEmpty(entry.errmessage)){ - if (first) { - buf.append(",errors:"); - } else { - buf.append(','); - } - buf.append('\''+entry.errmessage+"\'"); - first = false; - } - } - return buf.toString(); - } - - - - public boolean isStrictMatch(){ - for (TreeWalkEntry entry : this){ - if (entry.status == TreeWalkEntry.STATUS.DOC_ERROR){ - return false; - } - if ( !( entry.status == TreeWalkEntry.STATUS.MATCHED - || entry.status == TreeWalkEntry.STATUS.INFO)){ - return false; - } - } - return true; - } - public int getMismatchCount(){ - int c = 0; - for (TreeWalkEntry entry : this){ - if ( entry.status == TreeWalkEntry.STATUS.DOC_ERROR - || entry.status != TreeWalkEntry.STATUS.MATCHED - || entry.status != TreeWalkEntry.STATUS.INFO){ - c++; - } - } - return c; - } - /** For our purposes, trees match if they have the same element tree structure - no checking is done for text node changes. */ - public boolean treesMatch(){ - for (TreeWalkEntry entry : this){ - if (entry.status == TreeWalkEntry.STATUS.DOC_ERROR - || entry.status == TreeWalkEntry.STATUS.R_MISSING - || entry.status == TreeWalkEntry.STATUS.R_ADDED ){ - return false; - } - } - return true; - } - - public boolean treesMatch(MatchSpec matchSpec) { - for (TreeWalkEntry entry : this) { - if (matchSpec.errorStati.contains(entry.status)) { - return false; - } - } - return true; - } - - public int countFor(TreeWalkEntry.STATUS status){ - int count = 0; - for (TreeWalkEntry entry : this){ - if (entry.status.equals(status)){ - count++; - } - } - return count; - } - - public String miniSummary(){ - //MATCHED, INFO, R_MISSING, R_ADDED, TEXT_DIFFERENT}; - StringBuffer buf = new StringBuffer(); - buf.append("{"); - boolean nextline = false; - for (TreeWalkEntry.STATUS st : TreeWalkEntry.STATUS.values()){ - if (nextline) buf.append(','); - buf.append(st.name()+':'+countFor(st)); - nextline = true; - } - buf.append(getErrorMessages()); - buf.append("}"); - return buf.toString(); - } - - public String fullSummary(){ - StringBuffer buf = new StringBuffer(); - for (TreeWalkResults.TreeWalkEntry entry : this){ - buf.append(entry.toString()).append("\r\n"); - } - return buf.toString(); - } - - - public String leftID; - public String rightID; +/** + * 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 (c) 2009 Regents of the University of California + * + * 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.IntegrationTests.xmlreplay; + +import org.collectionspace.services.common.api.Tools; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * User: laramie + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public class TreeWalkResults extends ArrayList { + public String toString(String LEAD){ + StringBuffer res = new StringBuffer(); + for (TreeWalkResults.TreeWalkEntry entry: this) { + res.append(entry.toString(LEAD)); + } + return res.toString(); + } + + /** This cllass has two public Lists: you can construct your own to set the acceptable and unacceptable STATUS codes. + * They are defaulted to R_ADDED being acceptable. */ + public static class MatchSpec { + public static final TreeWalkEntry.STATUS[] defaultAcceptableStatiArray = {TreeWalkEntry.STATUS.INFO, + TreeWalkEntry.STATUS.MATCHED, + TreeWalkEntry.STATUS.R_ADDED}; + + public static final TreeWalkEntry.STATUS[] defaultErrorStatiArray = {TreeWalkEntry.STATUS.R_MISSING, + TreeWalkEntry.STATUS.NESTED_ERROR, + TreeWalkEntry.STATUS.TEXT_DIFFERENT, + TreeWalkEntry.STATUS.DOC_ERROR}; + public List errorStati; + + public static MatchSpec createDefault(){ + MatchSpec result = new MatchSpec(); + result.errorStati = Arrays.asList(defaultErrorStatiArray); + return result; + } + public static MatchSpec create(TreeWalkEntry.STATUS[] statiArray){ + MatchSpec result = new MatchSpec(); + result.errorStati = Arrays.asList(statiArray); + return result; + } + public void removeErrorFromSpec(TreeWalkEntry.STATUS status){ + ArrayList arrayList = new ArrayList(errorStati); + arrayList.remove(status); + errorStati = arrayList; + } + public String toString(){ + StringBuffer buff = new StringBuffer("{"); + int i = 0; + for (TreeWalkEntry.STATUS status : errorStati){ + if (i>0) buff.append(","); + String foo = status.toString(); + buff.append(foo); + i++; + } + buff.append("}"); + return buff.toString(); + } + + } + + public static class TreeWalkEntry { + public String lpath = ""; + public String rpath = ""; + public String ltextTrimmed = ""; + public String rtextTrimmed = ""; + public String expected = ""; + public String actual = ""; + public String message = ""; + public String errmessage = ""; + public TreeWalkResults nested; + public static enum STATUS {INFO, MATCHED, R_MISSING, R_ADDED, DOC_ERROR, TEXT_DIFFERENT, NESTED_ERROR}; + public STATUS status; + public String toString(){ + return toString("\r\n"); + } + public String toString(String LEAD){ + String INDENT = " "; + return + LEAD + "{" + +status.name() + +(Tools.notEmpty(lpath) ? ", L.path:"+lpath : "") + +(Tools.notEmpty(rpath) ? ", R.path:"+rpath : "") + +(Tools.notEmpty(message) ? ", message:"+message : "") + +(Tools.notEmpty(errmessage) ? ", errmessage:"+errmessage : "") + +", status:"+status + +((status != STATUS.MATCHED) && Tools.notEmpty(ltextTrimmed) ? ","+LEAD+" L.trimmed:"+ltextTrimmed : "") + +((status != STATUS.MATCHED) && Tools.notEmpty(rtextTrimmed) ? ","+LEAD+" R.trimmed:"+rtextTrimmed : "") + +((status != STATUS.MATCHED) && Tools.notEmpty(expected) ? LEAD+"EXPECTED:"+LEAD+"------------------"+LEAD+expected.trim()+LEAD+"------------------" : "") + +((status != STATUS.MATCHED) && Tools.notEmpty(actual) ? LEAD+"ACTUAL:"+LEAD+"------------------"+LEAD+actual.trim()+LEAD+"------------------"+LEAD : "") + +((status != STATUS.MATCHED) && (nested != null) ? LEAD+"NESTED:"+LEAD+"------------------"+LEAD+nested.toString(LEAD+INDENT)+LEAD+"------------------"+LEAD : "") + +"}"; + } + } + + public boolean hasDocErrors(){ + for (TreeWalkEntry entry : this){ + if (entry.status == TreeWalkEntry.STATUS.DOC_ERROR){ + return true; + } + } + return false; + } + + public String getErrorMessages(){ + StringBuffer buf = new StringBuffer(); + boolean first = true; + for (TreeWalkEntry entry : this){ + if ( Tools.notEmpty(entry.errmessage)){ + if (first) { + buf.append(",errors:"); + } else { + buf.append(','); + } + buf.append('\''+entry.errmessage+"\'"); + first = false; + } + } + return buf.toString(); + } + + + + public boolean isStrictMatch(){ + for (TreeWalkEntry entry : this){ + if (entry.status == TreeWalkEntry.STATUS.DOC_ERROR){ + return false; + } + if ( !( entry.status == TreeWalkEntry.STATUS.MATCHED + || entry.status == TreeWalkEntry.STATUS.INFO)){ + return false; + } + } + return true; + } + public int getMismatchCount(){ + int c = 0; + for (TreeWalkEntry entry : this){ + if ( entry.status == TreeWalkEntry.STATUS.DOC_ERROR + || entry.status != TreeWalkEntry.STATUS.MATCHED + || entry.status != TreeWalkEntry.STATUS.INFO){ + c++; + } + } + return c; + } + /** For our purposes, trees match if they have the same element tree structure - no checking is done for text node changes. */ + public boolean treesMatch(){ + for (TreeWalkEntry entry : this){ + if (entry.status == TreeWalkEntry.STATUS.DOC_ERROR + || entry.status == TreeWalkEntry.STATUS.R_MISSING + || entry.status == TreeWalkEntry.STATUS.R_ADDED ){ + return false; + } + } + return true; + } + + public boolean treesMatch(MatchSpec matchSpec) { + for (TreeWalkEntry entry : this) { + if (matchSpec.errorStati.contains(entry.status)) { + return false; + } + } + return true; + } + + public int countFor(TreeWalkEntry.STATUS status){ + int count = 0; + for (TreeWalkEntry entry : this){ + if (entry.status.equals(status)){ + count++; + } + } + return count; + } + + public String miniSummary(){ + //MATCHED, INFO, R_MISSING, R_ADDED, TEXT_DIFFERENT}; + StringBuffer buf = new StringBuffer(); + buf.append("{"); + boolean nextline = false; + for (TreeWalkEntry.STATUS st : TreeWalkEntry.STATUS.values()){ + if (nextline) buf.append(','); + buf.append(st.name()+':'+countFor(st)); + nextline = true; + } + buf.append(getErrorMessages()); + buf.append("}"); + return buf.toString(); + } + + public String fullSummary(){ + StringBuffer buf = new StringBuffer(); + for (TreeWalkResults.TreeWalkEntry entry : this){ + buf.append(entry.toString()).append("\r\n"); + } + return buf.toString(); + } + + + public String leftID; + public String rightID; } \ No newline at end of file diff --git a/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlCompareJdom.java b/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlCompareJdom.java index fd49f9358..e6421751e 100644 --- a/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlCompareJdom.java +++ b/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlCompareJdom.java @@ -1,342 +1,342 @@ -/** - * 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 (c) 2009 Regents of the University of California - * - * 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.IntegrationTests.xmlreplay; - -import org.collectionspace.services.common.api.Tools; -import org.jdom.Document; -import org.jdom.Element; -import org.jdom.JDOMException; -import org.jdom.Namespace; -import org.jdom.input.SAXBuilder; -import org.jaxen.XPath; -import org.jaxen.jdom.JDOMXPath; - - -import java.io.IOException; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.collectionspace.services.IntegrationTests.xmlreplay.TreeWalkResults.TreeWalkEntry; -import org.jdom.output.XMLOutputter; - -/** - * User: laramie - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ -public class XmlCompareJdom { - -private static final String DEFAULT_SAX_DRIVER_CLASS = "org.apache.xerces.parsers.SAXParser"; - - public static org.jdom.Document getDocumentFromContent(String source) throws IOException, JDOMException { - org.jdom.Document doc; - SAXBuilder builder; - builder = new SAXBuilder(); - builder.setValidation(false); //has no effect, I think. - doc = builder.build(new StringReader(source)); - return doc; - } - - public static TreeWalkResults compareParts(String expectedContent, String leftID, String actualPartContent, String rightID, String startElement, TreeWalkResults.MatchSpec matchSpec){ - TreeWalkResults list = new TreeWalkResults(); - try { - - list.leftID = leftID; - list.rightID = rightID; - TreeWalkResults.TreeWalkEntry infoentry = new TreeWalkResults.TreeWalkEntry(); - infoentry.expected = expectedContent; - infoentry.actual = actualPartContent; - infoentry.status = TreeWalkResults.TreeWalkEntry.STATUS.INFO; - infoentry.message = "\r\n LEFT file: "+leftID+"\r\n RIGHT file: "+rightID; - list.add(infoentry); - if (Tools.isEmpty(expectedContent)){ - TreeWalkEntry entry = new TreeWalkEntry(); - entry.status = TreeWalkEntry.STATUS.DOC_ERROR; - entry.errmessage = "L dom was empty."; - list.add(entry); - } else if (Tools.isEmpty(actualPartContent)){ - TreeWalkEntry entry = new TreeWalkEntry(); - entry.errmessage = "R dom was empty."; - entry.status = TreeWalkEntry.STATUS.DOC_ERROR; - list.add(entry); - } else { - Document expected = getDocumentFromContent(expectedContent); - Document actual = getDocumentFromContent(actualPartContent); - treeWalk(expected, actual, list, startElement, matchSpec); - } - } catch (Throwable t){ - String msg = "ERROR in XmlReplay.compareParts(): "+t; - System.out.println(msg); - TreeWalkEntry entry = new TreeWalkEntry(); - entry.status = TreeWalkEntry.STATUS.DOC_ERROR; - entry.errmessage = msg; - list.add(entry); - } - return list; - } - - public static List select(Element element, String xpathExpression, Namespace namespace) throws Exception { - XPath xpath = new JDOMXPath(xpathExpression); - String prefix = namespace.getPrefix(); - String uri = namespace.getURI(); - xpath.addNamespace(prefix, uri); - return xpath.selectNodes(element); - } - - public static Object selectSingleNode(Element element, String xpathExpression, Namespace namespace) throws Exception { - XPath xpath = new JDOMXPath(xpathExpression); - if (namespace != null) { - String prefix = namespace.getPrefix(); - String uri = namespace.getURI(); - xpath.addNamespace(prefix, uri); - } - return xpath.selectSingleNode(element); - } - - public static Object selectSingleNode(String docSource, String xpathExpression, Namespace namespace) throws Exception { - Document doc = getDocumentFromContent(docSource); - Element element = doc.getRootElement(); - XPath xpath = new JDOMXPath(xpathExpression); - if (namespace != null) { - String prefix = namespace.getPrefix(); - String uri = namespace.getURI(); - xpath.addNamespace(prefix, uri); - } - return xpath.selectSingleNode(element); - } - - /* MAYBE DEAL WITH NAMESPACES IN THIS KIND OF APPROACH. - - for (Element el : doc.getRootElement().getDescendants(new ElementFilter())) { - if (el.getNamespace() != null) el.setNamespace(null); - - xpath.addNamespace("x", d.getRootElement().getNamespaceUri()); - */ - public static boolean treeWalk(Document left, Document right, TreeWalkResults list, String startElement, TreeWalkResults.MatchSpec matchSpec) throws Exception { - Element leftElement = left.getRootElement(); - Element rightElement = right.getRootElement(); - if (Tools.notBlank(startElement)) { - XPath xpath = new JDOMXPath(startElement); - Object test = xpath.selectSingleNode(leftElement); - if (test!=null){ - leftElement = (Element)test; - } - Object rtest = xpath.selectSingleNode(rightElement); - if (rtest!=null){ - rightElement = (Element)rtest; - } - } - boolean res = treeWalk(leftElement, rightElement, "/", list, matchSpec); - return res; - } - - public static boolean treeWalk(Element left, Element right, String parentPath, TreeWalkResults msgList, TreeWalkResults.MatchSpec matchSpec) throws Exception { - String SPACE = " "; - if (left == null && right == null){ - return true; - } - if (left == null){ - return false; - } - if (right == null){ - return false; - } - List l = left.getChildren(); - Map foundRightMap = new HashMap(); - List foundRepeatingList = new ArrayList(); - boolean result = true; - for (Object o : l) { - if (!(o instanceof Element)){ - continue; - } - Element leftChild = (Element)o; - //String leftChildName = leftChild.getName(); - String leftChildName = leftChild.getQualifiedName(); - if (Tools.isEmpty(leftChildName)){ - continue; - } - - Namespace namespace = leftChild.getNamespace(); - - String leftChildPath = Tools.glue(parentPath, "/", leftChildName); - - if (foundRepeatingList.indexOf(leftChildPath)>=0){ - continue; - } - List leftlist = select(left, leftChildName, namespace); - if (leftlist != null && leftlist.size() > 1){ - //System.out.println("-----------------doRepeating------"+leftChildPath); - foundRepeatingList.add(leftChildPath); - boolean repeatingIdentical = - doRepeatingFieldComparison(leftlist, leftChildPath, leftChildName, left, right, msgList, namespace, matchSpec) ; //todo: deal with foundRightMap in this repeating field block. - if ( ! repeatingIdentical ){ - //System.out.println("\r\n\r\n\r\n*****************************\r\nOne repeating field failed: "+msgList); - return false; - } - foundRightMap.put(leftChildName, "OK"); - } else { - Element rightChild = (Element)selectSingleNode(right,leftChildName, namespace); - if (rightChild == null){ - TreeWalkEntry entry = new TreeWalkEntry(); - entry.lpath = leftChildPath; //this works, but is questionable: selectSingleNode(right, "//*[local-name() = \"objectexit_common\"]") - entry.status = TreeWalkEntry.STATUS.R_MISSING; - msgList.add(entry); - continue; - } - foundRightMap.put(leftChildName, "OK"); - String leftChildTextTrim = leftChild.getText().trim(); - String rightChildTextTrim = rightChild.getText().trim(); - TreeWalkEntry entry = new TreeWalkEntry(); - entry.ltextTrimmed = leftChildTextTrim; - entry.rtextTrimmed = rightChildTextTrim; - entry.lpath = leftChildPath; - entry.rpath = leftChildPath; //same - - if (leftChildTextTrim.equals(rightChildTextTrim)){ - entry.status = TreeWalkEntry.STATUS.MATCHED; - msgList.add(entry); - } else { - entry.status = TreeWalkEntry.STATUS.TEXT_DIFFERENT; - msgList.add(entry); - } - //============ DIVE !! ===================================================== - result = result && treeWalk( leftChild, rightChild, leftChildPath, msgList, matchSpec); - } - } - for (Object r : right.getChildren()){ - if (!(r instanceof Element)){ - continue; - } - Element rightChild = (Element)r; - String rname = rightChild.getQualifiedName(); - if (null==foundRightMap.get(rname)){ - String rightChildPath = Tools.glue(parentPath, "/", rname); - - TreeWalkEntry entry = new TreeWalkEntry(); - entry.rpath = rightChildPath; - entry.status = TreeWalkEntry.STATUS.R_ADDED; - msgList.add(entry); - } - } - return true; - } - - private static void dumpXML_OUT(Element el) throws Exception { - XMLOutputter outputter = new XMLOutputter(); - outputter.output(el, System.out); - } - private static String dumpXML(Element el) throws Exception { - XMLOutputter outputter = new XMLOutputter(); - return outputter.outputString(el); - } - - public static boolean doRepeatingFieldComparison(List leftList, - String leftChildPath, - String leftChildName, - Element left, - Element right, - TreeWalkResults msgList, - Namespace namespace, - TreeWalkResults.MatchSpec matchSpec) - throws Exception { - //todo: deal with foundRightMap in this repeating field block. - List rightList = select(right, leftChildName, namespace); - if (rightList == null || rightList.size() == 0 || rightList.size() < leftList.size()){ - TreeWalkEntry twe = new TreeWalkEntry(); - twe.lpath = leftChildPath; - twe.status = TreeWalkEntry.STATUS.R_MISSING; - String rmsg = (rightList == null) - ? " Right: 0" - : " Right: "+rightList.size(); - twe.message = "Repeating field count not matched. Field: "+leftChildPath+" Left: "+leftList.size()+rmsg; - msgList.add(twe); - return false; - } - if (rightList.size() > leftList.size()){ - TreeWalkEntry twe = new TreeWalkEntry(); - twe.lpath = leftChildPath; - twe.status = TreeWalkEntry.STATUS.R_ADDED; - twe.message = "Repeating field count not matched. Field: "+leftChildPath+" Left: "+leftList.size()+" Right: "+rightList.size(); - msgList.add(twe); - //LC 20110429 return false; - } - - for (Object le : leftList){ - boolean found = false; - Element leftEl = (Element)le; - //pl("left", leftEl); - for(Object re : rightList){ - Element rightEl = (Element)re; - //pl("right", rightEl); - TreeWalkResults msgListInner = new TreeWalkResults(); - //========== DIVE !!! ======================= - treeWalk(leftEl, rightEl, leftChildPath, msgListInner, matchSpec); - //======================================== - - if (msgListInner.treesMatch(matchSpec)){ //if (msgListInner.isStrictMatch()){ - found = true; - TreeWalkEntry twe = new TreeWalkEntry(); - twe.lpath = leftChildPath; - twe.status = TreeWalkEntry.STATUS.MATCHED; - msgList.add(twe); - rightList.remove(re); //found it, don't need to inspect this element again. Since we are breaking from loop, removing element won't mess up iterator--we get a new one on the next loop. - break; - } else { - TreeWalkEntry twe = new TreeWalkEntry(); - twe.lpath = leftChildPath; - twe.status = TreeWalkEntry.STATUS.NESTED_ERROR; - twe.nested = msgListInner; - msgList.add(twe); - //String line = "\r\n\r\n*********************************\r\n"; - //System.out.println(line+"TreeWalkResults: from walking rightEl: "+rightEl+" leftEl: "+leftEl + " msgListInner:"+ msgListInner+line); - } - } // END for(rightList) - if ( ! found){ - TreeWalkEntry twe = new TreeWalkEntry(); - twe.lpath = leftChildPath; - twe.status = TreeWalkEntry.STATUS.R_MISSING; - twe.message = "Repeating field not matched. Source: {"+dumpXML(leftEl)+"}"; - msgList.add(twe); - return false; - } - } // END for(leftLlist) - return true; - } - - private static void pl(String name, Element el) throws Exception { - Namespace namespace = el.getNamespace(); - Object lobid = selectSingleNode(el, "@ID", namespace); - String lid = ""; - if (lobid!=null){ - lid = lobid.toString(); - } - - System.out.println(name+": "+lid); - dumpXML_OUT(el); - System.out.println(); - - } -} +/** + * 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 (c) 2009 Regents of the University of California + * + * 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.IntegrationTests.xmlreplay; + +import org.collectionspace.services.common.api.Tools; +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.JDOMException; +import org.jdom.Namespace; +import org.jdom.input.SAXBuilder; +import org.jaxen.XPath; +import org.jaxen.jdom.JDOMXPath; + + +import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.collectionspace.services.IntegrationTests.xmlreplay.TreeWalkResults.TreeWalkEntry; +import org.jdom.output.XMLOutputter; + +/** + * User: laramie + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public class XmlCompareJdom { + +private static final String DEFAULT_SAX_DRIVER_CLASS = "org.apache.xerces.parsers.SAXParser"; + + public static org.jdom.Document getDocumentFromContent(String source) throws IOException, JDOMException { + org.jdom.Document doc; + SAXBuilder builder; + builder = new SAXBuilder(); + builder.setValidation(false); //has no effect, I think. + doc = builder.build(new StringReader(source)); + return doc; + } + + public static TreeWalkResults compareParts(String expectedContent, String leftID, String actualPartContent, String rightID, String startElement, TreeWalkResults.MatchSpec matchSpec){ + TreeWalkResults list = new TreeWalkResults(); + try { + + list.leftID = leftID; + list.rightID = rightID; + TreeWalkResults.TreeWalkEntry infoentry = new TreeWalkResults.TreeWalkEntry(); + infoentry.expected = expectedContent; + infoentry.actual = actualPartContent; + infoentry.status = TreeWalkResults.TreeWalkEntry.STATUS.INFO; + infoentry.message = "\r\n LEFT file: "+leftID+"\r\n RIGHT file: "+rightID; + list.add(infoentry); + if (Tools.isEmpty(expectedContent)){ + TreeWalkEntry entry = new TreeWalkEntry(); + entry.status = TreeWalkEntry.STATUS.DOC_ERROR; + entry.errmessage = "L dom was empty."; + list.add(entry); + } else if (Tools.isEmpty(actualPartContent)){ + TreeWalkEntry entry = new TreeWalkEntry(); + entry.errmessage = "R dom was empty."; + entry.status = TreeWalkEntry.STATUS.DOC_ERROR; + list.add(entry); + } else { + Document expected = getDocumentFromContent(expectedContent); + Document actual = getDocumentFromContent(actualPartContent); + treeWalk(expected, actual, list, startElement, matchSpec); + } + } catch (Throwable t){ + String msg = "ERROR in XmlReplay.compareParts(): "+t; + System.out.println(msg); + TreeWalkEntry entry = new TreeWalkEntry(); + entry.status = TreeWalkEntry.STATUS.DOC_ERROR; + entry.errmessage = msg; + list.add(entry); + } + return list; + } + + public static List select(Element element, String xpathExpression, Namespace namespace) throws Exception { + XPath xpath = new JDOMXPath(xpathExpression); + String prefix = namespace.getPrefix(); + String uri = namespace.getURI(); + xpath.addNamespace(prefix, uri); + return xpath.selectNodes(element); + } + + public static Object selectSingleNode(Element element, String xpathExpression, Namespace namespace) throws Exception { + XPath xpath = new JDOMXPath(xpathExpression); + if (namespace != null) { + String prefix = namespace.getPrefix(); + String uri = namespace.getURI(); + xpath.addNamespace(prefix, uri); + } + return xpath.selectSingleNode(element); + } + + public static Object selectSingleNode(String docSource, String xpathExpression, Namespace namespace) throws Exception { + Document doc = getDocumentFromContent(docSource); + Element element = doc.getRootElement(); + XPath xpath = new JDOMXPath(xpathExpression); + if (namespace != null) { + String prefix = namespace.getPrefix(); + String uri = namespace.getURI(); + xpath.addNamespace(prefix, uri); + } + return xpath.selectSingleNode(element); + } + + /* MAYBE DEAL WITH NAMESPACES IN THIS KIND OF APPROACH. + + for (Element el : doc.getRootElement().getDescendants(new ElementFilter())) { + if (el.getNamespace() != null) el.setNamespace(null); + + xpath.addNamespace("x", d.getRootElement().getNamespaceUri()); + */ + public static boolean treeWalk(Document left, Document right, TreeWalkResults list, String startElement, TreeWalkResults.MatchSpec matchSpec) throws Exception { + Element leftElement = left.getRootElement(); + Element rightElement = right.getRootElement(); + if (Tools.notBlank(startElement)) { + XPath xpath = new JDOMXPath(startElement); + Object test = xpath.selectSingleNode(leftElement); + if (test!=null){ + leftElement = (Element)test; + } + Object rtest = xpath.selectSingleNode(rightElement); + if (rtest!=null){ + rightElement = (Element)rtest; + } + } + boolean res = treeWalk(leftElement, rightElement, "/", list, matchSpec); + return res; + } + + public static boolean treeWalk(Element left, Element right, String parentPath, TreeWalkResults msgList, TreeWalkResults.MatchSpec matchSpec) throws Exception { + String SPACE = " "; + if (left == null && right == null){ + return true; + } + if (left == null){ + return false; + } + if (right == null){ + return false; + } + List l = left.getChildren(); + Map foundRightMap = new HashMap(); + List foundRepeatingList = new ArrayList(); + boolean result = true; + for (Object o : l) { + if (!(o instanceof Element)){ + continue; + } + Element leftChild = (Element)o; + //String leftChildName = leftChild.getName(); + String leftChildName = leftChild.getQualifiedName(); + if (Tools.isEmpty(leftChildName)){ + continue; + } + + Namespace namespace = leftChild.getNamespace(); + + String leftChildPath = Tools.glue(parentPath, "/", leftChildName); + + if (foundRepeatingList.indexOf(leftChildPath)>=0){ + continue; + } + List leftlist = select(left, leftChildName, namespace); + if (leftlist != null && leftlist.size() > 1){ + //System.out.println("-----------------doRepeating------"+leftChildPath); + foundRepeatingList.add(leftChildPath); + boolean repeatingIdentical = + doRepeatingFieldComparison(leftlist, leftChildPath, leftChildName, left, right, msgList, namespace, matchSpec) ; //todo: deal with foundRightMap in this repeating field block. + if ( ! repeatingIdentical ){ + //System.out.println("\r\n\r\n\r\n*****************************\r\nOne repeating field failed: "+msgList); + return false; + } + foundRightMap.put(leftChildName, "OK"); + } else { + Element rightChild = (Element)selectSingleNode(right,leftChildName, namespace); + if (rightChild == null){ + TreeWalkEntry entry = new TreeWalkEntry(); + entry.lpath = leftChildPath; //this works, but is questionable: selectSingleNode(right, "//*[local-name() = \"objectexit_common\"]") + entry.status = TreeWalkEntry.STATUS.R_MISSING; + msgList.add(entry); + continue; + } + foundRightMap.put(leftChildName, "OK"); + String leftChildTextTrim = leftChild.getText().trim(); + String rightChildTextTrim = rightChild.getText().trim(); + TreeWalkEntry entry = new TreeWalkEntry(); + entry.ltextTrimmed = leftChildTextTrim; + entry.rtextTrimmed = rightChildTextTrim; + entry.lpath = leftChildPath; + entry.rpath = leftChildPath; //same + + if (leftChildTextTrim.equals(rightChildTextTrim)){ + entry.status = TreeWalkEntry.STATUS.MATCHED; + msgList.add(entry); + } else { + entry.status = TreeWalkEntry.STATUS.TEXT_DIFFERENT; + msgList.add(entry); + } + //============ DIVE !! ===================================================== + result = result && treeWalk( leftChild, rightChild, leftChildPath, msgList, matchSpec); + } + } + for (Object r : right.getChildren()){ + if (!(r instanceof Element)){ + continue; + } + Element rightChild = (Element)r; + String rname = rightChild.getQualifiedName(); + if (null==foundRightMap.get(rname)){ + String rightChildPath = Tools.glue(parentPath, "/", rname); + + TreeWalkEntry entry = new TreeWalkEntry(); + entry.rpath = rightChildPath; + entry.status = TreeWalkEntry.STATUS.R_ADDED; + msgList.add(entry); + } + } + return true; + } + + private static void dumpXML_OUT(Element el) throws Exception { + XMLOutputter outputter = new XMLOutputter(); + outputter.output(el, System.out); + } + private static String dumpXML(Element el) throws Exception { + XMLOutputter outputter = new XMLOutputter(); + return outputter.outputString(el); + } + + public static boolean doRepeatingFieldComparison(List leftList, + String leftChildPath, + String leftChildName, + Element left, + Element right, + TreeWalkResults msgList, + Namespace namespace, + TreeWalkResults.MatchSpec matchSpec) + throws Exception { + //todo: deal with foundRightMap in this repeating field block. + List rightList = select(right, leftChildName, namespace); + if (rightList == null || rightList.size() == 0 || rightList.size() < leftList.size()){ + TreeWalkEntry twe = new TreeWalkEntry(); + twe.lpath = leftChildPath; + twe.status = TreeWalkEntry.STATUS.R_MISSING; + String rmsg = (rightList == null) + ? " Right: 0" + : " Right: "+rightList.size(); + twe.message = "Repeating field count not matched. Field: "+leftChildPath+" Left: "+leftList.size()+rmsg; + msgList.add(twe); + return false; + } + if (rightList.size() > leftList.size()){ + TreeWalkEntry twe = new TreeWalkEntry(); + twe.lpath = leftChildPath; + twe.status = TreeWalkEntry.STATUS.R_ADDED; + twe.message = "Repeating field count not matched. Field: "+leftChildPath+" Left: "+leftList.size()+" Right: "+rightList.size(); + msgList.add(twe); + //LC 20110429 return false; + } + + for (Object le : leftList){ + boolean found = false; + Element leftEl = (Element)le; + //pl("left", leftEl); + for(Object re : rightList){ + Element rightEl = (Element)re; + //pl("right", rightEl); + TreeWalkResults msgListInner = new TreeWalkResults(); + //========== DIVE !!! ======================= + treeWalk(leftEl, rightEl, leftChildPath, msgListInner, matchSpec); + //======================================== + + if (msgListInner.treesMatch(matchSpec)){ //if (msgListInner.isStrictMatch()){ + found = true; + TreeWalkEntry twe = new TreeWalkEntry(); + twe.lpath = leftChildPath; + twe.status = TreeWalkEntry.STATUS.MATCHED; + msgList.add(twe); + rightList.remove(re); //found it, don't need to inspect this element again. Since we are breaking from loop, removing element won't mess up iterator--we get a new one on the next loop. + break; + } else { + TreeWalkEntry twe = new TreeWalkEntry(); + twe.lpath = leftChildPath; + twe.status = TreeWalkEntry.STATUS.NESTED_ERROR; + twe.nested = msgListInner; + msgList.add(twe); + //String line = "\r\n\r\n*********************************\r\n"; + //System.out.println(line+"TreeWalkResults: from walking rightEl: "+rightEl+" leftEl: "+leftEl + " msgListInner:"+ msgListInner+line); + } + } // END for(rightList) + if ( ! found){ + TreeWalkEntry twe = new TreeWalkEntry(); + twe.lpath = leftChildPath; + twe.status = TreeWalkEntry.STATUS.R_MISSING; + twe.message = "Repeating field not matched. Source: {"+dumpXML(leftEl)+"}"; + msgList.add(twe); + return false; + } + } // END for(leftLlist) + return true; + } + + private static void pl(String name, Element el) throws Exception { + Namespace namespace = el.getNamespace(); + Object lobid = selectSingleNode(el, "@ID", namespace); + String lid = ""; + if (lobid!=null){ + lid = lobid.toString(); + } + + System.out.println(name+": "+lid); + dumpXML_OUT(el); + System.out.println(); + + } +} diff --git a/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlReplay.java b/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlReplay.java index 944a8aea6..45d8c875a 100644 --- a/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlReplay.java +++ b/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlReplay.java @@ -1,873 +1,873 @@ -package org.collectionspace.services.IntegrationTests.xmlreplay; - -import org.apache.commons.cli.*; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.jexl2.JexlEngine; -import org.collectionspace.services.common.api.Tools; -import org.dom4j.*; -import org.dom4j.io.SAXReader; - -import java.io.*; -import java.util.*; - -/** This class is used to replay a request to the Services layer, by sending the XML payload - * in an appropriate Multipart request. - * See example usage in calling class XmlReplayTest in services/IntegrationTests, and also in main() in this class. - * @author Laramie Crocker - */ -public class XmlReplay { - - public XmlReplay(String basedir, String reportsDir){ - this.basedir = basedir; - this.serviceResultsMap = createResultsMap(); - this.reportsList = new ArrayList(); - this.reportsDir = reportsDir; - } - - public static final String DEFAULT_CONTROL = "xml-replay-control.xml"; - public static final String DEFAULT_MASTER_CONTROL = "xml-replay-master.xml"; - public static final String DEFAULT_DEV_MASTER_CONTROL = "dev-master.xml"; - - private String reportsDir = ""; - public String getReportsDir(){ - return reportsDir; - } - private String basedir = "."; //set from constructor. - public String getBaseDir(){ - return basedir; - } - - private String controlFileName = DEFAULT_CONTROL; - public String getControlFileName() { - return controlFileName; - } - public void setControlFileName(String controlFileName) { - this.controlFileName = controlFileName; - } - - private String protoHostPort = ""; - public String getProtoHostPort() { - return protoHostPort; - } - public void setProtoHostPort(String protoHostPort) { - this.protoHostPort = protoHostPort; - } - - private boolean autoDeletePOSTS = true; - public boolean isAutoDeletePOSTS() { - return autoDeletePOSTS; - } - public void setAutoDeletePOSTS(boolean autoDeletePOSTS) { - this.autoDeletePOSTS = autoDeletePOSTS; - } - - private Dump dump; - public Dump getDump() { - return dump; - } - public void setDump(Dump dump) { - this.dump = dump; - } - - AuthsMap defaultAuthsMap; - public AuthsMap getDefaultAuthsMap(){ - return defaultAuthsMap; - } - public void setDefaultAuthsMap(AuthsMap authsMap){ - defaultAuthsMap = authsMap; - } - - private Map serviceResultsMap; - public Map getServiceResultsMap(){ - return serviceResultsMap; - } - public static Map createResultsMap(){ - return new HashMap(); - } - - private List reportsList; - public List getReportsList(){ - return reportsList; - } - - public String toString(){ - return "XmlReplay{"+this.basedir+", "+this.defaultAuthsMap+", "+this.dump+", "+this.reportsDir+'}'; - } - - // ============== METHODS =========================================================== - - /** Optional information method: call this method after instantiating this class using the constructor XmlReplay(String), which sets the basedir. Then you - * pass in your relative masterFilename to that basedir to this method, which will return true if the file is readable, valid xml, etc. - * Do this in preference to just seeing if File.exists(), because there are rules to finding the file relative to the maven test dir, yada, yada. - * This method makes it easy to have a development test file that you don't check in, so that dev tests can be missing gracefully, etc. - */ - public boolean masterConfigFileExists(String masterFilename){ - try { - org.dom4j.Document doc = openMasterConfigFile(masterFilename); - if (doc == null){ - return false; - } - return true; - } catch (Throwable t){ - return false; - } - } - - public org.dom4j.Document openMasterConfigFile(String masterFilename) throws FileNotFoundException { - String fullPath = Tools.glue(basedir, "/", masterFilename); - File f = new File(fullPath); - if (!f.exists()){ - return null; - } - org.dom4j.Document document = getDocument(fullPath); //will check full path first, then checks relative to PWD. - if (document == null){ - throw new FileNotFoundException("XmlReplay master control file ("+masterFilename+") not found in basedir: "+basedir+". Exiting test."); - } - return document; - } - - /** specify the master config file, relative to getBaseDir(), but ignore any tests or testGroups in the master. - * @return a Document object, which you don't need to use: all options will be stored in XmlReplay instance. - */ - public org.dom4j.Document readOptionsFromMasterConfigFile(String masterFilename) throws FileNotFoundException { - org.dom4j.Document document = openMasterConfigFile(masterFilename); - if (document == null){ - throw new FileNotFoundException(masterFilename); - } - protoHostPort = document.selectSingleNode("/xmlReplayMaster/protoHostPort").getText().trim(); - AuthsMap authsMap = readAuths(document); - setDefaultAuthsMap(authsMap); - Dump dump = XmlReplay.readDumpOptions(document); - setDump(dump); - return document; - } - - public List> runMaster(String masterFilename) throws Exception { - return runMaster(masterFilename, true); - } - - /** Creates new instances of XmlReplay, one for each controlFile specified in the master, - * and setting defaults from this instance, but not sharing ServiceResult objects or maps. */ - public List> runMaster(String masterFilename, boolean readOptionsFromMaster) throws Exception { - List> list = new ArrayList>(); - org.dom4j.Document document; - if (readOptionsFromMaster){ - document = readOptionsFromMasterConfigFile(masterFilename); - } else { - document = openMasterConfigFile(masterFilename); - } - if (document==null){ - throw new FileNotFoundException(masterFilename); - } - String controlFile, testGroup, test; - List runNodes; - runNodes = document.selectNodes("/xmlReplayMaster/run"); - for (Node runNode : runNodes) { - controlFile = runNode.valueOf("@controlFile"); - testGroup = runNode.valueOf("@testGroup"); - test = runNode.valueOf("@test"); //may be empty - - //Create a new instance and clone only config values, not any results maps. - XmlReplay replay = new XmlReplay(basedir, this.reportsDir); - replay.setControlFileName(controlFile); - replay.setProtoHostPort(protoHostPort); - replay.setAutoDeletePOSTS(isAutoDeletePOSTS()); - replay.setDump(dump); - replay.setDefaultAuthsMap(getDefaultAuthsMap()); - - //Now run *that* instance. - List results = replay.runTests(testGroup, test); - list.add(results); - this.reportsList.addAll(replay.getReportsList()); //Add all the reports from the inner replay, to our master replay's reportsList, to generate the index.html file. - } - XmlReplayReport.saveIndexForMaster(basedir, reportsDir, masterFilename, this.reportsList); - return list; - } - - /** Use this if you wish to run named tests within a testGroup, otherwise call runTestGroup(). */ - public List runTests(String testGroupID, String testID) throws Exception { - List result = runXmlReplayFile(this.basedir, - this.controlFileName, - testGroupID, - testID, - this.serviceResultsMap, - this.autoDeletePOSTS, - dump, - this.protoHostPort, - this.defaultAuthsMap, - this.reportsList, - this.reportsDir); - return result; - } - - /** Use this if you wish to specify just ONE test to run within a testGroup, otherwise call runTestGroup(). */ - public ServiceResult runTest(String testGroupID, String testID) throws Exception { - List result = runXmlReplayFile(this.basedir, - this.controlFileName, - testGroupID, - testID, - this.serviceResultsMap, - this.autoDeletePOSTS, - dump, - this.protoHostPort, - this.defaultAuthsMap, - this.reportsList, - this.reportsDir); - if (result.size()>1){ - throw new IndexOutOfBoundsException("Multiple ("+result.size()+") tests with ID='"+testID+"' were found within test group '"+testGroupID+"', but there should only be one test per ID attribute."); - } - return result.get(0); - } - - /** Use this if you wish to run all tests within a testGroup.*/ - public List runTestGroup(String testGroupID) throws Exception { - //NOTE: calling runTest with empty testID runs all tests in a test group, but don't expose this fact. - // Expose this method (runTestGroup) instead. - return runTests(testGroupID, ""); - } - - public List autoDelete(String logName){ - return autoDelete(this.serviceResultsMap, logName); - } - - /** Use this method to clean up resources created on the server that returned CSIDs, if you have - * specified autoDeletePOSTS==false, which means you are managing the cleanup yourself. - * @param serviceResultsMap a Map of ServiceResult objects, which will contain ServiceResult.deleteURL. - * @return a List of debug info about which URLs could not be deleted. - */ - public static List autoDelete(Map serviceResultsMap, String logName){ - List results = new ArrayList(); - for (ServiceResult pr : serviceResultsMap.values()){ - try { - if (Tools.notEmpty(pr.deleteURL)){ - ServiceResult deleteResult = XmlReplayTransport.doDELETE(pr.deleteURL, pr.auth, pr.testID, "[autodelete:"+logName+"]"); - results.add(deleteResult); - } else { - ServiceResult errorResult = new ServiceResult(); - errorResult.fullURL = pr.fullURL; - errorResult.testGroupID = pr.testGroupID; - errorResult.fromTestID = pr.fromTestID; - errorResult.overrideGotExpectedResult(); - results.add(errorResult); - } - } catch (Throwable t){ - String s = (pr!=null) ? "ERROR while cleaning up ServiceResult map: "+pr+" for "+pr.deleteURL+" :: "+t - : "ERROR while cleaning up ServiceResult map (null ServiceResult): "+t; - System.err.println(s); - ServiceResult errorResult = new ServiceResult(); - errorResult.fullURL = pr.fullURL; - errorResult.testGroupID = pr.testGroupID; - errorResult.fromTestID = pr.fromTestID; - errorResult.error = s; - results.add(errorResult); - } - } - return results; - } - - public static class AuthsMap { - Map map; - String defaultID=""; - public String getDefaultAuth(){ - return map.get(defaultID); - } - public String toString(){ - return "AuthsMap: {default='"+defaultID+"'; "+map.keySet()+'}'; - } - } - - public static AuthsMap readAuths(org.dom4j.Document document){ - Map map = new HashMap(); - List authNodes = document.selectNodes("//auths/auth"); - for (Node auth : authNodes) { - map.put(auth.valueOf("@ID"), auth.getStringValue()); - } - AuthsMap authsMap = new AuthsMap(); - Node auths = document.selectSingleNode("//auths"); - String defaultID = ""; - if (auths != null){ - defaultID = auths.valueOf("@default"); - } - authsMap.map = map; - authsMap.defaultID = defaultID; - return authsMap; - } - - public static class Dump { - public boolean payloads = false; - //public static final ServiceResult.DUMP_OPTIONS dumpServiceResultOptions = ServiceResult.DUMP_OPTIONS; - public ServiceResult.DUMP_OPTIONS dumpServiceResult = ServiceResult.DUMP_OPTIONS.minimal; - public String toString(){ - return "payloads: "+payloads+" dumpServiceResult: "+dumpServiceResult; - } - } - - public static Dump getDumpConfig(){ - return new Dump(); - } - - public static Dump readDumpOptions(org.dom4j.Document document){ - Dump dump = getDumpConfig(); - Node dumpNode = document.selectSingleNode("//dump"); - if (dumpNode != null){ - dump.payloads = Tools.isTrue(dumpNode.valueOf("@payloads")); - String dumpServiceResultStr = dumpNode.valueOf("@dumpServiceResult"); - if (Tools.notEmpty(dumpServiceResultStr)){ - dump.dumpServiceResult = ServiceResult.DUMP_OPTIONS.valueOf(dumpServiceResultStr); - } - } - return dump; - } - - private static class PartsStruct { - public List> varsList = new ArrayList>(); - String responseFilename = ""; - String overrideTestID = ""; - String startElement = ""; - String label = ""; - - public static PartsStruct readParts(Node testNode, final String testID, String xmlReplayBaseDir){ - PartsStruct resultPartsStruct = new PartsStruct(); - resultPartsStruct.responseFilename = testNode.valueOf("filename"); - resultPartsStruct.startElement = testNode.valueOf("startElement"); - resultPartsStruct.label = testNode.valueOf("label"); - String responseFilename = testNode.valueOf("filename"); - if (Tools.notEmpty(responseFilename)){ - resultPartsStruct.responseFilename = xmlReplayBaseDir + '/' + responseFilename; - List varNodes = testNode.selectNodes("vars/var"); - readVars(testNode, varNodes, resultPartsStruct); - } - return resultPartsStruct; - } - - private static void readVars(Node testNode, List varNodes, PartsStruct resultPartsStruct){ - Map vars = new HashMap(); - resultPartsStruct.varsList.add(vars); - //System.out.println("### vars: "+vars.size()+" ########"); - for (Node var: varNodes){ - String ID = var.valueOf("@ID"); - String value = var.getText(); - //System.out.println("ID: "+ID+" value: "+value); - vars.put(ID, value); //vars is already part of resultPartsStruct.varsList - } - //System.out.println("### end-vars ########"); - } - } - - - - private static String fixupFullURL(String fullURL, String protoHostPort, String uri){ - if ( ! uri.startsWith(protoHostPort)){ - fullURL = Tools.glue(protoHostPort, "/", uri); - } else { - fullURL = uri; - } - return fullURL; - } - - private static String fromTestID(String fullURL, Node testNode, Map serviceResultsMap){ - String fromTestID = testNode.valueOf("fromTestID"); - if (Tools.notEmpty(fromTestID)){ - ServiceResult getPR = serviceResultsMap.get(fromTestID); - if (getPR != null){ - fullURL = Tools.glue(fullURL, "/", getPR.location); - } - } - return fullURL; - } - - private static String CSIDfromTestID(Node testNode, Map serviceResultsMap){ - String result = ""; - String fromTestID = testNode.valueOf("fromTestID"); - if (Tools.notEmpty(fromTestID)){ - ServiceResult getPR = serviceResultsMap.get(fromTestID); - if (getPR != null){ - result = getPR.location; - } - } - return result; - } - - public static org.dom4j.Document getDocument(String xmlFileName) { - org.dom4j.Document document = null; - SAXReader reader = new SAXReader(); - try { - document = reader.read(xmlFileName); - } catch (DocumentException e) { - System.out.println("ERROR reading document: "+e); - //e.printStackTrace(); - } - return document; - } - - protected static String validateResponseSinglePayload(ServiceResult serviceResult, - Map serviceResultsMap, - PartsStruct expectedResponseParts, - XmlReplayEval evalStruct) - throws Exception { - String OK = ""; - byte[] b = FileUtils.readFileToByteArray(new File(expectedResponseParts.responseFilename)); - String expectedPartContent = new String(b); - Map vars = expectedResponseParts.varsList.get(0); //just one part, so just one varsList. Must be there, even if empty. - expectedPartContent = evalStruct.eval(expectedPartContent, serviceResultsMap, vars, evalStruct.jexl, evalStruct.jc); - serviceResult.expectedContentExpanded = expectedPartContent; - String label = "NOLABEL"; - String leftID = "{from expected part, label:"+label+" filename: "+expectedResponseParts.responseFilename+"}"; - String rightID = "{from server, label:"+label - +" fromTestID: "+serviceResult.fromTestID - +" URL: "+serviceResult.fullURL - +"}"; - String startElement = expectedResponseParts.startElement; - String partLabel = expectedResponseParts.label; - if (Tools.isBlank(startElement)){ - if (Tools.notBlank(partLabel)) - startElement = "/document/*[local-name()='"+partLabel+"']"; - } - TreeWalkResults.MatchSpec matchSpec = TreeWalkResults.MatchSpec.createDefault(); - TreeWalkResults list = - XmlCompareJdom.compareParts(expectedPartContent, - leftID, - serviceResult.result, - rightID, - startElement, - matchSpec); - serviceResult.addPartSummary(label, list); - return OK; - } - - protected static String validateResponse(ServiceResult serviceResult, - Map serviceResultsMap, - PartsStruct expectedResponseParts, - XmlReplayEval evalStruct){ - String OK = ""; - if (expectedResponseParts == null) return OK; - if (serviceResult == null) return OK; - if (serviceResult.result.length() == 0) return OK; - try { - return validateResponseSinglePayload(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); - } catch (Exception e){ - String err = "ERROR in XmlReplay.validateResponse() : "+e; - return err ; - } - } - - //================= runXmlReplayFile ====================================================== - - public static List runXmlReplayFile(String xmlReplayBaseDir, - String controlFileName, - String testGroupID, - String oneTestID, - Map serviceResultsMap, - boolean param_autoDeletePOSTS, - Dump dump, - String protoHostPortParam, - AuthsMap defaultAuths, - List reportsList, - String reportsDir) - throws Exception { - //Internally, we maintain two collections of ServiceResult: - // the first is the return value of this method. - // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. - List results = new ArrayList(); - - XmlReplayReport report = new XmlReplayReport(reportsDir); - - String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); - org.dom4j.Document document; - document = getDocument(controlFile); //will check full path first, then checks relative to PWD. - if (document==null){ - throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); - } - String protoHostPort; - if (Tools.isEmpty(protoHostPortParam)){ - protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); - System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); - } else { - protoHostPort = protoHostPortParam; - } - if (Tools.isEmpty(protoHostPort)){ - throw new Exception("XmlReplay control file must have a protoHostPort element"); - } - - String authsMapINFO; - AuthsMap authsMap = readAuths(document); - if (authsMap.map.size()==0){ - authsMap = defaultAuths; - authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; - } else { - authsMapINFO = "Using AuthsMap from control file: "+authsMap; - } - - report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. - String xmlReplayHeader = "========================================================================" - +"\r\nXmlReplay running:" - +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) - +"\r\n protoHostPort: "+protoHostPort - +"\r\n testGroup: "+testGroupID - + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") - +"\r\n AuthsMap: "+authsMapINFO - +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS - +"\r\n Dump info: "+dump - +"\r\n========================================================================" - +"\r\n"; - report.addRunInfo(xmlReplayHeader); - - System.out.println(xmlReplayHeader); - - String autoDeletePOSTS = ""; - List testgroupNodes; - if (Tools.notEmpty(testGroupID)){ - testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); - } else { - testgroupNodes = document.selectNodes("//testGroup"); - } - - JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. - XmlReplayEval evalStruct = new XmlReplayEval(); - evalStruct.serviceResultsMap = serviceResultsMap; - evalStruct.jexl = jexl; - - for (Node testgroup : testgroupNodes) { - - XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. - evalStruct.jc = jc; - - autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); - List tests; - if (Tools.notEmpty(oneTestID)){ - tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); - } else { - tests = testgroup.selectNodes("test"); - } - String authForTest = ""; - int testElementIndex = -1; - - for (Node testNode : tests) { - long startTime = System.currentTimeMillis(); - try { - testElementIndex++; - String testID = testNode.valueOf("@ID"); - String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); - String method = testNode.valueOf("method"); - String uri = testNode.valueOf("uri"); - String fullURL = Tools.glue(protoHostPort, "/", uri); - - String authIDForTest = testNode.valueOf("@auth"); - String currentAuthForTest = authsMap.map.get(authIDForTest); - if (Tools.notEmpty(currentAuthForTest)){ - authForTest = currentAuthForTest; //else just run with current from last loop; - } - if (Tools.isEmpty(authForTest)){ - authForTest = defaultAuths.getDefaultAuth(); - } - - if (uri.indexOf("$")>-1){ - uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); - } - fullURL = fixupFullURL(fullURL, protoHostPort, uri); - - List expectedCodes = new ArrayList(); - String expectedCodesStr = testNode.valueOf("expectedCodes"); - if (Tools.notEmpty(expectedCodesStr)){ - String[] codesArray = expectedCodesStr.split(","); - for (String code : codesArray){ - expectedCodes.add(new Integer(code.trim())); - } - } - - Node responseNode = testNode.selectSingleNode("response"); - PartsStruct expectedResponseParts = null; - if (responseNode!=null){ - expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); - //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); - } - - ServiceResult serviceResult; - boolean isPOST = method.equalsIgnoreCase("POST"); - boolean isPUT = method.equalsIgnoreCase("PUT"); - if ( isPOST || isPUT ) { - PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); - if (Tools.notEmpty(parts.overrideTestID)) { - testID = parts.overrideTestID; - } - if (isPOST){ - String csid = CSIDfromTestID(testNode, serviceResultsMap); - if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); - } else if (isPUT) { - uri = fromTestID(uri, testNode, serviceResultsMap); - } - //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, - // and in nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. - Map vars = null; - if (parts.varsList.size()>0){ - vars = parts.varsList.get(0); - } - serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, XmlReplayTransport.APPLICATION_XML, evalStruct, authForTest, testIDLabel); - if (vars!=null) { - serviceResult.addVars(vars); - } - results.add(serviceResult); - //if (isPOST){ - serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. - //} - fullURL = fixupFullURL(fullURL, protoHostPort, uri); - } else if (method.equalsIgnoreCase("DELETE")){ - String fromTestID = testNode.valueOf("fromTestID"); - ServiceResult pr = serviceResultsMap.get(fromTestID); - if (pr!=null){ - serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); - serviceResult.fromTestID = fromTestID; - if (expectedCodes.size()>0){ - serviceResult.expectedCodes = expectedCodes; - } - results.add(serviceResult); - if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. - serviceResultsMap.remove(fromTestID); - } - } else { - if (Tools.notEmpty(fromTestID)){ - serviceResult = new ServiceResult(); - serviceResult.responseCode = 0; - serviceResult.error = "ID not found in element fromTestID: "+fromTestID; - System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); - } else { - serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); - } - serviceResult.fromTestID = fromTestID; - results.add(serviceResult); - } - } else if (method.equalsIgnoreCase("GET")){ - fullURL = fromTestID(fullURL, testNode, serviceResultsMap); - serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); - results.add(serviceResult); - serviceResultsMap.put(testID, serviceResult); - } else if (method.equalsIgnoreCase("LIST")){ - fullURL = fixupFullURL(fullURL, protoHostPort, uri); - String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. - serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); - results.add(serviceResult); - serviceResultsMap.put(testID, serviceResult); - } else { - throw new Exception("HTTP method not supported by XmlReplay: "+method); - } - - serviceResult.testID = testID; - serviceResult.fullURL = fullURL; - serviceResult.auth = authForTest; - serviceResult.method = method; - if (expectedCodes.size()>0){ - serviceResult.expectedCodes = expectedCodes; - } - if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; - if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; - - Node expectedLevel = testNode.selectSingleNode("response/expected"); - if (expectedLevel!=null){ - String level = expectedLevel.valueOf("@level"); - serviceResult.payloadStrictness = level; - } - //===================================================== - // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: - //===================================================== - boolean hasError = false; - String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); - if (Tools.notEmpty(vError)){ - serviceResult.error = vError; - serviceResult.failureReason = " : VALIDATION ERROR; "; - hasError = true; - } - if (hasError == false){ - hasError = ! serviceResult.gotExpectedResult(); - } - - boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); - String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); - String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; - - report.addTestResult(serviceResult); - - if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) - || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ - System.out.println("\r\n#---------------------#"); - } - System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); - if (dump.payloads || (doingAuto&&hasError) ) { - if (Tools.notBlank(serviceResult.requestPayload)){ - System.out.println("\r\n========== request payload ==============="); - System.out.println(serviceResult.requestPayload); - System.out.println("==========================================\r\n"); - } - } - if (dump.payloads || (doingAuto&&hasError)) { - if (Tools.notBlank(serviceResult.result)){ - System.out.println("\r\n========== response payload =============="); - System.out.println(serviceResult.result); - System.out.println("==========================================\r\n"); - } - } - } catch (Throwable t) { - String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; - System.out.println(msg); - System.out.println(Tools.getStackTrace(t)); - ServiceResult serviceResult = new ServiceResult(); - serviceResult.error = msg; - serviceResult.failureReason = " : SYSTEM ERROR; "; - results.add(serviceResult); - } - } - if (Tools.isTrue(autoDeletePOSTS)&¶m_autoDeletePOSTS){ - autoDelete(serviceResultsMap, "default"); - } - } - - //=== Now spit out the HTML report file === - File m = new File(controlFileName); - String localName = m.getName();//don't instantiate, just use File to extract file name without directory. - String reportName = localName+'-'+testGroupID+".html"; - - File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); - if (resultFile!=null) { - String toc = report.getTOC(reportName); - reportsList.add(toc); - } - //================================ - - return results; - } - - private static String timeString() { - java.util.Date date= new java.util.Date(); - java.sql.Timestamp ts = new java.sql.Timestamp(date.getTime()); - return ts.toString(); - } - - - //======================== MAIN =================================================================== - - private static Options createOptions() { - Options options = new Options(); - options.addOption("xmlReplayBaseDir", true, "default/basedir"); - return options; - } - - public static String usage(){ - String result = "org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplay {args}\r\n" - +" -xmlReplayBaseDir \r\n" - +" You may also override these with system args, e.g.: \r\n" - +" -DxmlReplayBaseDir=/path/to/dir \r\n" - +" These may also be passed in via the POM.\r\n" - +" You can also set these system args, e.g.: \r\n" - +" -DtestGroupID= \r\n" - +" -DtestID=" - +" -DautoDeletePOSTS= \r\n" - +" (note: -DautoDeletePOSTS won't force deletion if set to false in control file."; - return result; - } - - private static String opt(CommandLine line, String option){ - String result; - String fromProps = System.getProperty(option); - if (Tools.notEmpty(fromProps)){ - return fromProps; - } - if (line==null){ - return ""; - } - result = line.getOptionValue(option); - if (result == null){ - result = ""; - } - return result; - } - - public static void main(String[]args) throws Exception { - Options options = createOptions(); - //System.out.println("System CLASSPATH: "+prop.getProperty("java.class.path", null)); - CommandLineParser parser = new GnuParser(); - try { - // parse the command line arguments - CommandLine line = parser.parse(options, args); - - String xmlReplayBaseDir = opt(line, "xmlReplayBaseDir"); - String reportsDir = opt(line, "reportsDir"); - String testGroupID = opt(line, "testGroupID"); - String testID = opt(line, "testID"); - String autoDeletePOSTS = opt(line, "autoDeletePOSTS"); - String dumpResults = opt(line, "dumpResults"); - String controlFilename = opt(line, "controlFilename"); - String xmlReplayMaster = opt(line, "xmlReplayMaster"); - - if (Tools.isBlank(reportsDir)){ - reportsDir = xmlReplayBaseDir + XmlReplayTest.REPORTS_DIRNAME; - } - reportsDir = Tools.fixFilename(reportsDir); - xmlReplayBaseDir = Tools.fixFilename(xmlReplayBaseDir); - controlFilename = Tools.fixFilename(controlFilename); - - boolean bAutoDeletePOSTS = true; - if (Tools.notEmpty(autoDeletePOSTS)) { - bAutoDeletePOSTS = Tools.isTrue(autoDeletePOSTS); - } - boolean bDumpResults = false; - if (Tools.notEmpty(dumpResults)) { - bDumpResults = Tools.isTrue(autoDeletePOSTS); - } - if (Tools.isEmpty(xmlReplayBaseDir)){ - System.err.println("ERROR: xmlReplayBaseDir was not specified."); - return; - } - File f = new File(Tools.glue(xmlReplayBaseDir, "/", controlFilename)); - if (Tools.isEmpty(xmlReplayMaster) && !f.exists()){ - System.err.println("Control file not found: "+f.getCanonicalPath()); - return; - } - File fMaster = new File(Tools.glue(xmlReplayBaseDir, "/", xmlReplayMaster)); - if (Tools.notEmpty(xmlReplayMaster) && !fMaster.exists()){ - System.err.println("Master file not found: "+fMaster.getCanonicalPath()); - return; - } - - String xmlReplayBaseDirResolved = (new File(xmlReplayBaseDir)).getCanonicalPath(); - System.out.println("XmlReplay ::" - + "\r\n xmlReplayBaseDir: "+xmlReplayBaseDir - + "\r\n xmlReplayBaseDir(resolved): "+xmlReplayBaseDirResolved - + "\r\n controlFilename: "+controlFilename - + "\r\n xmlReplayMaster: "+xmlReplayMaster - + "\r\n testGroupID: "+testGroupID - + "\r\n testID: "+testID - + "\r\n autoDeletePOSTS: "+bAutoDeletePOSTS - + (Tools.notEmpty(xmlReplayMaster) - ? ("\r\n will use master file: "+fMaster.getCanonicalPath()) - : ("\r\n will use control file: "+f.getCanonicalPath()) ) - ); - - if (Tools.notEmpty(xmlReplayMaster)){ - if (Tools.notEmpty(controlFilename)){ - System.out.println("WARN: controlFilename: "+controlFilename+" will not be used because master was specified. Running master: "+xmlReplayMaster); - } - XmlReplay replay = new XmlReplay(xmlReplayBaseDirResolved, reportsDir); - replay.readOptionsFromMasterConfigFile(xmlReplayMaster); - replay.setAutoDeletePOSTS(bAutoDeletePOSTS); - Dump dumpFromMaster = replay.getDump(); - dumpFromMaster.payloads = Tools.isTrue(dumpResults); - replay.setDump(dumpFromMaster); - replay.runMaster(xmlReplayMaster, false); //false, because we already just read the options, and override a few. - } else { - Dump dump = getDumpConfig(); - dump.payloads = Tools.isTrue(dumpResults); - List reportsList = new ArrayList(); - runXmlReplayFile(xmlReplayBaseDirResolved, controlFilename, testGroupID, testID, createResultsMap(), bAutoDeletePOSTS, dump, "", null, reportsList, reportsDir); - System.out.println("DEPRECATED: reportsList is generated, but not dumped: "+reportsList.toString()); - } - } catch (ParseException exp) { - // oops, something went wrong - System.err.println("Cmd-line parsing failed. Reason: " + exp.getMessage()); - System.err.println(usage()); - } catch (Exception e) { - System.out.println("Error : " + e.getMessage()); - e.printStackTrace(); - } - } - -} +package org.collectionspace.services.IntegrationTests.xmlreplay; + +import org.apache.commons.cli.*; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.jexl2.JexlEngine; +import org.collectionspace.services.common.api.Tools; +import org.dom4j.*; +import org.dom4j.io.SAXReader; + +import java.io.*; +import java.util.*; + +/** This class is used to replay a request to the Services layer, by sending the XML payload + * in an appropriate Multipart request. + * See example usage in calling class XmlReplayTest in services/IntegrationTests, and also in main() in this class. + * @author Laramie Crocker + */ +public class XmlReplay { + + public XmlReplay(String basedir, String reportsDir){ + this.basedir = basedir; + this.serviceResultsMap = createResultsMap(); + this.reportsList = new ArrayList(); + this.reportsDir = reportsDir; + } + + public static final String DEFAULT_CONTROL = "xml-replay-control.xml"; + public static final String DEFAULT_MASTER_CONTROL = "xml-replay-master.xml"; + public static final String DEFAULT_DEV_MASTER_CONTROL = "dev-master.xml"; + + private String reportsDir = ""; + public String getReportsDir(){ + return reportsDir; + } + private String basedir = "."; //set from constructor. + public String getBaseDir(){ + return basedir; + } + + private String controlFileName = DEFAULT_CONTROL; + public String getControlFileName() { + return controlFileName; + } + public void setControlFileName(String controlFileName) { + this.controlFileName = controlFileName; + } + + private String protoHostPort = ""; + public String getProtoHostPort() { + return protoHostPort; + } + public void setProtoHostPort(String protoHostPort) { + this.protoHostPort = protoHostPort; + } + + private boolean autoDeletePOSTS = true; + public boolean isAutoDeletePOSTS() { + return autoDeletePOSTS; + } + public void setAutoDeletePOSTS(boolean autoDeletePOSTS) { + this.autoDeletePOSTS = autoDeletePOSTS; + } + + private Dump dump; + public Dump getDump() { + return dump; + } + public void setDump(Dump dump) { + this.dump = dump; + } + + AuthsMap defaultAuthsMap; + public AuthsMap getDefaultAuthsMap(){ + return defaultAuthsMap; + } + public void setDefaultAuthsMap(AuthsMap authsMap){ + defaultAuthsMap = authsMap; + } + + private Map serviceResultsMap; + public Map getServiceResultsMap(){ + return serviceResultsMap; + } + public static Map createResultsMap(){ + return new HashMap(); + } + + private List reportsList; + public List getReportsList(){ + return reportsList; + } + + public String toString(){ + return "XmlReplay{"+this.basedir+", "+this.defaultAuthsMap+", "+this.dump+", "+this.reportsDir+'}'; + } + + // ============== METHODS =========================================================== + + /** Optional information method: call this method after instantiating this class using the constructor XmlReplay(String), which sets the basedir. Then you + * pass in your relative masterFilename to that basedir to this method, which will return true if the file is readable, valid xml, etc. + * Do this in preference to just seeing if File.exists(), because there are rules to finding the file relative to the maven test dir, yada, yada. + * This method makes it easy to have a development test file that you don't check in, so that dev tests can be missing gracefully, etc. + */ + public boolean masterConfigFileExists(String masterFilename){ + try { + org.dom4j.Document doc = openMasterConfigFile(masterFilename); + if (doc == null){ + return false; + } + return true; + } catch (Throwable t){ + return false; + } + } + + public org.dom4j.Document openMasterConfigFile(String masterFilename) throws FileNotFoundException { + String fullPath = Tools.glue(basedir, "/", masterFilename); + File f = new File(fullPath); + if (!f.exists()){ + return null; + } + org.dom4j.Document document = getDocument(fullPath); //will check full path first, then checks relative to PWD. + if (document == null){ + throw new FileNotFoundException("XmlReplay master control file ("+masterFilename+") not found in basedir: "+basedir+". Exiting test."); + } + return document; + } + + /** specify the master config file, relative to getBaseDir(), but ignore any tests or testGroups in the master. + * @return a Document object, which you don't need to use: all options will be stored in XmlReplay instance. + */ + public org.dom4j.Document readOptionsFromMasterConfigFile(String masterFilename) throws FileNotFoundException { + org.dom4j.Document document = openMasterConfigFile(masterFilename); + if (document == null){ + throw new FileNotFoundException(masterFilename); + } + protoHostPort = document.selectSingleNode("/xmlReplayMaster/protoHostPort").getText().trim(); + AuthsMap authsMap = readAuths(document); + setDefaultAuthsMap(authsMap); + Dump dump = XmlReplay.readDumpOptions(document); + setDump(dump); + return document; + } + + public List> runMaster(String masterFilename) throws Exception { + return runMaster(masterFilename, true); + } + + /** Creates new instances of XmlReplay, one for each controlFile specified in the master, + * and setting defaults from this instance, but not sharing ServiceResult objects or maps. */ + public List> runMaster(String masterFilename, boolean readOptionsFromMaster) throws Exception { + List> list = new ArrayList>(); + org.dom4j.Document document; + if (readOptionsFromMaster){ + document = readOptionsFromMasterConfigFile(masterFilename); + } else { + document = openMasterConfigFile(masterFilename); + } + if (document==null){ + throw new FileNotFoundException(masterFilename); + } + String controlFile, testGroup, test; + List runNodes; + runNodes = document.selectNodes("/xmlReplayMaster/run"); + for (Node runNode : runNodes) { + controlFile = runNode.valueOf("@controlFile"); + testGroup = runNode.valueOf("@testGroup"); + test = runNode.valueOf("@test"); //may be empty + + //Create a new instance and clone only config values, not any results maps. + XmlReplay replay = new XmlReplay(basedir, this.reportsDir); + replay.setControlFileName(controlFile); + replay.setProtoHostPort(protoHostPort); + replay.setAutoDeletePOSTS(isAutoDeletePOSTS()); + replay.setDump(dump); + replay.setDefaultAuthsMap(getDefaultAuthsMap()); + + //Now run *that* instance. + List results = replay.runTests(testGroup, test); + list.add(results); + this.reportsList.addAll(replay.getReportsList()); //Add all the reports from the inner replay, to our master replay's reportsList, to generate the index.html file. + } + XmlReplayReport.saveIndexForMaster(basedir, reportsDir, masterFilename, this.reportsList); + return list; + } + + /** Use this if you wish to run named tests within a testGroup, otherwise call runTestGroup(). */ + public List runTests(String testGroupID, String testID) throws Exception { + List result = runXmlReplayFile(this.basedir, + this.controlFileName, + testGroupID, + testID, + this.serviceResultsMap, + this.autoDeletePOSTS, + dump, + this.protoHostPort, + this.defaultAuthsMap, + this.reportsList, + this.reportsDir); + return result; + } + + /** Use this if you wish to specify just ONE test to run within a testGroup, otherwise call runTestGroup(). */ + public ServiceResult runTest(String testGroupID, String testID) throws Exception { + List result = runXmlReplayFile(this.basedir, + this.controlFileName, + testGroupID, + testID, + this.serviceResultsMap, + this.autoDeletePOSTS, + dump, + this.protoHostPort, + this.defaultAuthsMap, + this.reportsList, + this.reportsDir); + if (result.size()>1){ + throw new IndexOutOfBoundsException("Multiple ("+result.size()+") tests with ID='"+testID+"' were found within test group '"+testGroupID+"', but there should only be one test per ID attribute."); + } + return result.get(0); + } + + /** Use this if you wish to run all tests within a testGroup.*/ + public List runTestGroup(String testGroupID) throws Exception { + //NOTE: calling runTest with empty testID runs all tests in a test group, but don't expose this fact. + // Expose this method (runTestGroup) instead. + return runTests(testGroupID, ""); + } + + public List autoDelete(String logName){ + return autoDelete(this.serviceResultsMap, logName); + } + + /** Use this method to clean up resources created on the server that returned CSIDs, if you have + * specified autoDeletePOSTS==false, which means you are managing the cleanup yourself. + * @param serviceResultsMap a Map of ServiceResult objects, which will contain ServiceResult.deleteURL. + * @return a List of debug info about which URLs could not be deleted. + */ + public static List autoDelete(Map serviceResultsMap, String logName){ + List results = new ArrayList(); + for (ServiceResult pr : serviceResultsMap.values()){ + try { + if (Tools.notEmpty(pr.deleteURL)){ + ServiceResult deleteResult = XmlReplayTransport.doDELETE(pr.deleteURL, pr.auth, pr.testID, "[autodelete:"+logName+"]"); + results.add(deleteResult); + } else { + ServiceResult errorResult = new ServiceResult(); + errorResult.fullURL = pr.fullURL; + errorResult.testGroupID = pr.testGroupID; + errorResult.fromTestID = pr.fromTestID; + errorResult.overrideGotExpectedResult(); + results.add(errorResult); + } + } catch (Throwable t){ + String s = (pr!=null) ? "ERROR while cleaning up ServiceResult map: "+pr+" for "+pr.deleteURL+" :: "+t + : "ERROR while cleaning up ServiceResult map (null ServiceResult): "+t; + System.err.println(s); + ServiceResult errorResult = new ServiceResult(); + errorResult.fullURL = pr.fullURL; + errorResult.testGroupID = pr.testGroupID; + errorResult.fromTestID = pr.fromTestID; + errorResult.error = s; + results.add(errorResult); + } + } + return results; + } + + public static class AuthsMap { + Map map; + String defaultID=""; + public String getDefaultAuth(){ + return map.get(defaultID); + } + public String toString(){ + return "AuthsMap: {default='"+defaultID+"'; "+map.keySet()+'}'; + } + } + + public static AuthsMap readAuths(org.dom4j.Document document){ + Map map = new HashMap(); + List authNodes = document.selectNodes("//auths/auth"); + for (Node auth : authNodes) { + map.put(auth.valueOf("@ID"), auth.getStringValue()); + } + AuthsMap authsMap = new AuthsMap(); + Node auths = document.selectSingleNode("//auths"); + String defaultID = ""; + if (auths != null){ + defaultID = auths.valueOf("@default"); + } + authsMap.map = map; + authsMap.defaultID = defaultID; + return authsMap; + } + + public static class Dump { + public boolean payloads = false; + //public static final ServiceResult.DUMP_OPTIONS dumpServiceResultOptions = ServiceResult.DUMP_OPTIONS; + public ServiceResult.DUMP_OPTIONS dumpServiceResult = ServiceResult.DUMP_OPTIONS.minimal; + public String toString(){ + return "payloads: "+payloads+" dumpServiceResult: "+dumpServiceResult; + } + } + + public static Dump getDumpConfig(){ + return new Dump(); + } + + public static Dump readDumpOptions(org.dom4j.Document document){ + Dump dump = getDumpConfig(); + Node dumpNode = document.selectSingleNode("//dump"); + if (dumpNode != null){ + dump.payloads = Tools.isTrue(dumpNode.valueOf("@payloads")); + String dumpServiceResultStr = dumpNode.valueOf("@dumpServiceResult"); + if (Tools.notEmpty(dumpServiceResultStr)){ + dump.dumpServiceResult = ServiceResult.DUMP_OPTIONS.valueOf(dumpServiceResultStr); + } + } + return dump; + } + + private static class PartsStruct { + public List> varsList = new ArrayList>(); + String responseFilename = ""; + String overrideTestID = ""; + String startElement = ""; + String label = ""; + + public static PartsStruct readParts(Node testNode, final String testID, String xmlReplayBaseDir){ + PartsStruct resultPartsStruct = new PartsStruct(); + resultPartsStruct.responseFilename = testNode.valueOf("filename"); + resultPartsStruct.startElement = testNode.valueOf("startElement"); + resultPartsStruct.label = testNode.valueOf("label"); + String responseFilename = testNode.valueOf("filename"); + if (Tools.notEmpty(responseFilename)){ + resultPartsStruct.responseFilename = xmlReplayBaseDir + '/' + responseFilename; + List varNodes = testNode.selectNodes("vars/var"); + readVars(testNode, varNodes, resultPartsStruct); + } + return resultPartsStruct; + } + + private static void readVars(Node testNode, List varNodes, PartsStruct resultPartsStruct){ + Map vars = new HashMap(); + resultPartsStruct.varsList.add(vars); + //System.out.println("### vars: "+vars.size()+" ########"); + for (Node var: varNodes){ + String ID = var.valueOf("@ID"); + String value = var.getText(); + //System.out.println("ID: "+ID+" value: "+value); + vars.put(ID, value); //vars is already part of resultPartsStruct.varsList + } + //System.out.println("### end-vars ########"); + } + } + + + + private static String fixupFullURL(String fullURL, String protoHostPort, String uri){ + if ( ! uri.startsWith(protoHostPort)){ + fullURL = Tools.glue(protoHostPort, "/", uri); + } else { + fullURL = uri; + } + return fullURL; + } + + private static String fromTestID(String fullURL, Node testNode, Map serviceResultsMap){ + String fromTestID = testNode.valueOf("fromTestID"); + if (Tools.notEmpty(fromTestID)){ + ServiceResult getPR = serviceResultsMap.get(fromTestID); + if (getPR != null){ + fullURL = Tools.glue(fullURL, "/", getPR.location); + } + } + return fullURL; + } + + private static String CSIDfromTestID(Node testNode, Map serviceResultsMap){ + String result = ""; + String fromTestID = testNode.valueOf("fromTestID"); + if (Tools.notEmpty(fromTestID)){ + ServiceResult getPR = serviceResultsMap.get(fromTestID); + if (getPR != null){ + result = getPR.location; + } + } + return result; + } + + public static org.dom4j.Document getDocument(String xmlFileName) { + org.dom4j.Document document = null; + SAXReader reader = new SAXReader(); + try { + document = reader.read(xmlFileName); + } catch (DocumentException e) { + System.out.println("ERROR reading document: "+e); + //e.printStackTrace(); + } + return document; + } + + protected static String validateResponseSinglePayload(ServiceResult serviceResult, + Map serviceResultsMap, + PartsStruct expectedResponseParts, + XmlReplayEval evalStruct) + throws Exception { + String OK = ""; + byte[] b = FileUtils.readFileToByteArray(new File(expectedResponseParts.responseFilename)); + String expectedPartContent = new String(b); + Map vars = expectedResponseParts.varsList.get(0); //just one part, so just one varsList. Must be there, even if empty. + expectedPartContent = evalStruct.eval(expectedPartContent, serviceResultsMap, vars, evalStruct.jexl, evalStruct.jc); + serviceResult.expectedContentExpanded = expectedPartContent; + String label = "NOLABEL"; + String leftID = "{from expected part, label:"+label+" filename: "+expectedResponseParts.responseFilename+"}"; + String rightID = "{from server, label:"+label + +" fromTestID: "+serviceResult.fromTestID + +" URL: "+serviceResult.fullURL + +"}"; + String startElement = expectedResponseParts.startElement; + String partLabel = expectedResponseParts.label; + if (Tools.isBlank(startElement)){ + if (Tools.notBlank(partLabel)) + startElement = "/document/*[local-name()='"+partLabel+"']"; + } + TreeWalkResults.MatchSpec matchSpec = TreeWalkResults.MatchSpec.createDefault(); + TreeWalkResults list = + XmlCompareJdom.compareParts(expectedPartContent, + leftID, + serviceResult.result, + rightID, + startElement, + matchSpec); + serviceResult.addPartSummary(label, list); + return OK; + } + + protected static String validateResponse(ServiceResult serviceResult, + Map serviceResultsMap, + PartsStruct expectedResponseParts, + XmlReplayEval evalStruct){ + String OK = ""; + if (expectedResponseParts == null) return OK; + if (serviceResult == null) return OK; + if (serviceResult.result.length() == 0) return OK; + try { + return validateResponseSinglePayload(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); + } catch (Exception e){ + String err = "ERROR in XmlReplay.validateResponse() : "+e; + return err ; + } + } + + //================= runXmlReplayFile ====================================================== + + public static List runXmlReplayFile(String xmlReplayBaseDir, + String controlFileName, + String testGroupID, + String oneTestID, + Map serviceResultsMap, + boolean param_autoDeletePOSTS, + Dump dump, + String protoHostPortParam, + AuthsMap defaultAuths, + List reportsList, + String reportsDir) + throws Exception { + //Internally, we maintain two collections of ServiceResult: + // the first is the return value of this method. + // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. + List results = new ArrayList(); + + XmlReplayReport report = new XmlReplayReport(reportsDir); + + String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); + org.dom4j.Document document; + document = getDocument(controlFile); //will check full path first, then checks relative to PWD. + if (document==null){ + throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); + } + String protoHostPort; + if (Tools.isEmpty(protoHostPortParam)){ + protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); + System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); + } else { + protoHostPort = protoHostPortParam; + } + if (Tools.isEmpty(protoHostPort)){ + throw new Exception("XmlReplay control file must have a protoHostPort element"); + } + + String authsMapINFO; + AuthsMap authsMap = readAuths(document); + if (authsMap.map.size()==0){ + authsMap = defaultAuths; + authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; + } else { + authsMapINFO = "Using AuthsMap from control file: "+authsMap; + } + + report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. + String xmlReplayHeader = "========================================================================" + +"\r\nXmlReplay running:" + +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) + +"\r\n protoHostPort: "+protoHostPort + +"\r\n testGroup: "+testGroupID + + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") + +"\r\n AuthsMap: "+authsMapINFO + +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS + +"\r\n Dump info: "+dump + +"\r\n========================================================================" + +"\r\n"; + report.addRunInfo(xmlReplayHeader); + + System.out.println(xmlReplayHeader); + + String autoDeletePOSTS = ""; + List testgroupNodes; + if (Tools.notEmpty(testGroupID)){ + testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); + } else { + testgroupNodes = document.selectNodes("//testGroup"); + } + + JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. + XmlReplayEval evalStruct = new XmlReplayEval(); + evalStruct.serviceResultsMap = serviceResultsMap; + evalStruct.jexl = jexl; + + for (Node testgroup : testgroupNodes) { + + XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. + evalStruct.jc = jc; + + autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); + List tests; + if (Tools.notEmpty(oneTestID)){ + tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); + } else { + tests = testgroup.selectNodes("test"); + } + String authForTest = ""; + int testElementIndex = -1; + + for (Node testNode : tests) { + long startTime = System.currentTimeMillis(); + try { + testElementIndex++; + String testID = testNode.valueOf("@ID"); + String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); + String method = testNode.valueOf("method"); + String uri = testNode.valueOf("uri"); + String fullURL = Tools.glue(protoHostPort, "/", uri); + + String authIDForTest = testNode.valueOf("@auth"); + String currentAuthForTest = authsMap.map.get(authIDForTest); + if (Tools.notEmpty(currentAuthForTest)){ + authForTest = currentAuthForTest; //else just run with current from last loop; + } + if (Tools.isEmpty(authForTest)){ + authForTest = defaultAuths.getDefaultAuth(); + } + + if (uri.indexOf("$")>-1){ + uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); + } + fullURL = fixupFullURL(fullURL, protoHostPort, uri); + + List expectedCodes = new ArrayList(); + String expectedCodesStr = testNode.valueOf("expectedCodes"); + if (Tools.notEmpty(expectedCodesStr)){ + String[] codesArray = expectedCodesStr.split(","); + for (String code : codesArray){ + expectedCodes.add(new Integer(code.trim())); + } + } + + Node responseNode = testNode.selectSingleNode("response"); + PartsStruct expectedResponseParts = null; + if (responseNode!=null){ + expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); + //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); + } + + ServiceResult serviceResult; + boolean isPOST = method.equalsIgnoreCase("POST"); + boolean isPUT = method.equalsIgnoreCase("PUT"); + if ( isPOST || isPUT ) { + PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); + if (Tools.notEmpty(parts.overrideTestID)) { + testID = parts.overrideTestID; + } + if (isPOST){ + String csid = CSIDfromTestID(testNode, serviceResultsMap); + if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); + } else if (isPUT) { + uri = fromTestID(uri, testNode, serviceResultsMap); + } + //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, + // and in nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. + Map vars = null; + if (parts.varsList.size()>0){ + vars = parts.varsList.get(0); + } + serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, XmlReplayTransport.APPLICATION_XML, evalStruct, authForTest, testIDLabel); + if (vars!=null) { + serviceResult.addVars(vars); + } + results.add(serviceResult); + //if (isPOST){ + serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. + //} + fullURL = fixupFullURL(fullURL, protoHostPort, uri); + } else if (method.equalsIgnoreCase("DELETE")){ + String fromTestID = testNode.valueOf("fromTestID"); + ServiceResult pr = serviceResultsMap.get(fromTestID); + if (pr!=null){ + serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); + serviceResult.fromTestID = fromTestID; + if (expectedCodes.size()>0){ + serviceResult.expectedCodes = expectedCodes; + } + results.add(serviceResult); + if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. + serviceResultsMap.remove(fromTestID); + } + } else { + if (Tools.notEmpty(fromTestID)){ + serviceResult = new ServiceResult(); + serviceResult.responseCode = 0; + serviceResult.error = "ID not found in element fromTestID: "+fromTestID; + System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); + } else { + serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); + } + serviceResult.fromTestID = fromTestID; + results.add(serviceResult); + } + } else if (method.equalsIgnoreCase("GET")){ + fullURL = fromTestID(fullURL, testNode, serviceResultsMap); + serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); + results.add(serviceResult); + serviceResultsMap.put(testID, serviceResult); + } else if (method.equalsIgnoreCase("LIST")){ + fullURL = fixupFullURL(fullURL, protoHostPort, uri); + String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. + serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); + results.add(serviceResult); + serviceResultsMap.put(testID, serviceResult); + } else { + throw new Exception("HTTP method not supported by XmlReplay: "+method); + } + + serviceResult.testID = testID; + serviceResult.fullURL = fullURL; + serviceResult.auth = authForTest; + serviceResult.method = method; + if (expectedCodes.size()>0){ + serviceResult.expectedCodes = expectedCodes; + } + if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; + if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; + + Node expectedLevel = testNode.selectSingleNode("response/expected"); + if (expectedLevel!=null){ + String level = expectedLevel.valueOf("@level"); + serviceResult.payloadStrictness = level; + } + //===================================================== + // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: + //===================================================== + boolean hasError = false; + String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); + if (Tools.notEmpty(vError)){ + serviceResult.error = vError; + serviceResult.failureReason = " : VALIDATION ERROR; "; + hasError = true; + } + if (hasError == false){ + hasError = ! serviceResult.gotExpectedResult(); + } + + boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); + String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); + String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; + + report.addTestResult(serviceResult); + + if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) + || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ + System.out.println("\r\n#---------------------#"); + } + System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); + if (dump.payloads || (doingAuto&&hasError) ) { + if (Tools.notBlank(serviceResult.requestPayload)){ + System.out.println("\r\n========== request payload ==============="); + System.out.println(serviceResult.requestPayload); + System.out.println("==========================================\r\n"); + } + } + if (dump.payloads || (doingAuto&&hasError)) { + if (Tools.notBlank(serviceResult.result)){ + System.out.println("\r\n========== response payload =============="); + System.out.println(serviceResult.result); + System.out.println("==========================================\r\n"); + } + } + } catch (Throwable t) { + String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; + System.out.println(msg); + System.out.println(Tools.getStackTrace(t)); + ServiceResult serviceResult = new ServiceResult(); + serviceResult.error = msg; + serviceResult.failureReason = " : SYSTEM ERROR; "; + results.add(serviceResult); + } + } + if (Tools.isTrue(autoDeletePOSTS)&¶m_autoDeletePOSTS){ + autoDelete(serviceResultsMap, "default"); + } + } + + //=== Now spit out the HTML report file === + File m = new File(controlFileName); + String localName = m.getName();//don't instantiate, just use File to extract file name without directory. + String reportName = localName+'-'+testGroupID+".html"; + + File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); + if (resultFile!=null) { + String toc = report.getTOC(reportName); + reportsList.add(toc); + } + //================================ + + return results; + } + + private static String timeString() { + java.util.Date date= new java.util.Date(); + java.sql.Timestamp ts = new java.sql.Timestamp(date.getTime()); + return ts.toString(); + } + + + //======================== MAIN =================================================================== + + private static Options createOptions() { + Options options = new Options(); + options.addOption("xmlReplayBaseDir", true, "default/basedir"); + return options; + } + + public static String usage(){ + String result = "org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplay {args}\r\n" + +" -xmlReplayBaseDir \r\n" + +" You may also override these with system args, e.g.: \r\n" + +" -DxmlReplayBaseDir=/path/to/dir \r\n" + +" These may also be passed in via the POM.\r\n" + +" You can also set these system args, e.g.: \r\n" + +" -DtestGroupID= \r\n" + +" -DtestID=" + +" -DautoDeletePOSTS= \r\n" + +" (note: -DautoDeletePOSTS won't force deletion if set to false in control file."; + return result; + } + + private static String opt(CommandLine line, String option){ + String result; + String fromProps = System.getProperty(option); + if (Tools.notEmpty(fromProps)){ + return fromProps; + } + if (line==null){ + return ""; + } + result = line.getOptionValue(option); + if (result == null){ + result = ""; + } + return result; + } + + public static void main(String[]args) throws Exception { + Options options = createOptions(); + //System.out.println("System CLASSPATH: "+prop.getProperty("java.class.path", null)); + CommandLineParser parser = new GnuParser(); + try { + // parse the command line arguments + CommandLine line = parser.parse(options, args); + + String xmlReplayBaseDir = opt(line, "xmlReplayBaseDir"); + String reportsDir = opt(line, "reportsDir"); + String testGroupID = opt(line, "testGroupID"); + String testID = opt(line, "testID"); + String autoDeletePOSTS = opt(line, "autoDeletePOSTS"); + String dumpResults = opt(line, "dumpResults"); + String controlFilename = opt(line, "controlFilename"); + String xmlReplayMaster = opt(line, "xmlReplayMaster"); + + if (Tools.isBlank(reportsDir)){ + reportsDir = xmlReplayBaseDir + XmlReplayTest.REPORTS_DIRNAME; + } + reportsDir = Tools.fixFilename(reportsDir); + xmlReplayBaseDir = Tools.fixFilename(xmlReplayBaseDir); + controlFilename = Tools.fixFilename(controlFilename); + + boolean bAutoDeletePOSTS = true; + if (Tools.notEmpty(autoDeletePOSTS)) { + bAutoDeletePOSTS = Tools.isTrue(autoDeletePOSTS); + } + boolean bDumpResults = false; + if (Tools.notEmpty(dumpResults)) { + bDumpResults = Tools.isTrue(autoDeletePOSTS); + } + if (Tools.isEmpty(xmlReplayBaseDir)){ + System.err.println("ERROR: xmlReplayBaseDir was not specified."); + return; + } + File f = new File(Tools.glue(xmlReplayBaseDir, "/", controlFilename)); + if (Tools.isEmpty(xmlReplayMaster) && !f.exists()){ + System.err.println("Control file not found: "+f.getCanonicalPath()); + return; + } + File fMaster = new File(Tools.glue(xmlReplayBaseDir, "/", xmlReplayMaster)); + if (Tools.notEmpty(xmlReplayMaster) && !fMaster.exists()){ + System.err.println("Master file not found: "+fMaster.getCanonicalPath()); + return; + } + + String xmlReplayBaseDirResolved = (new File(xmlReplayBaseDir)).getCanonicalPath(); + System.out.println("XmlReplay ::" + + "\r\n xmlReplayBaseDir: "+xmlReplayBaseDir + + "\r\n xmlReplayBaseDir(resolved): "+xmlReplayBaseDirResolved + + "\r\n controlFilename: "+controlFilename + + "\r\n xmlReplayMaster: "+xmlReplayMaster + + "\r\n testGroupID: "+testGroupID + + "\r\n testID: "+testID + + "\r\n autoDeletePOSTS: "+bAutoDeletePOSTS + + (Tools.notEmpty(xmlReplayMaster) + ? ("\r\n will use master file: "+fMaster.getCanonicalPath()) + : ("\r\n will use control file: "+f.getCanonicalPath()) ) + ); + + if (Tools.notEmpty(xmlReplayMaster)){ + if (Tools.notEmpty(controlFilename)){ + System.out.println("WARN: controlFilename: "+controlFilename+" will not be used because master was specified. Running master: "+xmlReplayMaster); + } + XmlReplay replay = new XmlReplay(xmlReplayBaseDirResolved, reportsDir); + replay.readOptionsFromMasterConfigFile(xmlReplayMaster); + replay.setAutoDeletePOSTS(bAutoDeletePOSTS); + Dump dumpFromMaster = replay.getDump(); + dumpFromMaster.payloads = Tools.isTrue(dumpResults); + replay.setDump(dumpFromMaster); + replay.runMaster(xmlReplayMaster, false); //false, because we already just read the options, and override a few. + } else { + Dump dump = getDumpConfig(); + dump.payloads = Tools.isTrue(dumpResults); + List reportsList = new ArrayList(); + runXmlReplayFile(xmlReplayBaseDirResolved, controlFilename, testGroupID, testID, createResultsMap(), bAutoDeletePOSTS, dump, "", null, reportsList, reportsDir); + System.out.println("DEPRECATED: reportsList is generated, but not dumped: "+reportsList.toString()); + } + } catch (ParseException exp) { + // oops, something went wrong + System.err.println("Cmd-line parsing failed. Reason: " + exp.getMessage()); + System.err.println(usage()); + } catch (Exception e) { + System.out.println("Error : " + e.getMessage()); + e.printStackTrace(); + } + } + +} diff --git a/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlReplayEval.java b/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlReplayEval.java index 1beebe553..fde549e78 100644 --- a/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlReplayEval.java +++ b/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlReplayEval.java @@ -1,152 +1,152 @@ -/** - * 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 (c) 2009 Regents of the University of California - * - * 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.IntegrationTests.xmlreplay; - -import org.apache.commons.jexl2.Expression; -import org.apache.commons.jexl2.JexlContext; -import org.apache.commons.jexl2.JexlEngine; -import org.apache.commons.jexl2.MapContext; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * User: laramie - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ -public class XmlReplayEval { - public Map serviceResultsMap; - public JexlEngine jexl; - public JexlContext jc; - - /** - * You may pass in a Jexl 2 expression, e.g. ${foo.bar} and it will be eval'd for you. - * We are looking at some URI like so: ${newOrgAuthority.CSID} - * The idea here is that the XML control file may bind to this namespace, and - * this module may find those values and any future extensions, specifically - * when someone says "I want to bind to ${CSID} and ${SUBRESOURCE.CSID} - * The code here is easy to extend, but the test cases build up, so you don't - * want to break all the config files by not being backward compatible. Binding - * to context variables like this makes it easy. - * EXAMPLE USAGE:
- * String uri = "/cspace-services/orgauthorities/${OrgAuth1.CSID}/items/${Org1.CSID}";
- * uri = eval(uri, serviceResultsMap, jexl, jc);
- * RESULT: "/cspace-services/orgauthorities/43a2739c-4f40-49c8-a6d5/items/" - */ - public static String eval(String inputJexlExpression, Map serviceResultsMap, Map vars, JexlEngine jexl, JexlContext jc) { - //System.out.println("\r\n---- REPLACE.init-uri: "+inputJexlExpression); - String result; - try { - jc.set("itemCSID", "${itemCSID}"); //noiseless passthru. - //System.out.println("eval :: serviceResultsMap "+serviceResultsMap.size()); - for (ServiceResult serviceResult : serviceResultsMap.values()) { - jc.set(serviceResult.testID, serviceResult); - //System.out.println("eval :: "+serviceResult.testID+"==>"+serviceResult.minimal()); - } - if (vars!=null){ - for (Map.Entry entry: vars.entrySet()) { - String value = entry.getValue(); - String key = entry.getKey(); - try { - value = parse(value, jexl, jc); - vars.put(key, value); //replace template value with actual value. - } catch (Exception e){ - value = "ERROR: "+e; - } - jc.set(key, value); - } - } - result = parse(inputJexlExpression, jexl, jc); - } catch (Throwable t) { - System.err.println("ERROR: " + t); - result = "ERROR"; - } - //System.out.println("---- REPLACE.uri: "+result+"\r\n"); - return result; - } - - private static String parse(String in, JexlEngine jexl, JexlContext jc) { - StringBuffer result = new StringBuffer(); - String s = in; - String var = ""; - int start, end, len; - len = in.length(); - start = 0; - int cursor = 0; - String front = ""; - while (start < len) { - end = in.indexOf("}", start); - start = in.indexOf("${", start); - if (start < 0) { - String tail = in.substring(cursor); - result.append(tail); - break; - } - if (end < 0) { - return "ERROR: unbalanced ${} braces"; - } - front = in.substring(cursor, start); - result.append(front); - cursor = end + 1; //bump past close brace - var = in.substring(start + 2, end); //+2 bump past open brace ${ and then "end" is indexed just before the close brace } - //s = s.substring(end+1); //bump past close brace - start = cursor; - - Expression expr = jexl.createExpression(var); - Object resultObj = expr.evaluate(jc); //REM - 5/9/2011 - Usually calls back to fields and methods in ServiceResult class to do the evaluation -e.g., the "got" method. - String resultStr; - if (null == resultObj){ - //debug: System.out.println("null found while evaluationg variable: '"+var+"' Jexl context: "+dumpContext(jc)); - resultStr = "${"+var+"}"; - } else { - resultStr = resultObj.toString(); - - } - result.append(resultStr); - } - return result.toString(); - } - - protected static String dumpContext(JexlContext jc){ - String result = ""; - if (jc instanceof MapContextWKeys){ - Set keys = ((MapContextWKeys)jc).getKeys(); - result = keys.toString(); - } else { - result = jc.toString(); - } - return result; - } - - public static class MapContextWKeys extends MapContext implements JexlContext { - private Map map = new HashMap(); - public Set getKeys(){ - return this.map.keySet(); - } - } - - -} +/** + * 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 (c) 2009 Regents of the University of California + * + * 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.IntegrationTests.xmlreplay; + +import org.apache.commons.jexl2.Expression; +import org.apache.commons.jexl2.JexlContext; +import org.apache.commons.jexl2.JexlEngine; +import org.apache.commons.jexl2.MapContext; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * User: laramie + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public class XmlReplayEval { + public Map serviceResultsMap; + public JexlEngine jexl; + public JexlContext jc; + + /** + * You may pass in a Jexl 2 expression, e.g. ${foo.bar} and it will be eval'd for you. + * We are looking at some URI like so: ${newOrgAuthority.CSID} + * The idea here is that the XML control file may bind to this namespace, and + * this module may find those values and any future extensions, specifically + * when someone says "I want to bind to ${CSID} and ${SUBRESOURCE.CSID} + * The code here is easy to extend, but the test cases build up, so you don't + * want to break all the config files by not being backward compatible. Binding + * to context variables like this makes it easy. + * EXAMPLE USAGE:
+ * String uri = "/cspace-services/orgauthorities/${OrgAuth1.CSID}/items/${Org1.CSID}";
+ * uri = eval(uri, serviceResultsMap, jexl, jc);
+ * RESULT: "/cspace-services/orgauthorities/43a2739c-4f40-49c8-a6d5/items/" + */ + public static String eval(String inputJexlExpression, Map serviceResultsMap, Map vars, JexlEngine jexl, JexlContext jc) { + //System.out.println("\r\n---- REPLACE.init-uri: "+inputJexlExpression); + String result; + try { + jc.set("itemCSID", "${itemCSID}"); //noiseless passthru. + //System.out.println("eval :: serviceResultsMap "+serviceResultsMap.size()); + for (ServiceResult serviceResult : serviceResultsMap.values()) { + jc.set(serviceResult.testID, serviceResult); + //System.out.println("eval :: "+serviceResult.testID+"==>"+serviceResult.minimal()); + } + if (vars!=null){ + for (Map.Entry entry: vars.entrySet()) { + String value = entry.getValue(); + String key = entry.getKey(); + try { + value = parse(value, jexl, jc); + vars.put(key, value); //replace template value with actual value. + } catch (Exception e){ + value = "ERROR: "+e; + } + jc.set(key, value); + } + } + result = parse(inputJexlExpression, jexl, jc); + } catch (Throwable t) { + System.err.println("ERROR: " + t); + result = "ERROR"; + } + //System.out.println("---- REPLACE.uri: "+result+"\r\n"); + return result; + } + + private static String parse(String in, JexlEngine jexl, JexlContext jc) { + StringBuffer result = new StringBuffer(); + String s = in; + String var = ""; + int start, end, len; + len = in.length(); + start = 0; + int cursor = 0; + String front = ""; + while (start < len) { + end = in.indexOf("}", start); + start = in.indexOf("${", start); + if (start < 0) { + String tail = in.substring(cursor); + result.append(tail); + break; + } + if (end < 0) { + return "ERROR: unbalanced ${} braces"; + } + front = in.substring(cursor, start); + result.append(front); + cursor = end + 1; //bump past close brace + var = in.substring(start + 2, end); //+2 bump past open brace ${ and then "end" is indexed just before the close brace } + //s = s.substring(end+1); //bump past close brace + start = cursor; + + Expression expr = jexl.createExpression(var); + Object resultObj = expr.evaluate(jc); //REM - 5/9/2011 - Usually calls back to fields and methods in ServiceResult class to do the evaluation -e.g., the "got" method. + String resultStr; + if (null == resultObj){ + //debug: System.out.println("null found while evaluationg variable: '"+var+"' Jexl context: "+dumpContext(jc)); + resultStr = "${"+var+"}"; + } else { + resultStr = resultObj.toString(); + + } + result.append(resultStr); + } + return result.toString(); + } + + protected static String dumpContext(JexlContext jc){ + String result = ""; + if (jc instanceof MapContextWKeys){ + Set keys = ((MapContextWKeys)jc).getKeys(); + result = keys.toString(); + } else { + result = jc.toString(); + } + return result; + } + + public static class MapContextWKeys extends MapContext implements JexlContext { + private Map map = new HashMap(); + public Set getKeys(){ + return this.map.keySet(); + } + } + + +} diff --git a/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlReplayTest.java b/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlReplayTest.java index 27d0fce30..6f7e462c3 100644 --- a/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlReplayTest.java +++ b/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlReplayTest.java @@ -1,200 +1,200 @@ -/** - * 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 (c) 2009 Regents of the University of California - * - * 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.IntegrationTests.xmlreplay; - -import org.collectionspace.services.common.api.Tools; -import org.testng.Assert; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** Subclass this test to programmatically control XmlReplay from a surefire test. See example in IntegrationTests :: XmlReplaySelfTest - * User: laramie - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ -public class XmlReplayTest { - - public static final String XMLREPLAY_REL_DIR_TO_MODULE = "/src/test/resources/test-data/xmlreplay"; - public static final String REPORTS_DIRNAME = "xml-replay-reports"; - public static final String XMLREPLAY_REL_DIR_REPORTS_TO_MODULE= "/target/"+REPORTS_DIRNAME; - - /** To use this method, you should have a test repository of xml files in the path - * defined by XMLREPLAY_REL_DIR_TO_MODULE, relative to your pom.xml file, but normally - * you would use the central repository of tests, which live in services/IntegrationTests, - * and which you can use by calling createXmlReplay() which calls createXmlReplayUsingIntegrationTestsModule() for you. - */ - public static XmlReplay createXmlReplayForModule() throws Exception { - String pwd = (new File(".")).getCanonicalPath(); - System.out.println("createXmlReplayForModule.pwd: "+pwd); - XmlReplay replay = new XmlReplay(pwd+XMLREPLAY_REL_DIR_TO_MODULE, - pwd+XMLREPLAY_REL_DIR_REPORTS_TO_MODULE); - System.out.println("XmlReplay: "+replay); - return replay; - } - - /** Use this method if your test xml files are stored in the central repository, - * which is "services/IntegrationTests" + XMLREPLAY_REL_DIR_TO_MODULE - */ - public static XmlReplay createXmlReplay() throws Exception { - return createXmlReplayUsingIntegrationTestsModule("../.."); - } - - /** - * @param relToServicesRoot is a Unix-like path from the calling module to the services root, - * so if if you are in services/dimension/client/ - * then relToServicesRoot is "../.." which is how most of the client tests are set up, or if you - * are setting up your test repository relative to the main service, e.g. you are in - * services/dimension/, then relToServicesRoot is ".." - */ - public static XmlReplay createXmlReplayUsingIntegrationTestsModule(String relToServicesRoot) throws Exception { - String thisDir = Tools.glue(relToServicesRoot, "/", "IntegrationTests"); - String pwd = (new File(thisDir)).getCanonicalPath(); - //System.out.println("createXmlReplayUsingIntegrationTestsModule.pwd: "+pwd); - XmlReplay replay = new XmlReplay(pwd+XMLREPLAY_REL_DIR_TO_MODULE, - pwd+XMLREPLAY_REL_DIR_REPORTS_TO_MODULE); - //System.out.println("XmlReplay: "+replay); - return replay; - } - - public static void logTest(ServiceResult sresult, String testname){ - ResultSummary summary = resultSummary(sresult, HTML); - org.testng.Reporter.log(summary.table); - Assert.assertEquals(summary.oks, summary.total, "Expected all "+summary.total+ " XmlReplay tests to pass. See Output from test '"+testname+"'. "+summary.errorTests); - } - - public static void logTest(List list, String testname){ - ResultSummary summary = resultSummary(list, HTML); - org.testng.Reporter.log(summary.table); - Assert.assertEquals(summary.oks, summary.total, "Expected all "+summary.total+ " XmlReplay tests to pass. See Output from test '"+testname+"'. "+summary.errorTests); - } - - public static void logTestForGroup(List> list, String testname){ - ResultSummary summary = resultSummaryForGroup(list, HTML); - org.testng.Reporter.log(summary.table); - ResultSummary textSummary = resultSummaryForGroup(list, TEXT); - System.out.println("SUMMARY: \r\n"+textSummary.table); - Assert.assertEquals(summary.oks, summary.total, "Expected all "+summary.total+ " XmlReplay tests to pass. See Output from test '"+testname+"'. "+summary.errorTests); - } - - - //============== HELPERS AND FORMATTING ===================================================== - public static class FORMAT { - private static final String TBLSTART = ""; - private static final String ROWSTART = "\r\n "; - private static final String ROWSTARTRED = "\r\n ** "; - private static final String SEP = " | "; - private static final String ROWEND = ""; - private static final String ROWENDRED = ""; - private static final String TBLEND = ""; - - } - public static final FORMAT TEXT = new FORMAT(); - public static class HTML_FORMAT extends FORMAT { - private static final String TBLSTART = ""; - private static final String ROWSTART = ""; - private static final String ROWENDRED = ""; - private static final String TBLEND = "
"; - private static final String ROWSTARTRED = "
"; - private static final String SEP = ""; - private static final String ROWEND = "
"; - } - public static final FORMAT HTML = new HTML_FORMAT(); - - public static class ResultSummary { - public long oks = 0; - public long total = 0; - public String table = ""; - public List groups = new ArrayList(); - public List errorTests = new ArrayList(); - } - - public static ResultSummary resultSummaryForGroup(List> list, FORMAT format){ - ResultSummary summary = new ResultSummary(); - summary.oks = 0; - summary.total = 0; - StringBuffer buff = new StringBuffer(); - buff.append(format.TBLSTART); - for (List serviceResults : list){ - String groupID = ""; - if (serviceResults.size()>0){ - groupID = serviceResults.get(0).testGroupID; - summary.groups.add(groupID); - } - buff.append(format.ROWSTART+"XmlReplay testGroup "+groupID+format.ROWEND); - for (ServiceResult serviceResult : serviceResults){ - summary.total++; - if (serviceResult.gotExpectedResult()){ - summary.oks++; - buff.append(format.ROWSTART+serviceResult.minimal()+format.ROWEND); - } else { - buff.append(format.ROWSTARTRED+serviceResult.minimal()+format.ROWENDRED); - summary.errorTests.add(serviceResult.testGroupID+':'+serviceResult.testID+':'+serviceResult.fullURL); - } - } - } - buff.append(format.TBLEND); - summary.table = buff.toString(); - return summary; - } - - public static ResultSummary resultSummary(List serviceResults, FORMAT format){ - ResultSummary summary = new ResultSummary(); - summary.oks = 0; - summary.total = 0; - StringBuffer buff = new StringBuffer(); - buff.append(format.TBLSTART); - for (ServiceResult serviceResult : serviceResults){ - summary.total++; - if (serviceResult.gotExpectedResult()){ - summary.oks++; - buff.append(format.ROWSTART+serviceResult.minimal()+format.ROWEND); - } else { - buff.append(format.ROWSTARTRED+serviceResult.minimal()+format.ROWENDRED); - } - } - buff.append(format.TBLEND); - summary.table = buff.toString(); - return summary; - } - - public static ResultSummary resultSummary(ServiceResult serviceResult, FORMAT format){ - ResultSummary summary = new ResultSummary(); - summary.oks = 0; - summary.total = 1; - StringBuffer buff = new StringBuffer(); - buff.append(format.TBLSTART); - if (serviceResult.gotExpectedResult()){ - summary.oks = 1; - buff.append(format.ROWSTART+serviceResult.minimal()+format.ROWEND); - } else { - buff.append(format.ROWSTARTRED+serviceResult.minimal()+format.ROWENDRED); - } - buff.append(format.TBLEND); - summary.table = buff.toString(); - return summary; - } - -} +/** + * 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 (c) 2009 Regents of the University of California + * + * 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.IntegrationTests.xmlreplay; + +import org.collectionspace.services.common.api.Tools; +import org.testng.Assert; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +/** Subclass this test to programmatically control XmlReplay from a surefire test. See example in IntegrationTests :: XmlReplaySelfTest + * User: laramie + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public class XmlReplayTest { + + public static final String XMLREPLAY_REL_DIR_TO_MODULE = "/src/test/resources/test-data/xmlreplay"; + public static final String REPORTS_DIRNAME = "xml-replay-reports"; + public static final String XMLREPLAY_REL_DIR_REPORTS_TO_MODULE= "/target/"+REPORTS_DIRNAME; + + /** To use this method, you should have a test repository of xml files in the path + * defined by XMLREPLAY_REL_DIR_TO_MODULE, relative to your pom.xml file, but normally + * you would use the central repository of tests, which live in services/IntegrationTests, + * and which you can use by calling createXmlReplay() which calls createXmlReplayUsingIntegrationTestsModule() for you. + */ + public static XmlReplay createXmlReplayForModule() throws Exception { + String pwd = (new File(".")).getCanonicalPath(); + System.out.println("createXmlReplayForModule.pwd: "+pwd); + XmlReplay replay = new XmlReplay(pwd+XMLREPLAY_REL_DIR_TO_MODULE, + pwd+XMLREPLAY_REL_DIR_REPORTS_TO_MODULE); + System.out.println("XmlReplay: "+replay); + return replay; + } + + /** Use this method if your test xml files are stored in the central repository, + * which is "services/IntegrationTests" + XMLREPLAY_REL_DIR_TO_MODULE + */ + public static XmlReplay createXmlReplay() throws Exception { + return createXmlReplayUsingIntegrationTestsModule("../.."); + } + + /** + * @param relToServicesRoot is a Unix-like path from the calling module to the services root, + * so if if you are in services/dimension/client/ + * then relToServicesRoot is "../.." which is how most of the client tests are set up, or if you + * are setting up your test repository relative to the main service, e.g. you are in + * services/dimension/, then relToServicesRoot is ".." + */ + public static XmlReplay createXmlReplayUsingIntegrationTestsModule(String relToServicesRoot) throws Exception { + String thisDir = Tools.glue(relToServicesRoot, "/", "IntegrationTests"); + String pwd = (new File(thisDir)).getCanonicalPath(); + //System.out.println("createXmlReplayUsingIntegrationTestsModule.pwd: "+pwd); + XmlReplay replay = new XmlReplay(pwd+XMLREPLAY_REL_DIR_TO_MODULE, + pwd+XMLREPLAY_REL_DIR_REPORTS_TO_MODULE); + //System.out.println("XmlReplay: "+replay); + return replay; + } + + public static void logTest(ServiceResult sresult, String testname){ + ResultSummary summary = resultSummary(sresult, HTML); + org.testng.Reporter.log(summary.table); + Assert.assertEquals(summary.oks, summary.total, "Expected all "+summary.total+ " XmlReplay tests to pass. See Output from test '"+testname+"'. "+summary.errorTests); + } + + public static void logTest(List list, String testname){ + ResultSummary summary = resultSummary(list, HTML); + org.testng.Reporter.log(summary.table); + Assert.assertEquals(summary.oks, summary.total, "Expected all "+summary.total+ " XmlReplay tests to pass. See Output from test '"+testname+"'. "+summary.errorTests); + } + + public static void logTestForGroup(List> list, String testname){ + ResultSummary summary = resultSummaryForGroup(list, HTML); + org.testng.Reporter.log(summary.table); + ResultSummary textSummary = resultSummaryForGroup(list, TEXT); + System.out.println("SUMMARY: \r\n"+textSummary.table); + Assert.assertEquals(summary.oks, summary.total, "Expected all "+summary.total+ " XmlReplay tests to pass. See Output from test '"+testname+"'. "+summary.errorTests); + } + + + //============== HELPERS AND FORMATTING ===================================================== + public static class FORMAT { + private static final String TBLSTART = ""; + private static final String ROWSTART = "\r\n "; + private static final String ROWSTARTRED = "\r\n ** "; + private static final String SEP = " | "; + private static final String ROWEND = ""; + private static final String ROWENDRED = ""; + private static final String TBLEND = ""; + + } + public static final FORMAT TEXT = new FORMAT(); + public static class HTML_FORMAT extends FORMAT { + private static final String TBLSTART = ""; + private static final String ROWSTART = ""; + private static final String ROWENDRED = ""; + private static final String TBLEND = "
"; + private static final String ROWSTARTRED = "
"; + private static final String SEP = ""; + private static final String ROWEND = "
"; + } + public static final FORMAT HTML = new HTML_FORMAT(); + + public static class ResultSummary { + public long oks = 0; + public long total = 0; + public String table = ""; + public List groups = new ArrayList(); + public List errorTests = new ArrayList(); + } + + public static ResultSummary resultSummaryForGroup(List> list, FORMAT format){ + ResultSummary summary = new ResultSummary(); + summary.oks = 0; + summary.total = 0; + StringBuffer buff = new StringBuffer(); + buff.append(format.TBLSTART); + for (List serviceResults : list){ + String groupID = ""; + if (serviceResults.size()>0){ + groupID = serviceResults.get(0).testGroupID; + summary.groups.add(groupID); + } + buff.append(format.ROWSTART+"XmlReplay testGroup "+groupID+format.ROWEND); + for (ServiceResult serviceResult : serviceResults){ + summary.total++; + if (serviceResult.gotExpectedResult()){ + summary.oks++; + buff.append(format.ROWSTART+serviceResult.minimal()+format.ROWEND); + } else { + buff.append(format.ROWSTARTRED+serviceResult.minimal()+format.ROWENDRED); + summary.errorTests.add(serviceResult.testGroupID+':'+serviceResult.testID+':'+serviceResult.fullURL); + } + } + } + buff.append(format.TBLEND); + summary.table = buff.toString(); + return summary; + } + + public static ResultSummary resultSummary(List serviceResults, FORMAT format){ + ResultSummary summary = new ResultSummary(); + summary.oks = 0; + summary.total = 0; + StringBuffer buff = new StringBuffer(); + buff.append(format.TBLSTART); + for (ServiceResult serviceResult : serviceResults){ + summary.total++; + if (serviceResult.gotExpectedResult()){ + summary.oks++; + buff.append(format.ROWSTART+serviceResult.minimal()+format.ROWEND); + } else { + buff.append(format.ROWSTARTRED+serviceResult.minimal()+format.ROWENDRED); + } + } + buff.append(format.TBLEND); + summary.table = buff.toString(); + return summary; + } + + public static ResultSummary resultSummary(ServiceResult serviceResult, FORMAT format){ + ResultSummary summary = new ResultSummary(); + summary.oks = 0; + summary.total = 1; + StringBuffer buff = new StringBuffer(); + buff.append(format.TBLSTART); + if (serviceResult.gotExpectedResult()){ + summary.oks = 1; + buff.append(format.ROWSTART+serviceResult.minimal()+format.ROWEND); + } else { + buff.append(format.ROWSTARTRED+serviceResult.minimal()+format.ROWENDRED); + } + buff.append(format.TBLEND); + summary.table = buff.toString(); + return summary; + } + +} diff --git a/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlReplayTransport.java b/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlReplayTransport.java index 58ec12861..3d52e1793 100644 --- a/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlReplayTransport.java +++ b/services/IntegrationTests/src/main/java/org/collectionspace/services/IntegrationTests/xmlreplay/XmlReplayTransport.java @@ -1,334 +1,334 @@ -/** - * 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 (c) 2009 Regents of the University of California - * - * 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.IntegrationTests.xmlreplay; - -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.methods.DeleteMethod; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.io.FileUtils; - -import java.io.BufferedReader; -import java.io.File; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.collectionspace.services.common.api.Tools; - -/** - * @author Laramie Crocker - */ -public class XmlReplayTransport { - - private static String BOUNDARY = "34d97c83-0d61-4958-80ab-6bf8d362290f"; - private static String DD = "--"; - private static String CRLF = "\r\n"; - - public static ServiceResult doGET(String urlString, String authForTest, String fromTestID) throws Exception { - ServiceResult pr = new ServiceResult(); - pr.fromTestID = fromTestID; - pr.method = "GET"; - //HACK for speed testing. - //pr.CSID = "2"; - //pr.overrideGotExpectedResult(); - //if (true) return pr; - //END-HACK - HttpClient client = new HttpClient(); - GetMethod getMethod = new GetMethod(urlString); - getMethod.addRequestHeader("Accept", "multipart/mixed"); - getMethod.addRequestHeader("Accept", "application/xml"); - getMethod.setRequestHeader("Authorization", "Basic " + authForTest); //"dGVzdDp0ZXN0"); - getMethod.setRequestHeader("X-XmlReplay-fromTestID", fromTestID); - try { - int statusCode1 = client.executeMethod(getMethod); - pr.responseCode = statusCode1; - pr.result = getMethod.getResponseBodyAsString(); - pr.responseMessage = getMethod.getStatusText(); - Header[] headers = getMethod.getResponseHeaders(); - pr.responseHeaders = Arrays.copyOf(headers, headers.length); - Header hdr = getMethod.getResponseHeader("CONTENT-TYPE"); - if (hdr!=null){ - String hdrStr = hdr.toExternalForm(); - pr.boundary = PayloadLogger.parseBoundary(hdrStr); - } - pr.contentLength = getMethod.getResponseContentLength(); - getMethod.releaseConnection(); - } catch (Throwable t){ - //System.err.println("ERROR getting content from response: "+t); - pr.error = t.toString(); - } - return pr; - } - - public static ServiceResult doDELETE(String urlString, String authForTest, String testID, String fromTestID) throws Exception { - ServiceResult pr = new ServiceResult(); - pr.failureReason = ""; - pr.method = "DELETE"; - pr.fullURL = urlString; - pr.fromTestID = fromTestID; - if (Tools.isEmpty(urlString)){ - pr.error = "url was empty. Check the result for fromTestID: "+fromTestID+". currentTest: "+testID; - return pr; - } - HttpClient client = new HttpClient(); - DeleteMethod deleteMethod = new DeleteMethod(urlString); - deleteMethod.setRequestHeader("Accept", "multipart/mixed"); - deleteMethod.addRequestHeader("Accept", "application/xml"); - deleteMethod.setRequestHeader("Authorization", "Basic " + authForTest); - deleteMethod.setRequestHeader("X-XmlReplay-fromTestID", fromTestID); - int statusCode1 = 0; - String res = ""; - try { - statusCode1 = client.executeMethod(deleteMethod); - pr.responseCode = statusCode1; - //System.out.println("statusCode: "+statusCode1+" statusLine ==>" + deleteMethod.getStatusLine()); - pr.responseMessage = deleteMethod.getStatusText(); - res = deleteMethod.getResponseBodyAsString(); - deleteMethod.releaseConnection(); - } catch (Throwable t){ - pr.error = t.toString(); - } - pr.result = res; - pr.responseCode = statusCode1; - return pr; - } - - public static ServiceResult doLIST(String urlString, String listQueryParams, String authForTest, String fromTestID) throws Exception { - //String u = Tools.glue(urlString, "/", "items/"); - if (Tools.notEmpty(listQueryParams)){ - urlString = Tools.glue(urlString, "?", listQueryParams); - } - return doGET(urlString, authForTest, fromTestID); - } - - public static final String MULTIPART_MIXED = "multipart/mixed"; - public static final String APPLICATION_XML = "application/xml"; - - /** Use this overload for multipart messages. */ - /** - public static ServiceResult doPOST_PUTFromXML_Multipart(List filesList, - List partsList, - List> varsList, - String protoHostPort, - String uri, - String method, - XmlReplayEval evalStruct, - String authForTest, - String fromTestID) - throws Exception { - if ( filesList==null||filesList.size()==0 - ||partsList==null||partsList.size()==0 - ||(partsList.size() != filesList.size())){ - throw new Exception("filesList and partsList must not be empty and must have the same number of items each."); - } - String content = DD + BOUNDARY; - Map contentRaw = new HashMap(); - for (int i=0; i vars, - String protoHostPort, - String uri, - String method, - String contentType, - XmlReplayEval evalStruct, - String authForTest, - String fromTestID) - throws Exception { - byte[] b = FileUtils.readFileToByteArray(new File(fileName)); - String xmlString = new String(b); - String contentRaw = xmlString; - xmlString = evalStruct.eval(xmlString, evalStruct.serviceResultsMap, vars, evalStruct.jexl, evalStruct.jc); - String urlString = protoHostPort+uri; - return doPOST_PUT(urlString, xmlString, contentRaw, BOUNDARY, method, contentType, authForTest, fromTestID); //method is POST or PUT. - } - - //HACK for speed testing in doPOST_PUT. - // Result: XmlReplay takes 9ms to process one test - // right up to the point of actually firing an HTTP request. - // or ~ 120 records per second. - //result.CSID = "2"; - //result.overrideGotExpectedResult(); - //if (true) return result; - //END-HACK - - public static ServiceResult doPOST_PUT(String urlString, - String content, - String contentRaw, - String boundary, - String method, - String contentType, - String authForTest, - String fromTestID) throws Exception { - ServiceResult result = new ServiceResult(); - result.method = method; - String deleteURL = ""; - String location = ""; - try { - URL url = new URL(urlString); - HttpURLConnection conn; - conn = (HttpURLConnection) url.openConnection(); - - if (MULTIPART_MIXED.equalsIgnoreCase(contentType)){ - conn.setRequestProperty("Accept", "multipart/mixed"); - conn.setRequestProperty("content-type", "multipart/mixed; boundary=" + boundary); - } else { - conn.setRequestProperty("Accept", "application/xml"); - conn.setRequestProperty("content-type", contentType); - } - conn.setRequestProperty("Authorization", "Basic " + authForTest); //TODO: remove test user : hard-coded as "dGVzdDp0ZXN0" - conn.setRequestProperty("Connection", "close"); - conn.setRequestProperty("X-XmlReplay-fromTestID", fromTestID); - conn.setDoOutput(true); - conn.setDoInput(true); - conn.setRequestMethod(method); // "POST" or "PUT" - OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); - wr.write(content); - wr.flush(); - - try { - result.requestPayload = content; - result.requestPayloadsRaw = contentRaw; - result.responseCode = conn.getResponseCode(); - //System.out.println("responseCode: "+result.responseCode); - if (400 <= result.responseCode && result.responseCode <= 499){ - return result; - } - readStream(conn, result); - } catch (Throwable t){ - //System.err.println("ERROR getting content from response: "+t); - result.error = t.toString(); - } - wr.close(); - - Map> headers = conn.getHeaderFields(); - List locations = headers.get("Location"); - if (locations != null){ - String locationZero = locations.get(0); - if (locationZero != null){ - String[] segments = locationZero.split("/"); - location = segments[segments.length - 1]; - deleteURL = Tools.glue(urlString, "/", location); - } - } - result.location = location; - result.deleteURL = deleteURL; - result.CSID = location; - } catch (Throwable t2){ - result.error = "ERROR in XmlReplayTransport: "+t2; - } - return result; - } - - public static ServiceResult doPOST_PUT_PostMethod(String urlString, String content, Map contentRaw, - String boundary, String method, String contentType, - String authForTest, String fromTestID) throws Exception { - ServiceResult result = new ServiceResult(); - result.method = method; - String deleteURL = ""; - String location = ""; - try { - HttpClient client = new HttpClient(); - PostMethod postMethod = new PostMethod(urlString); - postMethod.setRequestHeader("Accept", "multipart/mixed"); - postMethod.addRequestHeader("Accept", "application/xml"); - postMethod.setRequestHeader("Authorization", "Basic " + authForTest); - postMethod.setRequestHeader("X-XmlReplay-fromTestID", fromTestID); - //this method takes an array of params. Not sure what they expect us to do with a raw post: - // postMethod.setRequestBody(); - int statusCode1 = 0; - String res = ""; - try { - statusCode1 = client.executeMethod(postMethod); - result.responseCode = statusCode1; - //System.out.println("statusCode: "+statusCode1+" statusLine ==>" + postMethod.getStatusLine()); - result.responseMessage = postMethod.getStatusText(); - res = postMethod.getResponseBodyAsString(); - Header[] headers = postMethod.getResponseHeaders("Location"); - if (headers.length>0) { - System.out.println("headers[0]: "+headers[0]); - String locationZero = headers[0].getValue(); - if (locationZero != null){ - String[] segments = locationZero.split("/"); - location = segments[segments.length - 1]; - deleteURL = Tools.glue(urlString, "/", location); - } - } - postMethod.releaseConnection(); - } catch (Throwable t){ - result.error = t.toString(); - } - result.result = res; - result.location = location; - result.deleteURL = deleteURL; - result.CSID = location; - } catch (Throwable t2){ - result.error = "ERROR in XmlReplayTransport: "+t2; - } - return result; - } - - private static void readStream(HttpURLConnection conn, ServiceResult result) throws Throwable { - BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); - try { - String line; - StringBuffer sb = new StringBuffer(); - while ((line = rd.readLine()) != null) { - sb.append(line).append("\r\n"); - } - String msg = sb.toString(); - result.result = msg; - result.boundary = PayloadLogger.parseBoundary(conn.getHeaderField("CONTENT-TYPE")); - } finally { - rd.close(); - } - } - -} +/** + * 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 (c) 2009 Regents of the University of California + * + * 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.IntegrationTests.xmlreplay; + +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.methods.DeleteMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.io.FileUtils; + +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.collectionspace.services.common.api.Tools; + +/** + * @author Laramie Crocker + */ +public class XmlReplayTransport { + + private static String BOUNDARY = "34d97c83-0d61-4958-80ab-6bf8d362290f"; + private static String DD = "--"; + private static String CRLF = "\r\n"; + + public static ServiceResult doGET(String urlString, String authForTest, String fromTestID) throws Exception { + ServiceResult pr = new ServiceResult(); + pr.fromTestID = fromTestID; + pr.method = "GET"; + //HACK for speed testing. + //pr.CSID = "2"; + //pr.overrideGotExpectedResult(); + //if (true) return pr; + //END-HACK + HttpClient client = new HttpClient(); + GetMethod getMethod = new GetMethod(urlString); + getMethod.addRequestHeader("Accept", "multipart/mixed"); + getMethod.addRequestHeader("Accept", "application/xml"); + getMethod.setRequestHeader("Authorization", "Basic " + authForTest); //"dGVzdDp0ZXN0"); + getMethod.setRequestHeader("X-XmlReplay-fromTestID", fromTestID); + try { + int statusCode1 = client.executeMethod(getMethod); + pr.responseCode = statusCode1; + pr.result = getMethod.getResponseBodyAsString(); + pr.responseMessage = getMethod.getStatusText(); + Header[] headers = getMethod.getResponseHeaders(); + pr.responseHeaders = Arrays.copyOf(headers, headers.length); + Header hdr = getMethod.getResponseHeader("CONTENT-TYPE"); + if (hdr!=null){ + String hdrStr = hdr.toExternalForm(); + pr.boundary = PayloadLogger.parseBoundary(hdrStr); + } + pr.contentLength = getMethod.getResponseContentLength(); + getMethod.releaseConnection(); + } catch (Throwable t){ + //System.err.println("ERROR getting content from response: "+t); + pr.error = t.toString(); + } + return pr; + } + + public static ServiceResult doDELETE(String urlString, String authForTest, String testID, String fromTestID) throws Exception { + ServiceResult pr = new ServiceResult(); + pr.failureReason = ""; + pr.method = "DELETE"; + pr.fullURL = urlString; + pr.fromTestID = fromTestID; + if (Tools.isEmpty(urlString)){ + pr.error = "url was empty. Check the result for fromTestID: "+fromTestID+". currentTest: "+testID; + return pr; + } + HttpClient client = new HttpClient(); + DeleteMethod deleteMethod = new DeleteMethod(urlString); + deleteMethod.setRequestHeader("Accept", "multipart/mixed"); + deleteMethod.addRequestHeader("Accept", "application/xml"); + deleteMethod.setRequestHeader("Authorization", "Basic " + authForTest); + deleteMethod.setRequestHeader("X-XmlReplay-fromTestID", fromTestID); + int statusCode1 = 0; + String res = ""; + try { + statusCode1 = client.executeMethod(deleteMethod); + pr.responseCode = statusCode1; + //System.out.println("statusCode: "+statusCode1+" statusLine ==>" + deleteMethod.getStatusLine()); + pr.responseMessage = deleteMethod.getStatusText(); + res = deleteMethod.getResponseBodyAsString(); + deleteMethod.releaseConnection(); + } catch (Throwable t){ + pr.error = t.toString(); + } + pr.result = res; + pr.responseCode = statusCode1; + return pr; + } + + public static ServiceResult doLIST(String urlString, String listQueryParams, String authForTest, String fromTestID) throws Exception { + //String u = Tools.glue(urlString, "/", "items/"); + if (Tools.notEmpty(listQueryParams)){ + urlString = Tools.glue(urlString, "?", listQueryParams); + } + return doGET(urlString, authForTest, fromTestID); + } + + public static final String MULTIPART_MIXED = "multipart/mixed"; + public static final String APPLICATION_XML = "application/xml"; + + /** Use this overload for multipart messages. */ + /** + public static ServiceResult doPOST_PUTFromXML_Multipart(List filesList, + List partsList, + List> varsList, + String protoHostPort, + String uri, + String method, + XmlReplayEval evalStruct, + String authForTest, + String fromTestID) + throws Exception { + if ( filesList==null||filesList.size()==0 + ||partsList==null||partsList.size()==0 + ||(partsList.size() != filesList.size())){ + throw new Exception("filesList and partsList must not be empty and must have the same number of items each."); + } + String content = DD + BOUNDARY; + Map contentRaw = new HashMap(); + for (int i=0; i vars, + String protoHostPort, + String uri, + String method, + String contentType, + XmlReplayEval evalStruct, + String authForTest, + String fromTestID) + throws Exception { + byte[] b = FileUtils.readFileToByteArray(new File(fileName)); + String xmlString = new String(b); + String contentRaw = xmlString; + xmlString = evalStruct.eval(xmlString, evalStruct.serviceResultsMap, vars, evalStruct.jexl, evalStruct.jc); + String urlString = protoHostPort+uri; + return doPOST_PUT(urlString, xmlString, contentRaw, BOUNDARY, method, contentType, authForTest, fromTestID); //method is POST or PUT. + } + + //HACK for speed testing in doPOST_PUT. + // Result: XmlReplay takes 9ms to process one test + // right up to the point of actually firing an HTTP request. + // or ~ 120 records per second. + //result.CSID = "2"; + //result.overrideGotExpectedResult(); + //if (true) return result; + //END-HACK + + public static ServiceResult doPOST_PUT(String urlString, + String content, + String contentRaw, + String boundary, + String method, + String contentType, + String authForTest, + String fromTestID) throws Exception { + ServiceResult result = new ServiceResult(); + result.method = method; + String deleteURL = ""; + String location = ""; + try { + URL url = new URL(urlString); + HttpURLConnection conn; + conn = (HttpURLConnection) url.openConnection(); + + if (MULTIPART_MIXED.equalsIgnoreCase(contentType)){ + conn.setRequestProperty("Accept", "multipart/mixed"); + conn.setRequestProperty("content-type", "multipart/mixed; boundary=" + boundary); + } else { + conn.setRequestProperty("Accept", "application/xml"); + conn.setRequestProperty("content-type", contentType); + } + conn.setRequestProperty("Authorization", "Basic " + authForTest); //TODO: remove test user : hard-coded as "dGVzdDp0ZXN0" + conn.setRequestProperty("Connection", "close"); + conn.setRequestProperty("X-XmlReplay-fromTestID", fromTestID); + conn.setDoOutput(true); + conn.setDoInput(true); + conn.setRequestMethod(method); // "POST" or "PUT" + OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); + wr.write(content); + wr.flush(); + + try { + result.requestPayload = content; + result.requestPayloadsRaw = contentRaw; + result.responseCode = conn.getResponseCode(); + //System.out.println("responseCode: "+result.responseCode); + if (400 <= result.responseCode && result.responseCode <= 499){ + return result; + } + readStream(conn, result); + } catch (Throwable t){ + //System.err.println("ERROR getting content from response: "+t); + result.error = t.toString(); + } + wr.close(); + + Map> headers = conn.getHeaderFields(); + List locations = headers.get("Location"); + if (locations != null){ + String locationZero = locations.get(0); + if (locationZero != null){ + String[] segments = locationZero.split("/"); + location = segments[segments.length - 1]; + deleteURL = Tools.glue(urlString, "/", location); + } + } + result.location = location; + result.deleteURL = deleteURL; + result.CSID = location; + } catch (Throwable t2){ + result.error = "ERROR in XmlReplayTransport: "+t2; + } + return result; + } + + public static ServiceResult doPOST_PUT_PostMethod(String urlString, String content, Map contentRaw, + String boundary, String method, String contentType, + String authForTest, String fromTestID) throws Exception { + ServiceResult result = new ServiceResult(); + result.method = method; + String deleteURL = ""; + String location = ""; + try { + HttpClient client = new HttpClient(); + PostMethod postMethod = new PostMethod(urlString); + postMethod.setRequestHeader("Accept", "multipart/mixed"); + postMethod.addRequestHeader("Accept", "application/xml"); + postMethod.setRequestHeader("Authorization", "Basic " + authForTest); + postMethod.setRequestHeader("X-XmlReplay-fromTestID", fromTestID); + //this method takes an array of params. Not sure what they expect us to do with a raw post: + // postMethod.setRequestBody(); + int statusCode1 = 0; + String res = ""; + try { + statusCode1 = client.executeMethod(postMethod); + result.responseCode = statusCode1; + //System.out.println("statusCode: "+statusCode1+" statusLine ==>" + postMethod.getStatusLine()); + result.responseMessage = postMethod.getStatusText(); + res = postMethod.getResponseBodyAsString(); + Header[] headers = postMethod.getResponseHeaders("Location"); + if (headers.length>0) { + System.out.println("headers[0]: "+headers[0]); + String locationZero = headers[0].getValue(); + if (locationZero != null){ + String[] segments = locationZero.split("/"); + location = segments[segments.length - 1]; + deleteURL = Tools.glue(urlString, "/", location); + } + } + postMethod.releaseConnection(); + } catch (Throwable t){ + result.error = t.toString(); + } + result.result = res; + result.location = location; + result.deleteURL = deleteURL; + result.CSID = location; + } catch (Throwable t2){ + result.error = "ERROR in XmlReplayTransport: "+t2; + } + return result; + } + + private static void readStream(HttpURLConnection conn, ServiceResult result) throws Throwable { + BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); + try { + String line; + StringBuffer sb = new StringBuffer(); + while ((line = rd.readLine()) != null) { + sb.append(line).append("\r\n"); + } + String msg = sb.toString(); + result.result = msg; + result.boundary = PayloadLogger.parseBoundary(conn.getHeaderField("CONTENT-TYPE")); + } finally { + rd.close(); + } + } + +} diff --git a/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/CollectionSpaceIntegrationTest.java b/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/CollectionSpaceIntegrationTest.java index 03e9ef279..209cccf9f 100644 --- a/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/CollectionSpaceIntegrationTest.java +++ b/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/CollectionSpaceIntegrationTest.java @@ -1,227 +1,227 @@ -/** - * CollectionSpaceIntegrationTest.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.IntegrationTests.test; - -import java.util.ArrayList; -import java.util.List; - -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; - -import org.collectionspace.services.client.PayloadInputPart; -import org.collectionspace.services.client.PoxPayloadIn; -import org.collectionspace.services.collectionobject.CollectionobjectsCommon; -import org.collectionspace.services.collectionobject.TitleGroup; -import org.collectionspace.services.collectionobject.TitleGroupList; -import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils; -import org.collectionspace.services.intake.IntakesCommon; -import org.collectionspace.services.relation.RelationsCommon; -import org.jboss.resteasy.client.ClientResponse; - -/** - * The Class CollectionSpaceIntegrationTest. - */ -public abstract class CollectionSpaceIntegrationTest { - - /* - * Package scoped methods. - */ - - /** - * Fill collection object. - * - * @param co the co - * @param identifier the identifier - */ - void fillCollectionObject(CollectionobjectsCommon co, String identifier) { - fillCollectionObject(co, "objectNumber-" + identifier, "title-" - + identifier); - } - - /** - * Fill collection object. - * - * @param co the co - * @param objectNumber the object number - * @param title the object title - */ - void fillCollectionObject(CollectionobjectsCommon co, String objectNumber, - String title) { - co.setObjectNumber(objectNumber); - TitleGroupList titleGroupList = new TitleGroupList(); - List titleGroups = titleGroupList.getTitleGroup(); - TitleGroup titleGroup = new TitleGroup(); - titleGroup.setTitle(title); - titleGroups.add(titleGroup); - co.setTitleGroupList(titleGroupList); - } - - /** - * Fill intake. - * - * @param theIntake the the intake - * @param identifier the identifier - */ - void fillIntake(IntakesCommon theIntake, String identifier) { - String CURRENT_DATE_UTC = GregorianCalendarDateTimeUtils.currentDateUTC(); - fillIntake(theIntake, "entryNumber-" + identifier, CURRENT_DATE_UTC); - } - - /** - * Fill intake. - * - * @param theIntake the the intake - * @param entryNumber the entry number - * @param entryDate the entry date - */ - void fillIntake(IntakesCommon theIntake, String entryNumber, String entryDate) { - theIntake.setEntryNumber(entryNumber); - theIntake.setEntryDate(entryDate); - } - - /** - * Fill relation. - * - * @param relation the relation - * @param subjectCsid the document id1 - * @param subjectDocumentType the document type1 - * @param objectCsid the document id2 - * @param objectDocumentType the document type2 - * @param rt the rt - */ - void fillRelation(RelationsCommon relation, - String subjectCsid, String subjectDocumentType, - String objectCsid, String objectDocumentType, - String rt) - { - relation.setSubjectCsid(subjectCsid); - relation.setSubjectDocumentType(subjectDocumentType); - relation.setObjectCsid(objectCsid); - relation.setObjectDocumentType(objectDocumentType); - - relation.setRelationshipType(rt); - } - - /** - * Creates the identifier. - * - * @return the string - */ - String createIdentifier() { - long identifier = System.currentTimeMillis(); - return Long.toString(identifier); - } - - /** - * Extract id. - * - * @param res the res - * - * @return the string - */ - String extractId(ClientResponse res) { - String result = null; - - MultivaluedMap mvm = res.getMetadata(); - String uri = (String) ((ArrayList) mvm.get("Location")).get(0); - verbose("extractId:uri=" + uri); - String[] segments = uri.split("/"); - result = segments[segments.length - 1]; - verbose("id=" + result); - - return result; - } - - /** - * Extract part. - * - * @param input - * the input - * @param label - * the label - * @param clazz - * the clazz - * - * @return the object - * - * @throws Exception - * the exception - */ - static Object extractPart(PoxPayloadIn input, String label, Class clazz) { - Object obj = null; - - PayloadInputPart payloadInputPart = input.getPart(label); - if (payloadInputPart != null) { - obj = payloadInputPart.getBody(); - } - - return obj; - } - - /** - * Verbose. - * - * @param msg the msg - */ - void verbose(String msg) { - System.out.println(msg); - } - - /** - * Verbose. - * - * @param msg the msg - * @param o the o - * @param clazz the clazz - */ - void verbose(String msg, Object o, Class clazz) { - try { - verbose(msg); - JAXBContext jc = JAXBContext.newInstance(clazz); - Marshaller m = jc.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - m.marshal(o, System.out); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Verbose map. - * - * @param map the map - */ - void verboseMap(MultivaluedMap map) { - for (Object entry : map.entrySet()) { - MultivaluedMap.Entry mentry = (MultivaluedMap.Entry) entry; - verbose(" name=" + mentry.getKey() + " value=" + mentry.getValue()); - } - } - -} +/** + * CollectionSpaceIntegrationTest.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.IntegrationTests.test; + +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; + +import org.collectionspace.services.client.PayloadInputPart; +import org.collectionspace.services.client.PoxPayloadIn; +import org.collectionspace.services.collectionobject.CollectionobjectsCommon; +import org.collectionspace.services.collectionobject.TitleGroup; +import org.collectionspace.services.collectionobject.TitleGroupList; +import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils; +import org.collectionspace.services.intake.IntakesCommon; +import org.collectionspace.services.relation.RelationsCommon; +import org.jboss.resteasy.client.ClientResponse; + +/** + * The Class CollectionSpaceIntegrationTest. + */ +public abstract class CollectionSpaceIntegrationTest { + + /* + * Package scoped methods. + */ + + /** + * Fill collection object. + * + * @param co the co + * @param identifier the identifier + */ + void fillCollectionObject(CollectionobjectsCommon co, String identifier) { + fillCollectionObject(co, "objectNumber-" + identifier, "title-" + + identifier); + } + + /** + * Fill collection object. + * + * @param co the co + * @param objectNumber the object number + * @param title the object title + */ + void fillCollectionObject(CollectionobjectsCommon co, String objectNumber, + String title) { + co.setObjectNumber(objectNumber); + TitleGroupList titleGroupList = new TitleGroupList(); + List titleGroups = titleGroupList.getTitleGroup(); + TitleGroup titleGroup = new TitleGroup(); + titleGroup.setTitle(title); + titleGroups.add(titleGroup); + co.setTitleGroupList(titleGroupList); + } + + /** + * Fill intake. + * + * @param theIntake the the intake + * @param identifier the identifier + */ + void fillIntake(IntakesCommon theIntake, String identifier) { + String CURRENT_DATE_UTC = GregorianCalendarDateTimeUtils.currentDateUTC(); + fillIntake(theIntake, "entryNumber-" + identifier, CURRENT_DATE_UTC); + } + + /** + * Fill intake. + * + * @param theIntake the the intake + * @param entryNumber the entry number + * @param entryDate the entry date + */ + void fillIntake(IntakesCommon theIntake, String entryNumber, String entryDate) { + theIntake.setEntryNumber(entryNumber); + theIntake.setEntryDate(entryDate); + } + + /** + * Fill relation. + * + * @param relation the relation + * @param subjectCsid the document id1 + * @param subjectDocumentType the document type1 + * @param objectCsid the document id2 + * @param objectDocumentType the document type2 + * @param rt the rt + */ + void fillRelation(RelationsCommon relation, + String subjectCsid, String subjectDocumentType, + String objectCsid, String objectDocumentType, + String rt) + { + relation.setSubjectCsid(subjectCsid); + relation.setSubjectDocumentType(subjectDocumentType); + relation.setObjectCsid(objectCsid); + relation.setObjectDocumentType(objectDocumentType); + + relation.setRelationshipType(rt); + } + + /** + * Creates the identifier. + * + * @return the string + */ + String createIdentifier() { + long identifier = System.currentTimeMillis(); + return Long.toString(identifier); + } + + /** + * Extract id. + * + * @param res the res + * + * @return the string + */ + String extractId(ClientResponse res) { + String result = null; + + MultivaluedMap mvm = res.getMetadata(); + String uri = (String) ((ArrayList) mvm.get("Location")).get(0); + verbose("extractId:uri=" + uri); + String[] segments = uri.split("/"); + result = segments[segments.length - 1]; + verbose("id=" + result); + + return result; + } + + /** + * Extract part. + * + * @param input + * the input + * @param label + * the label + * @param clazz + * the clazz + * + * @return the object + * + * @throws Exception + * the exception + */ + static Object extractPart(PoxPayloadIn input, String label, Class clazz) { + Object obj = null; + + PayloadInputPart payloadInputPart = input.getPart(label); + if (payloadInputPart != null) { + obj = payloadInputPart.getBody(); + } + + return obj; + } + + /** + * Verbose. + * + * @param msg the msg + */ + void verbose(String msg) { + System.out.println(msg); + } + + /** + * Verbose. + * + * @param msg the msg + * @param o the o + * @param clazz the clazz + */ + void verbose(String msg, Object o, Class clazz) { + try { + verbose(msg); + JAXBContext jc = JAXBContext.newInstance(clazz); + Marshaller m = jc.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + m.marshal(o, System.out); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Verbose map. + * + * @param map the map + */ + void verboseMap(MultivaluedMap map) { + for (Object entry : map.entrySet()) { + MultivaluedMap.Entry mentry = (MultivaluedMap.Entry) entry; + verbose(" name=" + mentry.getKey() + " value=" + mentry.getValue()); + } + } + +} diff --git a/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/XmlCompareJdomRepeatingTest.java b/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/XmlCompareJdomRepeatingTest.java index 634b96f56..b63dcbe87 100644 --- a/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/XmlCompareJdomRepeatingTest.java +++ b/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/XmlCompareJdomRepeatingTest.java @@ -1,102 +1,102 @@ -/** - * 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 (c) 2009 Regents of the University of California - * - * 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.IntegrationTests.test; - -import org.collectionspace.services.IntegrationTests.xmlreplay.TreeWalkResults; -import org.collectionspace.services.IntegrationTests.xmlreplay.XmlCompareJdom; -import org.collectionspace.services.common.api.FileTools; -import org.collectionspace.services.common.api.Tools; -import org.testng.annotations.Test; - -import java.io.File; - -/** - * User: laramie - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ -public class XmlCompareJdomRepeatingTest { - - private static String getDirectory(){ - String dataDir = "src/test/resources/test-data/xmlreplay/XmlCompareJdom"; // this dir lives under service/IntegrationTests - String pwd = "."; - try { - pwd = (new File(".")).getCanonicalPath(); - } catch (Exception e){ - System.err.println("Error trying to find current working directory: "+e); - } - String thisDir = Tools.glue(pwd, "/", dataDir); - return thisDir; - } - - private void testBanner(String msg){ - String BANNER ="-------------------------------------------------------"; - String R = "\r\n"; - System.out.println(BANNER - + R +" TEST CLASS: "+this.getClass().getName() - + R +" TEST NAME: "+msg - + R +" TEST DATA DIR: "+getDirectory() - + R - +BANNER); - } - - @Test - public void testLeftAndRightSame(){ - testBanner("testLeftAndRightSame"); - String dir = getDirectory(); - String expectedPartContent = FileTools.readFile(dir, "1-left.xml"); - String fromServerContent = FileTools.readFile(dir, "1-right.xml"); - String startPath = "/document/*[local-name()='relations-common-list']"; - TreeWalkResults.MatchSpec matchSpec = TreeWalkResults.MatchSpec.createDefault(); - TreeWalkResults results = - XmlCompareJdom.compareParts(expectedPartContent, - "expected", - fromServerContent, - "from-server", - startPath, - matchSpec); - XmlCompareJdomTest.assertTreeWalkResults(results,1,0,0,false, matchSpec); - // addedRight,missingRight,textMismatches,strictMatch,treesMatch - } - - @Test - public void testLeftAndRightSameNoStartElement(){ - testBanner("testLeftAndRightSameNoStartElement"); - String dir = getDirectory(); - String expectedPartContent = FileTools.readFile(dir, "2-left.xml"); - String fromServerContent = FileTools.readFile(dir, "2-right.xml"); - String startPath = "/document"; - TreeWalkResults.MatchSpec matchSpec = TreeWalkResults.MatchSpec.createDefault(); - TreeWalkResults results = - XmlCompareJdom.compareParts(expectedPartContent, - "expected", - fromServerContent, - "from-server", - startPath, - matchSpec); - XmlCompareJdomTest.assertTreeWalkResults(results,0,0,0,true,matchSpec); - // addedRight,missingRight,textMismatches,strictMatch,treesMatch - } - - -} +/** + * 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 (c) 2009 Regents of the University of California + * + * 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.IntegrationTests.test; + +import org.collectionspace.services.IntegrationTests.xmlreplay.TreeWalkResults; +import org.collectionspace.services.IntegrationTests.xmlreplay.XmlCompareJdom; +import org.collectionspace.services.common.api.FileTools; +import org.collectionspace.services.common.api.Tools; +import org.testng.annotations.Test; + +import java.io.File; + +/** + * User: laramie + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public class XmlCompareJdomRepeatingTest { + + private static String getDirectory(){ + String dataDir = "src/test/resources/test-data/xmlreplay/XmlCompareJdom"; // this dir lives under service/IntegrationTests + String pwd = "."; + try { + pwd = (new File(".")).getCanonicalPath(); + } catch (Exception e){ + System.err.println("Error trying to find current working directory: "+e); + } + String thisDir = Tools.glue(pwd, "/", dataDir); + return thisDir; + } + + private void testBanner(String msg){ + String BANNER ="-------------------------------------------------------"; + String R = "\r\n"; + System.out.println(BANNER + + R +" TEST CLASS: "+this.getClass().getName() + + R +" TEST NAME: "+msg + + R +" TEST DATA DIR: "+getDirectory() + + R + +BANNER); + } + + @Test + public void testLeftAndRightSame(){ + testBanner("testLeftAndRightSame"); + String dir = getDirectory(); + String expectedPartContent = FileTools.readFile(dir, "1-left.xml"); + String fromServerContent = FileTools.readFile(dir, "1-right.xml"); + String startPath = "/document/*[local-name()='relations-common-list']"; + TreeWalkResults.MatchSpec matchSpec = TreeWalkResults.MatchSpec.createDefault(); + TreeWalkResults results = + XmlCompareJdom.compareParts(expectedPartContent, + "expected", + fromServerContent, + "from-server", + startPath, + matchSpec); + XmlCompareJdomTest.assertTreeWalkResults(results,1,0,0,false, matchSpec); + // addedRight,missingRight,textMismatches,strictMatch,treesMatch + } + + @Test + public void testLeftAndRightSameNoStartElement(){ + testBanner("testLeftAndRightSameNoStartElement"); + String dir = getDirectory(); + String expectedPartContent = FileTools.readFile(dir, "2-left.xml"); + String fromServerContent = FileTools.readFile(dir, "2-right.xml"); + String startPath = "/document"; + TreeWalkResults.MatchSpec matchSpec = TreeWalkResults.MatchSpec.createDefault(); + TreeWalkResults results = + XmlCompareJdom.compareParts(expectedPartContent, + "expected", + fromServerContent, + "from-server", + startPath, + matchSpec); + XmlCompareJdomTest.assertTreeWalkResults(results,0,0,0,true,matchSpec); + // addedRight,missingRight,textMismatches,strictMatch,treesMatch + } + + +} diff --git a/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/XmlCompareJdomTest.java b/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/XmlCompareJdomTest.java index 93cb23430..190fb6491 100644 --- a/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/XmlCompareJdomTest.java +++ b/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/XmlCompareJdomTest.java @@ -1,220 +1,220 @@ -/** - * 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 (c) 2009 Regents of the University of California - * - * 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.IntegrationTests.test; - -import org.collectionspace.services.IntegrationTests.xmlreplay.TreeWalkResults; -import org.collectionspace.services.IntegrationTests.xmlreplay.XmlCompareJdom; -import org.testng.Assert; -import org.testng.annotations.Test; - -/** - * User: laramie - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ -public class XmlCompareJdomTest { - - - private void testBanner(String msg){ - String BANNER ="-------------------------------------------------------"; - System.out.println(BANNER+"\r\n"+this.getClass().getName()+"\r\n"+msg+"\r\n"+BANNER); - } - public static void printTreeWalkResults(TreeWalkResults list){ - for (TreeWalkResults.TreeWalkEntry entry : list){ - System.out.println(entry.toString()); - } - } - - static void assertTrue(boolean stmt, String msg, TreeWalkResults results){ - if (!stmt){ - System.out.println("=====> Assertion Failed: "+msg); - printTreeWalkResults(results); - } - Assert.assertTrue(stmt, msg); - } - static void assertEquals(Object o1, Object o2, String msg, TreeWalkResults results){ - if ( ! o1.equals(o2)) { - System.out.println("=====> Assertion Equals Failed: "+" o1: {"+o1+"} o2: {"+o2+"}"+"\r\n "+msg); - printTreeWalkResults(results); - } - Assert.assertEquals(o1, o2, msg); - } - - public static void assertTreeWalkResults(TreeWalkResults results, - int addedRight, - int missingRight, - int textMismatches, - boolean strictMatch, - TreeWalkResults.MatchSpec matchSpec){ - int addedr = results.countFor(TreeWalkResults.TreeWalkEntry.STATUS.R_ADDED); - int missingr = results.countFor(TreeWalkResults.TreeWalkEntry.STATUS.R_MISSING); - int tdiff = results.countFor(TreeWalkResults.TreeWalkEntry.STATUS.TEXT_DIFFERENT); - int badCount = results.getMismatchCount(); - boolean strict = results.isStrictMatch(); - boolean treeOK = results.treesMatch(matchSpec); - - String expected = "\r\n expected: addedRight:"+addedRight+",missingRight:"+missingRight+",textMismatches:"+textMismatches - +",strictMatch:"+strictMatch+",matchSpec:"+matchSpec; - - String actual = "\r\n actual: addedRight:"+addedr+",missingRight:"+missingr+",textMismatches:"+tdiff - +",strictMatch:"+strict+",matchSpec:"+matchSpec; - String exp_act = expected +"\r\n"+actual+"\r\n"; - boolean done = false; - try { - assertEquals(addedr, addedRight, "assertTreeWalkResults:R_ADDED mismatch." + exp_act, results); - assertEquals(missingr, missingRight, "assertTreeWalkResults:R_MISSING mismatch." + exp_act, results); - assertEquals(tdiff, textMismatches, "assertTreeWalkResults:TEXT_DIFFERENT mismatch." + exp_act, results); - assertTrue((strict == strictMatch), "assertTreeWalkResults:strictMatch mismatch." + exp_act, results); - assertTrue((treeOK), "assertTreeWalkResults:treesMatch("+matchSpec+") returned false."+exp_act, results); - //System.out.println("SUCCESS: assertTreeWalkResults done.\r\n"); - done = true; - } finally { - if (!done) System.out.println("FAILURE: assertTreeWalkResults failed an assertion. See surefire report.\r\n"); - } - } - - @Test - public void testXmlCompareJdom(){ - testBanner("testXmlCompareJdom"); - TreeWalkResults.MatchSpec matchSpec = TreeWalkResults.MatchSpec.createDefault(); - TreeWalkResults results = - XmlCompareJdom.compareParts(expectedPartContent, - "expected", - partFromServer, - "from-server", - exPARTNAME, - matchSpec); - assertTreeWalkResults(results,0,0,0,true,matchSpec); - // addedRight,missingRight,textMismatches,strictMatch,treesMatch - } - - @Test - public void testTextContentDifferent(){ - testBanner("testTextContentDifferent"); - TreeWalkResults.MatchSpec matchSpec = TreeWalkResults.MatchSpec.createDefault(); - matchSpec.removeErrorFromSpec(TreeWalkResults.TreeWalkEntry.STATUS.TEXT_DIFFERENT); - TreeWalkResults results = - XmlCompareJdom.compareParts(expectedPartContent, - "expected", - srvHEAD+srvEN2+srvDEPOSITOR+srvFOOT, - "from-server", - exPARTNAME, - matchSpec); - assertTreeWalkResults(results,0,0,1,false,matchSpec); - // addedRight,missingRight,textMismatches,strictMatch,treesMatch - } - - - @Test - public void testAddedR(){ - testBanner("testAddedR"); - TreeWalkResults.MatchSpec matchSpec = TreeWalkResults.MatchSpec.createDefault(); - TreeWalkResults results = - XmlCompareJdom.compareParts(expectedPartContent, - "expected", - srvHEAD+srvEN+exNEWTREE+srvDEPOSITOR+exNEW+srvFOOT, - "from-server", - exPARTNAME, - matchSpec); - assertTreeWalkResults(results,2,0,0,false,matchSpec); - // addedRight,missingRight,textMismatches,strictMatch,treesMatch - - } - - @Test - public void testAddedL(){ - testBanner("testAddedL"); - TreeWalkResults.MatchSpec matchSpec = TreeWalkResults.MatchSpec.createDefault(); - matchSpec.removeErrorFromSpec(TreeWalkResults.TreeWalkEntry.STATUS.R_MISSING); - - TreeWalkResults results = - XmlCompareJdom.compareParts(exHEAD + exEN_WCH + exNEWTREE + exDEP + exNEW + exFOOT, - "expected", - partFromServer, - "from-server", - exPARTNAME, - matchSpec); - assertTreeWalkResults(results,0,3,0,false,matchSpec); - // addedRight,missingRight,textMismatches,strictMatch,treesMatch - } - - @Test - public void testChildrenReordered(){ - testBanner("testChildrenReordered"); - TreeWalkResults.MatchSpec matchSpec = TreeWalkResults.MatchSpec.createDefault(); - TreeWalkResults results = - XmlCompareJdom.compareParts(exHEAD + exDEP + exEN + exFOOT, - "expected", - partFromServer, - "from-server", - exPARTNAME, - matchSpec); - assertTreeWalkResults(results,0,0,0,true,matchSpec); - // addedRight,missingRight,textMismatches,strictMatch,treesMatch - } - - // ============ expected part, will be used as LEFT tree ========================================================== - private static String exPARTNAME = "objectexit_common"; - - private static String exHEAD ="\r\n" - +"" - +"\r\n"; - private static String exEN =" objectexitNumber-1290026472360\r\n"; - private static String exEN_WCH =" objectexitNumber-1290026472360\r\n" - +" \r\n" - +" enChild content\r\n" - +" \r\n" - +" \r\n"; - private static String exNEWTREE =" \r\n" - +" \r\n" - +" second content\r\n" - +" \r\n" - +" \r\n"; - private static String exDEP =" urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum'\r\n"; - private static String exNEW =" objectexitNumber-1290026472360\r\n"; - private static String exFOOT ="" - +""; - - private static String expectedPartContent = exHEAD + exEN + exDEP + exFOOT; - - - // ============ from-server part, will be used as RIGHT tree ========================================================== - - private static String srvHEAD = "\r\n" - +"" - +"\r\n"; - - private static String srvEN = "objectexitNumber-1290026472360\r\n"; - private static String srvEN2 = "objectexitNumber-9999999999999\r\n"; - private static String srvDEPOSITOR = "urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum'\r\n"; - private static String srvFOOT = "\r\n" - +""; - - private static String partFromServer = srvHEAD+srvEN+srvDEPOSITOR+srvFOOT; - - - -} +/** + * 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 (c) 2009 Regents of the University of California + * + * 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.IntegrationTests.test; + +import org.collectionspace.services.IntegrationTests.xmlreplay.TreeWalkResults; +import org.collectionspace.services.IntegrationTests.xmlreplay.XmlCompareJdom; +import org.testng.Assert; +import org.testng.annotations.Test; + +/** + * User: laramie + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public class XmlCompareJdomTest { + + + private void testBanner(String msg){ + String BANNER ="-------------------------------------------------------"; + System.out.println(BANNER+"\r\n"+this.getClass().getName()+"\r\n"+msg+"\r\n"+BANNER); + } + public static void printTreeWalkResults(TreeWalkResults list){ + for (TreeWalkResults.TreeWalkEntry entry : list){ + System.out.println(entry.toString()); + } + } + + static void assertTrue(boolean stmt, String msg, TreeWalkResults results){ + if (!stmt){ + System.out.println("=====> Assertion Failed: "+msg); + printTreeWalkResults(results); + } + Assert.assertTrue(stmt, msg); + } + static void assertEquals(Object o1, Object o2, String msg, TreeWalkResults results){ + if ( ! o1.equals(o2)) { + System.out.println("=====> Assertion Equals Failed: "+" o1: {"+o1+"} o2: {"+o2+"}"+"\r\n "+msg); + printTreeWalkResults(results); + } + Assert.assertEquals(o1, o2, msg); + } + + public static void assertTreeWalkResults(TreeWalkResults results, + int addedRight, + int missingRight, + int textMismatches, + boolean strictMatch, + TreeWalkResults.MatchSpec matchSpec){ + int addedr = results.countFor(TreeWalkResults.TreeWalkEntry.STATUS.R_ADDED); + int missingr = results.countFor(TreeWalkResults.TreeWalkEntry.STATUS.R_MISSING); + int tdiff = results.countFor(TreeWalkResults.TreeWalkEntry.STATUS.TEXT_DIFFERENT); + int badCount = results.getMismatchCount(); + boolean strict = results.isStrictMatch(); + boolean treeOK = results.treesMatch(matchSpec); + + String expected = "\r\n expected: addedRight:"+addedRight+",missingRight:"+missingRight+",textMismatches:"+textMismatches + +",strictMatch:"+strictMatch+",matchSpec:"+matchSpec; + + String actual = "\r\n actual: addedRight:"+addedr+",missingRight:"+missingr+",textMismatches:"+tdiff + +",strictMatch:"+strict+",matchSpec:"+matchSpec; + String exp_act = expected +"\r\n"+actual+"\r\n"; + boolean done = false; + try { + assertEquals(addedr, addedRight, "assertTreeWalkResults:R_ADDED mismatch." + exp_act, results); + assertEquals(missingr, missingRight, "assertTreeWalkResults:R_MISSING mismatch." + exp_act, results); + assertEquals(tdiff, textMismatches, "assertTreeWalkResults:TEXT_DIFFERENT mismatch." + exp_act, results); + assertTrue((strict == strictMatch), "assertTreeWalkResults:strictMatch mismatch." + exp_act, results); + assertTrue((treeOK), "assertTreeWalkResults:treesMatch("+matchSpec+") returned false."+exp_act, results); + //System.out.println("SUCCESS: assertTreeWalkResults done.\r\n"); + done = true; + } finally { + if (!done) System.out.println("FAILURE: assertTreeWalkResults failed an assertion. See surefire report.\r\n"); + } + } + + @Test + public void testXmlCompareJdom(){ + testBanner("testXmlCompareJdom"); + TreeWalkResults.MatchSpec matchSpec = TreeWalkResults.MatchSpec.createDefault(); + TreeWalkResults results = + XmlCompareJdom.compareParts(expectedPartContent, + "expected", + partFromServer, + "from-server", + exPARTNAME, + matchSpec); + assertTreeWalkResults(results,0,0,0,true,matchSpec); + // addedRight,missingRight,textMismatches,strictMatch,treesMatch + } + + @Test + public void testTextContentDifferent(){ + testBanner("testTextContentDifferent"); + TreeWalkResults.MatchSpec matchSpec = TreeWalkResults.MatchSpec.createDefault(); + matchSpec.removeErrorFromSpec(TreeWalkResults.TreeWalkEntry.STATUS.TEXT_DIFFERENT); + TreeWalkResults results = + XmlCompareJdom.compareParts(expectedPartContent, + "expected", + srvHEAD+srvEN2+srvDEPOSITOR+srvFOOT, + "from-server", + exPARTNAME, + matchSpec); + assertTreeWalkResults(results,0,0,1,false,matchSpec); + // addedRight,missingRight,textMismatches,strictMatch,treesMatch + } + + + @Test + public void testAddedR(){ + testBanner("testAddedR"); + TreeWalkResults.MatchSpec matchSpec = TreeWalkResults.MatchSpec.createDefault(); + TreeWalkResults results = + XmlCompareJdom.compareParts(expectedPartContent, + "expected", + srvHEAD+srvEN+exNEWTREE+srvDEPOSITOR+exNEW+srvFOOT, + "from-server", + exPARTNAME, + matchSpec); + assertTreeWalkResults(results,2,0,0,false,matchSpec); + // addedRight,missingRight,textMismatches,strictMatch,treesMatch + + } + + @Test + public void testAddedL(){ + testBanner("testAddedL"); + TreeWalkResults.MatchSpec matchSpec = TreeWalkResults.MatchSpec.createDefault(); + matchSpec.removeErrorFromSpec(TreeWalkResults.TreeWalkEntry.STATUS.R_MISSING); + + TreeWalkResults results = + XmlCompareJdom.compareParts(exHEAD + exEN_WCH + exNEWTREE + exDEP + exNEW + exFOOT, + "expected", + partFromServer, + "from-server", + exPARTNAME, + matchSpec); + assertTreeWalkResults(results,0,3,0,false,matchSpec); + // addedRight,missingRight,textMismatches,strictMatch,treesMatch + } + + @Test + public void testChildrenReordered(){ + testBanner("testChildrenReordered"); + TreeWalkResults.MatchSpec matchSpec = TreeWalkResults.MatchSpec.createDefault(); + TreeWalkResults results = + XmlCompareJdom.compareParts(exHEAD + exDEP + exEN + exFOOT, + "expected", + partFromServer, + "from-server", + exPARTNAME, + matchSpec); + assertTreeWalkResults(results,0,0,0,true,matchSpec); + // addedRight,missingRight,textMismatches,strictMatch,treesMatch + } + + // ============ expected part, will be used as LEFT tree ========================================================== + private static String exPARTNAME = "objectexit_common"; + + private static String exHEAD ="\r\n" + +"" + +"\r\n"; + private static String exEN =" objectexitNumber-1290026472360\r\n"; + private static String exEN_WCH =" objectexitNumber-1290026472360\r\n" + +" \r\n" + +" enChild content\r\n" + +" \r\n" + +" \r\n"; + private static String exNEWTREE =" \r\n" + +" \r\n" + +" second content\r\n" + +" \r\n" + +" \r\n"; + private static String exDEP =" urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum'\r\n"; + private static String exNEW =" objectexitNumber-1290026472360\r\n"; + private static String exFOOT ="" + +""; + + private static String expectedPartContent = exHEAD + exEN + exDEP + exFOOT; + + + // ============ from-server part, will be used as RIGHT tree ========================================================== + + private static String srvHEAD = "\r\n" + +"" + +"\r\n"; + + private static String srvEN = "objectexitNumber-1290026472360\r\n"; + private static String srvEN2 = "objectexitNumber-9999999999999\r\n"; + private static String srvDEPOSITOR = "urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum'\r\n"; + private static String srvFOOT = "\r\n" + +""; + + private static String partFromServer = srvHEAD+srvEN+srvDEPOSITOR+srvFOOT; + + + +} diff --git a/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/XmlReplayMasterTest.java b/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/XmlReplayMasterTest.java index eed0cfe65..8ffe2d9e7 100644 --- a/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/XmlReplayMasterTest.java +++ b/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/XmlReplayMasterTest.java @@ -1,23 +1,23 @@ -package org.collectionspace.services.IntegrationTests.test; - -import org.collectionspace.services.IntegrationTests.xmlreplay.ServiceResult; -import org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplay; -import org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplayTest; -import org.testng.annotations.Test; - -import java.util.List; - -/** - * User: laramie - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ -public class XmlReplayMasterTest extends XmlReplayTest { - - @Test - public void runMaster() throws Exception { - XmlReplay replay = createXmlReplayUsingIntegrationTestsModule(".."); - List> list = replay.runMaster(XmlReplay.DEFAULT_MASTER_CONTROL); - logTestForGroup(list, "XmlReplayMasterTest"); - } -} +package org.collectionspace.services.IntegrationTests.test; + +import org.collectionspace.services.IntegrationTests.xmlreplay.ServiceResult; +import org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplay; +import org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplayTest; +import org.testng.annotations.Test; + +import java.util.List; + +/** + * User: laramie + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public class XmlReplayMasterTest extends XmlReplayTest { + + @Test + public void runMaster() throws Exception { + XmlReplay replay = createXmlReplayUsingIntegrationTestsModule(".."); + List> list = replay.runMaster(XmlReplay.DEFAULT_MASTER_CONTROL); + logTestForGroup(list, "XmlReplayMasterTest"); + } +} diff --git a/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/XmlReplaySelfTest.java b/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/XmlReplaySelfTest.java index a4200fe7e..fd32960bf 100644 --- a/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/XmlReplaySelfTest.java +++ b/services/IntegrationTests/src/test/java/org/collectionspace/services/IntegrationTests/test/XmlReplaySelfTest.java @@ -1,170 +1,170 @@ -/** - * 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 (c) 2009 Regents of the University of California - * - * 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.IntegrationTests.test; - -import org.collectionspace.services.IntegrationTests.xmlreplay.ServiceResult; -import org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplay; -import org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplayTest; -import org.testng.annotations.Test; - -import java.util.List; -import java.util.Map; - -/** The test cases in here also document the ways that XmlReplay was designed to be used programmatically. - * The most automated way to use XmlReplay is demonstrated in runMaster(). You just create a master file and a control - * file in the IntegrationTests xml replay repository, which is in services/IntegrationTests + XmlReplayTest.XMLREPLAY_REL_DIR_TO_MODULE. - * - * If you choose to run from a module, you'll need to add a dependency to the IntegrationTests module: - * e.g. - * <project ...> - * <dependencies> - * <dependency> - <groupId>org.collectionspace.services</groupId> - <artifactId>org.collectionspace.services.IntegrationTests</artifactId> - <version>${project.version}</version> - </dependency> - * - * User: laramie - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ -public class XmlReplaySelfTest extends XmlReplayTest { - - public static XmlReplay createXmlReplay() throws Exception { - return XmlReplayTest.createXmlReplayUsingIntegrationTestsModule(".."); - //NOTE: this self-test lives in services/IntegrationTests, so relToServicesRoot is ".." - // but if you were running from, say, services/dimension/client, then relToServicesRoot would be "../.." - // so you would have to call XmlReplayTest.createXmlReplayUsingIntegrationTestsModule("../..") - // which is done for you if you just call XmlReplayTest.createXmlReplay(). - } - - @Test - public void runMaster() throws Exception { - XmlReplay replay = createXmlReplay(); - List> list = replay.runMaster("xml-replay-master-self-test.xml"); - logTestForGroup(list, "runMaster"); - } - - @Test - public void runTestGroup() throws Exception { - XmlReplay replay = createXmlReplay(); - replay.readOptionsFromMasterConfigFile("xml-replay-master-self-test.xml"); //or use: XmlReplay.DEFAULT_MASTER_CONTROL as master filename; - replay.setControlFileName("xml-replay-self-test.xml"); - List list = replay.runTestGroup("selftestGroup"); - logTest(list, "runTestGroup"); - } - -/* - @Test - public void runOneTest() throws Exception { - XmlReplay replay = createXmlReplay(); - replay.readOptionsFromMasterConfigFile("xml-replay-master-self-test.xml"); - replay.setControlFileName("xml-replay-self-test.xml"); - - ServiceResult res = replay.runTest("selftestGroup", "OrgAuth1"); - logTest(res, "runOneTest"); - } - - - @Test - public void runMultipleTestsManualCleanup() throws Exception { - XmlReplay replay = createXmlReplay(); - replay.readOptionsFromMasterConfigFile("xml-replay-master-self-test.xml"); - replay.setControlFileName("xml-replay-self-test.xml"); - replay.setAutoDeletePOSTS(false); //defaults to true, so turn it off to to it ourselves. - - List testResultsList = new ArrayList(); - - ServiceResult res1 = replay.runTest("selftestGroup", "OrgAuth1"); - testResultsList.add(res1); - - ServiceResult res2 = replay.runTest("selftestGroup", "Org1"); - testResultsList.add(res2); - - ServiceResult res3 = replay.runTest("selftestGroup", "getOrg1"); - testResultsList.add(res3); - - //Now, clean up. You may skip this if your tests do all the DELETEs. - List deleteList = replay.autoDelete("runMultipleTestsManualCleanup"); - - logTest(testResultsList, "runTwoTestsManualCleanup.tests"); - logTest(deleteList, "runTwoTestsManualCleanup.cleanups"); - - } -*/ - - - @Test - public void runTestGroup_AllOptions() throws Exception { - XmlReplay replay = createXmlReplay(); //Use the central repository. - //You can also use your own xml replay repository in your module, like so: - // XmlReplay replay = XmlReplayTest.createXmlReplayForModule(); if you are in your module - //You can also manually specify to use the central repository: - // XmlReplay replay = XmlReplayTest.createXmlReplayUsingIntegrationTestsModule(".."); if you are in a module such as dimension - // XmlReplay replay = XmlReplayTest.createXmlReplayUsingIntegrationTestsModule("../.."); if you are in a module such as dimension/client - - //You may read Dump, Auths, and protoHostPort from the master file: - replay.readOptionsFromMasterConfigFile("xml-replay-master-self-test.xml"); //or use: XmlReplay.DEFAULT_MASTER_CONTROL as master filename; - //or you may set those options individually as shown next. - // Note that controlFileName is NOT set from calling readOptionsFromMasterConfigFile. - // If you run a master, it sets controlFileName, possibly in a loop. - // All of the Auths will be read from the master file, and may be referenced from your control file, - // or you may specify Auths in your control file. There are also public methods to set the AuthsMap yourself. - - //XmlReplay wants to know about two files: a master and a control file - // The master references one to many control files. - // If you don't call runMaster(), you must specify the control file: - replay.setControlFileName("xml-replay-self-test.xml"); - - //These option default sensibly, some of them from the master, but here's how to set them all: - - //Dump determines how much goes to log, and how verbose. - XmlReplay.Dump dump = XmlReplay.getDumpConfig(); //static factory call. - dump.payloads = false; - dump.dumpServiceResult = ServiceResult.DUMP_OPTIONS.minimal; - replay.setDump(dump); - - //use this if you must look it up from some other place. - // Default is to have it in xml-replay-master.xml - replay.setProtoHostPort("http://localhost:8180"); - - //Default is true, but you can override if you want to leave objects on server, or control the order of deletion. - replay.setAutoDeletePOSTS(false); - - //You don't need this, but you can inspect what XmlReplay holds onto: a data structure of CSIDs - Map serviceResultsMap = replay.getServiceResultsMap(); - - // ****** RUN A GROUP *********************************************** - List list = replay.runTestGroup("selftestGroup"); - - // This runs a group called "organization" inside a control file named above, which happens to be called "organization.xml". - // You could also run just one test using these options by calling replay.runTest as shown above in XmlReplayTest.runOneTest() - - //Now, since we set setAutoDeletePOSTS(false) above, you can clean up manually: - replay.autoDelete("runTestGroup_AllOptions"); //deletes everything in serviceResultsMap, which it hangs onto. - - logTest(list, "runTestGroup_AllOptions"); - } - -} +/** + * 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 (c) 2009 Regents of the University of California + * + * 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.IntegrationTests.test; + +import org.collectionspace.services.IntegrationTests.xmlreplay.ServiceResult; +import org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplay; +import org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplayTest; +import org.testng.annotations.Test; + +import java.util.List; +import java.util.Map; + +/** The test cases in here also document the ways that XmlReplay was designed to be used programmatically. + * The most automated way to use XmlReplay is demonstrated in runMaster(). You just create a master file and a control + * file in the IntegrationTests xml replay repository, which is in services/IntegrationTests + XmlReplayTest.XMLREPLAY_REL_DIR_TO_MODULE. + * + * If you choose to run from a module, you'll need to add a dependency to the IntegrationTests module: + * e.g. + * <project ...> + * <dependencies> + * <dependency> + <groupId>org.collectionspace.services</groupId> + <artifactId>org.collectionspace.services.IntegrationTests</artifactId> + <version>${project.version}</version> + </dependency> + * + * User: laramie + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public class XmlReplaySelfTest extends XmlReplayTest { + + public static XmlReplay createXmlReplay() throws Exception { + return XmlReplayTest.createXmlReplayUsingIntegrationTestsModule(".."); + //NOTE: this self-test lives in services/IntegrationTests, so relToServicesRoot is ".." + // but if you were running from, say, services/dimension/client, then relToServicesRoot would be "../.." + // so you would have to call XmlReplayTest.createXmlReplayUsingIntegrationTestsModule("../..") + // which is done for you if you just call XmlReplayTest.createXmlReplay(). + } + + @Test + public void runMaster() throws Exception { + XmlReplay replay = createXmlReplay(); + List> list = replay.runMaster("xml-replay-master-self-test.xml"); + logTestForGroup(list, "runMaster"); + } + + @Test + public void runTestGroup() throws Exception { + XmlReplay replay = createXmlReplay(); + replay.readOptionsFromMasterConfigFile("xml-replay-master-self-test.xml"); //or use: XmlReplay.DEFAULT_MASTER_CONTROL as master filename; + replay.setControlFileName("xml-replay-self-test.xml"); + List list = replay.runTestGroup("selftestGroup"); + logTest(list, "runTestGroup"); + } + +/* + @Test + public void runOneTest() throws Exception { + XmlReplay replay = createXmlReplay(); + replay.readOptionsFromMasterConfigFile("xml-replay-master-self-test.xml"); + replay.setControlFileName("xml-replay-self-test.xml"); + + ServiceResult res = replay.runTest("selftestGroup", "OrgAuth1"); + logTest(res, "runOneTest"); + } + + + @Test + public void runMultipleTestsManualCleanup() throws Exception { + XmlReplay replay = createXmlReplay(); + replay.readOptionsFromMasterConfigFile("xml-replay-master-self-test.xml"); + replay.setControlFileName("xml-replay-self-test.xml"); + replay.setAutoDeletePOSTS(false); //defaults to true, so turn it off to to it ourselves. + + List testResultsList = new ArrayList(); + + ServiceResult res1 = replay.runTest("selftestGroup", "OrgAuth1"); + testResultsList.add(res1); + + ServiceResult res2 = replay.runTest("selftestGroup", "Org1"); + testResultsList.add(res2); + + ServiceResult res3 = replay.runTest("selftestGroup", "getOrg1"); + testResultsList.add(res3); + + //Now, clean up. You may skip this if your tests do all the DELETEs. + List deleteList = replay.autoDelete("runMultipleTestsManualCleanup"); + + logTest(testResultsList, "runTwoTestsManualCleanup.tests"); + logTest(deleteList, "runTwoTestsManualCleanup.cleanups"); + + } +*/ + + + @Test + public void runTestGroup_AllOptions() throws Exception { + XmlReplay replay = createXmlReplay(); //Use the central repository. + //You can also use your own xml replay repository in your module, like so: + // XmlReplay replay = XmlReplayTest.createXmlReplayForModule(); if you are in your module + //You can also manually specify to use the central repository: + // XmlReplay replay = XmlReplayTest.createXmlReplayUsingIntegrationTestsModule(".."); if you are in a module such as dimension + // XmlReplay replay = XmlReplayTest.createXmlReplayUsingIntegrationTestsModule("../.."); if you are in a module such as dimension/client + + //You may read Dump, Auths, and protoHostPort from the master file: + replay.readOptionsFromMasterConfigFile("xml-replay-master-self-test.xml"); //or use: XmlReplay.DEFAULT_MASTER_CONTROL as master filename; + //or you may set those options individually as shown next. + // Note that controlFileName is NOT set from calling readOptionsFromMasterConfigFile. + // If you run a master, it sets controlFileName, possibly in a loop. + // All of the Auths will be read from the master file, and may be referenced from your control file, + // or you may specify Auths in your control file. There are also public methods to set the AuthsMap yourself. + + //XmlReplay wants to know about two files: a master and a control file + // The master references one to many control files. + // If you don't call runMaster(), you must specify the control file: + replay.setControlFileName("xml-replay-self-test.xml"); + + //These option default sensibly, some of them from the master, but here's how to set them all: + + //Dump determines how much goes to log, and how verbose. + XmlReplay.Dump dump = XmlReplay.getDumpConfig(); //static factory call. + dump.payloads = false; + dump.dumpServiceResult = ServiceResult.DUMP_OPTIONS.minimal; + replay.setDump(dump); + + //use this if you must look it up from some other place. + // Default is to have it in xml-replay-master.xml + replay.setProtoHostPort("http://localhost:8180"); + + //Default is true, but you can override if you want to leave objects on server, or control the order of deletion. + replay.setAutoDeletePOSTS(false); + + //You don't need this, but you can inspect what XmlReplay holds onto: a data structure of CSIDs + Map serviceResultsMap = replay.getServiceResultsMap(); + + // ****** RUN A GROUP *********************************************** + List list = replay.runTestGroup("selftestGroup"); + + // This runs a group called "organization" inside a control file named above, which happens to be called "organization.xml". + // You could also run just one test using these options by calling replay.runTest as shown above in XmlReplayTest.runOneTest() + + //Now, since we set setAutoDeletePOSTS(false) above, you can clean up manually: + replay.autoDelete("runTestGroup_AllOptions"); //deletes everything in serviceResultsMap, which it hangs onto. + + logTest(list, "runTestGroup_AllOptions"); + } + +} diff --git a/services/IntegrationTests/src/test/resources/log4j.properties b/services/IntegrationTests/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/IntegrationTests/src/test/resources/log4j.properties +++ b/services/IntegrationTests/src/test/resources/log4j.properties @@ -1,23 +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 +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/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/ac1.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/ac1.xml index ae8665103..844436dc1 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/ac1.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/ac1.xml @@ -1,22 +1,22 @@ - - - - - 2010-11-15T07:30:24Z - 2009-10-15T07:30:24Z - - acquisitionReferenceNumber-1 - - First Owner -1292275630222 - Second Owner-1292275630222 - - - NEW Museum Acquisition Source-333 - Donor Acquisition Source-1292275630222 - - - - - + + + + + 2010-11-15T07:30:24Z + 2009-10-15T07:30:24Z + + acquisitionReferenceNumber-1 + + First Owner -1292275630222 + Second Owner-1292275630222 + + + NEW Museum Acquisition Source-333 + Donor Acquisition Source-1292275630222 + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/ac2.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/ac2.xml index dfa99178c..d2d8db762 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/ac2.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/ac2.xml @@ -1,22 +1,22 @@ - - - - - 2010-11-15T07:30:24Z - 2009-10-15T07:30:24Z - - acquisitionReferenceNumber-1292275631503 - - Second Owner-1292275631503 - First Owner -1292275631503 - - - Museum Acquisition Source-1292275631503 - Donor Acquisition Source-1292275631503 - - - - - + + + + + 2010-11-15T07:30:24Z + 2009-10-15T07:30:24Z + + acquisitionReferenceNumber-1292275631503 + + Second Owner-1292275631503 + First Owner -1292275631503 + + + Museum Acquisition Source-1292275631503 + Donor Acquisition Source-1292275631503 + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/acquisitions.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/acquisitions.xml index 7848c8306..5f974a5c3 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/acquisitions.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/acquisitions.xml @@ -1,74 +1,74 @@ - - - - - YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= - YWRtaW5AY29sbGVjdGlvbnNwYWNlLm9yZzpBZG1pbmlzdHJhdG9y - - - - - POST - /cspace-services/acquisitions/ - acquisitions/ac1.xml - - - GET - /cspace-services/acquisitions/${ac1.CSID} - - - - acquisitions/res/ac1.res.xml - - - - - - - POST - /cspace-services/acquisitions/ - acquisitions/ac1.xml - - - - GET - /cspace-services/acquisitions/${ac1.CSID} - - - - acquisitions/res/ac1.res.xml - - - - - POST - /cspace-services/acquisitions/ - acquisitions/ac2.xml - - - - GET - /cspace-services/acquisitions/${ac2.CSID} - - - - acquisitions/res/ac2.res.xml - - - - - GET - /cspace-services/acquisitions/?sortBy=&pgNum=0&pgSz=10 - - - - acquisitions/res/ac3list.res.xml - - - - - - - - - + + + + + YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= + YWRtaW5AY29sbGVjdGlvbnNwYWNlLm9yZzpBZG1pbmlzdHJhdG9y + + + + + POST + /cspace-services/acquisitions/ + acquisitions/ac1.xml + + + GET + /cspace-services/acquisitions/${ac1.CSID} + + + + acquisitions/res/ac1.res.xml + + + + + + + POST + /cspace-services/acquisitions/ + acquisitions/ac1.xml + + + + GET + /cspace-services/acquisitions/${ac1.CSID} + + + + acquisitions/res/ac1.res.xml + + + + + POST + /cspace-services/acquisitions/ + acquisitions/ac2.xml + + + + GET + /cspace-services/acquisitions/${ac2.CSID} + + + + acquisitions/res/ac2.res.xml + + + + + GET + /cspace-services/acquisitions/?sortBy=&pgNum=0&pgSz=10 + + + + acquisitions/res/ac3list.res.xml + + + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/res/ac1.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/res/ac1.res.xml index da16a0e14..008c19a4c 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/res/ac1.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/res/ac1.res.xml @@ -1,20 +1,20 @@ - - - -acquisitionReferenceNumber-1 - - -2010-11-15T07:30:24Z -2009-10-15T07:30:24Z - - -Donor Acquisition Source-1292275630222 -Museum Acquisition Source-1292275630222 - - -First Owner -1292275630222 -Second Owner-1292275630222 - - - - + + + +acquisitionReferenceNumber-1 + + +2010-11-15T07:30:24Z +2009-10-15T07:30:24Z + + +Donor Acquisition Source-1292275630222 +Museum Acquisition Source-1292275630222 + + +First Owner -1292275630222 +Second Owner-1292275630222 + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/res/ac2.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/res/ac2.res.xml index 9fa704a36..d80b19ccf 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/res/ac2.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/res/ac2.res.xml @@ -1,21 +1,21 @@ - - - -acquisitionReferenceNumber-1292275631503 - - -2010-11-15T07:30:24Z -2009-10-15T07:30:24Z - - -Museum Acquisition Source-1292275631503 -Donor Acquisition Source-1292275631503 - - -Second Owner-1292275631503 -First Owner -1292275631503 - - - - - + + + +acquisitionReferenceNumber-1292275631503 + + +2010-11-15T07:30:24Z +2009-10-15T07:30:24Z + + +Museum Acquisition Source-1292275631503 +Donor Acquisition Source-1292275631503 + + +Second Owner-1292275631503 +First Owner -1292275631503 + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/res/ac3.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/res/ac3.res.xml index ebe0bbfe8..b281e264d 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/res/ac3.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/res/ac3.res.xml @@ -1,21 +1,21 @@ - - - -acquisitionReferenceNumber-1292275630222 - - -2010-11-15T07:30:24Z -2009-10-15T07:30:24Z - - -Donor Acquisition Source-1292275630222 -Museum Acquisition Source-1292275630222 - - -First Owner -1292275630222 -Second Owner-1292275630222 - - - - - + + + +acquisitionReferenceNumber-1292275630222 + + +2010-11-15T07:30:24Z +2009-10-15T07:30:24Z + + +Donor Acquisition Source-1292275630222 +Museum Acquisition Source-1292275630222 + + +First Owner -1292275630222 +Second Owner-1292275630222 + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/res/ac3list.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/res/ac3list.res.xml index 9ab1c0583..617b494e2 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/res/ac3list.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/acquisitions/res/ac3list.res.xml @@ -1,29 +1,29 @@ - - - - 0 - 10 - 2 - 2 - - acquisitionReferenceNumber|acquisitionSources|owners|uri|csid - - acquisitionReferenceNumber-1292275631503 - Donor Acquisition Source-1292275631503 - First Owner -1292275631503 - /acquisitions/bff1deb6-03af-457c-af98 - bff1deb6-03af-457c-af98 - - - acquisitionReferenceNumber-1292275630222 - Museum Acquisition Source-1292275630222 - Second Owner-1292275630222 - /acquisitions/549dd907-01cd-4f20-aeb7 - 549dd907-01cd-4f20-aeb7 - - - - - + + + + 0 + 10 + 2 + 2 + + acquisitionReferenceNumber|acquisitionSources|owners|uri|csid + + acquisitionReferenceNumber-1292275631503 + Donor Acquisition Source-1292275631503 + First Owner -1292275631503 + /acquisitions/bff1deb6-03af-457c-af98 + bff1deb6-03af-457c-af98 + + + acquisitionReferenceNumber-1292275630222 + Museum Acquisition Source-1292275630222 + Second Owner-1292275630222 + /acquisitions/549dd907-01cd-4f20-aeb7 + 549dd907-01cd-4f20-aeb7 + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/personauthority.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/personauthority.xml index 7f8e5c9ec..78c384bc1 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/personauthority.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/personauthority.xml @@ -1,11 +1,11 @@ - - - - ${authDisplayName} - ${authShortIdentifier} - PersonAuthority - This is a test Person Authority. - - - - + + + + ${authDisplayName} + ${authShortIdentifier} + PersonAuthority + This is a test Person Authority. + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/personitem.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/personitem.xml index 8204bb32f..460329795 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/personitem.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/personitem.xml @@ -1,13 +1,13 @@ - - - - - - ${itemDisplayName} - - - ${itemShortIdentifier} - ${itemBioNote} - ${itemDisplayName} - - + + + + + + ${itemDisplayName} + + + ${itemShortIdentifier} + ${itemBioNote} + ${itemDisplayName} + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/locationItems.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/locationItems.res.xml index 15cd5c253..05e038d45 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/locationItems.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/locationItems.res.xml @@ -1,7 +1,7 @@ - - - 0 - ${numItems} - ${numItems} - - + + + 0 + ${numItems} + ${numItems} + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/locationItemsWithShortID.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/locationItemsWithShortID.res.xml index ddeb00653..16424a357 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/locationItemsWithShortID.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/locationItemsWithShortID.res.xml @@ -1,8 +1,8 @@ - - - 1 - - ${itemShortIdentifier} - - - + + + 1 + + ${itemShortIdentifier} + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/personItems.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/personItems.res.xml index 15cd5c253..05e038d45 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/personItems.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/personItems.res.xml @@ -1,7 +1,7 @@ - - - 0 - ${numItems} - ${numItems} - - + + + 0 + ${numItems} + ${numItems} + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/personItemsContainingWord1.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/personItemsContainingWord1.res.xml index 45892e451..8d75fba8c 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/personItemsContainingWord1.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/personItemsContainingWord1.res.xml @@ -1,27 +1,27 @@ - - - 3 - - - ${createPersonAuthority1.word1}item3 - - - ${createPersonAuthority1.word1}item2 - - - ${createPersonAuthority1.word1}item1 - - - + + + 3 + + + ${createPersonAuthority1.word1}item3 + + + ${createPersonAuthority1.word1}item2 + + + ${createPersonAuthority1.word1}item1 + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/personItemsContainingWord2.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/personItemsContainingWord2.res.xml index e0c43540b..54f8d4818 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/personItemsContainingWord2.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/personItemsContainingWord2.res.xml @@ -1,24 +1,24 @@ - - - 2 - - - ${createPersonAuthority1.word1}item3 - - - ${createPersonAuthority1.word1}item1 - - - + + + 2 + + + ${createPersonAuthority1.word1}item3 + + + ${createPersonAuthority1.word1}item1 + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/personItemsOnlyWord1.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/personItemsOnlyWord1.res.xml index 50f513dce..fb035fcb4 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/personItemsOnlyWord1.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authority/res/personItemsOnlyWord1.res.xml @@ -1,9 +1,9 @@ - - - 1 - - ${createPersonAuthority1.word1}item2 - - - - + + + 1 + + ${createPersonAuthority1.word1}item2 + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/authrefs.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/authrefs.xml index 414f53a51..ff361053f 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/authrefs.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/authrefs.xml @@ -1,215 +1,215 @@ - - - - - - POST - /cspace-services/personauthorities/ - authrefs/newPersonAuthority.xml - - - POST - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ - authrefs/newPerson1.xml - - - POST - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ - authrefs/newPerson2.xml - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID} - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person2.CSID} - - - - POST - /cspace-services/loansout/ - authrefs/loanout.xml - - 42 - ${GetPerson1.got("//refName")} - - - - - POST - /cspace-services/loansout/ - authrefs/loanout.xml - - 102 - ${GetPerson2.got("//refName")} - - - - - POST - /cspace-services/loansout/ - authrefs/loanout.xml - - 103 - ${GetPerson2.got("//refName")} - - - - - POST - /cspace-services/loansout/ - authrefs/loanout.xml - - 104 - ${GetPerson2.got("//refName")} - - - - - POST - /cspace-services/loansout/ - authrefs/loanout.xml - - 105 - ${GetPerson2.got("//refName")} - - - - - POST - /cspace-services/loansout/ - authrefs/loanout.xml - - 106 - ${GetPerson2.got("//refName")} - - - - - POST - /cspace-services/loansout/ - authrefs/loanout.xml - - 107 - ${GetPerson2.got("//refName")} - - - - - POST - /cspace-services/loansout/ - authrefs/loanout.xml - - 108 - ${GetPerson2.got("//refName")} - - - - - POST - /cspace-services/loansout/ - authrefs/loanout.xml - - 109 - ${GetPerson2.got("//refName")} - - - - - POST - /cspace-services/loansout/ - authrefs/loanout.xml - - 110 - ${GetPerson2.got("//refName")} - - - - - PUT - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID} - authrefs/updatePerson1.xml - - - - PUT - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person2.CSID} - authrefs/updatePerson2.xml - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID} - - - authrefs/updatePerson1.xml - - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person2.CSID} - - - authrefs/updatePerson2.xml - - - - - GET - /cspace-services/loansout/${loanout1.CSID} - - - - authrefs/res/loanout.res.xml - - ${GetFirstUpdatedPerson.got("//refName")} - - - - - - GET - /cspace-services/loansout/${loanout2.CSID} - - - - authrefs/res/loanout.res.xml - - ${GetSecondUpdatedPerson.got("//refName")} - - - - - GET - /cspace-services/loansout/${loanout5.CSID} - - - - authrefs/res/loanout.res.xml - - ${GetSecondUpdatedPerson.got("//refName")} - - - - - GET - /cspace-services/loansout/${loanout9.CSID} - - - - authrefs/res/loanout.res.xml - - ${GetSecondUpdatedPerson.got("//refName")} - - - - - - + + + + + + POST + /cspace-services/personauthorities/ + authrefs/newPersonAuthority.xml + + + POST + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ + authrefs/newPerson1.xml + + + POST + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ + authrefs/newPerson2.xml + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID} + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person2.CSID} + + + + POST + /cspace-services/loansout/ + authrefs/loanout.xml + + 42 + ${GetPerson1.got("//refName")} + + + + + POST + /cspace-services/loansout/ + authrefs/loanout.xml + + 102 + ${GetPerson2.got("//refName")} + + + + + POST + /cspace-services/loansout/ + authrefs/loanout.xml + + 103 + ${GetPerson2.got("//refName")} + + + + + POST + /cspace-services/loansout/ + authrefs/loanout.xml + + 104 + ${GetPerson2.got("//refName")} + + + + + POST + /cspace-services/loansout/ + authrefs/loanout.xml + + 105 + ${GetPerson2.got("//refName")} + + + + + POST + /cspace-services/loansout/ + authrefs/loanout.xml + + 106 + ${GetPerson2.got("//refName")} + + + + + POST + /cspace-services/loansout/ + authrefs/loanout.xml + + 107 + ${GetPerson2.got("//refName")} + + + + + POST + /cspace-services/loansout/ + authrefs/loanout.xml + + 108 + ${GetPerson2.got("//refName")} + + + + + POST + /cspace-services/loansout/ + authrefs/loanout.xml + + 109 + ${GetPerson2.got("//refName")} + + + + + POST + /cspace-services/loansout/ + authrefs/loanout.xml + + 110 + ${GetPerson2.got("//refName")} + + + + + PUT + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID} + authrefs/updatePerson1.xml + + + + PUT + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person2.CSID} + authrefs/updatePerson2.xml + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID} + + + authrefs/updatePerson1.xml + + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person2.CSID} + + + authrefs/updatePerson2.xml + + + + + GET + /cspace-services/loansout/${loanout1.CSID} + + + + authrefs/res/loanout.res.xml + + ${GetFirstUpdatedPerson.got("//refName")} + + + + + + GET + /cspace-services/loansout/${loanout2.CSID} + + + + authrefs/res/loanout.res.xml + + ${GetSecondUpdatedPerson.got("//refName")} + + + + + GET + /cspace-services/loansout/${loanout5.CSID} + + + + authrefs/res/loanout.res.xml + + ${GetSecondUpdatedPerson.got("//refName")} + + + + + GET + /cspace-services/loansout/${loanout9.CSID} + + + + authrefs/res/loanout.res.xml + + ${GetSecondUpdatedPerson.got("//refName")} + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/authrefsComplex.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/authrefsComplex.xml index 6100d1feb..18f76bd43 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/authrefsComplex.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/authrefsComplex.xml @@ -1,24 +1,24 @@ - - - - - - POST - /cspace-services/intakes/ - authrefs/intake1.xml - - - - GET - /cspace-services/intakes/${intake1.CSID}/authorityrefs - - - authrefs/res/intakesAuthRefs.res.xml - - - - - + + + + + + POST + /cspace-services/intakes/ + authrefs/intake1.xml + + + + GET + /cspace-services/intakes/${intake1.CSID}/authorityrefs + + + authrefs/res/intakesAuthRefs.res.xml + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/authrefsSimple.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/authrefsSimple.xml index 66adebb96..8f55a0d81 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/authrefsSimple.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/authrefsSimple.xml @@ -1,98 +1,98 @@ - - - - - - POST - /cspace-services/personauthorities/ - authrefs/newPersonAuthority.xml - - - POST - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ - authrefs/newPerson1.xml - - - POST - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ - authrefs/newPerson2.xml - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID} - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person2.CSID} - - - - POST - /cspace-services/loansout/ - authrefs/loanout.xml - - 42 - ${GetPerson1.got("//refName")} - - - - - POST - /cspace-services/loansout/ - authrefs/loanout.xml - - 102 - ${GetPerson2.got("//refName")} - - - - - GET - /cspace-services/loansout/${loanout1.CSID}/authorityrefs - - - authrefs/res/foo.res.xml - - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}/refObjs - - - authrefs/res/refObjs.res.xml - - - - - POST - /cspace-services/orgauthorities/ - authrefs/orgauthorities_common.xml - - - - POST - /cspace-services/orgauthorities/${OrganizationAuth1.CSID}/items/ - authrefs/organizations_common.xml - - ${GetPerson1.got("//refName")} - ${GetPerson2.got("//refName")} - - - - - GET - /cspace-services/orgauthorities/${OrganizationAuth1.CSID}/items/${Org1.CSID}/authorityrefs - - - authrefs/res/foo.res.xml - - - - - + + + + + + POST + /cspace-services/personauthorities/ + authrefs/newPersonAuthority.xml + + + POST + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ + authrefs/newPerson1.xml + + + POST + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ + authrefs/newPerson2.xml + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID} + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person2.CSID} + + + + POST + /cspace-services/loansout/ + authrefs/loanout.xml + + 42 + ${GetPerson1.got("//refName")} + + + + + POST + /cspace-services/loansout/ + authrefs/loanout.xml + + 102 + ${GetPerson2.got("//refName")} + + + + + GET + /cspace-services/loansout/${loanout1.CSID}/authorityrefs + + + authrefs/res/foo.res.xml + + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}/refObjs + + + authrefs/res/refObjs.res.xml + + + + + POST + /cspace-services/orgauthorities/ + authrefs/orgauthorities_common.xml + + + + POST + /cspace-services/orgauthorities/${OrganizationAuth1.CSID}/items/ + authrefs/organizations_common.xml + + ${GetPerson1.got("//refName")} + ${GetPerson2.got("//refName")} + + + + + GET + /cspace-services/orgauthorities/${OrganizationAuth1.CSID}/items/${Org1.CSID}/authorityrefs + + + authrefs/res/foo.res.xml + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/authrefsSimple2.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/authrefsSimple2.xml index 8fab390db..e9e1925cb 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/authrefsSimple2.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/authrefsSimple2.xml @@ -1,62 +1,62 @@ - - - - - - POST - /cspace-services/personauthorities/ - authrefs/newPersonAuthority.xml - - - POST - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ - authrefs/newPerson1.xml - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID} - - - - POST - /cspace-services/loansin/ - authrefs/loanin.xml - - 42 - ${GetPerson1.got("//refName")} - - - - - GET - /cspace-services/loansin/${loanin1.CSID}/ - - - authrefs/res/foo.res.xml - - - - - GET - /cspace-services/loansin/${loanin1.CSID}/authorityrefs - - - authrefs/res/foo.res.xml - - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}/refObjs - - - authrefs/res/refObjs.res.xml - - - - - + + + + + + POST + /cspace-services/personauthorities/ + authrefs/newPersonAuthority.xml + + + POST + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ + authrefs/newPerson1.xml + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID} + + + + POST + /cspace-services/loansin/ + authrefs/loanin.xml + + 42 + ${GetPerson1.got("//refName")} + + + + + GET + /cspace-services/loansin/${loanin1.CSID}/ + + + authrefs/res/foo.res.xml + + + + + GET + /cspace-services/loansin/${loanin1.CSID}/authorityrefs + + + authrefs/res/foo.res.xml + + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}/refObjs + + + authrefs/res/refObjs.res.xml + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/loanin.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/loanin.xml index dc8d5f4f2..20321e132 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/loanin.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/loanin.xml @@ -1,15 +1,15 @@ - - - - loaninNumber-${loannum} - - - October 29, 2009 - ${person} - - - For Surfboards of the 1960s exhibition. - Loan in conditions. - - + + + + loaninNumber-${loannum} + + + October 29, 2009 + ${person} + + + For Surfboards of the 1960s exhibition. + Loan in conditions. + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/newPerson.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/newPerson.xml index 01634aa30..b011e8122 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/newPerson.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/newPerson.xml @@ -1,21 +1,21 @@ - - - - 4a6dc8f3-3329-4c5d-a1a8 - connieContactPerson - urn:cspace:org.collectionspace.demo:personauthority:name(TestPersonAuth)'TestPersonAuth':person:name(connieContactPerson) - - - - Connie ContactPerson - false - Connie ContactPerson - ${termStatus} - Connie - ContactPerson - - - + + + + 4a6dc8f3-3329-4c5d-a1a8 + connieContactPerson + urn:cspace:org.collectionspace.demo:personauthority:name(TestPersonAuth)'TestPersonAuth':person:name(connieContactPerson) + + + + Connie ContactPerson + false + Connie ContactPerson + ${termStatus} + Connie + ContactPerson + + + \ No newline at end of file diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/newPerson1.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/newPerson1.xml index 308cf1215..82b75401d 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/newPerson1.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/newPerson1.xml @@ -1,18 +1,18 @@ - - - - connieContactPerson - - - - Connie ContactPerson - false - Connie ContactPerson - ${termStatus} - Connie - ContactPerson - - - - - + + + + connieContactPerson + + + + Connie ContactPerson + false + Connie ContactPerson + ${termStatus} + Connie + ContactPerson + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/newPerson2.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/newPerson2.xml index 610c72e45..16f889aa4 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/newPerson2.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/newPerson2.xml @@ -1,18 +1,18 @@ - - - - debbieDoNothingPerson - - - - Debbie DoNothingPerson - false - Debbie DoNothingPerson - ${termStatus} - Debbie - DoNothingPerson - - - - - + + + + debbieDoNothingPerson + + + + Debbie DoNothingPerson + false + Debbie DoNothingPerson + ${termStatus} + Debbie + DoNothingPerson + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/newPersonAuthority.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/newPersonAuthority.xml index 86f4d56be..86a8b4048 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/newPersonAuthority.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/newPersonAuthority.xml @@ -1,8 +1,8 @@ - - - - TestPersonAuth - TestPersonAuth - PersonAuthority - - + + + + TestPersonAuth + TestPersonAuth + PersonAuthority + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/organizations_common.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/organizations_common.xml index 0b392fdd4..54ba92617 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/organizations_common.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/organizations_common.xml @@ -1,46 +1,46 @@ - - - - 1288047801161 - - - - - Test Organization-1288047801161 - - - - - false - Test Organization Name - - - - - - - - - ${person1} - ${person2} - - Anytown, USA - - urn:cspace:org.collectionspace.demo:orgauthority:name(1288047801161):organization:name(1288047803708) - - - My new function - My second function - - - My new group - My second group - My third group - - This is a test Authority item - Some mythical book - Let's say page 39 - - - + + + + 1288047801161 + + + + + Test Organization-1288047801161 + + + + + false + Test Organization Name + + + + + + + + + ${person1} + ${person2} + + Anytown, USA + + urn:cspace:org.collectionspace.demo:orgauthority:name(1288047801161):organization:name(1288047803708) + + + My new function + My second function + + + My new group + My second group + My third group + + This is a test Authority item + Some mythical book + Let's say page 39 + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/orgauthorities_common.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/orgauthorities_common.xml index 0fef4cf3e..9f13ff011 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/orgauthorities_common.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/orgauthorities_common.xml @@ -1,11 +1,11 @@ - - - - 1288047801161 - TestOrgAuth-1288047801161 - OrgAuthority - This is a test authority - Some mythical book - - + + + + 1288047801161 + TestOrgAuth-1288047801161 + OrgAuthority + This is a test authority + Some mythical book + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/res/refObjs.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/res/refObjs.res.xml index 635f8dbe4..a0ae9e497 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/res/refObjs.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/res/refObjs.res.xml @@ -1,6 +1,6 @@ - - - 1 - 1 - + + + 1 + 1 + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/updatePerson1.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/updatePerson1.xml index ff4147715..f1730403f 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/updatePerson1.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/updatePerson1.xml @@ -1,18 +1,18 @@ - - - - connieContactPerson - - - - Connie ContactPerson - false - Connie ContactPerson - ${termStatus} - Connie - ContactPersonlity - - - - - + + + + connieContactPerson + + + + Connie ContactPerson + false + Connie ContactPerson + ${termStatus} + Connie + ContactPersonlity + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/updatePerson2.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/updatePerson2.xml index 89508b600..824664b1c 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/updatePerson2.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/authrefs/updatePerson2.xml @@ -1,18 +1,18 @@ - - - - debbieDoNothingPerson - - - - Debbie DoNothingPerson - false - Debbie DoNothingPerson - ${termStatus} - Debbie - Do Nothing Personality - - - - - + + + + debbieDoNothingPerson + + + + Debbie DoNothingPerson + false + Debbie DoNothingPerson + ${termStatus} + Debbie + Do Nothing Personality + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-create-updateobjloc-nocontext.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-create-updateobjloc-nocontext.xml index c6253a472..8f0cfd627 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-create-updateobjloc-nocontext.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-create-updateobjloc-nocontext.xml @@ -1,17 +1,17 @@ - - - - TestUpdateObjectLocationBatchJob - - CollectionObject - - true - true - true - true - false - org.collectionspace.services.batch.nuxeo.UpdateObjectLocationBatchJob - - + + + + TestUpdateObjectLocationBatchJob + + CollectionObject + + true + true + true + true + false + org.collectionspace.services.batch.nuxeo.UpdateObjectLocationBatchJob + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-create-updateobjloc.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-create-updateobjloc.xml index 7e47ad688..b200bc950 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-create-updateobjloc.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-create-updateobjloc.xml @@ -1,17 +1,17 @@ - - - - TestUpdateObjectLocationBatchJob - - CollectionObject - - true - true - true - false - false - org.collectionspace.services.batch.nuxeo.UpdateObjectLocationBatchJob - - + + + + TestUpdateObjectLocationBatchJob + + CollectionObject + + true + true + true + false + false + org.collectionspace.services.batch.nuxeo.UpdateObjectLocationBatchJob + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-invoke-updateobjloc-group.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-invoke-updateobjloc-group.xml index 9d060f20f..e763789eb 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-invoke-updateobjloc-group.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-invoke-updateobjloc-group.xml @@ -1,13 +1,13 @@ - - - group - CollectionObject - - ${groupCSID} - - - - - + + + group + CollectionObject + + ${groupCSID} + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-invoke-updateobjloc-list.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-invoke-updateobjloc-list.xml index 4ca90476f..d64d11039 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-invoke-updateobjloc-list.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-invoke-updateobjloc-list.xml @@ -1,21 +1,21 @@ - - - list - CollectionObject - - - - ${collectionObject1CSID} - ${collectionObject2CSID} - - - - some key - some value - - - - - + + + list + CollectionObject + + + + ${collectionObject1CSID} + ${collectionObject2CSID} + + + + some key + some value + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-invoke-updateobjloc-nocontext.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-invoke-updateobjloc-nocontext.xml index 74d7b17d7..7d191dfed 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-invoke-updateobjloc-nocontext.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-invoke-updateobjloc-nocontext.xml @@ -1,13 +1,13 @@ - - - nocontext - CollectionObject - - - - - - - + + + nocontext + CollectionObject + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-invoke-updateobjloc-single.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-invoke-updateobjloc-single.xml index beb1ccfa1..4eba76d87 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-invoke-updateobjloc-single.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-invoke-updateobjloc-single.xml @@ -1,13 +1,13 @@ - - - single - CollectionObject - ${collectionObjectCSID} - - - - - - + + + single + CollectionObject + ${collectionObjectCSID} + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-update-object-loc.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-update-object-loc.xml index 439cc9e4b..ec9577b47 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-update-object-loc.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch-update-object-loc.xml @@ -1,1039 +1,1039 @@ - - - - - YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= - YWRtaW5AbGlmZXNjaS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= - - - - - - - - - - - POST - /cspace-services/batch - batch/batch-create-updateobjloc.xml - 201 - - - - POST - /cspace-services/collectionobjects - batch/collObj1.xml - 201 - - - - POST - /cspace-services/movements - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Seattle1358215545509)'Seattle, WA, USA' - 1900-01-01 - - 201 - - - - - - - - POST - /cspace-services/movements - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Portland1358215545512)'Portland, OR, USA' - 2000-01-01 - - 201 - - - - POST - /cspace-services/movements - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Victoria1358215545515)'Victoria, BC, Canada' - 1800-01-01 - - 201 - - - - POST - /cspace-services/relations - batch/relation.xml - - ${createCollectionObject.CSID} - CollectionObject - ${createMovement1.CSID} - Movement - - 201 - - - - POST - /cspace-services/relations - batch/relation.xml - - ${createCollectionObject.CSID} - CollectionObject - ${createMovement2.CSID} - Movement - - 201 - - - - POST - /cspace-services/relations - batch/relation.xml - - ${createCollectionObject.CSID} - CollectionObject - ${createMovement3.CSID} - Movement - - 201 - - - - - - POST - /cspace-services/batch/${createBatchRecord.CSID} - batch/batch-invoke-updateobjloc-single.xml - - ${createCollectionObject.CSID} - - 200 - - - - - - - - GET - /cspace-services/collectionobjects/${createCollectionObject.CSID} - batch/updateobjloc.xml - - - batch/res/collectionobject.res.xml - - ${createMovement2.currentLocation} - - - 200 - - - - - - - - - - POST - /cspace-services/movements - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Vancouver1358215545518)'Vancouver, BC, Canada' - 2100-01-01 - - 201 - - - - - - - POST - /cspace-services/relations - batch/relation.xml - - ${createMovement4.CSID} - Movement - ${createCollectionObject.CSID} - CollectionObject - - 201 - - - - POST - /cspace-services/batch/${createBatchRecord.CSID} - batch/batch-invoke-updateobjloc-single.xml - - ${createCollectionObject.CSID} - - 200 - - - - GET - /cspace-services/collectionobjects/${createCollectionObject.CSID} - batch/updateobjloc.xml - - - batch/res/collectionobject.res.xml - - ${createMovement4.currentLocation} - - - 200 - - - - - - PUT - /cspace-services/movements/${createMovement4.CSID}/workflow/delete - 200 - - - - - - relation/res/workflowState.res.xml - - deleted - - - - - POST - /cspace-services/batch/${createBatchRecord.CSID} - batch/batch-invoke-updateobjloc-single.xml - - ${createCollectionObject.CSID} - - 200 - - - - - - GET - /cspace-services/collectionobjects/${createCollectionObject.CSID} - batch/updateobjloc.xml - - - batch/res/collectionobject.res.xml - - ${createMovement2.currentLocation} - - - 200 - - - - - - - - - DELETE - /cspace-services/movements/${createMovement2.CSID} - 200 - - - - - PUT - /cspace-services/collectionobjects/${createCollectionObject.CSID}/workflow/delete - 200 - relation/res/workflowState.res.xml - - deleted - - - - - POST - /cspace-services/batch/${createBatchRecord.CSID} - batch/batch-invoke-updateobjloc-single.xml - - ${createCollectionObject.CSID} - - 200 - - - - - - GET - /cspace-services/collectionobjects/${createCollectionObject.CSID} - batch/updateobjloc.xml - - - batch/res/collectionobject.res.xml - - ${createMovement2.currentLocation} - - - 200 - - - - - - - - POST - /cspace-services/batch - batch/batch-create-updateobjloc.xml - 201 - - - - POST - /cspace-services/collectionobjects - batch/collObj1.xml - 201 - - - - POST - /cspace-services/movements - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Olympia1358215545521)'Olympia, WA, USA' - 1900-01-01 - - 201 - - - - POST - /cspace-services/movements - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Ottawa1358215545567)'Ottawa, ON, Canada' - ${createMovement1WithTiebreaker.locationDate} - - 201 - - - - POST - /cspace-services/movements - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Spokane1358215545524)'Spokane, WA, USA' - ${createMovement1WithTiebreaker.locationDate} - - 201 - - - - POST - /cspace-services/relations - batch/relation.xml - - ${createCollectionObjectWithTiebreaker.CSID} - CollectionObject - ${createMovement1WithTiebreaker.CSID} - Movement - - 201 - - - - POST - /cspace-services/relations - batch/relation.xml - - ${createCollectionObjectWithTiebreaker.CSID} - CollectionObject - ${createMovement2WithTiebreaker.CSID} - Movement - - 201 - - - - POST - /cspace-services/relations - batch/relation.xml - - ${createCollectionObjectWithTiebreaker.CSID} - CollectionObject - ${createMovement3WithTiebreaker.CSID} - Movement - - 201 - - - - PUT - /cspace-services/movements/${createMovement1WithTiebreaker.CSID} - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Guadalajara13582155455562)'Guadalajara, Mexico' - ${createMovement1WithTiebreaker.locationDate} - - 200 - - - - POST - /cspace-services/batch/${createBatchRecordWithTiebreaker.CSID} - batch/batch-invoke-updateobjloc-single.xml - - ${createCollectionObjectWithTiebreaker.CSID} - - 200 - - - - - - - - - - GET - /cspace-services/collectionobjects/${createCollectionObjectWithTiebreaker.CSID} - batch/updateobjloc.xml - - - batch/res/collectionobject.res.xml - - ${modifyMovement1WithTiebreaker.currentLocation} - - - 200 - - - - PUT - /cspace-services/movements/${createMovement2WithTiebreaker.CSID} - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Ecatepec13582155455560)'Ecatepec, Mexico' - ${createMovement1WithTiebreaker.locationDate} - - 200 - - - - POST - /cspace-services/batch/${createBatchRecordWithTiebreaker.CSID} - batch/batch-invoke-updateobjloc-single.xml - - ${createCollectionObjectWithTiebreaker.CSID} - - 200 - - - - GET - /cspace-services/collectionobjects/${createCollectionObjectWithTiebreaker.CSID} - batch/updateobjloc.xml - - - batch/res/collectionobject.res.xml - - ${modifyMovement2WithTiebreaker.currentLocation} - - - 200 - - - - PUT - /cspace-services/movements/${createMovement3WithTiebreaker.CSID} - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Calgary1358215545564)'Calgary, AB, Canada' - ${createMovement1WithTiebreaker.locationDate} - - 200 - - - - POST - /cspace-services/batch/${createBatchRecordWithTiebreaker.CSID} - batch/batch-invoke-updateobjloc-single.xml - - ${createCollectionObjectWithTiebreaker.CSID} - - 200 - - - - GET - /cspace-services/collectionobjects/${createCollectionObjectWithTiebreaker.CSID} - batch/updateobjloc.xml - - - batch/res/collectionobject.res.xml - - ${modifyMovement3WithTiebreaker.currentLocation} - - - 200 - - - - - - - - POST - /cspace-services/batch - batch/batch-create-updateobjloc.xml - 201 - - - - POST - /cspace-services/collectionobjects - batch/collObj1.xml - 201 - - - - POST - /cspace-services/collectionobjects - batch/collObj1.xml - 201 - - - - POST - /cspace-services/movements - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Winnipeg13582155455568)'Winnipeg, MB, Canada' - 1900-01-01 - - 201 - - - - POST - /cspace-services/movements - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Saskatoon13582155455570)'Saskatoon, SK, Canada' - 2000-01-01 - - 201 - - - - POST - /cspace-services/movements - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Montreal13582155455570)'Montreal, QC, Canada' - 1800-01-01 - - 201 - - - - POST - /cspace-services/relations - batch/relation.xml - - ${createCollectionObject1.CSID} - CollectionObject - ${createMovement1.CSID} - Movement - - 201 - - - - POST - /cspace-services/relations - batch/relation.xml - - ${createCollectionObject1.CSID} - CollectionObject - ${createMovement2.CSID} - Movement - - 201 - - - - POST - /cspace-services/relations - batch/relation.xml - - ${createCollectionObject2.CSID} - CollectionObject - ${createMovement3.CSID} - Movement - - 201 - - - - POST - /cspace-services/batch/${createBatchRecord.CSID} - batch/batch-invoke-updateobjloc-list.xml - - ${createCollectionObject1.CSID} - ${createCollectionObject2.CSID} - - 200 - - - - - - GET - /cspace-services/collectionobjects/${createCollectionObject1.CSID} - batch/updateobjloc.xml - - - batch/res/collectionobject.res.xml - - ${createMovement2.currentLocation} - - - 200 - - - - - - GET - /cspace-services/collectionobjects/${createCollectionObject2.CSID} - batch/updateobjloc.xml - - - batch/res/collectionobject.res.xml - - ${createMovement3.currentLocation} - - - 200 - - - - - - - - POST - /cspace-services/batch - batch/batch-create-updateobjloc.xml - 201 - - - - POST - /cspace-services/collectionobjects - batch/collObj1.xml - 201 - - - - POST - /cspace-services/collectionobjects - batch/collObj1.xml - 201 - - - - POST - /cspace-services/movements - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Eugene13582155455572)'Eugene, OR, USA' - 1900-01-01 - - 201 - - - - POST - /cspace-services/movements - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Salem13582155455574)'Salem, OR, USA' - 2000-01-01 - - 201 - - - - POST - /cspace-services/movements - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Gresham13582155455574)'Gresham, OR, USA' - 1800-01-01 - - 201 - - - - POST - /cspace-services/relations - batch/relation.xml - - ${createCollectionObject1.CSID} - CollectionObject - ${createMovement1.CSID} - Movement - - 201 - - - - POST - /cspace-services/relations - batch/relation.xml - - ${createMovement2.CSID} - Movement - ${createCollectionObject1.CSID} - CollectionObject - - 201 - - - - POST - /cspace-services/relations - batch/relation.xml - - ${createCollectionObject2.CSID} - CollectionObject - ${createMovement3.CSID} - Movement - - 201 - - - - POST - /cspace-services/groups - batch/group.xml - 201 - - - - POST - /cspace-services/relations - batch/relation.xml - - ${createCollectionObject1.CSID} - CollectionObject - ${createGroup.CSID} - Group - - 201 - - - - POST - /cspace-services/relations - batch/relation.xml - - ${createCollectionObject2.CSID} - CollectionObject - ${createGroup.CSID} - Group - - 201 - - - - POST - /cspace-services/batch/${createBatchRecord.CSID} - batch/batch-invoke-updateobjloc-group.xml - - ${createGroup.CSID} - - 200 - - - - - - GET - /cspace-services/collectionobjects/${createCollectionObject1.CSID} - batch/updateobjloc.xml - - - batch/res/collectionobject.res.xml - - ${createMovement2.currentLocation} - - - 200 - - - - - - GET - /cspace-services/collectionobjects/${createCollectionObject2.CSID} - batch/updateobjloc.xml - - - batch/res/collectionobject.res.xml - - ${createMovement3.currentLocation} - - - 200 - - - - - - - - - - - POST - /cspace-services/batch - batch/batch-create-updateobjloc.xml - 201 - - - - POST - /cspace-services/collectionobjects - batch/collObj1.xml - 201 - - - - POST - /cspace-services/movements - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Ecatepec13582155455560)'Ecatepec, Mexico' - 2000-01-01 - - 201 - - - - POST - /cspace-services/relations - batch/relation.xml - - ${createCollectionObjectInVersioningTenant.CSID} - CollectionObject - ${createMovementInVersioningTenant.CSID} - Movement - - 201 - - - - - - POST - /cspace-services/batch/${createBatchRecordInVersioningTenant.CSID} - batch/batch-invoke-updateobjloc-single.xml - - ${createCollectionObjectInVersioningTenant.CSID} - - 200 - - - - GET - /cspace-services/collectionobjects/${createCollectionObjectInVersioningTenant.CSID} - - - batch/res/collectionobject.res.xml - - ${createMovementInVersioningTenant.currentLocation} - - - 200 - - - - PUT - /cspace-services/movements/${createMovementInVersioningTenant.CSID} - batch/movement.xml - - urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Guadalajara13582155455562)'Guadalajara, Mexico' - 2000-01-02 - - 200 - - - - POST - /cspace-services/batch/${createBatchRecordInVersioningTenant.CSID} - batch/batch-invoke-updateobjloc-single.xml - - ${createCollectionObjectInVersioningTenant.CSID} - - 200 - - - - GET - /cspace-services/collectionobjects/${createCollectionObjectInVersioningTenant.CSID} - - - batch/res/collectionobject.res.xml - - ${modifyMovementInVersioningTenant.currentLocation} - - - 200 - - - - - - - - - - + + + + + YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= + YWRtaW5AbGlmZXNjaS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= + + + + + + + + + + + POST + /cspace-services/batch + batch/batch-create-updateobjloc.xml + 201 + + + + POST + /cspace-services/collectionobjects + batch/collObj1.xml + 201 + + + + POST + /cspace-services/movements + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Seattle1358215545509)'Seattle, WA, USA' + 1900-01-01 + + 201 + + + + + + + + POST + /cspace-services/movements + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Portland1358215545512)'Portland, OR, USA' + 2000-01-01 + + 201 + + + + POST + /cspace-services/movements + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Victoria1358215545515)'Victoria, BC, Canada' + 1800-01-01 + + 201 + + + + POST + /cspace-services/relations + batch/relation.xml + + ${createCollectionObject.CSID} + CollectionObject + ${createMovement1.CSID} + Movement + + 201 + + + + POST + /cspace-services/relations + batch/relation.xml + + ${createCollectionObject.CSID} + CollectionObject + ${createMovement2.CSID} + Movement + + 201 + + + + POST + /cspace-services/relations + batch/relation.xml + + ${createCollectionObject.CSID} + CollectionObject + ${createMovement3.CSID} + Movement + + 201 + + + + + + POST + /cspace-services/batch/${createBatchRecord.CSID} + batch/batch-invoke-updateobjloc-single.xml + + ${createCollectionObject.CSID} + + 200 + + + + + + + + GET + /cspace-services/collectionobjects/${createCollectionObject.CSID} + batch/updateobjloc.xml + + + batch/res/collectionobject.res.xml + + ${createMovement2.currentLocation} + + + 200 + + + + + + + + + + POST + /cspace-services/movements + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Vancouver1358215545518)'Vancouver, BC, Canada' + 2100-01-01 + + 201 + + + + + + + POST + /cspace-services/relations + batch/relation.xml + + ${createMovement4.CSID} + Movement + ${createCollectionObject.CSID} + CollectionObject + + 201 + + + + POST + /cspace-services/batch/${createBatchRecord.CSID} + batch/batch-invoke-updateobjloc-single.xml + + ${createCollectionObject.CSID} + + 200 + + + + GET + /cspace-services/collectionobjects/${createCollectionObject.CSID} + batch/updateobjloc.xml + + + batch/res/collectionobject.res.xml + + ${createMovement4.currentLocation} + + + 200 + + + + + + PUT + /cspace-services/movements/${createMovement4.CSID}/workflow/delete + 200 + + + + + + relation/res/workflowState.res.xml + + deleted + + + + + POST + /cspace-services/batch/${createBatchRecord.CSID} + batch/batch-invoke-updateobjloc-single.xml + + ${createCollectionObject.CSID} + + 200 + + + + + + GET + /cspace-services/collectionobjects/${createCollectionObject.CSID} + batch/updateobjloc.xml + + + batch/res/collectionobject.res.xml + + ${createMovement2.currentLocation} + + + 200 + + + + + + + + + DELETE + /cspace-services/movements/${createMovement2.CSID} + 200 + + + + + PUT + /cspace-services/collectionobjects/${createCollectionObject.CSID}/workflow/delete + 200 + relation/res/workflowState.res.xml + + deleted + + + + + POST + /cspace-services/batch/${createBatchRecord.CSID} + batch/batch-invoke-updateobjloc-single.xml + + ${createCollectionObject.CSID} + + 200 + + + + + + GET + /cspace-services/collectionobjects/${createCollectionObject.CSID} + batch/updateobjloc.xml + + + batch/res/collectionobject.res.xml + + ${createMovement2.currentLocation} + + + 200 + + + + + + + + POST + /cspace-services/batch + batch/batch-create-updateobjloc.xml + 201 + + + + POST + /cspace-services/collectionobjects + batch/collObj1.xml + 201 + + + + POST + /cspace-services/movements + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Olympia1358215545521)'Olympia, WA, USA' + 1900-01-01 + + 201 + + + + POST + /cspace-services/movements + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Ottawa1358215545567)'Ottawa, ON, Canada' + ${createMovement1WithTiebreaker.locationDate} + + 201 + + + + POST + /cspace-services/movements + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Spokane1358215545524)'Spokane, WA, USA' + ${createMovement1WithTiebreaker.locationDate} + + 201 + + + + POST + /cspace-services/relations + batch/relation.xml + + ${createCollectionObjectWithTiebreaker.CSID} + CollectionObject + ${createMovement1WithTiebreaker.CSID} + Movement + + 201 + + + + POST + /cspace-services/relations + batch/relation.xml + + ${createCollectionObjectWithTiebreaker.CSID} + CollectionObject + ${createMovement2WithTiebreaker.CSID} + Movement + + 201 + + + + POST + /cspace-services/relations + batch/relation.xml + + ${createCollectionObjectWithTiebreaker.CSID} + CollectionObject + ${createMovement3WithTiebreaker.CSID} + Movement + + 201 + + + + PUT + /cspace-services/movements/${createMovement1WithTiebreaker.CSID} + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Guadalajara13582155455562)'Guadalajara, Mexico' + ${createMovement1WithTiebreaker.locationDate} + + 200 + + + + POST + /cspace-services/batch/${createBatchRecordWithTiebreaker.CSID} + batch/batch-invoke-updateobjloc-single.xml + + ${createCollectionObjectWithTiebreaker.CSID} + + 200 + + + + + + + + + + GET + /cspace-services/collectionobjects/${createCollectionObjectWithTiebreaker.CSID} + batch/updateobjloc.xml + + + batch/res/collectionobject.res.xml + + ${modifyMovement1WithTiebreaker.currentLocation} + + + 200 + + + + PUT + /cspace-services/movements/${createMovement2WithTiebreaker.CSID} + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Ecatepec13582155455560)'Ecatepec, Mexico' + ${createMovement1WithTiebreaker.locationDate} + + 200 + + + + POST + /cspace-services/batch/${createBatchRecordWithTiebreaker.CSID} + batch/batch-invoke-updateobjloc-single.xml + + ${createCollectionObjectWithTiebreaker.CSID} + + 200 + + + + GET + /cspace-services/collectionobjects/${createCollectionObjectWithTiebreaker.CSID} + batch/updateobjloc.xml + + + batch/res/collectionobject.res.xml + + ${modifyMovement2WithTiebreaker.currentLocation} + + + 200 + + + + PUT + /cspace-services/movements/${createMovement3WithTiebreaker.CSID} + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Calgary1358215545564)'Calgary, AB, Canada' + ${createMovement1WithTiebreaker.locationDate} + + 200 + + + + POST + /cspace-services/batch/${createBatchRecordWithTiebreaker.CSID} + batch/batch-invoke-updateobjloc-single.xml + + ${createCollectionObjectWithTiebreaker.CSID} + + 200 + + + + GET + /cspace-services/collectionobjects/${createCollectionObjectWithTiebreaker.CSID} + batch/updateobjloc.xml + + + batch/res/collectionobject.res.xml + + ${modifyMovement3WithTiebreaker.currentLocation} + + + 200 + + + + + + + + POST + /cspace-services/batch + batch/batch-create-updateobjloc.xml + 201 + + + + POST + /cspace-services/collectionobjects + batch/collObj1.xml + 201 + + + + POST + /cspace-services/collectionobjects + batch/collObj1.xml + 201 + + + + POST + /cspace-services/movements + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Winnipeg13582155455568)'Winnipeg, MB, Canada' + 1900-01-01 + + 201 + + + + POST + /cspace-services/movements + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Saskatoon13582155455570)'Saskatoon, SK, Canada' + 2000-01-01 + + 201 + + + + POST + /cspace-services/movements + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Montreal13582155455570)'Montreal, QC, Canada' + 1800-01-01 + + 201 + + + + POST + /cspace-services/relations + batch/relation.xml + + ${createCollectionObject1.CSID} + CollectionObject + ${createMovement1.CSID} + Movement + + 201 + + + + POST + /cspace-services/relations + batch/relation.xml + + ${createCollectionObject1.CSID} + CollectionObject + ${createMovement2.CSID} + Movement + + 201 + + + + POST + /cspace-services/relations + batch/relation.xml + + ${createCollectionObject2.CSID} + CollectionObject + ${createMovement3.CSID} + Movement + + 201 + + + + POST + /cspace-services/batch/${createBatchRecord.CSID} + batch/batch-invoke-updateobjloc-list.xml + + ${createCollectionObject1.CSID} + ${createCollectionObject2.CSID} + + 200 + + + + + + GET + /cspace-services/collectionobjects/${createCollectionObject1.CSID} + batch/updateobjloc.xml + + + batch/res/collectionobject.res.xml + + ${createMovement2.currentLocation} + + + 200 + + + + + + GET + /cspace-services/collectionobjects/${createCollectionObject2.CSID} + batch/updateobjloc.xml + + + batch/res/collectionobject.res.xml + + ${createMovement3.currentLocation} + + + 200 + + + + + + + + POST + /cspace-services/batch + batch/batch-create-updateobjloc.xml + 201 + + + + POST + /cspace-services/collectionobjects + batch/collObj1.xml + 201 + + + + POST + /cspace-services/collectionobjects + batch/collObj1.xml + 201 + + + + POST + /cspace-services/movements + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Eugene13582155455572)'Eugene, OR, USA' + 1900-01-01 + + 201 + + + + POST + /cspace-services/movements + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Salem13582155455574)'Salem, OR, USA' + 2000-01-01 + + 201 + + + + POST + /cspace-services/movements + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Gresham13582155455574)'Gresham, OR, USA' + 1800-01-01 + + 201 + + + + POST + /cspace-services/relations + batch/relation.xml + + ${createCollectionObject1.CSID} + CollectionObject + ${createMovement1.CSID} + Movement + + 201 + + + + POST + /cspace-services/relations + batch/relation.xml + + ${createMovement2.CSID} + Movement + ${createCollectionObject1.CSID} + CollectionObject + + 201 + + + + POST + /cspace-services/relations + batch/relation.xml + + ${createCollectionObject2.CSID} + CollectionObject + ${createMovement3.CSID} + Movement + + 201 + + + + POST + /cspace-services/groups + batch/group.xml + 201 + + + + POST + /cspace-services/relations + batch/relation.xml + + ${createCollectionObject1.CSID} + CollectionObject + ${createGroup.CSID} + Group + + 201 + + + + POST + /cspace-services/relations + batch/relation.xml + + ${createCollectionObject2.CSID} + CollectionObject + ${createGroup.CSID} + Group + + 201 + + + + POST + /cspace-services/batch/${createBatchRecord.CSID} + batch/batch-invoke-updateobjloc-group.xml + + ${createGroup.CSID} + + 200 + + + + + + GET + /cspace-services/collectionobjects/${createCollectionObject1.CSID} + batch/updateobjloc.xml + + + batch/res/collectionobject.res.xml + + ${createMovement2.currentLocation} + + + 200 + + + + + + GET + /cspace-services/collectionobjects/${createCollectionObject2.CSID} + batch/updateobjloc.xml + + + batch/res/collectionobject.res.xml + + ${createMovement3.currentLocation} + + + 200 + + + + + + + + + + + POST + /cspace-services/batch + batch/batch-create-updateobjloc.xml + 201 + + + + POST + /cspace-services/collectionobjects + batch/collObj1.xml + 201 + + + + POST + /cspace-services/movements + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Ecatepec13582155455560)'Ecatepec, Mexico' + 2000-01-01 + + 201 + + + + POST + /cspace-services/relations + batch/relation.xml + + ${createCollectionObjectInVersioningTenant.CSID} + CollectionObject + ${createMovementInVersioningTenant.CSID} + Movement + + 201 + + + + + + POST + /cspace-services/batch/${createBatchRecordInVersioningTenant.CSID} + batch/batch-invoke-updateobjloc-single.xml + + ${createCollectionObjectInVersioningTenant.CSID} + + 200 + + + + GET + /cspace-services/collectionobjects/${createCollectionObjectInVersioningTenant.CSID} + + + batch/res/collectionobject.res.xml + + ${createMovementInVersioningTenant.currentLocation} + + + 200 + + + + PUT + /cspace-services/movements/${createMovementInVersioningTenant.CSID} + batch/movement.xml + + urn:cspace:core.collectionspace.org:locationauthorities:name(offsite_sla):item:name(Guadalajara13582155455562)'Guadalajara, Mexico' + 2000-01-02 + + 200 + + + + POST + /cspace-services/batch/${createBatchRecordInVersioningTenant.CSID} + batch/batch-invoke-updateobjloc-single.xml + + ${createCollectionObjectInVersioningTenant.CSID} + + 200 + + + + GET + /cspace-services/collectionobjects/${createCollectionObjectInVersioningTenant.CSID} + + + batch/res/collectionobject.res.xml + + ${modifyMovementInVersioningTenant.currentLocation} + + + 200 + + + + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch.xml index 91c22683c..59981205a 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch.xml @@ -1,79 +1,79 @@ - - - - - YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= - - - - POST - /cspace-services/batch/ - batch/batch1.xml - - - POST - /cspace-services/batch/ - batch/batch1.xml - - - POST - /cspace-services/collectionobjects/ - batch/collObj1.xml - - - POST - /cspace-services/batch/${createBatch1.CSID} - batch/batchInvContextSingle.xml - - ${createBatch.CSID} - - - - POST - /cspace-services/batch/${createBatch1.CSID} - batch/batchInvContextList.xml - - ${createBatch.CSID} - - - - POST - 400 - /cspace-services/batch/${createBatch1.CSID} - batch/batchBadInvContext.xml - - ${createBatch.CSID} - - - - POST - 400 - /cspace-services/batch/${createBatch1.CSID} - batch/batchBadInvContextList.xml - - ${createBatch.CSID} - - - - GET - /cspace-services/batch?doctype=CollectionObject&inv=single - - - GET - /cspace-services/batch?doctype=Intake&inv=group - - - - - + + + + + YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= + + + + POST + /cspace-services/batch/ + batch/batch1.xml + + + POST + /cspace-services/batch/ + batch/batch1.xml + + + POST + /cspace-services/collectionobjects/ + batch/collObj1.xml + + + POST + /cspace-services/batch/${createBatch1.CSID} + batch/batchInvContextSingle.xml + + ${createBatch.CSID} + + + + POST + /cspace-services/batch/${createBatch1.CSID} + batch/batchInvContextList.xml + + ${createBatch.CSID} + + + + POST + 400 + /cspace-services/batch/${createBatch1.CSID} + batch/batchBadInvContext.xml + + ${createBatch.CSID} + + + + POST + 400 + /cspace-services/batch/${createBatch1.CSID} + batch/batchBadInvContextList.xml + + ${createBatch.CSID} + + + + GET + /cspace-services/batch?doctype=CollectionObject&inv=single + + + GET + /cspace-services/batch?doctype=Intake&inv=group + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch1.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch1.xml index 6c66e7717..bc3cc1093 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch1.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch1.xml @@ -1,16 +1,16 @@ - - - - TestCreateAndLinkLoanOutBatchJob - This should be interesting - - CollectionObject - - true - true - true - org.collectionspace.services.batch.nuxeo.CreateAndLinkLoanOutBatchJob - - + + + + TestCreateAndLinkLoanOutBatchJob + This should be interesting + + CollectionObject + + true + true + true + org.collectionspace.services.batch.nuxeo.CreateAndLinkLoanOutBatchJob + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch1InvContext.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch1InvContext.xml index fb3ac7bb6..dc262c48f 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch1InvContext.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batch1InvContext.xml @@ -1,10 +1,10 @@ - - - single - CollectionObject - ${CollObj1} - - - + + + single + CollectionObject + ${CollObj1} + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batchBadInvContext.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batchBadInvContext.xml index f07f70890..6374d63a2 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batchBadInvContext.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batchBadInvContext.xml @@ -1,12 +1,12 @@ - - - garbage - CollectionObject - - ${CollObj1} - - - - + + + garbage + CollectionObject + + ${CollObj1} + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batchBadInvContextList.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batchBadInvContextList.xml index 007b010bc..4da3e959e 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batchBadInvContextList.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batchBadInvContextList.xml @@ -1,11 +1,11 @@ - - - list - CollectionObject - - - - - + + + list + CollectionObject + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batchInvContextList.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batchInvContextList.xml index 26b00693a..cb25db6d2 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batchInvContextList.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batchInvContextList.xml @@ -1,12 +1,12 @@ - - - list - CollectionObject - - ${CollObj1} - - - - + + + list + CollectionObject + + ${CollObj1} + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batchInvContextSingle.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batchInvContextSingle.xml index fb3ac7bb6..dc262c48f 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batchInvContextSingle.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/batch/batchInvContextSingle.xml @@ -1,10 +1,10 @@ - - - single - CollectionObject - ${CollObj1} - - - + + + single + CollectionObject + ${CollObj1} + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/bugs/nonlatin/non-latin-3.txt b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/bugs/nonlatin/non-latin-3.txt index ff06d2f62..9ee621bd0 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/bugs/nonlatin/non-latin-3.txt +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/bugs/nonlatin/non-latin-3.txt @@ -1 +1 @@ - ⺠, 0 1The β Source of All ψ Acquisitions + ⺠, 0 1The β Source of All ψ Acquisitions diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/bugs/nonlatin/non-latin-notes.txt b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/bugs/nonlatin/non-latin-notes.txt index 765ff9abc..190becb52 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/bugs/nonlatin/non-latin-notes.txt +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/bugs/nonlatin/non-latin-notes.txt @@ -1,27 +1,27 @@ -Here are the steps we tried: - -On nightly.collectionspace.org, which is running Nuxeo 5.3 with mysql - - Update a record through Nuxeo Web GUI, inserting a greek psi character. - ==> failure: able to edit record, but on read and edit again, character is tranformed into question mark. - -On nightly, we ran a SQL update and then a SQL dump on a table, and got the UTF8 non-Latin1 characters back. - ==> success: full round trip, from file.sql to MySQL to file.out . - Note that we used the UTF8 option on the command line: - - mysql -u cspace_user -p --default_character_set utf8 nuxeo < ~/acq.sql - - mysqldump -u cspace_user -p nuxeo acquisitions_common_acquisitionsources > acq.out - -On localhost which is running the older version of Nuxeo with mysql - - Update a record through Nuxeo Web GUI, inserting a greek psi character. - ==> success: able to read and edit record and see character. - - - -Notes: - Check the encoding of the DB: - mysql> SHOW VARIABLES LIKE 'character_set_database'; - - +Here are the steps we tried: + +On nightly.collectionspace.org, which is running Nuxeo 5.3 with mysql + + Update a record through Nuxeo Web GUI, inserting a greek psi character. + ==> failure: able to edit record, but on read and edit again, character is tranformed into question mark. + +On nightly, we ran a SQL update and then a SQL dump on a table, and got the UTF8 non-Latin1 characters back. + ==> success: full round trip, from file.sql to MySQL to file.out . + Note that we used the UTF8 option on the command line: + + mysql -u cspace_user -p --default_character_set utf8 nuxeo < ~/acq.sql + + mysqldump -u cspace_user -p nuxeo acquisitions_common_acquisitionsources > acq.out + +On localhost which is running the older version of Nuxeo with mysql + + Update a record through Nuxeo Web GUI, inserting a greek psi character. + ==> success: able to read and edit record and see character. + + + +Notes: + Check the encoding of the DB: + mysql> SHOW VARIABLES LIKE 'character_set_database'; + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/bugs/nonlatin/non-latin.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/bugs/nonlatin/non-latin.xml index 534d65f8f..0037268a1 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/bugs/nonlatin/non-latin.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/bugs/nonlatin/non-latin.xml @@ -1,19 +1,19 @@ - - - http://localhost:8280 - - - POST - /cspace-services/acquisitions/ - - - acq19-mod.xml - - - - GET - /cspace-services/acquisitions/ - 1001 - - - + + + http://localhost:8280 + + + POST + /cspace-services/acquisitions/ + + + acq19-mod.xml + + + + GET + /cspace-services/acquisitions/ + 1001 + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/bugs/nonlatin/utf-8-bug.txt b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/bugs/nonlatin/utf-8-bug.txt index 765ff9abc..190becb52 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/bugs/nonlatin/utf-8-bug.txt +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/bugs/nonlatin/utf-8-bug.txt @@ -1,27 +1,27 @@ -Here are the steps we tried: - -On nightly.collectionspace.org, which is running Nuxeo 5.3 with mysql - - Update a record through Nuxeo Web GUI, inserting a greek psi character. - ==> failure: able to edit record, but on read and edit again, character is tranformed into question mark. - -On nightly, we ran a SQL update and then a SQL dump on a table, and got the UTF8 non-Latin1 characters back. - ==> success: full round trip, from file.sql to MySQL to file.out . - Note that we used the UTF8 option on the command line: - - mysql -u cspace_user -p --default_character_set utf8 nuxeo < ~/acq.sql - - mysqldump -u cspace_user -p nuxeo acquisitions_common_acquisitionsources > acq.out - -On localhost which is running the older version of Nuxeo with mysql - - Update a record through Nuxeo Web GUI, inserting a greek psi character. - ==> success: able to read and edit record and see character. - - - -Notes: - Check the encoding of the DB: - mysql> SHOW VARIABLES LIKE 'character_set_database'; - - +Here are the steps we tried: + +On nightly.collectionspace.org, which is running Nuxeo 5.3 with mysql + + Update a record through Nuxeo Web GUI, inserting a greek psi character. + ==> failure: able to edit record, but on read and edit again, character is tranformed into question mark. + +On nightly, we ran a SQL update and then a SQL dump on a table, and got the UTF8 non-Latin1 characters back. + ==> success: full round trip, from file.sql to MySQL to file.out . + Note that we used the UTF8 option on the command line: + + mysql -u cspace_user -p --default_character_set utf8 nuxeo < ~/acq.sql + + mysqldump -u cspace_user -p nuxeo acquisitions_common_acquisitionsources > acq.out + +On localhost which is running the older version of Nuxeo with mysql + + Update a record through Nuxeo Web GUI, inserting a greek psi character. + ==> success: able to read and edit record and see character. + + + +Notes: + Check the encoding of the DB: + mysql> SHOW VARIABLES LIKE 'character_set_database'; + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/collectionobject/AuthRefsCollObj.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/collectionobject/AuthRefsCollObj.xml index b017bdc5b..2e34a4715 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/collectionobject/AuthRefsCollObj.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/collectionobject/AuthRefsCollObj.xml @@ -1,35 +1,35 @@ - - - - 1-1001 - PLS-2011.1 - - ethnography - - open - - - Sponsor - urn:cspace:org.collectionspace.demo:orgauthority:name(organization):organization:name(ucberkeley)'UC Berkeley' - - - Coding - urn:cspace:org.collectionspace.demo:orgauthority:name(organization):organization:name(ucberkeleyist)'UCB IST' - - - - - - urn:cspace:org.collectionspace.demo:personauthority:name(person):person:name(pschmitz)'Patrick Schmitz' - - - - A virtual object to check authRefs - - - - urn:cspace:org.collectionspace.demo:personauthority:name(person):person:name(pmadry)'Penelope Madry' - - nonTextualInscriptionGroupList> - - + + + + 1-1001 + PLS-2011.1 + + ethnography + + open + + + Sponsor + urn:cspace:org.collectionspace.demo:orgauthority:name(organization):organization:name(ucberkeley)'UC Berkeley' + + + Coding + urn:cspace:org.collectionspace.demo:orgauthority:name(organization):organization:name(ucberkeleyist)'UCB IST' + + + + + + urn:cspace:org.collectionspace.demo:personauthority:name(person):person:name(pschmitz)'Patrick Schmitz' + + + + A virtual object to check authRefs + + + + urn:cspace:org.collectionspace.demo:personauthority:name(person):person:name(pmadry)'Penelope Madry' + + nonTextualInscriptionGroupList> + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/collectionobject/nh-collectionobject.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/collectionobject/nh-collectionobject.xml index e11b3e34b..a19c93226 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/collectionobject/nh-collectionobject.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/collectionobject/nh-collectionobject.xml @@ -1,47 +1,47 @@ - - -objectNumber-1285644709375 - - -101.objectName-1285644709375 -integer - - -101.502.23.456.objectName-1285644709375 -ipaddress - - - -Papier mache bird cow mask with horns, painted red with black and yellow spots. Puerto Rico. ca. 8&quot; high, 6&quot; wide, projects 10&quot; (with horns). -Acrylic rabbit mask with wings, painted red with green and aquamarine spots. Puerto Rico. ca. 8&quot; high, 6&quot; wide, projects 10&quot; (with wings). - - - -an object name - - - -urn:org.collectionspace.services.department:Registrar -urn:org.walkerart.department:Fine Art - -title - - - - -length -head -cm -30 - - -width -leg -m -2.57 - - - - - - + + +objectNumber-1285644709375 + + +101.objectName-1285644709375 +integer + + +101.502.23.456.objectName-1285644709375 +ipaddress + + + +Papier mache bird cow mask with horns, painted red with black and yellow spots. Puerto Rico. ca. 8&quot; high, 6&quot; wide, projects 10&quot; (with horns). +Acrylic rabbit mask with wings, painted red with green and aquamarine spots. Puerto Rico. ca. 8&quot; high, 6&quot; wide, projects 10&quot; (with wings). + + + +an object name + + + +urn:org.collectionspace.services.department:Registrar +urn:org.walkerart.department:Fine Art + +title + + + + +length +head +cm +30 + + +width +leg +m +2.57 + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/collectionobject/nh-part.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/collectionobject/nh-part.xml index 1debb2a30..991be259a 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/collectionobject/nh-part.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/collectionobject/nh-part.xml @@ -1,6 +1,6 @@ - - -test-string -999 -9999 - + + +test-string +999 +9999 + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dev-all.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dev-all.xml index a3850b9fa..601562f79 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dev-all.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dev-all.xml @@ -1,96 +1,96 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dev-master-example.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dev-master-example.xml index 437b4058d..77912f62f 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dev-master-example.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dev-master-example.xml @@ -1,48 +1,48 @@ - - - - http://localhost:8180 - - - - - - YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= - - - - - + + + + http://localhost:8180 + + + + + + YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dimension-master.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dimension-master.xml index ba2ed1dd8..8950382a8 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dimension-master.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dimension-master.xml @@ -1,23 +1,23 @@ - - - http://localhost:8180 - - - - - - YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= - - - - - - - - - - + + + http://localhost:8180 + + + + + + YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= + + + + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dimension.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dimension.xml index 7f0220dd0..17e187153 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dimension.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dimension.xml @@ -1,76 +1,76 @@ - - - - - 59PnafP1k9rcuGNMxbCfyQ3TphxKBqecsJI2Yv5vrms= - YmlnYmlyZDIwMTA6YmlnYmlyZDIwMTA= - - - - - - - - 401,403 - POST - /cspace-services/dimensions/ - - - dimension/1.xml - - - - - - - 201,403 - POST - /cspace-services/dimensions/ - - - dimension/1.xml - - - - - - - - - - - 201 - POST - /cspace-services/dimensions/ - - - dimension/1.xml - - - - - - GET - /cspace-services/dimensions/${dimPOST.CSID} - - - - PUT - /cspace-services/dimensions/${dimPOST.CSID} - - - dimension/2-put.xml - - - - - GET - /cspace-services/dimensions/${dimPOST.CSID} - - - - - - - - + + + + + 59PnafP1k9rcuGNMxbCfyQ3TphxKBqecsJI2Yv5vrms= + YmlnYmlyZDIwMTA6YmlnYmlyZDIwMTA= + + + + + + + + 401,403 + POST + /cspace-services/dimensions/ + + + dimension/1.xml + + + + + + + 201,403 + POST + /cspace-services/dimensions/ + + + dimension/1.xml + + + + + + + + + + + 201 + POST + /cspace-services/dimensions/ + + + dimension/1.xml + + + + + + GET + /cspace-services/dimensions/${dimPOST.CSID} + + + + PUT + /cspace-services/dimensions/${dimPOST.CSID} + + + dimension/2-put.xml + + + + + GET + /cspace-services/dimensions/${dimPOST.CSID} + + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dimension/1.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dimension/1.xml index 5c84204da..2e9afdc0f 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dimension/1.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dimension/1.xml @@ -1,11 +1,11 @@ - - - - dimensionType-1288727556164 - entryNumber-1288727556164 - entryDate-1288727556164 - - - + + + + dimensionType-1288727556164 + entryNumber-1288727556164 + entryDate-1288727556164 + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dimension/2-put.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dimension/2-put.xml index 2edfa4eb5..68213b457 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dimension/2-put.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/dimension/2-put.xml @@ -1,10 +1,10 @@ - - - - dimensionType-1288727552274 - updated-entryNumber-1288727552274 - updated-entryDate-1288727552274 - - + + + + dimensionType-1288727552274 + updated-entryNumber-1288727552274 + updated-entryDate-1288727552274 + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/imports/res/import-objectexit-utf8.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/imports/res/import-objectexit-utf8.res.xml index 612ed1b20..caa0f1cef 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/imports/res/import-objectexit-utf8.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/imports/res/import-objectexit-utf8.res.xml @@ -1,14 +1,14 @@ - - - - This is an exit note written by Sebastián (a-acute accent) and Barnes, -which includes a pleasant façade (c-cedilla) and this cast of additional characters: -Δ : Greek capital letter Delta (U+0394) -Ж : Cyrillic capital letter Zhe with breve (U+04C1) -Ŵ : Latin capital letter W with circumflex (U+0174) -Ω : Greek capital letter Omega (U+03A9) -月 : Han (CJK) character 'moon; month' ((U+6708) - OE-IMPORT-TEST-1999.2 - - - + + + + This is an exit note written by Sebastián (a-acute accent) and Barnes, +which includes a pleasant façade (c-cedilla) and this cast of additional characters: +Δ : Greek capital letter Delta (U+0394) +Ж : Cyrillic capital letter Zhe with breve (U+04C1) +Ŵ : Latin capital letter W with circumflex (U+0174) +Ω : Greek capital letter Omega (U+03A9) +月 : Han (CJK) character 'moon; month' ((U+6708) + OE-IMPORT-TEST-1999.2 + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/loanin/li1.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/loanin/li1.xml index d7695200b..34c60309d 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/loanin/li1.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/loanin/li1.xml @@ -1,25 +1,25 @@ - - - loaninNumber-4 - - - An Authorizer - A Contact - October 29, 2009 - urn:cspace:org.collectionspace.demo:orgauthority:id(2a6dcf2e-2ec6-47ca-a460):organization:id(b53b23c9-81bf-447b-838f)'Bing+Crosby+Ice+Cream+Sales%2C+Inc.' - - - An Authorizer 2 - A Contact 2 - October 30, 2009 - urn:cspace:org.collectionspace.demo:orgauthority:id(2a6dcf2e-2ec6-47ca-a460):organization:id(b53b23c9-81bf-447b-838f)'Another Lender' - - - returnDate-1292347312955 - For Surfboards of the 1960s exhibition. - Loan in conditions. - - - + + + loaninNumber-4 + + + An Authorizer + A Contact + October 29, 2009 + urn:cspace:org.collectionspace.demo:orgauthority:id(2a6dcf2e-2ec6-47ca-a460):organization:id(b53b23c9-81bf-447b-838f)'Bing+Crosby+Ice+Cream+Sales%2C+Inc.' + + + An Authorizer 2 + A Contact 2 + October 30, 2009 + urn:cspace:org.collectionspace.demo:orgauthority:id(2a6dcf2e-2ec6-47ca-a460):organization:id(b53b23c9-81bf-447b-838f)'Another Lender' + + + returnDate-1292347312955 + For Surfboards of the 1960s exhibition. + Loan in conditions. + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/loanin/loanin.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/loanin/loanin.xml index 94a9fe109..7df8f2059 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/loanin/loanin.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/loanin/loanin.xml @@ -1,28 +1,28 @@ - - - - - YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= - YWRtaW5AY29sbGVjdGlvbnNwYWNlLm9yZzpBZG1pbmlzdHJhdG9y - - - - - POST - /cspace-services/loansin/ - - - loanin/li1.xml - - - - - - - DELETE - /cspace-services/loansin/8080b6b8-393a-4e8a-b823 - - - - - + + + + + YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= + YWRtaW5AY29sbGVjdGlvbnNwYWNlLm9yZzpBZG1pbmlzdHJhdG9y + + + + + POST + /cspace-services/loansin/ + + + loanin/li1.xml + + + + + + + DELETE + /cspace-services/loansin/8080b6b8-393a-4e8a-b823 + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/location/hierarchy/3-locations_w_relations_CSID.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/location/hierarchy/3-locations_w_relations_CSID.xml index 7c81f5f66..3acab5b08 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/location/hierarchy/3-locations_w_relations_CSID.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/location/hierarchy/3-locations_w_relations_CSID.xml @@ -1,86 +1,86 @@ - - - - - - - - false - ${name} - ${name} - Approved - - - - - - - - hasBroader - - ${itemCSID} - - - - ${parentCSID} - - - - - hasBroader - - ${childCSID} - - - - ${itemCSID} - - - - - hasBroader - - ${child2CSID} - - - - ${itemCSID} - - - - - hasBroader - - ${child3CSID} - - - - ${itemCSID} - - - - - - - + + + + + + + + false + ${name} + ${name} + Approved + + + + + + + + hasBroader + + ${itemCSID} + + + + ${parentCSID} + + + + + hasBroader + + ${childCSID} + + + + ${itemCSID} + + + + + hasBroader + + ${child2CSID} + + + + ${itemCSID} + + + + + hasBroader + + ${child3CSID} + + + + ${itemCSID} + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/location/hierarchy/4-locations_w_relations_mixed.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/location/hierarchy/4-locations_w_relations_mixed.xml index 43d1b38a2..3a64676ac 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/location/hierarchy/4-locations_w_relations_mixed.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/location/hierarchy/4-locations_w_relations_mixed.xml @@ -1,44 +1,44 @@ - - - - ${inAuthority} - ${shortIdentifier} - urn:cspace:org.collectionspace.demo:locationauthority:name(${authShortIdentifier}):location:name(${shortIdentifier})'${name}' - - - - false - ${name} - ${name} - Approved - - - - - - - hasBroader - - ${childCSID} - Locationitem - - - ${itemCSID} - Locationitem - - - - hasBroader - - ${child2CSID} - Locationitem - - - ${itemCSID} - Locationitem - - - - - - + + + + ${inAuthority} + ${shortIdentifier} + urn:cspace:org.collectionspace.demo:locationauthority:name(${authShortIdentifier}):location:name(${shortIdentifier})'${name}' + + + + false + ${name} + ${name} + Approved + + + + + + + hasBroader + + ${childCSID} + Locationitem + + + ${itemCSID} + Locationitem + + + + hasBroader + + ${child2CSID} + Locationitem + + + ${itemCSID} + Locationitem + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/location/hierarchy/5-locations_w_relations_RefNames.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/location/hierarchy/5-locations_w_relations_RefNames.xml index 2306f9ca5..6367888ed 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/location/hierarchy/5-locations_w_relations_RefNames.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/location/hierarchy/5-locations_w_relations_RefNames.xml @@ -1,61 +1,61 @@ - - - - ${shortIdentifier} - - - - false - ${name} - ${name} - Approved - - - - - - - - hasBroader - - ${itemCSID} - - - urn:cspace:core.collectionspace.org:locationauthorities:name(CSPACE3739LocationAuthority):item:name(Aisle3)'Aisle 3' - - - - hasBroader - - urn:cspace:core.collectionspace.org:locationauthorities:name(CSPACE3739LocationAuthority):item:name(Shelf1)'Shelf 1' - - - ${itemCSID} - - - - hasBroader - - urn:cspace:core.collectionspace.org:locationauthorities:name(CSPACE3739LocationAuthority):item:name(Shelf2)'Shelf 2' - - - ${itemCSID} - - - - hasBroader - - urn:cspace:core.collectionspace.org:locationauthorities:name(CSPACE3739LocationAuthority):item:name(Shelf3)'Shelf 3' - - - ${itemCSID} - - - - - - - + + + + ${shortIdentifier} + + + + false + ${name} + ${name} + Approved + + + + + + + + hasBroader + + ${itemCSID} + + + urn:cspace:core.collectionspace.org:locationauthorities:name(CSPACE3739LocationAuthority):item:name(Aisle3)'Aisle 3' + + + + hasBroader + + urn:cspace:core.collectionspace.org:locationauthorities:name(CSPACE3739LocationAuthority):item:name(Shelf1)'Shelf 1' + + + ${itemCSID} + + + + hasBroader + + urn:cspace:core.collectionspace.org:locationauthorities:name(CSPACE3739LocationAuthority):item:name(Shelf2)'Shelf 2' + + + ${itemCSID} + + + + hasBroader + + urn:cspace:core.collectionspace.org:locationauthorities:name(CSPACE3739LocationAuthority):item:name(Shelf3)'Shelf 3' + + + ${itemCSID} + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/media/media.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/media/media.xml index 586103dd1..9b77b3bb6 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/media/media.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/media/media.xml @@ -1,39 +1,39 @@ - - - - - - POST - /cspace-services/personauthorities/ - - - media/oe9.xml - - - - POST - /cspace-services/personauthorities/${oe9.CSID}/items/ - - - media/oe11.xml - - - - POST - /cspace-services/media/ - - - media/oe15.xml - - - - GET - /cspace-services/media/${oe15.CSID}/authorityrefs - - - GET - /cspace-services/personauthorities/${oe9.CSID}/items/${oe11.CSID}/refObjs - - - - + + + + + + POST + /cspace-services/personauthorities/ + + + media/oe9.xml + + + + POST + /cspace-services/personauthorities/${oe9.CSID}/items/ + + + media/oe11.xml + + + + POST + /cspace-services/media/ + + + media/oe15.xml + + + + GET + /cspace-services/media/${oe15.CSID}/authorityrefs + + + GET + /cspace-services/personauthorities/${oe9.CSID}/items/${oe11.CSID}/refObjs + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/media/oe11.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/media/oe11.xml index e40aa5d41..1be238962 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/media/oe11.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/media/oe11.xml @@ -1,14 +1,14 @@ - - - - owenCurOwner2 - urn:cspace:org.collectionspace.demo:personauthority:name(MediaPersonAuth2)'MediaPersonAuth2':person:name(owenCurOwner2) - true - true - Owen the Cur - Owner - - - + + + + owenCurOwner2 + urn:cspace:org.collectionspace.demo:personauthority:name(MediaPersonAuth2)'MediaPersonAuth2':person:name(owenCurOwner2) + true + true + Owen the Cur + Owner + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/media/oe15.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/media/oe15.xml index 600802c72..bd44810d1 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/media/oe15.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/media/oe15.xml @@ -1,10 +1,10 @@ - - - urn:cspace:org.collectionspace.demo:personauthority:name(MediaPersonAuth2)'MediaPersonAuth2':person:name(owenCurOwner2) - title new authority - source 1 - - - + + + urn:cspace:org.collectionspace.demo:personauthority:name(MediaPersonAuth2)'MediaPersonAuth2':person:name(owenCurOwner2) + title new authority + source 1 + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/media/oe9.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/media/oe9.xml index 41a99e04a..8f580d091 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/media/oe9.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/media/oe9.xml @@ -1,10 +1,10 @@ - - - MediaPersonAuth2 - MediaPersonAuth2 - urn:cspace:org.collectionspace.demo:personauthority:name(MediaPersonAuth2)'MediaPersonAuth2' - PersonAuthority - - + + + MediaPersonAuth2 + MediaPersonAuth2 + urn:cspace:org.collectionspace.demo:personauthority:name(MediaPersonAuth2)'MediaPersonAuth2' + PersonAuthority + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/object-exit-display.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/object-exit-display.xml index 20e2375b5..7d377c40a 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/object-exit-display.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/object-exit-display.xml @@ -1,53 +1,53 @@ - - - - - YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= - YWRtaW5AY29sbGVjdGlvbnNwYWNlLm9yZzpBZG1pbmlzdHJhdG9y - - - - - - - POST - /cspace-services/personauthorities/ - objectexit/oePersonauthority.xml - - - POST - /cspace-services/personauthorities/${oePersonauthority.CSID}/items/ - objectexit/oePersonDisplayOnly.xml - - Finbar the DisplayName - Finbar_the_shortIdentifier - - - - GET - /cspace-services/personauthorities/${oePersonauthority.CSID}/items/${oePerson.CSID} - - - - objectexit/res/oePersonDisplayGET.res.xml - - - ${oePersonGET.got("//csid")} - ${oePersonauthority.CSID} - ${oePersonauthority.sent("//shortIdentifier")} - ${oePerson.sent("//displayName")} - ${oePerson.sent("//shortIdentifier")} - urn:cspace:core.collectionspace.org:personauthorities:name(${inAuthorityShortIdentifier}):item:name(${shortIdentifier})'${displayName}' - - - - - - - - + + + + + YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= + YWRtaW5AY29sbGVjdGlvbnNwYWNlLm9yZzpBZG1pbmlzdHJhdG9y + + + + + + + POST + /cspace-services/personauthorities/ + objectexit/oePersonauthority.xml + + + POST + /cspace-services/personauthorities/${oePersonauthority.CSID}/items/ + objectexit/oePersonDisplayOnly.xml + + Finbar the DisplayName + Finbar_the_shortIdentifier + + + + GET + /cspace-services/personauthorities/${oePersonauthority.CSID}/items/${oePerson.CSID} + + + + objectexit/res/oePersonDisplayGET.res.xml + + + ${oePersonGET.got("//csid")} + ${oePersonauthority.CSID} + ${oePersonauthority.sent("//shortIdentifier")} + ${oePerson.sent("//displayName")} + ${oePerson.sent("//shortIdentifier")} + urn:cspace:core.collectionspace.org:personauthorities:name(${inAuthorityShortIdentifier}):item:name(${shortIdentifier})'${displayName}' + + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/object-exit.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/object-exit.xml index 6f572089e..ad84ffdd7 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/object-exit.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/object-exit.xml @@ -1,405 +1,405 @@ - - - - - YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= - YWRtaW5AY29sbGVjdGlvbnNwYWNlLm9yZzpBZG1pbmlzdHJhdG9y - - - - - - - POST - /cspace-services/personauthorities/ - - - objectexit/oe9.xml - - - - POST - /cspace-services/personauthorities/${oe9.CSID}/items/ - - - objectexit/oe11.xml - - - - POST - /cspace-services/objectexit/ - - - objectexit/oe15.xml - - - - - - - POST - /cspace-services/objectexit/ - objectexit/oe1.xml - - - GET - /cspace-services/objectexit/${oe1.CSID} - - - objectexit/res/oe2.res.xml - - - - - - - - POST - /cspace-services/objectexit/ - objectexit/oe1.xml - - - GET - /cspace-services/objectexit/${oe1.CSID} - - - objectexit/res/oe2.res.xml - - /document/*[local-name()='objectexit_common'] - - - - - - - POST - /cspace-services/objectexit/ - - checkList-1234 - - objectexit/oe35.xml - - - GET - /cspace-services/objectexit/ - - - objectexit/res/oe35.res.xml - - ${oe35.CSID} - - - //list-item[./exitNumber='checkList-1234'] - - - - - - - DELETE - /cspace-services/objectexit/065aa56e-a4f5-44b7-955e - - - DELETE - /cspace-services/objectexit/1735327c-f9bb-42c7-959b - - - DELETE - /cspace-services/objectexit/106cb53d-ee79-44e3-8665 - - - - - - POST - /cspace-services/objectexit/ - - - objectexit/oe1.xml - - - - GET - /cspace-services/objectexit/${oe1.CSID} - - - - objectexit/res/oe2.res.xml - - - - - - - - - - POST - /cspace-services/objectexit/ - - - objectexit/oeRepeat.xml - - - - - - - - - POST - /cspace-services/objectexit/ - - - objectexit/oe1.xml - - - - GET - /cspace-services/objectexit/${oe1.CSID} - - - objectexit/res/oe2.res.xml - - - - POST - /cspace-services/objectexit/ - - - objectexit/oe3.xml - - - - POST - /cspace-services/objectexit/ - - - objectexit/oe4.xml - - - - POST - /cspace-services/objectexit/ - - - objectexit/oe5.xml - - - - - - - - - GET - /cspace-services/objectexit/9223372036854775807 - 404 - - - GET - /cspace-services/objectexit/${oe1.CSID} - oe8.res.xml - - - POST - /cspace-services/personauthorities/ - - - objectexit/oe9.xml - - - - GET - /cspace-services/personauthorities/${oe9.CSID} - - - - POST - /cspace-services/personauthorities/${oe9.CSID}/items/ - - - objectexit/oe11.xml - - - - GET - /cspace-services/personauthorities/${oe9.CSID}/items/${oe11.CSID} - - - POST - /cspace-services/personauthorities/${oe9.CSID}/items/ - - - objectexit/oe13.xml - - - - GET - /cspace-services/personauthorities/${oe11.CSID}/items/${oe13.CSID} - - - POST - /cspace-services/objectexit/ - - - objectexit/oe15.xml - - - - GET - /cspace-services/objectexit/${oe15.CSID} - - - GET - /cspace-services/objectexit/${oe15.CSID}/authorityrefs/ - - - DELETE - /cspace-services/personauthorities/${oe9.CSID}/items/${oe11.CSID} - - - - DELETE - /cspace-services/personauthorities/${oe9.CSID}/items/${oe13.CSID} - - - DELETE - /cspace-services/personauthorities/${oe9.CSID} - - - DELETE - /cspace-services/objectexit/${oe15.CSID} - - - GET - /cspace-services/objectexit/${oe1.CSID} - - - PUT - /cspace-services/objectexit/${oe1.CSID} - - - objectexit/oe23.xml - - - - DELETE - /cspace-services/objectexit/${oe1.CSID} - - - DELETE - /cspace-services/objectexit/9223372036854775807 - 404 - - - PUT - /cspace-services/objectexit/9223372036854775807 - - - objectexit/oe23.xml - - 404 - - - GET - /cspace-services/objectexit/?sortBy=&pgNum=0&pgSz=1 - - - GET - /cspace-services/objectexit/?sortBy=&pgNum=0&pgSz=1 - - - GET - /cspace-services/objectexit/?sortBy=&pgNum=1&pgSz=1 - - - GET - /cspace-services/objectexit/?sortBy=&pgNum=2&pgSz=1 - - - DELETE - /cspace-services/objectexit/${oe1.CSID} - 404 - - - DELETE - /cspace-services/objectexit/${oe3.CSID} - - - DELETE - /cspace-services/objectexit/${oe4.CSID} - - - DELETE - /cspace-services/objectexit/${oe5.CSID} - - - - - - - - - POST - /cspace-services/objectexit/ - - - objectexit/oe1.xml - - - - POST - /cspace-services/objectexit/ - - - objectexit/oe3.xml - - - - POST - /cspace-services/objectexit/ - - - objectexit/oe4.xml - - - - POST - /cspace-services/objectexit/ - - - objectexit/oe5.xml - - - - GET - /cspace-services/objectexit/ - - - objectexit/res/oe6.res.xml - - - - - - - - + + + + + YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= + YWRtaW5AY29sbGVjdGlvbnNwYWNlLm9yZzpBZG1pbmlzdHJhdG9y + + + + + + + POST + /cspace-services/personauthorities/ + + + objectexit/oe9.xml + + + + POST + /cspace-services/personauthorities/${oe9.CSID}/items/ + + + objectexit/oe11.xml + + + + POST + /cspace-services/objectexit/ + + + objectexit/oe15.xml + + + + + + + POST + /cspace-services/objectexit/ + objectexit/oe1.xml + + + GET + /cspace-services/objectexit/${oe1.CSID} + + + objectexit/res/oe2.res.xml + + + + + + + + POST + /cspace-services/objectexit/ + objectexit/oe1.xml + + + GET + /cspace-services/objectexit/${oe1.CSID} + + + objectexit/res/oe2.res.xml + + /document/*[local-name()='objectexit_common'] + + + + + + + POST + /cspace-services/objectexit/ + + checkList-1234 + + objectexit/oe35.xml + + + GET + /cspace-services/objectexit/ + + + objectexit/res/oe35.res.xml + + ${oe35.CSID} + + + //list-item[./exitNumber='checkList-1234'] + + + + + + + DELETE + /cspace-services/objectexit/065aa56e-a4f5-44b7-955e + + + DELETE + /cspace-services/objectexit/1735327c-f9bb-42c7-959b + + + DELETE + /cspace-services/objectexit/106cb53d-ee79-44e3-8665 + + + + + + POST + /cspace-services/objectexit/ + + + objectexit/oe1.xml + + + + GET + /cspace-services/objectexit/${oe1.CSID} + + + + objectexit/res/oe2.res.xml + + + + + + + + + + POST + /cspace-services/objectexit/ + + + objectexit/oeRepeat.xml + + + + + + + + + POST + /cspace-services/objectexit/ + + + objectexit/oe1.xml + + + + GET + /cspace-services/objectexit/${oe1.CSID} + + + objectexit/res/oe2.res.xml + + + + POST + /cspace-services/objectexit/ + + + objectexit/oe3.xml + + + + POST + /cspace-services/objectexit/ + + + objectexit/oe4.xml + + + + POST + /cspace-services/objectexit/ + + + objectexit/oe5.xml + + + + + + + + + GET + /cspace-services/objectexit/9223372036854775807 + 404 + + + GET + /cspace-services/objectexit/${oe1.CSID} + oe8.res.xml + + + POST + /cspace-services/personauthorities/ + + + objectexit/oe9.xml + + + + GET + /cspace-services/personauthorities/${oe9.CSID} + + + + POST + /cspace-services/personauthorities/${oe9.CSID}/items/ + + + objectexit/oe11.xml + + + + GET + /cspace-services/personauthorities/${oe9.CSID}/items/${oe11.CSID} + + + POST + /cspace-services/personauthorities/${oe9.CSID}/items/ + + + objectexit/oe13.xml + + + + GET + /cspace-services/personauthorities/${oe11.CSID}/items/${oe13.CSID} + + + POST + /cspace-services/objectexit/ + + + objectexit/oe15.xml + + + + GET + /cspace-services/objectexit/${oe15.CSID} + + + GET + /cspace-services/objectexit/${oe15.CSID}/authorityrefs/ + + + DELETE + /cspace-services/personauthorities/${oe9.CSID}/items/${oe11.CSID} + + + + DELETE + /cspace-services/personauthorities/${oe9.CSID}/items/${oe13.CSID} + + + DELETE + /cspace-services/personauthorities/${oe9.CSID} + + + DELETE + /cspace-services/objectexit/${oe15.CSID} + + + GET + /cspace-services/objectexit/${oe1.CSID} + + + PUT + /cspace-services/objectexit/${oe1.CSID} + + + objectexit/oe23.xml + + + + DELETE + /cspace-services/objectexit/${oe1.CSID} + + + DELETE + /cspace-services/objectexit/9223372036854775807 + 404 + + + PUT + /cspace-services/objectexit/9223372036854775807 + + + objectexit/oe23.xml + + 404 + + + GET + /cspace-services/objectexit/?sortBy=&pgNum=0&pgSz=1 + + + GET + /cspace-services/objectexit/?sortBy=&pgNum=0&pgSz=1 + + + GET + /cspace-services/objectexit/?sortBy=&pgNum=1&pgSz=1 + + + GET + /cspace-services/objectexit/?sortBy=&pgNum=2&pgSz=1 + + + DELETE + /cspace-services/objectexit/${oe1.CSID} + 404 + + + DELETE + /cspace-services/objectexit/${oe3.CSID} + + + DELETE + /cspace-services/objectexit/${oe4.CSID} + + + DELETE + /cspace-services/objectexit/${oe5.CSID} + + + + + + + + + POST + /cspace-services/objectexit/ + + + objectexit/oe1.xml + + + + POST + /cspace-services/objectexit/ + + + objectexit/oe3.xml + + + + POST + /cspace-services/objectexit/ + + + objectexit/oe4.xml + + + + POST + /cspace-services/objectexit/ + + + objectexit/oe5.xml + + + + GET + /cspace-services/objectexit/ + + + objectexit/res/oe6.res.xml + + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe1.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe1.xml index 78ee56693..1e94f2838 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe1.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe1.xml @@ -1,10 +1,10 @@ - - - - urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum' - objectexitNumber-1290026472360 - - - + + + + urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum' + objectexitNumber-1290026472360 + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe11.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe11.xml index fac5fb04e..2b55fdd12 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe11.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe11.xml @@ -1,2 +1,2 @@ -7f441679-ab83-4832-85f9owenCurOwnerurn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth':person:name(owenCurOwner)truetrueOwen the CurOwner - +7f441679-ab83-4832-85f9owenCurOwnerurn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth':person:name(owenCurOwner)truetrueOwen the CurOwner + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe13.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe13.xml index 94beedf9e..6dfd4603d 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe13.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe13.xml @@ -1,2 +1,2 @@ -7f441679-ab83-4832-85f9davenportDepositorurn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth':person:name(davenportDepositor)truetrueDavenportDepositor - +7f441679-ab83-4832-85f9davenportDepositorurn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth':person:name(davenportDepositor)truetrueDavenportDepositor + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe15.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe15.xml index 4c156cd20..3c358d87a 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe15.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe15.xml @@ -1,2 +1,2 @@ -urn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth':person:name(davenportDepositor)exitDate-1290026474563exitNumber-1290026474563 - +urn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth':person:name(davenportDepositor)exitDate-1290026474563exitNumber-1290026474563 + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe23.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe23.xml index ce7491206..01e31df12 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe23.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe23.xml @@ -1,2 +1,2 @@ -urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum'updated-objectexitNumber-1290026472360 - +urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum'updated-objectexitNumber-1290026472360 + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe3.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe3.xml index 3f59daaa0..44d98316f 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe3.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe3.xml @@ -1,2 +1,2 @@ -urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum'objectexitNumber-1290026473391 - +urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum'objectexitNumber-1290026473391 + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe35.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe35.xml index a707148dc..988c995d4 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe35.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe35.xml @@ -1,10 +1,10 @@ - - - - urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum' - ${exitNumber} - - - + + + + urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum' + ${exitNumber} + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe4.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe4.xml index cc92b72d9..2554e2859 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe4.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe4.xml @@ -1,2 +1,2 @@ -urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum'objectexitNumber-1290026473626 - +urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum'objectexitNumber-1290026473626 + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe5.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe5.xml index b7c110026..5d82a1e2b 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe5.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe5.xml @@ -1,2 +1,2 @@ -urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum'objectexitNumber-1290026473860 - +urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum'objectexitNumber-1290026473860 + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe9.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe9.xml index de0c7cc4b..41fbedd9a 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe9.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oe9.xml @@ -1,2 +1,2 @@ -ObjectexitPersonAuthObjectexitPersonAuthurn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth'PersonAuthority - +ObjectexitPersonAuthObjectexitPersonAuthurn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth'PersonAuthority + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oeObject.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oeObject.xml index 17acce70a..2db2785ce 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oeObject.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oeObject.xml @@ -1,9 +1,9 @@ - - - ${depositor} - ${currentOwner} - exitDate-1290026474563 - ${exitNumber} - + + + ${depositor} + ${currentOwner} + exitDate-1290026474563 + ${exitNumber} + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oePersonDisplayOnly.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oePersonDisplayOnly.xml index 28e4a7b00..ab6ff8be2 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oePersonDisplayOnly.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oePersonDisplayOnly.xml @@ -1,15 +1,15 @@ - - - - ${shortIdentifier} - - - ${displayName} - false - ${displayName} - - - - + + + + ${shortIdentifier} + + + ${displayName} + false + ${displayName} + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oePersonauthority.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oePersonauthority.xml index b66c80abc..0fd40a588 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oePersonauthority.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oePersonauthority.xml @@ -1,12 +1,12 @@ - - - - Default Person Authority - defaultPersonAuthority - PersonAuthority - - - - + + + + Default Person Authority + defaultPersonAuthority + PersonAuthority + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oeRepeat.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oeRepeat.xml index 5ea3b5c6c..38eeff9a3 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oeRepeat.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/oeRepeat.xml @@ -1,11 +1,11 @@ - - - urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum' - objectexitNumber-1290026472360 - - courier - - - + + + urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum' + objectexitNumber-1290026472360 + + courier + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe10.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe10.res.xml index 20ae40fd4..de123420a 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe10.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe10.res.xml @@ -1,9 +1,9 @@ - - -ObjectexitPersonAuth -urn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth' -${oe9.CSID} -ObjectexitPersonAuth -PersonAuthority - - + + +ObjectexitPersonAuth +urn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth' +${oe9.CSID} +ObjectexitPersonAuth +PersonAuthority + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe12.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe12.res.xml index 61e1d7447..3103f4568 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe12.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe12.res.xml @@ -1,18 +1,18 @@ - - -Owner - -owenCurOwner -Owen the Cur Owner - -Owen the Cur - - -true -${oe11.CSID} -true -${oe9.CSID} -urn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth':person:name(owenCurOwner) -Owen the Cur Owner - - + + +Owner + +owenCurOwner +Owen the Cur Owner + +Owen the Cur + + +true +${oe11.CSID} +true +${oe9.CSID} +urn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth':person:name(owenCurOwner) +Owen the Cur Owner + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe14.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe14.res.xml index ba4aaee50..8137c6ffe 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe14.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe14.res.xml @@ -1,18 +1,18 @@ - - -Depositor - -davenportDepositor -Davenport Depositor - -Davenport - - -true -${oe13.CSID} -true -${oe9.CSID} -urn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth':person:name(davenportDepositor) -Davenport Depositor - - + + +Depositor + +davenportDepositor +Davenport Depositor + +Davenport + + +true +${oe13.CSID} +true +${oe9.CSID} +urn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth':person:name(davenportDepositor) +Davenport Depositor + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe16.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe16.res.xml index d79e702f7..f683e10da 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe16.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe16.res.xml @@ -1,7 +1,7 @@ - - -exitDate-1290026474563 -exitNumber-1290026474563 -urn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth':person:name(davenportDepositor) - - + + +exitDate-1290026474563 +exitNumber-1290026474563 +urn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth':person:name(davenportDepositor) + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe17.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe17.res.xml index 97c4e2d9b..f08d12086 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe17.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe17.res.xml @@ -1,14 +1,14 @@ - - - 0 - 40 - 1 - 1 - - objectexit_common:depositor - urn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth':person:name(davenportDepositor) - ObjectexitPersonAuth - /personauthorities/urn:cspace:name(ObjectexitPersonAuth)/items/urn:cspace:name(davenportDepositor) - - - + + + 0 + 40 + 1 + 1 + + objectexit_common:depositor + urn:cspace:org.collectionspace.demo:personauthority:name(ObjectexitPersonAuth)'ObjectexitPersonAuth':person:name(davenportDepositor) + ObjectexitPersonAuth + /personauthorities/urn:cspace:name(ObjectexitPersonAuth)/items/urn:cspace:name(davenportDepositor) + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe2.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe2.res.xml index d690617d7..d8dc4c1a5 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe2.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe2.res.xml @@ -1,14 +1,14 @@ - - - - - objectexitNumber-1290026472360 - urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum' - - - - 1 - - - - + + + + + objectexitNumber-1290026472360 + urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum' + + + + 1 + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe22.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe22.res.xml index ce5931731..b56a2b002 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe22.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe22.res.xml @@ -1,6 +1,6 @@ - - -objectexitNumber-1290026472360 -urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum' - - + + +objectexitNumber-1290026472360 +urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum' + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe23.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe23.res.xml index 31e03b825..0721d6ada 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe23.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe23.res.xml @@ -1,6 +1,6 @@ - - -updated-objectexitNumber-1290026472360 -urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum' - - + + +updated-objectexitNumber-1290026472360 +urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum' + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe27.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe27.res.xml index 7c21e3e3b..7e48d15b1 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe27.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe27.res.xml @@ -1,2 +1,2 @@ -0113currentOwner|depositor|exitDate|exitMethod|exitNote|exitNumber|exitReason|packingNote|uri|csidobjectexitNumber-1290026473391/objectexit/${oe3.CSID}${oe3.CSID} - +0113currentOwner|depositor|exitDate|exitMethod|exitNote|exitNumber|exitReason|packingNote|uri|csidobjectexitNumber-1290026473391/objectexit/${oe3.CSID}${oe3.CSID} + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe28.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe28.res.xml index 7c21e3e3b..7e48d15b1 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe28.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe28.res.xml @@ -1,2 +1,2 @@ -0113currentOwner|depositor|exitDate|exitMethod|exitNote|exitNumber|exitReason|packingNote|uri|csidobjectexitNumber-1290026473391/objectexit/${oe3.CSID}${oe3.CSID} - +0113currentOwner|depositor|exitDate|exitMethod|exitNote|exitNumber|exitReason|packingNote|uri|csidobjectexitNumber-1290026473391/objectexit/${oe3.CSID}${oe3.CSID} + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe29.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe29.res.xml index f66fb74fa..f0d63b363 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe29.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe29.res.xml @@ -1,2 +1,2 @@ -1113currentOwner|depositor|exitDate|exitMethod|exitNote|exitNumber|exitReason|packingNote|uri|csidobjectexitNumber-1290026473626/objectexit/${oe4.CSID}${oe4.CSID} - +1113currentOwner|depositor|exitDate|exitMethod|exitNote|exitNumber|exitReason|packingNote|uri|csidobjectexitNumber-1290026473626/objectexit/${oe4.CSID}${oe4.CSID} + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe30.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe30.res.xml index 72cdfbf2b..99cd58d3d 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe30.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe30.res.xml @@ -1,2 +1,2 @@ -2113currentOwner|depositor|exitDate|exitMethod|exitNote|exitNumber|exitReason|packingNote|uri|csidobjectexitNumber-1290026473860/objectexit/${oe5.CSID}${oe5.CSID} - +2113currentOwner|depositor|exitDate|exitMethod|exitNote|exitNumber|exitReason|packingNote|uri|csidobjectexitNumber-1290026473860/objectexit/${oe5.CSID}${oe5.CSID} + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe6.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe6.res.xml index 0704abb0c..0518b77ee 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe6.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe6.res.xml @@ -1,36 +1,36 @@ - - - 0 - 40 - 4 - 4 - exitNumber|currentOwner|uri|csid - - - objectexitNumber-1290026473860 - /objectexit/${oe5.CSID} - ${oe5.CSID} - - - - objectexitNumber-1290026473391 - /objectexit/${oe3.CSID} - ${oe3.CSID} - - - - objectexitNumber-1290026473626 - /objectexit/${oe4.CSID} - ${oe4.CSID} - - - - objectexitNumber-1290026472360 - /objectexit/${oe1.CSID} - ${oe1.CSID} - - - - + + + 0 + 40 + 4 + 4 + exitNumber|currentOwner|uri|csid + + + objectexitNumber-1290026473860 + /objectexit/${oe5.CSID} + ${oe5.CSID} + + + + objectexitNumber-1290026473391 + /objectexit/${oe3.CSID} + ${oe3.CSID} + + + + objectexitNumber-1290026473626 + /objectexit/${oe4.CSID} + ${oe4.CSID} + + + + objectexitNumber-1290026472360 + /objectexit/${oe1.CSID} + ${oe1.CSID} + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe8.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe8.res.xml index ce5931731..b56a2b002 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe8.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/objectexit/res/oe8.res.xml @@ -1,6 +1,6 @@ - - -objectexitNumber-1290026472360 -urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum' - - + + +objectexitNumber-1290026472360 +urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum' + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization.xml index 27d07505d..b4661808e 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization.xml @@ -1,37 +1,37 @@ - - - - - POST - /cspace-services/orgauthorities/ - - - organization/orgauthorities_common.xml - - - - POST - /cspace-services/orgauthorities/${OrgAuth1.CSID}/items/ - - - organization/organizations_common.xml - - - - GET - /cspace-services/orgauthorities/${OrgAuth1.CSID}/items/${Org1.CSID} - - - GET - /cspace-services/orgauthorities/${OrgAuth1.CSID} - - - LIST - /cspace-services/orgauthorities/${OrgAuth1.CSID} - - - LIST - /cspace-services/orgauthorities/${OrgAuth1.CSID}/items/ - - - + + + + + POST + /cspace-services/orgauthorities/ + + + organization/orgauthorities_common.xml + + + + POST + /cspace-services/orgauthorities/${OrgAuth1.CSID}/items/ + + + organization/organizations_common.xml + + + + GET + /cspace-services/orgauthorities/${OrgAuth1.CSID}/items/${Org1.CSID} + + + GET + /cspace-services/orgauthorities/${OrgAuth1.CSID} + + + LIST + /cspace-services/orgauthorities/${OrgAuth1.CSID} + + + LIST + /cspace-services/orgauthorities/${OrgAuth1.CSID}/items/ + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/hierarchy/3-organizations_w_relations.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/hierarchy/3-organizations_w_relations.xml index 16bb19314..7185bbd8f 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/hierarchy/3-organizations_w_relations.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/hierarchy/3-organizations_w_relations.xml @@ -1,83 +1,83 @@ - - - - ${inAuthority} - ${shortIdentifier} - urn:cspace:org.collectionspace.demo:organizationauthority:name(${authShortIdentifier}):organization:name(${shortIdentifier})'${name}' - - - - - ${name} - - - - - false - ${name} - - The real test official test organization - - - - - - - - - - - hasBroader - - ${itemCSID} - Organization - - - ${parentCSID} - ${parentUri} - Organization - - - - hasBroader - - ${childCSID} - ${childUri} - Organization - - - ${itemCSID} - Organization - - - - hasBroader - - ${child2Uri} - ${child2CSID} - Organization - - - ${itemCSID} - Organization - - - - hasBroader - - ${child3Uri} - ${child3CSID} - Organization - - - ${itemCSID} - Organization - - - - - - + + + + ${inAuthority} + ${shortIdentifier} + urn:cspace:org.collectionspace.demo:organizationauthority:name(${authShortIdentifier}):organization:name(${shortIdentifier})'${name}' + + + + + ${name} + + + + + false + ${name} + + The real test official test organization + + + + + + + + + + + hasBroader + + ${itemCSID} + Organization + + + ${parentCSID} + ${parentUri} + Organization + + + + hasBroader + + ${childCSID} + ${childUri} + Organization + + + ${itemCSID} + Organization + + + + hasBroader + + ${child2Uri} + ${child2CSID} + Organization + + + ${itemCSID} + Organization + + + + hasBroader + + ${child3Uri} + ${child3CSID} + Organization + + + ${itemCSID} + Organization + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/organizations_common.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/organizations_common.xml index 1e12090bc..0f6494c87 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/organizations_common.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/organizations_common.xml @@ -1,34 +1,34 @@ - - - 1288047801161 - urn:cspace:org.collectionspace.demo:orgauthority:name(1288047801161):organization:name(1288047801161) - true - true - Test Organization-1288047801161 - Test Organization Name - - urn:cspace:org.collectionspace.demo:personauthority:name(TestPersonAuth)'TestPersonAuth':person:name(charlieOrgcontact) - urn:cspace:org.collectionspace.demo:personauthority:name(TestPersonAuth)'TestPersonAuth':person:name(chelsieContact) - - Anytown, USA - - urn:cspace:org.collectionspace.demo:orgauthority:name(1288047801161):organization:name(1288047803708) - - - My new function - My second function - - - My new group - My second group - My third group - - This is a test Authority item - Some mythical book - Let's say page 39 - - - - + + + 1288047801161 + urn:cspace:org.collectionspace.demo:orgauthority:name(1288047801161):organization:name(1288047801161) + true + true + Test Organization-1288047801161 + Test Organization Name + + urn:cspace:org.collectionspace.demo:personauthority:name(TestPersonAuth)'TestPersonAuth':person:name(charlieOrgcontact) + urn:cspace:org.collectionspace.demo:personauthority:name(TestPersonAuth)'TestPersonAuth':person:name(chelsieContact) + + Anytown, USA + + urn:cspace:org.collectionspace.demo:orgauthority:name(1288047801161):organization:name(1288047803708) + + + My new function + My second function + + + My new group + My second group + My third group + + This is a test Authority item + Some mythical book + Let's say page 39 + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/organizations_ucb.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/organizations_ucb.xml index df7ba5f88..57b95fdce 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/organizations_ucb.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/organizations_ucb.xml @@ -1,19 +1,19 @@ - - - - ucberkeley - urn:cspace:org.collectionspace.demo:orgauthority:name(testorgauth):organization:name(ucberkeley)'UC Berkeley' - false - false - U.C. Berkeley - University of California, Berkeley - Berkeley, CA - - urn:cspace:org.collectionspace.demo:orgauthority:name(testorgauth):organization:name(ucberkeleyist)'UCB IST' - - This is a test Authority item - Some mythical book - Let's say page 39 - - - + + + + ucberkeley + urn:cspace:org.collectionspace.demo:orgauthority:name(testorgauth):organization:name(ucberkeley)'UC Berkeley' + false + false + U.C. Berkeley + University of California, Berkeley + Berkeley, CA + + urn:cspace:org.collectionspace.demo:orgauthority:name(testorgauth):organization:name(ucberkeleyist)'UCB IST' + + This is a test Authority item + Some mythical book + Let's say page 39 + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/organizations_ucbist.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/organizations_ucbist.xml index 0e9656fff..2124b17aa 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/organizations_ucbist.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/organizations_ucbist.xml @@ -1,13 +1,13 @@ - - - - ucberkeley - urn:cspace:org.collectionspace.demo:orgauthority:name(testorgauth):organization:name(ucberkeleyist)'UCB IST' - false - false - U.C. Berkeley IST - University of California, Berkeley Information Systems and Technology - Berkeley, CA - - - + + + + ucberkeley + urn:cspace:org.collectionspace.demo:orgauthority:name(testorgauth):organization:name(ucberkeleyist)'UCB IST' + false + false + U.C. Berkeley IST + University of California, Berkeley Information Systems and Technology + Berkeley, CA + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/orgauthorities_common.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/orgauthorities_common.xml index eebc48d9f..8fc112b37 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/orgauthorities_common.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/orgauthorities_common.xml @@ -1,12 +1,12 @@ - - - 1288047801161 - TestOrgAuth-1288047801161 - urn:cspace:org.collectionspace.demo:orgauthority:name(1288047801161)'TestOrgAuth-1288047801161' - OrgAuthority - This is a test authority - Some mythical book - - + + + 1288047801161 + TestOrgAuth-1288047801161 + urn:cspace:org.collectionspace.demo:orgauthority:name(1288047801161)'TestOrgAuth-1288047801161' + OrgAuthority + This is a test authority + Some mythical book + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/orgauthorities_testorgauth.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/orgauthorities_testorgauth.xml index 6cdaf95be..7056f450d 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/orgauthorities_testorgauth.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/orgauthorities_testorgauth.xml @@ -1,12 +1,12 @@ - - - testorgauth - Test Org Authority - urn:cspace:org.collectionspace.demo:orgauthority:name(testorgauth)'Test Org Authority' - OrgAuthority - This is a test authority - Some mythical book - - + + + testorgauth + Test Org Authority + urn:cspace:org.collectionspace.demo:orgauthority:name(testorgauth)'Test Org Authority' + OrgAuthority + This is a test authority + Some mythical book + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/repeatables.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/repeatables.xml index 7a85a0740..fd41cef36 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/repeatables.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/organization/repeatables.xml @@ -1,11 +1,11 @@ - - - 1288047805974 - displayName-1288047805974 - urn:cspace:org.collectionspace.demo:orgauthority:name(1288047805974)'displayName-1288047805974' - OrgAuthority - - - + + + 1288047805974 + displayName-1288047805974 + urn:cspace:org.collectionspace.demo:orgauthority:name(1288047805974)'displayName-1288047805974' + OrgAuthority + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/person.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/person.xml index 99b43a029..6ff2193ae 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/person.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/person.xml @@ -1,501 +1,501 @@ - - - - - - POST - /cspace-services/personauthorities/ - person/personauthorities_common.xml - - CSPACE3739PersonAuthority - - - - POST - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ - person/persons_common.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActor1 - - - - POST - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ - person/persons_common.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActor2 - - - - GET - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority) - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID} - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID} - - - GET - /cspace-services/personauthorities/ - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ - - - - POST - /cspace-services/relations/ - relation/r-1.xml - - ${Person1.CSID} - ${Person2.CSID} - Persons - Persons - hasBroader - - - - - POST - /cspace-services/relations/ - relation/r-1.xml - - - ${Person2.CSID} - ${Person1.CSID} - Persons - Persons - hasNarrower - - - - - - - - POST - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ - person/persons_common_w_relations.xml - - - CSPACE3739PersonAuthority - - - - - - - - POST - /cspace-services/personauthorities/ - person/personauthorities_common.xml - - CSPACE3739PersonAuthority - - - - - POST - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ - person/persons_common.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActor - - - - - POST - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ - person/persons_common.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActorParent - - - - - POST - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ - person/persons_common.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActorChild - - - - - POST - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ - person/persons_common.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActorChild2 - - - - - - PUT - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${Person1.CSID} - person/persons_common_w_relations.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActor - ${Person1.CSID} - ${PersonParent.CSID} - ${PersonChild.CSID} - - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}?showRelations=true - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${PersonChild.CSID}?showSiblings=true - - - - - PUT - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${Person1.CSID} - person/persons_common_w_relations_2.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActor - ${Person1.CSID} - ${PersonParent.CSID} - - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}?showRelations=true - - - - - PUT - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${Person1.CSID} - person/persons_common_w_relations.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActor - ${Person1.CSID} - ${PersonParent.CSID} - ${PersonChild.CSID} - - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}?showRelations=true - - - - PUT - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${Person1.CSID} - person/persons_common_w_relations_3.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActor - ${Person1.CSID} - ${PersonChild.CSID} - ${PersonChild2.CSID} - - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}?showRelations=true - - - - !-- ========================= POST a person ===================================================== --> - - - - POST - /cspace-services/personauthorities/ - person/personauthorities_common.xml - - CSPACE3739PersonAuthority - - - - - POST - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ - person/persons_common.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActorParent - - - - - POST - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ - person/persons_common.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActorChild - actorChild1 - - - - - POST - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ - person/persons_common.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActorChild2 - actorChild2 - - - - - POST - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ - person/persons_common.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActorChild3 - actorChild3 - - - - - POST - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ - person/persons_common_w_relations_POST.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActor - - ${PersonParent.CSID} - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonParent.CSID} - ${PersonChild.CSID} - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonChild.CSID} - ${PersonChild2.CSID} - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonChild2.CSID} - ${PersonChild3.CSID} - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonChild3.CSID} - - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}?showRelations=true - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${PersonChild.CSID}?showSiblings=true - - - person/res/GETpostPerson_siblings.res.xml - - ${Person1.CSID} - ${PersonChild.CSID} - ${PersonChild2.CSID} - ${PersonChild3.CSID} - ${PersonChild2.termDisplayNameSuffix} - ${PersonChild3.termDisplayNameSuffix} - - /document/*[local-name()='relations-common-list'] - - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}?showAllRelations=true - - - person/res/showAllRelations.res.xml - - /document/*[local-name()='relations-common-list'] - - - - - - GET - /cspace-services/relations/ - - - - GET - /cspace-services/relations?sbj=${PersonAuth1.CSID} - - - - GET - /cspace-services/relations?obj=${PersonAuth1.CSID} - - - - - - - POST - /cspace-services/personauthorities/ - person/personauthorities_common.xml - - CSPACE3739PersonAuthority - - - - - POST - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ - person/persons_common.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActorParent - - - - - - POST - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ - person/persons_common.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActorChild - - - - - POST - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ - person/persons_common.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActorChild2 - - - - - POST - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ - person/persons_common.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActorChild3 - - - - - - POST - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ - person/persons_common_w_relations_POST.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActor - ${PersonParent.CSID} - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonParent.CSID} - ${PersonChild.CSID} - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonChild.CSID} - ${PersonChild2.CSID} - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonChild2.CSID} - ${PersonChild3.CSID} - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonChild3.CSID} - - - - - GET - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${Person1.CSID}?showRelations=true - - - - GET - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ - - - - PUT - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${Person1.CSID} - person/persons_common_delete_relations_PUT.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActor - ${PersonChild.CSID} - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonChild.CSID} - - - - - GET - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${Person1.CSID}?showRelations=true - - - - - PUT - /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${Person1.CSID} - person/persons_common_delete_all_relations_PUT.xml - - ${PersonAuth1.CSID} - CSPACE3739PersonAuthority - johnWayneActor - - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}?showRelations=true - - - - - - - + + + + + + POST + /cspace-services/personauthorities/ + person/personauthorities_common.xml + + CSPACE3739PersonAuthority + + + + POST + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ + person/persons_common.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActor1 + + + + POST + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ + person/persons_common.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActor2 + + + + GET + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority) + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID} + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID} + + + GET + /cspace-services/personauthorities/ + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ + + + + POST + /cspace-services/relations/ + relation/r-1.xml + + ${Person1.CSID} + ${Person2.CSID} + Persons + Persons + hasBroader + + + + + POST + /cspace-services/relations/ + relation/r-1.xml + + + ${Person2.CSID} + ${Person1.CSID} + Persons + Persons + hasNarrower + + + + + + + + POST + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ + person/persons_common_w_relations.xml + + + CSPACE3739PersonAuthority + + + + + + + + POST + /cspace-services/personauthorities/ + person/personauthorities_common.xml + + CSPACE3739PersonAuthority + + + + + POST + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ + person/persons_common.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActor + + + + + POST + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ + person/persons_common.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActorParent + + + + + POST + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ + person/persons_common.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActorChild + + + + + POST + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ + person/persons_common.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActorChild2 + + + + + + PUT + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${Person1.CSID} + person/persons_common_w_relations.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActor + ${Person1.CSID} + ${PersonParent.CSID} + ${PersonChild.CSID} + + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}?showRelations=true + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${PersonChild.CSID}?showSiblings=true + + + + + PUT + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${Person1.CSID} + person/persons_common_w_relations_2.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActor + ${Person1.CSID} + ${PersonParent.CSID} + + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}?showRelations=true + + + + + PUT + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${Person1.CSID} + person/persons_common_w_relations.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActor + ${Person1.CSID} + ${PersonParent.CSID} + ${PersonChild.CSID} + + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}?showRelations=true + + + + PUT + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${Person1.CSID} + person/persons_common_w_relations_3.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActor + ${Person1.CSID} + ${PersonChild.CSID} + ${PersonChild2.CSID} + + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}?showRelations=true + + + + !-- ========================= POST a person ===================================================== --> + + + + POST + /cspace-services/personauthorities/ + person/personauthorities_common.xml + + CSPACE3739PersonAuthority + + + + + POST + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ + person/persons_common.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActorParent + + + + + POST + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ + person/persons_common.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActorChild + actorChild1 + + + + + POST + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ + person/persons_common.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActorChild2 + actorChild2 + + + + + POST + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ + person/persons_common.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActorChild3 + actorChild3 + + + + + POST + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ + person/persons_common_w_relations_POST.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActor + + ${PersonParent.CSID} + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonParent.CSID} + ${PersonChild.CSID} + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonChild.CSID} + ${PersonChild2.CSID} + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonChild2.CSID} + ${PersonChild3.CSID} + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonChild3.CSID} + + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}?showRelations=true + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${PersonChild.CSID}?showSiblings=true + + + person/res/GETpostPerson_siblings.res.xml + + ${Person1.CSID} + ${PersonChild.CSID} + ${PersonChild2.CSID} + ${PersonChild3.CSID} + ${PersonChild2.termDisplayNameSuffix} + ${PersonChild3.termDisplayNameSuffix} + + /document/*[local-name()='relations-common-list'] + + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}?showAllRelations=true + + + person/res/showAllRelations.res.xml + + /document/*[local-name()='relations-common-list'] + + + + + + GET + /cspace-services/relations/ + + + + GET + /cspace-services/relations?sbj=${PersonAuth1.CSID} + + + + GET + /cspace-services/relations?obj=${PersonAuth1.CSID} + + + + + + + POST + /cspace-services/personauthorities/ + person/personauthorities_common.xml + + CSPACE3739PersonAuthority + + + + + POST + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ + person/persons_common.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActorParent + + + + + + POST + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ + person/persons_common.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActorChild + + + + + POST + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ + person/persons_common.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActorChild2 + + + + + POST + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ + person/persons_common.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActorChild3 + + + + + + POST + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ + person/persons_common_w_relations_POST.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActor + ${PersonParent.CSID} + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonParent.CSID} + ${PersonChild.CSID} + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonChild.CSID} + ${PersonChild2.CSID} + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonChild2.CSID} + ${PersonChild3.CSID} + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonChild3.CSID} + + + + + GET + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${Person1.CSID}?showRelations=true + + + + GET + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/ + + + + PUT + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${Person1.CSID} + person/persons_common_delete_relations_PUT.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActor + ${PersonChild.CSID} + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${PersonChild.CSID} + + + + + GET + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${Person1.CSID}?showRelations=true + + + + + PUT + /cspace-services/personauthorities/urn:cspace:name(CSPACE3739PersonAuthority)/items/${Person1.CSID} + person/persons_common_delete_all_relations_PUT.xml + + ${PersonAuth1.CSID} + CSPACE3739PersonAuthority + johnWayneActor + + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/${Person1.CSID}?showRelations=true + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/personTermStatusSearch.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/personTermStatusSearch.xml index 499951824..964f8e3dc 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/personTermStatusSearch.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/personTermStatusSearch.xml @@ -1,83 +1,83 @@ - - - - - - POST - /cspace-services/personauthorities/ - person/personauthorities_common.xml - - TermStatusTestAuth - - - - POST - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ - person/person_pschmitz.xml - - Approved - - - - POST - /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ - person/person_pmadry.xml - - Inactive - - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items - - - person/res/personlistAll.res.xml - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items?ts=Inactive - - - person/res/personlistActive.res.xml - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items?ts=Garbage - - - person/res/personlistAll.res.xml - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items?ts=Inactive%7CApproved - - - person/res/personlistNone.res.xml - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items?pt=Patrick - - - person/res/personlistActive.res.xml - - - - GET - /cspace-services/personauthorities/${PersonAuth1.CSID}/items?pt=Patrick&ts=Approved - - - person/res/personlistNone.res.xml - - - - - + + + + + + POST + /cspace-services/personauthorities/ + person/personauthorities_common.xml + + TermStatusTestAuth + + + + POST + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ + person/person_pschmitz.xml + + Approved + + + + POST + /cspace-services/personauthorities/${PersonAuth1.CSID}/items/ + person/person_pmadry.xml + + Inactive + + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items + + + person/res/personlistAll.res.xml + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items?ts=Inactive + + + person/res/personlistActive.res.xml + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items?ts=Garbage + + + person/res/personlistAll.res.xml + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items?ts=Inactive%7CApproved + + + person/res/personlistNone.res.xml + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items?pt=Patrick + + + person/res/personlistActive.res.xml + + + + GET + /cspace-services/personauthorities/${PersonAuth1.CSID}/items?pt=Patrick&ts=Approved + + + person/res/personlistNone.res.xml + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/person_pmadry.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/person_pmadry.xml index a5f9d9888..e21bbc8d9 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/person_pmadry.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/person_pmadry.xml @@ -1,17 +1,17 @@ - - - - pmadry - - - - Penelope Madry, New York - false - Penelope Madry, New York - ${termStatus} - - - - Project Manager for CollectionSpace - - + + + + pmadry + + + + Penelope Madry, New York + false + Penelope Madry, New York + ${termStatus} + + + + Project Manager for CollectionSpace + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/person_pschmitz.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/person_pschmitz.xml index d7f2cb81c..ce4682096 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/person_pschmitz.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/person_pschmitz.xml @@ -1,20 +1,20 @@ - - - - pschmitz - - - - Patrick Schmitz, Berkeley - false - Patrick Schmitz, Berkeley - ${termStatus} - - - - Technical Lead for CollectionSpace - This is a test PersonAuthority item - Some mythical book - Let's say page 39 - - + + + + pschmitz + + + + Patrick Schmitz, Berkeley + false + Patrick Schmitz, Berkeley + ${termStatus} + + + + Technical Lead for CollectionSpace + This is a test PersonAuthority item + Some mythical book + Let's say page 39 + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/personauthorities_common.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/personauthorities_common.xml index 8a108d6f3..93d0d58ed 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/personauthorities_common.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/personauthorities_common.xml @@ -1,13 +1,13 @@ - - - -${authShortIdentifier} -${authShortIdentifier} -urn:cspace:org.collectionspace.demo:personauthority:name(${authShortIdentifier})'${authShortIdentifier}' -PersonAuthority - This is a test authority - Some mythical book - - - - + + + +${authShortIdentifier} +${authShortIdentifier} +urn:cspace:org.collectionspace.demo:personauthority:name(${authShortIdentifier})'${authShortIdentifier}' +PersonAuthority + This is a test authority + Some mythical book + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/personauthorities_testpersonauth.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/personauthorities_testpersonauth.xml index e3792f9bf..a14ed9ac9 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/personauthorities_testpersonauth.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/personauthorities_testpersonauth.xml @@ -1,12 +1,12 @@ - - - - testpersonauth - Test Person Authority - urn:cspace:org.collectionspace.demo:personauthority:name(testpersonauth)'Test Person Authority' - PersonAuthority - This is a test authority - Some mythical book - - - + + + + testpersonauth + Test Person Authority + urn:cspace:org.collectionspace.demo:personauthority:name(testpersonauth)'Test Person Authority' + PersonAuthority + This is a test authority + Some mythical book + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common.xml index 5e6765c98..614269c8d 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common.xml @@ -1,34 +1,34 @@ - - - - ${inAuthority} - ${shortIdentifier} - urn:cspace:org.collectionspace.demo:personauthority:name(${authShortIdentifier}):person:name(${shortIdentifier})'John Wayne' - - - - John Wayne - false - John Wayne${termDisplayNameSuffix} - John - Wayne - - - - May 26, 1907 - June 11, 1979 - Winterset, Iowa - - Irish - Scottish - - male - born Marion Robert Morrison and betterknown by his stage name John Wayne, was an American film actor, director and producer. He epitomized rugged masculinity and has become an enduring American icon. He is famous for his distinctive - voice, walk and height. He was also known for his conservative political views and his support in the 1950s for anti-communist positions. - This is a test Authority item - Some mythical book - Let's say page 39 - - - - + + + + ${inAuthority} + ${shortIdentifier} + urn:cspace:org.collectionspace.demo:personauthority:name(${authShortIdentifier}):person:name(${shortIdentifier})'John Wayne' + + + + John Wayne + false + John Wayne${termDisplayNameSuffix} + John + Wayne + + + + May 26, 1907 + June 11, 1979 + Winterset, Iowa + + Irish + Scottish + + male + born Marion Robert Morrison and betterknown by his stage name John Wayne, was an American film actor, director and producer. He epitomized rugged masculinity and has become an enduring American icon. He is famous for his distinctive + voice, walk and height. He was also known for his conservative political views and his support in the 1950s for anti-communist positions. + This is a test Authority item + Some mythical book + Let's say page 39 + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_delete_all_relations_PUT.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_delete_all_relations_PUT.xml index 4a36bf057..c48d74f39 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_delete_all_relations_PUT.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_delete_all_relations_PUT.xml @@ -1,37 +1,37 @@ - - - - ${inAuthority} - ${shortIdentifier} - urn:cspace:org.collectionspace.demo:personauthority:name(${authShortIdentifier}):person:name(${shortIdentifier})'John Wayne' - - - - John Wayne - false - John Wayne - John - Wayne - - - - May 26, 1907 - June 11, 1979 - Winterset, Iowa - - Irish - Scottish - - male - born Marion Robert Morrison and betterknown by his stage name John Wayne, was an American film actor, director and producer. He epitomized rugged masculinity and has become an enduring American icon. He is famous for his distinctive - voice, walk and height. He was also known for his conservative political views and his support in the 1950s for anti-communist positions. - - - - - - - + + + + ${inAuthority} + ${shortIdentifier} + urn:cspace:org.collectionspace.demo:personauthority:name(${authShortIdentifier}):person:name(${shortIdentifier})'John Wayne' + + + + John Wayne + false + John Wayne + John + Wayne + + + + May 26, 1907 + June 11, 1979 + Winterset, Iowa + + Irish + Scottish + + male + born Marion Robert Morrison and betterknown by his stage name John Wayne, was an American film actor, director and producer. He epitomized rugged masculinity and has become an enduring American icon. He is famous for his distinctive + voice, walk and height. He was also known for his conservative political views and his support in the 1950s for anti-communist positions. + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_delete_relations_PUT.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_delete_relations_PUT.xml index 820d7ad38..f76606255 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_delete_relations_PUT.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_delete_relations_PUT.xml @@ -1,53 +1,53 @@ - - - - ${inAuthority} - ${shortIdentifier} - urn:cspace:org.collectionspace.demo:personauthority:name(${authShortIdentifier}):person:name(${shortIdentifier})'John Wayne' - - - - John Wayne - false - John Wayne - John - Wayne - - - - May 26, 1907 - June 11, 1979 - Winterset, Iowa - - Irish - Scottish - - male - born Marion Robert Morrison and betterknown by his stage name John Wayne, was an American film actor, director and producer. He epitomized rugged masculinity and has become an enduring American icon. He is famous for his distinctive - voice, walk and height. He was also known for his conservative political views and his support in the 1950s for anti-communist positions. - - - - - hasBroader - - ${childCSID} - ${childUri} - Person - John Wayne 1, the evil twin, child - 2222 - - - ${itemCSID} - Person - John Wayne - 1111 - - - - - - + + + + ${inAuthority} + ${shortIdentifier} + urn:cspace:org.collectionspace.demo:personauthority:name(${authShortIdentifier}):person:name(${shortIdentifier})'John Wayne' + + + + John Wayne + false + John Wayne + John + Wayne + + + + May 26, 1907 + June 11, 1979 + Winterset, Iowa + + Irish + Scottish + + male + born Marion Robert Morrison and betterknown by his stage name John Wayne, was an American film actor, director and producer. He epitomized rugged masculinity and has become an enduring American icon. He is famous for his distinctive + voice, walk and height. He was also known for his conservative political views and his support in the 1950s for anti-communist positions. + + + + + hasBroader + + ${childCSID} + ${childUri} + Person + John Wayne 1, the evil twin, child + 2222 + + + ${itemCSID} + Person + John Wayne + 1111 + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_w_relations.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_w_relations.xml index 1564a871a..d68c5487a 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_w_relations.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_w_relations.xml @@ -1,79 +1,79 @@ - - - - ${inAuthority} - ${shortIdentifier} - urn:cspace:org.collectionspace.demo:personauthority:name(${authShortIdentifier}):person:name(${shortIdentifier})'John Wayne' - - - - John Wayne - false - John Wayne - John - Wayne - - - - May 26, 1907 - June 11, 1979 - Winterset, Iowa - - Irish - Scottish - - male - born Marion Robert Morrison and betterknown by his stage name John Wayne, was an American film actor, director and producer. He epitomized rugged masculinity and has become an enduring American icon. He is famous for his distinctive - voice, walk and height. He was also known for his conservative political views and his support in the 1950s for anti-communist positions. - - - - 0 - 40 - 1 - 1 - subjectCsid|relationshipType|predicateDisplayName|objectCsid|uri|csid|subject|object - - ${myCSID} - Person - Person - hasBroader - hasBroader - hasBroader - ${parentCSID} - - ${myCSID} - Person - John Wayne, Me - - - ${parentCSID} - Person - John Wayne 2, the evil twin, Parent - - - - ${childCSID} - Person - Person - hasBroader - hasBroader - hasBroader - ${myCSID} - - ${childCSID} - Person - John Wayne 2, the evil twin, child - - - ${myCSID} - Person - John Wayne - - - - - - - - + + + + ${inAuthority} + ${shortIdentifier} + urn:cspace:org.collectionspace.demo:personauthority:name(${authShortIdentifier}):person:name(${shortIdentifier})'John Wayne' + + + + John Wayne + false + John Wayne + John + Wayne + + + + May 26, 1907 + June 11, 1979 + Winterset, Iowa + + Irish + Scottish + + male + born Marion Robert Morrison and betterknown by his stage name John Wayne, was an American film actor, director and producer. He epitomized rugged masculinity and has become an enduring American icon. He is famous for his distinctive + voice, walk and height. He was also known for his conservative political views and his support in the 1950s for anti-communist positions. + + + + 0 + 40 + 1 + 1 + subjectCsid|relationshipType|predicateDisplayName|objectCsid|uri|csid|subject|object + + ${myCSID} + Person + Person + hasBroader + hasBroader + hasBroader + ${parentCSID} + + ${myCSID} + Person + John Wayne, Me + + + ${parentCSID} + Person + John Wayne 2, the evil twin, Parent + + + + ${childCSID} + Person + Person + hasBroader + hasBroader + hasBroader + ${myCSID} + + ${childCSID} + Person + John Wayne 2, the evil twin, child + + + ${myCSID} + Person + John Wayne + + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_w_relations_2.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_w_relations_2.xml index a257f38c8..6c8a740b3 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_w_relations_2.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_w_relations_2.xml @@ -1,60 +1,60 @@ - - - - ${inAuthority} - ${shortIdentifier} - urn:cspace:org.collectionspace.demo:personauthority:name(${authShortIdentifier}):person:name(${shortIdentifier})'John Wayne' - - - - John Wayne - false - John Wayne - John - Wayne - - - - May 26, 1907 - June 11, 1979 - Winterset, Iowa - - Irish - Scottish - - male - born Marion Robert Morrison and betterknown by his stage name John Wayne, was an American film actor, director and producer. He epitomized rugged masculinity and has become an enduring American icon. He is famous for his distinctive - voice, walk and height. He was also known for his conservative political views and his support in the 1950s for anti-communist positions. - - - - 0 - 40 - 1 - 1 - subjectCsid|relationshipType|predicateDisplayName|objectCsid|uri|csid|subject|object - - ${myCSID} - Person - Person - hasBroader - hasBroader - hasBroader - ${parentCSID} - - ${myCSID} - Person - John Wayne, Me - - - ${parentCSID} - Person - John Wayne 2, the evil twin, Parent - - - - - - - - + + + + ${inAuthority} + ${shortIdentifier} + urn:cspace:org.collectionspace.demo:personauthority:name(${authShortIdentifier}):person:name(${shortIdentifier})'John Wayne' + + + + John Wayne + false + John Wayne + John + Wayne + + + + May 26, 1907 + June 11, 1979 + Winterset, Iowa + + Irish + Scottish + + male + born Marion Robert Morrison and betterknown by his stage name John Wayne, was an American film actor, director and producer. He epitomized rugged masculinity and has become an enduring American icon. He is famous for his distinctive + voice, walk and height. He was also known for his conservative political views and his support in the 1950s for anti-communist positions. + + + + 0 + 40 + 1 + 1 + subjectCsid|relationshipType|predicateDisplayName|objectCsid|uri|csid|subject|object + + ${myCSID} + Person + Person + hasBroader + hasBroader + hasBroader + ${parentCSID} + + ${myCSID} + Person + John Wayne, Me + + + ${parentCSID} + Person + John Wayne 2, the evil twin, Parent + + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_w_relations_3.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_w_relations_3.xml index cc6175557..49132258a 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_w_relations_3.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_w_relations_3.xml @@ -1,79 +1,79 @@ - - - - ${inAuthority} - ${shortIdentifier} - urn:cspace:org.collectionspace.demo:personauthority:name(${authShortIdentifier}):person:name(${shortIdentifier})'John Wayne' - - - - John Wayne - false - John Wayne - John - Wayne - - - - May 26, 1907 - June 11, 1979 - Winterset, Iowa - - Irish - Scottish - - male - born Marion Robert Morrison and betterknown by his stage name John Wayne, was an American film actor, director and producer. He epitomized rugged masculinity and has become an enduring American icon. He is famous for his distinctive - voice, walk and height. He was also known for his conservative political views and his support in the 1950s for anti-communist positions. - - - - 0 - 40 - 1 - 1 - subjectCsid|relationshipType|predicateDisplayName|objectCsid|uri|csid|subject|object - - ${childCSID} - Person - Person - hasBroader - hasBroader - hasBroader - ${myCSID} - - ${childCSID} - Person - John Wayne 2, the evil twin, child - - - ${myCSID} - Person - John Wayne - - - - ${child2CSID} - Person - Person - hasBroader - hasBroader - hasBroader - ${myCSID} - - ${child2CSID} - Person - John Wayne 2, the evil twin, child - - - ${myCSID} - Person - John Wayne - - - - - - - - + + + + ${inAuthority} + ${shortIdentifier} + urn:cspace:org.collectionspace.demo:personauthority:name(${authShortIdentifier}):person:name(${shortIdentifier})'John Wayne' + + + + John Wayne + false + John Wayne + John + Wayne + + + + May 26, 1907 + June 11, 1979 + Winterset, Iowa + + Irish + Scottish + + male + born Marion Robert Morrison and betterknown by his stage name John Wayne, was an American film actor, director and producer. He epitomized rugged masculinity and has become an enduring American icon. He is famous for his distinctive + voice, walk and height. He was also known for his conservative political views and his support in the 1950s for anti-communist positions. + + + + 0 + 40 + 1 + 1 + subjectCsid|relationshipType|predicateDisplayName|objectCsid|uri|csid|subject|object + + ${childCSID} + Person + Person + hasBroader + hasBroader + hasBroader + ${myCSID} + + ${childCSID} + Person + John Wayne 2, the evil twin, child + + + ${myCSID} + Person + John Wayne + + + + ${child2CSID} + Person + Person + hasBroader + hasBroader + hasBroader + ${myCSID} + + ${child2CSID} + Person + John Wayne 2, the evil twin, child + + + ${myCSID} + Person + John Wayne + + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_w_relations_POST.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_w_relations_POST.xml index 0d05a7611..0443f1d36 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_w_relations_POST.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/persons_common_w_relations_POST.xml @@ -1,107 +1,107 @@ - - - - ${inAuthority} - ${shortIdentifier} - urn:cspace:org.collectionspace.demo:personauthority:name(${authShortIdentifier}):person:name(${shortIdentifier})'John Wayne' - - - - John Wayne - false - John Wayne - John - Wayne - - - - May 26, 1907 - June 11, 1979 - Winterset, Iowa - - Irish - Scottish - - male - born Marion Robert Morrison and betterknown by his stage name John Wayne, was an American film actor, director and producer. He epitomized rugged masculinity and has become an enduring American icon. He is famous for his distinctive - voice, walk and height. He was also known for his conservative political views and his support in the 1950s for anti-communist positions. - - - - 0 - 40 - 1 - 1 - subjectCsid|relationshipType|predicateDisplayName|objectCsid|uri|csid|subject|object - - hasBroader - - ${itemCSID} - Person - John Wayne, Me - 1111 - - - ${parentCSID} - ${parentUri} - Person - John Wayne 2, the evil twin, Parent - 0000 - - - - hasBroader - - ${childCSID} - ${childUri} - Person - John Wayne 1, the evil twin, child - 1100 - - - ${itemCSID} - Person - John Wayne - 1111 - - - - hasBroader - - ${child2Uri} - ${child2CSID} - Person - John Wayne 2, the evil twin, child - 2222 - - - ${itemCSID} - Person - John Wayne - 1111 - - - - hasBroader - - ${child3Uri} - ${child3CSID} - Person - John Wayne 3, the evil twin, child - 3333 - - - ${itemCSID} - Person - John Wayne - 1111 - - - - - - - + + + + ${inAuthority} + ${shortIdentifier} + urn:cspace:org.collectionspace.demo:personauthority:name(${authShortIdentifier}):person:name(${shortIdentifier})'John Wayne' + + + + John Wayne + false + John Wayne + John + Wayne + + + + May 26, 1907 + June 11, 1979 + Winterset, Iowa + + Irish + Scottish + + male + born Marion Robert Morrison and betterknown by his stage name John Wayne, was an American film actor, director and producer. He epitomized rugged masculinity and has become an enduring American icon. He is famous for his distinctive + voice, walk and height. He was also known for his conservative political views and his support in the 1950s for anti-communist positions. + + + + 0 + 40 + 1 + 1 + subjectCsid|relationshipType|predicateDisplayName|objectCsid|uri|csid|subject|object + + hasBroader + + ${itemCSID} + Person + John Wayne, Me + 1111 + + + ${parentCSID} + ${parentUri} + Person + John Wayne 2, the evil twin, Parent + 0000 + + + + hasBroader + + ${childCSID} + ${childUri} + Person + John Wayne 1, the evil twin, child + 1100 + + + ${itemCSID} + Person + John Wayne + 1111 + + + + hasBroader + + ${child2Uri} + ${child2CSID} + Person + John Wayne 2, the evil twin, child + 2222 + + + ${itemCSID} + Person + John Wayne + 1111 + + + + hasBroader + + ${child3Uri} + ${child3CSID} + Person + John Wayne 3, the evil twin, child + 3333 + + + ${itemCSID} + Person + John Wayne + 1111 + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/res/personlistActive.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/res/personlistActive.res.xml index bcc759c16..f42f8401a 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/res/personlistActive.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/res/personlistActive.res.xml @@ -1,11 +1,11 @@ - - - 0 - 40 - 1 - csid|uri|refName|updatedAt|displayName|shortIdentifier|termStatus - - pschmitz - - - + + + 0 + 40 + 1 + csid|uri|refName|updatedAt|displayName|shortIdentifier|termStatus + + pschmitz + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/res/personlistAll.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/res/personlistAll.res.xml index 12e22f149..34ab1f3ea 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/res/personlistAll.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/res/personlistAll.res.xml @@ -1,14 +1,14 @@ - - - 0 - 40 - 2 - csid|uri|refName|updatedAt|displayName|shortIdentifier|termStatus - - pschmitz - - - pmadry - - - + + + 0 + 40 + 2 + csid|uri|refName|updatedAt|displayName|shortIdentifier|termStatus + + pschmitz + + + pmadry + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/res/personlistNone.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/res/personlistNone.res.xml index 5b230c091..4f6c0ac69 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/res/personlistNone.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/person/res/personlistNone.res.xml @@ -1,8 +1,8 @@ - - - 0 - 40 - 0 - csid|uri|refName|updatedAt|displayName|shortIdentifier|termStatus - - + + + 0 + 40 + 0 + csid|uri|refName|updatedAt|displayName|shortIdentifier|termStatus + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/relation/oe1.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/relation/oe1.xml index 78ee56693..1e94f2838 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/relation/oe1.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/relation/oe1.xml @@ -1,10 +1,10 @@ - - - - urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum' - objectexitNumber-1290026472360 - - - + + + + urn:cspace:org.collectionspace.demo:orgauthority:name(TestOrgAuth):organization:name(Northern Climes Museum)'Northern Climes Museum' + objectexitNumber-1290026472360 + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/relation/relation.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/relation/relation.xml index 76150204d..bce5372a3 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/relation/relation.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/relation/relation.xml @@ -1,354 +1,354 @@ - - - - - YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= - - - - - POST - /cspace-services/objectexit/ - relation/oe1.xml - - - POST - /cspace-services/objectexit/ - relation/oe1.xml - - - POST - /cspace-services/relations/ - relation/r-1.xml - - ${oe1.CSID} - ${oe2.CSID} - objectexit - objectexit - hasBroader - - - - POST - /cspace-services/relations/ - relation/r-1.xml - - - ${oe2.CSID} - ${oe1.CSID} - objectexit - objectexit - hasBroader - - - - GET - /cspace-services/relations/ - - - - - - - - POST - /cspace-services/objectexit/ - relation/oe1.xml - - - POST - /cspace-services/objectexit/ - relation/oe1.xml - - - POST - /cspace-services/relations/ - relation/r-2.xml - - ${oe1.CSID} - ${itemCSID} - ObjectExit - ObjectExit - hasBroader - - - - GET - /cspace-services/relations/ - - - - - - POST - /cspace-services/relations/ - relation/r-2.xml - - 1234-5678 - ${itemCSID} - ObjectExit - ObjectExit - hasBroader - - - - GET - /cspace-services/relations/ - - - - - - - - POST - /cspace-services/objectexit/ - relation/oe1.xml - 201 - - - POST - /cspace-services/objectexit/ - relation/oe1.xml - 201 - - - POST - /cspace-services/relations - relation/r-1.xml - - ${createSubject.CSID} - ${createObject.CSID} - objectexit - objectexit - affects - - 201 - - - GET - /cspace-services/relations/${createRelation.CSID}/workflow - 200 - - - relation/res/workflowState.res.xml - - project - - - - - GET - /cspace-services/relations?sbj=${createSubject.CSID}&wf_deleted=false - 200 - - - relation/res/relationsList.res.xml - - 1 - - - - - PUT - /cspace-services/objectexit/${createSubject.CSID}/workflow/delete - 200 - - - - relation/res/workflowState.res.xml - - deleted - - - - GET - /cspace-services/objectexit/${createSubject.CSID}/workflow - 200 - - - relation/res/workflowState.res.xml - - deleted - - - - - GET - /cspace-services/relations/${createRelation.CSID}/workflow - 200 - - - relation/res/workflowState.res.xml - - deleted - - - - - GET - /cspace-services/relations?sbj=${createSubject.CSID}&wf_deleted=false - 200 - - - relation/res/relationsList.res.xml - - 0 - - - - - - - - - - POST - /cspace-services/objectexit/ - relation/oe1.xml - 201 - - - POST - /cspace-services/objectexit/ - relation/oe1.xml - 201 - - - POST - /cspace-services/objectexit/ - relation/oe1.xml - 201 - - - POST - /cspace-services/relations - relation/r-1.xml - - ${createSubject1.CSID} - ${createObject.CSID} - objectexit - objectexit - affects - - 201 - - - POST - /cspace-services/relations - relation/r-1.xml - - ${createSubject2.CSID} - ${createObject.CSID} - objectexit - objectexit - affects - - 201 - - - GET - /cspace-services/relations/${createRelation1.CSID}/workflow - 200 - - - relation/res/workflowState.res.xml - - project - - - - - GET - /cspace-services/relations/${createRelation2.CSID}/workflow - 200 - - - relation/res/workflowState.res.xml - - project - - - - - GET - /cspace-services/relations?obj=${createObject.CSID}&wf_deleted=false - 200 - - - relation/res/relationsList.res.xml - - 2 - - - - - PUT - /cspace-services/objectexit/${createObject.CSID}/workflow/delete - 200 - - - - relation/res/workflowState.res.xml - - deleted - - - - GET - /cspace-services/objectexit/${createObject.CSID}/workflow - 200 - - - relation/res/workflowState.res.xml - - deleted - - - - - GET - /cspace-services/relations/${createRelation1.CSID}/workflow - 200 - - - relation/res/workflowState.res.xml - - deleted - - - - - GET - /cspace-services/relations/${createRelation2.CSID}/workflow - 200 - - - relation/res/workflowState.res.xml - - deleted - - - - - GET - /cspace-services/relations?obj=${createObject.CSID}&wf_deleted=false - 200 - - - relation/res/relationsList.res.xml - - 0 - - - - - - - - + + + + + YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= + + + + + POST + /cspace-services/objectexit/ + relation/oe1.xml + + + POST + /cspace-services/objectexit/ + relation/oe1.xml + + + POST + /cspace-services/relations/ + relation/r-1.xml + + ${oe1.CSID} + ${oe2.CSID} + objectexit + objectexit + hasBroader + + + + POST + /cspace-services/relations/ + relation/r-1.xml + + + ${oe2.CSID} + ${oe1.CSID} + objectexit + objectexit + hasBroader + + + + GET + /cspace-services/relations/ + + + + + + + + POST + /cspace-services/objectexit/ + relation/oe1.xml + + + POST + /cspace-services/objectexit/ + relation/oe1.xml + + + POST + /cspace-services/relations/ + relation/r-2.xml + + ${oe1.CSID} + ${itemCSID} + ObjectExit + ObjectExit + hasBroader + + + + GET + /cspace-services/relations/ + + + + + + POST + /cspace-services/relations/ + relation/r-2.xml + + 1234-5678 + ${itemCSID} + ObjectExit + ObjectExit + hasBroader + + + + GET + /cspace-services/relations/ + + + + + + + + POST + /cspace-services/objectexit/ + relation/oe1.xml + 201 + + + POST + /cspace-services/objectexit/ + relation/oe1.xml + 201 + + + POST + /cspace-services/relations + relation/r-1.xml + + ${createSubject.CSID} + ${createObject.CSID} + objectexit + objectexit + affects + + 201 + + + GET + /cspace-services/relations/${createRelation.CSID}/workflow + 200 + + + relation/res/workflowState.res.xml + + project + + + + + GET + /cspace-services/relations?sbj=${createSubject.CSID}&wf_deleted=false + 200 + + + relation/res/relationsList.res.xml + + 1 + + + + + PUT + /cspace-services/objectexit/${createSubject.CSID}/workflow/delete + 200 + + + + relation/res/workflowState.res.xml + + deleted + + + + GET + /cspace-services/objectexit/${createSubject.CSID}/workflow + 200 + + + relation/res/workflowState.res.xml + + deleted + + + + + GET + /cspace-services/relations/${createRelation.CSID}/workflow + 200 + + + relation/res/workflowState.res.xml + + deleted + + + + + GET + /cspace-services/relations?sbj=${createSubject.CSID}&wf_deleted=false + 200 + + + relation/res/relationsList.res.xml + + 0 + + + + + + + + + + POST + /cspace-services/objectexit/ + relation/oe1.xml + 201 + + + POST + /cspace-services/objectexit/ + relation/oe1.xml + 201 + + + POST + /cspace-services/objectexit/ + relation/oe1.xml + 201 + + + POST + /cspace-services/relations + relation/r-1.xml + + ${createSubject1.CSID} + ${createObject.CSID} + objectexit + objectexit + affects + + 201 + + + POST + /cspace-services/relations + relation/r-1.xml + + ${createSubject2.CSID} + ${createObject.CSID} + objectexit + objectexit + affects + + 201 + + + GET + /cspace-services/relations/${createRelation1.CSID}/workflow + 200 + + + relation/res/workflowState.res.xml + + project + + + + + GET + /cspace-services/relations/${createRelation2.CSID}/workflow + 200 + + + relation/res/workflowState.res.xml + + project + + + + + GET + /cspace-services/relations?obj=${createObject.CSID}&wf_deleted=false + 200 + + + relation/res/relationsList.res.xml + + 2 + + + + + PUT + /cspace-services/objectexit/${createObject.CSID}/workflow/delete + 200 + + + + relation/res/workflowState.res.xml + + deleted + + + + GET + /cspace-services/objectexit/${createObject.CSID}/workflow + 200 + + + relation/res/workflowState.res.xml + + deleted + + + + + GET + /cspace-services/relations/${createRelation1.CSID}/workflow + 200 + + + relation/res/workflowState.res.xml + + deleted + + + + + GET + /cspace-services/relations/${createRelation2.CSID}/workflow + 200 + + + relation/res/workflowState.res.xml + + deleted + + + + + GET + /cspace-services/relations?obj=${createObject.CSID}&wf_deleted=false + 200 + + + relation/res/relationsList.res.xml + + 0 + + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/relation/res/workflowState.res.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/relation/res/workflowState.res.xml index 7182973b5..5b1428c7a 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/relation/res/workflowState.res.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/relation/res/workflowState.res.xml @@ -1,7 +1,7 @@ - - - - cs_default - ${workflowState} - + + + + cs_default + ${workflowState} + \ No newline at end of file diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/report/report.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/report/report.xml index 57c6960a3..1b0ccaf78 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/report/report.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/report/report.xml @@ -1,67 +1,67 @@ - - - - - - YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= - - - - - - POST - /cspace-services/reports/ - report/report1Record.xml - 201 - - - GET - /cspace-services/reports/${createReport1.CSID} - - - - POST - /cspace-services/acquisitions/ - report/acquisition1.xml - - Ac2011.1.2-jdlmbsoq - - 201 - - - - - POST - /cspace-services/reports/${createReport1.CSID} - report/report1InvContextStandalone.xml - - ${createAcquisition1.CSID} - - - - report/res/report1.res.xml - - ${createAcquisition1.acquisitionReferenceNumber} - - - 200 - - - - - - - - - - + + + + + + YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= + + + + + + POST + /cspace-services/reports/ + report/report1Record.xml + 201 + + + GET + /cspace-services/reports/${createReport1.CSID} + + + + POST + /cspace-services/acquisitions/ + report/acquisition1.xml + + Ac2011.1.2-jdlmbsoq + + 201 + + + + + POST + /cspace-services/reports/${createReport1.CSID} + report/report1InvContextStandalone.xml + + ${createAcquisition1.CSID} + + + + report/res/report1.res.xml + + ${createAcquisition1.acquisitionReferenceNumber} + + + 200 + + + + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/report/report1InvContextStandalone.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/report/report1InvContextStandalone.xml index ba95d818f..15bdc22a2 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/report/report1InvContextStandalone.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/report/report1InvContextStandalone.xml @@ -1,10 +1,10 @@ - - - single - Acquisition - ${acquisitionCSID} - - - + + + single + Acquisition + ${acquisitionCSID} + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security.xml index fce3290a1..013d72b5c 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security.xml @@ -1,441 +1,441 @@ - - - - - YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= - dXNlcjFAbXVzZXVtMS5vcmc6dXNlcjFAbXVzZXVtMS5vcmc= - YmlnYmlyZDIwMTA6YmlnYmlyZDIwMTA= - ZWxtbzIwMTA6ZWxtbzIwMTA= - - - - - - POST - /cspace-services/authorization/permissions - security/2-elmo-permission.xml - - - POST - /cspace-services/authorization/permissions/${permElmo.CSID}/permroles - security/10-permissionroles-elmo.xml - - - POST - /cspace-services/accounts - security/6-account-elmo.xml - - - - POST - /cspace-services/dimensions/ - dimension/1.xml - - - 403 - DELETE - dimension1 - - - DELETE - dimension1 - - - DELETE - /cspace-services/authorization/permissions/${permElmo.CSID}/permroles - - - DELETE - accountElmo - - - - - - - - - 401,500,501 - POST - /cspace-services/dimensions/ - dimension/1.xml - - - - - POST - /cspace-services/authorization/permissions - security/1-bigbird-permission.xml - - - POST - /cspace-services/authorization/permissions - security/2-elmo-permission.xml - - - POST - /cspace-services/authorization/roles - security/3-role-test-cm.xml - - - POST - /cspace-services/authorization/roles - security/4-role-intern.xml - - - POST - /cspace-services/accounts - security/5-account-bigbird.xml - - - POST - /cspace-services/accounts - security/6-account-elmo.xml - - - POST - /cspace-services/accounts/${accountBigbird.CSID}/accountroles - security/7-accountroles-bigbird.xml - - - POST - /cspace-services/accounts/${accountElmo.CSID}/accountroles - security/8-account-roles-elmo.xml - - - POST - /cspace-services/authorization/permissions/${permBigbird.CSID}/permroles - security/9-permissionroles-bigbird.xml - - - POST - /cspace-services/authorization/permissions/${permElmo.CSID}/permroles - security/10-permissionroles-elmo.xml - - - - POST - /cspace-services/dimensions/ - dimension/1.xml - - - PUT - /cspace-services/dimensions/${dimension1.CSID} - dimension/2-put.xml - - - GET - /cspace-services/dimensions/ - dimension1 - - - 403 - POST - /cspace-services/dimensions/ - dimension/1.xml - - - 403 - PUT - /cspace-services/dimensions/${dimension1.CSID} - dimension/2-put.xml - - - GET - /cspace-services/dimensions/ - dimension1 - - - 403 - DELETE - dimension1 - - - DELETE - dimension1 - - - - - - - DELETE - /cspace-services/authorization/permissions/${permBigbird.CSID}/permroles - - - - DELETE - /cspace-services/authorization/permissions/${permElmo.CSID}/permroles - - - - Removing all permissions from Bigbird's role - 403,404 - POST - /cspace-services/dimensions/ - dimension/1.xml - - - 404 - PUT - /cspace-services/dimensions/${dimension1.CSID} - dimension/2-put.xml - - - - - DELETE - /cspace-services/accounts/${accountBigbird.CSID}/accountroles - - - DELETE - /cspace-services/accounts/${accountElmo.CSID}/accountroles - - - DELETE - - ${roleTestCM.deleteURL} - roleTestCM - - - DELETE - roleIntern - - - DELETE - accountBigbird - - - DELETE - accountElmo - - - - - - - - - - - - - - - 401,403,500,501 - POST - /cspace-services/dimensions/ - dimension/1.xml - - - - - POST - /cspace-services/authorization/permissions - security/1-bigbird-permission.xml - - - POST - /cspace-services/authorization/roles - security/3-role-test-cm.xml - - - POST - /cspace-services/accounts - security/5-account-bigbird.xml - - - POST - /cspace-services/accounts/${accountBigbird.CSID}/accountroles - security/7-accountroles-bigbird.xml - - - POST - /cspace-services/authorization/permissions/${permBigbird.CSID}/permroles - security/9-permissionroles-bigbird.xml - - - - - - - POST - /cspace-services/dimensions/ - dimension/1.xml - - - - PUT - /cspace-services/dimensions/${dimensionBigbird_POST.CSID} - dimension/2-put.xml - - - - - - GET - /cspace-services/dimensions/ - dimensionBigbird_POST - - - DELETE - dimensionBigbird_POST - - - - - - Deleting permroles from bigbird2010 - DELETE - /cspace-services/authorization/permissions/${permBigbird.CSID}/permroles - - - - - - Trying to POST after permroles removed from Bigbird - 403,404 - POST - /cspace-services/dimensions/ - dimension/1.xml - - - 403,404,405 - PUT - /cspace-services/dimensions/${dimensionBigbird_POST_AfterPermrolesDeleted.CSID} - dimension/2-put.xml - - - 403,404 - GET - /cspace-services/dimensions/ - dimensionBigbird_POST_AfterPermrolesDeleted - - - 0,403,404 - DELETE - dimensionBigbird_POST_AfterPermrolesDeleted - - - - - - POST - /cspace-services/authorization/permissions - security/11-bigbird-permission-CRU.xml - - - POST - /cspace-services/authorization/permissions/${permBigbird_CRU.CSID}/permroles - security/11-permissionroles-bigbird-CRU.xml - - - - - - POST - /cspace-services/dimensions/ - dimension/1.xml - - - PUT - /cspace-services/dimensions/${dimensionBigbird_POST_CRU.CSID} - dimension/2-put.xml - - - GET - /cspace-services/dimensions/ - dimensionBigbird_POST_CRU - - - 403,404 - DELETE - dimensionBigbird_POST_CRU - - - - - - Deleting permroles from bigbird2010 - DELETE - /cspace-services/authorization/permissions/${permBigbird_CRU.CSID}/permroles - - - - - - POST - /cspace-services/authorization/permissions - security/12-bigbird-permission-R.xml - - - POST - /cspace-services/authorization/permissions/${permBigbird_R.CSID}/permroles - security/12-permissionroles-bigbird-R.xml - - - - - - 403,404 - POST - /cspace-services/dimensions/ - dimension/1.xml - - - 403,404,405 - PUT - /cspace-services/dimensions/${dimensionBigbird_POST_R.CSID} - dimension/2-put.xml - - - GET - /cspace-services/dimensions/ - dimensionBigbird_POST_R - - - - 0,403,404 - DELETE - dimensionBigbird_POST_R - - - - - - Deleting permroles from bigbird2010 - DELETE - /cspace-services/authorization/permissions/${permBigbird.CSID}/permroles - - - DELETE - /cspace-services/accounts/${accountBigbird.CSID}/accountroles - - - DELETE - roleTestCM - - - DELETE - accountBigbird - - - - - - - - - + + + + + YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= + dXNlcjFAbXVzZXVtMS5vcmc6dXNlcjFAbXVzZXVtMS5vcmc= + YmlnYmlyZDIwMTA6YmlnYmlyZDIwMTA= + ZWxtbzIwMTA6ZWxtbzIwMTA= + + + + + + POST + /cspace-services/authorization/permissions + security/2-elmo-permission.xml + + + POST + /cspace-services/authorization/permissions/${permElmo.CSID}/permroles + security/10-permissionroles-elmo.xml + + + POST + /cspace-services/accounts + security/6-account-elmo.xml + + + + POST + /cspace-services/dimensions/ + dimension/1.xml + + + 403 + DELETE + dimension1 + + + DELETE + dimension1 + + + DELETE + /cspace-services/authorization/permissions/${permElmo.CSID}/permroles + + + DELETE + accountElmo + + + + + + + + + 401,500,501 + POST + /cspace-services/dimensions/ + dimension/1.xml + + + + + POST + /cspace-services/authorization/permissions + security/1-bigbird-permission.xml + + + POST + /cspace-services/authorization/permissions + security/2-elmo-permission.xml + + + POST + /cspace-services/authorization/roles + security/3-role-test-cm.xml + + + POST + /cspace-services/authorization/roles + security/4-role-intern.xml + + + POST + /cspace-services/accounts + security/5-account-bigbird.xml + + + POST + /cspace-services/accounts + security/6-account-elmo.xml + + + POST + /cspace-services/accounts/${accountBigbird.CSID}/accountroles + security/7-accountroles-bigbird.xml + + + POST + /cspace-services/accounts/${accountElmo.CSID}/accountroles + security/8-account-roles-elmo.xml + + + POST + /cspace-services/authorization/permissions/${permBigbird.CSID}/permroles + security/9-permissionroles-bigbird.xml + + + POST + /cspace-services/authorization/permissions/${permElmo.CSID}/permroles + security/10-permissionroles-elmo.xml + + + + POST + /cspace-services/dimensions/ + dimension/1.xml + + + PUT + /cspace-services/dimensions/${dimension1.CSID} + dimension/2-put.xml + + + GET + /cspace-services/dimensions/ + dimension1 + + + 403 + POST + /cspace-services/dimensions/ + dimension/1.xml + + + 403 + PUT + /cspace-services/dimensions/${dimension1.CSID} + dimension/2-put.xml + + + GET + /cspace-services/dimensions/ + dimension1 + + + 403 + DELETE + dimension1 + + + DELETE + dimension1 + + + + + + + DELETE + /cspace-services/authorization/permissions/${permBigbird.CSID}/permroles + + + + DELETE + /cspace-services/authorization/permissions/${permElmo.CSID}/permroles + + + + Removing all permissions from Bigbird's role + 403,404 + POST + /cspace-services/dimensions/ + dimension/1.xml + + + 404 + PUT + /cspace-services/dimensions/${dimension1.CSID} + dimension/2-put.xml + + + + + DELETE + /cspace-services/accounts/${accountBigbird.CSID}/accountroles + + + DELETE + /cspace-services/accounts/${accountElmo.CSID}/accountroles + + + DELETE + + ${roleTestCM.deleteURL} + roleTestCM + + + DELETE + roleIntern + + + DELETE + accountBigbird + + + DELETE + accountElmo + + + + + + + + + + + + + + + 401,403,500,501 + POST + /cspace-services/dimensions/ + dimension/1.xml + + + + + POST + /cspace-services/authorization/permissions + security/1-bigbird-permission.xml + + + POST + /cspace-services/authorization/roles + security/3-role-test-cm.xml + + + POST + /cspace-services/accounts + security/5-account-bigbird.xml + + + POST + /cspace-services/accounts/${accountBigbird.CSID}/accountroles + security/7-accountroles-bigbird.xml + + + POST + /cspace-services/authorization/permissions/${permBigbird.CSID}/permroles + security/9-permissionroles-bigbird.xml + + + + + + + POST + /cspace-services/dimensions/ + dimension/1.xml + + + + PUT + /cspace-services/dimensions/${dimensionBigbird_POST.CSID} + dimension/2-put.xml + + + + + + GET + /cspace-services/dimensions/ + dimensionBigbird_POST + + + DELETE + dimensionBigbird_POST + + + + + + Deleting permroles from bigbird2010 + DELETE + /cspace-services/authorization/permissions/${permBigbird.CSID}/permroles + + + + + + Trying to POST after permroles removed from Bigbird + 403,404 + POST + /cspace-services/dimensions/ + dimension/1.xml + + + 403,404,405 + PUT + /cspace-services/dimensions/${dimensionBigbird_POST_AfterPermrolesDeleted.CSID} + dimension/2-put.xml + + + 403,404 + GET + /cspace-services/dimensions/ + dimensionBigbird_POST_AfterPermrolesDeleted + + + 0,403,404 + DELETE + dimensionBigbird_POST_AfterPermrolesDeleted + + + + + + POST + /cspace-services/authorization/permissions + security/11-bigbird-permission-CRU.xml + + + POST + /cspace-services/authorization/permissions/${permBigbird_CRU.CSID}/permroles + security/11-permissionroles-bigbird-CRU.xml + + + + + + POST + /cspace-services/dimensions/ + dimension/1.xml + + + PUT + /cspace-services/dimensions/${dimensionBigbird_POST_CRU.CSID} + dimension/2-put.xml + + + GET + /cspace-services/dimensions/ + dimensionBigbird_POST_CRU + + + 403,404 + DELETE + dimensionBigbird_POST_CRU + + + + + + Deleting permroles from bigbird2010 + DELETE + /cspace-services/authorization/permissions/${permBigbird_CRU.CSID}/permroles + + + + + + POST + /cspace-services/authorization/permissions + security/12-bigbird-permission-R.xml + + + POST + /cspace-services/authorization/permissions/${permBigbird_R.CSID}/permroles + security/12-permissionroles-bigbird-R.xml + + + + + + 403,404 + POST + /cspace-services/dimensions/ + dimension/1.xml + + + 403,404,405 + PUT + /cspace-services/dimensions/${dimensionBigbird_POST_R.CSID} + dimension/2-put.xml + + + GET + /cspace-services/dimensions/ + dimensionBigbird_POST_R + + + + 0,403,404 + DELETE + dimensionBigbird_POST_R + + + + + + Deleting permroles from bigbird2010 + DELETE + /cspace-services/authorization/permissions/${permBigbird.CSID}/permroles + + + DELETE + /cspace-services/accounts/${accountBigbird.CSID}/accountroles + + + DELETE + roleTestCM + + + DELETE + accountBigbird + + + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/1-bigbird-permission.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/1-bigbird-permission.xml index b806b583f..3f7afdb7c 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/1-bigbird-permission.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/1-bigbird-permission.xml @@ -1,18 +1,18 @@ - - - dimensions - - CREATE - - - READ - - - UPDATE - - - DELETE - - PERMIT - - + + + dimensions + + CREATE + + + READ + + + UPDATE + + + DELETE + + PERMIT + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/10-permissionroles-elmo.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/10-permissionroles-elmo.xml index 0806b9414..af52b93e4 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/10-permissionroles-elmo.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/10-permissionroles-elmo.xml @@ -1,13 +1,13 @@ - - - - ${permElmo.CSID} - dimensions - - - ${roleIntern.CSID} - ROLE_TEST_INTERN - - - + + + + ${permElmo.CSID} + dimensions + + + ${roleIntern.CSID} + ROLE_TEST_INTERN + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/11-bigbird-permission-CRU.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/11-bigbird-permission-CRU.xml index f542aa5e6..bb7ae5607 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/11-bigbird-permission-CRU.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/11-bigbird-permission-CRU.xml @@ -1,16 +1,16 @@ - - - dimensions - - CREATE - - - READ - - - UPDATE - - PERMIT - - + + + dimensions + + CREATE + + + READ + + + UPDATE + + PERMIT + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/11-permissionroles-bigbird-CRU.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/11-permissionroles-bigbird-CRU.xml index 90287511f..df8889fb6 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/11-permissionroles-bigbird-CRU.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/11-permissionroles-bigbird-CRU.xml @@ -1,13 +1,13 @@ - - - - ${permBigbird_CRU.CSID} - dimensions - - - ${roleTestCM.CSID} - ROLE_TEST_CM - - - + + + + ${permBigbird_CRU.CSID} + dimensions + + + ${roleTestCM.CSID} + ROLE_TEST_CM + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/12-bigbird-permission-R.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/12-bigbird-permission-R.xml index 4786d012f..6d4da79f5 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/12-bigbird-permission-R.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/12-bigbird-permission-R.xml @@ -1,10 +1,10 @@ - - - dimensions - - READ - - PERMIT - - + + + dimensions + + READ + + PERMIT + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/12-permissionroles-bigbird-R.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/12-permissionroles-bigbird-R.xml index dde7075cc..f4517f2d9 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/12-permissionroles-bigbird-R.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/12-permissionroles-bigbird-R.xml @@ -1,13 +1,13 @@ - - - - ${permBigbird_R.CSID} - dimensions - - - ${roleTestCM.CSID} - ROLE_TEST_CM - - - + + + + ${permBigbird_R.CSID} + dimensions + + + ${roleTestCM.CSID} + ROLE_TEST_CM + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/13-permissionroles-bigbird.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/13-permissionroles-bigbird.xml index dde7075cc..f4517f2d9 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/13-permissionroles-bigbird.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/13-permissionroles-bigbird.xml @@ -1,13 +1,13 @@ - - - - ${permBigbird_R.CSID} - dimensions - - - ${roleTestCM.CSID} - ROLE_TEST_CM - - - + + + + ${permBigbird_R.CSID} + dimensions + + + ${roleTestCM.CSID} + ROLE_TEST_CM + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/2-elmo-permission.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/2-elmo-permission.xml index 684999962..d4eec7790 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/2-elmo-permission.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/2-elmo-permission.xml @@ -1,8 +1,8 @@ - - - dimensions - - READ - - PERMIT - + + + dimensions + + READ + + PERMIT + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/3-role-test-cm.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/3-role-test-cm.xml index d81506a7f..8575b3a78 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/3-role-test-cm.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/3-role-test-cm.xml @@ -1,6 +1,6 @@ - - - ROLE_TEST_CM - role for ROLE_TEST_CM - + + + ROLE_TEST_CM + role for ROLE_TEST_CM + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/4-role-intern.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/4-role-intern.xml index b0fdce4b8..d74115ed2 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/4-role-intern.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/4-role-intern.xml @@ -1,5 +1,5 @@ - - - ROLE_TEST_INTERN - role for ROLE_TEST_INTERN - + + + ROLE_TEST_INTERN + role for ROLE_TEST_INTERN + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/5-account-bigbird.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/5-account-bigbird.xml index ed2795378..023dd1dbe 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/5-account-bigbird.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/5-account-bigbird.xml @@ -1,15 +1,15 @@ - - - bigbird2010 - bigbird2010 - bigbird@cspace.org - 1234567890 - bigbird2010 - - YmlnYmlyZDIwMTA= - - 1 - - + + + bigbird2010 + bigbird2010 + bigbird@cspace.org + 1234567890 + bigbird2010 + + YmlnYmlyZDIwMTA= + + 1 + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/6-account-elmo.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/6-account-elmo.xml index dc3bf0301..af1447aee 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/6-account-elmo.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/6-account-elmo.xml @@ -1,16 +1,16 @@ - - - elmo2010 - elmo2010 - elmo@cspace.org - 1234567890 - elmo2010 - - ZWxtbzIwMTA= - - 1 - - - + + + elmo2010 + elmo2010 + elmo@cspace.org + 1234567890 + elmo2010 + + ZWxtbzIwMTA= + + 1 + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/7-accountroles-bigbird.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/7-accountroles-bigbird.xml index 585db05b5..a1d518c04 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/7-accountroles-bigbird.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/7-accountroles-bigbird.xml @@ -1,15 +1,15 @@ - - - ROLE - - ${accountBigbird.CSID} - bigbird2010 - bigbird2010 - - - ${roleTestCM.CSID} - ROLE_TEST_CM - - - + + + ROLE + + ${accountBigbird.CSID} + bigbird2010 + bigbird2010 + + + ${roleTestCM.CSID} + ROLE_TEST_CM + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/8-account-roles-elmo.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/8-account-roles-elmo.xml index 1e34d9f5d..5c321065e 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/8-account-roles-elmo.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/8-account-roles-elmo.xml @@ -1,15 +1,15 @@ - - - ROLE - - ${permElmo.CSID} - elmo2010 - elmo2010 - - - ${roleIntern.CSID} - ROLE_TEST_INTERN - - - + + + ROLE + + ${permElmo.CSID} + elmo2010 + elmo2010 + + + ${roleIntern.CSID} + ROLE_TEST_INTERN + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/9-permissionroles-bigbird.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/9-permissionroles-bigbird.xml index 9e05c2fdd..08df47170 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/9-permissionroles-bigbird.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/9-permissionroles-bigbird.xml @@ -1,13 +1,13 @@ - - - - ${permBigbird.CSID} - dimensions - - - ${roleTestCM.CSID} - ROLE_TEST_CM - - - + + + + ${permBigbird.CSID} + dimensions + + + ${roleTestCM.CSID} + ROLE_TEST_CM + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/Base64-authentication-notes.txt b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/Base64-authentication-notes.txt index 8a31d0df0..8b73a3caa 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/Base64-authentication-notes.txt +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/security/Base64-authentication-notes.txt @@ -1,44 +1,44 @@ - bigbird2010 - bsh % unp = "bigbird2010:bigbird2010"; - - bsh % String encoding = new sun.misc.BASE64Encoder().encode (unp.getBytes()); - bsh % encoding = new sun.misc.BASE64Encoder().encode (unp.getBytes()); - - - bsh % unp = "bigbird2010:bigbird2010"; - - bsh % encoding = new sun.misc.BASE64Encoder().encode (unp.getBytes()); - - - bsh % String decode(String s){return new String(Base64.decode(s.getBytes()));} - - bsh % decode("dGVzdC1wYWhtYTp0ZXN0"); - test-pahma:test - //used for DELETE /cspace-services/accounts/9230dc97-0888-4252-8c89-795c92305ca0 HTTP/1.1 - - //used for creating accounts, roles, etc: - bsh % decode("dGVzdDp0ZXN0"); - test:test - - //used for dimension service tests: - bsh % decode("dXNlcjFAbXVzZXVtMS5vcmc6dXNlcjFAbXVzZXVtMS5vcmc="); - user1@museum1.org:user1@museum1.org - - dGVzdDpudWxs - bsh % decode("dGVzdDpudWxs"); - test:null (no password) - ==> HTTP/1.1 401 Password Incorrect/Password Required - - bsh % decode("dXNlcjJAbXVzZXVtMi5vcmc6dXNlcjJAbXVzZXVtMi5vcmc="); - user2@museum2.org:user2@museum2.org - DELETE OK on DELETE /cspace-services/dimensions/7922ea12-401d-4a7b-9f1a HTTP/1.1 - - dGVzdDpiYXI= - test:bar - //used for incorrect password. - Some more forbidden auths: - bsh % decode("YmFieWJvcDpiYWJ5Ym9wMDk="); - babybop:babybop09 - bsh % decode("YmFybmV5OmJhcm5leTA4"); - barney:barney08 - + bigbird2010 + bsh % unp = "bigbird2010:bigbird2010"; + + bsh % String encoding = new sun.misc.BASE64Encoder().encode (unp.getBytes()); + bsh % encoding = new sun.misc.BASE64Encoder().encode (unp.getBytes()); + + + bsh % unp = "bigbird2010:bigbird2010"; + + bsh % encoding = new sun.misc.BASE64Encoder().encode (unp.getBytes()); + + + bsh % String decode(String s){return new String(Base64.decode(s.getBytes()));} + + bsh % decode("dGVzdC1wYWhtYTp0ZXN0"); + test-pahma:test + //used for DELETE /cspace-services/accounts/9230dc97-0888-4252-8c89-795c92305ca0 HTTP/1.1 + + //used for creating accounts, roles, etc: + bsh % decode("dGVzdDp0ZXN0"); + test:test + + //used for dimension service tests: + bsh % decode("dXNlcjFAbXVzZXVtMS5vcmc6dXNlcjFAbXVzZXVtMS5vcmc="); + user1@museum1.org:user1@museum1.org + + dGVzdDpudWxs + bsh % decode("dGVzdDpudWxs"); + test:null (no password) + ==> HTTP/1.1 401 Password Incorrect/Password Required + + bsh % decode("dXNlcjJAbXVzZXVtMi5vcmc6dXNlcjJAbXVzZXVtMi5vcmc="); + user2@museum2.org:user2@museum2.org + DELETE OK on DELETE /cspace-services/dimensions/7922ea12-401d-4a7b-9f1a HTTP/1.1 + + dGVzdDpiYXI= + test:bar + //used for incorrect password. + Some more forbidden auths: + bsh % decode("YmFieWJvcDpiYWJ5Ym9wMDk="); + babybop:babybop09 + bsh % decode("YmFybmV5OmJhcm5leTA4"); + barney:barney08 + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/xml-replay-master-self-test.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/xml-replay-master-self-test.xml index 44e4012f9..fe8f1134f 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/xml-replay-master-self-test.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/xml-replay-master-self-test.xml @@ -1,16 +1,16 @@ - - - http://localhost:8180 - - - - - - YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= - - - - - + + + http://localhost:8180 + + + + + + YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/xml-replay-master.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/xml-replay-master.xml index 52a57212c..26f4e3706 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/xml-replay-master.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/xml-replay-master.xml @@ -1,94 +1,94 @@ - - - http://localhost:8180 - - - - - - YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + http://localhost:8180 + + + + + + YWRtaW5AY29yZS5jb2xsZWN0aW9uc3BhY2Uub3JnOkFkbWluaXN0cmF0b3I= + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/xml-replay-self-test.xml b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/xml-replay-self-test.xml index 12a695c0c..0c056cc36 100644 --- a/services/IntegrationTests/src/test/resources/test-data/xmlreplay/xml-replay-self-test.xml +++ b/services/IntegrationTests/src/test/resources/test-data/xmlreplay/xml-replay-self-test.xml @@ -1,39 +1,39 @@ - - - - + + + + diff --git a/services/JaxRsServiceProvider/pom.xml b/services/JaxRsServiceProvider/pom.xml index 8ce200604..ed9ae51de 100644 --- a/services/JaxRsServiceProvider/pom.xml +++ b/services/JaxRsServiceProvider/pom.xml @@ -1,770 +1,770 @@ - - - - - org.collectionspace.services.main - org.collectionspace.services - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.jaxrs.provider - services.jaxrs.provider - war - - - 0.5 - 3.0.0.RELEASE - 3.0.2.RELEASE - - - - - org.slf4j - slf4j-api - provided - - - org.slf4j - slf4j-log4j12 - provided - - - log4j - log4j - 1.2.14 - provided - - - - org.slf4j - slf4j-simple - 1.6.1 - test - - - org.slf4j - jcl-over-slf4j - 1.6.1 - test - - - - org.collectionspace.services - org.collectionspace.services.authority.service - ${project.version} - - - nuxeo-core-facade - org.nuxeo.ecm.core - - - servlet-api-2.5 - org.mortbay.jetty - - - - - org.collectionspace.services - org.collectionspace.services.authorization.service - ${project.version} - - - jboss-logging-log4j - org.jboss.logging - - - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - servlet-api-2.5 - org.mortbay.jetty - - - - - org.collectionspace.services - org.collectionspace.services.account.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authorization-mgt.service - ${project.version} - - - jboss-logging-log4j - org.jboss.logging - - - org.collectionspace.services - org.collectionspace.services.authorization-mgt.import - - - - - org.collectionspace.services - org.collectionspace.services.blob.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.collectionobject.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.id.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.intake.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.group.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.loanin.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.loanout.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.conditioncheck.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.objectexit.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.batch.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.imports.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.media.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.valuationcontrol.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.location.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.place.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.work.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.concept.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.taxonomy.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.movement.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.report.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.dimension.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.publicitem.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.servicegroup.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.contact.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.acquisition.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.vocabulary.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.organization.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.person.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.citation.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.relation.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.workflow.service - ${project.version} - - - - commons-io - commons-io - - - org.jboss.resteasy - jaxrs-api - - - org.jboss.resteasy - resteasy-jaxrs - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - junit - junit - 4.1 - test - - - - - - - - org.springframework.security - spring-security-core - ${spring.security.version} - provided - - - org.springframework.security - spring-security-config - ${spring.security.version} - provided - - - org.springframework.security - spring-security-web - ${spring.security.version} - provided - - - org.springframework - spring-context - ${spring.version} - provided - - - org.springframework - spring-context-support - ${spring.version} - provided - - - org.springframework - spring-web - ${spring.version} - provided - - - - - - servlet-api - javax.servlet - provided - - - - - jboss - jboss-remoting - 2.2.2.SP8 - provided - - - - - org.nuxeo.common - nuxeo-common - ${nuxeo.core.version} - - - org.nuxeo.runtime - nuxeo-runtime - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core - ${nuxeo.core.version} - - - xerces - xercesImpl - - - - - org.nuxeo.ecm.core - nuxeo-core-api - - - org.nuxeo.ecm.core - nuxeo-core-convert - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-storage-sql-extensions - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-storage-sql-ra - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-client - ${nuxeo.core.version} - - - org.jboss.jbossas - jboss-as-jbossas-remoting - - - - - org.nuxeo.ecm.core - nuxeo-core-query - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-schema - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-io - ${nuxeo.core.version} - - - - org.nuxeo.runtime - nuxeo-runtime-jtajca - ${nuxeo.core.version} - - - - geronimo-transaction - org.apache.geronimo.components - - - geronimo-connector - org.apache.geronimo.components - - - - - org.nuxeo.runtime - nuxeo-runtime-datasource - ${nuxeo.core.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-usermanager-api - ${nuxeo.core.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-commandline-executor - ${nuxeo.core.version} - provided - - - org.nuxeo.ecm.platform - nuxeo-platform-api - ${nuxeo.core.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-login - ${nuxeo.core.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-imaging-core - ${nuxeo.core.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-imaging-preview - ${nuxeo.core.version} - - - jboss-seam-pdf - org.jboss.seam - - - jboss-seam-rss - org.jboss.seam - - - jboss-seam-excel - org.jboss.seam - - - nuxeo-platform-ui-web - org.nuxeo.ecm.platform - - - xercesImpl - xerces - - - servlet-api - javax.servlet - - - oauth-httpclient3 - net.oauth.core - - - oauth-consumer - net.oauth.core - - - oauth-provider - net.oauth.core - - - oauth - net.oauth.core - - - - - org.nuxeo.ecm.platform - nuxeo-platform-audit-api - ${nuxeo.core.version} - - - org.nuxeo.runtime - nuxeo-runtime-osgi - ${nuxeo.core.version} - - - org.osgi - org.osgi.core - 4.1.0 - - - - org.testng - testng - - - - javax.security - jaas - 1.0.01 - - - wutka-dtdparser - dtdparser121 - 1.2.1 - - - oswego-concurrent - concurrent - 1.3.4-jboss-update1 - - - trove - trove - 2.1.1 - - - qdox - qdox - 1.6.1 - - - apache-xerces - xml-apis - 2.9.1 - - - org.apache - xmlsec - 1.4.2 - - - org.apache.bcel - bcel - 5.1 - - - org.apache.ant - ant - 1.7.0 - - - - - cspace-services - package - - ../../build.properties - - - - src/main/resources - true - - - src/main/webapp/META-INF - true - - - - - org.codehaus.mojo - properties-maven-plugin - - - initialize - - read-project-properties - - - - - - ../../build.properties - - - - - org.apache.maven.plugins - maven-resources-plugin - 2.5 - - - process-resources - - resources - - - - - - org.codehaus.cargo - cargo-maven2-plugin - 0.3 - - - - jboss4x - ${jboss.dir} - remote - - - runtime - - ${jboss.domain.cspace.port} - cspace - - - - remote - - - org.collectionspace.services - org.collectionspace.services.jaxrs.provider - war - http://${host}:${jboss.domain.cspace.port} - - - - - - - - - org.apache.maven.plugins - maven-war-plugin - - - - src/main/webapp - true - - - - - ${project.groupId} - - - - CollectionSpace Services - ${project.groupId} - ${cs.release} - - - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - - org.codehaus.mojo - - - properties-maven-plugin - - - [1.0-alpha-2,) - - - - read-project-properties - - - - - - - - - - - - - - - - + + + + + org.collectionspace.services.main + org.collectionspace.services + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.jaxrs.provider + services.jaxrs.provider + war + + + 0.5 + 3.0.0.RELEASE + 3.0.2.RELEASE + + + + + org.slf4j + slf4j-api + provided + + + org.slf4j + slf4j-log4j12 + provided + + + log4j + log4j + 1.2.14 + provided + + + + org.slf4j + slf4j-simple + 1.6.1 + test + + + org.slf4j + jcl-over-slf4j + 1.6.1 + test + + + + org.collectionspace.services + org.collectionspace.services.authority.service + ${project.version} + + + nuxeo-core-facade + org.nuxeo.ecm.core + + + servlet-api-2.5 + org.mortbay.jetty + + + + + org.collectionspace.services + org.collectionspace.services.authorization.service + ${project.version} + + + jboss-logging-log4j + org.jboss.logging + + + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + servlet-api-2.5 + org.mortbay.jetty + + + + + org.collectionspace.services + org.collectionspace.services.account.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authorization-mgt.service + ${project.version} + + + jboss-logging-log4j + org.jboss.logging + + + org.collectionspace.services + org.collectionspace.services.authorization-mgt.import + + + + + org.collectionspace.services + org.collectionspace.services.blob.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.collectionobject.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.id.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.intake.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.group.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.loanin.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.loanout.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.conditioncheck.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.objectexit.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.batch.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.imports.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.media.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.valuationcontrol.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.location.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.place.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.work.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.concept.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.taxonomy.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.movement.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.report.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.dimension.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.publicitem.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.servicegroup.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.contact.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.acquisition.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.vocabulary.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.organization.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.person.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.citation.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.relation.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.workflow.service + ${project.version} + + + + commons-io + commons-io + + + org.jboss.resteasy + jaxrs-api + + + org.jboss.resteasy + resteasy-jaxrs + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + junit + junit + 4.1 + test + + + + + + + + org.springframework.security + spring-security-core + ${spring.security.version} + provided + + + org.springframework.security + spring-security-config + ${spring.security.version} + provided + + + org.springframework.security + spring-security-web + ${spring.security.version} + provided + + + org.springframework + spring-context + ${spring.version} + provided + + + org.springframework + spring-context-support + ${spring.version} + provided + + + org.springframework + spring-web + ${spring.version} + provided + + + + + + servlet-api + javax.servlet + provided + + + + + jboss + jboss-remoting + 2.2.2.SP8 + provided + + + + + org.nuxeo.common + nuxeo-common + ${nuxeo.core.version} + + + org.nuxeo.runtime + nuxeo-runtime + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core + ${nuxeo.core.version} + + + xerces + xercesImpl + + + + + org.nuxeo.ecm.core + nuxeo-core-api + + + org.nuxeo.ecm.core + nuxeo-core-convert + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-storage-sql-extensions + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-storage-sql-ra + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-client + ${nuxeo.core.version} + + + org.jboss.jbossas + jboss-as-jbossas-remoting + + + + + org.nuxeo.ecm.core + nuxeo-core-query + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-schema + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-io + ${nuxeo.core.version} + + + + org.nuxeo.runtime + nuxeo-runtime-jtajca + ${nuxeo.core.version} + + + + geronimo-transaction + org.apache.geronimo.components + + + geronimo-connector + org.apache.geronimo.components + + + + + org.nuxeo.runtime + nuxeo-runtime-datasource + ${nuxeo.core.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-usermanager-api + ${nuxeo.core.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-commandline-executor + ${nuxeo.core.version} + provided + + + org.nuxeo.ecm.platform + nuxeo-platform-api + ${nuxeo.core.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-login + ${nuxeo.core.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-imaging-core + ${nuxeo.core.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-imaging-preview + ${nuxeo.core.version} + + + jboss-seam-pdf + org.jboss.seam + + + jboss-seam-rss + org.jboss.seam + + + jboss-seam-excel + org.jboss.seam + + + nuxeo-platform-ui-web + org.nuxeo.ecm.platform + + + xercesImpl + xerces + + + servlet-api + javax.servlet + + + oauth-httpclient3 + net.oauth.core + + + oauth-consumer + net.oauth.core + + + oauth-provider + net.oauth.core + + + oauth + net.oauth.core + + + + + org.nuxeo.ecm.platform + nuxeo-platform-audit-api + ${nuxeo.core.version} + + + org.nuxeo.runtime + nuxeo-runtime-osgi + ${nuxeo.core.version} + + + org.osgi + org.osgi.core + 4.1.0 + + + + org.testng + testng + + + + javax.security + jaas + 1.0.01 + + + wutka-dtdparser + dtdparser121 + 1.2.1 + + + oswego-concurrent + concurrent + 1.3.4-jboss-update1 + + + trove + trove + 2.1.1 + + + qdox + qdox + 1.6.1 + + + apache-xerces + xml-apis + 2.9.1 + + + org.apache + xmlsec + 1.4.2 + + + org.apache.bcel + bcel + 5.1 + + + org.apache.ant + ant + 1.7.0 + + + + + cspace-services + package + + ../../build.properties + + + + src/main/resources + true + + + src/main/webapp/META-INF + true + + + + + org.codehaus.mojo + properties-maven-plugin + + + initialize + + read-project-properties + + + + + + ../../build.properties + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.5 + + + process-resources + + resources + + + + + + org.codehaus.cargo + cargo-maven2-plugin + 0.3 + + + + jboss4x + ${jboss.dir} + remote + + + runtime + + ${jboss.domain.cspace.port} + cspace + + + + remote + + + org.collectionspace.services + org.collectionspace.services.jaxrs.provider + war + http://${host}:${jboss.domain.cspace.port} + + + + + + + + + org.apache.maven.plugins + maven-war-plugin + + + + src/main/webapp + true + + + + + ${project.groupId} + + + + CollectionSpace Services + ${project.groupId} + ${cs.release} + + + + + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.codehaus.mojo + + + properties-maven-plugin + + + [1.0-alpha-2,) + + + + read-project-properties + + + + + + + + + + + + + + + + diff --git a/services/JaxRsServiceProvider/src/main/java/org/collectionspace/services/jaxrs/CSpaceResteasyBootstrap.java b/services/JaxRsServiceProvider/src/main/java/org/collectionspace/services/jaxrs/CSpaceResteasyBootstrap.java index 1a84953fb..48f79b626 100644 --- a/services/JaxRsServiceProvider/src/main/java/org/collectionspace/services/jaxrs/CSpaceResteasyBootstrap.java +++ b/services/JaxRsServiceProvider/src/main/java/org/collectionspace/services/jaxrs/CSpaceResteasyBootstrap.java @@ -1,36 +1,36 @@ -package org.collectionspace.services.jaxrs; - -import javax.servlet.ServletContextEvent; - -import org.jboss.resteasy.core.Dispatcher; -import org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap; -import org.collectionspace.services.common.ResourceMap; - -public class CSpaceResteasyBootstrap extends ResteasyBootstrap { - - public void contextInitialized(ServletContextEvent event) { - try { - // - // This call to super instantiates and initializes our JAX-RS application class. - // The application class is org.collectionspace.services.jaxrs.CollectionSpaceJaxRsApplication. - // - System.out.println("[INFO] Starting up the CollectionSpace Services' JAX-RS application."); - super.contextInitialized(event); - CollectionSpaceJaxRsApplication app = - (CollectionSpaceJaxRsApplication)deployment.getApplication(); - Dispatcher disp = deployment.getDispatcher(); - disp.getDefaultContextObjects().put(ResourceMap.class, app.getResourceMap()); - System.out.println("[INFO] CollectionSpace Services' JAX-RS application started."); - } catch (Throwable e) { - e.printStackTrace(); - } - } - - @Override - public void contextDestroyed(ServletContextEvent event) { - System.out.println("[INFO] Shutting down the CollectionSpace Services' JAX-RS application."); - //Do something if needed. - System.out.println("[INFO] CollectionSpace Services' JAX-RS application stopped."); - } - -} +package org.collectionspace.services.jaxrs; + +import javax.servlet.ServletContextEvent; + +import org.jboss.resteasy.core.Dispatcher; +import org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap; +import org.collectionspace.services.common.ResourceMap; + +public class CSpaceResteasyBootstrap extends ResteasyBootstrap { + + public void contextInitialized(ServletContextEvent event) { + try { + // + // This call to super instantiates and initializes our JAX-RS application class. + // The application class is org.collectionspace.services.jaxrs.CollectionSpaceJaxRsApplication. + // + System.out.println("[INFO] Starting up the CollectionSpace Services' JAX-RS application."); + super.contextInitialized(event); + CollectionSpaceJaxRsApplication app = + (CollectionSpaceJaxRsApplication)deployment.getApplication(); + Dispatcher disp = deployment.getDispatcher(); + disp.getDefaultContextObjects().put(ResourceMap.class, app.getResourceMap()); + System.out.println("[INFO] CollectionSpace Services' JAX-RS application started."); + } catch (Throwable e) { + e.printStackTrace(); + } + } + + @Override + public void contextDestroyed(ServletContextEvent event) { + System.out.println("[INFO] Shutting down the CollectionSpace Services' JAX-RS application."); + //Do something if needed. + System.out.println("[INFO] CollectionSpace Services' JAX-RS application stopped."); + } + +} diff --git a/services/JaxRsServiceProvider/src/main/resources/META-INF/persistence.xml b/services/JaxRsServiceProvider/src/main/resources/META-INF/persistence.xml index 430644f5b..89a20b8fd 100644 --- a/services/JaxRsServiceProvider/src/main/resources/META-INF/persistence.xml +++ b/services/JaxRsServiceProvider/src/main/resources/META-INF/persistence.xml @@ -1,32 +1,32 @@ - - - - org.hibernate.ejb.HibernatePersistence - - - org.collectionspace.services.account.AccountsCommon - org.collectionspace.services.account.Tenant - org.collectionspace.services.account.AccountTenant - org.collectionspace.services.account.Status - org.collectionspace.services.authentication.User - org.collectionspace.services.authorization.perms.Permission - org.collectionspace.services.authorization.perms.PermissionAction - org.collectionspace.services.authorization.PermissionRoleRel - org.collectionspace.services.authorization.Role - org.collectionspace.services.authorization.AccountRoleRel - - - - - - - - - - - - - - + + + + org.hibernate.ejb.HibernatePersistence + + + org.collectionspace.services.account.AccountsCommon + org.collectionspace.services.account.Tenant + org.collectionspace.services.account.AccountTenant + org.collectionspace.services.account.Status + org.collectionspace.services.authentication.User + org.collectionspace.services.authorization.perms.Permission + org.collectionspace.services.authorization.perms.PermissionAction + org.collectionspace.services.authorization.PermissionRoleRel + org.collectionspace.services.authorization.Role + org.collectionspace.services.authorization.AccountRoleRel + + + + + + + + + + + + + + diff --git a/services/JaxRsServiceProvider/src/main/resources/log4j.properties b/services/JaxRsServiceProvider/src/main/resources/log4j.properties index ba0b6ce4f..aa385c38a 100644 --- a/services/JaxRsServiceProvider/src/main/resources/log4j.properties +++ b/services/JaxRsServiceProvider/src/main/resources/log4j.properties @@ -1,83 +1,83 @@ -# -# The default logging level -# -log4j.rootLogger=debug, error, cspace_appender - -# -# The stdout appender -# -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 - -# -# An appender that shows just ERROR log messsages -# -log4j.appender.error=org.apache.log4j.ConsoleAppender -log4j.appender.error.layout=org.apache.log4j.PatternLayout -# Pattern to output the caller's file name and line number. -log4j.appender.error.layout.ConversionPattern=%d %-5p [%t] [%c:%L] %m%n -log4j.appender.error.Threshold=WARN - -# -# The "cspace_appender" appender - the standout CollectionSpace services log file appender -# -log4j.appender.cspace_appender=org.apache.log4j.RollingFileAppender -log4j.appender.cspace_appender.File=${catalina.home}/logs/cspace-services.log -log4j.appender.cspace_appender.MaxFileSize=5000KB -# Keep ten backup files -log4j.appender.cspace_appender.MaxBackupIndex=10 -log4j.appender.cspace_appender.layout=org.apache.log4j.PatternLayout -log4j.appender.cspace_appender.layout.ConversionPattern=%d %-5p [%t] [%c:%L] %m%n - -# -# CollectionSpace Services Performance appender -# -log4j.appender.cspace_perf_appender=org.apache.log4j.RollingFileAppender -log4j.appender.cspace_perf_appender.File=${catalina.home}/logs/cspace-services-perf.log -log4j.appender.cspace_perf_appender.MaxFileSize=5000KB -# Keep ten backup files -log4j.appender.cspace_perf_appender.MaxBackupIndex=10 -log4j.appender.cspace_perf_appender.layout=org.apache.log4j.PatternLayout -log4j.appender.cspace_perf_appender.layout.ConversionPattern=%d %-5p [%t] [%c:%L] %m%n - -# -# This logger uses the "cspace_perf_appender" appender to log performance profiling information. -# -log4j.logger.perf.collectionspace=DEBUG, cspace_perf_appender, stdout -# send the logs only to our appender -no inheritence. -log4j.additivity.perf.collectionspace=false - -# -# CollectionSpace loggers and default levels - all loggers using the rootLogger if not otherwise specified -# -log4j.logger.org.collectionspace=INFO -log4j.logger.org.collectionspace.services.nuxeo.client.java=ERROR -log4j.logger.org.collectionspace.services.common.storage.JDBCTools=ERROR -log4j.logger.org.collectionspace.services.common.profile.CSpaceFilter=ERROR - -#log4j.logger.org.collectionspace.services.common.vocabulary.nuxeo=TRACE - -# -# Nuxeo loggers, levels, and associated appenders -# -log4j.logger.org.nuxeo=WARN -#log4j.logger.org.nuxeo.ecm.core.storage.sql=TRACE - -# -# Misc loggers, levels -# -log4j.logger.org.apache=ERROR -log4j.logger.httpclient=ERROR -log4j.logger.org.jboss.resteasy=ERROR -log4j.logger.org.apache.catalina.core=ERROR -log4j.logger.org.springframework=ERROR -log4j.logger.org.springframework.security=ERROR -log4j.logger.org.jboss.security=ERROR -log4j.logger.org.apache.catalina.realm=ERROR -log4j.logger.org.hibernate=ERROR -log4j.logger.ch.elca.el4j.services.xmlmerge=ERROR -log4j.logger.net.sf.jmimemagic.MagicParser=ERROR - - +# +# The default logging level +# +log4j.rootLogger=debug, error, cspace_appender + +# +# The stdout appender +# +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 + +# +# An appender that shows just ERROR log messsages +# +log4j.appender.error=org.apache.log4j.ConsoleAppender +log4j.appender.error.layout=org.apache.log4j.PatternLayout +# Pattern to output the caller's file name and line number. +log4j.appender.error.layout.ConversionPattern=%d %-5p [%t] [%c:%L] %m%n +log4j.appender.error.Threshold=WARN + +# +# The "cspace_appender" appender - the standout CollectionSpace services log file appender +# +log4j.appender.cspace_appender=org.apache.log4j.RollingFileAppender +log4j.appender.cspace_appender.File=${catalina.home}/logs/cspace-services.log +log4j.appender.cspace_appender.MaxFileSize=5000KB +# Keep ten backup files +log4j.appender.cspace_appender.MaxBackupIndex=10 +log4j.appender.cspace_appender.layout=org.apache.log4j.PatternLayout +log4j.appender.cspace_appender.layout.ConversionPattern=%d %-5p [%t] [%c:%L] %m%n + +# +# CollectionSpace Services Performance appender +# +log4j.appender.cspace_perf_appender=org.apache.log4j.RollingFileAppender +log4j.appender.cspace_perf_appender.File=${catalina.home}/logs/cspace-services-perf.log +log4j.appender.cspace_perf_appender.MaxFileSize=5000KB +# Keep ten backup files +log4j.appender.cspace_perf_appender.MaxBackupIndex=10 +log4j.appender.cspace_perf_appender.layout=org.apache.log4j.PatternLayout +log4j.appender.cspace_perf_appender.layout.ConversionPattern=%d %-5p [%t] [%c:%L] %m%n + +# +# This logger uses the "cspace_perf_appender" appender to log performance profiling information. +# +log4j.logger.perf.collectionspace=DEBUG, cspace_perf_appender, stdout +# send the logs only to our appender -no inheritence. +log4j.additivity.perf.collectionspace=false + +# +# CollectionSpace loggers and default levels - all loggers using the rootLogger if not otherwise specified +# +log4j.logger.org.collectionspace=INFO +log4j.logger.org.collectionspace.services.nuxeo.client.java=ERROR +log4j.logger.org.collectionspace.services.common.storage.JDBCTools=ERROR +log4j.logger.org.collectionspace.services.common.profile.CSpaceFilter=ERROR + +#log4j.logger.org.collectionspace.services.common.vocabulary.nuxeo=TRACE + +# +# Nuxeo loggers, levels, and associated appenders +# +log4j.logger.org.nuxeo=WARN +#log4j.logger.org.nuxeo.ecm.core.storage.sql=TRACE + +# +# Misc loggers, levels +# +log4j.logger.org.apache=ERROR +log4j.logger.httpclient=ERROR +log4j.logger.org.jboss.resteasy=ERROR +log4j.logger.org.apache.catalina.core=ERROR +log4j.logger.org.springframework=ERROR +log4j.logger.org.springframework.security=ERROR +log4j.logger.org.jboss.security=ERROR +log4j.logger.org.apache.catalina.realm=ERROR +log4j.logger.org.hibernate=ERROR +log4j.logger.ch.elca.el4j.services.xmlmerge=ERROR +log4j.logger.net.sf.jmimemagic.MagicParser=ERROR + + diff --git a/services/JaxRsServiceProvider/src/main/webapp/WEB-INF/jboss-web.xml b/services/JaxRsServiceProvider/src/main/webapp/WEB-INF/jboss-web.xml index f9d978f1b..132b8f629 100644 --- a/services/JaxRsServiceProvider/src/main/webapp/WEB-INF/jboss-web.xml +++ b/services/JaxRsServiceProvider/src/main/webapp/WEB-INF/jboss-web.xml @@ -1,15 +1,15 @@ - - - - - - java:/jaas/cspace - /cspace-services - - + + + + + + java:/jaas/cspace + /cspace-services + + diff --git a/services/JaxRsServiceProvider/src/main/webapp/WEB-INF/login.conf b/services/JaxRsServiceProvider/src/main/webapp/WEB-INF/login.conf index 09da0de64..0892750f9 100644 --- a/services/JaxRsServiceProvider/src/main/webapp/WEB-INF/login.conf +++ b/services/JaxRsServiceProvider/src/main/webapp/WEB-INF/login.conf @@ -1,32 +1,32 @@ -CSpaceJBossDBLoginModule { - org.collectionspace.authentication.jaas.CSpaceJBossDBLoginModule required - dsJndiName="CspaceDS" - hashAlgorithm="SHA-256" - ignorePasswordCase="false" - principalClass="org.collectionspace.authentication.CSpacePrincipal" - principalsQuery="select passwd from users where username=?" - rolesQuery="select r.rolename, 'Role' from roles as r, accounts_roles as ar where ar.user_id=? and ar.role_id=r.csid" - tenantsQueryWithDisabled="select t.id, t.name, 'Tenants' from accounts_common as a, accounts_tenants as at, tenants as t where a.userid=? and a.csid = at.TENANTS_ACCOUNTSCOMMON_CSID and at.tenant_id = t.id" - tenantsQueryNoDisabled="select t.id, t.name, 'Tenants' from accounts_common as a, accounts_tenants as at, tenants as t where a.userid=? and a.csid = at.TENANTS_ACCOUNTSCOMMON_CSID and at.tenant_id = t.id and NOT t.disabled" - maxRetrySeconds="5000" - delayBetweenAttemptsMillis="200" - debug=true; - }; - - /** - * The JAAS login configuration. - */ - cspace { - org.collectionspace.authentication.jaas.CSpaceJBossDBLoginModule required - dsJndiName="CspaceDS" - hashAlgorithm="SHA-256" - ignorePasswordCase="false" - principalClass="org.collectionspace.authentication.CSpacePrincipal" - principalsQuery="select passwd from users where username=?" - rolesQuery="select r.rolename, 'Role' from roles as r, accounts_roles as ar where ar.user_id=? and ar.role_id=r.csid" - tenantsQueryWithDisabled="select t.id, t.name, 'Tenants' from accounts_common as a, accounts_tenants as at, tenants as t where a.userid=? and a.csid = at.TENANTS_ACCOUNTSCOMMON_CSID and at.tenant_id = t.id" - tenantsQueryNoDisabled="select t.id, t.name, 'Tenants' from accounts_common as a, accounts_tenants as at, tenants as t where a.userid=? and a.csid = at.TENANTS_ACCOUNTSCOMMON_CSID and at.tenant_id = t.id and NOT t.disabled" - maxRetrySeconds="5000" - delayBetweenAttemptsMillis="200" - debug=true; - }; +CSpaceJBossDBLoginModule { + org.collectionspace.authentication.jaas.CSpaceJBossDBLoginModule required + dsJndiName="CspaceDS" + hashAlgorithm="SHA-256" + ignorePasswordCase="false" + principalClass="org.collectionspace.authentication.CSpacePrincipal" + principalsQuery="select passwd from users where username=?" + rolesQuery="select r.rolename, 'Role' from roles as r, accounts_roles as ar where ar.user_id=? and ar.role_id=r.csid" + tenantsQueryWithDisabled="select t.id, t.name, 'Tenants' from accounts_common as a, accounts_tenants as at, tenants as t where a.userid=? and a.csid = at.TENANTS_ACCOUNTSCOMMON_CSID and at.tenant_id = t.id" + tenantsQueryNoDisabled="select t.id, t.name, 'Tenants' from accounts_common as a, accounts_tenants as at, tenants as t where a.userid=? and a.csid = at.TENANTS_ACCOUNTSCOMMON_CSID and at.tenant_id = t.id and NOT t.disabled" + maxRetrySeconds="5000" + delayBetweenAttemptsMillis="200" + debug=true; + }; + + /** + * The JAAS login configuration. + */ + cspace { + org.collectionspace.authentication.jaas.CSpaceJBossDBLoginModule required + dsJndiName="CspaceDS" + hashAlgorithm="SHA-256" + ignorePasswordCase="false" + principalClass="org.collectionspace.authentication.CSpacePrincipal" + principalsQuery="select passwd from users where username=?" + rolesQuery="select r.rolename, 'Role' from roles as r, accounts_roles as ar where ar.user_id=? and ar.role_id=r.csid" + tenantsQueryWithDisabled="select t.id, t.name, 'Tenants' from accounts_common as a, accounts_tenants as at, tenants as t where a.userid=? and a.csid = at.TENANTS_ACCOUNTSCOMMON_CSID and at.tenant_id = t.id" + tenantsQueryNoDisabled="select t.id, t.name, 'Tenants' from accounts_common as a, accounts_tenants as at, tenants as t where a.userid=? and a.csid = at.TENANTS_ACCOUNTSCOMMON_CSID and at.tenant_id = t.id and NOT t.disabled" + maxRetrySeconds="5000" + delayBetweenAttemptsMillis="200" + debug=true; + }; diff --git a/services/JaxRsServiceProvider/src/main/webapp/WEB-INF/web.xml b/services/JaxRsServiceProvider/src/main/webapp/WEB-INF/web.xml index 28714fd3b..9de96d989 100644 --- a/services/JaxRsServiceProvider/src/main/webapp/WEB-INF/web.xml +++ b/services/JaxRsServiceProvider/src/main/webapp/WEB-INF/web.xml @@ -1,154 +1,154 @@ - - - - CollectionSpace Services - - - - - Sets the logging context for the Tiger web-app - cspace-logging-context - java.lang.String - CSpaceLoggingContext - - - - javax.ws.rs.Application - org.collectionspace.services.jaxrs.CollectionSpaceJaxRsApplication - - - - resteasy.servlet.mapping.prefix - / - - - - - contextConfigLocation - - /WEB-INF/applicationContext-security.xml - - - - - - springSecurityFilterChain - org.springframework.web.filter.DelegatingFilterProxy - - - - springSecurityFilterChain - /* - - - - - - - - CSpaceFilter - org.collectionspace.services.common.profile.CSpaceFilter - - - - CSpaceFilter - /* - - - - - - - - org.springframework.web.context.ContextLoaderListener - - - - - org.springframework.security.web.session.HttpSessionEventPublisher - - - - - - - - org.collectionspace.services.common.CollectionSpaceServiceContextListener - - - - - - - org.collectionspace.services.jaxrs.CSpaceResteasyBootstrap - - - - - Resteasy - - org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher - - - - Resteasy - /* - - - + + + + CollectionSpace Services + + + + + Sets the logging context for the Tiger web-app + cspace-logging-context + java.lang.String + CSpaceLoggingContext + + + + javax.ws.rs.Application + org.collectionspace.services.jaxrs.CollectionSpaceJaxRsApplication + + + + resteasy.servlet.mapping.prefix + / + + + + + contextConfigLocation + + /WEB-INF/applicationContext-security.xml + + + + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + + springSecurityFilterChain + /* + + + + + + + + CSpaceFilter + org.collectionspace.services.common.profile.CSpaceFilter + + + + CSpaceFilter + /* + + + + + + + + org.springframework.web.context.ContextLoaderListener + + + + + org.springframework.security.web.session.HttpSessionEventPublisher + + + + + + + + org.collectionspace.services.common.CollectionSpaceServiceContextListener + + + + + + + org.collectionspace.services.jaxrs.CSpaceResteasyBootstrap + + + + + Resteasy + + org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher + + + + Resteasy + /* + + + diff --git a/services/PerformanceTests/pom.xml b/services/PerformanceTests/pom.xml index 818edfe14..d3bbc7ab9 100644 --- a/services/PerformanceTests/pom.xml +++ b/services/PerformanceTests/pom.xml @@ -1,131 +1,131 @@ - - - - org.collectionspace.services.main - org.collectionspace.services - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.PerformanceTests - jar - services.PerformanceTests - - - - org.slf4j - slf4j-api - test - - - org.slf4j - slf4j-log4j12 - test - - - - org.collectionspace.services - org.collectionspace.services.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.collectionobject.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.collectionobject.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.intake.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.intake.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.relation.client - ${project.version} - - - - org.testng - testng - - - org.jboss.resteasy - resteasy-jaxrs - - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - commons-httpclient - commons-httpclient - 3.1 - - - - - collectionspace-services-PerformanceTests - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - - - - - - - - perftests - - - - org.apache.maven.plugins - maven-surefire-plugin - - false - - - - - - - - - + + + + org.collectionspace.services.main + org.collectionspace.services + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.PerformanceTests + jar + services.PerformanceTests + + + + org.slf4j + slf4j-api + test + + + org.slf4j + slf4j-log4j12 + test + + + + org.collectionspace.services + org.collectionspace.services.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.collectionobject.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.collectionobject.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.intake.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.intake.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.relation.client + ${project.version} + + + + org.testng + testng + + + org.jboss.resteasy + resteasy-jaxrs + + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + commons-httpclient + commons-httpclient + 3.1 + + + + + collectionspace-services-PerformanceTests + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + + + + + perftests + + + + org.apache.maven.plugins + maven-surefire-plugin + + false + + + + + + + + + diff --git a/services/PerformanceTests/src/test/java/org/collectionspace/services/PerformanceTests/test/CollectionSpacePerformanceTest.java b/services/PerformanceTests/src/test/java/org/collectionspace/services/PerformanceTests/test/CollectionSpacePerformanceTest.java index ae9cf2115..cdefbad9e 100644 --- a/services/PerformanceTests/src/test/java/org/collectionspace/services/PerformanceTests/test/CollectionSpacePerformanceTest.java +++ b/services/PerformanceTests/src/test/java/org/collectionspace/services/PerformanceTests/test/CollectionSpacePerformanceTest.java @@ -1,240 +1,240 @@ -/** - * CollectionSpacePerformanceTest.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.PerformanceTests.test; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; - -import org.collectionspace.services.collectionobject.CollectionobjectsCommon; -import org.collectionspace.services.collectionobject.TitleGroup; -import org.collectionspace.services.collectionobject.TitleGroupList; -import org.collectionspace.services.intake.IntakesCommon; -import org.collectionspace.services.relation.RelationsCommon; -import org.collectionspace.services.relation.RelationshipType; -import org.jboss.resteasy.client.ClientResponse; -import org.jboss.resteasy.plugins.providers.multipart.InputPart; -import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; - -/** - * The Class CollectionSpacePerformanceTests. - */ -public abstract class CollectionSpacePerformanceTest { - - protected final static String OBJECT_NUMBER = "objectNumber_"; - protected final static String OBJECT_TITLE = "objectTitle_"; - - /* - * Package scoped methods. - */ - - /** - * Fill collection object. - * - * @param co the co - * @param identifier the identifier - */ - void fillCollectionObject(CollectionobjectsCommon co, String identifier) { - fillCollectionObject(co, OBJECT_NUMBER + identifier, OBJECT_TITLE + identifier); - } - - /** - * Fill collection object. - * - * @param co the co - * @param objectNumber the object number - * @param title the object title - */ - void fillCollectionObject(CollectionobjectsCommon co, String objectNumber, - String title) { - co.setObjectNumber(objectNumber); - TitleGroupList titleGroupList = new TitleGroupList(); - List titleGroups = titleGroupList.getTitleGroup(); - TitleGroup titleGroup = new TitleGroup(); - titleGroup.setTitle(title); - titleGroups.add(titleGroup); - co.setTitleGroupList(titleGroupList); - } - - /** - * Fill intake. - * - * @param theIntake the the intake - * @param identifier the identifier - */ - void fillIntake(IntakesCommon theIntake, String identifier) { - fillIntake(theIntake, "entryNumber-" + identifier, "entryDate-" - + identifier); - } - - /** - * Fill intake. - * - * @param theIntake the the intake - * @param entryNumber the entry number - * @param entryDate the entry date - */ - void fillIntake(IntakesCommon theIntake, String entryNumber, String entryDate) { - theIntake.setEntryNumber(entryNumber); - theIntake.setEntryDate(entryDate); - } - - /** - * Fill relation. - * - * @param relation the relation - * @param subjectCsid the document id1 - * @param subjectDocumentType the document type1 - * @param objectCsid the document id2 - * @param objectDocumentType the document type2 - * @param rt the rt - */ - void fillRelation(RelationsCommon relation, String subjectCsid, String subjectDocumentType, - String objectCsid, String objectDocumentType, RelationshipType rt) - { - relation.setSubjectCsid(subjectCsid); - relation.setSubjectDocumentType(subjectDocumentType); - relation.setSubjectCsid(objectCsid); - relation.setObjectDocumentType(objectDocumentType); - - relation.setRelationshipType(rt.toString()); - } - - /** - * Creates the identifier. - * - * @return the string - */ - String createIdentifier() { - long identifier = System.currentTimeMillis(); - return Long.toString(identifier); - } - - /** - * Extract id. - * - * @param res the res - * - * @return the string - */ - String extractId(ClientResponse res) { - String result = null; - - MultivaluedMap mvm = res.getMetadata(); - String uri = (String) ((ArrayList) mvm.get("Location")).get(0); - verbose("extractId:uri=" + uri); - String[] segments = uri.split("/"); - result = segments[segments.length - 1]; - verbose("id=" + result); - - return result; - } - - /** - * Extract part. - * - * @param input - * the input - * @param label - * the label - * @param clazz - * the clazz - * - * @return the object - * - * @throws Exception - * the exception - */ - static Object extractPart(MultipartInput input, String label, Class clazz) { - Object obj = null; - - try { - for (InputPart part : input.getParts()) { - String partLabel = part.getHeaders().getFirst("label"); - if (label.equalsIgnoreCase(partLabel)) { - String partStr = part.getBodyAsString(); - obj = part.getBody(clazz, null); - break; - } - } - } catch (Exception e) { - e.printStackTrace(); - } - - return obj; - } - - /** - * Verbose. - * - * @param msg the msg - */ - void verbose(String msg) { -// System.out.println(msg); - } - - /** - * Verbose. - * - * @param msg the msg - * @param o the o - * @param clazz the clazz - */ - void verbose(String msg, Object o, Class clazz) { - try { - verbose(msg); - JAXBContext jc = JAXBContext.newInstance(clazz); - Marshaller m = jc.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - m.marshal(o, System.out); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Verbose map. - * - * @param map the map - */ - void verboseMap(MultivaluedMap map) { - for (Object entry : map.entrySet()) { - MultivaluedMap.Entry mentry = (MultivaluedMap.Entry) entry; - verbose(" name=" + mentry.getKey() + " value=" + mentry.getValue()); - } - } - - boolean isEnabled() { - return Boolean.getBoolean("cspace.perf"); - } - -} +/** + * CollectionSpacePerformanceTest.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.PerformanceTests.test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; + +import org.collectionspace.services.collectionobject.CollectionobjectsCommon; +import org.collectionspace.services.collectionobject.TitleGroup; +import org.collectionspace.services.collectionobject.TitleGroupList; +import org.collectionspace.services.intake.IntakesCommon; +import org.collectionspace.services.relation.RelationsCommon; +import org.collectionspace.services.relation.RelationshipType; +import org.jboss.resteasy.client.ClientResponse; +import org.jboss.resteasy.plugins.providers.multipart.InputPart; +import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; + +/** + * The Class CollectionSpacePerformanceTests. + */ +public abstract class CollectionSpacePerformanceTest { + + protected final static String OBJECT_NUMBER = "objectNumber_"; + protected final static String OBJECT_TITLE = "objectTitle_"; + + /* + * Package scoped methods. + */ + + /** + * Fill collection object. + * + * @param co the co + * @param identifier the identifier + */ + void fillCollectionObject(CollectionobjectsCommon co, String identifier) { + fillCollectionObject(co, OBJECT_NUMBER + identifier, OBJECT_TITLE + identifier); + } + + /** + * Fill collection object. + * + * @param co the co + * @param objectNumber the object number + * @param title the object title + */ + void fillCollectionObject(CollectionobjectsCommon co, String objectNumber, + String title) { + co.setObjectNumber(objectNumber); + TitleGroupList titleGroupList = new TitleGroupList(); + List titleGroups = titleGroupList.getTitleGroup(); + TitleGroup titleGroup = new TitleGroup(); + titleGroup.setTitle(title); + titleGroups.add(titleGroup); + co.setTitleGroupList(titleGroupList); + } + + /** + * Fill intake. + * + * @param theIntake the the intake + * @param identifier the identifier + */ + void fillIntake(IntakesCommon theIntake, String identifier) { + fillIntake(theIntake, "entryNumber-" + identifier, "entryDate-" + + identifier); + } + + /** + * Fill intake. + * + * @param theIntake the the intake + * @param entryNumber the entry number + * @param entryDate the entry date + */ + void fillIntake(IntakesCommon theIntake, String entryNumber, String entryDate) { + theIntake.setEntryNumber(entryNumber); + theIntake.setEntryDate(entryDate); + } + + /** + * Fill relation. + * + * @param relation the relation + * @param subjectCsid the document id1 + * @param subjectDocumentType the document type1 + * @param objectCsid the document id2 + * @param objectDocumentType the document type2 + * @param rt the rt + */ + void fillRelation(RelationsCommon relation, String subjectCsid, String subjectDocumentType, + String objectCsid, String objectDocumentType, RelationshipType rt) + { + relation.setSubjectCsid(subjectCsid); + relation.setSubjectDocumentType(subjectDocumentType); + relation.setSubjectCsid(objectCsid); + relation.setObjectDocumentType(objectDocumentType); + + relation.setRelationshipType(rt.toString()); + } + + /** + * Creates the identifier. + * + * @return the string + */ + String createIdentifier() { + long identifier = System.currentTimeMillis(); + return Long.toString(identifier); + } + + /** + * Extract id. + * + * @param res the res + * + * @return the string + */ + String extractId(ClientResponse res) { + String result = null; + + MultivaluedMap mvm = res.getMetadata(); + String uri = (String) ((ArrayList) mvm.get("Location")).get(0); + verbose("extractId:uri=" + uri); + String[] segments = uri.split("/"); + result = segments[segments.length - 1]; + verbose("id=" + result); + + return result; + } + + /** + * Extract part. + * + * @param input + * the input + * @param label + * the label + * @param clazz + * the clazz + * + * @return the object + * + * @throws Exception + * the exception + */ + static Object extractPart(MultipartInput input, String label, Class clazz) { + Object obj = null; + + try { + for (InputPart part : input.getParts()) { + String partLabel = part.getHeaders().getFirst("label"); + if (label.equalsIgnoreCase(partLabel)) { + String partStr = part.getBodyAsString(); + obj = part.getBody(clazz, null); + break; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + return obj; + } + + /** + * Verbose. + * + * @param msg the msg + */ + void verbose(String msg) { +// System.out.println(msg); + } + + /** + * Verbose. + * + * @param msg the msg + * @param o the o + * @param clazz the clazz + */ + void verbose(String msg, Object o, Class clazz) { + try { + verbose(msg); + JAXBContext jc = JAXBContext.newInstance(clazz); + Marshaller m = jc.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + m.marshal(o, System.out); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Verbose map. + * + * @param map the map + */ + void verboseMap(MultivaluedMap map) { + for (Object entry : map.entrySet()) { + MultivaluedMap.Entry mentry = (MultivaluedMap.Entry) entry; + verbose(" name=" + mentry.getKey() + " value=" + mentry.getValue()); + } + } + + boolean isEnabled() { + return Boolean.getBoolean("cspace.perf"); + } + +} diff --git a/services/PerformanceTests/src/test/resources/log4j.properties b/services/PerformanceTests/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/PerformanceTests/src/test/resources/log4j.properties +++ b/services/PerformanceTests/src/test/resources/log4j.properties @@ -1,23 +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 +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/account/.classpath b/services/account/.classpath index d7501e2c4..b8a2888f8 100644 --- a/services/account/.classpath +++ b/services/account/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/account/.project b/services/account/.project index 551ac7ac0..76aa9ca04 100644 --- a/services/account/.project +++ b/services/account/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.account - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.account + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/account/build.xml b/services/account/build.xml index 6e7e82320..049c17372 100644 --- a/services/account/build.xml +++ b/services/account/build.xml @@ -1,135 +1,135 @@ - - - - collectionobject service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + collectionobject service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/account/client/build.xml b/services/account/client/build.xml index 914ced664..86a05a179 100644 --- a/services/account/client/build.xml +++ b/services/account/client/build.xml @@ -1,138 +1,138 @@ - - - collectionspace account service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + collectionspace account service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/account/client/pom.xml b/services/account/client/pom.xml index 20c3e56d7..7787b8615 100644 --- a/services/account/client/pom.xml +++ b/services/account/client/pom.xml @@ -1,124 +1,124 @@ - - - - org.collectionspace.services - org.collectionspace.services.account - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.account.client - services.account.client - - - - - org.slf4j - slf4j-api - provided - - - org.slf4j - slf4j-log4j12 - provided - - - org.collectionspace.services - org.collectionspace.services.account.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.hyperjaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authorization.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authorization-mgt.client - ${project.version} - - - - - - - mysql - mysql-connector-java - test - - - postgresql - postgresql - test - - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - commons-httpclient - commons-httpclient - 3.1 - - - - - cspace-services-account-client - - - maven-antrun-plugin - - - subs-hibernate-config - generate-test-resources - - run - - - - - - - - - - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.account + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.account.client + services.account.client + + + + + org.slf4j + slf4j-api + provided + + + org.slf4j + slf4j-log4j12 + provided + + + org.collectionspace.services + org.collectionspace.services.account.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.hyperjaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authorization.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authorization-mgt.client + ${project.version} + + + + + + + mysql + mysql-connector-java + test + + + postgresql + postgresql + test + + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + commons-httpclient + commons-httpclient + 3.1 + + + + + cspace-services-account-client + + + maven-antrun-plugin + + + subs-hibernate-config + generate-test-resources + + run + + + + + + + + + + + + + + + diff --git a/services/account/client/src/test/resources/log4j.properties b/services/account/client/src/test/resources/log4j.properties index f9c47870a..8a63f9f10 100644 --- a/services/account/client/src/test/resources/log4j.properties +++ b/services/account/client/src/test/resources/log4j.properties @@ -1,25 +1,25 @@ -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 -log4j.logger.org.hibernate=INFO -log4j.logger.org.hibernate.cfg=WARN +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 +log4j.logger.org.hibernate=INFO +log4j.logger.org.hibernate.cfg=WARN diff --git a/services/account/jaxb/src/test/resources/log4j.properties b/services/account/jaxb/src/test/resources/log4j.properties index 3aa34b3fc..53720a742 100644 --- a/services/account/jaxb/src/test/resources/log4j.properties +++ b/services/account/jaxb/src/test/resources/log4j.properties @@ -1,25 +1,25 @@ -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 -log4j.logger.org.jvnet.hyperjaxb3=DEBUG +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 +log4j.logger.org.jvnet.hyperjaxb3=DEBUG log4j.logger.org.hibernate=WARN \ No newline at end of file diff --git a/services/account/pom.xml b/services/account/pom.xml index 4f16ab255..28987a60c 100644 --- a/services/account/pom.xml +++ b/services/account/pom.xml @@ -1,23 +1,23 @@ - - - - org.collectionspace.services - org.collectionspace.services.main - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.account - services.account - pom - - - jaxb - pstore - service - client - - - - + + + + org.collectionspace.services + org.collectionspace.services.main + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.account + services.account + pom + + + jaxb + pstore + service + client + + + + diff --git a/services/account/pstore/build.xml b/services/account/pstore/build.xml index 09106c56f..04588bc42 100644 --- a/services/account/pstore/build.xml +++ b/services/account/pstore/build.xml @@ -1,209 +1,209 @@ - - - collectionspace account service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + collectionspace account service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/account/pstore/pom.xml b/services/account/pstore/pom.xml index 9c2e4d03e..76ff48353 100644 --- a/services/account/pstore/pom.xml +++ b/services/account/pstore/pom.xml @@ -1,157 +1,157 @@ - - - - org.collectionspace.services.account - org.collectionspace.services - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.account.pstore - services.account.pstore - - - account.sql - ${basedir}/src/main/resources/db - - - - - com.sun.xml.bind - jaxb-impl - - - org.jvnet.jaxb2-commons - property-listener-injector - - - - mysql - mysql-connector-java - - - postgresql - postgresql - - - - org.collectionspace.services - org.collectionspace.services.account.jaxb - ${project.version} - - - - - collectionspace-services-account-pstore - - - maven-antrun-plugin - - - subs-hibernate-config - generate-test-resources - - run - - - - - - - - - - - - - - - - - ddl - - - - org.codehaus.mojo - properties-maven-plugin - 1.0-alpha-2 - - - initialize - - read-project-properties - - - - ${basedir}/../../../build.properties - - - - - - - org.codehaus.mojo - hibernate3-maven-plugin - 2.2 - - - process-test-resources - - hbm2ddl - - - - - - - hbm2ddl - - - - ${sql.file} - jpaconfiguration - true - true - true - true - false - org.collectionspace.services.account - - - - - mysql - mysql-connector-java - - - postgresql - postgresql - - - - - maven-antrun-plugin - - - process-test-resources - - - - - - - run - - - - - - - - - - - + + + + org.collectionspace.services.account + org.collectionspace.services + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.account.pstore + services.account.pstore + + + account.sql + ${basedir}/src/main/resources/db + + + + + com.sun.xml.bind + jaxb-impl + + + org.jvnet.jaxb2-commons + property-listener-injector + + + + mysql + mysql-connector-java + + + postgresql + postgresql + + + + org.collectionspace.services + org.collectionspace.services.account.jaxb + ${project.version} + + + + + collectionspace-services-account-pstore + + + maven-antrun-plugin + + + subs-hibernate-config + generate-test-resources + + run + + + + + + + + + + + + + + + + + ddl + + + + org.codehaus.mojo + properties-maven-plugin + 1.0-alpha-2 + + + initialize + + read-project-properties + + + + ${basedir}/../../../build.properties + + + + + + + org.codehaus.mojo + hibernate3-maven-plugin + 2.2 + + + process-test-resources + + hbm2ddl + + + + + + + hbm2ddl + + + + ${sql.file} + jpaconfiguration + true + true + true + true + false + org.collectionspace.services.account + + + + + mysql + mysql-connector-java + + + postgresql + postgresql + + + + + maven-antrun-plugin + + + process-test-resources + + + + + + + run + + + + + + + + + + + diff --git a/services/account/pstore/src/main/resources/db/postgresql/README.txt b/services/account/pstore/src/main/resources/db/postgresql/README.txt index b591433f8..4497b3aa8 100644 --- a/services/account/pstore/src/main/resources/db/postgresql/README.txt +++ b/services/account/pstore/src/main/resources/db/postgresql/README.txt @@ -1,32 +1,32 @@ -The file account.sql is basically generated by the gen_ddl ant target. -However, you must modify the result of that to make the - - DROP TABLE - -statements be - - DROP TABLE IF EXISTS table CASCADE - -This ensures that first time setup does not fail, and that later invocations -can deal with dependencies. - -You must also make the - - DROP SEQUENCE - -statements be - - DROP SEQUENCE IF EXISTS - -for similar reasons. - -You must also remove (comment out) the statement (which is superfluous with the CASCADE above): - - alter table permissions_actions drop constraint FKFDA649B05A9CEEB5; - -When using the account_tenants table on insert, you have to specify "nextval('hibernate_sequence')" -as the value for the HJID column. - -Note that because of the way gen_ddl does its work per-sub-project, there is a single shared -sequence for both this and the authorization.sql script. This should be okay, even if it does -create gaps in what would be a nice sequence for each table. +The file account.sql is basically generated by the gen_ddl ant target. +However, you must modify the result of that to make the + + DROP TABLE + +statements be + + DROP TABLE IF EXISTS table CASCADE + +This ensures that first time setup does not fail, and that later invocations +can deal with dependencies. + +You must also make the + + DROP SEQUENCE + +statements be + + DROP SEQUENCE IF EXISTS + +for similar reasons. + +You must also remove (comment out) the statement (which is superfluous with the CASCADE above): + + alter table permissions_actions drop constraint FKFDA649B05A9CEEB5; + +When using the account_tenants table on insert, you have to specify "nextval('hibernate_sequence')" +as the value for the HJID column. + +Note that because of the way gen_ddl does its work per-sub-project, there is a single shared +sequence for both this and the authorization.sql script. This should be okay, even if it does +create gaps in what would be a nice sequence for each table. diff --git a/services/account/pstore/src/test/resources/log4j.properties b/services/account/pstore/src/test/resources/log4j.properties index f9c47870a..8a63f9f10 100644 --- a/services/account/pstore/src/test/resources/log4j.properties +++ b/services/account/pstore/src/test/resources/log4j.properties @@ -1,25 +1,25 @@ -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 -log4j.logger.org.hibernate=INFO -log4j.logger.org.hibernate.cfg=WARN +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 +log4j.logger.org.hibernate=INFO +log4j.logger.org.hibernate.cfg=WARN diff --git a/services/account/service/pom.xml b/services/account/service/pom.xml index 2845a9b73..d04c6d364 100644 --- a/services/account/service/pom.xml +++ b/services/account/service/pom.xml @@ -1,121 +1,121 @@ - - - - org.collectionspace.services.account - org.collectionspace.services - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.account.service - services.account.service - jar - - - 3.0.2.RELEASE - - - - org.slf4j - slf4j-api - provided - - - org.slf4j - slf4j-log4j12 - provided - - - - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authentication.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authorization.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.account.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.account.client - ${project.version} - - - - - - junit - junit - 4.1 - test - - - org.testng - testng - - - - - commons-beanutils - commons-beanutils - 1.6.1 - - - commons-logging - commons-logging - 1.1 - - - - - - javax.security - jaas - 1.0.01 - provided - - - - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - - collectionspace-services-account - - - - - - + + + + org.collectionspace.services.account + org.collectionspace.services + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.account.service + services.account.service + jar + + + 3.0.2.RELEASE + + + + org.slf4j + slf4j-api + provided + + + org.slf4j + slf4j-log4j12 + provided + + + + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authentication.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authorization.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.account.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.account.client + ${project.version} + + + + + + junit + junit + 4.1 + test + + + org.testng + testng + + + + + commons-beanutils + commons-beanutils + 1.6.1 + + + commons-logging + commons-logging + 1.1 + + + + + + javax.security + jaas + 1.0.01 + provided + + + + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + + collectionspace-services-account + + + + + + diff --git a/services/acquisition/.classpath b/services/acquisition/.classpath index 046988541..25df93560 100644 --- a/services/acquisition/.classpath +++ b/services/acquisition/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/acquisition/.project b/services/acquisition/.project index 34718ac73..f509f695a 100644 --- a/services/acquisition/.project +++ b/services/acquisition/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.acquisition - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.acquisition + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/acquisition/3rdparty/.classpath b/services/acquisition/3rdparty/.classpath index d7501e2c4..b8a2888f8 100644 --- a/services/acquisition/3rdparty/.classpath +++ b/services/acquisition/3rdparty/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/acquisition/3rdparty/.project b/services/acquisition/3rdparty/.project index 526750fff..122a4b806 100644 --- a/services/acquisition/3rdparty/.project +++ b/services/acquisition/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.acquisition.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.acquisition.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/acquisition/3rdparty/build.xml b/services/acquisition/3rdparty/build.xml index 46457bb93..dabea25c8 100644 --- a/services/acquisition/3rdparty/build.xml +++ b/services/acquisition/3rdparty/build.xml @@ -1,131 +1,131 @@ - - - - acquisition service 3rdparty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + acquisition service 3rdparty + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/acquisition/3rdparty/pom.xml b/services/acquisition/3rdparty/pom.xml index b325bd51e..df2de39c3 100644 --- a/services/acquisition/3rdparty/pom.xml +++ b/services/acquisition/3rdparty/pom.xml @@ -1,24 +1,24 @@ - - - - org.collectionspace.services - org.collectionspace.services.acquisition - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.acquisition.3rdparty - pom - services.acquisition.3rdparty - - 3rd party build for acquisition service - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.acquisition + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.acquisition.3rdparty + pom + services.acquisition.3rdparty + + 3rd party build for acquisition service + + + + + + diff --git a/services/acquisition/build.xml b/services/acquisition/build.xml index edc7de211..158ee20e2 100644 --- a/services/acquisition/build.xml +++ b/services/acquisition/build.xml @@ -1,124 +1,124 @@ - - - - acquisition service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + acquisition service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/acquisition/client/pom.xml b/services/acquisition/client/pom.xml index a99a63936..2d628cfc0 100644 --- a/services/acquisition/client/pom.xml +++ b/services/acquisition/client/pom.xml @@ -1,103 +1,103 @@ - - - - org.collectionspace.services - org.collectionspace.services.acquisition - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.acquisition.client - services.acquisition.client - jar - - - - - org.slf4j - slf4j-api - test - - - org.slf4j - slf4j-log4j12 - test - - - - org.collectionspace.services - org.collectionspace.services.authority.jaxb - true - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.acquisition.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.person.client - ${project.version} - - - - org.testng - testng - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - commons-httpclient - commons-httpclient - 3.1 - - - - - collectionspace-services-acquisition-client - - - org.apache.maven.plugins - maven-surefire-plugin - - - - test-data.fileName - ${project.build.directory}/test-classes/test-data - - - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.acquisition + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.acquisition.client + services.acquisition.client + jar + + + + + org.slf4j + slf4j-api + test + + + org.slf4j + slf4j-log4j12 + test + + + + org.collectionspace.services + org.collectionspace.services.authority.jaxb + true + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.acquisition.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.person.client + ${project.version} + + + + org.testng + testng + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + commons-httpclient + commons-httpclient + 3.1 + + + + + collectionspace-services-acquisition-client + + + org.apache.maven.plugins + maven-surefire-plugin + + + + test-data.fileName + ${project.build.directory}/test-classes/test-data + + + + + + + + diff --git a/services/acquisition/client/src/test/resources/log4j.properties b/services/acquisition/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/acquisition/client/src/test/resources/log4j.properties +++ b/services/acquisition/client/src/test/resources/log4j.properties @@ -1,23 +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 +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/acquisition/jaxb/src/main/java/org/collectionspace/services/AcquisitionJAXBSchema.java b/services/acquisition/jaxb/src/main/java/org/collectionspace/services/AcquisitionJAXBSchema.java index c6de59ff1..a328209d2 100644 --- a/services/acquisition/jaxb/src/main/java/org/collectionspace/services/AcquisitionJAXBSchema.java +++ b/services/acquisition/jaxb/src/main/java/org/collectionspace/services/AcquisitionJAXBSchema.java @@ -1,14 +1,14 @@ -/** - * - */ -package org.collectionspace.services; - -/** - * @author remillet - * - */ -public interface AcquisitionJAXBSchema { - -} - - +/** + * + */ +package org.collectionspace.services; + +/** + * @author remillet + * + */ +public interface AcquisitionJAXBSchema { + +} + + diff --git a/services/acquisition/jaxb/src/main/java/org/collectionspace/services/AcquisitionListItemJAXBSchema.java b/services/acquisition/jaxb/src/main/java/org/collectionspace/services/AcquisitionListItemJAXBSchema.java index cde3b8e75..ede6e5396 100644 --- a/services/acquisition/jaxb/src/main/java/org/collectionspace/services/AcquisitionListItemJAXBSchema.java +++ b/services/acquisition/jaxb/src/main/java/org/collectionspace/services/AcquisitionListItemJAXBSchema.java @@ -1,14 +1,14 @@ -package org.collectionspace.services; - -public interface AcquisitionListItemJAXBSchema { - final static String ACQUISITION_REFERENCE_NUMBER = "acquisitionReferenceNumber"; - final static String ACQUISITION_SOURCE = "acquisitionSource"; - final static String ACQUISITION_SOURCES = "acquisitionSources"; - //final static String ACQUISITION_SOURCE_LIST = "acquisitionSourceList"; - - final static String OWNER = "owner"; - final static String OWNERS = "owners"; - //final static String OWNER_LIST = "ownerList"; - final static String CSID = "csid"; - final static String URI = "url"; -} +package org.collectionspace.services; + +public interface AcquisitionListItemJAXBSchema { + final static String ACQUISITION_REFERENCE_NUMBER = "acquisitionReferenceNumber"; + final static String ACQUISITION_SOURCE = "acquisitionSource"; + final static String ACQUISITION_SOURCES = "acquisitionSources"; + //final static String ACQUISITION_SOURCE_LIST = "acquisitionSourceList"; + + final static String OWNER = "owner"; + final static String OWNERS = "owners"; + //final static String OWNER_LIST = "ownerList"; + final static String CSID = "csid"; + final static String URI = "url"; +} diff --git a/services/acquisition/pom.xml b/services/acquisition/pom.xml index 30198c420..39e4bdd93 100644 --- a/services/acquisition/pom.xml +++ b/services/acquisition/pom.xml @@ -1,28 +1,28 @@ - - - - - org.collectionspace.services - org.collectionspace.services.main - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.acquisition - services.acquisition - pom - - - jaxb - service - 3rdparty - client - - - - - - - - + + + + + org.collectionspace.services + org.collectionspace.services.main + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.acquisition + services.acquisition + pom + + + jaxb + service + 3rdparty + client + + + + + + + + diff --git a/services/acquisition/service/pom.xml b/services/acquisition/service/pom.xml index 2247fb648..dbd8e25f1 100644 --- a/services/acquisition/service/pom.xml +++ b/services/acquisition/service/pom.xml @@ -1,46 +1,46 @@ - - - - org.collectionspace.services.acquisition - org.collectionspace.services - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.acquisition.service - services.acquisition.service - jar - - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.acquisition.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.acquisition.client - ${project.version} - - - - - collectionspace-services-acquisition - - - org.codehaus.mojo - jboss-maven-plugin - - ${jboss.dir} - - - - - - + + + + org.collectionspace.services.acquisition + org.collectionspace.services + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.acquisition.service + services.acquisition.service + jar + + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.acquisition.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.acquisition.client + ${project.version} + + + + + collectionspace-services-acquisition + + + org.codehaus.mojo + jboss-maven-plugin + + ${jboss.dir} + + + + + + diff --git a/services/acquisition/service/src/main/java/org/collectionspace/services/acquisition/nuxeo/AcquisitionValidatorHandler.java b/services/acquisition/service/src/main/java/org/collectionspace/services/acquisition/nuxeo/AcquisitionValidatorHandler.java index 3fda48096..6147f2ac7 100644 --- a/services/acquisition/service/src/main/java/org/collectionspace/services/acquisition/nuxeo/AcquisitionValidatorHandler.java +++ b/services/acquisition/service/src/main/java/org/collectionspace/services/acquisition/nuxeo/AcquisitionValidatorHandler.java @@ -1,18 +1,18 @@ -package org.collectionspace.services.acquisition.nuxeo; - -import org.collectionspace.services.common.context.ServiceContext; -import org.collectionspace.services.common.document.InvalidDocumentException; -import org.collectionspace.services.common.document.ValidatorHandler; -import org.collectionspace.services.common.document.DocumentHandler.Action; - -public class AcquisitionValidatorHandler implements ValidatorHandler { - - @Override - public void validate(Action action, ServiceContext ctx) - throws InvalidDocumentException { - // TODO Auto-generated method stub - System.out.println("AcquisitionValidatorHandler executed."); - - } - -} +package org.collectionspace.services.acquisition.nuxeo; + +import org.collectionspace.services.common.context.ServiceContext; +import org.collectionspace.services.common.document.InvalidDocumentException; +import org.collectionspace.services.common.document.ValidatorHandler; +import org.collectionspace.services.common.document.DocumentHandler.Action; + +public class AcquisitionValidatorHandler implements ValidatorHandler { + + @Override + public void validate(Action action, ServiceContext ctx) + throws InvalidDocumentException { + // TODO Auto-generated method stub + System.out.println("AcquisitionValidatorHandler executed."); + + } + +} diff --git a/services/authentication/.classpath b/services/authentication/.classpath index 046988541..25df93560 100644 --- a/services/authentication/.classpath +++ b/services/authentication/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/authentication/.project b/services/authentication/.project index 80f21e119..9d8929677 100644 --- a/services/authentication/.project +++ b/services/authentication/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.authentication - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.authentication + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/authentication/build.xml b/services/authentication/build.xml index 3a721a66b..b0d2709f1 100644 --- a/services/authentication/build.xml +++ b/services/authentication/build.xml @@ -1,138 +1,138 @@ - - - - authentication service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + authentication service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/authentication/client/build.xml b/services/authentication/client/build.xml index 557933f52..c617b450f 100644 --- a/services/authentication/client/build.xml +++ b/services/authentication/client/build.xml @@ -1,139 +1,139 @@ - - - collectionspace authentication service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + collectionspace authentication service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/authentication/client/pom.xml b/services/authentication/client/pom.xml index 94f4bc860..5dd48b4e3 100644 --- a/services/authentication/client/pom.xml +++ b/services/authentication/client/pom.xml @@ -1,67 +1,67 @@ - - - - - org.collectionspace.services - org.collectionspace.services.authentication - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.authentication.client - services.authentication.client - - - - - org.slf4j - slf4j-api - test - - - org.slf4j - slf4j-log4j12 - test - - - - org.collectionspace.services - org.collectionspace.services.authentication.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - - - cspace-services-authentication-client - - - maven-antrun-plugin - - - subs-hibernate-config - generate-test-resources - - run - - - - - - - - - - - - - - - + + + + + org.collectionspace.services + org.collectionspace.services.authentication + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.authentication.client + services.authentication.client + + + + + org.slf4j + slf4j-api + test + + + org.slf4j + slf4j-log4j12 + test + + + + org.collectionspace.services + org.collectionspace.services.authentication.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + + + cspace-services-authentication-client + + + maven-antrun-plugin + + + subs-hibernate-config + generate-test-resources + + run + + + + + + + + + + + + + + + diff --git a/services/authentication/client/src/test/resources/log4j.properties b/services/authentication/client/src/test/resources/log4j.properties index 5d288d87d..a78d35474 100644 --- a/services/authentication/client/src/test/resources/log4j.properties +++ b/services/authentication/client/src/test/resources/log4j.properties @@ -1,23 +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=WARN +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=WARN diff --git a/services/authentication/nb-configuration.xml b/services/authentication/nb-configuration.xml index 6c3fe600b..bcf0a33c9 100644 --- a/services/authentication/nb-configuration.xml +++ b/services/authentication/nb-configuration.xml @@ -1,20 +1,20 @@ - - + + - +--> + - default - 8 - 80 - - +--> + default + 8 + 80 + + diff --git a/services/authentication/pom.xml b/services/authentication/pom.xml index 805e827d8..766c894c7 100644 --- a/services/authentication/pom.xml +++ b/services/authentication/pom.xml @@ -1,26 +1,26 @@ - - - - org.collectionspace.services - org.collectionspace.services.main - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.authentication - services.authentication - pom - http://www.collectionspace.org - - - - - jaxb - pstore - service - client - - - - + + + + org.collectionspace.services + org.collectionspace.services.main + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.authentication + services.authentication + pom + http://www.collectionspace.org + + + + + jaxb + pstore + service + client + + + + diff --git a/services/authentication/pstore/build.xml b/services/authentication/pstore/build.xml index 13a5ff5f5..b2e346625 100644 --- a/services/authentication/pstore/build.xml +++ b/services/authentication/pstore/build.xml @@ -1,215 +1,215 @@ - - - collectionspace authentication service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + collectionspace authentication service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/authentication/pstore/pom.xml b/services/authentication/pstore/pom.xml index ff01982a1..899f3f447 100644 --- a/services/authentication/pstore/pom.xml +++ b/services/authentication/pstore/pom.xml @@ -1,148 +1,148 @@ - - - - - org.collectionspace.services - org.collectionspace.services.authentication - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.authentication.pstore - services.authentication.pstore - - - authentication.sql - ${basedir}/src/main/resources/db - - - - - mysql - mysql-connector-java - - - postgresql - postgresql - - - - org.collectionspace.services - org.collectionspace.services.authentication.jaxb - ${project.version} - - - - - cspace-services-authentication-pstore - - - maven-antrun-plugin - - - subs-hibernate-config - generate-test-resources - - run - - - - - - - - - - - - - - - - ddl - - - - org.codehaus.mojo - properties-maven-plugin - 1.0-alpha-2 - - - initialize - - read-project-properties - - - - ${basedir}/../../../build.properties - - - - - - - org.codehaus.mojo - hibernate3-maven-plugin - 2.2 - - - process-test-resources - - hbm2ddl - - - - - - - hbm2ddl - - - - ${sql.file} - jpaconfiguration - true - true - true - true - false - org.collectionspace.services.authentication - - - - - mysql - mysql-connector-java - - - postgresql - postgresql - - - - - maven-antrun-plugin - - - process-test-resources - - - - - - - run - - - - - - - - - - - + + + + + org.collectionspace.services + org.collectionspace.services.authentication + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.authentication.pstore + services.authentication.pstore + + + authentication.sql + ${basedir}/src/main/resources/db + + + + + mysql + mysql-connector-java + + + postgresql + postgresql + + + + org.collectionspace.services + org.collectionspace.services.authentication.jaxb + ${project.version} + + + + + cspace-services-authentication-pstore + + + maven-antrun-plugin + + + subs-hibernate-config + generate-test-resources + + run + + + + + + + + + + + + + + + + ddl + + + + org.codehaus.mojo + properties-maven-plugin + 1.0-alpha-2 + + + initialize + + read-project-properties + + + + ${basedir}/../../../build.properties + + + + + + + org.codehaus.mojo + hibernate3-maven-plugin + 2.2 + + + process-test-resources + + hbm2ddl + + + + + + + hbm2ddl + + + + ${sql.file} + jpaconfiguration + true + true + true + true + false + org.collectionspace.services.authentication + + + + + mysql + mysql-connector-java + + + postgresql + postgresql + + + + + maven-antrun-plugin + + + process-test-resources + + + + + + + run + + + + + + + + + + + diff --git a/services/authentication/pstore/src/main/resources/db/postgresql/README.txt b/services/authentication/pstore/src/main/resources/db/postgresql/README.txt index 4967d1a78..a543133d9 100644 --- a/services/authentication/pstore/src/main/resources/db/postgresql/README.txt +++ b/services/authentication/pstore/src/main/resources/db/postgresql/README.txt @@ -1,11 +1,11 @@ -The file authentication.sql is basically generated by the gen_ddl ant target. - -However, you must modify the result of that to make the - - DROP TABLE - -statements be - - DROP TABLE IF EXISTS table - -This ensures that first time setup does not fail. +The file authentication.sql is basically generated by the gen_ddl ant target. + +However, you must modify the result of that to make the + + DROP TABLE + +statements be + + DROP TABLE IF EXISTS table + +This ensures that first time setup does not fail. diff --git a/services/authentication/service/build.xml b/services/authentication/service/build.xml index 621abf13a..eba054e64 100644 --- a/services/authentication/service/build.xml +++ b/services/authentication/service/build.xml @@ -1,151 +1,151 @@ - - - - collectionspace authentication service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + collectionspace authentication service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/authentication/service/src/main/java/org/collectionspace/authentication/jaas/CSpaceJBossDBLoginModule.java b/services/authentication/service/src/main/java/org/collectionspace/authentication/jaas/CSpaceJBossDBLoginModule.java index bc585755b..b5b22930b 100644 --- a/services/authentication/service/src/main/java/org/collectionspace/authentication/jaas/CSpaceJBossDBLoginModule.java +++ b/services/authentication/service/src/main/java/org/collectionspace/authentication/jaas/CSpaceJBossDBLoginModule.java @@ -1,155 +1,155 @@ -/** - * 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.authentication.jaas; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.security.acl.Group; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.login.LoginException; - -import org.collectionspace.authentication.realm.db.CSpaceDbRealm; -import org.jboss.security.auth.spi.UsernamePasswordLoginModule; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * CollectionSpace default identity provider supporting multi-tenancy - * @author - */ -public class CSpaceJBossDBLoginModule extends UsernamePasswordLoginModule { - - private Logger logger = LoggerFactory.getLogger(CSpaceJBossDBLoginModule.class); - - private CSpaceDbRealm realm; - - /** - * Initialize CSpaceDBLoginModule - * - * @param options - - * dsJndiName: The name of the DataSource of the database containing the - * Principals, Roles tables - * principalsQuery: The prepared statement query, equivalent to: - * "select Password from Principals where PrincipalID=?" - * rolesQuery: The prepared statement query, equivalent to: - * "select Role, RoleGroup from Roles where PrincipalID=?" - * tenantsQuery: - * "select TenantId, TenantName, TenantGroup from Tenants where PrincipalID=?" - */ - public void initialize(Subject subject, CallbackHandler callbackHandler, - Map sharedState, Map options) { - super.initialize(subject, callbackHandler, sharedState, options); - realm = new CSpaceDbRealm(options); - } - - @Override - protected String createPasswordHash(String username, String password, - String digestOption) - throws LoginException { - String result = super.createPasswordHash(username, password, digestOption); - - if (result == null) { - String message = "Could not create a password hash for the supplied password. Check your login.conf configuration's hash algorithm setting."; - log.error(message); - throw new LoginException(message); - } - - return result; - } - - protected String getUsersPassword() throws LoginException { - - String username = getUsername(); - String password = null; - - try { - password = realm.getUsersPassword(username); - password = convertRawPassword(password); - if (logger.isDebugEnabled()) { - logger.debug("Obtained user password for: " + username); - } - } catch (LoginException lex) { - log.error("Could not retrieve user password for: " + username, lex); - throw lex; - } catch (Exception ex) { - log.error("Could not retrieve user password for: " + username, ex); - LoginException le = new LoginException("Unknown Exception"); - le.initCause(ex); - throw le; - } - - return password; - } - - @Override - public boolean commit() throws LoginException { - boolean result; - result = super.commit(); - return result; - } - - @Override - public boolean abort() throws LoginException { - boolean result; - result = super.abort(); - return result; - } - - /** Execute the rolesQuery against the dsJndiName to obtain the roles for - the authenticated user. - - @return Group[] containing the sets of roles - */ - protected Group[] getRoleSets() throws LoginException { - String username = getUsername(); - - Collection roles = realm.getRoles(username, - "org.collectionspace.authentication.CSpacePrincipal", - "org.jboss.security.SimpleGroup"); - - Collection tenants = realm.getTenants(username, - "org.jboss.security.SimpleGroup"); - - List all = new ArrayList(); - all.addAll(roles); - all.addAll(tenants); - Group[] roleSets = new Group[all.size()]; - all.toArray(roleSets); - return roleSets; - } - - /** A hook to allow subclasses to convert a password from the database - into a plain text string or whatever form is used for matching against - the user input. It is called from within the getUsersPassword() method. - @param rawPassword - the password as obtained from the database - @return the argument rawPassword - */ - protected String convertRawPassword(String rawPassword) { - return rawPassword; - } -} +/** + * 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.authentication.jaas; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.security.acl.Group; + +import javax.security.auth.Subject; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.login.LoginException; + +import org.collectionspace.authentication.realm.db.CSpaceDbRealm; +import org.jboss.security.auth.spi.UsernamePasswordLoginModule; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * CollectionSpace default identity provider supporting multi-tenancy + * @author + */ +public class CSpaceJBossDBLoginModule extends UsernamePasswordLoginModule { + + private Logger logger = LoggerFactory.getLogger(CSpaceJBossDBLoginModule.class); + + private CSpaceDbRealm realm; + + /** + * Initialize CSpaceDBLoginModule + * + * @param options - + * dsJndiName: The name of the DataSource of the database containing the + * Principals, Roles tables + * principalsQuery: The prepared statement query, equivalent to: + * "select Password from Principals where PrincipalID=?" + * rolesQuery: The prepared statement query, equivalent to: + * "select Role, RoleGroup from Roles where PrincipalID=?" + * tenantsQuery: + * "select TenantId, TenantName, TenantGroup from Tenants where PrincipalID=?" + */ + public void initialize(Subject subject, CallbackHandler callbackHandler, + Map sharedState, Map options) { + super.initialize(subject, callbackHandler, sharedState, options); + realm = new CSpaceDbRealm(options); + } + + @Override + protected String createPasswordHash(String username, String password, + String digestOption) + throws LoginException { + String result = super.createPasswordHash(username, password, digestOption); + + if (result == null) { + String message = "Could not create a password hash for the supplied password. Check your login.conf configuration's hash algorithm setting."; + log.error(message); + throw new LoginException(message); + } + + return result; + } + + protected String getUsersPassword() throws LoginException { + + String username = getUsername(); + String password = null; + + try { + password = realm.getUsersPassword(username); + password = convertRawPassword(password); + if (logger.isDebugEnabled()) { + logger.debug("Obtained user password for: " + username); + } + } catch (LoginException lex) { + log.error("Could not retrieve user password for: " + username, lex); + throw lex; + } catch (Exception ex) { + log.error("Could not retrieve user password for: " + username, ex); + LoginException le = new LoginException("Unknown Exception"); + le.initCause(ex); + throw le; + } + + return password; + } + + @Override + public boolean commit() throws LoginException { + boolean result; + result = super.commit(); + return result; + } + + @Override + public boolean abort() throws LoginException { + boolean result; + result = super.abort(); + return result; + } + + /** Execute the rolesQuery against the dsJndiName to obtain the roles for + the authenticated user. + + @return Group[] containing the sets of roles + */ + protected Group[] getRoleSets() throws LoginException { + String username = getUsername(); + + Collection roles = realm.getRoles(username, + "org.collectionspace.authentication.CSpacePrincipal", + "org.jboss.security.SimpleGroup"); + + Collection tenants = realm.getTenants(username, + "org.jboss.security.SimpleGroup"); + + List all = new ArrayList(); + all.addAll(roles); + all.addAll(tenants); + Group[] roleSets = new Group[all.size()]; + all.toArray(roleSets); + return roleSets; + } + + /** A hook to allow subclasses to convert a password from the database + into a plain text string or whatever form is used for matching against + the user input. It is called from within the getUsersPassword() method. + @param rawPassword - the password as obtained from the database + @return the argument rawPassword + */ + protected String convertRawPassword(String rawPassword) { + return rawPassword; + } +} diff --git a/services/authentication/service/src/test/resources/log4j.properties b/services/authentication/service/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/authentication/service/src/test/resources/log4j.properties +++ b/services/authentication/service/src/test/resources/log4j.properties @@ -1,23 +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 +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/authority/build.xml b/services/authority/build.xml index d5290c7d5..9dc3e098e 100644 --- a/services/authority/build.xml +++ b/services/authority/build.xml @@ -1,132 +1,132 @@ - - - CollectionSpace Authority services common code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + CollectionSpace Authority services common code + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/authority/jaxb/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityItemJAXBSchema.java b/services/authority/jaxb/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityItemJAXBSchema.java index e48c29eac..2bb0252c1 100644 --- a/services/authority/jaxb/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityItemJAXBSchema.java +++ b/services/authority/jaxb/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityItemJAXBSchema.java @@ -1,48 +1,48 @@ -/** - * 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.vocabulary; - -/** - * @author pschmitz - * - */ -public interface AuthorityItemJAXBSchema { - - final static String IN_AUTHORITY = "inAuthority"; // REM - Is this a CSID? Or a refname? Either? - final static String REF_NAME = "refName"; - final static String ORDER = "order"; - final static String SHORT_IDENTIFIER = "shortIdentifier"; - final static String CSID = "csid"; - final static String DISPLAY_NAME = "displayName"; // This is the display name element for the Vocabulary service's item - final static String TERM_DISPLAY_NAME = "termDisplayName"; // This is the display name element for all Authority services' items - final static String TERM_NAME = "termName"; - final static String TERM_STATUS = "termStatus"; - final static String TERM_INFO_GROUP_SCHEMA_NAME = ""; // FIXME: REM - Needs - // to be defined. - // CSPACE-4813 - Remove all the below values and recompile all authorityitem - // related classes - final static String DISPLAY_NAME_COMPUTED = "displayNameComputed"; - final static String SHORT_DISPLAY_NAME = "shortDisplayName"; - final static String SHORT_DISPLAY_NAME_COMPUTED = "shortDisplayNameComputed"; - // final static String TERM_STATUS = "termStatus"; -} +/** + * 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.vocabulary; + +/** + * @author pschmitz + * + */ +public interface AuthorityItemJAXBSchema { + + final static String IN_AUTHORITY = "inAuthority"; // REM - Is this a CSID? Or a refname? Either? + final static String REF_NAME = "refName"; + final static String ORDER = "order"; + final static String SHORT_IDENTIFIER = "shortIdentifier"; + final static String CSID = "csid"; + final static String DISPLAY_NAME = "displayName"; // This is the display name element for the Vocabulary service's item + final static String TERM_DISPLAY_NAME = "termDisplayName"; // This is the display name element for all Authority services' items + final static String TERM_NAME = "termName"; + final static String TERM_STATUS = "termStatus"; + final static String TERM_INFO_GROUP_SCHEMA_NAME = ""; // FIXME: REM - Needs + // to be defined. + // CSPACE-4813 - Remove all the below values and recompile all authorityitem + // related classes + final static String DISPLAY_NAME_COMPUTED = "displayNameComputed"; + final static String SHORT_DISPLAY_NAME = "shortDisplayName"; + final static String SHORT_DISPLAY_NAME_COMPUTED = "shortDisplayNameComputed"; + // final static String TERM_STATUS = "termStatus"; +} diff --git a/services/authority/jaxb/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityItemListItemJAXBSchema.java b/services/authority/jaxb/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityItemListItemJAXBSchema.java index b5d2f0d81..6814288f6 100644 --- a/services/authority/jaxb/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityItemListItemJAXBSchema.java +++ b/services/authority/jaxb/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityItemListItemJAXBSchema.java @@ -1,33 +1,33 @@ -/** - * 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.vocabulary; - -public interface AuthorityItemListItemJAXBSchema { - final static String DISPLAY_NAME = "displayName"; - final static String SHORT_DISPLAY_NAME = "shortDisplayName"; - final static String REF_NAME = "refName"; - final static String SHORT_IDENTIFIER = "shortIdentifier"; - final static String CSID = "csid"; - final static String URI = "url"; -} +/** + * 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.vocabulary; + +public interface AuthorityItemListItemJAXBSchema { + final static String DISPLAY_NAME = "displayName"; + final static String SHORT_DISPLAY_NAME = "shortDisplayName"; + final static String REF_NAME = "refName"; + final static String SHORT_IDENTIFIER = "shortIdentifier"; + final static String CSID = "csid"; + final static String URI = "url"; +} diff --git a/services/authority/jaxb/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityJAXBSchema.java b/services/authority/jaxb/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityJAXBSchema.java index 456ea65e0..adecfe1ec 100644 --- a/services/authority/jaxb/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityJAXBSchema.java +++ b/services/authority/jaxb/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityJAXBSchema.java @@ -1,38 +1,38 @@ -/** - * 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.vocabulary; - -/** - * @author pschmitz - * - */ -public interface AuthorityJAXBSchema { - final static String DISPLAY_NAME = "displayName"; - final static String SHORT_IDENTIFIER = "shortIdentifier"; - final static String REF_NAME = "refName"; - final static String VOCAB_TYPE = "vocabType"; - final static String CSID = "csid"; -} - - +/** + * 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.vocabulary; + +/** + * @author pschmitz + * + */ +public interface AuthorityJAXBSchema { + final static String DISPLAY_NAME = "displayName"; + final static String SHORT_IDENTIFIER = "shortIdentifier"; + final static String REF_NAME = "refName"; + final static String VOCAB_TYPE = "vocabType"; + final static String CSID = "csid"; +} + + diff --git a/services/authority/jaxb/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityListItemJAXBSchema.java b/services/authority/jaxb/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityListItemJAXBSchema.java index b02c59a34..2cd5ae704 100644 --- a/services/authority/jaxb/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityListItemJAXBSchema.java +++ b/services/authority/jaxb/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityListItemJAXBSchema.java @@ -1,33 +1,33 @@ -/** - * 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.vocabulary; - -public interface AuthorityListItemJAXBSchema { - final static String DISPLAY_NAME = "displayName"; - final static String REF_NAME = "refName"; - final static String SHORT_IDENTIFIER = "shortIdentifier"; - final static String VOCAB_TYPE = "vocabType"; - final static String CSID = "csid"; - final static String URI = "url"; -} +/** + * 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.vocabulary; + +public interface AuthorityListItemJAXBSchema { + final static String DISPLAY_NAME = "displayName"; + final static String REF_NAME = "refName"; + final static String SHORT_IDENTIFIER = "shortIdentifier"; + final static String VOCAB_TYPE = "vocabType"; + final static String CSID = "csid"; + final static String URI = "url"; +} diff --git a/services/authority/pom.xml b/services/authority/pom.xml index 06fc4fb53..382184e7f 100644 --- a/services/authority/pom.xml +++ b/services/authority/pom.xml @@ -1,268 +1,268 @@ - - - - org.collectionspace.services - org.collectionspace.services.main - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.authority - services.authority - pom - - - - - - - - - - log4j - log4j - 1.2.14 - provided - - - org.apache.commons - commons-jexl - 2.0.1 - - - commons-codec - commons-codec - 1.4 - - - - - javax.servlet - servlet-api - 2.5 - provided - - - - javax.security - jaas - 1.0.01 - provided - - - javax.security - jacc - 1.0 - provided - - - - mysql - mysql-connector-java - - - postgresql - postgresql - - - javax.persistence - persistence-api - - - - - org.jboss.resteasy - jaxrs-api - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - org.hibernate - hibernate-entitymanager - - - - jboss - jbosssx - 4.2.3.GA - provided - - - jboss - jboss-remoting - 2.2.2.SP8 - provided - - - - - - - - jaxb - service - - - - + + + + org.collectionspace.services + org.collectionspace.services.main + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.authority + services.authority + pom + + + + + + + + + + log4j + log4j + 1.2.14 + provided + + + org.apache.commons + commons-jexl + 2.0.1 + + + commons-codec + commons-codec + 1.4 + + + + + javax.servlet + servlet-api + 2.5 + provided + + + + javax.security + jaas + 1.0.01 + provided + + + javax.security + jacc + 1.0 + provided + + + + mysql + mysql-connector-java + + + postgresql + postgresql + + + javax.persistence + persistence-api + + + + + org.jboss.resteasy + jaxrs-api + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + org.hibernate + hibernate-entitymanager + + + + jboss + jbosssx + 4.2.3.GA + provided + + + jboss + jboss-remoting + 2.2.2.SP8 + provided + + + + + + + + jaxb + service + + + + diff --git a/services/authority/service/pom.xml b/services/authority/service/pom.xml index 03deed877..7435ca575 100644 --- a/services/authority/service/pom.xml +++ b/services/authority/service/pom.xml @@ -1,301 +1,301 @@ - - - - org.collectionspace.services - org.collectionspace.services.authority - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.authority.service - services.authority.service - jar - - - - - org.collectionspace.services - org.collectionspace.services.config - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.common-api - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authority.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.vocabulary.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authentication.jaxb - ${project.version} - provided - - - org.collectionspace.services - org.collectionspace.services.authentication.service - ${project.version} - provided - - - org.collectionspace.services - org.collectionspace.services.authorization.jaxb - ${project.version} - provided - - - org.collectionspace.services - org.collectionspace.services.authorization.service - ${project.version} - provided - - - org.collectionspace.services - org.collectionspace.services.relation.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.relation.client - ${project.version} - - - - - - - org.slf4j - slf4j-api - provided - - - org.slf4j - slf4j-log4j12 - provided - - - log4j - log4j - 1.2.14 - provided - - - org.apache.commons - commons-jexl - 2.0.1 - - - commons-codec - commons-codec - 1.4 - - - - - javax.servlet - servlet-api - 2.5 - provided - - - - javax.security - jaas - 1.0.01 - provided - - - javax.security - jacc - 1.0 - provided - - - - mysql - mysql-connector-java - - - postgresql - postgresql - - - javax.persistence - persistence-api - - - - com.sun.xml.bind - jaxb-impl - - - org.jvnet.jaxb2-commons - property-listener-injector - - - - - - org.jboss.resteasy - jaxrs-api - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - org.hibernate - hibernate-entitymanager - - - - jboss - jbosssx - 4.2.3.GA - provided - - - jboss - jboss-remoting - 2.2.2.SP8 - provided - - - - org.nuxeo.ecm.platform - nuxeo-platform-mimetype-api - ${nuxeo.platform.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-imaging-core - ${nuxeo.platform.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-imaging-api - ${nuxeo.platform.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-filemanager-api - ${nuxeo.platform.version} - - - org.nuxeo.common - nuxeo-common - ${nuxeo.core.version} - provided - - - org.nuxeo.runtime - nuxeo-runtime - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-api - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-client - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-query - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-schema - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-storage-sql - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-io - ${nuxeo.core.version} - - - - org.nuxeo.ecm.core - nuxeo-core-io - ${nuxeo.core.version} - - - org.nuxeo.runtime - nuxeo-runtime-osgi - ${nuxeo.core.version} - - - org.osgi - org.osgi.core - 4.1.0 - - - - + + + + org.collectionspace.services + org.collectionspace.services.authority + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.authority.service + services.authority.service + jar + + + + + org.collectionspace.services + org.collectionspace.services.config + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.common-api + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authority.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.vocabulary.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authentication.jaxb + ${project.version} + provided + + + org.collectionspace.services + org.collectionspace.services.authentication.service + ${project.version} + provided + + + org.collectionspace.services + org.collectionspace.services.authorization.jaxb + ${project.version} + provided + + + org.collectionspace.services + org.collectionspace.services.authorization.service + ${project.version} + provided + + + org.collectionspace.services + org.collectionspace.services.relation.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.relation.client + ${project.version} + + + + + + + org.slf4j + slf4j-api + provided + + + org.slf4j + slf4j-log4j12 + provided + + + log4j + log4j + 1.2.14 + provided + + + org.apache.commons + commons-jexl + 2.0.1 + + + commons-codec + commons-codec + 1.4 + + + + + javax.servlet + servlet-api + 2.5 + provided + + + + javax.security + jaas + 1.0.01 + provided + + + javax.security + jacc + 1.0 + provided + + + + mysql + mysql-connector-java + + + postgresql + postgresql + + + javax.persistence + persistence-api + + + + com.sun.xml.bind + jaxb-impl + + + org.jvnet.jaxb2-commons + property-listener-injector + + + + + + org.jboss.resteasy + jaxrs-api + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + org.hibernate + hibernate-entitymanager + + + + jboss + jbosssx + 4.2.3.GA + provided + + + jboss + jboss-remoting + 2.2.2.SP8 + provided + + + + org.nuxeo.ecm.platform + nuxeo-platform-mimetype-api + ${nuxeo.platform.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-imaging-core + ${nuxeo.platform.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-imaging-api + ${nuxeo.platform.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-filemanager-api + ${nuxeo.platform.version} + + + org.nuxeo.common + nuxeo-common + ${nuxeo.core.version} + provided + + + org.nuxeo.runtime + nuxeo-runtime + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-api + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-client + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-query + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-schema + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-storage-sql + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-io + ${nuxeo.core.version} + + + + org.nuxeo.ecm.core + nuxeo-core-io + ${nuxeo.core.version} + + + org.nuxeo.runtime + nuxeo-runtime-osgi + ${nuxeo.core.version} + + + org.osgi + org.osgi.core + 4.1.0 + + + + diff --git a/services/authority/service/src/main/java/org/collectionspace/services/common/vocabulary/IVocabManager.java b/services/authority/service/src/main/java/org/collectionspace/services/common/vocabulary/IVocabManager.java index c39206bba..ad272c82a 100644 --- a/services/authority/service/src/main/java/org/collectionspace/services/common/vocabulary/IVocabManager.java +++ b/services/authority/service/src/main/java/org/collectionspace/services/common/vocabulary/IVocabManager.java @@ -1,7 +1,7 @@ -package org.collectionspace.services.common.vocabulary; - -public interface IVocabManager { - - public void exampleMethod(String someParam); - -} +package org.collectionspace.services.common.vocabulary; + +public interface IVocabManager { + + public void exampleMethod(String someParam); + +} diff --git a/services/authority/service/src/main/java/org/collectionspace/services/common/vocabulary/VocabManager.java b/services/authority/service/src/main/java/org/collectionspace/services/common/vocabulary/VocabManager.java index 849599071..27d1cfdad 100644 --- a/services/authority/service/src/main/java/org/collectionspace/services/common/vocabulary/VocabManager.java +++ b/services/authority/service/src/main/java/org/collectionspace/services/common/vocabulary/VocabManager.java @@ -1,9 +1,9 @@ -package org.collectionspace.services.common.vocabulary; - -public class VocabManager { - static private final IVocabManager vocabManager = new VocabManagerImpl(); - - static public void exampleMethod(String someParam) { - vocabManager.exampleMethod(someParam); - } -} +package org.collectionspace.services.common.vocabulary; + +public class VocabManager { + static private final IVocabManager vocabManager = new VocabManagerImpl(); + + static public void exampleMethod(String someParam) { + vocabManager.exampleMethod(someParam); + } +} diff --git a/services/authority/service/src/main/java/org/collectionspace/services/common/vocabulary/VocabManagerImpl.java b/services/authority/service/src/main/java/org/collectionspace/services/common/vocabulary/VocabManagerImpl.java index 3fbac6ae1..655eb125e 100644 --- a/services/authority/service/src/main/java/org/collectionspace/services/common/vocabulary/VocabManagerImpl.java +++ b/services/authority/service/src/main/java/org/collectionspace/services/common/vocabulary/VocabManagerImpl.java @@ -1,22 +1,22 @@ -package org.collectionspace.services.common.vocabulary; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.nuxeo.ecm.core.api.DocumentModel; -import org.nuxeo.ecm.core.api.DocumentModelList; -import org.nuxeo.ecm.core.api.repository.RepositoryInstance; -import org.nuxeo.ecm.core.client.NuxeoClient; - -//import org.collectionspace.services.nuxeo.client.java.NuxeoConnector; -import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl; -//import org.collectionspace.services.common.query.IQueryManager; - -public class VocabManagerImpl implements IVocabManager { - - private final Logger logger = LoggerFactory - .getLogger(VocabManagerImpl.class); - - public void exampleMethod(String someParam) { - } -} +package org.collectionspace.services.common.vocabulary; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.nuxeo.ecm.core.api.DocumentModel; +import org.nuxeo.ecm.core.api.DocumentModelList; +import org.nuxeo.ecm.core.api.repository.RepositoryInstance; +import org.nuxeo.ecm.core.client.NuxeoClient; + +//import org.collectionspace.services.nuxeo.client.java.NuxeoConnector; +import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl; +//import org.collectionspace.services.common.query.IQueryManager; + +public class VocabManagerImpl implements IVocabManager { + + private final Logger logger = LoggerFactory + .getLogger(VocabManagerImpl.class); + + public void exampleMethod(String someParam) { + } +} diff --git a/services/authorization-mgt/.classpath b/services/authorization-mgt/.classpath index 046988541..25df93560 100644 --- a/services/authorization-mgt/.classpath +++ b/services/authorization-mgt/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/authorization-mgt/.project b/services/authorization-mgt/.project index a8ee8d880..32a8c1d9e 100644 --- a/services/authorization-mgt/.project +++ b/services/authorization-mgt/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.authorization-mgt - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.authorization-mgt + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/authorization-mgt/build.xml b/services/authorization-mgt/build.xml index 507dccee2..c26169646 100644 --- a/services/authorization-mgt/build.xml +++ b/services/authorization-mgt/build.xml @@ -1,138 +1,138 @@ - - - - authorization service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + authorization service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/authorization-mgt/client/build.xml b/services/authorization-mgt/client/build.xml index e0d3efcf5..976f4ed01 100644 --- a/services/authorization-mgt/client/build.xml +++ b/services/authorization-mgt/client/build.xml @@ -1,126 +1,126 @@ - - - - collectionspace authorization-mgt client - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + collectionspace authorization-mgt client + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/authorization-mgt/client/pom.xml b/services/authorization-mgt/client/pom.xml index 3e9d1ff5f..423f22876 100644 --- a/services/authorization-mgt/client/pom.xml +++ b/services/authorization-mgt/client/pom.xml @@ -1,184 +1,184 @@ - - - - org.collectionspace.services - org.collectionspace.services.authorization-mgt - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.authorization-mgt.client - services.authorization-mgt.client - - 3.0.0.RELEASE - 3.0.2.RELEASE - - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - org.collectionspace.services - org.collectionspace.services.authentication.service - ${project.version} - provided - - - org.collectionspace.services - org.collectionspace.services.authorization.service - ${project.version} - provided - - - org.collectionspace.services - org.collectionspace.services.authorization.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - - - - - - org.testng - testng - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - commons-httpclient - commons-httpclient - 3.1 - - - - org.springframework.security - spring-security-core - ${spring.security.version} - provided - - - org.springframework.security - spring-security-config - ${spring.security.version} - provided - - - org.springframework.security - spring-security-acl - ${spring.security.version} - provided - - - org.springframework.security - spring-security-web - ${spring.security.version} - provided - - - org.springframework - spring-context - ${spring.version} - provided - - - org.springframework - spring-context-support - ${spring.version} - provided - - - org.springframework - spring-aop - ${spring.version} - provided - - - aopalliance - aopalliance - 1.0 - provided - - - - net.sf.ehcache - ehcache - 1.6.2 - true - - - mysql - mysql-connector-java - test - - - postgresql - postgresql - test - - - - - cspace-services-authorization-mgt-client - - - org.apache.maven.plugins - maven-surefire-plugin - - - - maven.basedir - ${basedir} - - - log4j.configuration - file:${project.build.directory}/test-classes/log4j.properties - - - - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.authorization-mgt + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.authorization-mgt.client + services.authorization-mgt.client + + 3.0.0.RELEASE + 3.0.2.RELEASE + + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + org.collectionspace.services + org.collectionspace.services.authentication.service + ${project.version} + provided + + + org.collectionspace.services + org.collectionspace.services.authorization.service + ${project.version} + provided + + + org.collectionspace.services + org.collectionspace.services.authorization.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + + + + + + org.testng + testng + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + commons-httpclient + commons-httpclient + 3.1 + + + + org.springframework.security + spring-security-core + ${spring.security.version} + provided + + + org.springframework.security + spring-security-config + ${spring.security.version} + provided + + + org.springframework.security + spring-security-acl + ${spring.security.version} + provided + + + org.springframework.security + spring-security-web + ${spring.security.version} + provided + + + org.springframework + spring-context + ${spring.version} + provided + + + org.springframework + spring-context-support + ${spring.version} + provided + + + org.springframework + spring-aop + ${spring.version} + provided + + + aopalliance + aopalliance + 1.0 + provided + + + + net.sf.ehcache + ehcache + 1.6.2 + true + + + mysql + mysql-connector-java + test + + + postgresql + postgresql + test + + + + + cspace-services-authorization-mgt-client + + + org.apache.maven.plugins + maven-surefire-plugin + + + + maven.basedir + ${basedir} + + + log4j.configuration + file:${project.build.directory}/test-classes/log4j.properties + + + + + + + + + diff --git a/services/authorization-mgt/client/src/test/resources/log4j.properties b/services/authorization-mgt/client/src/test/resources/log4j.properties index f9c47870a..8a63f9f10 100644 --- a/services/authorization-mgt/client/src/test/resources/log4j.properties +++ b/services/authorization-mgt/client/src/test/resources/log4j.properties @@ -1,25 +1,25 @@ -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 -log4j.logger.org.hibernate=INFO -log4j.logger.org.hibernate.cfg=WARN +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 +log4j.logger.org.hibernate=INFO +log4j.logger.org.hibernate.cfg=WARN diff --git a/services/authorization-mgt/import/build.xml b/services/authorization-mgt/import/build.xml index c3b7594bd..0ea7137cf 100644 --- a/services/authorization-mgt/import/build.xml +++ b/services/authorization-mgt/import/build.xml @@ -1,165 +1,165 @@ - - - collectionspace authorization-mgt import - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + collectionspace authorization-mgt import + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/authorization-mgt/import/pom.xml b/services/authorization-mgt/import/pom.xml index be1d9ea9c..fdaaf8a08 100644 --- a/services/authorization-mgt/import/pom.xml +++ b/services/authorization-mgt/import/pom.xml @@ -1,237 +1,237 @@ - - - - org.collectionspace.services - org.collectionspace.services.authorization-mgt - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.authorization-mgt.import - services.authorization-mgt.import - - false - 3.0.0.RELEASE - 3.0.2.RELEASE - - - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - - org.collectionspace.services - org.collectionspace.services.authentication.service - ${project.version} - provided - - - org.collectionspace.services - org.collectionspace.services.authorization.service - ${project.version} - provided - - - org.collectionspace.services - org.collectionspace.services.authorization.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.config - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - provided - - - org.collectionspace.services - org.collectionspace.services.account.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authorization-mgt.service - ${project.version} - provided - - - org.collectionspace.services - org.collectionspace.services.authorization-mgt.client - ${project.version} - - - - org.testng - testng - - - commons-cli - commons-cli - - - org.springframework.security - spring-security-core - ${spring.security.version} - provided - - - org.springframework.security - spring-security-config - ${spring.security.version} - provided - - - org.springframework.security - spring-security-acl - ${spring.security.version} - provided - - - org.springframework.security - spring-security-web - ${spring.security.version} - provided - - - org.springframework - spring-context - ${spring.version} - provided - - - org.springframework - spring-context-support - ${spring.version} - provided - - - org.springframework - spring-aop - ${spring.version} - provided - - - aopalliance - aopalliance - 1.0 - provided - - - - net.sf.ehcache - ehcache - 1.6.2 - true - - - mysql - mysql-connector-java - - - postgresql - postgresql - - - ch.elca.el4j.modules - module-xml_merge-common - 3.1 - - - - - - cspace-services-authorization-mgt-import - - ../../../build.properties - - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-resources-plugin - 2.5 - - - process-resources - - resources - - - - - - org.codehaus.mojo - exec-maven-plugin - - - - java - - - - - org.collectionspace.ImportAuthz - - -g - ${generate_only} - -u - SPRING_ADMIN - -p - does_not_matter - -b - - ${env.CSPACE_JEESERVER_HOME} - -edir - ${basedir}/target - - - - - - - - - postgresql - postgresql - ${postgres.driver.version} - - - - - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.authorization-mgt + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.authorization-mgt.import + services.authorization-mgt.import + + false + 3.0.0.RELEASE + 3.0.2.RELEASE + + + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + + org.collectionspace.services + org.collectionspace.services.authentication.service + ${project.version} + provided + + + org.collectionspace.services + org.collectionspace.services.authorization.service + ${project.version} + provided + + + org.collectionspace.services + org.collectionspace.services.authorization.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.config + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + provided + + + org.collectionspace.services + org.collectionspace.services.account.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authorization-mgt.service + ${project.version} + provided + + + org.collectionspace.services + org.collectionspace.services.authorization-mgt.client + ${project.version} + + + + org.testng + testng + + + commons-cli + commons-cli + + + org.springframework.security + spring-security-core + ${spring.security.version} + provided + + + org.springframework.security + spring-security-config + ${spring.security.version} + provided + + + org.springframework.security + spring-security-acl + ${spring.security.version} + provided + + + org.springframework.security + spring-security-web + ${spring.security.version} + provided + + + org.springframework + spring-context + ${spring.version} + provided + + + org.springframework + spring-context-support + ${spring.version} + provided + + + org.springframework + spring-aop + ${spring.version} + provided + + + aopalliance + aopalliance + 1.0 + provided + + + + net.sf.ehcache + ehcache + 1.6.2 + true + + + mysql + mysql-connector-java + + + postgresql + postgresql + + + ch.elca.el4j.modules + module-xml_merge-common + 3.1 + + + + + + cspace-services-authorization-mgt-import + + ../../../build.properties + + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.5 + + + process-resources + + resources + + + + + + org.codehaus.mojo + exec-maven-plugin + + + + java + + + + + org.collectionspace.ImportAuthz + + -g + ${generate_only} + -u + SPRING_ADMIN + -p + does_not_matter + -b + + ${env.CSPACE_JEESERVER_HOME} + -edir + ${basedir}/target + + + + + + + + + postgresql + postgresql + ${postgres.driver.version} + + + + + + + + + + diff --git a/services/authorization-mgt/import/src/main/resources/log4j.properties b/services/authorization-mgt/import/src/main/resources/log4j.properties index f39efb3db..b5f601bdf 100644 --- a/services/authorization-mgt/import/src/main/resources/log4j.properties +++ b/services/authorization-mgt/import/src/main/resources/log4j.properties @@ -1,39 +1,39 @@ -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.commandline=org.apache.log4j.ConsoleAppender -log4j.appender.commandline.target=System.err -log4j.appender.commandline.layout=org.apache.log4j.PatternLayout -log4j.appender.commandline.layout.ConversionPattern=%d %p: %m%n - -log4j.appender.R=org.apache.log4j.RollingFileAppender -log4j.appender.R.File=target/test-client.log -log4j.appender.R.MaxFileSize=100KB -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.services.authorization.spring=INFO -# log4j.logger.org.collectionspace.services.common.authorization_mgt.AuthorizationStore=TRACE -log4j.logger.org.apache=INFO -log4j.logger.httpclient=INFO -log4j.logger.org.jboss.resteasy=INFO -log4j.logger.hibernate=WARN -log4j.logger.org.hibernate=WARN -log4j.logger.org.hibernate.cfg=WARN -log4j.logger.org.springframework=WARN -log4j.logger.ch.elca.el4j.services.xmlmerge=INFO -log4j.logger.com.sun.xml.bind.v2.runtime=DEBUG -log4j.logger.javax.persistence.PersistenceException=ERROR - -# -# Logging for the command line tool that generates the Service artifacts -# -log4j.logger.org.collectionspace=INFO, commandline -log4j.additivity.org.collectionspace=false - +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.commandline=org.apache.log4j.ConsoleAppender +log4j.appender.commandline.target=System.err +log4j.appender.commandline.layout=org.apache.log4j.PatternLayout +log4j.appender.commandline.layout.ConversionPattern=%d %p: %m%n + +log4j.appender.R=org.apache.log4j.RollingFileAppender +log4j.appender.R.File=target/test-client.log +log4j.appender.R.MaxFileSize=100KB +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.services.authorization.spring=INFO +# log4j.logger.org.collectionspace.services.common.authorization_mgt.AuthorizationStore=TRACE +log4j.logger.org.apache=INFO +log4j.logger.httpclient=INFO +log4j.logger.org.jboss.resteasy=INFO +log4j.logger.hibernate=WARN +log4j.logger.org.hibernate=WARN +log4j.logger.org.hibernate.cfg=WARN +log4j.logger.org.springframework=WARN +log4j.logger.ch.elca.el4j.services.xmlmerge=INFO +log4j.logger.com.sun.xml.bind.v2.runtime=DEBUG +log4j.logger.javax.persistence.PersistenceException=ERROR + +# +# Logging for the command line tool that generates the Service artifacts +# +log4j.logger.org.collectionspace=INFO, commandline +log4j.additivity.org.collectionspace=false + diff --git a/services/authorization-mgt/service/build.xml b/services/authorization-mgt/service/build.xml index 04f900b88..389065094 100644 --- a/services/authorization-mgt/service/build.xml +++ b/services/authorization-mgt/service/build.xml @@ -1,134 +1,134 @@ - - - - collectionspace authorization service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + collectionspace authorization service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/authorization-mgt/service/pom.xml b/services/authorization-mgt/service/pom.xml index 9ed3fc315..cf9bcdc0c 100644 --- a/services/authorization-mgt/service/pom.xml +++ b/services/authorization-mgt/service/pom.xml @@ -1,200 +1,200 @@ - - - 4.0.0 - - org.collectionspace.services.authorization-mgt - org.collectionspace.services - 4.2-SNAPSHOT - - - org.collectionspace.services.authorization-mgt.service - jar - services.authorization-mgt.service - http://www.collectionspace.org - - - UTF-8 - 3.0.0.RELEASE - 3.0.2.RELEASE - - - - - org.collectionspace.services - org.collectionspace.services.authorization-mgt.client - ${project.version} - provided - - - - - - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - junit - junit - 4.1 - test - - - org.testng - testng - test - - - - javax.security - jaas - 1.0.01 - provided - - - - - org.jboss.logging - jboss-logging-log4j - 2.1.0.GA - - - jboss - jbosssx - 4.2.3.GA - provided - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - - org.springframework.security - spring-security-core - ${spring.security.version} - provided - - - org.springframework.security - spring-security-config - ${spring.security.version} - provided - - - org.springframework.security - spring-security-acl - ${spring.security.version} - provided - - - org.springframework.security - spring-security-web - ${spring.security.version} - provided - - - org.springframework - spring-context - ${spring.version} - provided - - - org.springframework - spring-context-support - ${spring.version} - provided - - - org.springframework - spring-aop - ${spring.version} - provided - - - aopalliance - aopalliance - 1.0 - provided - - - - net.sf.ehcache - ehcache - 1.6.2 - true - - - - - org.collectionspace.services - org.collectionspace.services.authentication.service - ${project.version} - provided - - - org.collectionspace.services - org.collectionspace.services.authorization.jaxb - ${project.version} - provided - - - org.collectionspace.services - org.collectionspace.services.authorization.service - ${project.version} - provided - - - org.collectionspace.services - org.collectionspace.services.account.service - ${project.version} - provided - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - - - collectionspace-services-authz-mgt - - + + + 4.0.0 + + org.collectionspace.services.authorization-mgt + org.collectionspace.services + 4.2-SNAPSHOT + + + org.collectionspace.services.authorization-mgt.service + jar + services.authorization-mgt.service + http://www.collectionspace.org + + + UTF-8 + 3.0.0.RELEASE + 3.0.2.RELEASE + + + + + org.collectionspace.services + org.collectionspace.services.authorization-mgt.client + ${project.version} + provided + + + + + + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + junit + junit + 4.1 + test + + + org.testng + testng + test + + + + javax.security + jaas + 1.0.01 + provided + + + + + org.jboss.logging + jboss-logging-log4j + 2.1.0.GA + + + jboss + jbosssx + 4.2.3.GA + provided + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + + org.springframework.security + spring-security-core + ${spring.security.version} + provided + + + org.springframework.security + spring-security-config + ${spring.security.version} + provided + + + org.springframework.security + spring-security-acl + ${spring.security.version} + provided + + + org.springframework.security + spring-security-web + ${spring.security.version} + provided + + + org.springframework + spring-context + ${spring.version} + provided + + + org.springframework + spring-context-support + ${spring.version} + provided + + + org.springframework + spring-aop + ${spring.version} + provided + + + aopalliance + aopalliance + 1.0 + provided + + + + net.sf.ehcache + ehcache + 1.6.2 + true + + + + + org.collectionspace.services + org.collectionspace.services.authentication.service + ${project.version} + provided + + + org.collectionspace.services + org.collectionspace.services.authorization.jaxb + ${project.version} + provided + + + org.collectionspace.services + org.collectionspace.services.authorization.service + ${project.version} + provided + + + org.collectionspace.services + org.collectionspace.services.account.service + ${project.version} + provided + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + + + collectionspace-services-authz-mgt + + diff --git a/services/authorization/.classpath b/services/authorization/.classpath index 046988541..25df93560 100644 --- a/services/authorization/.classpath +++ b/services/authorization/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/authorization/.project b/services/authorization/.project index 53fed1555..142a7d68a 100644 --- a/services/authorization/.project +++ b/services/authorization/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.authorization - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.authorization + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/authorization/build.xml b/services/authorization/build.xml index 3ee6d6dc2..97ea8d2f8 100644 --- a/services/authorization/build.xml +++ b/services/authorization/build.xml @@ -1,138 +1,138 @@ - - - - authorization service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + authorization service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/authorization/jaxb/pom.xml b/services/authorization/jaxb/pom.xml index 049837bbc..845dec84a 100644 --- a/services/authorization/jaxb/pom.xml +++ b/services/authorization/jaxb/pom.xml @@ -1,80 +1,80 @@ - - - - - org.collectionspace.services.authorization - org.collectionspace.services - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.authorization.jaxb - services.authorization.jaxb - - - - - com.sun.xml.bind - jaxb-impl - - - org.jvnet.jaxb2-commons - property-listener-injector - - - javax.persistence - persistence-api - - - org.hibernate - hibernate-entitymanager - - - org.jvnet.hyperjaxb3 - hyperjaxb3-ejb-runtime - - - org.collectionspace.services - org.collectionspace.services.hyperjaxb - ${project.version} - - - - - - collectionspace-services-authorization-jaxb - install - - - org.jvnet.hyperjaxb3 - maven-hyperjaxb3-plugin - - - - - + + + + + org.collectionspace.services.authorization + org.collectionspace.services + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.authorization.jaxb + services.authorization.jaxb + + + + + com.sun.xml.bind + jaxb-impl + + + org.jvnet.jaxb2-commons + property-listener-injector + + + javax.persistence + persistence-api + + + org.hibernate + hibernate-entitymanager + + + org.jvnet.hyperjaxb3 + hyperjaxb3-ejb-runtime + + + org.collectionspace.services + org.collectionspace.services.hyperjaxb + ${project.version} + + + + + + collectionspace-services-authorization-jaxb + install + + + org.jvnet.hyperjaxb3 + maven-hyperjaxb3-plugin + + + + + diff --git a/services/authorization/jaxb/src/main/resources/accounts_permissions.xsd b/services/authorization/jaxb/src/main/resources/accounts_permissions.xsd index 9417bd38c..9617f0827 100644 --- a/services/authorization/jaxb/src/main/resources/accounts_permissions.xsd +++ b/services/authorization/jaxb/src/main/resources/accounts_permissions.xsd @@ -1,45 +1,45 @@ - - - - - - - - - - - - - AccountPermission defines 1-n association between - an account and its corresponding permissions. - - - - - - - - - - - - - - + + + + + + + + + + + + + AccountPermission defines 1-n association between + an account and its corresponding permissions. + + + + + + + + + + + + + + diff --git a/services/authorization/jaxb/src/test/resources/log4j.properties b/services/authorization/jaxb/src/test/resources/log4j.properties index 3aa34b3fc..53720a742 100644 --- a/services/authorization/jaxb/src/test/resources/log4j.properties +++ b/services/authorization/jaxb/src/test/resources/log4j.properties @@ -1,25 +1,25 @@ -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 -log4j.logger.org.jvnet.hyperjaxb3=DEBUG +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 +log4j.logger.org.jvnet.hyperjaxb3=DEBUG log4j.logger.org.hibernate=WARN \ No newline at end of file diff --git a/services/authorization/pstore/build.xml b/services/authorization/pstore/build.xml index 7be651fc9..807f25686 100644 --- a/services/authorization/pstore/build.xml +++ b/services/authorization/pstore/build.xml @@ -1,227 +1,227 @@ - - - collectionspace authorization service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + collectionspace authorization service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/authorization/pstore/pom.xml b/services/authorization/pstore/pom.xml index 3d1fd7764..88d0cdd91 100644 --- a/services/authorization/pstore/pom.xml +++ b/services/authorization/pstore/pom.xml @@ -1,142 +1,142 @@ - - - - - org.collectionspace.services.authorization - org.collectionspace.services - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.authorization.pstore - services.authorization.pstore - - authorization.sql - ${basedir}/src/main/resources/db - - - - org.collectionspace.services - org.collectionspace.services.authorization.jaxb - ${project.version} - - - mysql - mysql-connector-java - - - postgresql - postgresql - - - - - cspace-services-authorization-pstore - - - maven-antrun-plugin - - - subs-hibernate-config - generate-test-resources - - run - - - - - - - - - - - - - - - - ddl - - - - org.codehaus.mojo - properties-maven-plugin - 1.0-alpha-2 - - - initialize - - read-project-properties - - - - ${basedir}/../../../build.properties - - - - - - - org.codehaus.mojo - hibernate3-maven-plugin - 2.2 - - - process-test-resources - - hbm2ddl - - - - - - - hbm2ddl - - - - ${sql.file} - jpaconfiguration - true - true - true - true - false - org.collectionspace.services.authorization - - - - - mysql - mysql-connector-java - - - postgresql - postgresql - - - - - maven-antrun-plugin - - - process-test-resources - - - - - - - run - - - - - - - - - - + + + + + org.collectionspace.services.authorization + org.collectionspace.services + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.authorization.pstore + services.authorization.pstore + + authorization.sql + ${basedir}/src/main/resources/db + + + + org.collectionspace.services + org.collectionspace.services.authorization.jaxb + ${project.version} + + + mysql + mysql-connector-java + + + postgresql + postgresql + + + + + cspace-services-authorization-pstore + + + maven-antrun-plugin + + + subs-hibernate-config + generate-test-resources + + run + + + + + + + + + + + + + + + + ddl + + + + org.codehaus.mojo + properties-maven-plugin + 1.0-alpha-2 + + + initialize + + read-project-properties + + + + ${basedir}/../../../build.properties + + + + + + + org.codehaus.mojo + hibernate3-maven-plugin + 2.2 + + + process-test-resources + + hbm2ddl + + + + + + + hbm2ddl + + + + ${sql.file} + jpaconfiguration + true + true + true + true + false + org.collectionspace.services.authorization + + + + + mysql + mysql-connector-java + + + postgresql + postgresql + + + + + maven-antrun-plugin + + + process-test-resources + + + + + + + run + + + + + + + + + + diff --git a/services/authorization/pstore/src/main/resources/db/postgresql/README.txt b/services/authorization/pstore/src/main/resources/db/postgresql/README.txt index b9cf6f804..fbc2b8919 100644 --- a/services/authorization/pstore/src/main/resources/db/postgresql/README.txt +++ b/services/authorization/pstore/src/main/resources/db/postgresql/README.txt @@ -1,32 +1,32 @@ -The file authorization.sql is basically generated by the gen_ddl ant target. -However, you must modify the result of that to make the - - DROP TABLE - -statements be - - DROP TABLE IF EXISTS table CASCADE - -This ensures that first time setup does not fail, and that later invocations -can deal with dependencies. - -You must also make the - - DROP SEQUENCE - -statements be - - DROP SEQUENCE IF EXISTS - -for similar reasons. - -You must also remove (comment out) the statement (which is superfluous with the CASCADE above): - - alter table permissions_actions drop constraint FK85F82042E2DC84FD; - -When using the account_tenants table on insert, you have to specify "nextval('hibernate_sequence')" -as the value for the HJID column. - -Note that because of the way gen_ddl does its work per-sub-project, there is a single shared -sequence for both this and the authorization.sql script. This should be okay, even if it does -create gaps in what would be a nice sequence for each table. +The file authorization.sql is basically generated by the gen_ddl ant target. +However, you must modify the result of that to make the + + DROP TABLE + +statements be + + DROP TABLE IF EXISTS table CASCADE + +This ensures that first time setup does not fail, and that later invocations +can deal with dependencies. + +You must also make the + + DROP SEQUENCE + +statements be + + DROP SEQUENCE IF EXISTS + +for similar reasons. + +You must also remove (comment out) the statement (which is superfluous with the CASCADE above): + + alter table permissions_actions drop constraint FK85F82042E2DC84FD; + +When using the account_tenants table on insert, you have to specify "nextval('hibernate_sequence')" +as the value for the HJID column. + +Note that because of the way gen_ddl does its work per-sub-project, there is a single shared +sequence for both this and the authorization.sql script. This should be okay, even if it does +create gaps in what would be a nice sequence for each table. diff --git a/services/authorization/service/build.xml b/services/authorization/service/build.xml index d57186612..86b7206ce 100644 --- a/services/authorization/service/build.xml +++ b/services/authorization/service/build.xml @@ -1,132 +1,132 @@ - - - - collectionspace authorization service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + collectionspace authorization service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/authorization/service/src/main/java/org/collectionspace/services/authorization/PermissionActionUtil.java b/services/authorization/service/src/main/java/org/collectionspace/services/authorization/PermissionActionUtil.java index 306e0e10b..bc75b164d 100644 --- a/services/authorization/service/src/main/java/org/collectionspace/services/authorization/PermissionActionUtil.java +++ b/services/authorization/service/src/main/java/org/collectionspace/services/authorization/PermissionActionUtil.java @@ -1,5 +1,5 @@ -package org.collectionspace.services.authorization; - -public class PermissionActionUtil { - -} +package org.collectionspace.services.authorization; + +public class PermissionActionUtil { + +} diff --git a/services/authorization/service/src/test/resources/log4j.properties b/services/authorization/service/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/authorization/service/src/test/resources/log4j.properties +++ b/services/authorization/service/src/test/resources/log4j.properties @@ -1,23 +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 +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/batch/.project b/services/batch/.project index e857f894e..a8deb97b6 100644 --- a/services/batch/.project +++ b/services/batch/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.batch - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.batch + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/batch/3rdparty/.project b/services/batch/3rdparty/.project index 9f043a30b..361dafef6 100644 --- a/services/batch/3rdparty/.project +++ b/services/batch/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.batch.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.batch.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/batch/3rdparty/nuxeo-platform-cs-batch/src/main/resources/META-INF/MANIFEST.MF b/services/batch/3rdparty/nuxeo-platform-cs-batch/src/main/resources/META-INF/MANIFEST.MF index d05375dbd..ef5f42081 100644 --- a/services/batch/3rdparty/nuxeo-platform-cs-batch/src/main/resources/META-INF/MANIFEST.MF +++ b/services/batch/3rdparty/nuxeo-platform-cs-batch/src/main/resources/META-INF/MANIFEST.MF @@ -1,23 +1,23 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 1 -Bundle-Name: NuxeoCS -Bundle-SymbolicName: org.collectionspace.batch;singleton:=true -Bundle-Version: 1.0.0 -Bundle-Localization: plugin -Bundle-Vendor: Nuxeo -Require-Bundle: org.nuxeo.runtime, - org.nuxeo.ecm.core.api, - org.nuxeo.ecm.core, - org.nuxeo.ecm.core.api, - org.nuxeo.ecm.platform.types.api, - org.nuxeo.ecm.platform.versioning.api, - org.nuxeo.ecm.platform.ui, - org.nuxeo.ecm.platform.forms.layout.client, - org.nuxeo.ecm.platform.ws, - org.collectionspace.collectionspace_core -Provide-Package: org.collectionspace.batch -Nuxeo-Component: OSGI-INF/core-types-contrib.xml, - OSGI-INF/life-cycle-contrib.xml, - OSGI-INF/ecm-types-contrib.xml, - OSGI-INF/layouts-contrib.xml - +Manifest-Version: 1.0 +Bundle-ManifestVersion: 1 +Bundle-Name: NuxeoCS +Bundle-SymbolicName: org.collectionspace.batch;singleton:=true +Bundle-Version: 1.0.0 +Bundle-Localization: plugin +Bundle-Vendor: Nuxeo +Require-Bundle: org.nuxeo.runtime, + org.nuxeo.ecm.core.api, + org.nuxeo.ecm.core, + org.nuxeo.ecm.core.api, + org.nuxeo.ecm.platform.types.api, + org.nuxeo.ecm.platform.versioning.api, + org.nuxeo.ecm.platform.ui, + org.nuxeo.ecm.platform.forms.layout.client, + org.nuxeo.ecm.platform.ws, + org.collectionspace.collectionspace_core +Provide-Package: org.collectionspace.batch +Nuxeo-Component: OSGI-INF/core-types-contrib.xml, + OSGI-INF/life-cycle-contrib.xml, + OSGI-INF/ecm-types-contrib.xml, + OSGI-INF/layouts-contrib.xml + diff --git a/services/batch/3rdparty/nuxeo-platform-cs-batch/src/main/resources/schemas/batch_common.xsd b/services/batch/3rdparty/nuxeo-platform-cs-batch/src/main/resources/schemas/batch_common.xsd index 2b0b5e44d..0b670e4e2 100644 --- a/services/batch/3rdparty/nuxeo-platform-cs-batch/src/main/resources/schemas/batch_common.xsd +++ b/services/batch/3rdparty/nuxeo-platform-cs-batch/src/main/resources/schemas/batch_common.xsd @@ -1,41 +1,41 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/batch/client/src/test/resources/log4j.properties b/services/batch/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/batch/client/src/test/resources/log4j.properties +++ b/services/batch/client/src/test/resources/log4j.properties @@ -1,23 +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 +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/batch/service/src/main/java/org/collectionspace/services/batch/BatchInvocable.java b/services/batch/service/src/main/java/org/collectionspace/services/batch/BatchInvocable.java index 01274ea20..5275e58e3 100644 --- a/services/batch/service/src/main/java/org/collectionspace/services/batch/BatchInvocable.java +++ b/services/batch/service/src/main/java/org/collectionspace/services/batch/BatchInvocable.java @@ -1,18 +1,18 @@ -package org.collectionspace.services.batch; - -import java.util.HashMap; -import java.util.Set; - -import org.collectionspace.services.common.ResourceBase; -import org.collectionspace.services.common.ResourceMap; -import org.collectionspace.services.common.invocable.Invocable; - -public interface BatchInvocable extends Invocable { - - /** - * Sets the invocation context for the batch job. Called before run(). - * @param context an instance of InvocationContext. - */ - public void setResourceMap(ResourceMap resourceMap); - -} +package org.collectionspace.services.batch; + +import java.util.HashMap; +import java.util.Set; + +import org.collectionspace.services.common.ResourceBase; +import org.collectionspace.services.common.ResourceMap; +import org.collectionspace.services.common.invocable.Invocable; + +public interface BatchInvocable extends Invocable { + + /** + * Sets the invocation context for the batch job. Called before run(). + * @param context an instance of InvocationContext. + */ + public void setResourceMap(ResourceMap resourceMap); + +} diff --git a/services/blob/.project b/services/blob/.project index 2cb6d0902..316c54e48 100644 --- a/services/blob/.project +++ b/services/blob/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.blob - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.blob + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/blob/3rdparty/.project b/services/blob/3rdparty/.project index 5ca2f2bb0..32f0563ad 100644 --- a/services/blob/3rdparty/.project +++ b/services/blob/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.blob.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.blob.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/blob/client/src/test/java/org/collectionspace/services/client/test/BlobScaleTest.java b/services/blob/client/src/test/java/org/collectionspace/services/client/test/BlobScaleTest.java index 557b59c69..6a9c95d3e 100644 --- a/services/blob/client/src/test/java/org/collectionspace/services/client/test/BlobScaleTest.java +++ b/services/blob/client/src/test/java/org/collectionspace/services/client/test/BlobScaleTest.java @@ -1,169 +1,169 @@ -package org.collectionspace.services.client.test; - -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Random; - -import javax.imageio.ImageIO; -import javax.ws.rs.core.Response; - -import org.collectionspace.services.client.BlobClient; -import org.collectionspace.services.client.CollectionSpaceClient; -import org.collectionspace.services.client.Profiler; -import org.collectionspace.services.jaxb.AbstractCommonList; -import org.jboss.resteasy.client.ClientResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.annotations.Test; - -public class BlobScaleTest extends BaseServiceTest { - - private final Logger logger = LoggerFactory.getLogger(BlobScaleTest.class); - - private static final int IMAGE_SIZE = 1000; - private static final int IMAGE_EDGE = -15; - private static final int MIN_FONTSIZE = 15; - private static final int MAX_FONTSIZE = 60; - private static final String IMAGES_TO_CREATE_PROP = "imagesToCreate"; - private static final int DEFAULT_IMAGES_TO_CREATE = 1; - private static final int DEFAULT_IMAGES_TO_GET = 12; //1024; - private static final String GENERATED_IMAGES = "target/generated_images"; - - private static Random generator = new Random(System.currentTimeMillis()); - - @Override - protected CollectionSpaceClient getClientInstance() { - return new BlobClient(); - } - - @Override - protected String getServicePathComponent() { - return BlobClient.SERVICE_PATH_COMPONENT; - } - - @Override - protected String getServiceName() { - return BlobClient.SERVICE_NAME; - } - - private int getImagesToCreate() { - int result = DEFAULT_IMAGES_TO_CREATE; - - String imagesToCreate = System.getProperty(IMAGES_TO_CREATE_PROP); - try { - result = Integer.parseInt(imagesToCreate); - } catch (NumberFormatException np) { - logger.info("No value (or a bad value) for system property '" - + IMAGES_TO_CREATE_PROP - + "' was defined, so we'll use the default instead."); - } finally { - logger.info("Testing blob scaling by creating " - + result - + " images."); - } - - return result; - } - - @Test(dataProvider = "testName", dependsOnMethods = {"scaleTest"}) - public void scaleGETTest(String testName) throws MalformedURLException { - this.setupRead(); - String blobToGetID = getKnowResourceId(); - BlobClient client = new BlobClient(); - - for (int i = 0; i < DEFAULT_IMAGES_TO_GET; i++) { - ClientResponse res = client.getDerivativeContent(blobToGetID, "Thumbnail"); - assertStatusCode(res, testName); - } - - logger.debug(String.format("Performed %d GET operations on blob = %s.", - DEFAULT_IMAGES_TO_GET, blobToGetID)); - } - - @Test(dataProvider = "testName") - public void scaleTest(String testName) throws MalformedURLException { - this.createDirectory(GENERATED_IMAGES); - setupCreate(); - int imagesToCreate = getImagesToCreate(); - BlobClient client = new BlobClient(); - Profiler profiler = new Profiler(this, 1); - - for (int i = 0; i < imagesToCreate; i++, profiler.reset()) { - File jpegFile = createJpeg(GENERATED_IMAGES); - URL url = jpegFile.toURI().toURL(); - - profiler.start(); - ClientResponse res = client.createBlobFromURI("http://farm6.static.flickr.com/5289/5688023100_15e00cde47_o.jpg");//url.toString()); - try { - profiler.stop(); - assertStatusCode(res, testName); - - logger.debug( - i + ": Uploaded image to Nuxeo in " - + profiler.getCumulativeTime() - + " milleseconds " - + " - " - + " : " - + jpegFile.getAbsolutePath()); - - String csid = extractId(res); - this.knownResourceId = csid; - allResourceIdsCreated.add(csid); - } finally { - if (res != null) { - res.releaseConnection(); - } - } - } - } - - private void createDirectory(String dirName) { - boolean success = ( - new File(dirName)).mkdir(); - if (success) { - logger.debug("Directory: " - + dirName + " created"); - } - } - - public File createJpeg(String destDir) { - File result = null; - - BufferedImage image = new BufferedImage(IMAGE_SIZE, IMAGE_SIZE, BufferedImage.TYPE_INT_RGB); - Graphics g = image.getGraphics(); - for (int i = 0; i < IMAGE_SIZE; i = i + 10) { - int x = random(IMAGE_EDGE, IMAGE_SIZE); - int y = random(IMAGE_EDGE, IMAGE_SIZE); - g.drawString(Integer.toString(random(-123456789, 123456789)), x, y); - Color c = new Color(random(0, 255), random(0, 255), random(0, 255)); - g.setColor(c); - - Font currentFont = g.getFont(); - Font newFont = new Font(currentFont.getFontName(), currentFont.getStyle(), - random(MIN_FONTSIZE, MAX_FONTSIZE)); - g.setFont(newFont); - } - try { - ImageIO.write(image, "jpg", result = new File(destDir - + File.separator - + System.currentTimeMillis() - + ".jpg")); - } catch (IOException e) { - e.printStackTrace(); - } - - return result; - } - - public int random(int min, int max) { - return min + (int)(generator.nextFloat() * ((max - min) + 1)); - } - - -} +package org.collectionspace.services.client.test; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Random; + +import javax.imageio.ImageIO; +import javax.ws.rs.core.Response; + +import org.collectionspace.services.client.BlobClient; +import org.collectionspace.services.client.CollectionSpaceClient; +import org.collectionspace.services.client.Profiler; +import org.collectionspace.services.jaxb.AbstractCommonList; +import org.jboss.resteasy.client.ClientResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.annotations.Test; + +public class BlobScaleTest extends BaseServiceTest { + + private final Logger logger = LoggerFactory.getLogger(BlobScaleTest.class); + + private static final int IMAGE_SIZE = 1000; + private static final int IMAGE_EDGE = -15; + private static final int MIN_FONTSIZE = 15; + private static final int MAX_FONTSIZE = 60; + private static final String IMAGES_TO_CREATE_PROP = "imagesToCreate"; + private static final int DEFAULT_IMAGES_TO_CREATE = 1; + private static final int DEFAULT_IMAGES_TO_GET = 12; //1024; + private static final String GENERATED_IMAGES = "target/generated_images"; + + private static Random generator = new Random(System.currentTimeMillis()); + + @Override + protected CollectionSpaceClient getClientInstance() { + return new BlobClient(); + } + + @Override + protected String getServicePathComponent() { + return BlobClient.SERVICE_PATH_COMPONENT; + } + + @Override + protected String getServiceName() { + return BlobClient.SERVICE_NAME; + } + + private int getImagesToCreate() { + int result = DEFAULT_IMAGES_TO_CREATE; + + String imagesToCreate = System.getProperty(IMAGES_TO_CREATE_PROP); + try { + result = Integer.parseInt(imagesToCreate); + } catch (NumberFormatException np) { + logger.info("No value (or a bad value) for system property '" + + IMAGES_TO_CREATE_PROP + + "' was defined, so we'll use the default instead."); + } finally { + logger.info("Testing blob scaling by creating " + + result + + " images."); + } + + return result; + } + + @Test(dataProvider = "testName", dependsOnMethods = {"scaleTest"}) + public void scaleGETTest(String testName) throws MalformedURLException { + this.setupRead(); + String blobToGetID = getKnowResourceId(); + BlobClient client = new BlobClient(); + + for (int i = 0; i < DEFAULT_IMAGES_TO_GET; i++) { + ClientResponse res = client.getDerivativeContent(blobToGetID, "Thumbnail"); + assertStatusCode(res, testName); + } + + logger.debug(String.format("Performed %d GET operations on blob = %s.", + DEFAULT_IMAGES_TO_GET, blobToGetID)); + } + + @Test(dataProvider = "testName") + public void scaleTest(String testName) throws MalformedURLException { + this.createDirectory(GENERATED_IMAGES); + setupCreate(); + int imagesToCreate = getImagesToCreate(); + BlobClient client = new BlobClient(); + Profiler profiler = new Profiler(this, 1); + + for (int i = 0; i < imagesToCreate; i++, profiler.reset()) { + File jpegFile = createJpeg(GENERATED_IMAGES); + URL url = jpegFile.toURI().toURL(); + + profiler.start(); + ClientResponse res = client.createBlobFromURI("http://farm6.static.flickr.com/5289/5688023100_15e00cde47_o.jpg");//url.toString()); + try { + profiler.stop(); + assertStatusCode(res, testName); + + logger.debug( + i + ": Uploaded image to Nuxeo in " + + profiler.getCumulativeTime() + + " milleseconds " + + " - " + + " : " + + jpegFile.getAbsolutePath()); + + String csid = extractId(res); + this.knownResourceId = csid; + allResourceIdsCreated.add(csid); + } finally { + if (res != null) { + res.releaseConnection(); + } + } + } + } + + private void createDirectory(String dirName) { + boolean success = ( + new File(dirName)).mkdir(); + if (success) { + logger.debug("Directory: " + + dirName + " created"); + } + } + + public File createJpeg(String destDir) { + File result = null; + + BufferedImage image = new BufferedImage(IMAGE_SIZE, IMAGE_SIZE, BufferedImage.TYPE_INT_RGB); + Graphics g = image.getGraphics(); + for (int i = 0; i < IMAGE_SIZE; i = i + 10) { + int x = random(IMAGE_EDGE, IMAGE_SIZE); + int y = random(IMAGE_EDGE, IMAGE_SIZE); + g.drawString(Integer.toString(random(-123456789, 123456789)), x, y); + Color c = new Color(random(0, 255), random(0, 255), random(0, 255)); + g.setColor(c); + + Font currentFont = g.getFont(); + Font newFont = new Font(currentFont.getFontName(), currentFont.getStyle(), + random(MIN_FONTSIZE, MAX_FONTSIZE)); + g.setFont(newFont); + } + try { + ImageIO.write(image, "jpg", result = new File(destDir + + File.separator + + System.currentTimeMillis() + + ".jpg")); + } catch (IOException e) { + e.printStackTrace(); + } + + return result; + } + + public int random(int min, int max) { + return min + (int)(generator.nextFloat() * ((max - min) + 1)); + } + + +} diff --git a/services/blob/client/src/test/resources/log4j.properties b/services/blob/client/src/test/resources/log4j.properties index 5b4e490b6..be32f185c 100644 --- a/services/blob/client/src/test/resources/log4j.properties +++ b/services/blob/client/src/test/resources/log4j.properties @@ -1,25 +1,25 @@ -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.perf.collectionspace=TRACE - -log4j.logger.org.apache=INFO -log4j.logger.httpclient=INFO -log4j.logger.org.jboss.resteasy=INFO +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.perf.collectionspace=TRACE + +log4j.logger.org.apache=INFO +log4j.logger.httpclient=INFO +log4j.logger.org.jboss.resteasy=INFO diff --git a/services/blob/jaxb/.classpath b/services/blob/jaxb/.classpath index 1674079c1..ec5d6c258 100644 --- a/services/blob/jaxb/.classpath +++ b/services/blob/jaxb/.classpath @@ -1,31 +1,31 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/services/build.xml b/services/build.xml index e8f3befcb..5078e9d49 100644 --- a/services/build.xml +++ b/services/build.xml @@ -1,348 +1,348 @@ - - - collectionspace services main - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + collectionspace services main + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/citation/.classpath b/services/citation/.classpath index d18316afc..2068e34f3 100644 --- a/services/citation/.classpath +++ b/services/citation/.classpath @@ -1,5 +1,5 @@ - - - - - + + + + + diff --git a/services/citation/.project b/services/citation/.project index 0d6e32b7d..788c80f37 100644 --- a/services/citation/.project +++ b/services/citation/.project @@ -1,29 +1,29 @@ - - - org.collectionspace.services.citation - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - org.eclipse.jdt.core.javanature - org.maven.ide.eclipse.maven2Nature - - + + + org.collectionspace.services.citation + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.maven.ide.eclipse.maven2Builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.jdt.core.javanature + org.maven.ide.eclipse.maven2Nature + + diff --git a/services/citation/3rdparty/.classpath b/services/citation/3rdparty/.classpath index d18316afc..2068e34f3 100644 --- a/services/citation/3rdparty/.classpath +++ b/services/citation/3rdparty/.classpath @@ -1,5 +1,5 @@ - - - - - + + + + + diff --git a/services/citation/3rdparty/.project b/services/citation/3rdparty/.project index 6f2a74af4..32ddd40d4 100644 --- a/services/citation/3rdparty/.project +++ b/services/citation/3rdparty/.project @@ -1,29 +1,29 @@ - - - org.collectionspace.services.citation.3rdparty - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.maven.ide.eclipse.maven2Builder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - org.eclipse.jdt.core.javanature - org.maven.ide.eclipse.maven2Nature - - + + + org.collectionspace.services.citation.3rdparty + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.maven.ide.eclipse.maven2Builder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + org.eclipse.jdt.core.javanature + org.maven.ide.eclipse.maven2Nature + + diff --git a/services/citation/jaxb/src/main/java/org/collectionspace/services/CitationJAXBSchema.java b/services/citation/jaxb/src/main/java/org/collectionspace/services/CitationJAXBSchema.java index fb5453bc2..223a9a2f5 100644 --- a/services/citation/jaxb/src/main/java/org/collectionspace/services/CitationJAXBSchema.java +++ b/services/citation/jaxb/src/main/java/org/collectionspace/services/CitationJAXBSchema.java @@ -1,14 +1,14 @@ -/** - * - */ -package org.collectionspace.services; -import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema; - -/** - * @author pschmitz - * - */ -public interface CitationJAXBSchema extends AuthorityItemJAXBSchema { - final static String CITATIONS_COMMON = "citations_common"; -} - +/** + * + */ +package org.collectionspace.services; +import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema; + +/** + * @author pschmitz + * + */ +public interface CitationJAXBSchema extends AuthorityItemJAXBSchema { + final static String CITATIONS_COMMON = "citations_common"; +} + diff --git a/services/client/pom.xml b/services/client/pom.xml index d59201497..edfdc6365 100644 --- a/services/client/pom.xml +++ b/services/client/pom.xml @@ -1,120 +1,120 @@ - - - - org.collectionspace.services - org.collectionspace.services.main - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.client - services.client - jar - - - - org.slf4j - slf4j-api - provided - - - org.slf4j - slf4j-log4j12 - provided - - - - - - org.collectionspace.services - org.collectionspace.services.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.common-api - ${project.version} - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.4.3 - test - - - commons-io - commons-io - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - jaxrs-api - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - - org.testng - testng - compile - - - - - javax.security - jaas - 1.0.01 - provided - - - com.sun.xml.bind - jaxb-impl - 2.2.2 - jar - compile - - - dom4j - dom4j - 1.6.1 - provided - - - - - collectionspace-services-client - - - org.apache.maven.plugins - maven-jar-plugin - - - - test-jar - - - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.main + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.client + services.client + jar + + + + org.slf4j + slf4j-api + provided + + + org.slf4j + slf4j-log4j12 + provided + + + + + + org.collectionspace.services + org.collectionspace.services.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.common-api + ${project.version} + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.4.3 + test + + + commons-io + commons-io + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + jaxrs-api + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + + org.testng + testng + compile + + + + + javax.security + jaas + 1.0.01 + provided + + + com.sun.xml.bind + jaxb-impl + 2.2.2 + jar + compile + + + dom4j + dom4j + 1.6.1 + provided + + + + + collectionspace-services-client + + + org.apache.maven.plugins + maven-jar-plugin + + + + test-jar + + + + + + + + diff --git a/services/client/src/main/java/org/collectionspace/services/client/AbstractCommonListPoxServiceClientImpl.java b/services/client/src/main/java/org/collectionspace/services/client/AbstractCommonListPoxServiceClientImpl.java index 22cae7501..e62fe58ea 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/AbstractCommonListPoxServiceClientImpl.java +++ b/services/client/src/main/java/org/collectionspace/services/client/AbstractCommonListPoxServiceClientImpl.java @@ -1,18 +1,18 @@ -package org.collectionspace.services.client; - -import org.collectionspace.services.jaxb.AbstractCommonList; - -/** - * - * @author remillet - * - * All clients returning AbstractCommonList types should extend this class. - * - * @param

- */ -public abstract class AbstractCommonListPoxServiceClientImpl

- extends AbstractPoxServiceClientImpl { - // - // All clients returning AbstractCommonList types should extend this class. - // -} +package org.collectionspace.services.client; + +import org.collectionspace.services.jaxb.AbstractCommonList; + +/** + * + * @author remillet + * + * All clients returning AbstractCommonList types should extend this class. + * + * @param

+ */ +public abstract class AbstractCommonListPoxServiceClientImpl

+ extends AbstractPoxServiceClientImpl { + // + // All clients returning AbstractCommonList types should extend this class. + // +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/AbstractCommonListUtils.java b/services/client/src/main/java/org/collectionspace/services/client/AbstractCommonListUtils.java index 22866cccc..1741033bd 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/AbstractCommonListUtils.java +++ b/services/client/src/main/java/org/collectionspace/services/client/AbstractCommonListUtils.java @@ -1,46 +1,46 @@ -package org.collectionspace.services.client; - -import java.util.List; - -import org.collectionspace.services.jaxb.AbstractCommonList; -import org.slf4j.Logger; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -public class AbstractCommonListUtils { - public static void ListItemsInAbstractCommonList( - AbstractCommonList list, Logger logger, String testName) { - List items = - list.getListItem(); - int i = 0; - for(AbstractCommonList.ListItem item : items){ - List elList = item.getAny(); - StringBuilder elementStrings = new StringBuilder(); - for(Element el : elList) { - Node textEl = el.getFirstChild(); - elementStrings.append("["+el.getNodeName()+":"+((textEl!=null)?textEl.getNodeValue():"NULL")+"] "); - } - logger.debug(testName + ": list-item[" + i + "]: "+elementStrings.toString()); - i++; - } - } - - public static String ListItemGetCSID(AbstractCommonList.ListItem item) { - return ListItemGetElementValue(item, "csid"); - } - - public static String ListItemGetElementValue(AbstractCommonList.ListItem item, - String elName) { - List elList = item.getAny(); - for(Element el : elList) { - if(elName.equalsIgnoreCase(el.getNodeName())) { - Node textEl = el.getFirstChild(); - return textEl.getNodeValue(); - } - } - return null; - } - - - -} +package org.collectionspace.services.client; + +import java.util.List; + +import org.collectionspace.services.jaxb.AbstractCommonList; +import org.slf4j.Logger; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +public class AbstractCommonListUtils { + public static void ListItemsInAbstractCommonList( + AbstractCommonList list, Logger logger, String testName) { + List items = + list.getListItem(); + int i = 0; + for(AbstractCommonList.ListItem item : items){ + List elList = item.getAny(); + StringBuilder elementStrings = new StringBuilder(); + for(Element el : elList) { + Node textEl = el.getFirstChild(); + elementStrings.append("["+el.getNodeName()+":"+((textEl!=null)?textEl.getNodeValue():"NULL")+"] "); + } + logger.debug(testName + ": list-item[" + i + "]: "+elementStrings.toString()); + i++; + } + } + + public static String ListItemGetCSID(AbstractCommonList.ListItem item) { + return ListItemGetElementValue(item, "csid"); + } + + public static String ListItemGetElementValue(AbstractCommonList.ListItem item, + String elName) { + List elList = item.getAny(); + for(Element el : elList) { + if(elName.equalsIgnoreCase(el.getNodeName())) { + Node textEl = el.getFirstChild(); + return textEl.getNodeValue(); + } + } + return null; + } + + + +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/AbstractPoxServiceClientImpl.java b/services/client/src/main/java/org/collectionspace/services/client/AbstractPoxServiceClientImpl.java index 56ad16593..b326a2cfb 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/AbstractPoxServiceClientImpl.java +++ b/services/client/src/main/java/org/collectionspace/services/client/AbstractPoxServiceClientImpl.java @@ -1,60 +1,60 @@ -package org.collectionspace.services.client; - -import javax.ws.rs.core.Response; -import org.jboss.resteasy.client.ClientResponse; - -import org.collectionspace.services.jaxb.AbstractCommonList; - -/* - * CLT = List type - * P = Proxy type - */ -public abstract class AbstractPoxServiceClientImpl> - extends AbstractServiceClientImpl - implements CollectionSpacePoxClient { - - @Override - public ClientResponse create(PoxPayloadOut xmlPayload) { - return getProxy().create(xmlPayload.getBytes()); - } - - @Override - public ClientResponse read(String csid) { - return getProxy().read(csid); - } - - public ClientResponse readList() { - CollectionSpaceProxy proxy = (CollectionSpaceProxy)getProxy(); - return proxy.readList(); - } - - @Override - public ClientResponse readIncludeDeleted(Boolean includeDeleted) { - CollectionSpacePoxProxy proxy = getProxy(); - return proxy.readIncludeDeleted(includeDeleted.toString()); - } - - @Override - public ClientResponse readIncludeDeleted(String csid, Boolean includeDeleted) { - return getProxy().readIncludeDeleted(csid, includeDeleted.toString()); - } - - @Override - public ClientResponse update(String csid, PoxPayloadOut xmlPayload) { - return getProxy().update(csid, xmlPayload.getBytes()); - } - - - @Override - public ClientResponse keywordSearchIncludeDeleted(String keywords, Boolean includeDeleted) { - CollectionSpacePoxProxy proxy = getProxy(); - return proxy.keywordSearchIncludeDeleted(keywords, includeDeleted.toString()); - } - - @Override - public ClientResponse advancedSearchIncludeDeleted(String whereClause, Boolean includeDeleted) { - CollectionSpacePoxProxy proxy = getProxy(); - return proxy.advancedSearchIncludeDeleted(whereClause, includeDeleted.toString()); - } - -} +package org.collectionspace.services.client; + +import javax.ws.rs.core.Response; +import org.jboss.resteasy.client.ClientResponse; + +import org.collectionspace.services.jaxb.AbstractCommonList; + +/* + * CLT = List type + * P = Proxy type + */ +public abstract class AbstractPoxServiceClientImpl> + extends AbstractServiceClientImpl + implements CollectionSpacePoxClient { + + @Override + public ClientResponse create(PoxPayloadOut xmlPayload) { + return getProxy().create(xmlPayload.getBytes()); + } + + @Override + public ClientResponse read(String csid) { + return getProxy().read(csid); + } + + public ClientResponse readList() { + CollectionSpaceProxy proxy = (CollectionSpaceProxy)getProxy(); + return proxy.readList(); + } + + @Override + public ClientResponse readIncludeDeleted(Boolean includeDeleted) { + CollectionSpacePoxProxy proxy = getProxy(); + return proxy.readIncludeDeleted(includeDeleted.toString()); + } + + @Override + public ClientResponse readIncludeDeleted(String csid, Boolean includeDeleted) { + return getProxy().readIncludeDeleted(csid, includeDeleted.toString()); + } + + @Override + public ClientResponse update(String csid, PoxPayloadOut xmlPayload) { + return getProxy().update(csid, xmlPayload.getBytes()); + } + + + @Override + public ClientResponse keywordSearchIncludeDeleted(String keywords, Boolean includeDeleted) { + CollectionSpacePoxProxy proxy = getProxy(); + return proxy.keywordSearchIncludeDeleted(keywords, includeDeleted.toString()); + } + + @Override + public ClientResponse advancedSearchIncludeDeleted(String whereClause, Boolean includeDeleted) { + CollectionSpacePoxProxy proxy = getProxy(); + return proxy.advancedSearchIncludeDeleted(whereClause, includeDeleted.toString()); + } + +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/AbstractServiceClientImpl.java b/services/client/src/main/java/org/collectionspace/services/client/AbstractServiceClientImpl.java index 377fb551a..b9102852f 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/AbstractServiceClientImpl.java +++ b/services/client/src/main/java/org/collectionspace/services/client/AbstractServiceClientImpl.java @@ -1,469 +1,469 @@ -/** - * 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.client; - -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.net.URL; -import java.util.Properties; - -import javax.ws.rs.PathParam; -import javax.ws.rs.core.Response; - -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.UsernamePasswordCredentials; -import org.apache.commons.httpclient.auth.AuthScope; //import org.collectionspace.services.collectionobject.CollectionobjectsCommonList; - -import org.collectionspace.services.common.authorityref.AuthorityRefList; -import org.collectionspace.services.jaxb.AbstractCommonList; - -import org.jboss.resteasy.client.ClientResponse; //import org.collectionspace.services.common.context.ServiceContext; -import org.jboss.resteasy.client.ProxyFactory; -import org.jboss.resteasy.client.core.executors.ApacheHttpClientExecutor; -import org.jboss.resteasy.plugins.providers.RegisterBuiltin; -import org.jboss.resteasy.spi.ResteasyProviderFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * BaseServiceClient is an abstract base client of all service clients FIXME: - * http://issues.collectionspace.org/browse/CSPACE-1684 - * @param - * @param - * - * CLT - List type - * REQUEST_PT - Request payload type - * RESPONSE_PT - Response payload type - * P - Proxy type - */ -public abstract class AbstractServiceClientImpl> - implements CollectionSpaceClient { - - /** The logger. */ - protected final Logger logger = LoggerFactory.getLogger(AbstractServiceClientImpl.class); - /** - * The character used to separate the words in a part label - */ - public static final String PART_LABEL_SEPARATOR = "_"; - /** The Constant PART_COMMON_LABEL. */ - public static final String PART_COMMON_LABEL = "common"; - /** The properties. */ - private Properties properties = new Properties(); - /** The url. */ - private URL url; - /** The http client. */ - private HttpClient httpClient; - /** The RESTEasy proxy */ - private P proxy; - - /** - * Gets the logger. - * - * @return the logger - */ - public Logger getLogger() { - return logger; - } - - abstract public String getServicePathComponent(); - - /** - * Returns a UTF-8 encode byte array from 'string' - * - * @return UTF-8 encoded byte array - */ - protected byte[] getBytes(String string) { - byte[] result = null; - try { - result = string.getBytes("UTF8"); - } catch (UnsupportedEncodingException e) { - if (logger.isWarnEnabled() == true) { - logger.warn(e.getMessage(), e); - } - } - return result; - } - - /* - * Subclasses can override this method to return their AbstractCommonList subclass - */ - protected Class getCommonListType() { - return (Class) AbstractCommonList.class; - } - - /** - * Gets the common part name. - * - * @return the common part name - */ - @Override - public String getCommonPartName() { - return getCommonPartName(getServiceName()); - } - - /** - * Gets the common part name. - * - * @param servicePathComponent - * the service path component - * @return the common part name - */ - protected String getCommonPartName(String commonPrefix) { - return commonPrefix + PART_LABEL_SEPARATOR + PART_COMMON_LABEL; - } - -// /** -// * Gets the service path component. -// * -// * @return the service path component -// */ -// abstract public String getServicePathComponent(); - - /** - * Instantiates a new abstract service client impl. - */ - protected AbstractServiceClientImpl() { - readProperties(); - setupHttpClient(); - ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance(); - RegisterBuiltin.register(factory); - setProxy(); - } - - /* - * (non-Javadoc) - * - * @see - * org.collectionspace.services.client.CollectionSpaceClient#getProperty - * (java.lang.String) - */ - @Override - public String getProperty(String propName) { - return properties.getProperty(propName); - } - - /* - * (non-Javadoc) - * - * @see - * org.collectionspace.services.client.CollectionSpaceClient#setProperty - * (java.lang.String, java.lang.String) - */ - @Override - public void setProperty(String propName, String value) { - properties.setProperty(propName, value); - } - - /* - * (non-Javadoc) - * - * @see - * org.collectionspace.services.client.CollectionSpaceClient#removeProperty - * (java.lang.String) - */ - @Override - public Object removeProperty(String propName) { - return properties.remove(propName); - } - - /** - * Prints the properties. - */ - public void printProperties() { - for (Object kobj : properties.keySet()) { - String key = (String) kobj; - logger.trace("begin property name=" + key + " value=" - + properties.get(key)); - } - } - - /* - * (non-Javadoc) - * - * @see - * org.collectionspace.services.client.CollectionSpaceClient#getBaseURL() - */ - @Override - public String getBaseURL() { - return properties.getProperty(URL_PROPERTY); - } - - /* - * (non-Javadoc) - * - * @see - * org.collectionspace.services.client.CollectionSpaceClient#getHttpClient() - */ - @Override - public HttpClient getHttpClient() { - return httpClient; - } - - /* - * (non-Javadoc) - * - * @see org.collectionspace.services.client.CollectionSpaceClient#useAuth() - */ - @Override - public boolean useAuth() { - String auth = properties.getProperty(AUTH_PROPERTY); - return Boolean.valueOf(auth); - } - - /* - * (non-Javadoc) - * - * @see org.collectionspace.services.client.CollectionSpaceClient#useSSL() - */ - @Override - public boolean useSSL() { - String ssl = properties.getProperty(SSL_PROPERTY); - return Boolean.valueOf(ssl); - } - - /** - * readProperties reads properties from system class path as well as it - * overrides properties made available using command line - * - * @exception RuntimeException - */ - private void readProperties() { - - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - InputStream is = null; - try { - is = cl.getResourceAsStream("collectionspace-client.properties"); - properties.load(is); - if (logger.isDebugEnabled()) { - printProperties(); - } - String spec = System.getProperty(URL_PROPERTY); - if (spec != null && !"".equals(spec)) { - properties.setProperty(URL_PROPERTY, spec); - } - - spec = properties.getProperty(URL_PROPERTY); - url = new URL(spec); - logger.debug("readProperties() using url=" + url); - - String auth = System.getProperty(AUTH_PROPERTY); - if (auth != null && !"".equals(auth)) { - properties.setProperty(AUTH_PROPERTY, auth); - } - String ssl = System.getProperty(SSL_PROPERTY); - if (ssl != null && !"".equals(ssl)) { - properties.setProperty(AUTH_PROPERTY, ssl); - } - String user = System.getProperty(USER_PROPERTY); - if (user != null && !"".equals(user)) { - properties.setProperty(USER_PROPERTY, user); - } - String password = System.getProperty(PASSWORD_PROPERTY); - if (password != null && !"".equals(password)) { - properties.setProperty(PASSWORD_PROPERTY, password); - } - String tenant = System.getProperty(TENANT_PROPERTY); - if (tenant != null && !"".equals(tenant)) { - properties.setProperty(TENANT_PROPERTY, tenant); - } - if (logger.isDebugEnabled()) { - printProperties(); - } - } catch (Exception e) { - logger.debug("Caught exception while reading properties", e); - throw new RuntimeException(e); - } finally { - if (is != null) { - try { - is.close(); - } catch (Exception e) { - if (logger.isDebugEnabled() == true) { - e.printStackTrace(); - } - } - } - } - } - - /** - * setupHttpClient sets up HTTP client for the service client the setup - * process relies on the following properties URL_PROPERTY USER_PROPERTY - * PASSWORD_PROPERTY AUTH_PROPERTY SSL_PROPERTY - */ - @Override - public void setupHttpClient() { - try { - this.httpClient = new HttpClient(); - if (useAuth()) { - String user = properties.getProperty(USER_PROPERTY); - String password = properties.getProperty(PASSWORD_PROPERTY); - if (logger.isDebugEnabled()) { - logger.debug("setupHttpClient() using url=" + url + " user=" - + user + " password=" + password); - } - - httpClient.getState().setCredentials( - new AuthScope(url.getHost(), url.getPort(), - AuthScope.ANY_REALM), - new UsernamePasswordCredentials(user, password)); - // JAXRS client library requires HTTP preemptive authentication - httpClient.getParams().setAuthenticationPreemptive(true); - if (logger.isDebugEnabled()) { - logger.debug("setupHttpClient: set preemptive authentication"); - } - } else { - if (logger.isDebugEnabled()) { - logger.debug("setupHttpClient() : no auth mode!"); - } - } - } catch (Throwable e) { - e.printStackTrace(); - } - } - - /* - * (non-Javadoc) - * - * @see - * org.collectionspace.services.client.CollectionSpaceClient#isServerSecure - * () - */ - @Override - public boolean isServerSecure() { - return Boolean.getBoolean("cspace.server.secure"); - } - - @Override - public P getProxy() { - return proxy; - } - - /** - * allow to reset proxy as per security needs - */ - @Override - public void setProxy() { - Class

proxyClass = this.getProxyClass(); - if (useAuth()) { - proxy = ProxyFactory.create(proxyClass, - getBaseURL(), new ApacheHttpClientExecutor(getHttpClient())); - } else { - proxy = ProxyFactory.create(proxyClass, - getBaseURL()); - } - } - - @Override - public void setAuth(boolean useAuth, - String user, boolean useUser, - String password, boolean usePassword) { - if (useAuth == true) { - setProperty(CollectionSpaceClient.AUTH_PROPERTY, "true"); - if (useUser) { - setProperty(CollectionSpaceClient.USER_PROPERTY, - user); - } else { - removeProperty(CollectionSpaceClient.USER_PROPERTY); - } - if (usePassword) { - setProperty(CollectionSpaceClient.PASSWORD_PROPERTY, - password); - } else { - removeProperty(CollectionSpaceClient.PASSWORD_PROPERTY); - } - } else { - removeProperty(CollectionSpaceClient.AUTH_PROPERTY); - } - setupHttpClient(); - setProxy(); - } - - /* - * - * Common Proxied service calls - * - */ - - /* (non-Javadoc) - * @see org.collectionspace.services.client.AbstractServiceClientImpl#delete(java.lang.String) - */ - @Override - public ClientResponse delete(String csid) { - return getProxy().delete(csid); - } - - /** - * @param csid - * @return - * @see org.collectionspace.services.client.BlobProxy#getAuthorityRefs(java.lang.String) - */ - @Override - public ClientResponse getAuthorityRefs(String csid) { - return getProxy().getAuthorityRefs(csid); - } - - @Override - public ClientResponse getWorkflow(String csid) { - return getProxy().getWorkflow(csid); - } - - @Override - public ClientResponse updateWorkflowWithTransition(String csid, String workflowTransition) { - return getProxy().updateWorkflowWithTransition(csid, workflowTransition); - } - - /* - * Because of how RESTEasy creates proxy classes, sub-interfaces will need to override - * these methods with their specific "common" list return types. Otherwise, only the info - * in the AbstractCommonList type will be returned to the callers - */ - - - /* - * (non-Javadoc) - * - * @see - * org.collectionspace.services.client.CollectionSpaceClient#readList(java - * .lang.String, java.lang.String) - */ - @Override - public ClientResponse readList(Long pageSize, - Long pageNumber) { - return getProxy().readList(pageSize, pageNumber); - } - - /* - * (non-Javadoc) - * - * @see - * org.collectionspace.services.client.CollectionSpaceClient#readList(java - * .lang.String, java.lang.String) - */ - @Override - public ClientResponse readList(String sortBy, Long pageSize, - Long pageNumber) { - return getProxy().readList(sortBy, pageSize, pageNumber); - } -} +/** + * 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.client; + +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URL; +import java.util.Properties; + +import javax.ws.rs.PathParam; +import javax.ws.rs.core.Response; + +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.UsernamePasswordCredentials; +import org.apache.commons.httpclient.auth.AuthScope; //import org.collectionspace.services.collectionobject.CollectionobjectsCommonList; + +import org.collectionspace.services.common.authorityref.AuthorityRefList; +import org.collectionspace.services.jaxb.AbstractCommonList; + +import org.jboss.resteasy.client.ClientResponse; //import org.collectionspace.services.common.context.ServiceContext; +import org.jboss.resteasy.client.ProxyFactory; +import org.jboss.resteasy.client.core.executors.ApacheHttpClientExecutor; +import org.jboss.resteasy.plugins.providers.RegisterBuiltin; +import org.jboss.resteasy.spi.ResteasyProviderFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * BaseServiceClient is an abstract base client of all service clients FIXME: + * http://issues.collectionspace.org/browse/CSPACE-1684 + * @param + * @param + * + * CLT - List type + * REQUEST_PT - Request payload type + * RESPONSE_PT - Response payload type + * P - Proxy type + */ +public abstract class AbstractServiceClientImpl> + implements CollectionSpaceClient { + + /** The logger. */ + protected final Logger logger = LoggerFactory.getLogger(AbstractServiceClientImpl.class); + /** + * The character used to separate the words in a part label + */ + public static final String PART_LABEL_SEPARATOR = "_"; + /** The Constant PART_COMMON_LABEL. */ + public static final String PART_COMMON_LABEL = "common"; + /** The properties. */ + private Properties properties = new Properties(); + /** The url. */ + private URL url; + /** The http client. */ + private HttpClient httpClient; + /** The RESTEasy proxy */ + private P proxy; + + /** + * Gets the logger. + * + * @return the logger + */ + public Logger getLogger() { + return logger; + } + + abstract public String getServicePathComponent(); + + /** + * Returns a UTF-8 encode byte array from 'string' + * + * @return UTF-8 encoded byte array + */ + protected byte[] getBytes(String string) { + byte[] result = null; + try { + result = string.getBytes("UTF8"); + } catch (UnsupportedEncodingException e) { + if (logger.isWarnEnabled() == true) { + logger.warn(e.getMessage(), e); + } + } + return result; + } + + /* + * Subclasses can override this method to return their AbstractCommonList subclass + */ + protected Class getCommonListType() { + return (Class) AbstractCommonList.class; + } + + /** + * Gets the common part name. + * + * @return the common part name + */ + @Override + public String getCommonPartName() { + return getCommonPartName(getServiceName()); + } + + /** + * Gets the common part name. + * + * @param servicePathComponent + * the service path component + * @return the common part name + */ + protected String getCommonPartName(String commonPrefix) { + return commonPrefix + PART_LABEL_SEPARATOR + PART_COMMON_LABEL; + } + +// /** +// * Gets the service path component. +// * +// * @return the service path component +// */ +// abstract public String getServicePathComponent(); + + /** + * Instantiates a new abstract service client impl. + */ + protected AbstractServiceClientImpl() { + readProperties(); + setupHttpClient(); + ResteasyProviderFactory factory = ResteasyProviderFactory.getInstance(); + RegisterBuiltin.register(factory); + setProxy(); + } + + /* + * (non-Javadoc) + * + * @see + * org.collectionspace.services.client.CollectionSpaceClient#getProperty + * (java.lang.String) + */ + @Override + public String getProperty(String propName) { + return properties.getProperty(propName); + } + + /* + * (non-Javadoc) + * + * @see + * org.collectionspace.services.client.CollectionSpaceClient#setProperty + * (java.lang.String, java.lang.String) + */ + @Override + public void setProperty(String propName, String value) { + properties.setProperty(propName, value); + } + + /* + * (non-Javadoc) + * + * @see + * org.collectionspace.services.client.CollectionSpaceClient#removeProperty + * (java.lang.String) + */ + @Override + public Object removeProperty(String propName) { + return properties.remove(propName); + } + + /** + * Prints the properties. + */ + public void printProperties() { + for (Object kobj : properties.keySet()) { + String key = (String) kobj; + logger.trace("begin property name=" + key + " value=" + + properties.get(key)); + } + } + + /* + * (non-Javadoc) + * + * @see + * org.collectionspace.services.client.CollectionSpaceClient#getBaseURL() + */ + @Override + public String getBaseURL() { + return properties.getProperty(URL_PROPERTY); + } + + /* + * (non-Javadoc) + * + * @see + * org.collectionspace.services.client.CollectionSpaceClient#getHttpClient() + */ + @Override + public HttpClient getHttpClient() { + return httpClient; + } + + /* + * (non-Javadoc) + * + * @see org.collectionspace.services.client.CollectionSpaceClient#useAuth() + */ + @Override + public boolean useAuth() { + String auth = properties.getProperty(AUTH_PROPERTY); + return Boolean.valueOf(auth); + } + + /* + * (non-Javadoc) + * + * @see org.collectionspace.services.client.CollectionSpaceClient#useSSL() + */ + @Override + public boolean useSSL() { + String ssl = properties.getProperty(SSL_PROPERTY); + return Boolean.valueOf(ssl); + } + + /** + * readProperties reads properties from system class path as well as it + * overrides properties made available using command line + * + * @exception RuntimeException + */ + private void readProperties() { + + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + InputStream is = null; + try { + is = cl.getResourceAsStream("collectionspace-client.properties"); + properties.load(is); + if (logger.isDebugEnabled()) { + printProperties(); + } + String spec = System.getProperty(URL_PROPERTY); + if (spec != null && !"".equals(spec)) { + properties.setProperty(URL_PROPERTY, spec); + } + + spec = properties.getProperty(URL_PROPERTY); + url = new URL(spec); + logger.debug("readProperties() using url=" + url); + + String auth = System.getProperty(AUTH_PROPERTY); + if (auth != null && !"".equals(auth)) { + properties.setProperty(AUTH_PROPERTY, auth); + } + String ssl = System.getProperty(SSL_PROPERTY); + if (ssl != null && !"".equals(ssl)) { + properties.setProperty(AUTH_PROPERTY, ssl); + } + String user = System.getProperty(USER_PROPERTY); + if (user != null && !"".equals(user)) { + properties.setProperty(USER_PROPERTY, user); + } + String password = System.getProperty(PASSWORD_PROPERTY); + if (password != null && !"".equals(password)) { + properties.setProperty(PASSWORD_PROPERTY, password); + } + String tenant = System.getProperty(TENANT_PROPERTY); + if (tenant != null && !"".equals(tenant)) { + properties.setProperty(TENANT_PROPERTY, tenant); + } + if (logger.isDebugEnabled()) { + printProperties(); + } + } catch (Exception e) { + logger.debug("Caught exception while reading properties", e); + throw new RuntimeException(e); + } finally { + if (is != null) { + try { + is.close(); + } catch (Exception e) { + if (logger.isDebugEnabled() == true) { + e.printStackTrace(); + } + } + } + } + } + + /** + * setupHttpClient sets up HTTP client for the service client the setup + * process relies on the following properties URL_PROPERTY USER_PROPERTY + * PASSWORD_PROPERTY AUTH_PROPERTY SSL_PROPERTY + */ + @Override + public void setupHttpClient() { + try { + this.httpClient = new HttpClient(); + if (useAuth()) { + String user = properties.getProperty(USER_PROPERTY); + String password = properties.getProperty(PASSWORD_PROPERTY); + if (logger.isDebugEnabled()) { + logger.debug("setupHttpClient() using url=" + url + " user=" + + user + " password=" + password); + } + + httpClient.getState().setCredentials( + new AuthScope(url.getHost(), url.getPort(), + AuthScope.ANY_REALM), + new UsernamePasswordCredentials(user, password)); + // JAXRS client library requires HTTP preemptive authentication + httpClient.getParams().setAuthenticationPreemptive(true); + if (logger.isDebugEnabled()) { + logger.debug("setupHttpClient: set preemptive authentication"); + } + } else { + if (logger.isDebugEnabled()) { + logger.debug("setupHttpClient() : no auth mode!"); + } + } + } catch (Throwable e) { + e.printStackTrace(); + } + } + + /* + * (non-Javadoc) + * + * @see + * org.collectionspace.services.client.CollectionSpaceClient#isServerSecure + * () + */ + @Override + public boolean isServerSecure() { + return Boolean.getBoolean("cspace.server.secure"); + } + + @Override + public P getProxy() { + return proxy; + } + + /** + * allow to reset proxy as per security needs + */ + @Override + public void setProxy() { + Class

proxyClass = this.getProxyClass(); + if (useAuth()) { + proxy = ProxyFactory.create(proxyClass, + getBaseURL(), new ApacheHttpClientExecutor(getHttpClient())); + } else { + proxy = ProxyFactory.create(proxyClass, + getBaseURL()); + } + } + + @Override + public void setAuth(boolean useAuth, + String user, boolean useUser, + String password, boolean usePassword) { + if (useAuth == true) { + setProperty(CollectionSpaceClient.AUTH_PROPERTY, "true"); + if (useUser) { + setProperty(CollectionSpaceClient.USER_PROPERTY, + user); + } else { + removeProperty(CollectionSpaceClient.USER_PROPERTY); + } + if (usePassword) { + setProperty(CollectionSpaceClient.PASSWORD_PROPERTY, + password); + } else { + removeProperty(CollectionSpaceClient.PASSWORD_PROPERTY); + } + } else { + removeProperty(CollectionSpaceClient.AUTH_PROPERTY); + } + setupHttpClient(); + setProxy(); + } + + /* + * + * Common Proxied service calls + * + */ + + /* (non-Javadoc) + * @see org.collectionspace.services.client.AbstractServiceClientImpl#delete(java.lang.String) + */ + @Override + public ClientResponse delete(String csid) { + return getProxy().delete(csid); + } + + /** + * @param csid + * @return + * @see org.collectionspace.services.client.BlobProxy#getAuthorityRefs(java.lang.String) + */ + @Override + public ClientResponse getAuthorityRefs(String csid) { + return getProxy().getAuthorityRefs(csid); + } + + @Override + public ClientResponse getWorkflow(String csid) { + return getProxy().getWorkflow(csid); + } + + @Override + public ClientResponse updateWorkflowWithTransition(String csid, String workflowTransition) { + return getProxy().updateWorkflowWithTransition(csid, workflowTransition); + } + + /* + * Because of how RESTEasy creates proxy classes, sub-interfaces will need to override + * these methods with their specific "common" list return types. Otherwise, only the info + * in the AbstractCommonList type will be returned to the callers + */ + + + /* + * (non-Javadoc) + * + * @see + * org.collectionspace.services.client.CollectionSpaceClient#readList(java + * .lang.String, java.lang.String) + */ + @Override + public ClientResponse readList(Long pageSize, + Long pageNumber) { + return getProxy().readList(pageSize, pageNumber); + } + + /* + * (non-Javadoc) + * + * @see + * org.collectionspace.services.client.CollectionSpaceClient#readList(java + * .lang.String, java.lang.String) + */ + @Override + public ClientResponse readList(String sortBy, Long pageSize, + Long pageNumber) { + return getProxy().readList(sortBy, pageSize, pageNumber); + } +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/AuthorityClient.java b/services/client/src/main/java/org/collectionspace/services/client/AuthorityClient.java index 1dea28bba..affb581bd 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/AuthorityClient.java +++ b/services/client/src/main/java/org/collectionspace/services/client/AuthorityClient.java @@ -1,151 +1,151 @@ -package org.collectionspace.services.client; - -import javax.ws.rs.core.Response; -import org.jboss.resteasy.client.ClientResponse; - -import org.collectionspace.services.common.authorityref.AuthorityRefDocList; -import org.collectionspace.services.common.authorityref.AuthorityRefList; -import org.collectionspace.services.jaxb.AbstractCommonList; - -/* - * LT - List type - * ILT - Authority item list type - * P - Proxy type - */ -public interface AuthorityClient - extends CollectionSpacePoxClient { - - /** The uri path element for items in an authority */ - public static String ITEMS = "items"; //used to construct uri's in service paths for authorities. - - /* - * Basic CRUD operations - */ - - String getItemCommonPartName(); - - // Get the inAuthorityCsid (the item's parent) - String getInAuthority(AUTHORITY_ITEM_TYPE item); - - // Get the inAuthorityCsid (the item's parent) - void setInAuthority(AUTHORITY_ITEM_TYPE item, String inAuthorityCsid); - - //(C)reate Item - ClientResponse createItem(String vcsid, PoxPayloadOut poxPayloadOut); - - //(R)ead Item - ClientResponse readItem(String vcsid, String csid); - - //(R)ead Item - ClientResponse readItem(String vcsid, String csid, Boolean includeDeleted); - - //(U)pdate Item - ClientResponse updateItem(String vcsid, String csid, PoxPayloadOut poxPayloadOut); - - //(D)elete Item - ClientResponse deleteItem(String vcsid, String csid); - - // Get a list of objects that - ClientResponse getReferencingObjects( - String parentcsid, - String itemcsid); - /** - * Get a list of objects that reference a given authority term. - * - * @param parentcsid - * @param itemcsid - * @param csid - * @return - * @see org.collectionspace.services.client.IntakeProxy#getAuthorityRefs(java.lang.String) - */ - public ClientResponse getItemAuthorityRefs(String parentcsid, String itemcsid); - - /* - * - */ - - ClientResponse readByName(String name); - - ClientResponse readByName(String name, Boolean includeDeleted); - - /* - * Item subresource methods - */ - - /** - * Read named item. - * - * @param vcsid the vcsid - * @param shortId the shortIdentifier - * @return the client response - */ - public ClientResponse readNamedItem(String vcsid, String shortId); - - public ClientResponse readNamedItem(String vcsid, String shortId, Boolean includeDeleted); - - /** - * Read item in Named Authority. - * - * @param authShortId the shortIdentifier for the Authority - * @param csid the csid - * @return the client response - */ - public ClientResponse readItemInNamedAuthority(String authShortId, String csid); - - public ClientResponse readItemInNamedAuthority(String authShortId, String csid, Boolean includeDeleted); - - /** - * Read named item in Named Authority. - * - * @param authShortId the shortIdentifier for the Authority - * @param itemShortId the shortIdentifier for the item - * @return the client response - */ - public ClientResponse readNamedItemInNamedAuthority(String authShortId, String itemShortId); - - public ClientResponse readNamedItemInNamedAuthority(String authShortId, String itemShortId, Boolean includeDeleted); - - /** - * Read item list, filtering by partial term match, or keywords. Only one of - * partialTerm or keywords should be specified. If both are specified, keywords - * will be ignored. - * - * @param inAuthority the parent authority - * @param partialTerm A partial term on which to match, - * which will filter list results to return only matched resources. - * @param keywords A set of keywords on which to match, - * which will filter list results to return only matched resources. - * @return the client response - */ - public ClientResponse readItemList(String inAuthority, String partialTerm, String keywords); - - public ClientResponse readItemList(String inAuthority, String partialTerm, String keywords, Boolean includeDeleted); - - /** - * Read item list for named vocabulary, filtering by partial term match, or keywords. Only one of - * partialTerm or keywords should be specified. If both are specified, keywords - * will be ignored. - * - * @param specifier the specifier - * @param partialTerm A partial term on which to match, - * which will filter list results to return only matched resources. - * @param keywords A set of keywords on which to match, - * which will filter list results to return only matched resources. - * @return the client response - */ - public ClientResponse readItemListForNamedAuthority(String specifier, - String partialTerm, String keywords); - - public ClientResponse readItemListForNamedAuthority(String specifier, - String partialTerm, - String keywords, - Boolean includeDeleted); - - /* - * Workflow related methods - */ - - public ClientResponse readItemWorkflow(String vcsid, String csid); - - public ClientResponse updateItemWorkflowWithTransition(String vcsid, String csid, String workflowTransition); -} +package org.collectionspace.services.client; + +import javax.ws.rs.core.Response; +import org.jboss.resteasy.client.ClientResponse; + +import org.collectionspace.services.common.authorityref.AuthorityRefDocList; +import org.collectionspace.services.common.authorityref.AuthorityRefList; +import org.collectionspace.services.jaxb.AbstractCommonList; + +/* + * LT - List type + * ILT - Authority item list type + * P - Proxy type + */ +public interface AuthorityClient + extends CollectionSpacePoxClient { + + /** The uri path element for items in an authority */ + public static String ITEMS = "items"; //used to construct uri's in service paths for authorities. + + /* + * Basic CRUD operations + */ + + String getItemCommonPartName(); + + // Get the inAuthorityCsid (the item's parent) + String getInAuthority(AUTHORITY_ITEM_TYPE item); + + // Get the inAuthorityCsid (the item's parent) + void setInAuthority(AUTHORITY_ITEM_TYPE item, String inAuthorityCsid); + + //(C)reate Item + ClientResponse createItem(String vcsid, PoxPayloadOut poxPayloadOut); + + //(R)ead Item + ClientResponse readItem(String vcsid, String csid); + + //(R)ead Item + ClientResponse readItem(String vcsid, String csid, Boolean includeDeleted); + + //(U)pdate Item + ClientResponse updateItem(String vcsid, String csid, PoxPayloadOut poxPayloadOut); + + //(D)elete Item + ClientResponse deleteItem(String vcsid, String csid); + + // Get a list of objects that + ClientResponse getReferencingObjects( + String parentcsid, + String itemcsid); + /** + * Get a list of objects that reference a given authority term. + * + * @param parentcsid + * @param itemcsid + * @param csid + * @return + * @see org.collectionspace.services.client.IntakeProxy#getAuthorityRefs(java.lang.String) + */ + public ClientResponse getItemAuthorityRefs(String parentcsid, String itemcsid); + + /* + * + */ + + ClientResponse readByName(String name); + + ClientResponse readByName(String name, Boolean includeDeleted); + + /* + * Item subresource methods + */ + + /** + * Read named item. + * + * @param vcsid the vcsid + * @param shortId the shortIdentifier + * @return the client response + */ + public ClientResponse readNamedItem(String vcsid, String shortId); + + public ClientResponse readNamedItem(String vcsid, String shortId, Boolean includeDeleted); + + /** + * Read item in Named Authority. + * + * @param authShortId the shortIdentifier for the Authority + * @param csid the csid + * @return the client response + */ + public ClientResponse readItemInNamedAuthority(String authShortId, String csid); + + public ClientResponse readItemInNamedAuthority(String authShortId, String csid, Boolean includeDeleted); + + /** + * Read named item in Named Authority. + * + * @param authShortId the shortIdentifier for the Authority + * @param itemShortId the shortIdentifier for the item + * @return the client response + */ + public ClientResponse readNamedItemInNamedAuthority(String authShortId, String itemShortId); + + public ClientResponse readNamedItemInNamedAuthority(String authShortId, String itemShortId, Boolean includeDeleted); + + /** + * Read item list, filtering by partial term match, or keywords. Only one of + * partialTerm or keywords should be specified. If both are specified, keywords + * will be ignored. + * + * @param inAuthority the parent authority + * @param partialTerm A partial term on which to match, + * which will filter list results to return only matched resources. + * @param keywords A set of keywords on which to match, + * which will filter list results to return only matched resources. + * @return the client response + */ + public ClientResponse readItemList(String inAuthority, String partialTerm, String keywords); + + public ClientResponse readItemList(String inAuthority, String partialTerm, String keywords, Boolean includeDeleted); + + /** + * Read item list for named vocabulary, filtering by partial term match, or keywords. Only one of + * partialTerm or keywords should be specified. If both are specified, keywords + * will be ignored. + * + * @param specifier the specifier + * @param partialTerm A partial term on which to match, + * which will filter list results to return only matched resources. + * @param keywords A set of keywords on which to match, + * which will filter list results to return only matched resources. + * @return the client response + */ + public ClientResponse readItemListForNamedAuthority(String specifier, + String partialTerm, String keywords); + + public ClientResponse readItemListForNamedAuthority(String specifier, + String partialTerm, + String keywords, + Boolean includeDeleted); + + /* + * Workflow related methods + */ + + public ClientResponse readItemWorkflow(String vcsid, String csid); + + public ClientResponse updateItemWorkflowWithTransition(String vcsid, String csid, String workflowTransition); +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/AuthorityClientImpl.java b/services/client/src/main/java/org/collectionspace/services/client/AuthorityClientImpl.java index a79d44844..7d8443a21 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/AuthorityClientImpl.java +++ b/services/client/src/main/java/org/collectionspace/services/client/AuthorityClientImpl.java @@ -1,205 +1,205 @@ -package org.collectionspace.services.client; - -import javax.ws.rs.core.Response; -import org.jboss.resteasy.client.ClientResponse; - -import org.collectionspace.services.common.authorityref.AuthorityRefDocList; -import org.collectionspace.services.common.authorityref.AuthorityRefList; -import org.collectionspace.services.jaxb.AbstractCommonList; - -/* - * P - Proxy type - */ -public abstract class AuthorityClientImpl - extends AbstractPoxServiceClientImpl - implements AuthorityClient { - - private static final String INCLUDE_DELETE_TRUE = Boolean.TRUE.toString(); - /* - * Basic CRUD proxied methods - */ - - //(C)reate Item - @Override - public ClientResponse createItem(String vcsid, PoxPayloadOut poxPayloadOut) { - return getProxy().createItem(vcsid, poxPayloadOut.getBytes()); - } - - //(R)ead Item - @Override - public ClientResponse readItem(String vcsid, String csid) { - return getProxy().readItem(vcsid, csid, INCLUDE_DELETE_TRUE); - } - - @Override - public ClientResponse readItem(String vcsid, String csid, Boolean includeDeleted) { - return getProxy().readItem(vcsid, csid, includeDeleted.toString()); - } - - //(U)pdate Item - @Override - public ClientResponse updateItem(String vcsid, String csid, PoxPayloadOut poxPayloadOut) { - return getProxy().updateItem(vcsid, csid, poxPayloadOut.getBytes()); - } - - //(D)elete Item - @Override - public ClientResponse deleteItem(String vcsid, String csid) { - return getProxy().deleteItem(vcsid, csid); - } - - @Override - public ClientResponse getReferencingObjects( - String parentcsid, - String itemcsid) { - return getProxy().getReferencingObjects(parentcsid, itemcsid, Boolean.TRUE.toString()); - } - - /** - * Gets the item authority refs. - * - * @param parentcsid the parentcsid - * @param csid the csid - * @return the item authority refs - */ - @Override - public ClientResponse getItemAuthorityRefs(String parentcsid, String csid) { - return getProxy().getItemAuthorityRefs(parentcsid, csid); - } - - /* - * - */ - - @Override - public ClientResponse readByName(String name) { - return getProxy().readByName(name, INCLUDE_DELETE_TRUE); - } - - @Override - public ClientResponse readByName(String name, Boolean includeDeleted) { - return getProxy().readByName(name, includeDeleted.toString()); - } - - /* - * Item subresource methods - */ - - /** - * Read named item. - * - * @param vcsid the vcsid - * @param shortId the shortIdentifier - * @return the client response - */ - @Override - public ClientResponse readNamedItem(String vcsid, String shortId) { - return getProxy().readNamedItem(vcsid, shortId, INCLUDE_DELETE_TRUE); - } - - @Override - public ClientResponse readNamedItem(String vcsid, String shortId, Boolean includeDeleted) { - return getProxy().readNamedItem(vcsid, shortId, includeDeleted.toString()); - } - - /** - * Read item in Named Authority. - * - * @param authShortId the shortIdentifier for the Authority - * @param csid the csid - * @return the client response - */ - @Override - public ClientResponse readItemInNamedAuthority(String authShortId, String csid) { - return getProxy().readItemInNamedAuthority(authShortId, csid, INCLUDE_DELETE_TRUE); - } - - @Override - public ClientResponse readItemInNamedAuthority(String authShortId, String csid, Boolean includeDeleted) { - return getProxy().readItemInNamedAuthority(authShortId, csid, includeDeleted.toString()); - } - - /** - * Read named item in Named Authority. - * - * @param authShortId the shortIdentifier for the Authority - * @param itemShortId the shortIdentifier for the item - * @return the client response - */ - @Override - public ClientResponse readNamedItemInNamedAuthority(String authShortId, String itemShortId) { - return getProxy().readNamedItemInNamedAuthority(authShortId, itemShortId, INCLUDE_DELETE_TRUE); - } - - @Override - public ClientResponse readNamedItemInNamedAuthority(String authShortId, String itemShortId, Boolean includeDeleted) { - return getProxy().readNamedItemInNamedAuthority(authShortId, itemShortId, includeDeleted.toString()); - } - - /** - * Read item list, filtering by partial term match, or keywords. Only one of - * partialTerm or keywords should be specified. If both are specified, keywords - * will be ignored. - * - * @param inAuthority the parent authority - * @param partialTerm A partial term on which to match, - * which will filter list results to return only matched resources. - * @param keywords A set of keywords on which to match, - * which will filter list results to return only matched resources. - * @return the client response - */ - @Override - public ClientResponse - readItemList(String inAuthority, String partialTerm, String keywords) { - return getProxy().readItemList(inAuthority, partialTerm, keywords, INCLUDE_DELETE_TRUE); - } - - @Override - public ClientResponse - readItemList(String inAuthority, String partialTerm, String keywords, Boolean includeDeleted) { - return getProxy().readItemList(inAuthority, partialTerm, keywords, includeDeleted.toString()); - } - - /** - * Read item list for named vocabulary, filtering by partial term match, or keywords. Only one of - * partialTerm or keywords should be specified. If both are specified, keywords - * will be ignored. - * - * @param specifier the specifier - * @param partialTerm A partial term on which to match, - * which will filter list results to return only matched resources. - * @param keywords A set of keywords on which to match, - * which will filter list results to return only matched resources. - * @return the client response - */ - - @Override - public ClientResponse readItemListForNamedAuthority( - String specifier, String partialTerm, String keywords) { - return getProxy().readItemListForNamedAuthority(specifier, partialTerm, keywords, INCLUDE_DELETE_TRUE); - } - - @Override - public ClientResponse readItemListForNamedAuthority( - String specifier, - String partialTerm, - String keywords, - Boolean includeDeleted) { - return getProxy().readItemListForNamedAuthority(specifier, partialTerm, keywords, includeDeleted.toString()); - } - - /* - * Workflow related methods - */ - - @Override - public ClientResponse readItemWorkflow(String vcsid, String csid) { - return getProxy().readItemWorkflow(vcsid, csid); - } - - @Override - public ClientResponse updateItemWorkflowWithTransition(String vcsid, String csid, String workflowTransition) { - return getProxy().updateItemWorkflowWithTransition(vcsid, csid, workflowTransition); - } - -} +package org.collectionspace.services.client; + +import javax.ws.rs.core.Response; +import org.jboss.resteasy.client.ClientResponse; + +import org.collectionspace.services.common.authorityref.AuthorityRefDocList; +import org.collectionspace.services.common.authorityref.AuthorityRefList; +import org.collectionspace.services.jaxb.AbstractCommonList; + +/* + * P - Proxy type + */ +public abstract class AuthorityClientImpl + extends AbstractPoxServiceClientImpl + implements AuthorityClient { + + private static final String INCLUDE_DELETE_TRUE = Boolean.TRUE.toString(); + /* + * Basic CRUD proxied methods + */ + + //(C)reate Item + @Override + public ClientResponse createItem(String vcsid, PoxPayloadOut poxPayloadOut) { + return getProxy().createItem(vcsid, poxPayloadOut.getBytes()); + } + + //(R)ead Item + @Override + public ClientResponse readItem(String vcsid, String csid) { + return getProxy().readItem(vcsid, csid, INCLUDE_DELETE_TRUE); + } + + @Override + public ClientResponse readItem(String vcsid, String csid, Boolean includeDeleted) { + return getProxy().readItem(vcsid, csid, includeDeleted.toString()); + } + + //(U)pdate Item + @Override + public ClientResponse updateItem(String vcsid, String csid, PoxPayloadOut poxPayloadOut) { + return getProxy().updateItem(vcsid, csid, poxPayloadOut.getBytes()); + } + + //(D)elete Item + @Override + public ClientResponse deleteItem(String vcsid, String csid) { + return getProxy().deleteItem(vcsid, csid); + } + + @Override + public ClientResponse getReferencingObjects( + String parentcsid, + String itemcsid) { + return getProxy().getReferencingObjects(parentcsid, itemcsid, Boolean.TRUE.toString()); + } + + /** + * Gets the item authority refs. + * + * @param parentcsid the parentcsid + * @param csid the csid + * @return the item authority refs + */ + @Override + public ClientResponse getItemAuthorityRefs(String parentcsid, String csid) { + return getProxy().getItemAuthorityRefs(parentcsid, csid); + } + + /* + * + */ + + @Override + public ClientResponse readByName(String name) { + return getProxy().readByName(name, INCLUDE_DELETE_TRUE); + } + + @Override + public ClientResponse readByName(String name, Boolean includeDeleted) { + return getProxy().readByName(name, includeDeleted.toString()); + } + + /* + * Item subresource methods + */ + + /** + * Read named item. + * + * @param vcsid the vcsid + * @param shortId the shortIdentifier + * @return the client response + */ + @Override + public ClientResponse readNamedItem(String vcsid, String shortId) { + return getProxy().readNamedItem(vcsid, shortId, INCLUDE_DELETE_TRUE); + } + + @Override + public ClientResponse readNamedItem(String vcsid, String shortId, Boolean includeDeleted) { + return getProxy().readNamedItem(vcsid, shortId, includeDeleted.toString()); + } + + /** + * Read item in Named Authority. + * + * @param authShortId the shortIdentifier for the Authority + * @param csid the csid + * @return the client response + */ + @Override + public ClientResponse readItemInNamedAuthority(String authShortId, String csid) { + return getProxy().readItemInNamedAuthority(authShortId, csid, INCLUDE_DELETE_TRUE); + } + + @Override + public ClientResponse readItemInNamedAuthority(String authShortId, String csid, Boolean includeDeleted) { + return getProxy().readItemInNamedAuthority(authShortId, csid, includeDeleted.toString()); + } + + /** + * Read named item in Named Authority. + * + * @param authShortId the shortIdentifier for the Authority + * @param itemShortId the shortIdentifier for the item + * @return the client response + */ + @Override + public ClientResponse readNamedItemInNamedAuthority(String authShortId, String itemShortId) { + return getProxy().readNamedItemInNamedAuthority(authShortId, itemShortId, INCLUDE_DELETE_TRUE); + } + + @Override + public ClientResponse readNamedItemInNamedAuthority(String authShortId, String itemShortId, Boolean includeDeleted) { + return getProxy().readNamedItemInNamedAuthority(authShortId, itemShortId, includeDeleted.toString()); + } + + /** + * Read item list, filtering by partial term match, or keywords. Only one of + * partialTerm or keywords should be specified. If both are specified, keywords + * will be ignored. + * + * @param inAuthority the parent authority + * @param partialTerm A partial term on which to match, + * which will filter list results to return only matched resources. + * @param keywords A set of keywords on which to match, + * which will filter list results to return only matched resources. + * @return the client response + */ + @Override + public ClientResponse + readItemList(String inAuthority, String partialTerm, String keywords) { + return getProxy().readItemList(inAuthority, partialTerm, keywords, INCLUDE_DELETE_TRUE); + } + + @Override + public ClientResponse + readItemList(String inAuthority, String partialTerm, String keywords, Boolean includeDeleted) { + return getProxy().readItemList(inAuthority, partialTerm, keywords, includeDeleted.toString()); + } + + /** + * Read item list for named vocabulary, filtering by partial term match, or keywords. Only one of + * partialTerm or keywords should be specified. If both are specified, keywords + * will be ignored. + * + * @param specifier the specifier + * @param partialTerm A partial term on which to match, + * which will filter list results to return only matched resources. + * @param keywords A set of keywords on which to match, + * which will filter list results to return only matched resources. + * @return the client response + */ + + @Override + public ClientResponse readItemListForNamedAuthority( + String specifier, String partialTerm, String keywords) { + return getProxy().readItemListForNamedAuthority(specifier, partialTerm, keywords, INCLUDE_DELETE_TRUE); + } + + @Override + public ClientResponse readItemListForNamedAuthority( + String specifier, + String partialTerm, + String keywords, + Boolean includeDeleted) { + return getProxy().readItemListForNamedAuthority(specifier, partialTerm, keywords, includeDeleted.toString()); + } + + /* + * Workflow related methods + */ + + @Override + public ClientResponse readItemWorkflow(String vcsid, String csid) { + return getProxy().readItemWorkflow(vcsid, csid); + } + + @Override + public ClientResponse updateItemWorkflowWithTransition(String vcsid, String csid, String workflowTransition) { + return getProxy().updateItemWorkflowWithTransition(vcsid, csid, workflowTransition); + } + +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/AuthorityProxy.java b/services/client/src/main/java/org/collectionspace/services/client/AuthorityProxy.java index d10344f4e..37f16e458 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/AuthorityProxy.java +++ b/services/client/src/main/java/org/collectionspace/services/client/AuthorityProxy.java @@ -1,157 +1,157 @@ -package org.collectionspace.services.client; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; -import org.jboss.resteasy.client.ClientResponse; - -import org.collectionspace.services.client.workflow.WorkflowClient; -import org.collectionspace.services.common.authorityref.AuthorityRefDocList; -import org.collectionspace.services.common.authorityref.AuthorityRefList; -import org.collectionspace.services.jaxb.AbstractCommonList; - -/* - * ILT = Item list type - * LT = List type - */ -public interface AuthorityProxy extends CollectionSpaceCommonListPoxProxy { - - /* - * Basic CRUD operations - */ - - //(C)reate Item - @POST - @Path("/{vcsid}/items/") - ClientResponse createItem(@PathParam("vcsid") String vcsid, byte[] xmlPayload); - - //(R)ead Item - @GET - @Path("/{vcsid}/items/{csid}") - ClientResponse readItem(@PathParam("vcsid") String vcsid, - @PathParam("csid") String csid, - @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); - - //(U)pdate Item - @PUT - @Path("/{vcsid}/items/{csid}") - ClientResponse updateItem(@PathParam("vcsid") String vcsid, @PathParam("csid") String csid, byte[] xmlPayload); - - //(D)elete Item - @DELETE - @Path("/{vcsid}/items/{csid}") - ClientResponse deleteItem(@PathParam("vcsid") String vcsid, @PathParam("csid") String csid); - - /** - * Get a list of objects that reference a given authority term. - * - * @param parentcsid - * @param itemcsid - * @param csid - * @return - * @see org.collectionspace.services.client.IntakeProxy#getAuthorityRefs(java.lang.String) - */ - @GET - @Path("{csid}/items/{itemcsid}/refObjs") - @Produces("application/xml") - ClientResponse getReferencingObjects( - @PathParam("csid") String parentcsid, - @PathParam("itemcsid") String itemcsid, - @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); - - // List Item Authority References - @GET - @Produces({"application/xml"}) - @Path("/{parentcsid}/items/{itemcsid}/authorityrefs/") - public ClientResponse getItemAuthorityRefs( - @PathParam("parentcsid") String parentcsid, - @PathParam("itemcsid") String itemcsid); - - /* - * - */ - - //(R)ead by name - @GET - @Path("/urn:cspace:name({name})") - ClientResponse readByName(@PathParam("name") String name, - @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); - - /* - * Item subresource methods - */ - - //(R)ead Named Item - @GET - @Path("/{vcsid}/items/urn:cspace:name({specifier})") - ClientResponse readNamedItem(@PathParam("vcsid") String vcsid, - @PathParam("specifier") String specifier, - @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); - - //(R)ead Item In Named Authority - @GET - @Path("/urn:cspace:name({specifier})/items/{csid}") - ClientResponse readItemInNamedAuthority(@PathParam("specifier") String specifier, - @PathParam("csid") String csid, - @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); - - //(R)ead Named Item In Named Authority - @GET - @Path("/urn:cspace:name({specifier})/items/urn:cspace:name({itemspecifier})") - ClientResponse readNamedItemInNamedAuthority(@PathParam("specifier") String specifier, - @PathParam("itemspecifier") String itemspecifier, - @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); - - /* - * Item subresource List methods - */ - - // List Items matching a partial term or keywords. - @GET - @Produces({"application/xml"}) - @Path("/{csid}/items/") - ClientResponse readItemList( - @PathParam("csid") String vcsid, - @QueryParam (IQueryManager.SEARCH_TYPE_PARTIALTERM) String partialTerm, - @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_KW) String keywords, - @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); - - // List Items for a named authority matching a partial term or keywords. - @GET - @Produces({"application/xml"}) - @Path("/urn:cspace:name({specifier})/items/") - ClientResponse readItemListForNamedAuthority( - @PathParam("specifier") String specifier, - @QueryParam (IQueryManager.SEARCH_TYPE_PARTIALTERM) String partialTerm, - @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_KW) String keywords, - @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); - - /* - * Workflow related methods - * - */ - - //(R)ead Item workflow - @GET - @Produces({"application/xml"}) - @Consumes({"application/xml"}) - @Path("/{vcsid}/items/{csid}" + WorkflowClient.SERVICE_PATH) - ClientResponse readItemWorkflow(@PathParam("vcsid") String vcsid, - @PathParam("csid") String csid); - - //(U)pdate Item workflow - @PUT - @Path("/{vcsid}/items/{csid}" + WorkflowClient.SERVICE_PATH + "/{transition}") - ClientResponse updateItemWorkflowWithTransition( - @PathParam("vcsid") String vcsid, - @PathParam("csid") String csid, - @PathParam("transition") String transition); - -} +package org.collectionspace.services.client; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; +import org.jboss.resteasy.client.ClientResponse; + +import org.collectionspace.services.client.workflow.WorkflowClient; +import org.collectionspace.services.common.authorityref.AuthorityRefDocList; +import org.collectionspace.services.common.authorityref.AuthorityRefList; +import org.collectionspace.services.jaxb.AbstractCommonList; + +/* + * ILT = Item list type + * LT = List type + */ +public interface AuthorityProxy extends CollectionSpaceCommonListPoxProxy { + + /* + * Basic CRUD operations + */ + + //(C)reate Item + @POST + @Path("/{vcsid}/items/") + ClientResponse createItem(@PathParam("vcsid") String vcsid, byte[] xmlPayload); + + //(R)ead Item + @GET + @Path("/{vcsid}/items/{csid}") + ClientResponse readItem(@PathParam("vcsid") String vcsid, + @PathParam("csid") String csid, + @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); + + //(U)pdate Item + @PUT + @Path("/{vcsid}/items/{csid}") + ClientResponse updateItem(@PathParam("vcsid") String vcsid, @PathParam("csid") String csid, byte[] xmlPayload); + + //(D)elete Item + @DELETE + @Path("/{vcsid}/items/{csid}") + ClientResponse deleteItem(@PathParam("vcsid") String vcsid, @PathParam("csid") String csid); + + /** + * Get a list of objects that reference a given authority term. + * + * @param parentcsid + * @param itemcsid + * @param csid + * @return + * @see org.collectionspace.services.client.IntakeProxy#getAuthorityRefs(java.lang.String) + */ + @GET + @Path("{csid}/items/{itemcsid}/refObjs") + @Produces("application/xml") + ClientResponse getReferencingObjects( + @PathParam("csid") String parentcsid, + @PathParam("itemcsid") String itemcsid, + @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); + + // List Item Authority References + @GET + @Produces({"application/xml"}) + @Path("/{parentcsid}/items/{itemcsid}/authorityrefs/") + public ClientResponse getItemAuthorityRefs( + @PathParam("parentcsid") String parentcsid, + @PathParam("itemcsid") String itemcsid); + + /* + * + */ + + //(R)ead by name + @GET + @Path("/urn:cspace:name({name})") + ClientResponse readByName(@PathParam("name") String name, + @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); + + /* + * Item subresource methods + */ + + //(R)ead Named Item + @GET + @Path("/{vcsid}/items/urn:cspace:name({specifier})") + ClientResponse readNamedItem(@PathParam("vcsid") String vcsid, + @PathParam("specifier") String specifier, + @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); + + //(R)ead Item In Named Authority + @GET + @Path("/urn:cspace:name({specifier})/items/{csid}") + ClientResponse readItemInNamedAuthority(@PathParam("specifier") String specifier, + @PathParam("csid") String csid, + @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); + + //(R)ead Named Item In Named Authority + @GET + @Path("/urn:cspace:name({specifier})/items/urn:cspace:name({itemspecifier})") + ClientResponse readNamedItemInNamedAuthority(@PathParam("specifier") String specifier, + @PathParam("itemspecifier") String itemspecifier, + @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); + + /* + * Item subresource List methods + */ + + // List Items matching a partial term or keywords. + @GET + @Produces({"application/xml"}) + @Path("/{csid}/items/") + ClientResponse readItemList( + @PathParam("csid") String vcsid, + @QueryParam (IQueryManager.SEARCH_TYPE_PARTIALTERM) String partialTerm, + @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_KW) String keywords, + @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); + + // List Items for a named authority matching a partial term or keywords. + @GET + @Produces({"application/xml"}) + @Path("/urn:cspace:name({specifier})/items/") + ClientResponse readItemListForNamedAuthority( + @PathParam("specifier") String specifier, + @QueryParam (IQueryManager.SEARCH_TYPE_PARTIALTERM) String partialTerm, + @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_KW) String keywords, + @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); + + /* + * Workflow related methods + * + */ + + //(R)ead Item workflow + @GET + @Produces({"application/xml"}) + @Consumes({"application/xml"}) + @Path("/{vcsid}/items/{csid}" + WorkflowClient.SERVICE_PATH) + ClientResponse readItemWorkflow(@PathParam("vcsid") String vcsid, + @PathParam("csid") String csid); + + //(U)pdate Item workflow + @PUT + @Path("/{vcsid}/items/{csid}" + WorkflowClient.SERVICE_PATH + "/{transition}") + ClientResponse updateItemWorkflowWithTransition( + @PathParam("vcsid") String vcsid, + @PathParam("csid") String csid, + @PathParam("transition") String transition); + +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/CollectionSpaceClientUtils.java b/services/client/src/main/java/org/collectionspace/services/client/CollectionSpaceClientUtils.java index 8f2bf0b8f..138b87181 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/CollectionSpaceClientUtils.java +++ b/services/client/src/main/java/org/collectionspace/services/client/CollectionSpaceClientUtils.java @@ -1,302 +1,302 @@ -/** - * 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 (c) 2009 Regents of the University of California - * - * 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.client; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.InputStream; -import java.io.StringWriter; -import java.util.List; - -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.apache.commons.io.FileUtils; -import org.jboss.resteasy.client.ClientResponse; -import org.jboss.resteasy.plugins.providers.multipart.InputPart; -import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; - -/** - * CollectionSpaceClientUtils. - * - * Base abstract class on which client tests of services are based. - * - * $LastChangedRevision: 2261 $ - * $LastChangedDate: 2010-05-28 16:52:22 -0700 (Fri, 28 May 2010) $ - */ - -// FIXME: http://issues.collectionspace.org/browse/CSPACE-1685 - -public class CollectionSpaceClientUtils { - - //Maven's base directory -i.e., the one containing the current pom.xml - /** The Constant logger. */ - private static final Logger logger = LoggerFactory.getLogger(CollectionSpaceClientUtils.class); - - protected static final int STATUS_BAD_REQUEST = - Response.Status.BAD_REQUEST.getStatusCode(); - protected static final int STATUS_CREATED = - Response.Status.CREATED.getStatusCode(); - protected static final int STATUS_NOT_FOUND = - Response.Status.NOT_FOUND.getStatusCode(); - protected static final int STATUS_OK = - Response.Status.OK.getStatusCode(); - - /** - * Extract id. - * - * @param res the res - * @return the string - */ - static public String extractId(ClientResponse res) { - MultivaluedMap mvm = res.getMetadata(); - return extractIdFromResponseMetadata(mvm); - } - - /** - * Extract id. - * - * @param res the res - * @return the string - */ - static public String extractId(Response res) { - MultivaluedMap mvm = res.getMetadata(); - return extractIdFromResponseMetadata(mvm); - } - - static protected String extractIdFromResponseMetadata(MultivaluedMap mvm) { - // mvm may return a java.net.URI which complains about casting to String... - String uri = ((List) mvm.get("Location")).get(0).toString(); - if (logger.isDebugEnabled()) { - logger.debug("extractId:uri=" + uri); - } - String[] segments = uri.split("/"); - String id = segments[segments.length - 1]; - if (logger.isDebugEnabled()) { - logger.debug("id=" + id); - } - return id; - } - - /** - * Extract part. - * - * @param input the input - * @param label the label - * @param clazz the clazz - * @return the object - * @throws Exception the exception - */ - static protected Object extractPart(PoxPayloadIn input, String label, Class clazz) - throws Exception { - Object result = null; - PayloadInputPart payloadInputPart = input.getPart(label); - if (payloadInputPart != null) { - result = payloadInputPart.getBody(); - } else if (logger.isWarnEnabled() == true) { - logger.warn("Payload part: " + label + - " is missing from payload: " + input.getName()); - } - return result; - } - - /** - * Extract part. - * - * @param input the input - * @param label the label - * @param clazz the clazz - * @return the object - * @throws Exception the exception - */ - @Deprecated - static public Object extractPart(MultipartInput input, String label, Class clazz) - throws Exception { - Object obj = null; - String partLabel = ""; - List parts = input.getParts(); - if (parts.size() == 0) { - logger.warn("No parts found in multipart body."); - } - if (logger.isDebugEnabled()) { - logger.debug("Parts:"); - for (InputPart part : parts) { - partLabel = part.getHeaders().getFirst("label"); - logger.debug("part = " + partLabel); - } - } - boolean partLabelMatched = false; - for (InputPart part : parts) { - partLabel = part.getHeaders().getFirst("label"); - if (label.equalsIgnoreCase(partLabel)) { - partLabelMatched = true; - if (logger.isDebugEnabled()) { - logger.debug("found part" + partLabel); - } - String partStr = part.getBodyAsString(); - if (partStr == null || partStr.trim().isEmpty()) { - logger.warn("Part '" + label + "' in multipart body is empty."); - } else { - if (logger.isDebugEnabled()) { - logger.debug("extracted part as str=\n" + partStr); - } - obj = part.getBody(clazz, null); - if (logger.isDebugEnabled()) { - logger.debug("extracted part as obj=\n", - objectAsXmlString(obj, clazz)); - } - } - break; - } - } - if (!partLabelMatched) { - logger.warn("Could not find part '" + label + "' in multipart body."); - // In the event that getBodyAsString() or getBody(), above, do *not* - // throw an IOException, but getBody() nonetheless retrieves a null object. - // This *may* be unreachable. - } else if (obj == null) { - logger.warn("Could not extract part '" + label - + "' in multipart body as an object."); - } - return obj; - } - - /** - * Gets the part object. - * - * @param partStr the part str - * @param clazz the clazz - * @return the part object - * @throws JAXBException the jAXB exception - */ - static public Object getPartObject(String partStr, Class clazz) - throws JAXBException { - JAXBContext jc = JAXBContext.newInstance(clazz); - ByteArrayInputStream bais = null; - Object obj = null; - try { - bais = new ByteArrayInputStream(partStr.getBytes()); - Unmarshaller um = jc.createUnmarshaller(); - obj = um.unmarshal(bais); - } finally { - if (bais != null) { - try { - bais.close(); - } catch (Exception e) { - if (logger.isDebugEnabled() == true) { - e.printStackTrace(); - } - } - } - } - return obj; - } - - /** - * Object as xml string. - * - * @param o the o - * @param clazz the clazz - * @return the string - */ - static public String objectAsXmlString(Object o, Class clazz) { - StringWriter sw = new StringWriter(); - try { - JAXBContext jc = JAXBContext.newInstance(clazz); - Marshaller m = jc.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, - Boolean.TRUE); - m.marshal(o, sw); - } catch (Exception e) { - e.printStackTrace(); - } - return sw.toString(); - } - - /** - * getObjectFromFile get object of given class from given file (in classpath) - * @param jaxbClass - * @param fileName of the file to read to construct the object - * @return - * @throws Exception - */ - static public Object getObjectFromFile(Class jaxbClass, String fileName) - throws Exception { - ClassLoader tccl = Thread.currentThread().getContextClassLoader(); - InputStream is = tccl.getResourceAsStream(fileName); - return getObjectFromStream(jaxbClass, is); - } - - /** - * Gets the xml document. - * - * @param fileName the file name - * @return the xml document - * @throws Exception the exception - */ - static public Document getXmlDocument(String fileName) throws Exception { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - File f = new File(fileName); - if (!f.exists()) { - throw new IllegalArgumentException("test data file " + fileName + " not found!"); - } - // Create the builder and parse the file - return factory.newDocumentBuilder().parse(f); - } - - /** - * Gets the xml document as string. - * - * @param fileName the file name - * @return the xml document as string - * @throws Exception the exception - */ - static public String getXmlDocumentAsString(String fileName) throws Exception { - byte[] b = FileUtils.readFileToByteArray(new File(fileName)); - return new String(b); - } - - /** - * getObjectFromStream get object of given class from given inputstream - * @param jaxbClass - * @param is stream to read to construct the object - * @return - * @throws Exception - */ - static public Object getObjectFromStream(Class jaxbClass, InputStream is) throws Exception { - JAXBContext context = JAXBContext.newInstance(jaxbClass); - Unmarshaller unmarshaller = context.createUnmarshaller(); - //note: setting schema to null will turn validator off - unmarshaller.setSchema(null); - return jaxbClass.cast(unmarshaller.unmarshal(is)); - } -} +/** + * 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 (c) 2009 Regents of the University of California + * + * 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.client; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.InputStream; +import java.io.StringWriter; +import java.util.List; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.apache.commons.io.FileUtils; +import org.jboss.resteasy.client.ClientResponse; +import org.jboss.resteasy.plugins.providers.multipart.InputPart; +import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; + +/** + * CollectionSpaceClientUtils. + * + * Base abstract class on which client tests of services are based. + * + * $LastChangedRevision: 2261 $ + * $LastChangedDate: 2010-05-28 16:52:22 -0700 (Fri, 28 May 2010) $ + */ + +// FIXME: http://issues.collectionspace.org/browse/CSPACE-1685 + +public class CollectionSpaceClientUtils { + + //Maven's base directory -i.e., the one containing the current pom.xml + /** The Constant logger. */ + private static final Logger logger = LoggerFactory.getLogger(CollectionSpaceClientUtils.class); + + protected static final int STATUS_BAD_REQUEST = + Response.Status.BAD_REQUEST.getStatusCode(); + protected static final int STATUS_CREATED = + Response.Status.CREATED.getStatusCode(); + protected static final int STATUS_NOT_FOUND = + Response.Status.NOT_FOUND.getStatusCode(); + protected static final int STATUS_OK = + Response.Status.OK.getStatusCode(); + + /** + * Extract id. + * + * @param res the res + * @return the string + */ + static public String extractId(ClientResponse res) { + MultivaluedMap mvm = res.getMetadata(); + return extractIdFromResponseMetadata(mvm); + } + + /** + * Extract id. + * + * @param res the res + * @return the string + */ + static public String extractId(Response res) { + MultivaluedMap mvm = res.getMetadata(); + return extractIdFromResponseMetadata(mvm); + } + + static protected String extractIdFromResponseMetadata(MultivaluedMap mvm) { + // mvm may return a java.net.URI which complains about casting to String... + String uri = ((List) mvm.get("Location")).get(0).toString(); + if (logger.isDebugEnabled()) { + logger.debug("extractId:uri=" + uri); + } + String[] segments = uri.split("/"); + String id = segments[segments.length - 1]; + if (logger.isDebugEnabled()) { + logger.debug("id=" + id); + } + return id; + } + + /** + * Extract part. + * + * @param input the input + * @param label the label + * @param clazz the clazz + * @return the object + * @throws Exception the exception + */ + static protected Object extractPart(PoxPayloadIn input, String label, Class clazz) + throws Exception { + Object result = null; + PayloadInputPart payloadInputPart = input.getPart(label); + if (payloadInputPart != null) { + result = payloadInputPart.getBody(); + } else if (logger.isWarnEnabled() == true) { + logger.warn("Payload part: " + label + + " is missing from payload: " + input.getName()); + } + return result; + } + + /** + * Extract part. + * + * @param input the input + * @param label the label + * @param clazz the clazz + * @return the object + * @throws Exception the exception + */ + @Deprecated + static public Object extractPart(MultipartInput input, String label, Class clazz) + throws Exception { + Object obj = null; + String partLabel = ""; + List parts = input.getParts(); + if (parts.size() == 0) { + logger.warn("No parts found in multipart body."); + } + if (logger.isDebugEnabled()) { + logger.debug("Parts:"); + for (InputPart part : parts) { + partLabel = part.getHeaders().getFirst("label"); + logger.debug("part = " + partLabel); + } + } + boolean partLabelMatched = false; + for (InputPart part : parts) { + partLabel = part.getHeaders().getFirst("label"); + if (label.equalsIgnoreCase(partLabel)) { + partLabelMatched = true; + if (logger.isDebugEnabled()) { + logger.debug("found part" + partLabel); + } + String partStr = part.getBodyAsString(); + if (partStr == null || partStr.trim().isEmpty()) { + logger.warn("Part '" + label + "' in multipart body is empty."); + } else { + if (logger.isDebugEnabled()) { + logger.debug("extracted part as str=\n" + partStr); + } + obj = part.getBody(clazz, null); + if (logger.isDebugEnabled()) { + logger.debug("extracted part as obj=\n", + objectAsXmlString(obj, clazz)); + } + } + break; + } + } + if (!partLabelMatched) { + logger.warn("Could not find part '" + label + "' in multipart body."); + // In the event that getBodyAsString() or getBody(), above, do *not* + // throw an IOException, but getBody() nonetheless retrieves a null object. + // This *may* be unreachable. + } else if (obj == null) { + logger.warn("Could not extract part '" + label + + "' in multipart body as an object."); + } + return obj; + } + + /** + * Gets the part object. + * + * @param partStr the part str + * @param clazz the clazz + * @return the part object + * @throws JAXBException the jAXB exception + */ + static public Object getPartObject(String partStr, Class clazz) + throws JAXBException { + JAXBContext jc = JAXBContext.newInstance(clazz); + ByteArrayInputStream bais = null; + Object obj = null; + try { + bais = new ByteArrayInputStream(partStr.getBytes()); + Unmarshaller um = jc.createUnmarshaller(); + obj = um.unmarshal(bais); + } finally { + if (bais != null) { + try { + bais.close(); + } catch (Exception e) { + if (logger.isDebugEnabled() == true) { + e.printStackTrace(); + } + } + } + } + return obj; + } + + /** + * Object as xml string. + * + * @param o the o + * @param clazz the clazz + * @return the string + */ + static public String objectAsXmlString(Object o, Class clazz) { + StringWriter sw = new StringWriter(); + try { + JAXBContext jc = JAXBContext.newInstance(clazz); + Marshaller m = jc.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, + Boolean.TRUE); + m.marshal(o, sw); + } catch (Exception e) { + e.printStackTrace(); + } + return sw.toString(); + } + + /** + * getObjectFromFile get object of given class from given file (in classpath) + * @param jaxbClass + * @param fileName of the file to read to construct the object + * @return + * @throws Exception + */ + static public Object getObjectFromFile(Class jaxbClass, String fileName) + throws Exception { + ClassLoader tccl = Thread.currentThread().getContextClassLoader(); + InputStream is = tccl.getResourceAsStream(fileName); + return getObjectFromStream(jaxbClass, is); + } + + /** + * Gets the xml document. + * + * @param fileName the file name + * @return the xml document + * @throws Exception the exception + */ + static public Document getXmlDocument(String fileName) throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + File f = new File(fileName); + if (!f.exists()) { + throw new IllegalArgumentException("test data file " + fileName + " not found!"); + } + // Create the builder and parse the file + return factory.newDocumentBuilder().parse(f); + } + + /** + * Gets the xml document as string. + * + * @param fileName the file name + * @return the xml document as string + * @throws Exception the exception + */ + static public String getXmlDocumentAsString(String fileName) throws Exception { + byte[] b = FileUtils.readFileToByteArray(new File(fileName)); + return new String(b); + } + + /** + * getObjectFromStream get object of given class from given inputstream + * @param jaxbClass + * @param is stream to read to construct the object + * @return + * @throws Exception + */ + static public Object getObjectFromStream(Class jaxbClass, InputStream is) throws Exception { + JAXBContext context = JAXBContext.newInstance(jaxbClass); + Unmarshaller unmarshaller = context.createUnmarshaller(); + //note: setting schema to null will turn validator off + unmarshaller.setSchema(null); + return jaxbClass.cast(unmarshaller.unmarshal(is)); + } +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/CollectionSpaceCommonListPoxProxy.java b/services/client/src/main/java/org/collectionspace/services/client/CollectionSpaceCommonListPoxProxy.java index 6ee3dfd7f..a1f470806 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/CollectionSpaceCommonListPoxProxy.java +++ b/services/client/src/main/java/org/collectionspace/services/client/CollectionSpaceCommonListPoxProxy.java @@ -1,34 +1,34 @@ -package org.collectionspace.services.client; - -import javax.ws.rs.GET; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; - -import org.collectionspace.services.client.workflow.WorkflowClient; -import org.collectionspace.services.jaxb.AbstractCommonList; -import org.jboss.resteasy.client.ClientResponse; - -public interface CollectionSpaceCommonListPoxProxy extends CollectionSpacePoxProxy { - @GET - ClientResponse readList(); - - @Override - @GET - @Produces({"application/xml"}) - ClientResponse readIncludeDeleted( - @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); - - @Override - @GET - @Produces({"application/xml"}) - ClientResponse keywordSearchIncludeDeleted( - @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_KW) String keywords, - @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); - - @Override - @GET - @Produces({ "application/xml" }) - ClientResponse advancedSearchIncludeDeleted( - @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_AS) String whereClause, - @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); -} +package org.collectionspace.services.client; + +import javax.ws.rs.GET; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; + +import org.collectionspace.services.client.workflow.WorkflowClient; +import org.collectionspace.services.jaxb.AbstractCommonList; +import org.jboss.resteasy.client.ClientResponse; + +public interface CollectionSpaceCommonListPoxProxy extends CollectionSpacePoxProxy { + @GET + ClientResponse readList(); + + @Override + @GET + @Produces({"application/xml"}) + ClientResponse readIncludeDeleted( + @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); + + @Override + @GET + @Produces({"application/xml"}) + ClientResponse keywordSearchIncludeDeleted( + @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_KW) String keywords, + @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); + + @Override + @GET + @Produces({ "application/xml" }) + ClientResponse advancedSearchIncludeDeleted( + @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_AS) String whereClause, + @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/CollectionSpacePoxClient.java b/services/client/src/main/java/org/collectionspace/services/client/CollectionSpacePoxClient.java index 79ac9a3fe..676e4ad23 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/CollectionSpacePoxClient.java +++ b/services/client/src/main/java/org/collectionspace/services/client/CollectionSpacePoxClient.java @@ -1,27 +1,27 @@ -package org.collectionspace.services.client; - -import org.collectionspace.services.jaxb.AbstractCommonList; -import org.jboss.resteasy.client.ClientResponse; - -/* - * = List type - * = Payload type - *

= Proxy type - */ -public interface CollectionSpacePoxClient> - extends CollectionSpaceClient { - /* - * Common service calls - */ - - public ClientResponse readIncludeDeleted(String csid, Boolean includeDeleted); - - /* - * GET list with workflow 'deleted' state - */ - public ClientResponse readIncludeDeleted(Boolean includeDeleted); - - public ClientResponse keywordSearchIncludeDeleted(String keywords, Boolean includeDeleted); - - public ClientResponse advancedSearchIncludeDeleted(String whereClause, Boolean includeDeleted); -} +package org.collectionspace.services.client; + +import org.collectionspace.services.jaxb.AbstractCommonList; +import org.jboss.resteasy.client.ClientResponse; + +/* + * = List type + * = Payload type + *

= Proxy type + */ +public interface CollectionSpacePoxClient> + extends CollectionSpaceClient { + /* + * Common service calls + */ + + public ClientResponse readIncludeDeleted(String csid, Boolean includeDeleted); + + /* + * GET list with workflow 'deleted' state + */ + public ClientResponse readIncludeDeleted(Boolean includeDeleted); + + public ClientResponse keywordSearchIncludeDeleted(String keywords, Boolean includeDeleted); + + public ClientResponse advancedSearchIncludeDeleted(String whereClause, Boolean includeDeleted); +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/CollectionSpacePoxProxy.java b/services/client/src/main/java/org/collectionspace/services/client/CollectionSpacePoxProxy.java index 0e760ba4e..5fd88ad33 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/CollectionSpacePoxProxy.java +++ b/services/client/src/main/java/org/collectionspace/services/client/CollectionSpacePoxProxy.java @@ -1,66 +1,66 @@ -package org.collectionspace.services.client; - -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; -import org.jboss.resteasy.client.ClientResponse; - -import org.collectionspace.services.client.workflow.WorkflowClient; -import org.collectionspace.services.jaxb.AbstractCommonList; - -public interface CollectionSpacePoxProxy extends - CollectionSpaceProxy { - - // (C)reate - @POST - ClientResponse create(byte[] payload); - - // (R)ead - @GET - @Path("/{csid}") - ClientResponse read(@PathParam("csid") String csid); - - // (R)ead - @GET - @Path("/{csid}") - ClientResponse readIncludeDeleted( - @PathParam("csid") String csid, - @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); - - // (U)pdate - @PUT - @Path("/{csid}") - ClientResponse update(@PathParam("csid") String csid, byte[] payload); - - // (L)ist non-deleted items - @GET - @Produces({ "application/xml" }) - ClientResponse readIncludeDeleted( - @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); - - /** - * Keyword search. - * - * @param keywords - * keywords on which to search - * @param workflowState - * @return the client response - */ - @GET - @Produces({ "application/xml" }) - ClientResponse keywordSearchIncludeDeleted( - @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_KW) String keywords, - @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); - - @GET - @Produces({ "application/xml" }) - ClientResponse advancedSearchIncludeDeleted( - @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_AS) String whereClause, - @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); - -} +package org.collectionspace.services.client; + +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; +import org.jboss.resteasy.client.ClientResponse; + +import org.collectionspace.services.client.workflow.WorkflowClient; +import org.collectionspace.services.jaxb.AbstractCommonList; + +public interface CollectionSpacePoxProxy extends + CollectionSpaceProxy { + + // (C)reate + @POST + ClientResponse create(byte[] payload); + + // (R)ead + @GET + @Path("/{csid}") + ClientResponse read(@PathParam("csid") String csid); + + // (R)ead + @GET + @Path("/{csid}") + ClientResponse readIncludeDeleted( + @PathParam("csid") String csid, + @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); + + // (U)pdate + @PUT + @Path("/{csid}") + ClientResponse update(@PathParam("csid") String csid, byte[] payload); + + // (L)ist non-deleted items + @GET + @Produces({ "application/xml" }) + ClientResponse readIncludeDeleted( + @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); + + /** + * Keyword search. + * + * @param keywords + * keywords on which to search + * @param workflowState + * @return the client response + */ + @GET + @Produces({ "application/xml" }) + ClientResponse keywordSearchIncludeDeleted( + @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_KW) String keywords, + @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); + + @GET + @Produces({ "application/xml" }) + ClientResponse advancedSearchIncludeDeleted( + @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_AS) String whereClause, + @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); + +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/CollectionSpaceProxy.java b/services/client/src/main/java/org/collectionspace/services/client/CollectionSpaceProxy.java index c9dbdda6e..2ed0b6830 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/CollectionSpaceProxy.java +++ b/services/client/src/main/java/org/collectionspace/services/client/CollectionSpaceProxy.java @@ -1,108 +1,108 @@ -/** - * CollectionSpaceProxy.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.client; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.DELETE; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; - -import org.collectionspace.services.client.workflow.WorkflowClient; -import org.collectionspace.services.common.authorityref.AuthorityRefList; - -import org.jboss.resteasy.client.ClientResponse; - -/** - * The Interface CollectionSpaceProxy. - * FIXME: http://issues.collectionspace.org/browse/CSPACE-1684 - */ -public interface CollectionSpaceProxy { - - //(D)elete - @DELETE - @Path("/{csid}") - ClientResponse delete(@PathParam("csid") String csid); - - // List Authority References - @GET - @Produces({"application/xml"}) - @Path("/{csid}/authorityrefs/") - ClientResponse getAuthorityRefs(@PathParam("csid") String csid); - - @GET - @Produces({"application/xml"}) - @Consumes({"application/xml"}) - @Path("{csid}" + WorkflowClient.SERVICE_PATH) - ClientResponse getWorkflow(@PathParam("csid") String csid); - - @PUT - @Produces({"application/xml"}) - @Consumes({"application/xml"}) - @Path("{csid}" + WorkflowClient.SERVICE_PATH + "/" + "{transition}") - ClientResponse updateWorkflowWithTransition(@PathParam("csid") String csid, @PathParam("transition") String transition); - - /* - * (R)read List operations - */ - - @GET - @Produces({"application/xml"}) - ClientResponse readList(); - - /** - * Read list. - * - * @param pageSize the page size - * @param pageNumber the page number - * @return the client response - */ - @GET - @Produces({"application/xml"}) - ClientResponse readList( - @QueryParam(IClientQueryParams.PAGE_SIZE_PARAM) Long pageSize, - @QueryParam(IClientQueryParams.START_PAGE_PARAM) Long pageNumber); - - /** - * Read list. - * @param sortBy - * - * @param pageSize the page size - * @param pageNumber the page number - * @return the client response - */ - @GET - @Produces({"application/xml"}) - ClientResponse readList( - @QueryParam(IClientQueryParams.ORDER_BY_PARAM) String sortBy, - @QueryParam(IClientQueryParams.PAGE_SIZE_PARAM) Long pageSize, - @QueryParam(IClientQueryParams.START_PAGE_PARAM) Long pageNumber); -} +/** + * CollectionSpaceProxy.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.client; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.DELETE; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; + +import org.collectionspace.services.client.workflow.WorkflowClient; +import org.collectionspace.services.common.authorityref.AuthorityRefList; + +import org.jboss.resteasy.client.ClientResponse; + +/** + * The Interface CollectionSpaceProxy. + * FIXME: http://issues.collectionspace.org/browse/CSPACE-1684 + */ +public interface CollectionSpaceProxy { + + //(D)elete + @DELETE + @Path("/{csid}") + ClientResponse delete(@PathParam("csid") String csid); + + // List Authority References + @GET + @Produces({"application/xml"}) + @Path("/{csid}/authorityrefs/") + ClientResponse getAuthorityRefs(@PathParam("csid") String csid); + + @GET + @Produces({"application/xml"}) + @Consumes({"application/xml"}) + @Path("{csid}" + WorkflowClient.SERVICE_PATH) + ClientResponse getWorkflow(@PathParam("csid") String csid); + + @PUT + @Produces({"application/xml"}) + @Consumes({"application/xml"}) + @Path("{csid}" + WorkflowClient.SERVICE_PATH + "/" + "{transition}") + ClientResponse updateWorkflowWithTransition(@PathParam("csid") String csid, @PathParam("transition") String transition); + + /* + * (R)read List operations + */ + + @GET + @Produces({"application/xml"}) + ClientResponse readList(); + + /** + * Read list. + * + * @param pageSize the page size + * @param pageNumber the page number + * @return the client response + */ + @GET + @Produces({"application/xml"}) + ClientResponse readList( + @QueryParam(IClientQueryParams.PAGE_SIZE_PARAM) Long pageSize, + @QueryParam(IClientQueryParams.START_PAGE_PARAM) Long pageNumber); + + /** + * Read list. + * @param sortBy + * + * @param pageSize the page size + * @param pageNumber the page number + * @return the client response + */ + @GET + @Produces({"application/xml"}) + ClientResponse readList( + @QueryParam(IClientQueryParams.ORDER_BY_PARAM) String sortBy, + @QueryParam(IClientQueryParams.PAGE_SIZE_PARAM) Long pageSize, + @QueryParam(IClientQueryParams.START_PAGE_PARAM) Long pageNumber); +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/IClientQueryParams.java b/services/client/src/main/java/org/collectionspace/services/client/IClientQueryParams.java index 2401c6119..24865448c 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/IClientQueryParams.java +++ b/services/client/src/main/java/org/collectionspace/services/client/IClientQueryParams.java @@ -1,36 +1,36 @@ -/** - * 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 Regents of the University of California - * - * 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.client; - -/** - * IClientQueryParams.java - * - * Specifies contants used as query parameters in client requests to services. - * - * $LastChangedBy: $ - * $LastChangedRevision: $ - */ - -public interface IClientQueryParams { - - public static final String PAGE_SIZE_PARAM = "pgSz"; - public static final String START_PAGE_PARAM = "pgNum"; - public static final String ORDER_BY_PARAM = "sortBy"; - public static final String IMPORT_TIMEOUT_PARAM = "impTimout"; - -} +/** + * 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 Regents of the University of California + * + * 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.client; + +/** + * IClientQueryParams.java + * + * Specifies contants used as query parameters in client requests to services. + * + * $LastChangedBy: $ + * $LastChangedRevision: $ + */ + +public interface IClientQueryParams { + + public static final String PAGE_SIZE_PARAM = "pgSz"; + public static final String START_PAGE_PARAM = "pgNum"; + public static final String ORDER_BY_PARAM = "sortBy"; + public static final String IMPORT_TIMEOUT_PARAM = "impTimout"; + +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/IQueryManager.java b/services/client/src/main/java/org/collectionspace/services/client/IQueryManager.java index 513c443ad..0536a38ed 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/IQueryManager.java +++ b/services/client/src/main/java/org/collectionspace/services/client/IQueryManager.java @@ -1,163 +1,163 @@ -/** - * IQueryManager.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.client; - -public interface IQueryManager { - - final static String SEARCH_GROUP_OPEN = "("; - final static String SEARCH_GROUP_CLOSE = ")"; - final static String SEARCH_TERM_SEPARATOR = " "; - final static String SEARCH_LIKE = " LIKE "; - final static String SEARCH_ILIKE = " ILIKE "; - final static String SEARCH_TYPE_KEYWORDS = "keywords"; - final static String SEARCH_TYPE_KEYWORDS_KW = "kw"; - final static String SEARCH_TYPE_KEYWORDS_AS = "as"; - final static String SEARCH_TYPE_PARTIALTERM = "pt"; - final static String SEARCH_TYPE_DOCTYPE = "doctype"; - final static String SEARCH_TYPE_INVOCATION_MODE = "mode"; - final static String SEARCH_TYPE_INVOCATION = "inv"; - final static String SEARCH_QUALIFIER_AND = SEARCH_TERM_SEPARATOR + "AND" + SEARCH_TERM_SEPARATOR; - final static String SEARCH_QUALIFIER_OR = SEARCH_TERM_SEPARATOR + "OR" + SEARCH_TERM_SEPARATOR; - - // - // Nuxeo pseudo-values (and filters) for special document properties. - // - final static String NUXEO_UUID = "ecm:uuid"; - final static String NUXEO_IS_PROXY = "ecm:isProxy"; - final static String NUXEO_IS_PROXY_FILTER = NUXEO_IS_PROXY + " = 0"; - final static String NUXEO_IS_VERSION = "ecm:isCheckedInVersion"; - final static String NUXEO_IS_VERSION_FILTER = NUXEO_IS_VERSION + " = 0"; - // In the CMIS context, the prefix is nuxeo, not ecm - final static String NUXEO_CMIS_IS_VERSION = "nuxeo:isVersion"; - final static String NUXEO_CMIS_IS_VERSION_FILTER = NUXEO_CMIS_IS_VERSION + " = false"; - - // - // Query params for CMIS queries on the relationship (Relation) table. - // - final static String SEARCH_RELATED_TO_CSID_AS_SUBJECT = "rtSbj"; - final static String SEARCH_RELATED_TO_CSID_AS_OBJECT = "rtObj"; - final static String SEARCH_RELATED_TO_CSID_AS_EITHER = "rtEither"; - final static String SEARCH_RELATED_MATCH_OBJ_DOCTYPES = "rtObjDocTypes"; - final static String SELECT_DOC_TYPE_FIELD = "selectDocType"; - - final static String MARK_RELATED_TO_CSID_AS_SUBJECT = "mkRtSbj"; - // - // Generic CMIS property mapping constants - // - final static String CMIS_OBJECT_ID = "cmis:objectId"; - final static String CMIS_NUXEO_PATHSEGMENT = "nuxeo:pathSegment"; - // - // Nuxeo related CMIS property mapping constants - final static String CMIS_NUXEO_ID = CMIS_OBJECT_ID; - final static String CMIS_NUXEO_NAME = CMIS_NUXEO_PATHSEGMENT; - final static String CMIS_NUXEO_TITLE = "dc:title"; - final static String CMIS_CS_UPDATED_AT = CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA + ":" + CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_AT; - - // CollectionSpace CMIS property mapping constants - final static String CMIS_TARGET_PREFIX = "DOC"; - final static String CMIS_CORESCHEMA_PREFIX = "CORE"; - // Relations CMIS property mapping constants - final static String CMIS_RELATIONS_PREFIX = "REL"; - - final static String CMIS_JOIN_NUXEO_IS_VERSION_FILTER = - IQueryManager.CMIS_TARGET_PREFIX + "." + IQueryManager.NUXEO_CMIS_IS_VERSION_FILTER; - - - final static String CMIS_TARGET_NUXEO_ID = CMIS_TARGET_PREFIX + "." + CMIS_NUXEO_ID; - final static String CMIS_TARGET_CSID = CMIS_TARGET_PREFIX + "." + CMIS_NUXEO_NAME; - final static String CMIS_TARGET_TITLE = CMIS_TARGET_PREFIX + "." + CMIS_NUXEO_TITLE; - final static String CMIS_TARGET_NAME = CMIS_TARGET_PREFIX + "." + CMIS_NUXEO_NAME; - final static String CMIS_TARGET_UPDATED_AT = CMIS_TARGET_PREFIX + "." + CMIS_CS_UPDATED_AT; - - final static String TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM = "ptStartingWildcard"; - final static String MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES = "maxListItemsReturnedLimitOnJdbcQueries"; - final static String JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED = "jdbcQueriesAreTenantIdRestricted"; - - public void execQuery(String queryString); - - public String getDatasourceName(); - - /** - * Creates the where clause from keywords. - * - * @param keywords the keywords - * - * @return the string - */ - public String createWhereClauseFromKeywords(String keywords); - - public String createWhereClauseFromAdvancedSearch(String advancedSearch); - - final static boolean FILTER_EXCLUDE = true; - final static boolean FILTER_INCLUDE = false; - - /** - * Creates a query to filter a qualified (string) field according to a list of string values. - * @param qualifiedField The schema-qualified field to filter on - * @param filterTerms the list of one or more strings to filter on - * @param fExclude If true, will require qualifiedField NOT match the filters strings. - * If false, will require qualifiedField does match one of the filters strings. - * @return queryString - */ - public String createWhereClauseToFilterFromStringList(String qualifiedField, String[] filterTerms, boolean fExclude); - - /** - * Creates the where clause for partial term match. - * - * @param field the qualified field to match on - * @param partialTerm the term to match against - * - * @return the string - */ - public String createWhereClauseForPartialMatch(String dataSourceName, - String repositoryName, - String cspaceInstanceId, - String field, - boolean startingWildcard, - String partialTerm); - - /** - * Creates a filtering where clause from docType, for invocables. - * - * @param schema the schema name for this invocable type - * @param docType the docType - * - * @return the string - */ - public String createWhereClauseForInvocableByDocType(String schema, String docType); - - /** - * Creates a filtering where clause from invocation mode, for invocables. - * - * @param schema the schema name for this invocable type - * @param mode the mode - * - * @return the string - */ - public String createWhereClauseForInvocableByMode(String schema, String mode); - -} +/** + * IQueryManager.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.client; + +public interface IQueryManager { + + final static String SEARCH_GROUP_OPEN = "("; + final static String SEARCH_GROUP_CLOSE = ")"; + final static String SEARCH_TERM_SEPARATOR = " "; + final static String SEARCH_LIKE = " LIKE "; + final static String SEARCH_ILIKE = " ILIKE "; + final static String SEARCH_TYPE_KEYWORDS = "keywords"; + final static String SEARCH_TYPE_KEYWORDS_KW = "kw"; + final static String SEARCH_TYPE_KEYWORDS_AS = "as"; + final static String SEARCH_TYPE_PARTIALTERM = "pt"; + final static String SEARCH_TYPE_DOCTYPE = "doctype"; + final static String SEARCH_TYPE_INVOCATION_MODE = "mode"; + final static String SEARCH_TYPE_INVOCATION = "inv"; + final static String SEARCH_QUALIFIER_AND = SEARCH_TERM_SEPARATOR + "AND" + SEARCH_TERM_SEPARATOR; + final static String SEARCH_QUALIFIER_OR = SEARCH_TERM_SEPARATOR + "OR" + SEARCH_TERM_SEPARATOR; + + // + // Nuxeo pseudo-values (and filters) for special document properties. + // + final static String NUXEO_UUID = "ecm:uuid"; + final static String NUXEO_IS_PROXY = "ecm:isProxy"; + final static String NUXEO_IS_PROXY_FILTER = NUXEO_IS_PROXY + " = 0"; + final static String NUXEO_IS_VERSION = "ecm:isCheckedInVersion"; + final static String NUXEO_IS_VERSION_FILTER = NUXEO_IS_VERSION + " = 0"; + // In the CMIS context, the prefix is nuxeo, not ecm + final static String NUXEO_CMIS_IS_VERSION = "nuxeo:isVersion"; + final static String NUXEO_CMIS_IS_VERSION_FILTER = NUXEO_CMIS_IS_VERSION + " = false"; + + // + // Query params for CMIS queries on the relationship (Relation) table. + // + final static String SEARCH_RELATED_TO_CSID_AS_SUBJECT = "rtSbj"; + final static String SEARCH_RELATED_TO_CSID_AS_OBJECT = "rtObj"; + final static String SEARCH_RELATED_TO_CSID_AS_EITHER = "rtEither"; + final static String SEARCH_RELATED_MATCH_OBJ_DOCTYPES = "rtObjDocTypes"; + final static String SELECT_DOC_TYPE_FIELD = "selectDocType"; + + final static String MARK_RELATED_TO_CSID_AS_SUBJECT = "mkRtSbj"; + // + // Generic CMIS property mapping constants + // + final static String CMIS_OBJECT_ID = "cmis:objectId"; + final static String CMIS_NUXEO_PATHSEGMENT = "nuxeo:pathSegment"; + // + // Nuxeo related CMIS property mapping constants + final static String CMIS_NUXEO_ID = CMIS_OBJECT_ID; + final static String CMIS_NUXEO_NAME = CMIS_NUXEO_PATHSEGMENT; + final static String CMIS_NUXEO_TITLE = "dc:title"; + final static String CMIS_CS_UPDATED_AT = CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA + ":" + CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_AT; + + // CollectionSpace CMIS property mapping constants + final static String CMIS_TARGET_PREFIX = "DOC"; + final static String CMIS_CORESCHEMA_PREFIX = "CORE"; + // Relations CMIS property mapping constants + final static String CMIS_RELATIONS_PREFIX = "REL"; + + final static String CMIS_JOIN_NUXEO_IS_VERSION_FILTER = + IQueryManager.CMIS_TARGET_PREFIX + "." + IQueryManager.NUXEO_CMIS_IS_VERSION_FILTER; + + + final static String CMIS_TARGET_NUXEO_ID = CMIS_TARGET_PREFIX + "." + CMIS_NUXEO_ID; + final static String CMIS_TARGET_CSID = CMIS_TARGET_PREFIX + "." + CMIS_NUXEO_NAME; + final static String CMIS_TARGET_TITLE = CMIS_TARGET_PREFIX + "." + CMIS_NUXEO_TITLE; + final static String CMIS_TARGET_NAME = CMIS_TARGET_PREFIX + "." + CMIS_NUXEO_NAME; + final static String CMIS_TARGET_UPDATED_AT = CMIS_TARGET_PREFIX + "." + CMIS_CS_UPDATED_AT; + + final static String TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM = "ptStartingWildcard"; + final static String MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES = "maxListItemsReturnedLimitOnJdbcQueries"; + final static String JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED = "jdbcQueriesAreTenantIdRestricted"; + + public void execQuery(String queryString); + + public String getDatasourceName(); + + /** + * Creates the where clause from keywords. + * + * @param keywords the keywords + * + * @return the string + */ + public String createWhereClauseFromKeywords(String keywords); + + public String createWhereClauseFromAdvancedSearch(String advancedSearch); + + final static boolean FILTER_EXCLUDE = true; + final static boolean FILTER_INCLUDE = false; + + /** + * Creates a query to filter a qualified (string) field according to a list of string values. + * @param qualifiedField The schema-qualified field to filter on + * @param filterTerms the list of one or more strings to filter on + * @param fExclude If true, will require qualifiedField NOT match the filters strings. + * If false, will require qualifiedField does match one of the filters strings. + * @return queryString + */ + public String createWhereClauseToFilterFromStringList(String qualifiedField, String[] filterTerms, boolean fExclude); + + /** + * Creates the where clause for partial term match. + * + * @param field the qualified field to match on + * @param partialTerm the term to match against + * + * @return the string + */ + public String createWhereClauseForPartialMatch(String dataSourceName, + String repositoryName, + String cspaceInstanceId, + String field, + boolean startingWildcard, + String partialTerm); + + /** + * Creates a filtering where clause from docType, for invocables. + * + * @param schema the schema name for this invocable type + * @param docType the docType + * + * @return the string + */ + public String createWhereClauseForInvocableByDocType(String schema, String docType); + + /** + * Creates a filtering where clause from invocation mode, for invocables. + * + * @param schema the schema name for this invocable type + * @param mode the mode + * + * @return the string + */ + public String createWhereClauseForInvocableByMode(String schema, String mode); + +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/PayloadInputPart.java b/services/client/src/main/java/org/collectionspace/services/client/PayloadInputPart.java index af3b5d721..2892e85c1 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/PayloadInputPart.java +++ b/services/client/src/main/java/org/collectionspace/services/client/PayloadInputPart.java @@ -1,36 +1,36 @@ -package org.collectionspace.services.client; - -import javax.ws.rs.core.MediaType; -import org.dom4j.Element; - -public class PayloadInputPart extends PayloadPart { -// private Element elementBody; - - public PayloadInputPart(String label, Object body) { - super(label, body); - } - - public PayloadInputPart(String label, Object body, Element elementBody) { - super(label, body, elementBody); - } - - public PayloadInputPart(String label, Element elementBody) { - super(label, elementBody); - } - - @Override - public String asXML() { - String result = null; - Object body = getBody(); - if (getElementBody() != null) { - result = getElementBody().asXML(); - } else if (body != null) { - result = PoxPayload.toElement(getBody()).asXML(); - } - return result; - } - - public MediaType getMediaType() { - return MediaType.APPLICATION_XML_TYPE; - } -} +package org.collectionspace.services.client; + +import javax.ws.rs.core.MediaType; +import org.dom4j.Element; + +public class PayloadInputPart extends PayloadPart { +// private Element elementBody; + + public PayloadInputPart(String label, Object body) { + super(label, body); + } + + public PayloadInputPart(String label, Object body, Element elementBody) { + super(label, body, elementBody); + } + + public PayloadInputPart(String label, Element elementBody) { + super(label, elementBody); + } + + @Override + public String asXML() { + String result = null; + Object body = getBody(); + if (getElementBody() != null) { + result = getElementBody().asXML(); + } else if (body != null) { + result = PoxPayload.toElement(getBody()).asXML(); + } + return result; + } + + public MediaType getMediaType() { + return MediaType.APPLICATION_XML_TYPE; + } +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/PayloadOutputPart.java b/services/client/src/main/java/org/collectionspace/services/client/PayloadOutputPart.java index bd8c50caa..9a035c69e 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/PayloadOutputPart.java +++ b/services/client/src/main/java/org/collectionspace/services/client/PayloadOutputPart.java @@ -1,48 +1,48 @@ -package org.collectionspace.services.client; - -import org.dom4j.DocumentException; -import org.dom4j.Element; - -public class PayloadOutputPart extends PayloadPart { - - // - // Constructors - // - public PayloadOutputPart(String label, Object body) { - super(label, body); - } - - PayloadOutputPart(String label, Element elementBody) { - super(label, elementBody); - } - - PayloadOutputPart(String label, String xmlBody) throws DocumentException { - super(label, xmlBody); - } - - PayloadOutputPart(String label, Object body, Element elementBody) { - super(label, body, elementBody); - } - - // - // Utility Methods - // - - @Override - public String asXML() { - String result = null; - - Element elementBody = getElementBody(); - if (elementBody != null) { - result = elementBody.asXML(); - } else { - Object body = getBody(); - if (body != null) { - result = PoxPayload.toElement(body).asXML(); - } - } - - return result; - } - -} +package org.collectionspace.services.client; + +import org.dom4j.DocumentException; +import org.dom4j.Element; + +public class PayloadOutputPart extends PayloadPart { + + // + // Constructors + // + public PayloadOutputPart(String label, Object body) { + super(label, body); + } + + PayloadOutputPart(String label, Element elementBody) { + super(label, elementBody); + } + + PayloadOutputPart(String label, String xmlBody) throws DocumentException { + super(label, xmlBody); + } + + PayloadOutputPart(String label, Object body, Element elementBody) { + super(label, body, elementBody); + } + + // + // Utility Methods + // + + @Override + public String asXML() { + String result = null; + + Element elementBody = getElementBody(); + if (elementBody != null) { + result = elementBody.asXML(); + } else { + Object body = getBody(); + if (body != null) { + result = PoxPayload.toElement(body).asXML(); + } + } + + return result; + } + +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/PayloadPart.java b/services/client/src/main/java/org/collectionspace/services/client/PayloadPart.java index 810c6ba0b..2ba2f68ca 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/PayloadPart.java +++ b/services/client/src/main/java/org/collectionspace/services/client/PayloadPart.java @@ -1,82 +1,82 @@ -package org.collectionspace.services.client; - -import org.dom4j.DocumentException; -import org.dom4j.Element; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class PayloadPart { - protected final Logger logger = LoggerFactory.getLogger(PayloadPart.class); - - private String label; - private Object body; - private Element elementBody; - - public PayloadPart(String label) { - this.label = label; - } - - public PayloadPart(String label, Object body) { - this(label); - this.body = body; - } - - /** - * Instantiates a new payload part by parsing the XML string 'xmlPayload' - * - * @param label the label - * @param xmlPayload the xml payload - * @throws DocumentException the document exception - */ - public PayloadPart(String label, String xmlPayload) throws DocumentException { - this(label); - Element element = PoxPayload.toElement(xmlPayload); - this.elementBody = element; - - } - - public PayloadPart(String label, Object body, Element elementBody) { - this(label, body); - this.elementBody = elementBody; - } - - public PayloadPart(String label, Element elementBody) { - this(label); - this.elementBody = elementBody; - } - - abstract public String asXML(); - - public Element asElement() { - Element result = elementBody; - // if we don't already have an Element, let's try to create one from a JAXB object - if (result == null) { - if (body != null) { - //toElement(body) will return null if not given an JAXB object - result = PoxPayload.toElement(body); - } - } - return result; - } - - public Object getBody() { - Object result = body; - if (result == null) { - body = PoxPayload.toObject(this.getElementBody()); - result = body; - } - return result; - } - - public Element getElementBody() { - return elementBody; - } - - public void setLabel(String label) { - this.label = label; - } - - public String getLabel() { - return this.label; - } -} +package org.collectionspace.services.client; + +import org.dom4j.DocumentException; +import org.dom4j.Element; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class PayloadPart { + protected final Logger logger = LoggerFactory.getLogger(PayloadPart.class); + + private String label; + private Object body; + private Element elementBody; + + public PayloadPart(String label) { + this.label = label; + } + + public PayloadPart(String label, Object body) { + this(label); + this.body = body; + } + + /** + * Instantiates a new payload part by parsing the XML string 'xmlPayload' + * + * @param label the label + * @param xmlPayload the xml payload + * @throws DocumentException the document exception + */ + public PayloadPart(String label, String xmlPayload) throws DocumentException { + this(label); + Element element = PoxPayload.toElement(xmlPayload); + this.elementBody = element; + + } + + public PayloadPart(String label, Object body, Element elementBody) { + this(label, body); + this.elementBody = elementBody; + } + + public PayloadPart(String label, Element elementBody) { + this(label); + this.elementBody = elementBody; + } + + abstract public String asXML(); + + public Element asElement() { + Element result = elementBody; + // if we don't already have an Element, let's try to create one from a JAXB object + if (result == null) { + if (body != null) { + //toElement(body) will return null if not given an JAXB object + result = PoxPayload.toElement(body); + } + } + return result; + } + + public Object getBody() { + Object result = body; + if (result == null) { + body = PoxPayload.toObject(this.getElementBody()); + result = body; + } + return result; + } + + public Element getElementBody() { + return elementBody; + } + + public void setLabel(String label) { + this.label = label; + } + + public String getLabel() { + return this.label; + } +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/PoxPayload.java b/services/client/src/main/java/org/collectionspace/services/client/PoxPayload.java index 1d41669a0..e342d5ba4 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/PoxPayload.java +++ b/services/client/src/main/java/org/collectionspace/services/client/PoxPayload.java @@ -1,309 +1,309 @@ -package org.collectionspace.services.client; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.stream.StreamSource; - -import com.sun.xml.bind.api.impl.NameConverter; -import org.apache.commons.io.FileUtils; - -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.Namespace; -import org.dom4j.io.SAXReader; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -// TODO: Auto-generated Javadoc -/** - * The Class PoxPayload. - * - * @param the generic type - */ -public abstract class PoxPayload { - - /** The Constant logger. */ - protected static final Logger logger = LoggerFactory.getLogger(PayloadPart.class); - - /** The xml text. */ - private String xmlPayload; - - private Document domDocument; - - /** The payload name. */ - private String payloadName; - - // The list of POX parts contained in the xmlText payload - /** The parts. */ - private List parts = new ArrayList(); - - /** - * Instantiates a new pox payload. - */ - protected PoxPayload() { - //empty - } - - final protected void setPayloadName(String name) { - this.payloadName = name; - } - - private void setDomDocument(Document dom) throws DocumentException { - this.domDocument = dom; - String label = domDocument.getRootElement().getName(); - if (label != null) { - this.payloadName = label; - } else if (logger.isWarnEnabled() == true) { - logger.warn("Incoming message payload is missing a name/label."); - logger.warn(this.xmlPayload); - } - parseParts(); - } - - /** - * Instantiates a new PoxPayload by parsing the payload into a DOM4j - * Document instance - * - * @param payloadName the payload name - */ - protected PoxPayload(String xmlPayload) throws DocumentException { - this.xmlPayload = xmlPayload; - SAXReader reader = new SAXReader(); - Document dom = reader.read(new StringReader(xmlPayload)); - setDomDocument(dom); - } - - /** - * Instantiates a new payload, saves the original xml, creates a DOM and parses it into parts - * - * @param file the file - * @throws DocumentException the document exception - * @throws IOException Signals that an I/O exception has occurred. - */ - protected PoxPayload(File file) throws DocumentException, IOException { - this.xmlPayload = FileUtils.readFileToString(file); - SAXReader reader = new SAXReader(); - Document dom = reader.read(file); - setDomDocument(dom); - } - - /** - * Creates the part -either an PayloadOutputPart or a PayloadInputPart - * - * @param label the part label - * @param jaxbObject the JAXB object - * @param element the DOM4j element - * @return the pT - */ - abstract protected PT createPart(String label, Object jaxbObject, Element element); - - /** - * Creates the part -either an PayloadOutputPart or a PayloadInputPart - * - * @param label the part label - * @param element the DOM4j element - * @return the pT - */ - abstract protected PT createPart(String label, Element element); - - /** - * Parse the DOM object into schema parts. - * - * @throws DocumentException the document exception - */ - protected void parseParts() throws DocumentException { - Iterator it = getDOMDocument().getRootElement().elementIterator(); - PT payloadPart = null; - while (it.hasNext() == true) { - Element element = (Element) it.next(); - String label = element.getName(); - Object jaxbObject = PoxPayload.toObject(element); - if (jaxbObject != null) { - payloadPart = createPart(label, jaxbObject, element); - } else { - payloadPart = createPart(label, element); - } - if (payloadPart != null) { - this.addPart(payloadPart); - } - } - } - - /** - * Gets the name of the payload. - * - * @return the name - */ - public String getName() { - return payloadName; - } - - /** - * Gets the DOM object that we created at init time. This should never be null; - * - * @return the dOM document - */ - public Document getDOMDocument() { - return this.domDocument; - } - - /** - * Gets the xml text. - * - * @return the xml text - */ - public String getXmlPayload() { - return xmlPayload; - } - - /** - * Gets the POX part with name match 'label'. - * - * @param label the label - * @return the part - */ - public PT getPart(String label) { - PT result = null; - if (parts != null) { - Iterator it = parts.iterator(); - while (it.hasNext() == true) { - PT part = it.next(); - if (part.getLabel().equalsIgnoreCase(label) == true) { - result = part; - break; - } - } - } - return result; - } - - /** - * Gets a list of the POX parts. - * - * @return the parts - */ - public List getParts() { - return parts; - } - - /** - * Adds a POX part to the list of existing parts with the label 'label'. - * - * @param label the label - * @param entity the entity - * @return the pT - */ - public PT addPart(String label, PT entity) { - parts.add(entity); - return entity; - } - - /** - * Adds a POX part -assuming the part already has a label name. - * - * @param entity the entity - * @return the pT - */ - public PT addPart(PT entity) { - parts.add(entity); - return entity; - } - - /** - * Gets the Java package name from the specified namespace. This method - * assumes the Namespace is a xjc (JAXB compiler) generate namespace from - * which we can extract the Java package name. - * - * @param namespace the namespace - * @return the Java package name - */ - private static String getPackage(Namespace namespace) { - NameConverter nc = NameConverter.standard; - String namespaceURI = namespace.getURI(); - return nc.toPackageName(namespaceURI); - } - - /** - * Attempts to marshal a DOM4j element (for a part) into an instance of a JAXB object - * - * @param elementInput the element input - * @return the object - */ - public static Object toObject(Element elementInput) { - Object result = null; - try { - Namespace namespace = elementInput.getNamespace(); - String thePackage = getPackage(namespace); - JAXBContext jc = JAXBContext.newInstance(thePackage); - Unmarshaller um = jc.createUnmarshaller(); - result = um.unmarshal( - new StreamSource(new StringReader(elementInput.asXML()))); - } catch (Exception e) { - if (logger.isTraceEnabled() == true) { - logger.trace(e.getMessage()); - } - } - - return result; - } - - /** - * Attempts to unmarshal a JAXB object (for a part) to a DOM4j element. - * - * @param jaxbObject the jaxb object - * @return the element - */ - public static Element toElement(Object jaxbObject) { - Element result = null; - String text = null; - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try { - String thePackage = jaxbObject.getClass().getPackage().getName(); - if (thePackage.equals(JAXBElement.class.getPackage().getName())) { - JAXBElement jaxbElement = (JAXBElement)jaxbObject; - thePackage = jaxbElement.getValue().getClass().getPackage().getName(); - } - JAXBContext jc = JAXBContext.newInstance(thePackage); - //Create marshaller - Marshaller m = jc.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false); - //Marshal object into file. - m.marshal(jaxbObject, outputStream); - text = outputStream.toString("UTF8"); - - Document doc = DocumentHelper.parseText(text); - result = doc.getRootElement(); //FIXME: REM - call .detach() to free the element - } catch (Exception e) { - e.printStackTrace(); //FIXME: REM - Please use proper logger.isWarning() statement - } - - return result; - } - - /** - * Attempts to unmarshal a JAXB object (for a part) to a DOM4j element. - * - * @param jaxbObject the jaxb object - * @return the element - */ - public static Element toElement(String xmlPayload) throws DocumentException { - Element result = null; - Document doc = DocumentHelper.parseText(xmlPayload); - result = doc.getRootElement(); //FIXME: REM - .detach(); - return result; - } - - -} +package org.collectionspace.services.client; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; + +import com.sun.xml.bind.api.impl.NameConverter; +import org.apache.commons.io.FileUtils; + +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.DocumentHelper; +import org.dom4j.Element; +import org.dom4j.Namespace; +import org.dom4j.io.SAXReader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +// TODO: Auto-generated Javadoc +/** + * The Class PoxPayload. + * + * @param the generic type + */ +public abstract class PoxPayload { + + /** The Constant logger. */ + protected static final Logger logger = LoggerFactory.getLogger(PayloadPart.class); + + /** The xml text. */ + private String xmlPayload; + + private Document domDocument; + + /** The payload name. */ + private String payloadName; + + // The list of POX parts contained in the xmlText payload + /** The parts. */ + private List parts = new ArrayList(); + + /** + * Instantiates a new pox payload. + */ + protected PoxPayload() { + //empty + } + + final protected void setPayloadName(String name) { + this.payloadName = name; + } + + private void setDomDocument(Document dom) throws DocumentException { + this.domDocument = dom; + String label = domDocument.getRootElement().getName(); + if (label != null) { + this.payloadName = label; + } else if (logger.isWarnEnabled() == true) { + logger.warn("Incoming message payload is missing a name/label."); + logger.warn(this.xmlPayload); + } + parseParts(); + } + + /** + * Instantiates a new PoxPayload by parsing the payload into a DOM4j + * Document instance + * + * @param payloadName the payload name + */ + protected PoxPayload(String xmlPayload) throws DocumentException { + this.xmlPayload = xmlPayload; + SAXReader reader = new SAXReader(); + Document dom = reader.read(new StringReader(xmlPayload)); + setDomDocument(dom); + } + + /** + * Instantiates a new payload, saves the original xml, creates a DOM and parses it into parts + * + * @param file the file + * @throws DocumentException the document exception + * @throws IOException Signals that an I/O exception has occurred. + */ + protected PoxPayload(File file) throws DocumentException, IOException { + this.xmlPayload = FileUtils.readFileToString(file); + SAXReader reader = new SAXReader(); + Document dom = reader.read(file); + setDomDocument(dom); + } + + /** + * Creates the part -either an PayloadOutputPart or a PayloadInputPart + * + * @param label the part label + * @param jaxbObject the JAXB object + * @param element the DOM4j element + * @return the pT + */ + abstract protected PT createPart(String label, Object jaxbObject, Element element); + + /** + * Creates the part -either an PayloadOutputPart or a PayloadInputPart + * + * @param label the part label + * @param element the DOM4j element + * @return the pT + */ + abstract protected PT createPart(String label, Element element); + + /** + * Parse the DOM object into schema parts. + * + * @throws DocumentException the document exception + */ + protected void parseParts() throws DocumentException { + Iterator it = getDOMDocument().getRootElement().elementIterator(); + PT payloadPart = null; + while (it.hasNext() == true) { + Element element = (Element) it.next(); + String label = element.getName(); + Object jaxbObject = PoxPayload.toObject(element); + if (jaxbObject != null) { + payloadPart = createPart(label, jaxbObject, element); + } else { + payloadPart = createPart(label, element); + } + if (payloadPart != null) { + this.addPart(payloadPart); + } + } + } + + /** + * Gets the name of the payload. + * + * @return the name + */ + public String getName() { + return payloadName; + } + + /** + * Gets the DOM object that we created at init time. This should never be null; + * + * @return the dOM document + */ + public Document getDOMDocument() { + return this.domDocument; + } + + /** + * Gets the xml text. + * + * @return the xml text + */ + public String getXmlPayload() { + return xmlPayload; + } + + /** + * Gets the POX part with name match 'label'. + * + * @param label the label + * @return the part + */ + public PT getPart(String label) { + PT result = null; + if (parts != null) { + Iterator it = parts.iterator(); + while (it.hasNext() == true) { + PT part = it.next(); + if (part.getLabel().equalsIgnoreCase(label) == true) { + result = part; + break; + } + } + } + return result; + } + + /** + * Gets a list of the POX parts. + * + * @return the parts + */ + public List getParts() { + return parts; + } + + /** + * Adds a POX part to the list of existing parts with the label 'label'. + * + * @param label the label + * @param entity the entity + * @return the pT + */ + public PT addPart(String label, PT entity) { + parts.add(entity); + return entity; + } + + /** + * Adds a POX part -assuming the part already has a label name. + * + * @param entity the entity + * @return the pT + */ + public PT addPart(PT entity) { + parts.add(entity); + return entity; + } + + /** + * Gets the Java package name from the specified namespace. This method + * assumes the Namespace is a xjc (JAXB compiler) generate namespace from + * which we can extract the Java package name. + * + * @param namespace the namespace + * @return the Java package name + */ + private static String getPackage(Namespace namespace) { + NameConverter nc = NameConverter.standard; + String namespaceURI = namespace.getURI(); + return nc.toPackageName(namespaceURI); + } + + /** + * Attempts to marshal a DOM4j element (for a part) into an instance of a JAXB object + * + * @param elementInput the element input + * @return the object + */ + public static Object toObject(Element elementInput) { + Object result = null; + try { + Namespace namespace = elementInput.getNamespace(); + String thePackage = getPackage(namespace); + JAXBContext jc = JAXBContext.newInstance(thePackage); + Unmarshaller um = jc.createUnmarshaller(); + result = um.unmarshal( + new StreamSource(new StringReader(elementInput.asXML()))); + } catch (Exception e) { + if (logger.isTraceEnabled() == true) { + logger.trace(e.getMessage()); + } + } + + return result; + } + + /** + * Attempts to unmarshal a JAXB object (for a part) to a DOM4j element. + * + * @param jaxbObject the jaxb object + * @return the element + */ + public static Element toElement(Object jaxbObject) { + Element result = null; + String text = null; + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try { + String thePackage = jaxbObject.getClass().getPackage().getName(); + if (thePackage.equals(JAXBElement.class.getPackage().getName())) { + JAXBElement jaxbElement = (JAXBElement)jaxbObject; + thePackage = jaxbElement.getValue().getClass().getPackage().getName(); + } + JAXBContext jc = JAXBContext.newInstance(thePackage); + //Create marshaller + Marshaller m = jc.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false); + //Marshal object into file. + m.marshal(jaxbObject, outputStream); + text = outputStream.toString("UTF8"); + + Document doc = DocumentHelper.parseText(text); + result = doc.getRootElement(); //FIXME: REM - call .detach() to free the element + } catch (Exception e) { + e.printStackTrace(); //FIXME: REM - Please use proper logger.isWarning() statement + } + + return result; + } + + /** + * Attempts to unmarshal a JAXB object (for a part) to a DOM4j element. + * + * @param jaxbObject the jaxb object + * @return the element + */ + public static Element toElement(String xmlPayload) throws DocumentException { + Element result = null; + Document doc = DocumentHelper.parseText(xmlPayload); + result = doc.getRootElement(); //FIXME: REM - .detach(); + return result; + } + + +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/PoxPayloadIn.java b/services/client/src/main/java/org/collectionspace/services/client/PoxPayloadIn.java index e887e9886..65c3186eb 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/PoxPayloadIn.java +++ b/services/client/src/main/java/org/collectionspace/services/client/PoxPayloadIn.java @@ -1,80 +1,80 @@ -package org.collectionspace.services.client; - -//import java.io.ByteArrayInputStream; //FIXME: REM - Remove these unneeded import statements -//import java.io.InputStream; -//import java.io.Reader; -//import java.io.StringReader; -//import java.util.Iterator; -//import java.util.List; - -//import javax.xml.transform.Source; -//import javax.xml.transform.stream.StreamSource; - -//import org.dom4j.Attribute; -//import org.dom4j.Document; -import java.io.File; -import java.io.IOException; - -import org.dom4j.DocumentException; -import org.dom4j.Element; -//import org.dom4j.Namespace; -//import org.dom4j.io.SAXReader; -//import org.xml.sax.InputSource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PoxPayloadIn extends PoxPayload { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - public PoxPayloadIn(String payloadName, Object jaxbObject, String partLabel) { - setPayloadName(payloadName); - PayloadInputPart inputPart = createPart(partLabel, jaxbObject, null); - this.addPart(inputPart); - } - - /* - * Parse the POX 'xmlPayload' into individual parts. Each part is saved - * as a DOM4j Element and, if possible, a JAXB object instance as well. - */ - public PoxPayloadIn(String xmlPayload) throws DocumentException { - super(xmlPayload); - if (logger.isTraceEnabled() == true) { - logger.trace("\n\n>>>> Payload In : BEGIN >>>>\n" + - xmlPayload + - "\n>>>> Payload In : END >>>>\n"); - } - } - - /** - * Instantiates a new PoxPayloadIn, saves the xml, creates a DOM, and parses the parts. - * - * @param file the file - * @throws DocumentException the document exception - * @throws IOException Signals that an I/O exception has occurred. - */ - public PoxPayloadIn(File file) throws DocumentException, IOException { - super(file); - } - - /* (non-Javadoc) - * @see org.collectionspace.services.client.PoxPayload#createPart(java.lang.String, java.lang.Object, org.dom4j.Element) - * - * We need this method because the generic base class has no way of calling our constructor. - */ - @Override - protected PayloadInputPart createPart(String label, Object jaxbObject, Element element) { - return new PayloadInputPart(label, jaxbObject, element); - } - - /* (non-Javadoc) - * @see org.collectionspace.services.client.PoxPayload#createPart(java.lang.String, org.dom4j.Element) - * - * We need this method because the generic base class has no way of calling our constructor. - */ - @Override - protected PayloadInputPart createPart(String label, Element element) { - return new PayloadInputPart(label, element); - } - -} +package org.collectionspace.services.client; + +//import java.io.ByteArrayInputStream; //FIXME: REM - Remove these unneeded import statements +//import java.io.InputStream; +//import java.io.Reader; +//import java.io.StringReader; +//import java.util.Iterator; +//import java.util.List; + +//import javax.xml.transform.Source; +//import javax.xml.transform.stream.StreamSource; + +//import org.dom4j.Attribute; +//import org.dom4j.Document; +import java.io.File; +import java.io.IOException; + +import org.dom4j.DocumentException; +import org.dom4j.Element; +//import org.dom4j.Namespace; +//import org.dom4j.io.SAXReader; +//import org.xml.sax.InputSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PoxPayloadIn extends PoxPayload { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + public PoxPayloadIn(String payloadName, Object jaxbObject, String partLabel) { + setPayloadName(payloadName); + PayloadInputPart inputPart = createPart(partLabel, jaxbObject, null); + this.addPart(inputPart); + } + + /* + * Parse the POX 'xmlPayload' into individual parts. Each part is saved + * as a DOM4j Element and, if possible, a JAXB object instance as well. + */ + public PoxPayloadIn(String xmlPayload) throws DocumentException { + super(xmlPayload); + if (logger.isTraceEnabled() == true) { + logger.trace("\n\n>>>> Payload In : BEGIN >>>>\n" + + xmlPayload + + "\n>>>> Payload In : END >>>>\n"); + } + } + + /** + * Instantiates a new PoxPayloadIn, saves the xml, creates a DOM, and parses the parts. + * + * @param file the file + * @throws DocumentException the document exception + * @throws IOException Signals that an I/O exception has occurred. + */ + public PoxPayloadIn(File file) throws DocumentException, IOException { + super(file); + } + + /* (non-Javadoc) + * @see org.collectionspace.services.client.PoxPayload#createPart(java.lang.String, java.lang.Object, org.dom4j.Element) + * + * We need this method because the generic base class has no way of calling our constructor. + */ + @Override + protected PayloadInputPart createPart(String label, Object jaxbObject, Element element) { + return new PayloadInputPart(label, jaxbObject, element); + } + + /* (non-Javadoc) + * @see org.collectionspace.services.client.PoxPayload#createPart(java.lang.String, org.dom4j.Element) + * + * We need this method because the generic base class has no way of calling our constructor. + */ + @Override + protected PayloadInputPart createPart(String label, Element element) { + return new PayloadInputPart(label, element); + } + +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/PoxPayloadOut.java b/services/client/src/main/java/org/collectionspace/services/client/PoxPayloadOut.java index eca3df2c7..8cd0b4d32 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/PoxPayloadOut.java +++ b/services/client/src/main/java/org/collectionspace/services/client/PoxPayloadOut.java @@ -1,184 +1,184 @@ -package org.collectionspace.services.client; - -import javax.ws.rs.core.MediaType; - -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.Iterator; - -// TODO: Auto-generated Javadoc -/** - * The Class PoxPayloadOut. - */ -public class PoxPayloadOut extends PoxPayload { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - /** - * Instantiates a new pox payload out. - * - * @param payloadName the payload name - * @throws DocumentException the document exception - */ - public PoxPayloadOut(String payloadName) { - super(); - setPayloadName(payloadName); - } - - public PoxPayloadOut(byte[] xmlPayload) throws DocumentException { - super(new String(xmlPayload)); - } - - /** - * Instantiates a new PoxPayloadOut, saves the xml, creates a DOM, and parses the parts. - * - * @param file the file - * @throws DocumentException the document exception - * @throws IOException Signals that an I/O exception has occurred. - */ - protected PoxPayloadOut(File file) throws DocumentException, IOException { - super(file); - } - - /* (non-Javadoc) - * @see org.collectionspace.services.client.PoxPayload#createPart(java.lang.String, java.lang.Object, org.dom4j.Element) - * - * We need this method because the generic base class has no way of calling our constructor. - */ - @Override - protected PayloadOutputPart createPart(String label, Object jaxbObject, Element element) { - return new PayloadOutputPart(label, jaxbObject, element); - } - - /* (non-Javadoc) - * @see org.collectionspace.services.client.PoxPayload#createPart(java.lang.String, org.dom4j.Element) - * - * We need this method because the generic base class has no way of calling our constructor. - */ - @Override - protected PayloadOutputPart createPart(String label, Element element) { - return new PayloadOutputPart(label, element); - } - - /** - * Creates and returns an XML string representation of ourself. - * - * @return the string - */ - public String toXML() { - String result = null; - Document document = DocumentHelper.createDocument(); - document.setXMLEncoding("UTF-8"); - document.setName(getName()); - Element root = document.addElement( "document" ); - root.addAttribute("name", getName()); - - Iterator it = getParts().iterator(); - while (it.hasNext() == true) { - PayloadOutputPart outPart = it.next(); - Element element = outPart.asElement(); - if (element != null) { - root.add(element.detach()); - } else { - //Add if (logger.isTraceEnabled() == true) logger.trace("Output part: " + outPart.getLabel() + " was empty."); - } - } - result = document.asXML(); - - if (logger.isTraceEnabled() == true) { - logger.trace("\n\n<<<< Payload Out : BEGIN <<<<\n" + - result + - "\n<<<< Payload Out : END <<<<\n"); - } - - return result; - } - - /** - * Adds the part. - * - * @param entity the entity - * @param mediaType the media type - * @return the payload output part - */ - @Deprecated - public PayloadOutputPart addPart(Object entity, MediaType mediaType) { - PayloadOutputPart result = addPart("unlabelled", entity); - return result; - } - - @Deprecated - public PayloadOutputPart addPart(String xmlPayload, MediaType mediaType) throws DocumentException { - PayloadOutputPart result = addPart("unlabelled", xmlPayload); - return result; - } - - - /** - * Adds a DOM4j Element part. - * - * @param label the label - * @param elementBody the element body - * @return the payload output part - */ - public PayloadOutputPart addPart(String label, Element elementBody) { - PayloadOutputPart result = new PayloadOutputPart(label, elementBody); - getParts().add(result); - return result; - } - - /** - * Adds a DOM4j Element part. - * - * @param label the label - * @param elementBody the element body - * @return the payload output part - */ - public PayloadOutputPart addPart(String label, String xmlBody) throws DocumentException { - PayloadOutputPart result = new PayloadOutputPart(label, xmlBody); - getParts().add(result); - return result; - } - - - /** - * Adds a JAXB object part. - * - * @param label the label - * @param entity the entity - * @return the payload output part - */ - public PayloadOutputPart addPart(String label, Object entity) { - PayloadOutputPart result = new PayloadOutputPart(label, entity); - getParts().add(result); - return result; - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - * This method calls our "toXML()" method to return an XML representation of ourself. - */ - @Override - public String toString() { - return toXML(); - } - - public byte[] getBytes() { - byte[] result = null; - try { - result = toString().getBytes("UTF8"); - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); //FIXME: REM - Add proper logging statement here - } - return result; - } -} +package org.collectionspace.services.client; + +import javax.ws.rs.core.MediaType; + +import org.dom4j.Document; +import org.dom4j.DocumentException; +import org.dom4j.DocumentHelper; +import org.dom4j.Element; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.Iterator; + +// TODO: Auto-generated Javadoc +/** + * The Class PoxPayloadOut. + */ +public class PoxPayloadOut extends PoxPayload { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + /** + * Instantiates a new pox payload out. + * + * @param payloadName the payload name + * @throws DocumentException the document exception + */ + public PoxPayloadOut(String payloadName) { + super(); + setPayloadName(payloadName); + } + + public PoxPayloadOut(byte[] xmlPayload) throws DocumentException { + super(new String(xmlPayload)); + } + + /** + * Instantiates a new PoxPayloadOut, saves the xml, creates a DOM, and parses the parts. + * + * @param file the file + * @throws DocumentException the document exception + * @throws IOException Signals that an I/O exception has occurred. + */ + protected PoxPayloadOut(File file) throws DocumentException, IOException { + super(file); + } + + /* (non-Javadoc) + * @see org.collectionspace.services.client.PoxPayload#createPart(java.lang.String, java.lang.Object, org.dom4j.Element) + * + * We need this method because the generic base class has no way of calling our constructor. + */ + @Override + protected PayloadOutputPart createPart(String label, Object jaxbObject, Element element) { + return new PayloadOutputPart(label, jaxbObject, element); + } + + /* (non-Javadoc) + * @see org.collectionspace.services.client.PoxPayload#createPart(java.lang.String, org.dom4j.Element) + * + * We need this method because the generic base class has no way of calling our constructor. + */ + @Override + protected PayloadOutputPart createPart(String label, Element element) { + return new PayloadOutputPart(label, element); + } + + /** + * Creates and returns an XML string representation of ourself. + * + * @return the string + */ + public String toXML() { + String result = null; + Document document = DocumentHelper.createDocument(); + document.setXMLEncoding("UTF-8"); + document.setName(getName()); + Element root = document.addElement( "document" ); + root.addAttribute("name", getName()); + + Iterator it = getParts().iterator(); + while (it.hasNext() == true) { + PayloadOutputPart outPart = it.next(); + Element element = outPart.asElement(); + if (element != null) { + root.add(element.detach()); + } else { + //Add if (logger.isTraceEnabled() == true) logger.trace("Output part: " + outPart.getLabel() + " was empty."); + } + } + result = document.asXML(); + + if (logger.isTraceEnabled() == true) { + logger.trace("\n\n<<<< Payload Out : BEGIN <<<<\n" + + result + + "\n<<<< Payload Out : END <<<<\n"); + } + + return result; + } + + /** + * Adds the part. + * + * @param entity the entity + * @param mediaType the media type + * @return the payload output part + */ + @Deprecated + public PayloadOutputPart addPart(Object entity, MediaType mediaType) { + PayloadOutputPart result = addPart("unlabelled", entity); + return result; + } + + @Deprecated + public PayloadOutputPart addPart(String xmlPayload, MediaType mediaType) throws DocumentException { + PayloadOutputPart result = addPart("unlabelled", xmlPayload); + return result; + } + + + /** + * Adds a DOM4j Element part. + * + * @param label the label + * @param elementBody the element body + * @return the payload output part + */ + public PayloadOutputPart addPart(String label, Element elementBody) { + PayloadOutputPart result = new PayloadOutputPart(label, elementBody); + getParts().add(result); + return result; + } + + /** + * Adds a DOM4j Element part. + * + * @param label the label + * @param elementBody the element body + * @return the payload output part + */ + public PayloadOutputPart addPart(String label, String xmlBody) throws DocumentException { + PayloadOutputPart result = new PayloadOutputPart(label, xmlBody); + getParts().add(result); + return result; + } + + + /** + * Adds a JAXB object part. + * + * @param label the label + * @param entity the entity + * @return the payload output part + */ + public PayloadOutputPart addPart(String label, Object entity) { + PayloadOutputPart result = new PayloadOutputPart(label, entity); + getParts().add(result); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + * This method calls our "toXML()" method to return an XML representation of ourself. + */ + @Override + public String toString() { + return toXML(); + } + + public byte[] getBytes() { + byte[] result = null; + try { + result = toString().getBytes("UTF8"); + } catch (UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); //FIXME: REM - Add proper logging statement here + } + return result; + } +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/Profiler.java b/services/client/src/main/java/org/collectionspace/services/client/Profiler.java index 91554eac9..266eb8b74 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/Profiler.java +++ b/services/client/src/main/java/org/collectionspace/services/client/Profiler.java @@ -1,299 +1,299 @@ -/** - * 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.client; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Profiler.java - * - * Simple utility to store and report performance metrics. - * - * Records start and stop times, and elapsed and cumulative timings; - * writes performance-related log times. - * - * $LastChangedRevision: $ - * $LastChangedDate: $ - * - */ -public class Profiler { - - /** The level of indentation. */ - private int messageIndent = 0; - /** The indentation character(s) */ - private static String INDENT = "\t"; - /** The message prefix. */ - private String messagePrefix = ""; - /** The separator between the message prefix and the message. **/ - final static String PREFIX_SEPARATOR = ":"; - /** The start time. */ - private long startTime = 0; - /** The stop time. */ - private long stopTime = 0; - /** The segment time. */ - private long elapsedTime = 0; - /** The cumulative time. */ - private long cumulativeTime = 0; - /** The profiler logger. */ - private static String DEFAULT_LOG4J_CATEGORY = "perf.collectionspace"; - private static Logger profileLogger = LoggerFactory.getLogger(DEFAULT_LOG4J_CATEGORY); - - /** - * private default constructor. - */ - private Profiler() { - //empty default constructor - } - - /** - * Instantiates a new profiler. - * - * @param theObject a class whose name is to be logged. - */ - public Profiler(Object theObject) { - this(theObject, 0); - } - - /** - * Instantiates a new profiler. - * - * @param theObject a class whose name is to be logged. - * @param messageIndent the level of indentation for log messages. - */ - public Profiler(Object theObject, int messageIndent) { - init(objectName(theObject), messageIndent); - } - - /** - * Instantiates a new profiler. - * - * @param messagePrefix the message prefix to appear in log messages. - * @param messageIndent the level of indentation for log messages. - */ - public Profiler(String messagePrefix, int messageIndent) { - init(messagePrefix, messageIndent); - } - - private void init(String messagePrefix, int messageIndent) { - this.setMessagePrefix(messagePrefix); - this.setMessageIndent(messageIndent); - } - - /** - * Stores and logs the start time. - * - * Logs using a default message. - */ - public void start() { - start(defaultStartMessage()); - } - - /** - * Stores and logs the start time. - * - * @param msg the message to log. - */ - public void start(String msg) { - log(msg); - setStartTime(currentTime()); - } - - private void stopTimer() { - setStopTime(currentTime()); - setElapsedTime(getStopTime() - getStartTime()); - addToCumulativeTime(getElapsedTime()); - } - - /** - * Stores and logs the stop time, and the elapsed and cumulative timings - * from one or more cycles of start and stop. - * - * Logs using a default message. - */ - public void stop() { - stopTimer(); - log(defaultStopMessage()); - } - - /** - * Stores and logs the stop time, and the elapsed and cumulative timings, - * from one or more cycles of start and stop. - * - * @param msg the message to log. - */ - public void stop(String msg) { - stopTimer(); - log(msg); - } - - public long getStartTime() { - return this.startTime; - } - - public long getStopTime() { - return this.stopTime; - } - - public long getElapsedTime() { - return this.elapsedTime; - } - - public long getCumulativeTime() { - return this.cumulativeTime; - } - - /** - * Resets the start and stop time, and the elapsed and cumulative timings. - */ - public void reset() { - setStartTime(0); - setStopTime(0); - setElapsedTime(0); - setCumulativeTime(0); - } - - /** - * Writes a message to a log entry. The message will - * be formatted, using current settings for indentation, - * prefix, etc. before being written. - * - * @param msg the message to be written to a log entry. - */ - public void log(String msg) { - if (getLogger().isTraceEnabled()) { - getLogger().trace(formatLogMessage(msg)); - } - } - - /** - * Writes a message to a log entry, - * - * @param msg the message to write to a log entry. - * @param formatMsg true if the message is to be formatted; - * false if it is not to be formatted. - */ - public void log(String msg, boolean formatMsg) { - if (getLogger().isTraceEnabled()) { - if (formatMsg) { - getLogger().trace(formatLogMessage(msg)); - } else { - getLogger().trace(msg); - } - } - } - - /** - * Gets the logger. - * - * @return the logger - */ - protected Logger getLogger() { - return this.profileLogger; - } - - private void setMessagePrefix(String prefix) { - this.messagePrefix = prefix; - } - - private String getMessagePrefix() { - return this.messagePrefix; - } - - private int getMessageIndent() { - return this.messageIndent; - } - - private void setMessageIndent(int indent) { - this.messageIndent = indent; - } - - private void setStartTime(long start) { - this.startTime = start; - } - - private void setStopTime(long stop) { - this.stopTime = stop; - } - - private void setElapsedTime(long segment) { - this.elapsedTime = segment; - } - - private void setCumulativeTime(long cumulative) { - this.cumulativeTime = cumulative; - } - - private void addToCumulativeTime(long cumulative) { - this.cumulativeTime += cumulative; - } - - private long currentTime() { - return System.currentTimeMillis(); - } - - private long elapsedTime() { - return (currentTime() - getStartTime()); - } - - private String objectName(Object theObject) { - if (theObject != null) { - return (theObject.getClass().getSimpleName()); - } else { - return ""; - } - } - - /** - * Returns a formatted log message, after adding indentation and prefix, if any. - * - * @param msg the message to log. - * @return a formatted log message, including indentation and prefix, if any. - */ - private String formatLogMessage(String msg) { - StringBuffer logMsg = new StringBuffer(); - for (int i = 0; i < getMessageIndent(); i++) { - logMsg.append(INDENT); - } - String prefix = getMessagePrefix(); - if (prefix != null && !prefix.trim().isEmpty()) { - logMsg.append(prefix); - logMsg.append(PREFIX_SEPARATOR); - } - if (msg != null) { - logMsg.append(msg); - } - return logMsg.toString(); - } - - private String defaultStartMessage() { - StringBuffer defaultStartMessage = new StringBuffer(); - defaultStartMessage.append(">>>> Start >>>>"); - return defaultStartMessage.toString(); - } - - private String defaultStopMessage() { - StringBuffer defaultStopMessage = new StringBuffer(); - defaultStopMessage.append("<<<< Stopped <<<<"); - defaultStopMessage.append(" [" + getElapsedTime() + " ms]"); - if (getCumulativeTime() > getElapsedTime()) { - defaultStopMessage.append(" (cumulative [" + getCumulativeTime() + " ms])"); - } - return defaultStopMessage.toString(); - } - -} +/** + * 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.client; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Profiler.java + * + * Simple utility to store and report performance metrics. + * + * Records start and stop times, and elapsed and cumulative timings; + * writes performance-related log times. + * + * $LastChangedRevision: $ + * $LastChangedDate: $ + * + */ +public class Profiler { + + /** The level of indentation. */ + private int messageIndent = 0; + /** The indentation character(s) */ + private static String INDENT = "\t"; + /** The message prefix. */ + private String messagePrefix = ""; + /** The separator between the message prefix and the message. **/ + final static String PREFIX_SEPARATOR = ":"; + /** The start time. */ + private long startTime = 0; + /** The stop time. */ + private long stopTime = 0; + /** The segment time. */ + private long elapsedTime = 0; + /** The cumulative time. */ + private long cumulativeTime = 0; + /** The profiler logger. */ + private static String DEFAULT_LOG4J_CATEGORY = "perf.collectionspace"; + private static Logger profileLogger = LoggerFactory.getLogger(DEFAULT_LOG4J_CATEGORY); + + /** + * private default constructor. + */ + private Profiler() { + //empty default constructor + } + + /** + * Instantiates a new profiler. + * + * @param theObject a class whose name is to be logged. + */ + public Profiler(Object theObject) { + this(theObject, 0); + } + + /** + * Instantiates a new profiler. + * + * @param theObject a class whose name is to be logged. + * @param messageIndent the level of indentation for log messages. + */ + public Profiler(Object theObject, int messageIndent) { + init(objectName(theObject), messageIndent); + } + + /** + * Instantiates a new profiler. + * + * @param messagePrefix the message prefix to appear in log messages. + * @param messageIndent the level of indentation for log messages. + */ + public Profiler(String messagePrefix, int messageIndent) { + init(messagePrefix, messageIndent); + } + + private void init(String messagePrefix, int messageIndent) { + this.setMessagePrefix(messagePrefix); + this.setMessageIndent(messageIndent); + } + + /** + * Stores and logs the start time. + * + * Logs using a default message. + */ + public void start() { + start(defaultStartMessage()); + } + + /** + * Stores and logs the start time. + * + * @param msg the message to log. + */ + public void start(String msg) { + log(msg); + setStartTime(currentTime()); + } + + private void stopTimer() { + setStopTime(currentTime()); + setElapsedTime(getStopTime() - getStartTime()); + addToCumulativeTime(getElapsedTime()); + } + + /** + * Stores and logs the stop time, and the elapsed and cumulative timings + * from one or more cycles of start and stop. + * + * Logs using a default message. + */ + public void stop() { + stopTimer(); + log(defaultStopMessage()); + } + + /** + * Stores and logs the stop time, and the elapsed and cumulative timings, + * from one or more cycles of start and stop. + * + * @param msg the message to log. + */ + public void stop(String msg) { + stopTimer(); + log(msg); + } + + public long getStartTime() { + return this.startTime; + } + + public long getStopTime() { + return this.stopTime; + } + + public long getElapsedTime() { + return this.elapsedTime; + } + + public long getCumulativeTime() { + return this.cumulativeTime; + } + + /** + * Resets the start and stop time, and the elapsed and cumulative timings. + */ + public void reset() { + setStartTime(0); + setStopTime(0); + setElapsedTime(0); + setCumulativeTime(0); + } + + /** + * Writes a message to a log entry. The message will + * be formatted, using current settings for indentation, + * prefix, etc. before being written. + * + * @param msg the message to be written to a log entry. + */ + public void log(String msg) { + if (getLogger().isTraceEnabled()) { + getLogger().trace(formatLogMessage(msg)); + } + } + + /** + * Writes a message to a log entry, + * + * @param msg the message to write to a log entry. + * @param formatMsg true if the message is to be formatted; + * false if it is not to be formatted. + */ + public void log(String msg, boolean formatMsg) { + if (getLogger().isTraceEnabled()) { + if (formatMsg) { + getLogger().trace(formatLogMessage(msg)); + } else { + getLogger().trace(msg); + } + } + } + + /** + * Gets the logger. + * + * @return the logger + */ + protected Logger getLogger() { + return this.profileLogger; + } + + private void setMessagePrefix(String prefix) { + this.messagePrefix = prefix; + } + + private String getMessagePrefix() { + return this.messagePrefix; + } + + private int getMessageIndent() { + return this.messageIndent; + } + + private void setMessageIndent(int indent) { + this.messageIndent = indent; + } + + private void setStartTime(long start) { + this.startTime = start; + } + + private void setStopTime(long stop) { + this.stopTime = stop; + } + + private void setElapsedTime(long segment) { + this.elapsedTime = segment; + } + + private void setCumulativeTime(long cumulative) { + this.cumulativeTime = cumulative; + } + + private void addToCumulativeTime(long cumulative) { + this.cumulativeTime += cumulative; + } + + private long currentTime() { + return System.currentTimeMillis(); + } + + private long elapsedTime() { + return (currentTime() - getStartTime()); + } + + private String objectName(Object theObject) { + if (theObject != null) { + return (theObject.getClass().getSimpleName()); + } else { + return ""; + } + } + + /** + * Returns a formatted log message, after adding indentation and prefix, if any. + * + * @param msg the message to log. + * @return a formatted log message, including indentation and prefix, if any. + */ + private String formatLogMessage(String msg) { + StringBuffer logMsg = new StringBuffer(); + for (int i = 0; i < getMessageIndent(); i++) { + logMsg.append(INDENT); + } + String prefix = getMessagePrefix(); + if (prefix != null && !prefix.trim().isEmpty()) { + logMsg.append(prefix); + logMsg.append(PREFIX_SEPARATOR); + } + if (msg != null) { + logMsg.append(msg); + } + return logMsg.toString(); + } + + private String defaultStartMessage() { + StringBuffer defaultStartMessage = new StringBuffer(); + defaultStartMessage.append(">>>> Start >>>>"); + return defaultStartMessage.toString(); + } + + private String defaultStopMessage() { + StringBuffer defaultStopMessage = new StringBuffer(); + defaultStopMessage.append("<<<< Stopped <<<<"); + defaultStopMessage.append(" [" + getElapsedTime() + " ms]"); + if (getCumulativeTime() > getElapsedTime()) { + defaultStopMessage.append(" (cumulative [" + getCumulativeTime() + " ms])"); + } + return defaultStopMessage.toString(); + } + +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/TestServiceProxy.java b/services/client/src/main/java/org/collectionspace/services/client/TestServiceProxy.java index 0299771ca..3786f443c 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/TestServiceProxy.java +++ b/services/client/src/main/java/org/collectionspace/services/client/TestServiceProxy.java @@ -1,7 +1,7 @@ -package org.collectionspace.services.client; - -import org.collectionspace.services.jaxb.AbstractCommonList; - -public interface TestServiceProxy extends CollectionSpaceProxy { - -} +package org.collectionspace.services.client; + +import org.collectionspace.services.jaxb.AbstractCommonList; + +public interface TestServiceProxy extends CollectionSpaceProxy { + +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/test/AbstractAuthorityServiceTest.java b/services/client/src/main/java/org/collectionspace/services/client/test/AbstractAuthorityServiceTest.java index 3d3ff6001..f878f897e 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/test/AbstractAuthorityServiceTest.java +++ b/services/client/src/main/java/org/collectionspace/services/client/test/AbstractAuthorityServiceTest.java @@ -1,540 +1,540 @@ -package org.collectionspace.services.client.test; - -import java.util.List; - -import javax.ws.rs.core.Response; -import org.jboss.resteasy.client.ClientResponse; - -import org.collectionspace.services.client.AbstractCommonListUtils; -import org.collectionspace.services.client.AuthorityClient; -import org.collectionspace.services.client.AuthorityClientImpl; -import org.collectionspace.services.client.AuthorityProxy; -import org.collectionspace.services.client.PayloadInputPart; -import org.collectionspace.services.client.PayloadOutputPart; -import org.collectionspace.services.client.PoxPayloadOut; -import org.collectionspace.services.jaxb.AbstractCommonList; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -/** - * - * @author remillet - * - * @param - * @param - * - * All CRUD related authority test classes should extend this class. - * - */ -public abstract class AbstractAuthorityServiceTest - extends AbstractPoxServiceTestImpl { - - private final Logger logger = LoggerFactory.getLogger(AbstractAuthorityServiceTest.class); - - protected String knownResourceShortIdentifer = null; - protected static final String READITEMS_SHORT_IDENTIFIER = "resourceWithItems"; - protected String knownAuthorityWithItems = null; - - protected String knownResourceRefName = null; - protected String knownItemResourceId = null; - protected String knownItemResourceShortIdentifer = null; - protected int nItemsToCreateInList = 5; - - public abstract void authorityTests(String testName); - protected abstract String createItemInAuthority(String authorityId); - - protected abstract AUTHORITY_ITEM_TYPE updateItemInstance(final AUTHORITY_ITEM_TYPE authorityItem); - protected abstract void compareUpdatedItemInstances(AUTHORITY_ITEM_TYPE original, AUTHORITY_ITEM_TYPE updated) throws Exception; - - protected void setKnownItemResource(String id, String shortIdentifer ) { - knownItemResourceId = id; - knownItemResourceShortIdentifer = shortIdentifer; - } - - protected void setKnownResource(String id, String shortIdentifer, - String refName) { - knownResourceId = id; - knownResourceShortIdentifer = shortIdentifer; - knownResourceRefName = refName; - } - - /** - * Returns the root URL for a service. - * - * This URL consists of a base URL for all services, followed by - * a path component for the owning vocabulary, followed by the - * path component for the items. - * - * @return The root URL for a service. - */ - protected String getItemServiceRootURL(String parentResourceIdentifier) { - return getResourceURL(parentResourceIdentifier) + "/" + getServicePathItemsComponent(); - } - - /** - * Returns the URL of a specific resource managed by a service, and - * designated by an identifier (such as a universally unique ID, or UUID). - * - * @param resourceIdentifier An identifier (such as a UUID) for a resource. - * - * @return The URL of a specific resource managed by a service. - */ - protected String getItemResourceURL(String parentResourceIdentifier, String resourceIdentifier) { - return getItemServiceRootURL(parentResourceIdentifier) + "/" + resourceIdentifier; - } - - /** - * For authorities we override this method so we can save the shortid. - */ - @Override - protected String createWithIdentifier(String testName, String identifier) throws Exception { - String csid = createResource(testName, identifier); - // Store the ID returned from the first resource created - // for additional tests below. - if (getKnowResourceId() == null) { - setKnownResource(csid, identifier /*shortId*/, null /*refname*/ ); - if (logger.isDebugEnabled()) { - logger.debug(testName + ": Setting knownResourceId=" + getKnowResourceId()); - } - } - - return identifier; - } - - @Test(dependsOnMethods = {"readItem", "CRUDTests"}) - public void testItemSubmitRequest() { - - // Expected status code: 200 OK - final int EXPECTED_STATUS = Response.Status.OK.getStatusCode(); - - // Submit the request to the service and store the response. - String method = ServiceRequestType.READ.httpMethodName(); - String url = getItemResourceURL(knownResourceId, knownItemResourceId); - int statusCode = submitRequest(method, url); - - // Check the status code of the response: does it match - // the expected response(s)? - if (logger.isDebugEnabled()) { - logger.debug("testItemSubmitRequest: url=" + url - + " status=" + statusCode); - } - Assert.assertEquals(statusCode, EXPECTED_STATUS); - } - - - @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, - dependsOnMethods = {"readItem"}) - public void verifyIgnoredUpdateWithInAuthority(String testName) throws Exception { - // Perform setup. - setupUpdate(); - - // Submit the request to the service and store the response. - AuthorityClientImpl client = - (AuthorityClientImpl)this.getClientInstance(); - ClientResponse res = client.readItem(knownResourceId, knownItemResourceId); - int statusCode = res.getStatus(); - - // Check the status code of the response: does it match - // the expected response(s)? - if (logger.isDebugEnabled()) { - logger.debug(testName + " read authority:" + knownResourceId + "/Item:" - + knownItemResourceId + " status = " + statusCode); - } - Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), - invalidStatusCodeMessage(testRequestType, statusCode)); - Assert.assertEquals(statusCode, Response.Status.OK.getStatusCode()); - - AUTHORITY_ITEM_TYPE vitem = extractItemCommonPartValue(res); - Assert.assertNotNull(vitem); - // Try to Update with new parent vocab (use self, for test). - Assert.assertEquals(client.getInAuthority(vitem), knownResourceId, - "VocabularyItem inAuthority does not match knownResourceId."); - client.setInAuthority(vitem, knownItemResourceId); - - // Submit the updated resource to the service and store the response. - PoxPayloadOut output = this.createItemRequestTypeInstance(vitem); - res = client.updateItem(knownResourceId, knownItemResourceId, output); - statusCode = res.getStatus(); - - // Check the status code of the response: does it match the expected response(s)? - if (logger.isDebugEnabled()) { - logger.debug(testName + ": status = " + statusCode); - } - Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), - invalidStatusCodeMessage(testRequestType, statusCode)); - Assert.assertEquals(statusCode, testExpectedStatusCode); - - // Retrieve the updated resource and verify that the parent did not change - res = client.readItem(knownResourceId, knownItemResourceId); - AUTHORITY_ITEM_TYPE updatedVocabularyItem = extractItemCommonPartValue(res); - Assert.assertNotNull(updatedVocabularyItem); - - // Verify that the updated resource received the correct data. - Assert.assertEquals(client.getInAuthority(updatedVocabularyItem), - knownResourceId, - "VocabularyItem allowed update to the parent (inAuthority)."); - } - - @Test(dataProvider = "testName", - dependsOnMethods = {"CRUDTests"}) - public void createItem(String testName) { - // Perform setup. - setupCreate(); - - String newID = createItemInAuthority(knownResourceId); - - // Store the ID returned from the first item resource created - // for additional tests below. - if (knownItemResourceId == null) { - knownItemResourceId = newID; - if (null != testName && logger.isDebugEnabled()) { - logger.debug(testName + ": knownItemResourceId=" + knownItemResourceId); - } - } - } - - @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, - dependsOnMethods = {"createItem"}) - public void createItemList(String testName) throws Exception { - knownAuthorityWithItems = createResource(testName, READITEMS_SHORT_IDENTIFIER); - for (int j = 0; j < nItemsToCreateInList; j++) { - createItemInAuthority(knownAuthorityWithItems); - } - } - - /** - * Read by name. - * - * @param testName the test name - * @throws Exception the exception - */ - @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, - dependsOnMethods = {"CRUDTests"}) - public void readByName(String testName) throws Exception { - // Perform setup. - setupRead(); - - // Submit the request to the service and store the response. - AuthorityClientImpl client = (AuthorityClientImpl)this.getClientInstance(); - ClientResponse res = client.readByName(getKnowResourceIdentifier()); - int statusCode = res.getStatus(); - - // Check the status code of the response: does it match - // the expected response(s)? - if (logger.isDebugEnabled()) { - logger.debug(testName + ": status = " + statusCode); - } - Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), - invalidStatusCodeMessage(testRequestType, statusCode)); - Assert.assertEquals(statusCode, testExpectedStatusCode); - - AUTHORITY_COMMON_TYPE commonPart = extractCommonPartValue(res); - Assert.assertNotNull(commonPart); - } - - /** - * Extracts the common part item from a service's item payload. - * - * @param res - * @return - * @throws Exception - */ - public AUTHORITY_ITEM_TYPE extractItemCommonPartValue(ClientResponse res) throws Exception { - AUTHORITY_ITEM_TYPE result = null; - - AuthorityClientImpl client = (AuthorityClientImpl)this.getClientInstance(); - PayloadInputPart payloadInputPart = extractPart(res, client.getItemCommonPartName()); - if (payloadInputPart != null) { - result = (AUTHORITY_ITEM_TYPE) payloadInputPart.getBody(); - } - Assert.assertNotNull(result, - "Part or body of part " + client.getCommonPartName() + " was unexpectedly null."); - - return result; - } - - @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, - dependsOnMethods = {"readItem"}) - public void readItemNonExistent(String testName) { - // Perform setup. - setupReadNonExistent(); - - // Submit the request to the service and store the response. - AuthorityClientImpl client = (AuthorityClientImpl)this.getClientInstance(); - ClientResponse res = client.readItem(knownResourceId, NON_EXISTENT_ID); - int statusCode = res.getStatus(); - - // Check the status code of the response: does it match - // the expected response(s)? - if (logger.isDebugEnabled()) { - logger.debug(testName + ": status = " + statusCode); - } - Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), - invalidStatusCodeMessage(testRequestType, statusCode)); - Assert.assertEquals(statusCode, testExpectedStatusCode); - } - - @Test(dataProvider = "testName", - dependsOnMethods = {"createItem"}) - public void readItem(String testName) throws Exception { - // Perform setup. - setupRead(); - - // Submit the request to the service and store the response. - AuthorityClientImpl client = (AuthorityClientImpl)this.getClientInstance(); - ClientResponse res = client.readItem(knownResourceId, knownItemResourceId); - int statusCode = res.getStatus(); - - // Check the status code of the response: does it match - // the expected response(s)? - if (logger.isDebugEnabled()) { - logger.debug(testName + ": status = " + statusCode); - } - Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), - invalidStatusCodeMessage(testRequestType, statusCode)); - Assert.assertEquals(statusCode, testExpectedStatusCode); - - AUTHORITY_ITEM_TYPE itemCommonPart = extractItemCommonPartValue(res); - Assert.assertNotNull(itemCommonPart); - Assert.assertEquals(client.getInAuthority(itemCommonPart), knownResourceId); - verifyReadItemInstance(itemCommonPart); - } - - protected abstract void verifyReadItemInstance(AUTHORITY_ITEM_TYPE item) throws Exception; - - @Test(dataProvider = "testName", - dependsOnMethods = {"testItemSubmitRequest", "updateItem", "verifyIgnoredUpdateWithInAuthority"}) - public void deleteItem(String testName) throws Exception { - // Perform setup. - setupDelete(); - - // Submit the request to the service and store the response. - AuthorityClientImpl client = (AuthorityClientImpl)this.getClientInstance(); - ClientResponse res = client.deleteItem(knownResourceId, knownItemResourceId); - int statusCode = res.getStatus(); - - // Check the status code of the response: does it match - // the expected response(s)? - if (logger.isDebugEnabled()) { - logger.debug("delete: status = " + statusCode); - } - Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), - invalidStatusCodeMessage(testRequestType, statusCode)); - Assert.assertEquals(statusCode, testExpectedStatusCode); - } - - protected void readItemListInt(String vcsid, String shortId, String testName) { - // Perform setup. - setupReadList(); - - // Submit the request to the service and store the response. - AuthorityClientImpl client = (AuthorityClientImpl)this.getClientInstance(); - ClientResponse res = null; - if (vcsid != null) { - res = client.readItemList(vcsid, null, null); - } else if (shortId != null) { - res = client.readItemListForNamedAuthority(shortId, null, null); - } else { - Assert.fail("Internal Error: readItemList both vcsid and shortId are null!"); - } - int statusCode = res.getStatus(); - - // Check the status code of the response: does it match - // the expected response(s)? - if (logger.isDebugEnabled()) { - logger.debug(" " + testName + ": status = " + statusCode); - } - Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), - invalidStatusCodeMessage(testRequestType, statusCode)); - Assert.assertEquals(statusCode, testExpectedStatusCode); - - AbstractCommonList list = res.getEntity(); - List items = list.getListItem(); - int nItemsReturned = items.size(); - long nItemsTotal = list.getTotalItems(); - if (logger.isDebugEnabled()) { - logger.debug(" " + testName + ": Expected " - + nItemsToCreateInList + " items; got: " + nItemsReturned + " of: " + nItemsTotal); - } - Assert.assertEquals(nItemsTotal, nItemsToCreateInList); - - if(logger.isTraceEnabled()){ - AbstractCommonListUtils.ListItemsInAbstractCommonList(list, logger, testName); - } - } - - @Test(dataProvider = "testName", - dependsOnMethods = {"createItemList"}) - public void readItemList(String testName) { - readItemListInt(knownAuthorityWithItems, null, testName); - } - - @Test(dataProvider = "testName", - dependsOnMethods = {"readItem"}) - public void readItemListByName(String testName) { - readItemListInt(null, READITEMS_SHORT_IDENTIFIER, testName); - } - - @Test(dataProvider = "testName", - dependsOnMethods = {"deleteItem"}) - public void deleteNonExistentItem(String testName) { - // Perform setup. - setupDeleteNonExistent(); - - // Submit the request to the service and store the response. - AuthorityClientImpl client = (AuthorityClientImpl)this.getClientInstance(); - ClientResponse res = client.deleteItem(knownResourceId, NON_EXISTENT_ID); - int statusCode = res.getStatus(); - - // Check the status code of the response: does it match - // the expected response(s)? - if (logger.isDebugEnabled()) { - logger.debug(testName + ": status = " + statusCode); - } - Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), - invalidStatusCodeMessage(testRequestType, statusCode)); - Assert.assertEquals(statusCode, testExpectedStatusCode); - } - - protected String getServicePathItemsComponent() { - return AuthorityClient.ITEMS; - } - - public PoxPayloadOut createItemRequestTypeInstance(AUTHORITY_ITEM_TYPE itemTypeInstance) { - PoxPayloadOut result = null; - - AuthorityClientImpl client = (AuthorityClientImpl)this.getClientInstance(); - PoxPayloadOut payloadOut = new PoxPayloadOut(this.getServicePathItemsComponent()); - PayloadOutputPart part = payloadOut.addPart(client.getItemCommonPartName(), itemTypeInstance); - result = payloadOut; - - return result; - } - - /** - * Update an Authority item. - * - * @param testName - * @throws Exception - */ - @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, - dependsOnMethods = {"readItem", "CRUDTests", "verifyIgnoredUpdateWithInAuthority"}) - public void updateItem(String testName) throws Exception { - // Perform setup. - setupUpdate(); - AUTHORITY_ITEM_TYPE theUpdate = null; - - // Retrieve the contents of a resource to update. - AuthorityClientImpl client = - (AuthorityClientImpl)this.getClientInstance(); - ClientResponse res = - client.readItem(knownResourceId, knownItemResourceId); - try { - if (logger.isDebugEnabled()) { - logger.debug(testName + ": read status = " + res.getStatus()); - } - Assert.assertEquals(res.getStatus(), testExpectedStatusCode); - - if (logger.isDebugEnabled()) { - logger.debug("got Authority item to update with ID: " - + knownItemResourceId - + " in authority: " + knownResourceId); - } - AUTHORITY_ITEM_TYPE authorityItem = extractItemCommonPartValue(res); - Assert.assertNotNull(authorityItem); - - // Update the contents of this resource. - theUpdate = updateItemInstance(authorityItem); - if (logger.isDebugEnabled()) { - logger.debug("\n\nTo be updated fields: CSID = " + knownItemResourceId + "\n" - + objectAsXmlString(theUpdate)); - } - } finally { - res.releaseConnection(); - } - - // Submit the updated resource to the service and store the response. - PoxPayloadOut output = this.createItemRequestTypeInstance(theUpdate); - res = client.updateItem(knownResourceId, knownItemResourceId, output); - try { - int statusCode = res.getStatus(); - - // Check the status code of the response: does it match the expected response(s)? - if (logger.isDebugEnabled()) { - logger.debug("updateItem: status = " + statusCode); - } - Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), - invalidStatusCodeMessage(testRequestType, statusCode)); - Assert.assertEquals(statusCode, testExpectedStatusCode); - - // Retrieve the updated resource and verify that its contents exist. - AUTHORITY_ITEM_TYPE updatedVocabularyItem = extractItemCommonPartValue(res); - Assert.assertNotNull(updatedVocabularyItem); - - compareUpdatedItemInstances(theUpdate, updatedVocabularyItem); - } finally { - res.releaseConnection(); - } - } - - protected abstract PoxPayloadOut createNonExistenceItemInstance(String commonPartName, String identifier); - - /* (non-Javadoc) - * @see org.collectionspace.services.client.test.ServiceTest#updateNonExistent(java.lang.String) - */ - @Test(dataProvider = "testName", - dependsOnMethods = {"create", "update", "updateNonExistent"}) - public void updateNonExistentItem(String testName) throws Exception { - // Perform setup. - setupUpdateNonExistent(); - - // 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. - AuthorityClientImpl client = - (AuthorityClientImpl)this.getClientInstance(); - PoxPayloadOut multipart = createNonExistenceItemInstance(client.getItemCommonPartName(), NON_EXISTENT_ID); - ClientResponse res = - client.updateItem(knownResourceId, NON_EXISTENT_ID, multipart); - try { - int statusCode = res.getStatus(); - - // Check the status code of the response: does it match - // the expected response(s)? - if (logger.isDebugEnabled()) { - logger.debug(testName + ": status = " + statusCode); - } - Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), - invalidStatusCodeMessage(testRequestType, statusCode)); - Assert.assertEquals(statusCode, testExpectedStatusCode); - } finally { - res.releaseConnection(); - } - } - - // - // Methods to persuade TestNG to follow the correct test dependency path - // - - @Test(dataProvider = "testName", - dependsOnMethods = {"createItem"}) - public void baseAuthorityTests(String testName) { - // Do nothing. Here just to setup a test dependency chain. - } - - /* - * For convenience and terseness, this test method is the base of the test execution dependency chain. Other test methods may - * refer to this method in their @Test annotation declarations. - */ - @Override - @Test(dataProvider = "testName", - dependsOnMethods = { - "org.collectionspace.services.client.test.AbstractServiceTestImpl.baseCRUDTests"}) - public void CRUDTests(String testName) { - // TODO Auto-generated method stub - } - -} +package org.collectionspace.services.client.test; + +import java.util.List; + +import javax.ws.rs.core.Response; +import org.jboss.resteasy.client.ClientResponse; + +import org.collectionspace.services.client.AbstractCommonListUtils; +import org.collectionspace.services.client.AuthorityClient; +import org.collectionspace.services.client.AuthorityClientImpl; +import org.collectionspace.services.client.AuthorityProxy; +import org.collectionspace.services.client.PayloadInputPart; +import org.collectionspace.services.client.PayloadOutputPart; +import org.collectionspace.services.client.PoxPayloadOut; +import org.collectionspace.services.jaxb.AbstractCommonList; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.Test; + +/** + * + * @author remillet + * + * @param + * @param + * + * All CRUD related authority test classes should extend this class. + * + */ +public abstract class AbstractAuthorityServiceTest + extends AbstractPoxServiceTestImpl { + + private final Logger logger = LoggerFactory.getLogger(AbstractAuthorityServiceTest.class); + + protected String knownResourceShortIdentifer = null; + protected static final String READITEMS_SHORT_IDENTIFIER = "resourceWithItems"; + protected String knownAuthorityWithItems = null; + + protected String knownResourceRefName = null; + protected String knownItemResourceId = null; + protected String knownItemResourceShortIdentifer = null; + protected int nItemsToCreateInList = 5; + + public abstract void authorityTests(String testName); + protected abstract String createItemInAuthority(String authorityId); + + protected abstract AUTHORITY_ITEM_TYPE updateItemInstance(final AUTHORITY_ITEM_TYPE authorityItem); + protected abstract void compareUpdatedItemInstances(AUTHORITY_ITEM_TYPE original, AUTHORITY_ITEM_TYPE updated) throws Exception; + + protected void setKnownItemResource(String id, String shortIdentifer ) { + knownItemResourceId = id; + knownItemResourceShortIdentifer = shortIdentifer; + } + + protected void setKnownResource(String id, String shortIdentifer, + String refName) { + knownResourceId = id; + knownResourceShortIdentifer = shortIdentifer; + knownResourceRefName = refName; + } + + /** + * Returns the root URL for a service. + * + * This URL consists of a base URL for all services, followed by + * a path component for the owning vocabulary, followed by the + * path component for the items. + * + * @return The root URL for a service. + */ + protected String getItemServiceRootURL(String parentResourceIdentifier) { + return getResourceURL(parentResourceIdentifier) + "/" + getServicePathItemsComponent(); + } + + /** + * Returns the URL of a specific resource managed by a service, and + * designated by an identifier (such as a universally unique ID, or UUID). + * + * @param resourceIdentifier An identifier (such as a UUID) for a resource. + * + * @return The URL of a specific resource managed by a service. + */ + protected String getItemResourceURL(String parentResourceIdentifier, String resourceIdentifier) { + return getItemServiceRootURL(parentResourceIdentifier) + "/" + resourceIdentifier; + } + + /** + * For authorities we override this method so we can save the shortid. + */ + @Override + protected String createWithIdentifier(String testName, String identifier) throws Exception { + String csid = createResource(testName, identifier); + // Store the ID returned from the first resource created + // for additional tests below. + if (getKnowResourceId() == null) { + setKnownResource(csid, identifier /*shortId*/, null /*refname*/ ); + if (logger.isDebugEnabled()) { + logger.debug(testName + ": Setting knownResourceId=" + getKnowResourceId()); + } + } + + return identifier; + } + + @Test(dependsOnMethods = {"readItem", "CRUDTests"}) + public void testItemSubmitRequest() { + + // Expected status code: 200 OK + final int EXPECTED_STATUS = Response.Status.OK.getStatusCode(); + + // Submit the request to the service and store the response. + String method = ServiceRequestType.READ.httpMethodName(); + String url = getItemResourceURL(knownResourceId, knownItemResourceId); + int statusCode = submitRequest(method, url); + + // Check the status code of the response: does it match + // the expected response(s)? + if (logger.isDebugEnabled()) { + logger.debug("testItemSubmitRequest: url=" + url + + " status=" + statusCode); + } + Assert.assertEquals(statusCode, EXPECTED_STATUS); + } + + + @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, + dependsOnMethods = {"readItem"}) + public void verifyIgnoredUpdateWithInAuthority(String testName) throws Exception { + // Perform setup. + setupUpdate(); + + // Submit the request to the service and store the response. + AuthorityClientImpl client = + (AuthorityClientImpl)this.getClientInstance(); + ClientResponse res = client.readItem(knownResourceId, knownItemResourceId); + int statusCode = res.getStatus(); + + // Check the status code of the response: does it match + // the expected response(s)? + if (logger.isDebugEnabled()) { + logger.debug(testName + " read authority:" + knownResourceId + "/Item:" + + knownItemResourceId + " status = " + statusCode); + } + Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), + invalidStatusCodeMessage(testRequestType, statusCode)); + Assert.assertEquals(statusCode, Response.Status.OK.getStatusCode()); + + AUTHORITY_ITEM_TYPE vitem = extractItemCommonPartValue(res); + Assert.assertNotNull(vitem); + // Try to Update with new parent vocab (use self, for test). + Assert.assertEquals(client.getInAuthority(vitem), knownResourceId, + "VocabularyItem inAuthority does not match knownResourceId."); + client.setInAuthority(vitem, knownItemResourceId); + + // Submit the updated resource to the service and store the response. + PoxPayloadOut output = this.createItemRequestTypeInstance(vitem); + res = client.updateItem(knownResourceId, knownItemResourceId, output); + statusCode = res.getStatus(); + + // Check the status code of the response: does it match the expected response(s)? + if (logger.isDebugEnabled()) { + logger.debug(testName + ": status = " + statusCode); + } + Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), + invalidStatusCodeMessage(testRequestType, statusCode)); + Assert.assertEquals(statusCode, testExpectedStatusCode); + + // Retrieve the updated resource and verify that the parent did not change + res = client.readItem(knownResourceId, knownItemResourceId); + AUTHORITY_ITEM_TYPE updatedVocabularyItem = extractItemCommonPartValue(res); + Assert.assertNotNull(updatedVocabularyItem); + + // Verify that the updated resource received the correct data. + Assert.assertEquals(client.getInAuthority(updatedVocabularyItem), + knownResourceId, + "VocabularyItem allowed update to the parent (inAuthority)."); + } + + @Test(dataProvider = "testName", + dependsOnMethods = {"CRUDTests"}) + public void createItem(String testName) { + // Perform setup. + setupCreate(); + + String newID = createItemInAuthority(knownResourceId); + + // Store the ID returned from the first item resource created + // for additional tests below. + if (knownItemResourceId == null) { + knownItemResourceId = newID; + if (null != testName && logger.isDebugEnabled()) { + logger.debug(testName + ": knownItemResourceId=" + knownItemResourceId); + } + } + } + + @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, + dependsOnMethods = {"createItem"}) + public void createItemList(String testName) throws Exception { + knownAuthorityWithItems = createResource(testName, READITEMS_SHORT_IDENTIFIER); + for (int j = 0; j < nItemsToCreateInList; j++) { + createItemInAuthority(knownAuthorityWithItems); + } + } + + /** + * Read by name. + * + * @param testName the test name + * @throws Exception the exception + */ + @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, + dependsOnMethods = {"CRUDTests"}) + public void readByName(String testName) throws Exception { + // Perform setup. + setupRead(); + + // Submit the request to the service and store the response. + AuthorityClientImpl client = (AuthorityClientImpl)this.getClientInstance(); + ClientResponse res = client.readByName(getKnowResourceIdentifier()); + int statusCode = res.getStatus(); + + // Check the status code of the response: does it match + // the expected response(s)? + if (logger.isDebugEnabled()) { + logger.debug(testName + ": status = " + statusCode); + } + Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), + invalidStatusCodeMessage(testRequestType, statusCode)); + Assert.assertEquals(statusCode, testExpectedStatusCode); + + AUTHORITY_COMMON_TYPE commonPart = extractCommonPartValue(res); + Assert.assertNotNull(commonPart); + } + + /** + * Extracts the common part item from a service's item payload. + * + * @param res + * @return + * @throws Exception + */ + public AUTHORITY_ITEM_TYPE extractItemCommonPartValue(ClientResponse res) throws Exception { + AUTHORITY_ITEM_TYPE result = null; + + AuthorityClientImpl client = (AuthorityClientImpl)this.getClientInstance(); + PayloadInputPart payloadInputPart = extractPart(res, client.getItemCommonPartName()); + if (payloadInputPart != null) { + result = (AUTHORITY_ITEM_TYPE) payloadInputPart.getBody(); + } + Assert.assertNotNull(result, + "Part or body of part " + client.getCommonPartName() + " was unexpectedly null."); + + return result; + } + + @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, + dependsOnMethods = {"readItem"}) + public void readItemNonExistent(String testName) { + // Perform setup. + setupReadNonExistent(); + + // Submit the request to the service and store the response. + AuthorityClientImpl client = (AuthorityClientImpl)this.getClientInstance(); + ClientResponse res = client.readItem(knownResourceId, NON_EXISTENT_ID); + int statusCode = res.getStatus(); + + // Check the status code of the response: does it match + // the expected response(s)? + if (logger.isDebugEnabled()) { + logger.debug(testName + ": status = " + statusCode); + } + Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), + invalidStatusCodeMessage(testRequestType, statusCode)); + Assert.assertEquals(statusCode, testExpectedStatusCode); + } + + @Test(dataProvider = "testName", + dependsOnMethods = {"createItem"}) + public void readItem(String testName) throws Exception { + // Perform setup. + setupRead(); + + // Submit the request to the service and store the response. + AuthorityClientImpl client = (AuthorityClientImpl)this.getClientInstance(); + ClientResponse res = client.readItem(knownResourceId, knownItemResourceId); + int statusCode = res.getStatus(); + + // Check the status code of the response: does it match + // the expected response(s)? + if (logger.isDebugEnabled()) { + logger.debug(testName + ": status = " + statusCode); + } + Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), + invalidStatusCodeMessage(testRequestType, statusCode)); + Assert.assertEquals(statusCode, testExpectedStatusCode); + + AUTHORITY_ITEM_TYPE itemCommonPart = extractItemCommonPartValue(res); + Assert.assertNotNull(itemCommonPart); + Assert.assertEquals(client.getInAuthority(itemCommonPart), knownResourceId); + verifyReadItemInstance(itemCommonPart); + } + + protected abstract void verifyReadItemInstance(AUTHORITY_ITEM_TYPE item) throws Exception; + + @Test(dataProvider = "testName", + dependsOnMethods = {"testItemSubmitRequest", "updateItem", "verifyIgnoredUpdateWithInAuthority"}) + public void deleteItem(String testName) throws Exception { + // Perform setup. + setupDelete(); + + // Submit the request to the service and store the response. + AuthorityClientImpl client = (AuthorityClientImpl)this.getClientInstance(); + ClientResponse res = client.deleteItem(knownResourceId, knownItemResourceId); + int statusCode = res.getStatus(); + + // Check the status code of the response: does it match + // the expected response(s)? + if (logger.isDebugEnabled()) { + logger.debug("delete: status = " + statusCode); + } + Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), + invalidStatusCodeMessage(testRequestType, statusCode)); + Assert.assertEquals(statusCode, testExpectedStatusCode); + } + + protected void readItemListInt(String vcsid, String shortId, String testName) { + // Perform setup. + setupReadList(); + + // Submit the request to the service and store the response. + AuthorityClientImpl client = (AuthorityClientImpl)this.getClientInstance(); + ClientResponse res = null; + if (vcsid != null) { + res = client.readItemList(vcsid, null, null); + } else if (shortId != null) { + res = client.readItemListForNamedAuthority(shortId, null, null); + } else { + Assert.fail("Internal Error: readItemList both vcsid and shortId are null!"); + } + int statusCode = res.getStatus(); + + // Check the status code of the response: does it match + // the expected response(s)? + if (logger.isDebugEnabled()) { + logger.debug(" " + testName + ": status = " + statusCode); + } + Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), + invalidStatusCodeMessage(testRequestType, statusCode)); + Assert.assertEquals(statusCode, testExpectedStatusCode); + + AbstractCommonList list = res.getEntity(); + List items = list.getListItem(); + int nItemsReturned = items.size(); + long nItemsTotal = list.getTotalItems(); + if (logger.isDebugEnabled()) { + logger.debug(" " + testName + ": Expected " + + nItemsToCreateInList + " items; got: " + nItemsReturned + " of: " + nItemsTotal); + } + Assert.assertEquals(nItemsTotal, nItemsToCreateInList); + + if(logger.isTraceEnabled()){ + AbstractCommonListUtils.ListItemsInAbstractCommonList(list, logger, testName); + } + } + + @Test(dataProvider = "testName", + dependsOnMethods = {"createItemList"}) + public void readItemList(String testName) { + readItemListInt(knownAuthorityWithItems, null, testName); + } + + @Test(dataProvider = "testName", + dependsOnMethods = {"readItem"}) + public void readItemListByName(String testName) { + readItemListInt(null, READITEMS_SHORT_IDENTIFIER, testName); + } + + @Test(dataProvider = "testName", + dependsOnMethods = {"deleteItem"}) + public void deleteNonExistentItem(String testName) { + // Perform setup. + setupDeleteNonExistent(); + + // Submit the request to the service and store the response. + AuthorityClientImpl client = (AuthorityClientImpl)this.getClientInstance(); + ClientResponse res = client.deleteItem(knownResourceId, NON_EXISTENT_ID); + int statusCode = res.getStatus(); + + // Check the status code of the response: does it match + // the expected response(s)? + if (logger.isDebugEnabled()) { + logger.debug(testName + ": status = " + statusCode); + } + Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), + invalidStatusCodeMessage(testRequestType, statusCode)); + Assert.assertEquals(statusCode, testExpectedStatusCode); + } + + protected String getServicePathItemsComponent() { + return AuthorityClient.ITEMS; + } + + public PoxPayloadOut createItemRequestTypeInstance(AUTHORITY_ITEM_TYPE itemTypeInstance) { + PoxPayloadOut result = null; + + AuthorityClientImpl client = (AuthorityClientImpl)this.getClientInstance(); + PoxPayloadOut payloadOut = new PoxPayloadOut(this.getServicePathItemsComponent()); + PayloadOutputPart part = payloadOut.addPart(client.getItemCommonPartName(), itemTypeInstance); + result = payloadOut; + + return result; + } + + /** + * Update an Authority item. + * + * @param testName + * @throws Exception + */ + @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, + dependsOnMethods = {"readItem", "CRUDTests", "verifyIgnoredUpdateWithInAuthority"}) + public void updateItem(String testName) throws Exception { + // Perform setup. + setupUpdate(); + AUTHORITY_ITEM_TYPE theUpdate = null; + + // Retrieve the contents of a resource to update. + AuthorityClientImpl client = + (AuthorityClientImpl)this.getClientInstance(); + ClientResponse res = + client.readItem(knownResourceId, knownItemResourceId); + try { + if (logger.isDebugEnabled()) { + logger.debug(testName + ": read status = " + res.getStatus()); + } + Assert.assertEquals(res.getStatus(), testExpectedStatusCode); + + if (logger.isDebugEnabled()) { + logger.debug("got Authority item to update with ID: " + + knownItemResourceId + + " in authority: " + knownResourceId); + } + AUTHORITY_ITEM_TYPE authorityItem = extractItemCommonPartValue(res); + Assert.assertNotNull(authorityItem); + + // Update the contents of this resource. + theUpdate = updateItemInstance(authorityItem); + if (logger.isDebugEnabled()) { + logger.debug("\n\nTo be updated fields: CSID = " + knownItemResourceId + "\n" + + objectAsXmlString(theUpdate)); + } + } finally { + res.releaseConnection(); + } + + // Submit the updated resource to the service and store the response. + PoxPayloadOut output = this.createItemRequestTypeInstance(theUpdate); + res = client.updateItem(knownResourceId, knownItemResourceId, output); + try { + int statusCode = res.getStatus(); + + // Check the status code of the response: does it match the expected response(s)? + if (logger.isDebugEnabled()) { + logger.debug("updateItem: status = " + statusCode); + } + Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), + invalidStatusCodeMessage(testRequestType, statusCode)); + Assert.assertEquals(statusCode, testExpectedStatusCode); + + // Retrieve the updated resource and verify that its contents exist. + AUTHORITY_ITEM_TYPE updatedVocabularyItem = extractItemCommonPartValue(res); + Assert.assertNotNull(updatedVocabularyItem); + + compareUpdatedItemInstances(theUpdate, updatedVocabularyItem); + } finally { + res.releaseConnection(); + } + } + + protected abstract PoxPayloadOut createNonExistenceItemInstance(String commonPartName, String identifier); + + /* (non-Javadoc) + * @see org.collectionspace.services.client.test.ServiceTest#updateNonExistent(java.lang.String) + */ + @Test(dataProvider = "testName", + dependsOnMethods = {"create", "update", "updateNonExistent"}) + public void updateNonExistentItem(String testName) throws Exception { + // Perform setup. + setupUpdateNonExistent(); + + // 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. + AuthorityClientImpl client = + (AuthorityClientImpl)this.getClientInstance(); + PoxPayloadOut multipart = createNonExistenceItemInstance(client.getItemCommonPartName(), NON_EXISTENT_ID); + ClientResponse res = + client.updateItem(knownResourceId, NON_EXISTENT_ID, multipart); + try { + int statusCode = res.getStatus(); + + // Check the status code of the response: does it match + // the expected response(s)? + if (logger.isDebugEnabled()) { + logger.debug(testName + ": status = " + statusCode); + } + Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), + invalidStatusCodeMessage(testRequestType, statusCode)); + Assert.assertEquals(statusCode, testExpectedStatusCode); + } finally { + res.releaseConnection(); + } + } + + // + // Methods to persuade TestNG to follow the correct test dependency path + // + + @Test(dataProvider = "testName", + dependsOnMethods = {"createItem"}) + public void baseAuthorityTests(String testName) { + // Do nothing. Here just to setup a test dependency chain. + } + + /* + * For convenience and terseness, this test method is the base of the test execution dependency chain. Other test methods may + * refer to this method in their @Test annotation declarations. + */ + @Override + @Test(dataProvider = "testName", + dependsOnMethods = { + "org.collectionspace.services.client.test.AbstractServiceTestImpl.baseCRUDTests"}) + public void CRUDTests(String testName) { + // TODO Auto-generated method stub + } + +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/test/AbstractPoxServiceTestImpl.java b/services/client/src/main/java/org/collectionspace/services/client/test/AbstractPoxServiceTestImpl.java index 54d1e7136..5d228ee66 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/test/AbstractPoxServiceTestImpl.java +++ b/services/client/src/main/java/org/collectionspace/services/client/test/AbstractPoxServiceTestImpl.java @@ -1,80 +1,80 @@ -package org.collectionspace.services.client.test; - -import org.collectionspace.services.client.CollectionSpaceClient; -import org.collectionspace.services.client.PayloadInputPart; -import org.collectionspace.services.client.PayloadOutputPart; -import org.collectionspace.services.client.PoxPayloadIn; -import org.collectionspace.services.client.PoxPayloadOut; -import org.collectionspace.services.client.AbstractCommonListUtils; -import org.collectionspace.services.jaxb.AbstractCommonList; - -import org.jboss.resteasy.client.ClientResponse; -import org.testng.Assert; - -/* - * - Common list type - * - Common part type - */ -public abstract class AbstractPoxServiceTestImpl - extends AbstractServiceTestImpl { - - @Override - public CPT extractCommonPartValue(ClientResponse res) throws Exception { - CPT result = null; - - CollectionSpaceClient client = getClientInstance(); - PayloadInputPart payloadInputPart = extractPart(res, client.getCommonPartName()); - if (payloadInputPart != null) { - result = (CPT) payloadInputPart.getBody(); - } - Assert.assertNotNull(result, - "Part or body of part " + client.getCommonPartName() + " was unexpectedly null."); - - return result; - } - - protected void printList(String testName, CLT list) { - if (getLogger().isTraceEnabled()){ - AbstractCommonListUtils.ListItemsInAbstractCommonList(list, getLogger(), testName); - } - } - - @Override - public CPT extractCommonPartValue(PoxPayloadOut payloadOut) throws Exception { - CPT result = null; - - CollectionSpaceClient client = getClientInstance(); - PayloadOutputPart payloadOutputPart = payloadOut.getPart(client.getCommonPartName()); - if (payloadOutputPart != null) { - result = (CPT) payloadOutputPart.getBody(); - } - Assert.assertNotNull(result, - "Part or body of part " + client.getCommonPartName() + " was unexpectedly null."); - - return result; - } - - @Override - public PoxPayloadOut createRequestTypeInstance(CPT commonPartTypeInstance) { - PoxPayloadOut result = null; - - CollectionSpaceClient client = this.getClientInstance(); - PoxPayloadOut payloadOut = new PoxPayloadOut(this.getServicePathComponent()); - PayloadOutputPart part = payloadOut.addPart(client.getCommonPartName(), commonPartTypeInstance); - result = payloadOut; - - return result; - } - - protected PayloadInputPart extractPart(ClientResponse res, String partLabel) - throws Exception { - if (getLogger().isDebugEnabled()) { - getLogger().debug("Reading part " + partLabel + " ..."); - } - PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); - PayloadInputPart payloadInputPart = input.getPart(partLabel); - Assert.assertNotNull(payloadInputPart, - "Part " + partLabel + " was unexpectedly null."); - return payloadInputPart; - } -} +package org.collectionspace.services.client.test; + +import org.collectionspace.services.client.CollectionSpaceClient; +import org.collectionspace.services.client.PayloadInputPart; +import org.collectionspace.services.client.PayloadOutputPart; +import org.collectionspace.services.client.PoxPayloadIn; +import org.collectionspace.services.client.PoxPayloadOut; +import org.collectionspace.services.client.AbstractCommonListUtils; +import org.collectionspace.services.jaxb.AbstractCommonList; + +import org.jboss.resteasy.client.ClientResponse; +import org.testng.Assert; + +/* + * - Common list type + * - Common part type + */ +public abstract class AbstractPoxServiceTestImpl + extends AbstractServiceTestImpl { + + @Override + public CPT extractCommonPartValue(ClientResponse res) throws Exception { + CPT result = null; + + CollectionSpaceClient client = getClientInstance(); + PayloadInputPart payloadInputPart = extractPart(res, client.getCommonPartName()); + if (payloadInputPart != null) { + result = (CPT) payloadInputPart.getBody(); + } + Assert.assertNotNull(result, + "Part or body of part " + client.getCommonPartName() + " was unexpectedly null."); + + return result; + } + + protected void printList(String testName, CLT list) { + if (getLogger().isTraceEnabled()){ + AbstractCommonListUtils.ListItemsInAbstractCommonList(list, getLogger(), testName); + } + } + + @Override + public CPT extractCommonPartValue(PoxPayloadOut payloadOut) throws Exception { + CPT result = null; + + CollectionSpaceClient client = getClientInstance(); + PayloadOutputPart payloadOutputPart = payloadOut.getPart(client.getCommonPartName()); + if (payloadOutputPart != null) { + result = (CPT) payloadOutputPart.getBody(); + } + Assert.assertNotNull(result, + "Part or body of part " + client.getCommonPartName() + " was unexpectedly null."); + + return result; + } + + @Override + public PoxPayloadOut createRequestTypeInstance(CPT commonPartTypeInstance) { + PoxPayloadOut result = null; + + CollectionSpaceClient client = this.getClientInstance(); + PoxPayloadOut payloadOut = new PoxPayloadOut(this.getServicePathComponent()); + PayloadOutputPart part = payloadOut.addPart(client.getCommonPartName(), commonPartTypeInstance); + result = payloadOut; + + return result; + } + + protected PayloadInputPart extractPart(ClientResponse res, String partLabel) + throws Exception { + if (getLogger().isDebugEnabled()) { + getLogger().debug("Reading part " + partLabel + " ..."); + } + PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); + PayloadInputPart payloadInputPart = input.getPart(partLabel); + Assert.assertNotNull(payloadInputPart, + "Part " + partLabel + " was unexpectedly null."); + return payloadInputPart; + } +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/test/BaseServiceTest.java b/services/client/src/main/java/org/collectionspace/services/client/test/BaseServiceTest.java index 03e4267f4..383bdcd46 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/test/BaseServiceTest.java +++ b/services/client/src/main/java/org/collectionspace/services/client/test/BaseServiceTest.java @@ -1,904 +1,904 @@ -/** - * 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 (c) 2009 Regents of the University of California - * - * 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.client.test; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.StringWriter; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; - -import javax.activation.MimetypesFileTypeMap; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.apache.commons.httpclient.HttpMethodBase; -import org.apache.commons.httpclient.methods.EntityEnclosingMethod; -import org.apache.commons.httpclient.methods.DeleteMethod; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.methods.PutMethod; -import org.apache.commons.httpclient.methods.StringRequestEntity; -import org.apache.commons.io.FileUtils; - -import org.jboss.resteasy.client.ClientResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.w3c.dom.Document; - -import org.collectionspace.services.client.AuthorityClient; -import org.collectionspace.services.client.CollectionSpaceClient; -import org.collectionspace.services.client.PayloadInputPart; -import org.collectionspace.services.client.PoxPayloadIn; -import org.collectionspace.services.client.TestServiceClient; -import org.collectionspace.services.jaxb.AbstractCommonList; -import org.collectionspace.services.common.api.FileTools; - -/** - * BaseServiceTest. - * - * Base abstract class on which client tests of services are based. - * - * $LastChangedRevision$ - * $LastChangedDate$ - */ - -// FIXME: http://issues.collectionspace.org/browse/CSPACE-1685 - -/* - * - Common list type - */ -public abstract class BaseServiceTest { - //A default MIME type result - static protected final String DEFAULT_MIME = "application/octet-stream; charset=ISO-8859-1"; - //Maven's base directory -i.e., the one containing the current pom.xml - protected static final String MAVEN_BASEDIR_PROPERTY = "maven.basedir"; - /** The Constant logger. */ - private static final Logger logger = LoggerFactory.getLogger(BaseServiceTest.class); - /** The Constant serviceClient. */ - protected static final TestServiceClient serviceClient = new TestServiceClient(); - - protected String knownResourceIdentifier = null; - /** Use this to keep track of a single known resource */ - protected String knownResourceId = null; - /* Use this to keep track of resources to delete */ - protected List allResourceIdsCreated = new ArrayList(); - /* Use this to track authority items */ - protected Map allResourceItemIdsCreated = new HashMap(); /* itemCsid, parentCsid */ - /* A runtime/command-line parameter to indicate if we should delete all the test related resource objects */ - static private final String NO_TEST_CLEANUP = "noTestCleanup"; - /* A random number generator */ - static private final Random random = new Random(System.currentTimeMillis()); - - - /** The non-existent id. */ - protected final String NON_EXISTENT_ID = createNonExistentIdentifier(); - /** The expected status code. */ - protected int testExpectedStatusCode = 0; - /** The request type type. */ - protected ServiceRequestType testRequestType = ServiceRequestType.NON_EXISTENT; - - /** The Constant XML_DECLARATION. */ - protected static final String XML_DECLARATION = ""; - /** The Constant MALFORMED_XML_DATA. */ - protected static final String MALFORMED_XML_DATA = XML_DECLARATION - + "wrong schema contentswrong schema contents"; - /** The null charset. */ - private static final String NULL_CHARSET = null; - - /** A visual separator for our test banners */ - private static final String BANNER_SEPARATOR_LINE = "==================================================="; - private static final String BANNER_PREFIX = "\n" + BANNER_SEPARATOR_LINE + "\n"; - private static final String BANNER_SUFFIX = "\n" + BANNER_SEPARATOR_LINE; - - // A Unicode UTF-8 data fragment for use in test payloads: a random sequence, - // unlikely to be encountered in actual collections data, and capable of - // being rendered by the default fonts in many modern operating systems. - // - // This fragment consists of a run of USASCII characters, followed by - // four non-USASCII range Unicode UTF-8 characters: - // - // Δ : Greek capital letter Delta (U+0394) - // Ж : Cyrillic capital letter Zhe with breve (U+04C1) - // Ŵ : Latin capital letter W with circumflex (U+0174) - // Ω : Greek capital letter Omega (U+03A9) - private final static String UTF8_DATA_FRAGMENT = "utf-8-data-fragment:" - + '\u0394' + '\u04C1' + '\u0174' +'\u03A9'; - // - // Status constants - // - protected static final int STATUS_BAD_REQUEST = - Response.Status.BAD_REQUEST.getStatusCode(); - protected static final int STATUS_CREATED = - Response.Status.CREATED.getStatusCode(); - protected static final int STATUS_INTERNAL_SERVER_ERROR = - Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(); - protected static final int STATUS_NOT_FOUND = - Response.Status.NOT_FOUND.getStatusCode(); - protected static final int STATUS_OK = - Response.Status.OK.getStatusCode(); - protected static final int STATUS_FORBIDDEN = - Response.Status.FORBIDDEN.getStatusCode(); - - /** - * Instantiates a new base service test. - */ - public BaseServiceTest() { - super(); - } - - /* - * A getter for retrieving the tests logger - */ - protected Logger getLogger() { - return this.logger; - } - - @BeforeMethod - protected void beforeMethod(Method m) { - logTestBanner(getLogger(), m.getName()); - } - - /** - * Gets the client. - * - * @return the client - */ - abstract protected CollectionSpaceClient getClientInstance(); - - /* - * Subclasses can override this method to return their AbstractCommonList subclass - */ - protected Class getCommonListType() { - return (Class)AbstractCommonList.class; - } - - protected CLT getCommonList( - ClientResponse response) { - return response.getEntity(getCommonListType()); - } - - /** - * Returns the name of the currently running test. - * - * Note: although the return type is listed as Object[][], - * this method instead returns a String. - * - * @param m The currently running test method. - * - */ - @DataProvider(name = "testName") - public static Object[][] testName(Method m) { - return new Object[][]{ - new Object[]{m.getName()} - }; - } - - /** - * Returns the URL path component of the service. - * - * This component will follow directly after the - * base path, if any. - * - * @return The URL path component of the service. - */ - protected abstract String getServicePathComponent(); - - protected abstract String getServiceName(); - - /** - * Reinitializes setup values, to help expose any unintended reuse - * of those values between tests. - */ - protected void clearSetup() { - testExpectedStatusCode = 0; - testRequestType = ServiceRequestType.NON_EXISTENT; - } - - /** - * Sets up create tests. - */ - protected void setupCreate() { - testExpectedStatusCode = STATUS_CREATED; - testRequestType = ServiceRequestType.CREATE; - testSetup(testExpectedStatusCode, testRequestType); - } - - /** - * Initializes setup values for a given test. - * - * @param expectedStatusCode A status code expected to be returned in the response. - * - * @param reqType A type of service request (e.g. CREATE, DELETE). - */ - protected void testSetup( - int expectedStatusCode, - ServiceRequestType reqType) { - clearSetup(); - testExpectedStatusCode = expectedStatusCode; - testRequestType = reqType; - } - - /** - * Returns an error message indicating that the status code returned by a - * specific call to a service does not fall within a set of valid status - * codes for that service. - * - * @param requestType A type of service request (e.g. CREATE, DELETE). - * - * @param statusCode The invalid status code that was returned in the response, - * from submitting that type of request to the service. - * - * @return An error message. - */ - protected String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) { - return "Status code '" + statusCode - + "' in response is NOT within the expected set: " - + requestType.validStatusCodesAsString(); - } - - /** - * Returns the root URL for a service. - * - * This URL consists of a base URL for all services, followed by - * a path component (or components) for a service. - * - * @return The root URL for a service. - */ - protected String getServiceRootURL() { - return serviceClient.getBaseURL() + getServiceName(); //FIXME: REM - This should probably be calling getServicePathComponent() and not getServiceName(); - } - - public String getServiceClientTenantID() { - return serviceClient.getProperty("cspace.tenantID"); - } - - /** - * Returns the URL of a specific resource managed by a service, and - * designated by an identifier (such as a universally unique ID, or UUID). - * - * @param resourceIdentifier An identifier (such as a UUID) for a resource. - * - * @return The URL of a specific resource managed by a service. - */ - protected String getResourceURL(String resourceIdentifier) { - return getServiceRootURL() + "/" + resourceIdentifier; - } - - /** - * Submits an HTTP request to a specified URL, and returns the - * status code of the response. Currently accepts GET and DELETE - * requests. - * - * @param method An HTTP method. - * - * @param url A String representation of a URL. - * - * @return The status code received in the HTTP response. - */ - protected int submitRequest(String method, String url) { - int statusCode = 0; - HttpMethodBase httpMethod = null; - try { - TestServiceClient client = new TestServiceClient(); - if (method.equals(javax.ws.rs.HttpMethod.DELETE)) { - httpMethod = new DeleteMethod(url); - } else if (method.equals(javax.ws.rs.HttpMethod.GET)) { - httpMethod = new GetMethod(url); - } - if (httpMethod != null) { - statusCode = client.getHttpClient().executeMethod(httpMethod); - } - } catch (Exception e) { - logger.error( - "Exception during HTTP " + method + " request to " - + url + ":", e); - } finally { - if (httpMethod != null) httpMethod.releaseConnection(); - } - return statusCode; - } - - /** - * Submits an HTTP request to a specified URL, with the submitted - * entity body, and returns the status code of the response. - * Currently accepts POST and PUT requests. - * - * @param method An HTTP method. - * - * @param url A String representation of a URL. - * - * @param mediaType The media type of the entity body to be submitted. - * - * @param entityStr The contents of the entity body to be submitted. - * - * @return The status code received in the HTTP response. - */ - protected int submitRequest(String method, String url, String mediaType, String entityStr) { - int statusCode = 0; - EntityEnclosingMethod httpMethod = null; - try { - TestServiceClient client = new TestServiceClient(); - if (method.equals(javax.ws.rs.HttpMethod.POST)) { - httpMethod = new PostMethod(url); - } else if (method.equals(javax.ws.rs.HttpMethod.PUT)) { - httpMethod = new PutMethod(url); - } - if (httpMethod != null) { - StringRequestEntity entityBody = - new StringRequestEntity(mediaType, entityStr, NULL_CHARSET); - httpMethod.setRequestEntity(entityBody); - statusCode = client.getHttpClient().executeMethod(httpMethod); - } - } catch (Exception e) { - logger.error( - "Exception during HTTP " + method + " request to " - + url + ":", e); - } finally { - if (httpMethod != null) httpMethod.releaseConnection(); - } - return statusCode; - } - - // FIXME: Move some or all of the methods below to a common client and - // server utilities package, when this package becomes available. - - /** - * Extract id. - * - * @param res the res - * @return the string - */ - static protected String extractId(ClientResponse res) { - MultivaluedMap mvm = res.getMetadata(); - String uri = (String) ((List) mvm.get("Location")).get(0); - if (logger.isDebugEnabled()) { - logger.debug("extractId:uri=" + uri); - } - String[] segments = uri.split("/"); - String id = segments[segments.length - 1]; - if (logger.isDebugEnabled()) { - logger.debug("id=" + id); - } - return id; - } - - /** - * Tests can override this method to customize their identifiers. - */ - protected String createIdentifier() { - long identifier = System.currentTimeMillis() + random.nextInt(); - return Long.toString(identifier); - } - - /** - * Tests can override this method to customize their identifiers. - */ - protected String getKnowResourceIdentifier() { - if (knownResourceIdentifier == null) { - knownResourceIdentifier = createIdentifier(); - } - return knownResourceIdentifier; - } - - /** - * Tests can override this method if they have a different knownResourceId - * @return - */ - protected String getKnowResourceId() { - return this.knownResourceId; - } - - /** - * Creates the non existent identifier. - * - * @return the string - */ - protected String createNonExistentIdentifier() { - return Long.toString(Long.MAX_VALUE); - } - - /** - * Extract part. - * - * @param input the input - * @param label the label - * @param clazz the clazz - * @return the object - * @throws Exception the exception - */ - static protected Object extractPart(PoxPayloadIn input, String label, Class clazz) - throws Exception { - Object result = null; - PayloadInputPart payloadInputPart = input.getPart(label); - if (payloadInputPart != null) { - result = payloadInputPart.getBody(); - } else if (logger.isWarnEnabled() == true) { - logger.warn("Payload part: " + label + - " is missing from payload: " + input.getName()); - } - return result; - } - - /** - * Gets the part object. - * - * @param partStr the part str - * @param clazz the clazz - * @return the part object - * @throws JAXBException the jAXB exception - */ - @Deprecated - static protected Object getPartObject(String partStr, Class clazz) - throws JAXBException { - JAXBContext jc = JAXBContext.newInstance(clazz); - ByteArrayInputStream bais = null; - Object obj = null; - try { - bais = new ByteArrayInputStream(partStr.getBytes()); - Unmarshaller um = jc.createUnmarshaller(); - obj = um.unmarshal(bais); - } finally { - if (bais != null) { - try { - bais.close(); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - e.printStackTrace(); - } - } - } - } - return obj; - } - - /** - * Object as xml string. - * - * @param o the o - * @param clazz the clazz - * @return the string - */ - static protected String objectAsXmlString(Object o, Class clazz) { - StringWriter sw = new StringWriter(); - try { - JAXBContext jc = JAXBContext.newInstance(clazz); - Marshaller m = jc.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, - Boolean.TRUE); - m.marshal(o, sw); - } catch (Exception e) { - e.printStackTrace(); - } - return sw.toString(); - } - - static protected String objectAsXmlString(Object o) { - StringWriter sw = new StringWriter(); - try { - JAXBContext jc = JAXBContext.newInstance(o.getClass()); - Marshaller m = jc.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, - Boolean.TRUE); - m.marshal(o, sw); - } catch (Exception e) { - e.printStackTrace(); - } - return sw.toString(); - } - - /** - * getObjectFromFile get object of given class from given file (in classpath) - * @param jaxbClass - * @param fileName of the file to read to construct the object - * @return - * @throws Exception - */ - static protected Object getObjectFromFile(Class jaxbClass, String fileName) - throws Exception { - Object result = null; - - result = FileTools.getJaxbObjectFromFile(jaxbClass, fileName); - - return result; - } - - /** - * Gets the xml document. - * - * @param fileName the file name - * @return the xml document - * @throws Exception the exception - */ - static protected Document getXmlDocument(String fileName) throws Exception { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - File f = new File(fileName); - if (!f.exists()) { - throw new IllegalArgumentException("test data file " + fileName + " not found!"); - } - // Create the builder and parse the file - return factory.newDocumentBuilder().parse(f); - } - - /** - * Gets the xml document as string. - * - * @param fileName the file name - * @return the xml document as string - * @throws Exception the exception - */ - static protected String getXmlDocumentAsString(String fileName) throws Exception { - String result = FileUtils.readFileToString(new File(fileName), "UTF8"); - return result; - } - - /** - * Map as string. - * - * @param map the map - * @return the string - */ - protected String mapAsString(MultivaluedMap map) { - StringBuffer sb = new StringBuffer(); - for (Object entry : map.entrySet()) { - MultivaluedMap.Entry mentry = (MultivaluedMap.Entry) entry; - sb.append(" name=" + mentry.getKey()); - sb.append(" value=" + mentry.getValue() + "\n"); - } - return sb.toString(); - } - - /** - * Returns a 'banner', consisting of a text label inside a pair of prefix - * and suffix strings. - * - * @param label The label to be output inside the banner. - * - * @return The banner. - */ - protected static String getBannerStr(String label) { - StringBuffer sb = new StringBuffer(); - sb.append(BANNER_PREFIX); - sb.append(label); - sb.append(BANNER_SUFFIX); - return sb.toString(); - } - - /** - * Returns a test-specific banner. - * - * @param testName The name of a test method. - * - * @return A test-specific banner. - */ - private static String getNameBanner(String testName) { - testName = (testName == null || testName.trim().isEmpty()) ? - " Test = no test name specified" : " Test = " + testName; - return testName; - } - - /** - * Returns a test-specific banner. - * - * @param testName The name of a test method. - * - * @param testClass The name of a test class. - * - * @return A test-specific banner. - */ - private static String getBanner(String testName, String testClass) { - testName = getNameBanner(testName); - testClass = (testClass == null || testClass.trim().isEmpty()) ? - "Class = no test class specified" : "Class = " + classNameFromPackageName(testClass); - String testLabel = testClass + "\n" + testName; - return getBannerStr(testLabel); - } - - protected static String getTestBanner(String testName, String testClassName) { - return getBanner(testName, testClassName); - } - - protected String getTestBanner(String testName) { - return getTestBanner(testName, this.getClass().getCanonicalName()); - } - - protected void logTestBanner(Logger logger, String testName) { - if (logger.isDebugEnabled() == true) { - logger.debug(getTestBanner(testName)); - } - } - - protected static String classNameFromPackageName(String className) { - if (className == null || className.trim().isEmpty()) { - return className; - } - final char PKG_SEPARATOR = '.'; - int pos = className.lastIndexOf(PKG_SEPARATOR) + 1; - if (pos > 0) { - className = className.substring(pos); - } - return className; - } - - public int assertStatusCode(ClientResponse res, String testName) { - int statusCode = res.getStatus(); - - // Check the status code of the response: does it match the expected response(s)? - logger.debug(testName + ": status = " + statusCode); - Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), - invalidStatusCodeMessage(testRequestType, statusCode)); - Assert.assertEquals(statusCode, testExpectedStatusCode); - - return statusCode; - } - - public static String getUTF8DataFragment() { - return UTF8_DATA_FRAGMENT; - } - - protected String getMimeType(File theFile) { - String result = null; - result = new MimetypesFileTypeMap().getContentType(theFile); - if (result == null) { - logger.debug("Could not get MIME type for file at: " + theFile.getAbsolutePath()); - result = DEFAULT_MIME; - } - - return result; - } - - /* - * Test classes for authority services should override these method and return 'true' - */ - protected boolean isAuthorityClient(CollectionSpaceClient theClient) { - return AuthorityClient.class.isInstance(theClient); - } - - /** - * Deletes all resources created by tests, after all tests have been run. - * - * This cleanup method will always be run, even if one or more tests fail. - * For this reason, it attempts to remove all resources created - * at any point during testing, even if some of those resources - * may be expected to be deleted by certain tests. - */ - @AfterClass(alwaysRun = true) - public void cleanUp() { - String noTestCleanup = System.getProperty(NO_TEST_CLEANUP); - if (Boolean.TRUE.toString().equalsIgnoreCase(noTestCleanup)) { - if (logger.isDebugEnabled()) { - logger.debug("Skipping Cleanup phase ..."); - } - return; - } - if (logger.isDebugEnabled()) { - logger.debug("Cleaning up temporary resources created for testing ..."); - } - CollectionSpaceClient client = this.getClientInstance(); - // - // First, check to see if we need to cleanup any authority items - // - if (this.isAuthorityClient(client) == true) { - AuthorityClient authorityClient = (AuthorityClient) client; - for (Map.Entry entry : allResourceItemIdsCreated.entrySet()) { - String itemResourceId = entry.getKey(); - String authorityResourceId = entry.getValue(); - // Note: Any non-success responses are ignored and not reported. - authorityClient.deleteItem(authorityResourceId, itemResourceId).releaseConnection(); - } - } - // - // Next, delete all other entities include possible authorities. - // - for (String resourceId : allResourceIdsCreated) { - // Note: Any non-success responses are ignored and not reported. - client.delete(resourceId).releaseConnection(); - } - } - - // - // Status code setup methods for tests - // - - /** - * Sets up create tests with malformed xml. - */ - protected void setupCreateWithMalformedXml() { - testExpectedStatusCode = STATUS_BAD_REQUEST; - testRequestType = ServiceRequestType.CREATE; - testSetup(testExpectedStatusCode, testRequestType); - } - - /** - * Sets up create tests with wrong xml schema. - */ - protected void setupCreateWithWrongXmlSchema() { - testExpectedStatusCode = STATUS_BAD_REQUEST; - testRequestType = ServiceRequestType.CREATE; - testSetup(testExpectedStatusCode, testRequestType); - } - - /** - * Sets up read tests. - */ - protected void setupRead() { - testExpectedStatusCode = STATUS_OK; - testRequestType = ServiceRequestType.READ; - testSetup(testExpectedStatusCode, testRequestType); - } - - /** - * Sets up read tests. - */ - protected void setupForbidden() { - testExpectedStatusCode = STATUS_FORBIDDEN; - testRequestType = ServiceRequestType.READ; - testSetup(testExpectedStatusCode, testRequestType); - } - - /** - * Sets up read non existent tests. - */ - protected void setupReadNonExistent() { - testExpectedStatusCode = STATUS_NOT_FOUND; - testRequestType = ServiceRequestType.READ; - testSetup(testExpectedStatusCode, testRequestType); - } - - /** - * Sets up read list tests. - */ - protected void setupReadList() { - testExpectedStatusCode = STATUS_OK; - testRequestType = ServiceRequestType.READ_LIST; - testSetup(testExpectedStatusCode, testRequestType); - } - - /** - * Sets up update tests. - */ - protected void setupUpdate() { - testExpectedStatusCode = STATUS_OK; - testRequestType = ServiceRequestType.UPDATE; - testSetup(testExpectedStatusCode, testRequestType); - } - - /** - * Sets up update tests with an empty entity body. - */ - protected void setupUpdateWithEmptyEntityBody() { - testExpectedStatusCode = STATUS_BAD_REQUEST; - testRequestType = ServiceRequestType.UPDATE; - testSetup(testExpectedStatusCode, testRequestType); - } - - /** - * Sets up update tests with malformed xml. - */ - protected void setupUpdateWithMalformedXml() { - testExpectedStatusCode = STATUS_BAD_REQUEST; - testRequestType = ServiceRequestType.UPDATE; - testSetup(testExpectedStatusCode, testRequestType); - } - - /** - * Sets up update tests with wrong xml schema. - */ - protected void setupUpdateWithWrongXmlSchema() { - testExpectedStatusCode = STATUS_BAD_REQUEST; - testRequestType = ServiceRequestType.UPDATE; - testSetup(testExpectedStatusCode, testRequestType); - } - - /** - * Sets up update non existent tests - */ - protected void setupUpdateNonExistent() { - testExpectedStatusCode = STATUS_NOT_FOUND; - testRequestType = ServiceRequestType.UPDATE; - testSetup(testExpectedStatusCode, testRequestType); - } - - /** - * Sets up delete tests. - */ - protected void setupDelete() { - testExpectedStatusCode = STATUS_OK; - testRequestType = ServiceRequestType.DELETE; - testSetup(testExpectedStatusCode, testRequestType); - } - - // Failure outcomes - - /** - * Sets up delete non existent tests. - */ - protected void setupDeleteNonExistent() { - testExpectedStatusCode = STATUS_NOT_FOUND; - testRequestType = ServiceRequestType.DELETE; - testSetup(testExpectedStatusCode, testRequestType); - } - - /** - * Sets up create tests with empty entity body. - */ - protected void setupCreateWithEmptyEntityBody() { - testExpectedStatusCode = STATUS_BAD_REQUEST; - testRequestType = ServiceRequestType.CREATE; - testSetup(testExpectedStatusCode, testRequestType); - } - - /** - * Sets up create tests with empty entity body. - */ - protected void setupCreateWithInvalidBody() { - testExpectedStatusCode = STATUS_BAD_REQUEST; - testRequestType = ServiceRequestType.CREATE; - testSetup(testExpectedStatusCode, testRequestType); - } - - /** - * Sets up create tests with empty entity body. - */ - protected void setupUpdateWithInvalidBody() { - testExpectedStatusCode = STATUS_BAD_REQUEST; - testRequestType = ServiceRequestType.UPDATE; - testSetup(testExpectedStatusCode, testRequestType); - } - - public void updateWithEmptyEntityBody(String testName) throws Exception { - //FIXME: Should this test really be empty? If so, please comment accordingly. - } - - /* (non-Javadoc) - * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#updateWithMalformedXml(java.lang.String) - */ - public void updateWithMalformedXml(String testName) throws Exception { - //FIXME: Should this test really be empty? If so, please comment accordingly. - } - - /* (non-Javadoc) - * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#updateWithWrongXmlSchema(java.lang.String) - */ - public void updateWithWrongXmlSchema(String testName) throws Exception { - //FIXME: Should this test really be empty? If so, please comment accordingly. - } - -} +/** + * 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 (c) 2009 Regents of the University of California + * + * 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.client.test; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.StringWriter; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import javax.activation.MimetypesFileTypeMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.apache.commons.httpclient.HttpMethodBase; +import org.apache.commons.httpclient.methods.EntityEnclosingMethod; +import org.apache.commons.httpclient.methods.DeleteMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.PutMethod; +import org.apache.commons.httpclient.methods.StringRequestEntity; +import org.apache.commons.io.FileUtils; + +import org.jboss.resteasy.client.ClientResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.w3c.dom.Document; + +import org.collectionspace.services.client.AuthorityClient; +import org.collectionspace.services.client.CollectionSpaceClient; +import org.collectionspace.services.client.PayloadInputPart; +import org.collectionspace.services.client.PoxPayloadIn; +import org.collectionspace.services.client.TestServiceClient; +import org.collectionspace.services.jaxb.AbstractCommonList; +import org.collectionspace.services.common.api.FileTools; + +/** + * BaseServiceTest. + * + * Base abstract class on which client tests of services are based. + * + * $LastChangedRevision$ + * $LastChangedDate$ + */ + +// FIXME: http://issues.collectionspace.org/browse/CSPACE-1685 + +/* + * - Common list type + */ +public abstract class BaseServiceTest { + //A default MIME type result + static protected final String DEFAULT_MIME = "application/octet-stream; charset=ISO-8859-1"; + //Maven's base directory -i.e., the one containing the current pom.xml + protected static final String MAVEN_BASEDIR_PROPERTY = "maven.basedir"; + /** The Constant logger. */ + private static final Logger logger = LoggerFactory.getLogger(BaseServiceTest.class); + /** The Constant serviceClient. */ + protected static final TestServiceClient serviceClient = new TestServiceClient(); + + protected String knownResourceIdentifier = null; + /** Use this to keep track of a single known resource */ + protected String knownResourceId = null; + /* Use this to keep track of resources to delete */ + protected List allResourceIdsCreated = new ArrayList(); + /* Use this to track authority items */ + protected Map allResourceItemIdsCreated = new HashMap(); /* itemCsid, parentCsid */ + /* A runtime/command-line parameter to indicate if we should delete all the test related resource objects */ + static private final String NO_TEST_CLEANUP = "noTestCleanup"; + /* A random number generator */ + static private final Random random = new Random(System.currentTimeMillis()); + + + /** The non-existent id. */ + protected final String NON_EXISTENT_ID = createNonExistentIdentifier(); + /** The expected status code. */ + protected int testExpectedStatusCode = 0; + /** The request type type. */ + protected ServiceRequestType testRequestType = ServiceRequestType.NON_EXISTENT; + + /** The Constant XML_DECLARATION. */ + protected static final String XML_DECLARATION = ""; + /** The Constant MALFORMED_XML_DATA. */ + protected static final String MALFORMED_XML_DATA = XML_DECLARATION + + "wrong schema contentswrong schema contents"; + /** The null charset. */ + private static final String NULL_CHARSET = null; + + /** A visual separator for our test banners */ + private static final String BANNER_SEPARATOR_LINE = "==================================================="; + private static final String BANNER_PREFIX = "\n" + BANNER_SEPARATOR_LINE + "\n"; + private static final String BANNER_SUFFIX = "\n" + BANNER_SEPARATOR_LINE; + + // A Unicode UTF-8 data fragment for use in test payloads: a random sequence, + // unlikely to be encountered in actual collections data, and capable of + // being rendered by the default fonts in many modern operating systems. + // + // This fragment consists of a run of USASCII characters, followed by + // four non-USASCII range Unicode UTF-8 characters: + // + // Δ : Greek capital letter Delta (U+0394) + // Ж : Cyrillic capital letter Zhe with breve (U+04C1) + // Ŵ : Latin capital letter W with circumflex (U+0174) + // Ω : Greek capital letter Omega (U+03A9) + private final static String UTF8_DATA_FRAGMENT = "utf-8-data-fragment:" + + '\u0394' + '\u04C1' + '\u0174' +'\u03A9'; + // + // Status constants + // + protected static final int STATUS_BAD_REQUEST = + Response.Status.BAD_REQUEST.getStatusCode(); + protected static final int STATUS_CREATED = + Response.Status.CREATED.getStatusCode(); + protected static final int STATUS_INTERNAL_SERVER_ERROR = + Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(); + protected static final int STATUS_NOT_FOUND = + Response.Status.NOT_FOUND.getStatusCode(); + protected static final int STATUS_OK = + Response.Status.OK.getStatusCode(); + protected static final int STATUS_FORBIDDEN = + Response.Status.FORBIDDEN.getStatusCode(); + + /** + * Instantiates a new base service test. + */ + public BaseServiceTest() { + super(); + } + + /* + * A getter for retrieving the tests logger + */ + protected Logger getLogger() { + return this.logger; + } + + @BeforeMethod + protected void beforeMethod(Method m) { + logTestBanner(getLogger(), m.getName()); + } + + /** + * Gets the client. + * + * @return the client + */ + abstract protected CollectionSpaceClient getClientInstance(); + + /* + * Subclasses can override this method to return their AbstractCommonList subclass + */ + protected Class getCommonListType() { + return (Class)AbstractCommonList.class; + } + + protected CLT getCommonList( + ClientResponse response) { + return response.getEntity(getCommonListType()); + } + + /** + * Returns the name of the currently running test. + * + * Note: although the return type is listed as Object[][], + * this method instead returns a String. + * + * @param m The currently running test method. + * + */ + @DataProvider(name = "testName") + public static Object[][] testName(Method m) { + return new Object[][]{ + new Object[]{m.getName()} + }; + } + + /** + * Returns the URL path component of the service. + * + * This component will follow directly after the + * base path, if any. + * + * @return The URL path component of the service. + */ + protected abstract String getServicePathComponent(); + + protected abstract String getServiceName(); + + /** + * Reinitializes setup values, to help expose any unintended reuse + * of those values between tests. + */ + protected void clearSetup() { + testExpectedStatusCode = 0; + testRequestType = ServiceRequestType.NON_EXISTENT; + } + + /** + * Sets up create tests. + */ + protected void setupCreate() { + testExpectedStatusCode = STATUS_CREATED; + testRequestType = ServiceRequestType.CREATE; + testSetup(testExpectedStatusCode, testRequestType); + } + + /** + * Initializes setup values for a given test. + * + * @param expectedStatusCode A status code expected to be returned in the response. + * + * @param reqType A type of service request (e.g. CREATE, DELETE). + */ + protected void testSetup( + int expectedStatusCode, + ServiceRequestType reqType) { + clearSetup(); + testExpectedStatusCode = expectedStatusCode; + testRequestType = reqType; + } + + /** + * Returns an error message indicating that the status code returned by a + * specific call to a service does not fall within a set of valid status + * codes for that service. + * + * @param requestType A type of service request (e.g. CREATE, DELETE). + * + * @param statusCode The invalid status code that was returned in the response, + * from submitting that type of request to the service. + * + * @return An error message. + */ + protected String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) { + return "Status code '" + statusCode + + "' in response is NOT within the expected set: " + + requestType.validStatusCodesAsString(); + } + + /** + * Returns the root URL for a service. + * + * This URL consists of a base URL for all services, followed by + * a path component (or components) for a service. + * + * @return The root URL for a service. + */ + protected String getServiceRootURL() { + return serviceClient.getBaseURL() + getServiceName(); //FIXME: REM - This should probably be calling getServicePathComponent() and not getServiceName(); + } + + public String getServiceClientTenantID() { + return serviceClient.getProperty("cspace.tenantID"); + } + + /** + * Returns the URL of a specific resource managed by a service, and + * designated by an identifier (such as a universally unique ID, or UUID). + * + * @param resourceIdentifier An identifier (such as a UUID) for a resource. + * + * @return The URL of a specific resource managed by a service. + */ + protected String getResourceURL(String resourceIdentifier) { + return getServiceRootURL() + "/" + resourceIdentifier; + } + + /** + * Submits an HTTP request to a specified URL, and returns the + * status code of the response. Currently accepts GET and DELETE + * requests. + * + * @param method An HTTP method. + * + * @param url A String representation of a URL. + * + * @return The status code received in the HTTP response. + */ + protected int submitRequest(String method, String url) { + int statusCode = 0; + HttpMethodBase httpMethod = null; + try { + TestServiceClient client = new TestServiceClient(); + if (method.equals(javax.ws.rs.HttpMethod.DELETE)) { + httpMethod = new DeleteMethod(url); + } else if (method.equals(javax.ws.rs.HttpMethod.GET)) { + httpMethod = new GetMethod(url); + } + if (httpMethod != null) { + statusCode = client.getHttpClient().executeMethod(httpMethod); + } + } catch (Exception e) { + logger.error( + "Exception during HTTP " + method + " request to " + + url + ":", e); + } finally { + if (httpMethod != null) httpMethod.releaseConnection(); + } + return statusCode; + } + + /** + * Submits an HTTP request to a specified URL, with the submitted + * entity body, and returns the status code of the response. + * Currently accepts POST and PUT requests. + * + * @param method An HTTP method. + * + * @param url A String representation of a URL. + * + * @param mediaType The media type of the entity body to be submitted. + * + * @param entityStr The contents of the entity body to be submitted. + * + * @return The status code received in the HTTP response. + */ + protected int submitRequest(String method, String url, String mediaType, String entityStr) { + int statusCode = 0; + EntityEnclosingMethod httpMethod = null; + try { + TestServiceClient client = new TestServiceClient(); + if (method.equals(javax.ws.rs.HttpMethod.POST)) { + httpMethod = new PostMethod(url); + } else if (method.equals(javax.ws.rs.HttpMethod.PUT)) { + httpMethod = new PutMethod(url); + } + if (httpMethod != null) { + StringRequestEntity entityBody = + new StringRequestEntity(mediaType, entityStr, NULL_CHARSET); + httpMethod.setRequestEntity(entityBody); + statusCode = client.getHttpClient().executeMethod(httpMethod); + } + } catch (Exception e) { + logger.error( + "Exception during HTTP " + method + " request to " + + url + ":", e); + } finally { + if (httpMethod != null) httpMethod.releaseConnection(); + } + return statusCode; + } + + // FIXME: Move some or all of the methods below to a common client and + // server utilities package, when this package becomes available. + + /** + * Extract id. + * + * @param res the res + * @return the string + */ + static protected String extractId(ClientResponse res) { + MultivaluedMap mvm = res.getMetadata(); + String uri = (String) ((List) mvm.get("Location")).get(0); + if (logger.isDebugEnabled()) { + logger.debug("extractId:uri=" + uri); + } + String[] segments = uri.split("/"); + String id = segments[segments.length - 1]; + if (logger.isDebugEnabled()) { + logger.debug("id=" + id); + } + return id; + } + + /** + * Tests can override this method to customize their identifiers. + */ + protected String createIdentifier() { + long identifier = System.currentTimeMillis() + random.nextInt(); + return Long.toString(identifier); + } + + /** + * Tests can override this method to customize their identifiers. + */ + protected String getKnowResourceIdentifier() { + if (knownResourceIdentifier == null) { + knownResourceIdentifier = createIdentifier(); + } + return knownResourceIdentifier; + } + + /** + * Tests can override this method if they have a different knownResourceId + * @return + */ + protected String getKnowResourceId() { + return this.knownResourceId; + } + + /** + * Creates the non existent identifier. + * + * @return the string + */ + protected String createNonExistentIdentifier() { + return Long.toString(Long.MAX_VALUE); + } + + /** + * Extract part. + * + * @param input the input + * @param label the label + * @param clazz the clazz + * @return the object + * @throws Exception the exception + */ + static protected Object extractPart(PoxPayloadIn input, String label, Class clazz) + throws Exception { + Object result = null; + PayloadInputPart payloadInputPart = input.getPart(label); + if (payloadInputPart != null) { + result = payloadInputPart.getBody(); + } else if (logger.isWarnEnabled() == true) { + logger.warn("Payload part: " + label + + " is missing from payload: " + input.getName()); + } + return result; + } + + /** + * Gets the part object. + * + * @param partStr the part str + * @param clazz the clazz + * @return the part object + * @throws JAXBException the jAXB exception + */ + @Deprecated + static protected Object getPartObject(String partStr, Class clazz) + throws JAXBException { + JAXBContext jc = JAXBContext.newInstance(clazz); + ByteArrayInputStream bais = null; + Object obj = null; + try { + bais = new ByteArrayInputStream(partStr.getBytes()); + Unmarshaller um = jc.createUnmarshaller(); + obj = um.unmarshal(bais); + } finally { + if (bais != null) { + try { + bais.close(); + } catch (Exception e) { + if (logger.isDebugEnabled()) { + e.printStackTrace(); + } + } + } + } + return obj; + } + + /** + * Object as xml string. + * + * @param o the o + * @param clazz the clazz + * @return the string + */ + static protected String objectAsXmlString(Object o, Class clazz) { + StringWriter sw = new StringWriter(); + try { + JAXBContext jc = JAXBContext.newInstance(clazz); + Marshaller m = jc.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, + Boolean.TRUE); + m.marshal(o, sw); + } catch (Exception e) { + e.printStackTrace(); + } + return sw.toString(); + } + + static protected String objectAsXmlString(Object o) { + StringWriter sw = new StringWriter(); + try { + JAXBContext jc = JAXBContext.newInstance(o.getClass()); + Marshaller m = jc.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, + Boolean.TRUE); + m.marshal(o, sw); + } catch (Exception e) { + e.printStackTrace(); + } + return sw.toString(); + } + + /** + * getObjectFromFile get object of given class from given file (in classpath) + * @param jaxbClass + * @param fileName of the file to read to construct the object + * @return + * @throws Exception + */ + static protected Object getObjectFromFile(Class jaxbClass, String fileName) + throws Exception { + Object result = null; + + result = FileTools.getJaxbObjectFromFile(jaxbClass, fileName); + + return result; + } + + /** + * Gets the xml document. + * + * @param fileName the file name + * @return the xml document + * @throws Exception the exception + */ + static protected Document getXmlDocument(String fileName) throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + File f = new File(fileName); + if (!f.exists()) { + throw new IllegalArgumentException("test data file " + fileName + " not found!"); + } + // Create the builder and parse the file + return factory.newDocumentBuilder().parse(f); + } + + /** + * Gets the xml document as string. + * + * @param fileName the file name + * @return the xml document as string + * @throws Exception the exception + */ + static protected String getXmlDocumentAsString(String fileName) throws Exception { + String result = FileUtils.readFileToString(new File(fileName), "UTF8"); + return result; + } + + /** + * Map as string. + * + * @param map the map + * @return the string + */ + protected String mapAsString(MultivaluedMap map) { + StringBuffer sb = new StringBuffer(); + for (Object entry : map.entrySet()) { + MultivaluedMap.Entry mentry = (MultivaluedMap.Entry) entry; + sb.append(" name=" + mentry.getKey()); + sb.append(" value=" + mentry.getValue() + "\n"); + } + return sb.toString(); + } + + /** + * Returns a 'banner', consisting of a text label inside a pair of prefix + * and suffix strings. + * + * @param label The label to be output inside the banner. + * + * @return The banner. + */ + protected static String getBannerStr(String label) { + StringBuffer sb = new StringBuffer(); + sb.append(BANNER_PREFIX); + sb.append(label); + sb.append(BANNER_SUFFIX); + return sb.toString(); + } + + /** + * Returns a test-specific banner. + * + * @param testName The name of a test method. + * + * @return A test-specific banner. + */ + private static String getNameBanner(String testName) { + testName = (testName == null || testName.trim().isEmpty()) ? + " Test = no test name specified" : " Test = " + testName; + return testName; + } + + /** + * Returns a test-specific banner. + * + * @param testName The name of a test method. + * + * @param testClass The name of a test class. + * + * @return A test-specific banner. + */ + private static String getBanner(String testName, String testClass) { + testName = getNameBanner(testName); + testClass = (testClass == null || testClass.trim().isEmpty()) ? + "Class = no test class specified" : "Class = " + classNameFromPackageName(testClass); + String testLabel = testClass + "\n" + testName; + return getBannerStr(testLabel); + } + + protected static String getTestBanner(String testName, String testClassName) { + return getBanner(testName, testClassName); + } + + protected String getTestBanner(String testName) { + return getTestBanner(testName, this.getClass().getCanonicalName()); + } + + protected void logTestBanner(Logger logger, String testName) { + if (logger.isDebugEnabled() == true) { + logger.debug(getTestBanner(testName)); + } + } + + protected static String classNameFromPackageName(String className) { + if (className == null || className.trim().isEmpty()) { + return className; + } + final char PKG_SEPARATOR = '.'; + int pos = className.lastIndexOf(PKG_SEPARATOR) + 1; + if (pos > 0) { + className = className.substring(pos); + } + return className; + } + + public int assertStatusCode(ClientResponse res, String testName) { + int statusCode = res.getStatus(); + + // Check the status code of the response: does it match the expected response(s)? + logger.debug(testName + ": status = " + statusCode); + Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), + invalidStatusCodeMessage(testRequestType, statusCode)); + Assert.assertEquals(statusCode, testExpectedStatusCode); + + return statusCode; + } + + public static String getUTF8DataFragment() { + return UTF8_DATA_FRAGMENT; + } + + protected String getMimeType(File theFile) { + String result = null; + result = new MimetypesFileTypeMap().getContentType(theFile); + if (result == null) { + logger.debug("Could not get MIME type for file at: " + theFile.getAbsolutePath()); + result = DEFAULT_MIME; + } + + return result; + } + + /* + * Test classes for authority services should override these method and return 'true' + */ + protected boolean isAuthorityClient(CollectionSpaceClient theClient) { + return AuthorityClient.class.isInstance(theClient); + } + + /** + * Deletes all resources created by tests, after all tests have been run. + * + * This cleanup method will always be run, even if one or more tests fail. + * For this reason, it attempts to remove all resources created + * at any point during testing, even if some of those resources + * may be expected to be deleted by certain tests. + */ + @AfterClass(alwaysRun = true) + public void cleanUp() { + String noTestCleanup = System.getProperty(NO_TEST_CLEANUP); + if (Boolean.TRUE.toString().equalsIgnoreCase(noTestCleanup)) { + if (logger.isDebugEnabled()) { + logger.debug("Skipping Cleanup phase ..."); + } + return; + } + if (logger.isDebugEnabled()) { + logger.debug("Cleaning up temporary resources created for testing ..."); + } + CollectionSpaceClient client = this.getClientInstance(); + // + // First, check to see if we need to cleanup any authority items + // + if (this.isAuthorityClient(client) == true) { + AuthorityClient authorityClient = (AuthorityClient) client; + for (Map.Entry entry : allResourceItemIdsCreated.entrySet()) { + String itemResourceId = entry.getKey(); + String authorityResourceId = entry.getValue(); + // Note: Any non-success responses are ignored and not reported. + authorityClient.deleteItem(authorityResourceId, itemResourceId).releaseConnection(); + } + } + // + // Next, delete all other entities include possible authorities. + // + for (String resourceId : allResourceIdsCreated) { + // Note: Any non-success responses are ignored and not reported. + client.delete(resourceId).releaseConnection(); + } + } + + // + // Status code setup methods for tests + // + + /** + * Sets up create tests with malformed xml. + */ + protected void setupCreateWithMalformedXml() { + testExpectedStatusCode = STATUS_BAD_REQUEST; + testRequestType = ServiceRequestType.CREATE; + testSetup(testExpectedStatusCode, testRequestType); + } + + /** + * Sets up create tests with wrong xml schema. + */ + protected void setupCreateWithWrongXmlSchema() { + testExpectedStatusCode = STATUS_BAD_REQUEST; + testRequestType = ServiceRequestType.CREATE; + testSetup(testExpectedStatusCode, testRequestType); + } + + /** + * Sets up read tests. + */ + protected void setupRead() { + testExpectedStatusCode = STATUS_OK; + testRequestType = ServiceRequestType.READ; + testSetup(testExpectedStatusCode, testRequestType); + } + + /** + * Sets up read tests. + */ + protected void setupForbidden() { + testExpectedStatusCode = STATUS_FORBIDDEN; + testRequestType = ServiceRequestType.READ; + testSetup(testExpectedStatusCode, testRequestType); + } + + /** + * Sets up read non existent tests. + */ + protected void setupReadNonExistent() { + testExpectedStatusCode = STATUS_NOT_FOUND; + testRequestType = ServiceRequestType.READ; + testSetup(testExpectedStatusCode, testRequestType); + } + + /** + * Sets up read list tests. + */ + protected void setupReadList() { + testExpectedStatusCode = STATUS_OK; + testRequestType = ServiceRequestType.READ_LIST; + testSetup(testExpectedStatusCode, testRequestType); + } + + /** + * Sets up update tests. + */ + protected void setupUpdate() { + testExpectedStatusCode = STATUS_OK; + testRequestType = ServiceRequestType.UPDATE; + testSetup(testExpectedStatusCode, testRequestType); + } + + /** + * Sets up update tests with an empty entity body. + */ + protected void setupUpdateWithEmptyEntityBody() { + testExpectedStatusCode = STATUS_BAD_REQUEST; + testRequestType = ServiceRequestType.UPDATE; + testSetup(testExpectedStatusCode, testRequestType); + } + + /** + * Sets up update tests with malformed xml. + */ + protected void setupUpdateWithMalformedXml() { + testExpectedStatusCode = STATUS_BAD_REQUEST; + testRequestType = ServiceRequestType.UPDATE; + testSetup(testExpectedStatusCode, testRequestType); + } + + /** + * Sets up update tests with wrong xml schema. + */ + protected void setupUpdateWithWrongXmlSchema() { + testExpectedStatusCode = STATUS_BAD_REQUEST; + testRequestType = ServiceRequestType.UPDATE; + testSetup(testExpectedStatusCode, testRequestType); + } + + /** + * Sets up update non existent tests + */ + protected void setupUpdateNonExistent() { + testExpectedStatusCode = STATUS_NOT_FOUND; + testRequestType = ServiceRequestType.UPDATE; + testSetup(testExpectedStatusCode, testRequestType); + } + + /** + * Sets up delete tests. + */ + protected void setupDelete() { + testExpectedStatusCode = STATUS_OK; + testRequestType = ServiceRequestType.DELETE; + testSetup(testExpectedStatusCode, testRequestType); + } + + // Failure outcomes + + /** + * Sets up delete non existent tests. + */ + protected void setupDeleteNonExistent() { + testExpectedStatusCode = STATUS_NOT_FOUND; + testRequestType = ServiceRequestType.DELETE; + testSetup(testExpectedStatusCode, testRequestType); + } + + /** + * Sets up create tests with empty entity body. + */ + protected void setupCreateWithEmptyEntityBody() { + testExpectedStatusCode = STATUS_BAD_REQUEST; + testRequestType = ServiceRequestType.CREATE; + testSetup(testExpectedStatusCode, testRequestType); + } + + /** + * Sets up create tests with empty entity body. + */ + protected void setupCreateWithInvalidBody() { + testExpectedStatusCode = STATUS_BAD_REQUEST; + testRequestType = ServiceRequestType.CREATE; + testSetup(testExpectedStatusCode, testRequestType); + } + + /** + * Sets up create tests with empty entity body. + */ + protected void setupUpdateWithInvalidBody() { + testExpectedStatusCode = STATUS_BAD_REQUEST; + testRequestType = ServiceRequestType.UPDATE; + testSetup(testExpectedStatusCode, testRequestType); + } + + public void updateWithEmptyEntityBody(String testName) throws Exception { + //FIXME: Should this test really be empty? If so, please comment accordingly. + } + + /* (non-Javadoc) + * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#updateWithMalformedXml(java.lang.String) + */ + public void updateWithMalformedXml(String testName) throws Exception { + //FIXME: Should this test really be empty? If so, please comment accordingly. + } + + /* (non-Javadoc) + * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#updateWithWrongXmlSchema(java.lang.String) + */ + public void updateWithWrongXmlSchema(String testName) throws Exception { + //FIXME: Should this test really be empty? If so, please comment accordingly. + } + +} diff --git a/services/client/src/main/java/org/collectionspace/services/client/test/ServiceTestUtils.java b/services/client/src/main/java/org/collectionspace/services/client/test/ServiceTestUtils.java index cbf1d5ab2..b0ab6bf7a 100644 --- a/services/client/src/main/java/org/collectionspace/services/client/test/ServiceTestUtils.java +++ b/services/client/src/main/java/org/collectionspace/services/client/test/ServiceTestUtils.java @@ -1,6 +1,6 @@ -package org.collectionspace.services.client.test; - -public class ServiceTestUtils { - - -} +package org.collectionspace.services.client.test; + +public class ServiceTestUtils { + + +} diff --git a/services/client/src/main/resources/collectionspace-client.properties b/services/client/src/main/resources/collectionspace-client.properties index cdeb3d00c..472295ea7 100644 --- a/services/client/src/main/resources/collectionspace-client.properties +++ b/services/client/src/main/resources/collectionspace-client.properties @@ -1,18 +1,18 @@ -#url of the collectionspace server -cspace.url=http://localhost:8180/cspace-services/ -#cspace.url=http://qa.collectionspace.org:8180/cspace-services/ - -#cspace.url=http://localhost:8200/cspace-services/ -#for sockspy: -#cspace.url=http://localhost:8280/cspace-services/ - -cspace.ssl=false -cspace.auth=true -# default user -cspace.user=admin@core.collectionspace.org -#cspace.user=admin@lifesci.collectionspace.org -cspace.password=Administrator -# default tenant -cspace.tenant=1 -# the tenantID of the numbered tenant: +#url of the collectionspace server +cspace.url=http://localhost:8180/cspace-services/ +#cspace.url=http://qa.collectionspace.org:8180/cspace-services/ + +#cspace.url=http://localhost:8200/cspace-services/ +#for sockspy: +#cspace.url=http://localhost:8280/cspace-services/ + +cspace.ssl=false +cspace.auth=true +# default user +cspace.user=admin@core.collectionspace.org +#cspace.user=admin@lifesci.collectionspace.org +cspace.password=Administrator +# default tenant +cspace.tenant=1 +# the tenantID of the numbered tenant: cspace.tenantID=core.collectionspace.org \ No newline at end of file diff --git a/services/client/src/test/resources/log4j.properties b/services/client/src/test/resources/log4j.properties index 6236c6698..f23adc610 100644 --- a/services/client/src/test/resources/log4j.properties +++ b/services/client/src/test/resources/log4j.properties @@ -1,23 +1,23 @@ -log4j.rootLogger=info, 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=INFO -log4j.logger.org.apache=INFO -log4j.logger.httpclient=INFO -log4j.logger.org.jboss.resteasy=INFO +log4j.rootLogger=info, 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=INFO +log4j.logger.org.apache=INFO +log4j.logger.httpclient=INFO +log4j.logger.org.jboss.resteasy=INFO diff --git a/services/collectionobject/.classpath b/services/collectionobject/.classpath index 046988541..25df93560 100644 --- a/services/collectionobject/.classpath +++ b/services/collectionobject/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/collectionobject/.project b/services/collectionobject/.project index 741d82ba2..fcd836ff1 100644 --- a/services/collectionobject/.project +++ b/services/collectionobject/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.collectionobject - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.collectionobject + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/collectionobject/3rdparty/.classpath b/services/collectionobject/3rdparty/.classpath index 046988541..25df93560 100644 --- a/services/collectionobject/3rdparty/.classpath +++ b/services/collectionobject/3rdparty/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/collectionobject/3rdparty/.project b/services/collectionobject/3rdparty/.project index ce7699e90..242085f8e 100644 --- a/services/collectionobject/3rdparty/.project +++ b/services/collectionobject/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.collectionobject.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.collectionobject.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/collectionobject/3rdparty/build.xml b/services/collectionobject/3rdparty/build.xml index fe823eec2..5e92cd25c 100644 --- a/services/collectionobject/3rdparty/build.xml +++ b/services/collectionobject/3rdparty/build.xml @@ -1,143 +1,143 @@ - - - - collectionobject service 3rd party - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + collectionobject service 3rd party + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/collectionobject/3rdparty/nuxeo-platform-collectionobject-lifesci/build.xml b/services/collectionobject/3rdparty/nuxeo-platform-collectionobject-lifesci/build.xml index 01760d33a..7d3705ba7 100644 --- a/services/collectionobject/3rdparty/nuxeo-platform-collectionobject-lifesci/build.xml +++ b/services/collectionobject/3rdparty/nuxeo-platform-collectionobject-lifesci/build.xml @@ -1,166 +1,166 @@ - - - - Collectionobject nuxeo document type for the lifesci tenant - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + Collectionobject nuxeo document type for the lifesci tenant + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/collectionobject/3rdparty/nuxeo-platform-cs-collectionobject/build.xml b/services/collectionobject/3rdparty/nuxeo-platform-cs-collectionobject/build.xml index 53409adae..e252d382d 100644 --- a/services/collectionobject/3rdparty/nuxeo-platform-cs-collectionobject/build.xml +++ b/services/collectionobject/3rdparty/nuxeo-platform-cs-collectionobject/build.xml @@ -1,169 +1,169 @@ - - - - CollectionobjectsCommon Nuxeo document type - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + CollectionobjectsCommon Nuxeo document type + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/collectionobject/3rdparty/pom.xml b/services/collectionobject/3rdparty/pom.xml index 547e0f642..d9ccb49e3 100644 --- a/services/collectionobject/3rdparty/pom.xml +++ b/services/collectionobject/3rdparty/pom.xml @@ -1,34 +1,34 @@ - - - - org.collectionspace.services - org.collectionspace.services.collectionobject - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.collectionobject.3rdparty - services.collectionobject.3rdparty - pom - - 3rd party build for collectionobject service - - - - collectionobject - CollectionObject - collectionobjects_common - Tenant - cs_default - - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.collectionobject + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.collectionobject.3rdparty + services.collectionobject.3rdparty + pom + + 3rd party build for collectionobject service + + + + collectionobject + CollectionObject + collectionobjects_common + Tenant + cs_default + + + + + + + diff --git a/services/collectionobject/build.xml b/services/collectionobject/build.xml index f77cab499..9011d428e 100644 --- a/services/collectionobject/build.xml +++ b/services/collectionobject/build.xml @@ -1,136 +1,136 @@ - - - - collectionobject service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + collectionobject service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/collectionobject/client/nbactions.xml b/services/collectionobject/client/nbactions.xml index 458dbd096..fffbf0fe6 100644 --- a/services/collectionobject/client/nbactions.xml +++ b/services/collectionobject/client/nbactions.xml @@ -1,16 +1,16 @@ - - - - rebuild - - * - - - clean - install - - - true - - - + + + + rebuild + + * + + + clean + install + + + true + + + diff --git a/services/collectionobject/client/pom.xml b/services/collectionobject/client/pom.xml index 5573c6e26..ce9055c34 100644 --- a/services/collectionobject/client/pom.xml +++ b/services/collectionobject/client/pom.xml @@ -1,109 +1,109 @@ - - - - org.collectionspace.services - org.collectionspace.services.collectionobject - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.collectionobject.client - services.collectionobject.client - - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - - org.collectionspace.services - org.collectionspace.services.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.common - true - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authority.jaxb - true - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.collectionobject.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.organization.client - ${project.version} - test - - - - org.testng - testng - - - org.jboss.resteasy - resteasy-jaxrs - - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - commons-httpclient - commons-httpclient - 3.1 - - - - - cspace-services-collectionobject-client - - - org.apache.maven.plugins - maven-surefire-plugin - - - - test-data.fileName - ${project.build.directory}/test-classes/test-data - - - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.collectionobject + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.collectionobject.client + services.collectionobject.client + + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + + org.collectionspace.services + org.collectionspace.services.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.common + true + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authority.jaxb + true + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.collectionobject.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.organization.client + ${project.version} + test + + + + org.testng + testng + + + org.jboss.resteasy + resteasy-jaxrs + + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + commons-httpclient + commons-httpclient + 3.1 + + + + + cspace-services-collectionobject-client + + + org.apache.maven.plugins + maven-surefire-plugin + + + + test-data.fileName + ${project.build.directory}/test-classes/test-data + + + + + + + + diff --git a/services/collectionobject/client/src/test/resources/log4j.properties b/services/collectionobject/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/collectionobject/client/src/test/resources/log4j.properties +++ b/services/collectionobject/client/src/test/resources/log4j.properties @@ -1,23 +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 +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/collectionobject/installer/build.xml b/services/collectionobject/installer/build.xml index aa7b16f14..1632ba3bd 100644 --- a/services/collectionobject/installer/build.xml +++ b/services/collectionobject/installer/build.xml @@ -1,54 +1,54 @@ - - - - collectionobject service install - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + collectionobject service install + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/collectionobject/jaxb/src/main/java/org/collectionspace/services/CollectionObjectJAXBSchema.java b/services/collectionobject/jaxb/src/main/java/org/collectionspace/services/CollectionObjectJAXBSchema.java index 56774f27a..e74b8634a 100644 --- a/services/collectionobject/jaxb/src/main/java/org/collectionspace/services/CollectionObjectJAXBSchema.java +++ b/services/collectionobject/jaxb/src/main/java/org/collectionspace/services/CollectionObjectJAXBSchema.java @@ -1,20 +1,20 @@ -/** - * - */ -package org.collectionspace.services; - -/** - * @author remillet - * - */ -public interface CollectionObjectJAXBSchema { - final static String OBJECT_NUMBER = "objectNumber"; - final static String BRIEF_DESCRIPTION = "briefDescription"; - final static String COMMENTS = "comments"; - final static String DISTINGUISHING_FEATURES = "distinguishingFeatures"; - final static String OBJECT_NAME = "objectName"; - final static String RESPONSIBLE_DEPARTMENT = "responsibleDepartment"; - final static String TITLE = "title"; -} - - +/** + * + */ +package org.collectionspace.services; + +/** + * @author remillet + * + */ +public interface CollectionObjectJAXBSchema { + final static String OBJECT_NUMBER = "objectNumber"; + final static String BRIEF_DESCRIPTION = "briefDescription"; + final static String COMMENTS = "comments"; + final static String DISTINGUISHING_FEATURES = "distinguishingFeatures"; + final static String OBJECT_NAME = "objectName"; + final static String RESPONSIBLE_DEPARTMENT = "responsibleDepartment"; + final static String TITLE = "title"; +} + + diff --git a/services/collectionobject/jaxb/src/main/java/org/collectionspace/services/CollectionObjectListItemJAXBSchema.java b/services/collectionobject/jaxb/src/main/java/org/collectionspace/services/CollectionObjectListItemJAXBSchema.java index 165dcc53f..a392d9098 100644 --- a/services/collectionobject/jaxb/src/main/java/org/collectionspace/services/CollectionObjectListItemJAXBSchema.java +++ b/services/collectionobject/jaxb/src/main/java/org/collectionspace/services/CollectionObjectListItemJAXBSchema.java @@ -1,12 +1,12 @@ -package org.collectionspace.services; - -public interface CollectionObjectListItemJAXBSchema { - final static String OBJECT_NUMBER = "objectNumber"; - final static String OBJECT_NAME_LIST = "objectNameList"; - final static String OBJECT_NAME = "objectName"; - final static String TITLE_GROUP_LIST = "titleGroupList"; - final static String TITLE = "title"; - final static String RESPONSIBLE_DEPARTMENTS = "responsibleDepartments"; - final static String CSID = "csid"; - final static String URI = "url"; -} +package org.collectionspace.services; + +public interface CollectionObjectListItemJAXBSchema { + final static String OBJECT_NUMBER = "objectNumber"; + final static String OBJECT_NAME_LIST = "objectNameList"; + final static String OBJECT_NAME = "objectName"; + final static String TITLE_GROUP_LIST = "titleGroupList"; + final static String TITLE = "title"; + final static String RESPONSIBLE_DEPARTMENTS = "responsibleDepartments"; + final static String CSID = "csid"; + final static String URI = "url"; +} diff --git a/services/collectionobject/nbactions.xml b/services/collectionobject/nbactions.xml index 458dbd096..fffbf0fe6 100644 --- a/services/collectionobject/nbactions.xml +++ b/services/collectionobject/nbactions.xml @@ -1,16 +1,16 @@ - - - - rebuild - - * - - - clean - install - - - true - - - + + + + rebuild + + * + + + clean + install + + + true + + + diff --git a/services/collectionobject/pom.xml b/services/collectionobject/pom.xml index b00f3e8c1..b5fa272f8 100644 --- a/services/collectionobject/pom.xml +++ b/services/collectionobject/pom.xml @@ -1,36 +1,36 @@ - - - - org.collectionspace.services - org.collectionspace.services.main - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.collectionobject - services.collectionobject - pom - - - jaxb - service - 3rdparty - client - - - - - - - - - - samples - - sample - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.main + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.collectionobject + services.collectionobject + pom + + + jaxb + service + 3rdparty + client + + + + + + + + + + samples + + sample + + + + + + diff --git a/services/collectionobject/sample/.classpath b/services/collectionobject/sample/.classpath index ad5c57cd5..e526a4712 100644 --- a/services/collectionobject/sample/.classpath +++ b/services/collectionobject/sample/.classpath @@ -1,5 +1,5 @@ - - - - - + + + + + diff --git a/services/collectionobject/sample/.project b/services/collectionobject/sample/.project index 0b31a5792..da50f7861 100644 --- a/services/collectionobject/sample/.project +++ b/services/collectionobject/sample/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.collectionobject.client.samples - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.collectionobject.client.samples + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/collectionobject/sample/sample/.project b/services/collectionobject/sample/sample/.project index 18d3006a8..53e179832 100644 --- a/services/collectionobject/sample/sample/.project +++ b/services/collectionobject/sample/sample/.project @@ -1,23 +1,23 @@ - - - org.collectionspace.services.collectionobject.client.sample - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.collectionobject.client.sample + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/collectionobject/sample/sample/src/main/resources/collectionspace-client.properties b/services/collectionobject/sample/sample/src/main/resources/collectionspace-client.properties index 28b7c103e..75c24cd41 100644 --- a/services/collectionobject/sample/sample/src/main/resources/collectionspace-client.properties +++ b/services/collectionobject/sample/sample/src/main/resources/collectionspace-client.properties @@ -1,6 +1,6 @@ -#url of the collectionspace server -cspace.url=http://localhost:8180/cspace-services/ -cspace.ssl=false -cspace.auth=true -cspace.user=test +#url of the collectionspace server +cspace.url=http://localhost:8180/cspace-services/ +cspace.ssl=false +cspace.auth=true +cspace.user=test cspace.password=test \ No newline at end of file diff --git a/services/collectionobject/service/pom.xml b/services/collectionobject/service/pom.xml index 9d131b5cf..ac44b0bf7 100644 --- a/services/collectionobject/service/pom.xml +++ b/services/collectionobject/service/pom.xml @@ -1,167 +1,167 @@ - - - - org.collectionspace.services - org.collectionspace.services.collectionobject - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.collectionobject.service - services.collectionobject.service - jar - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.collectionobject.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.collectionobject.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.intake.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.intake.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.relation.service - ${project.version} - - - - junit - junit - 4.1 - test - - - org.testng - testng - - - - - commons-beanutils - commons-beanutils - 1.6.1 - - - - commons-logging - commons-logging - 1.1 - - - - - javax.security - jaas - 1.0.01 - provided - - - - dom4j - dom4j - 1.6.1 - provided - - - - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - - - org.nuxeo.ecm.core - nuxeo-core-api - - - jboss-remoting - jboss - - - - - - - collectionspace-services-collectionobject - - - com.qmino - miredot-maven-plugin - 1.3.1 - - - - restdoc - - - - - - UHJvamVjdHxvcmcuY29sbGVjdGlvbnNwYWNlLnNlcnZpY2VzLm9yZy5jb2xsZWN0aW9uc3BhY2Uuc2VydmljZXMuY29sbGVjdGlvbm9iamVjdC5zZXJ2aWNlfDIwMTktMDItMjh8dHJ1ZSNNQ3dDRkdHK29EM2hWTVRyckIveDVaWExNcWRBNWhyL0FoUXo2bkVKV1k1NjdabnFBelh6UFdiOW1iRnVIdz09 - - - - - - - - - miredot - MireDot Releases - http://nexus.qmino.com/content/repositories/miredot - - - - - + + + + org.collectionspace.services + org.collectionspace.services.collectionobject + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.collectionobject.service + services.collectionobject.service + jar + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.collectionobject.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.collectionobject.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.intake.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.intake.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.relation.service + ${project.version} + + + + junit + junit + 4.1 + test + + + org.testng + testng + + + + + commons-beanutils + commons-beanutils + 1.6.1 + + + + commons-logging + commons-logging + 1.1 + + + + + javax.security + jaas + 1.0.01 + provided + + + + dom4j + dom4j + 1.6.1 + provided + + + + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + + + org.nuxeo.ecm.core + nuxeo-core-api + + + jboss-remoting + jboss + + + + + + + collectionspace-services-collectionobject + + + com.qmino + miredot-maven-plugin + 1.3.1 + + + + restdoc + + + + + + UHJvamVjdHxvcmcuY29sbGVjdGlvbnNwYWNlLnNlcnZpY2VzLm9yZy5jb2xsZWN0aW9uc3BhY2Uuc2VydmljZXMuY29sbGVjdGlvbm9iamVjdC5zZXJ2aWNlfDIwMTktMDItMjh8dHJ1ZSNNQ3dDRkdHK29EM2hWTVRyckIveDVaWExNcWRBNWhyL0FoUXo2bkVKV1k1NjdabnFBelh6UFdiOW1iRnVIdz09 + + + + + + + + + miredot + MireDot Releases + http://nexus.qmino.com/content/repositories/miredot + + + + + diff --git a/services/collectionobject/service/src/main/java/org/collectionspace/services/collectionobject/nuxeo/CollectionObjectValidatorHandler.java b/services/collectionobject/service/src/main/java/org/collectionspace/services/collectionobject/nuxeo/CollectionObjectValidatorHandler.java index 289fcd548..557600432 100644 --- a/services/collectionobject/service/src/main/java/org/collectionspace/services/collectionobject/nuxeo/CollectionObjectValidatorHandler.java +++ b/services/collectionobject/service/src/main/java/org/collectionspace/services/collectionobject/nuxeo/CollectionObjectValidatorHandler.java @@ -1,138 +1,138 @@ -/** - * 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. - *//** - * 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. - */ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package org.collectionspace.services.collectionobject.nuxeo; - -import org.collectionspace.services.client.PoxPayloadIn; -import org.collectionspace.services.client.PoxPayloadOut; -import org.collectionspace.services.collectionobject.CollectionobjectsCommon; -//import org.collectionspace.services.common.context.MultipartServiceContext; -//import org.collectionspace.services.common.context.ServiceContext; -import org.collectionspace.services.common.document.InvalidDocumentException; -import org.collectionspace.services.common.document.ValidatorHandlerImpl; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * @author - */ -public class CollectionObjectValidatorHandler extends ValidatorHandlerImpl { - - final Logger logger = LoggerFactory.getLogger(CollectionObjectValidatorHandler.class); - - // - // Error Strings - // - private static final String VALIDATION_ERROR = "The collection object record payload was invalid. See log file for more details."; - private static final String OBJECTNUMBER_NULL_ERROR = "The collection object field \"objectNumber\" cannot be empty or missing."; - - @Override - protected Class getCommonPartClass() { - return CollectionobjectsCommon.class; - } - - @Override - protected void handleGet(){ - // TODO Auto-generated method stub - - } - - @Override - protected void handleGetAll() { - // TODO Auto-generated method stub - - } - - @Override - protected void handleUpdate() - throws InvalidDocumentException { - try { - CollectionobjectsCommon co = (CollectionobjectsCommon) getCommonPart(); - validateCollectionobjectsCommon(co); - } catch (AssertionError e) { - if (logger.isErrorEnabled() == true) { - logger.error(e.getMessage(), e); - } - throw new InvalidDocumentException(VALIDATION_ERROR, e); - } - } - - @Override - protected void handleDelete() { - // TODO Auto-generated method stub - - } - - @Override - protected void handleCreate() - throws InvalidDocumentException { - try { - CollectionobjectsCommon co = (CollectionobjectsCommon) getCommonPart(); - validateCollectionobjectsCommon(co); - } catch (AssertionError e) { - if (logger.isErrorEnabled() == true) { - logger.error(e.getMessage(), e); - } - throw new InvalidDocumentException(VALIDATION_ERROR, e); - } - } - - // - // Private Methods - // - private void validateCollectionobjectsCommon(CollectionobjectsCommon co) throws AssertionError { - CS_ASSERT(co != null); - String objectNumber = co.getObjectNumber(); - CS_ASSERT(objectNumber != null); - CS_ASSERT(objectNumber.isEmpty() == false, OBJECTNUMBER_NULL_ERROR); - - } -} +/** + * 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. + *//** + * 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. + */ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.collectionspace.services.collectionobject.nuxeo; + +import org.collectionspace.services.client.PoxPayloadIn; +import org.collectionspace.services.client.PoxPayloadOut; +import org.collectionspace.services.collectionobject.CollectionobjectsCommon; +//import org.collectionspace.services.common.context.MultipartServiceContext; +//import org.collectionspace.services.common.context.ServiceContext; +import org.collectionspace.services.common.document.InvalidDocumentException; +import org.collectionspace.services.common.document.ValidatorHandlerImpl; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * + * @author + */ +public class CollectionObjectValidatorHandler extends ValidatorHandlerImpl { + + final Logger logger = LoggerFactory.getLogger(CollectionObjectValidatorHandler.class); + + // + // Error Strings + // + private static final String VALIDATION_ERROR = "The collection object record payload was invalid. See log file for more details."; + private static final String OBJECTNUMBER_NULL_ERROR = "The collection object field \"objectNumber\" cannot be empty or missing."; + + @Override + protected Class getCommonPartClass() { + return CollectionobjectsCommon.class; + } + + @Override + protected void handleGet(){ + // TODO Auto-generated method stub + + } + + @Override + protected void handleGetAll() { + // TODO Auto-generated method stub + + } + + @Override + protected void handleUpdate() + throws InvalidDocumentException { + try { + CollectionobjectsCommon co = (CollectionobjectsCommon) getCommonPart(); + validateCollectionobjectsCommon(co); + } catch (AssertionError e) { + if (logger.isErrorEnabled() == true) { + logger.error(e.getMessage(), e); + } + throw new InvalidDocumentException(VALIDATION_ERROR, e); + } + } + + @Override + protected void handleDelete() { + // TODO Auto-generated method stub + + } + + @Override + protected void handleCreate() + throws InvalidDocumentException { + try { + CollectionobjectsCommon co = (CollectionobjectsCommon) getCommonPart(); + validateCollectionobjectsCommon(co); + } catch (AssertionError e) { + if (logger.isErrorEnabled() == true) { + logger.error(e.getMessage(), e); + } + throw new InvalidDocumentException(VALIDATION_ERROR, e); + } + } + + // + // Private Methods + // + private void validateCollectionobjectsCommon(CollectionobjectsCommon co) throws AssertionError { + CS_ASSERT(co != null); + String objectNumber = co.getObjectNumber(); + CS_ASSERT(objectNumber != null); + CS_ASSERT(objectNumber.isEmpty() == false, OBJECTNUMBER_NULL_ERROR); + + } +} diff --git a/services/common-api/pom.xml b/services/common-api/pom.xml index 3e69acd12..3a550afd8 100644 --- a/services/common-api/pom.xml +++ b/services/common-api/pom.xml @@ -1,42 +1,42 @@ - - - - org.collectionspace.services - org.collectionspace.services.main - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.common-api - services.common-api - jar - - - org.slf4j - slf4j-api - provided - - - - org.slf4j - slf4j-log4j12 - provided - - - - org.testng - testng - provided - - - - - jaxen - jaxen - 1.1.1 - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.main + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.common-api + services.common-api + jar + + + org.slf4j + slf4j-api + provided + + + + org.slf4j + slf4j-log4j12 + provided + + + + org.testng + testng + provided + + + + + jaxen + jaxen + 1.1.1 + + + + + + diff --git a/services/common-api/src/main/java/org/collectionspace/services/common/api/CommonAPI.java b/services/common-api/src/main/java/org/collectionspace/services/common/api/CommonAPI.java index fffc22727..0e8819ff5 100644 --- a/services/common-api/src/main/java/org/collectionspace/services/common/api/CommonAPI.java +++ b/services/common-api/src/main/java/org/collectionspace/services/common/api/CommonAPI.java @@ -1,23 +1,23 @@ -package org.collectionspace.services.common.api; - -/** - * User: laramie - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ -public class CommonAPI { - public static final String COMMON_API = "services common api version 1"; - public static String getVersionString(){ - return COMMON_API; - } - public static String AuthorityItemCSID_REPLACE="${itemCSID}"; - - public static String showRelations_QP = "showRelations"; - public static String showSiblings_QP = "showSiblings"; - public static String showAllRelations_QP = "showAllRelations"; - - public static final String GENERATE_BUNDLES = "core"; - public static final String GENERATE_BINDINGS = "delta"; - -} - +package org.collectionspace.services.common.api; + +/** + * User: laramie + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public class CommonAPI { + public static final String COMMON_API = "services common api version 1"; + public static String getVersionString(){ + return COMMON_API; + } + public static String AuthorityItemCSID_REPLACE="${itemCSID}"; + + public static String showRelations_QP = "showRelations"; + public static String showSiblings_QP = "showSiblings"; + public static String showAllRelations_QP = "showAllRelations"; + + public static final String GENERATE_BUNDLES = "core"; + public static final String GENERATE_BINDINGS = "delta"; + +} + diff --git a/services/common-api/src/main/java/org/collectionspace/services/common/api/FileTools.java b/services/common-api/src/main/java/org/collectionspace/services/common/api/FileTools.java index b7d65957e..a22218542 100644 --- a/services/common-api/src/main/java/org/collectionspace/services/common/api/FileTools.java +++ b/services/common-api/src/main/java/org/collectionspace/services/common/api/FileTools.java @@ -1,286 +1,286 @@ -/** - * 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.api; - -// This class is designed to avoid dependencies, so it does not include logging, or apache commons. -// There is another cspace utility class, called -// org.collectionspace.services.common.FileUtils -// albeit with different functions, which does have dependencies. - -import java.io.*; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardOpenOption; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Unmarshaller; - -/** - * @author Laramie Crocker - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ -public class FileTools { - - public static String DEFAULT_ENCODING = ""; - public static String UTF8_ENCODING = "UTF-8"; - public static Charset UTF8_CHARSET = java.nio.charset.StandardCharsets.UTF_8; - public static boolean FORCE_CREATE_PARENT_DIRS = true; - private static String JAVA_TEMP_DIR_PROPERTY = "java.io.tmpdir"; - - /** - * getObjectFromStream get object of given class from given inputstream - * @param jaxbClass - * @param is stream to read to construct the object - * @return - * @throws Exception - */ - static protected Object getObjectFromStream(Class jaxbClass, InputStream is) throws Exception { - JAXBContext context = JAXBContext.newInstance(jaxbClass); - Unmarshaller unmarshaller = context.createUnmarshaller(); - //note: setting schema to null will turn validator off - unmarshaller.setSchema(null); - return jaxbClass.cast(unmarshaller.unmarshal(is)); - } - - static public Object getJaxbObjectFromFile(Class jaxbClass, String fileName) - throws Exception { - - JAXBContext context = JAXBContext.newInstance(jaxbClass); - Unmarshaller unmarshaller = context.createUnmarshaller(); - //note: setting schema to null will turn validator off - unmarshaller.setSchema(null); - ClassLoader tccl = Thread.currentThread().getContextClassLoader(); - InputStream is = tccl.getResourceAsStream(fileName); - return getObjectFromStream(jaxbClass, is); - } - - public static String convertStreamToString(InputStream is) { - /* - * To convert the InputStream to String we use the - * Reader.read(char[] buffer) method. We iterate until the - * Reader return -1 which means there's no more data to - * read. We use the StringWriter class to produce the string. - */ - if (is != null) { - Writer writer = new StringWriter(); - - char[] buffer = new char[1024]; - try { - Reader reader = new BufferedReader( - new InputStreamReader(is, "UTF-8")); - int n; - while ((n = reader.read(buffer)) != -1) { - writer.write(buffer, 0, n); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } finally { - try { - is.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - return writer.toString(); - } else { - return ""; - } - } - - public static void forceParentDirectories(String filename) throws IOException { - File theFile = new File(filename); - String parent = theFile.getParent(); - if (parent != null){ - File p = new File(parent); - p.mkdirs(); - System.out.println("Making directory: "+p.getCanonicalPath()); - } - } - - public static boolean copyFile(String sourceFileName, String destFileName, boolean forceParentDirs) throws IOException { - if (sourceFileName == null || destFileName == null) - return false; - if (sourceFileName.equals(destFileName)) - return false; - if (forceParentDirs) - forceParentDirectories(destFileName); - try{ - java.io.FileInputStream in = new java.io.FileInputStream(sourceFileName); - java.io.FileOutputStream out = new java.io.FileOutputStream(destFileName); - try { - byte[] buf = new byte[31000]; - int read = in.read(buf); - while (read > -1){ - out.write(buf, 0, read); - read = in.read(buf); - } - } finally { - in.close(); - out.close(); - } - } catch (Exception e) { - System.out.println(e.toString()); - return false; - } - return true; - } - - public static String readFile(String dir, String relPath){ - File theFile = new File(dir, relPath); - return readFile(theFile); - - } - - public static String readFile(File theFile){ - try { - FileInputStream fis = new FileInputStream(theFile); - byte[] theData = new byte[(int) theFile.length()]; - // need to check the number of bytes read here - int howmany = fis.read(theData); - if (howmany != theData.length){ - System.out.println("ERROR: Couldn't read all of stream! filesize: "+theData.length+" read: "+howmany); - } - fis.close(); - return new String(theData); - } catch (Exception e) { // can't find the file - System.out.println("ERROR: "+e); - return null; - } - } - - public static List readFileAsLines(String filePath) { - List lines = new ArrayList(); - try { - Path path = Paths.get(filePath); - lines = Files.readAllLines(path, UTF8_CHARSET); - } catch (Exception e) { - System.out.println("ERROR: " + e); - return null; - } - return lines; - } - - public static void writeFileFromLines(String filePath, Iterable lines) { - try { - Path path = Paths.get(filePath); - Files.write(path, lines, UTF8_CHARSET, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); - } catch (Exception e) { - System.out.println("ERROR: " + e); - } - } - - public static File saveFile(String dir, String relativeName, String content, boolean forceParentDirs) { - return saveFile(dir, relativeName, content, forceParentDirs, DEFAULT_ENCODING); - } - - public static File saveFile(String dir, String relativeName, String content, boolean forceParentDirs, String encoding) { - File result = null; - PrintWriter writer; - try{ - if (forceParentDirs) forceParentDirectories(dir+'/'+relativeName); - result = new File(dir,relativeName); - if (Tools.notBlank(encoding)) { - writer = new PrintWriter(result, encoding); - } else { - writer = new PrintWriter(result); - } - }catch (Exception e){ - System.out.println("Can't write to file in FileTools.saveFile: " + relativeName + " :: " + e); - return null; - } - writer.write(content); - writer.close(); - return result; - } - - // FIXME: Java 7 now offers an integral method for this purpose, - // java.nio.file.Files.createTempDirectory() - public static File createTmpDir(String filePrefix){ - String tmpDir = System.getProperty(JAVA_TEMP_DIR_PROPERTY); - File result = new File(tmpDir, filePrefix + UUID.randomUUID().toString()); - return result; - } - - /** - * Returns information about the Java temporary directory, - * including its path and selected access rights of the - * current code to that directory. - * - * This can potentially be helpful when troubleshooting issues - * related to code that uses that temporary directory, as per CSPACE-5766. - * - * @return information about the Java temporary directory. - */ - public static String getJavaTmpDirInfo() { - StringBuffer strBuf = new StringBuffer(""); - String tmpDirProperty = System.getProperty(JAVA_TEMP_DIR_PROPERTY); - strBuf.append("\n"); - if (Tools.notBlank(tmpDirProperty)) { - strBuf.append("Java temporary directory property="); - strBuf.append(tmpDirProperty); - strBuf.append("\n"); - } else { - strBuf.append("Could not get Java temporary directory property"); - strBuf.append("\n"); - return strBuf.toString(); - } - File tmpDir = new File(tmpDirProperty); // Throws only NPE, if tmpDirProperty is null - boolean tmpDirExists = false; - boolean tmpDirIsDirectory = false; - try { - tmpDirExists = tmpDir.exists(); - strBuf.append("Temporary directory exists="); - strBuf.append(tmpDirExists); - strBuf.append("\n"); - tmpDirIsDirectory = tmpDir.isDirectory(); - strBuf.append("Temporary directory is actually a directory="); - strBuf.append(tmpDirIsDirectory); - strBuf.append("\n"); - } catch (SecurityException se) { - strBuf.append("Security manager settings prohibit reading temporary directory: "); - strBuf.append(se.getMessage()); - strBuf.append("\n"); - return strBuf.toString(); - } - if (tmpDirExists && tmpDirIsDirectory) { - try { - boolean tmpDirIsWriteable = tmpDir.canWrite(); - strBuf.append("Temporary directory is writeable by application="); - strBuf.append(tmpDirIsWriteable); - } catch (SecurityException se) { - strBuf.append("Security manager settings prohibit writing to temporary directory: "); - strBuf.append(se.getMessage()); - } - } - return strBuf.toString(); - } -} +/** + * 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.api; + +// This class is designed to avoid dependencies, so it does not include logging, or apache commons. +// There is another cspace utility class, called +// org.collectionspace.services.common.FileUtils +// albeit with different functions, which does have dependencies. + +import java.io.*; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; + +/** + * @author Laramie Crocker + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public class FileTools { + + public static String DEFAULT_ENCODING = ""; + public static String UTF8_ENCODING = "UTF-8"; + public static Charset UTF8_CHARSET = java.nio.charset.StandardCharsets.UTF_8; + public static boolean FORCE_CREATE_PARENT_DIRS = true; + private static String JAVA_TEMP_DIR_PROPERTY = "java.io.tmpdir"; + + /** + * getObjectFromStream get object of given class from given inputstream + * @param jaxbClass + * @param is stream to read to construct the object + * @return + * @throws Exception + */ + static protected Object getObjectFromStream(Class jaxbClass, InputStream is) throws Exception { + JAXBContext context = JAXBContext.newInstance(jaxbClass); + Unmarshaller unmarshaller = context.createUnmarshaller(); + //note: setting schema to null will turn validator off + unmarshaller.setSchema(null); + return jaxbClass.cast(unmarshaller.unmarshal(is)); + } + + static public Object getJaxbObjectFromFile(Class jaxbClass, String fileName) + throws Exception { + + JAXBContext context = JAXBContext.newInstance(jaxbClass); + Unmarshaller unmarshaller = context.createUnmarshaller(); + //note: setting schema to null will turn validator off + unmarshaller.setSchema(null); + ClassLoader tccl = Thread.currentThread().getContextClassLoader(); + InputStream is = tccl.getResourceAsStream(fileName); + return getObjectFromStream(jaxbClass, is); + } + + public static String convertStreamToString(InputStream is) { + /* + * To convert the InputStream to String we use the + * Reader.read(char[] buffer) method. We iterate until the + * Reader return -1 which means there's no more data to + * read. We use the StringWriter class to produce the string. + */ + if (is != null) { + Writer writer = new StringWriter(); + + char[] buffer = new char[1024]; + try { + Reader reader = new BufferedReader( + new InputStreamReader(is, "UTF-8")); + int n; + while ((n = reader.read(buffer)) != -1) { + writer.write(buffer, 0, n); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } finally { + try { + is.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + return writer.toString(); + } else { + return ""; + } + } + + public static void forceParentDirectories(String filename) throws IOException { + File theFile = new File(filename); + String parent = theFile.getParent(); + if (parent != null){ + File p = new File(parent); + p.mkdirs(); + System.out.println("Making directory: "+p.getCanonicalPath()); + } + } + + public static boolean copyFile(String sourceFileName, String destFileName, boolean forceParentDirs) throws IOException { + if (sourceFileName == null || destFileName == null) + return false; + if (sourceFileName.equals(destFileName)) + return false; + if (forceParentDirs) + forceParentDirectories(destFileName); + try{ + java.io.FileInputStream in = new java.io.FileInputStream(sourceFileName); + java.io.FileOutputStream out = new java.io.FileOutputStream(destFileName); + try { + byte[] buf = new byte[31000]; + int read = in.read(buf); + while (read > -1){ + out.write(buf, 0, read); + read = in.read(buf); + } + } finally { + in.close(); + out.close(); + } + } catch (Exception e) { + System.out.println(e.toString()); + return false; + } + return true; + } + + public static String readFile(String dir, String relPath){ + File theFile = new File(dir, relPath); + return readFile(theFile); + + } + + public static String readFile(File theFile){ + try { + FileInputStream fis = new FileInputStream(theFile); + byte[] theData = new byte[(int) theFile.length()]; + // need to check the number of bytes read here + int howmany = fis.read(theData); + if (howmany != theData.length){ + System.out.println("ERROR: Couldn't read all of stream! filesize: "+theData.length+" read: "+howmany); + } + fis.close(); + return new String(theData); + } catch (Exception e) { // can't find the file + System.out.println("ERROR: "+e); + return null; + } + } + + public static List readFileAsLines(String filePath) { + List lines = new ArrayList(); + try { + Path path = Paths.get(filePath); + lines = Files.readAllLines(path, UTF8_CHARSET); + } catch (Exception e) { + System.out.println("ERROR: " + e); + return null; + } + return lines; + } + + public static void writeFileFromLines(String filePath, Iterable lines) { + try { + Path path = Paths.get(filePath); + Files.write(path, lines, UTF8_CHARSET, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); + } catch (Exception e) { + System.out.println("ERROR: " + e); + } + } + + public static File saveFile(String dir, String relativeName, String content, boolean forceParentDirs) { + return saveFile(dir, relativeName, content, forceParentDirs, DEFAULT_ENCODING); + } + + public static File saveFile(String dir, String relativeName, String content, boolean forceParentDirs, String encoding) { + File result = null; + PrintWriter writer; + try{ + if (forceParentDirs) forceParentDirectories(dir+'/'+relativeName); + result = new File(dir,relativeName); + if (Tools.notBlank(encoding)) { + writer = new PrintWriter(result, encoding); + } else { + writer = new PrintWriter(result); + } + }catch (Exception e){ + System.out.println("Can't write to file in FileTools.saveFile: " + relativeName + " :: " + e); + return null; + } + writer.write(content); + writer.close(); + return result; + } + + // FIXME: Java 7 now offers an integral method for this purpose, + // java.nio.file.Files.createTempDirectory() + public static File createTmpDir(String filePrefix){ + String tmpDir = System.getProperty(JAVA_TEMP_DIR_PROPERTY); + File result = new File(tmpDir, filePrefix + UUID.randomUUID().toString()); + return result; + } + + /** + * Returns information about the Java temporary directory, + * including its path and selected access rights of the + * current code to that directory. + * + * This can potentially be helpful when troubleshooting issues + * related to code that uses that temporary directory, as per CSPACE-5766. + * + * @return information about the Java temporary directory. + */ + public static String getJavaTmpDirInfo() { + StringBuffer strBuf = new StringBuffer(""); + String tmpDirProperty = System.getProperty(JAVA_TEMP_DIR_PROPERTY); + strBuf.append("\n"); + if (Tools.notBlank(tmpDirProperty)) { + strBuf.append("Java temporary directory property="); + strBuf.append(tmpDirProperty); + strBuf.append("\n"); + } else { + strBuf.append("Could not get Java temporary directory property"); + strBuf.append("\n"); + return strBuf.toString(); + } + File tmpDir = new File(tmpDirProperty); // Throws only NPE, if tmpDirProperty is null + boolean tmpDirExists = false; + boolean tmpDirIsDirectory = false; + try { + tmpDirExists = tmpDir.exists(); + strBuf.append("Temporary directory exists="); + strBuf.append(tmpDirExists); + strBuf.append("\n"); + tmpDirIsDirectory = tmpDir.isDirectory(); + strBuf.append("Temporary directory is actually a directory="); + strBuf.append(tmpDirIsDirectory); + strBuf.append("\n"); + } catch (SecurityException se) { + strBuf.append("Security manager settings prohibit reading temporary directory: "); + strBuf.append(se.getMessage()); + strBuf.append("\n"); + return strBuf.toString(); + } + if (tmpDirExists && tmpDirIsDirectory) { + try { + boolean tmpDirIsWriteable = tmpDir.canWrite(); + strBuf.append("Temporary directory is writeable by application="); + strBuf.append(tmpDirIsWriteable); + } catch (SecurityException se) { + strBuf.append("Security manager settings prohibit writing to temporary directory: "); + strBuf.append(se.getMessage()); + } + } + return strBuf.toString(); + } +} diff --git a/services/common-api/src/main/java/org/collectionspace/services/common/api/RefName.java b/services/common-api/src/main/java/org/collectionspace/services/common/api/RefName.java index dd03e1b31..54b34ac21 100644 --- a/services/common-api/src/main/java/org/collectionspace/services/common/api/RefName.java +++ b/services/common-api/src/main/java/org/collectionspace/services/common/api/RefName.java @@ -1,320 +1,320 @@ -package org.collectionspace.services.common.api; - -import org.collectionspace.services.common.api.RefNameUtils.AuthorityInfo; -import org.collectionspace.services.common.api.RefNameUtils.AuthorityTermInfo; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Usage for this class, if you have a URN and would like to get at its fields, - * is to call one of these methods: - * - * RefName.AuthorityItem item = - * RefName.AuthorityItem.parse(RefName.AUTHORITY_ITEM_EXAMPLE); or - * RefName.Authority authority = - * RefName.Authority.parse(RefName.AUTHORITY_EXAMPLE); - * - * From the object returned, you may set/get any of the public fields. - * - * If you want to format a string urn, then you need to construct either a - * RefName.AuthorityItem or RefName.Authority. You can parse a URN to do so, as - * shown above, or you can construct one with a constructor, setting its fields - * afterwards. A better way is to use one of the build*() methods on this class: - * - * RefName.Authority authority2 = RefName.buildAuthority(tenantName, - * serviceName, authorityShortIdentifier, authorityDisplayName); - * - * RefName.AuthorityItem item2 = RefName.buildAuthorityItem(authority2, - * RefName.EX_itemShortIdentifier, RefName.EX_itemDisplayName); - * - * Note that authority2 is an object, not a String, and is passed in to - * RefName.buildAuthorityItem(). - * - * Then simply call toString() on the object: - * - * String authorityURN = authority2.toString(); - * - * String itemURN = item2.toString(); - * - * These test cases are kept up-to-date in - * - * org.collectionspace.services.common.api.test.RefNameTest - * - * User: laramie - */ -public class RefName { - - /** - * The logger. - */ - private static final Logger logger = LoggerFactory.getLogger(RefName.class); - public static final String URN_PREFIX = "urn:cspace:"; - public static final String URN_NAME_PREFIX = "urn:cspace:name"; - public static final String REFNAME = "refName"; - - public static interface RefNameInterface { - public String toString(); - } - - public static class Authority implements RefNameInterface { - - public String tenantName = ""; - public String resource = ""; - public String csid = null; - public String shortIdentifier = null; - public String displayName = ""; - - public static Authority parse(String urn) { - Authority authority; - try { - RefNameUtils.AuthorityInfo authorityInfo = - RefNameUtils.parseAuthorityInfo(urn); - authority = authorityFromAuthorityInfo(authorityInfo, true); - } catch (IllegalArgumentException iae) { - return null; - } - return authority; - } - - public String getDisplayName() { - return this.getDisplayName(); - } - - public String getShortIdentifier() { - return this.shortIdentifier; - } - - public String getCSID() { - return this.csid; - } - - public boolean equals(Object other) { - if (other == null) { - return false; - } - if (other instanceof Authority) { - Authority ao = (Authority) other; - return (this.tenantName.equals(ao.tenantName) - && this.resource.equals(ao.resource) - && ((this.shortIdentifier != null && - this.shortIdentifier.equals(ao.shortIdentifier)) - || (this.csid != null && this.csid.equals(ao.csid)))); - } else { - return false; - } - } - - public String getRelativeUri() { - StringBuilder sb = new StringBuilder(); - sb.append("/"); - sb.append(resource); - sb.append("/"); - if(csid!=null) { - sb.append(csid); - } else if(shortIdentifier!= null) { - sb.append(URN_NAME_PREFIX); - sb.append("("); - sb.append(shortIdentifier); - sb.append(")"); - } else { - throw new NullPointerException("Authority has neither CSID nor shortID!"); - } - return sb.toString(); - } - - public String toString() { - String displaySuffix = (displayName != null && (!displayName.isEmpty())) ? '\'' + displayName + '\'' : ""; - //return URN_PREFIX + tenantName + ':' + resource + ":" + "name" + "(" + shortIdentifier + ")" + displaySuffix; - StringBuilder sb = new StringBuilder(); - sb.append(URN_PREFIX); - sb.append(tenantName); - sb.append(RefNameUtils.SEPARATOR); - sb.append(resource); - sb.append(RefNameUtils.SEPARATOR); - if(csid!=null) { - sb.append(RefNameUtils.ID_SPECIFIER); - sb.append("("); - sb.append(csid); - sb.append(")"); - } else if(shortIdentifier!= null) { - sb.append(RefNameUtils.NAME_SPECIFIER); - sb.append("("); - sb.append(shortIdentifier); - sb.append(")"); - } else { - throw new NullPointerException("Authority has neither CSID nor shortID!"); - } - sb.append(displaySuffix); - return sb.toString(); - } - - public static Authority buildAuthority( - String tenantName, - String serviceName, - String csid, - String authorityShortIdentifier, - String authorityDisplayName) { - Authority authority = new Authority(); - authority.tenantName = tenantName; - authority.resource = serviceName; - if (Tools.notEmpty(authority.resource)) { - authority.resource = authority.resource.toLowerCase(); - } - authority.csid = csid; - authority.shortIdentifier = authorityShortIdentifier; - authority.displayName = authorityDisplayName; - return authority; - } - } - - public static class AuthorityItem implements RefNameInterface { - - public Authority inAuthority; - public String shortIdentifier = ""; - public String displayName = ""; - - public static AuthorityItem parse(String urn) { - AuthorityItem authorityItem = null; - try { - RefNameUtils.AuthorityTermInfo termInfo = - RefNameUtils.parseAuthorityTermInfo(urn); - authorityItem = authorityItemFromTermInfo(termInfo); - } catch (IllegalArgumentException iae) { - return null; - } - return authorityItem; - } - - public String getDisplayName() { - return this.displayName; - } - - public String getParentShortIdentifier() { - return this.inAuthority.shortIdentifier; - } - - public String getShortIdentifier() { - return this.shortIdentifier; - } - - public boolean equals(Object other) { - if (other == null) { - return false; - } - if (other instanceof AuthorityItem) { - AuthorityItem aio = (AuthorityItem) other; - boolean ok = true; - ok = ok && aio.inAuthority != null; - ok = ok && aio.inAuthority.equals(this.inAuthority); - ok = ok && aio.shortIdentifier.equals(this.shortIdentifier); - ok = ok && aio.displayName.equals(this.displayName); - return ok; - } else { - return false; - } - } - - public String getRelativeUri() { - return inAuthority.getRelativeUri() + "/items/" + URN_NAME_PREFIX + "(" + shortIdentifier + ")"; - } - - public String toString() { - String displaySuffix = (displayName != null && (!displayName.isEmpty())) ? '\'' + displayName + '\'' : ""; - Authority ai = inAuthority; - if (ai == null) { - return URN_PREFIX + "ERROR:inAuthorityNotSet: (" + shortIdentifier + ")" + displaySuffix; - } else { - String base = URN_PREFIX + ai.tenantName + ':' + ai.resource + ":" + "name" + "(" + ai.shortIdentifier + ")"; - String refname = base + ":item:name(" + shortIdentifier + ")" + displaySuffix; - return refname; - } - } - } - - public static AuthorityItem buildAuthorityItem(String tenantName, String serviceName, String authorityShortID, - String itemShortID, String itemDisplayName) { - Authority authority = Authority.buildAuthority(tenantName, serviceName, null, authorityShortID, ""); - return buildAuthorityItem(authority, itemShortID, itemDisplayName); - } - - public static AuthorityItem buildAuthorityItem(String authorityRefName, String itemShortID, String itemDisplayName) { - Authority authority = Authority.parse(authorityRefName); - AuthorityItem item = buildAuthorityItem(authority, itemShortID, itemDisplayName); - return item; - } - - public static AuthorityItem buildAuthorityItem(Authority authority, String itemShortID, String itemDisplayName) { - AuthorityItem item = new AuthorityItem(); - item.inAuthority = authority; - item.shortIdentifier = itemShortID; - item.displayName = itemDisplayName; - return item; - } - - /** - * Use this method to avoid formatting any urn's outside of this unit; - * Caller passes in a shortId, such as "TestAuthority", and method returns - * the correct urn path element, without any path delimiters such as '/' so - * that calling shortIdToPath("TestAuthority") returns - * "urn:cspace:name(TestAuthority)", and then this value may be put into a - * path, such as "/personauthorities/urn:cspace:name(TestAuthority)/items". - */ - public static String shortIdToPath(String shortId) { - return URN_NAME_PREFIX + '(' + shortId + ')'; - } - - /** - * Glue to create an AuthorityTermInfo object, used in RefNameUtils, from the - * highly similar AuthorityItem object, used in this class. - * - * @param termInfo an AuthorityTermInfo object - * @return an AuthorityItem object - */ - private static AuthorityItem authorityItemFromTermInfo(AuthorityTermInfo termInfo) { - if (termInfo == null) { - return null; - } - AuthorityItem authorityItem = new AuthorityItem(); - authorityItem.inAuthority = - authorityFromAuthorityInfo(termInfo.inAuthority, false); - if (termInfo.name != null - && !termInfo.name.trim().isEmpty()) { - authorityItem.shortIdentifier = termInfo.name; - } else { - authorityItem.shortIdentifier = termInfo.csid; - } - authorityItem.displayName = termInfo.displayName; - return authorityItem; - } - - /** - * Glue to create an AuthorityInfo object, used in RefNameUtils, from the - * highly similar Authority object, used in this class. - * - * @param authorityInfo an AuthorityInfo object - * @param includeDisplayName true to include the display name during creation; - * false to exclude it. - * @return an Authority object - */ - private static Authority authorityFromAuthorityInfo(AuthorityInfo authorityInfo, - boolean includeDisplayName) { - if (authorityInfo == null) { - return null; - } - Authority authority = new Authority(); - authority.tenantName = authorityInfo.domain; - authority.resource = authorityInfo.resource; - if (authorityInfo.name != null - && !authorityInfo.name.trim().isEmpty()) { - authority.shortIdentifier = authorityInfo.name; - } - if (authorityInfo.csid != null - && !authorityInfo.csid.trim().isEmpty()) { - authority.csid = authorityInfo.csid; - } - if (includeDisplayName) { - authority.displayName = authorityInfo.displayName; - } - return authority; - } -} +package org.collectionspace.services.common.api; + +import org.collectionspace.services.common.api.RefNameUtils.AuthorityInfo; +import org.collectionspace.services.common.api.RefNameUtils.AuthorityTermInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Usage for this class, if you have a URN and would like to get at its fields, + * is to call one of these methods: + * + * RefName.AuthorityItem item = + * RefName.AuthorityItem.parse(RefName.AUTHORITY_ITEM_EXAMPLE); or + * RefName.Authority authority = + * RefName.Authority.parse(RefName.AUTHORITY_EXAMPLE); + * + * From the object returned, you may set/get any of the public fields. + * + * If you want to format a string urn, then you need to construct either a + * RefName.AuthorityItem or RefName.Authority. You can parse a URN to do so, as + * shown above, or you can construct one with a constructor, setting its fields + * afterwards. A better way is to use one of the build*() methods on this class: + * + * RefName.Authority authority2 = RefName.buildAuthority(tenantName, + * serviceName, authorityShortIdentifier, authorityDisplayName); + * + * RefName.AuthorityItem item2 = RefName.buildAuthorityItem(authority2, + * RefName.EX_itemShortIdentifier, RefName.EX_itemDisplayName); + * + * Note that authority2 is an object, not a String, and is passed in to + * RefName.buildAuthorityItem(). + * + * Then simply call toString() on the object: + * + * String authorityURN = authority2.toString(); + * + * String itemURN = item2.toString(); + * + * These test cases are kept up-to-date in + * + * org.collectionspace.services.common.api.test.RefNameTest + * + * User: laramie + */ +public class RefName { + + /** + * The logger. + */ + private static final Logger logger = LoggerFactory.getLogger(RefName.class); + public static final String URN_PREFIX = "urn:cspace:"; + public static final String URN_NAME_PREFIX = "urn:cspace:name"; + public static final String REFNAME = "refName"; + + public static interface RefNameInterface { + public String toString(); + } + + public static class Authority implements RefNameInterface { + + public String tenantName = ""; + public String resource = ""; + public String csid = null; + public String shortIdentifier = null; + public String displayName = ""; + + public static Authority parse(String urn) { + Authority authority; + try { + RefNameUtils.AuthorityInfo authorityInfo = + RefNameUtils.parseAuthorityInfo(urn); + authority = authorityFromAuthorityInfo(authorityInfo, true); + } catch (IllegalArgumentException iae) { + return null; + } + return authority; + } + + public String getDisplayName() { + return this.getDisplayName(); + } + + public String getShortIdentifier() { + return this.shortIdentifier; + } + + public String getCSID() { + return this.csid; + } + + public boolean equals(Object other) { + if (other == null) { + return false; + } + if (other instanceof Authority) { + Authority ao = (Authority) other; + return (this.tenantName.equals(ao.tenantName) + && this.resource.equals(ao.resource) + && ((this.shortIdentifier != null && + this.shortIdentifier.equals(ao.shortIdentifier)) + || (this.csid != null && this.csid.equals(ao.csid)))); + } else { + return false; + } + } + + public String getRelativeUri() { + StringBuilder sb = new StringBuilder(); + sb.append("/"); + sb.append(resource); + sb.append("/"); + if(csid!=null) { + sb.append(csid); + } else if(shortIdentifier!= null) { + sb.append(URN_NAME_PREFIX); + sb.append("("); + sb.append(shortIdentifier); + sb.append(")"); + } else { + throw new NullPointerException("Authority has neither CSID nor shortID!"); + } + return sb.toString(); + } + + public String toString() { + String displaySuffix = (displayName != null && (!displayName.isEmpty())) ? '\'' + displayName + '\'' : ""; + //return URN_PREFIX + tenantName + ':' + resource + ":" + "name" + "(" + shortIdentifier + ")" + displaySuffix; + StringBuilder sb = new StringBuilder(); + sb.append(URN_PREFIX); + sb.append(tenantName); + sb.append(RefNameUtils.SEPARATOR); + sb.append(resource); + sb.append(RefNameUtils.SEPARATOR); + if(csid!=null) { + sb.append(RefNameUtils.ID_SPECIFIER); + sb.append("("); + sb.append(csid); + sb.append(")"); + } else if(shortIdentifier!= null) { + sb.append(RefNameUtils.NAME_SPECIFIER); + sb.append("("); + sb.append(shortIdentifier); + sb.append(")"); + } else { + throw new NullPointerException("Authority has neither CSID nor shortID!"); + } + sb.append(displaySuffix); + return sb.toString(); + } + + public static Authority buildAuthority( + String tenantName, + String serviceName, + String csid, + String authorityShortIdentifier, + String authorityDisplayName) { + Authority authority = new Authority(); + authority.tenantName = tenantName; + authority.resource = serviceName; + if (Tools.notEmpty(authority.resource)) { + authority.resource = authority.resource.toLowerCase(); + } + authority.csid = csid; + authority.shortIdentifier = authorityShortIdentifier; + authority.displayName = authorityDisplayName; + return authority; + } + } + + public static class AuthorityItem implements RefNameInterface { + + public Authority inAuthority; + public String shortIdentifier = ""; + public String displayName = ""; + + public static AuthorityItem parse(String urn) { + AuthorityItem authorityItem = null; + try { + RefNameUtils.AuthorityTermInfo termInfo = + RefNameUtils.parseAuthorityTermInfo(urn); + authorityItem = authorityItemFromTermInfo(termInfo); + } catch (IllegalArgumentException iae) { + return null; + } + return authorityItem; + } + + public String getDisplayName() { + return this.displayName; + } + + public String getParentShortIdentifier() { + return this.inAuthority.shortIdentifier; + } + + public String getShortIdentifier() { + return this.shortIdentifier; + } + + public boolean equals(Object other) { + if (other == null) { + return false; + } + if (other instanceof AuthorityItem) { + AuthorityItem aio = (AuthorityItem) other; + boolean ok = true; + ok = ok && aio.inAuthority != null; + ok = ok && aio.inAuthority.equals(this.inAuthority); + ok = ok && aio.shortIdentifier.equals(this.shortIdentifier); + ok = ok && aio.displayName.equals(this.displayName); + return ok; + } else { + return false; + } + } + + public String getRelativeUri() { + return inAuthority.getRelativeUri() + "/items/" + URN_NAME_PREFIX + "(" + shortIdentifier + ")"; + } + + public String toString() { + String displaySuffix = (displayName != null && (!displayName.isEmpty())) ? '\'' + displayName + '\'' : ""; + Authority ai = inAuthority; + if (ai == null) { + return URN_PREFIX + "ERROR:inAuthorityNotSet: (" + shortIdentifier + ")" + displaySuffix; + } else { + String base = URN_PREFIX + ai.tenantName + ':' + ai.resource + ":" + "name" + "(" + ai.shortIdentifier + ")"; + String refname = base + ":item:name(" + shortIdentifier + ")" + displaySuffix; + return refname; + } + } + } + + public static AuthorityItem buildAuthorityItem(String tenantName, String serviceName, String authorityShortID, + String itemShortID, String itemDisplayName) { + Authority authority = Authority.buildAuthority(tenantName, serviceName, null, authorityShortID, ""); + return buildAuthorityItem(authority, itemShortID, itemDisplayName); + } + + public static AuthorityItem buildAuthorityItem(String authorityRefName, String itemShortID, String itemDisplayName) { + Authority authority = Authority.parse(authorityRefName); + AuthorityItem item = buildAuthorityItem(authority, itemShortID, itemDisplayName); + return item; + } + + public static AuthorityItem buildAuthorityItem(Authority authority, String itemShortID, String itemDisplayName) { + AuthorityItem item = new AuthorityItem(); + item.inAuthority = authority; + item.shortIdentifier = itemShortID; + item.displayName = itemDisplayName; + return item; + } + + /** + * Use this method to avoid formatting any urn's outside of this unit; + * Caller passes in a shortId, such as "TestAuthority", and method returns + * the correct urn path element, without any path delimiters such as '/' so + * that calling shortIdToPath("TestAuthority") returns + * "urn:cspace:name(TestAuthority)", and then this value may be put into a + * path, such as "/personauthorities/urn:cspace:name(TestAuthority)/items". + */ + public static String shortIdToPath(String shortId) { + return URN_NAME_PREFIX + '(' + shortId + ')'; + } + + /** + * Glue to create an AuthorityTermInfo object, used in RefNameUtils, from the + * highly similar AuthorityItem object, used in this class. + * + * @param termInfo an AuthorityTermInfo object + * @return an AuthorityItem object + */ + private static AuthorityItem authorityItemFromTermInfo(AuthorityTermInfo termInfo) { + if (termInfo == null) { + return null; + } + AuthorityItem authorityItem = new AuthorityItem(); + authorityItem.inAuthority = + authorityFromAuthorityInfo(termInfo.inAuthority, false); + if (termInfo.name != null + && !termInfo.name.trim().isEmpty()) { + authorityItem.shortIdentifier = termInfo.name; + } else { + authorityItem.shortIdentifier = termInfo.csid; + } + authorityItem.displayName = termInfo.displayName; + return authorityItem; + } + + /** + * Glue to create an AuthorityInfo object, used in RefNameUtils, from the + * highly similar Authority object, used in this class. + * + * @param authorityInfo an AuthorityInfo object + * @param includeDisplayName true to include the display name during creation; + * false to exclude it. + * @return an Authority object + */ + private static Authority authorityFromAuthorityInfo(AuthorityInfo authorityInfo, + boolean includeDisplayName) { + if (authorityInfo == null) { + return null; + } + Authority authority = new Authority(); + authority.tenantName = authorityInfo.domain; + authority.resource = authorityInfo.resource; + if (authorityInfo.name != null + && !authorityInfo.name.trim().isEmpty()) { + authority.shortIdentifier = authorityInfo.name; + } + if (authorityInfo.csid != null + && !authorityInfo.csid.trim().isEmpty()) { + authority.csid = authorityInfo.csid; + } + if (includeDisplayName) { + authority.displayName = authorityInfo.displayName; + } + return authority; + } +} diff --git a/services/common-api/src/main/java/org/collectionspace/services/common/api/Tools.java b/services/common-api/src/main/java/org/collectionspace/services/common/api/Tools.java index 933ee30d2..277155e11 100644 --- a/services/common-api/src/main/java/org/collectionspace/services/common/api/Tools.java +++ b/services/common-api/src/main/java/org/collectionspace/services/common/api/Tools.java @@ -1,258 +1,258 @@ -/** - * 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 (c) 2009 Regents of the University of California - * - * 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.api; - -import java.io.File; -import java.util.regex.Pattern; -import java.util.regex.Matcher; - -/** General utility methods. - * @author Laramie Crocker - * v.1.4 - */ -public class Tools { - /** @return first glued to second with the separator string, at most one time - useful for appending paths. - */ - public static String glue(String first, String separator, String second){ - if (first==null) { first = ""; } - if (second==null) { second = ""; } - if (separator==null) { separator = ""; } - if (first.startsWith(separator) && second.startsWith(separator)){ - return first.substring(0, first.length()-separator.length()) + second; - } - if (first.endsWith(separator) || second.startsWith(separator)){ - return first+second; - } - return first+separator+second; - } - - /** Remove all whitespace from a String. */ - public static String squeeze(String s) { - return s.replaceAll("\\s+", ""); - } - - /** Milliseconds from start time as defined by the Date class. */ - public static Long now(){ - return new Long((new java.util.Date()).getTime()); - } - - public static String nowLocale(){ - java.util.Date date = new java.util.Date(); - String result = java.text.DateFormat.getDateTimeInstance().format(date); - date = null; - return result; - } - - /** Handles null strings as empty. */ - public static boolean isEmpty(String str){ - return !notEmpty(str); - } - - /** nulls, empty strings, and empty after trim() are considered blank. */ - public static boolean isBlank(String str){ - return !notBlank(str); - } - - /** Handles null strings as empty. */ - public static boolean notEmpty(String str){ - if (str==null) return false; - if (str.length()==0) return false; - return true; - } - public static boolean notBlank(String str){ - if (str==null) return false; - if (str.length()==0) return false; - if (str.trim().length()==0){ - return false; - } - return true; - } - - /** Handles null strings as false. */ - public static boolean isTrue(String test){ - return notEmpty(test) && (new Boolean(test)).booleanValue(); - } - - /* Example usage of searchAndReplace: - for (Map.Entry entry : variablesMap.entrySet()){ - String key = entry.getKey(); - String replace = entry.getValue(); - String find = "\\$\\{"+key+"\\}"; //must add expression escapes - //because $ and braces are "special", and we want to find "${object.CSID}" - uri = Tools.searchAndReplace(uri, find, replace); - System.out.println("---- REPLACE.uri: "+initURI); - System.out.println("---- REPLACE.find: "+find); - System.out.println("---- REPLACE.replace: "+replace); - System.out.println("---- REPLACE.uri result: "+uri); - } - */ - public static String searchAndReplace(String source, String find, String replace){ - Pattern pattern = Pattern.compile(find); - Matcher matcher = pattern.matcher(source); - String output = matcher.replaceAll(replace); - return output; - } - - public static String searchAndReplaceWithQuoteReplacement(String source, String find, String replace){ - Pattern pattern = Pattern.compile(find); - Matcher matcher = pattern.matcher(source); - String output = matcher.replaceAll(matcher.quoteReplacement(replace)); - return output; - } - - static boolean m_fileSystemIsDOS = "\\".equals(File.separator); - static boolean m_fileSystemIsMac = ":".equals(File.separator); - - public final static String FILE_EXTENSION_SEPARATOR = "."; - - public static boolean fileSystemIsDOS(){return m_fileSystemIsDOS;} - public static boolean fileSystemIsMac(){return m_fileSystemIsMac;} - - public static String fixFilename(String filename){ - if ( m_fileSystemIsDOS ) { - return filename.replace('/', '\\'); - } - if ( m_fileSystemIsMac ) { - String t = filename.replace('/', ':'); - t = t.replace('\\', ':'); - return t; - } - return filename.replace('\\','/'); - } - - public static String join(String dir, String file){ - if ( dir.length() == 0 ) { - return file; - } - dir = Tools.fixFilename(dir); - file = Tools.fixFilename(file); - if ( ! dir.endsWith(File.separator) ) { - dir += File.separator; - } - if ( file.startsWith(File.separator) ) { - file = file.substring(1); - } - return dir + file; - } - - public static String getFilenameExtension(String filename) { - int dot = filename.lastIndexOf(FILE_EXTENSION_SEPARATOR); - return (dot>=0)?filename.substring(dot + 1):null; - } - - public static String getFilenameBase(String filename) { - int dot = filename.lastIndexOf(FILE_EXTENSION_SEPARATOR); - if(dot<0) - dot = filename.length(); - int sep = filename.lastIndexOf(File.separator); // Note: if -1, then sep+1=0, which is right - return filename.substring(sep + 1, dot); - } - - public static String getStackTrace(Throwable e){ - return getStackTrace(e, -1); - } - - public static String implode(String strings[], String sep) { - String implodedString; - if (strings.length == 0) { - implodedString = ""; - } else { - StringBuffer sb = new StringBuffer(); - sb.append(strings[0]); - for (int i = 1; i < strings.length; i++) { - if (strings[i] != null && !strings[i].trim().isEmpty()) { - sb.append(sep); - sb.append(strings[i]); - } - } - implodedString = sb.toString(); - } - return implodedString; - } - - - - - /** @param includeLines if zero, returns all lines */ - public static String getStackTrace(Throwable e, int includeLines){ - if (e==null){ - return ""; - } - java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream(); - java.io.PrintStream ps = new java.io.PrintStream(bos); - e.printStackTrace(ps); - String result = bos.toString(); - try { - if(bos!=null)bos.reset(); - else System.out.println("bos was null, not closing"); - } catch (Exception e2) {System.out.println("ERROR: couldn't reset() bos in Tools "+e2);} - - if (includeLines == 0){ - return result; //return all. - } - StringBuffer sb = new StringBuffer(); - int i = 0; - // BUG - \n is not the separator on all systems. Have to use the system line separator. - String[] foo = result.split("\n"); - for (String line: foo){ - i++; - if (i>includeLines){ - sb.append(" ...first "+i+" lines. "+(foo.length-i)+" more.\r\n"); - return sb.toString(); - } - sb.append(line).append("\r\n"); - } - return sb.toString(); - } - - public static String errorToString(Throwable e, boolean stackTraceOnException){ - return errorToString(e, stackTraceOnException, 0); - } - - /** Takes an Exception object and formats a message that provides more debug information - * suitable for developers for printing to System.out or for logging. Not suitable for - * presentation of error messages to clients. - * @param includeLines if zero, return all lines of stack trace, otherwise return number of lines from top. - */ - public static String errorToString(Throwable e, boolean stackTraceOnException, int includeLines){ - if (e==null){ - return ""; - } - String s = e.toString() + "\r\n -- message: " + e.getMessage(); - - StringBuffer causeBuffer = new StringBuffer(); - Throwable cause = e.getCause(); - while (cause != null){ - causeBuffer.append(cause.getClass().getName()+"::"+cause.getMessage()+"\r\n"); - cause = cause.getCause(); - } - if (causeBuffer.length()>0) s = s + "\r\n -- Causes: "+causeBuffer.toString(); - - - s = s + "\r\n -- Stack Trace: \r\n -- " + getStackTrace(e, includeLines); - return s; - } - - -} +/** + * 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 (c) 2009 Regents of the University of California + * + * 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.api; + +import java.io.File; +import java.util.regex.Pattern; +import java.util.regex.Matcher; + +/** General utility methods. + * @author Laramie Crocker + * v.1.4 + */ +public class Tools { + /** @return first glued to second with the separator string, at most one time - useful for appending paths. + */ + public static String glue(String first, String separator, String second){ + if (first==null) { first = ""; } + if (second==null) { second = ""; } + if (separator==null) { separator = ""; } + if (first.startsWith(separator) && second.startsWith(separator)){ + return first.substring(0, first.length()-separator.length()) + second; + } + if (first.endsWith(separator) || second.startsWith(separator)){ + return first+second; + } + return first+separator+second; + } + + /** Remove all whitespace from a String. */ + public static String squeeze(String s) { + return s.replaceAll("\\s+", ""); + } + + /** Milliseconds from start time as defined by the Date class. */ + public static Long now(){ + return new Long((new java.util.Date()).getTime()); + } + + public static String nowLocale(){ + java.util.Date date = new java.util.Date(); + String result = java.text.DateFormat.getDateTimeInstance().format(date); + date = null; + return result; + } + + /** Handles null strings as empty. */ + public static boolean isEmpty(String str){ + return !notEmpty(str); + } + + /** nulls, empty strings, and empty after trim() are considered blank. */ + public static boolean isBlank(String str){ + return !notBlank(str); + } + + /** Handles null strings as empty. */ + public static boolean notEmpty(String str){ + if (str==null) return false; + if (str.length()==0) return false; + return true; + } + public static boolean notBlank(String str){ + if (str==null) return false; + if (str.length()==0) return false; + if (str.trim().length()==0){ + return false; + } + return true; + } + + /** Handles null strings as false. */ + public static boolean isTrue(String test){ + return notEmpty(test) && (new Boolean(test)).booleanValue(); + } + + /* Example usage of searchAndReplace: + for (Map.Entry entry : variablesMap.entrySet()){ + String key = entry.getKey(); + String replace = entry.getValue(); + String find = "\\$\\{"+key+"\\}"; //must add expression escapes + //because $ and braces are "special", and we want to find "${object.CSID}" + uri = Tools.searchAndReplace(uri, find, replace); + System.out.println("---- REPLACE.uri: "+initURI); + System.out.println("---- REPLACE.find: "+find); + System.out.println("---- REPLACE.replace: "+replace); + System.out.println("---- REPLACE.uri result: "+uri); + } + */ + public static String searchAndReplace(String source, String find, String replace){ + Pattern pattern = Pattern.compile(find); + Matcher matcher = pattern.matcher(source); + String output = matcher.replaceAll(replace); + return output; + } + + public static String searchAndReplaceWithQuoteReplacement(String source, String find, String replace){ + Pattern pattern = Pattern.compile(find); + Matcher matcher = pattern.matcher(source); + String output = matcher.replaceAll(matcher.quoteReplacement(replace)); + return output; + } + + static boolean m_fileSystemIsDOS = "\\".equals(File.separator); + static boolean m_fileSystemIsMac = ":".equals(File.separator); + + public final static String FILE_EXTENSION_SEPARATOR = "."; + + public static boolean fileSystemIsDOS(){return m_fileSystemIsDOS;} + public static boolean fileSystemIsMac(){return m_fileSystemIsMac;} + + public static String fixFilename(String filename){ + if ( m_fileSystemIsDOS ) { + return filename.replace('/', '\\'); + } + if ( m_fileSystemIsMac ) { + String t = filename.replace('/', ':'); + t = t.replace('\\', ':'); + return t; + } + return filename.replace('\\','/'); + } + + public static String join(String dir, String file){ + if ( dir.length() == 0 ) { + return file; + } + dir = Tools.fixFilename(dir); + file = Tools.fixFilename(file); + if ( ! dir.endsWith(File.separator) ) { + dir += File.separator; + } + if ( file.startsWith(File.separator) ) { + file = file.substring(1); + } + return dir + file; + } + + public static String getFilenameExtension(String filename) { + int dot = filename.lastIndexOf(FILE_EXTENSION_SEPARATOR); + return (dot>=0)?filename.substring(dot + 1):null; + } + + public static String getFilenameBase(String filename) { + int dot = filename.lastIndexOf(FILE_EXTENSION_SEPARATOR); + if(dot<0) + dot = filename.length(); + int sep = filename.lastIndexOf(File.separator); // Note: if -1, then sep+1=0, which is right + return filename.substring(sep + 1, dot); + } + + public static String getStackTrace(Throwable e){ + return getStackTrace(e, -1); + } + + public static String implode(String strings[], String sep) { + String implodedString; + if (strings.length == 0) { + implodedString = ""; + } else { + StringBuffer sb = new StringBuffer(); + sb.append(strings[0]); + for (int i = 1; i < strings.length; i++) { + if (strings[i] != null && !strings[i].trim().isEmpty()) { + sb.append(sep); + sb.append(strings[i]); + } + } + implodedString = sb.toString(); + } + return implodedString; + } + + + + + /** @param includeLines if zero, returns all lines */ + public static String getStackTrace(Throwable e, int includeLines){ + if (e==null){ + return ""; + } + java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream(); + java.io.PrintStream ps = new java.io.PrintStream(bos); + e.printStackTrace(ps); + String result = bos.toString(); + try { + if(bos!=null)bos.reset(); + else System.out.println("bos was null, not closing"); + } catch (Exception e2) {System.out.println("ERROR: couldn't reset() bos in Tools "+e2);} + + if (includeLines == 0){ + return result; //return all. + } + StringBuffer sb = new StringBuffer(); + int i = 0; + // BUG - \n is not the separator on all systems. Have to use the system line separator. + String[] foo = result.split("\n"); + for (String line: foo){ + i++; + if (i>includeLines){ + sb.append(" ...first "+i+" lines. "+(foo.length-i)+" more.\r\n"); + return sb.toString(); + } + sb.append(line).append("\r\n"); + } + return sb.toString(); + } + + public static String errorToString(Throwable e, boolean stackTraceOnException){ + return errorToString(e, stackTraceOnException, 0); + } + + /** Takes an Exception object and formats a message that provides more debug information + * suitable for developers for printing to System.out or for logging. Not suitable for + * presentation of error messages to clients. + * @param includeLines if zero, return all lines of stack trace, otherwise return number of lines from top. + */ + public static String errorToString(Throwable e, boolean stackTraceOnException, int includeLines){ + if (e==null){ + return ""; + } + String s = e.toString() + "\r\n -- message: " + e.getMessage(); + + StringBuffer causeBuffer = new StringBuffer(); + Throwable cause = e.getCause(); + while (cause != null){ + causeBuffer.append(cause.getClass().getName()+"::"+cause.getMessage()+"\r\n"); + cause = cause.getCause(); + } + if (causeBuffer.length()>0) s = s + "\r\n -- Causes: "+causeBuffer.toString(); + + + s = s + "\r\n -- Stack Trace: \r\n -- " + getStackTrace(e, includeLines); + return s; + } + + +} diff --git a/services/common-api/src/main/java/org/collectionspace/services/common/api/ZipTools.java b/services/common-api/src/main/java/org/collectionspace/services/common/api/ZipTools.java index f0aaa4be7..f32deba1b 100644 --- a/services/common-api/src/main/java/org/collectionspace/services/common/api/ZipTools.java +++ b/services/common-api/src/main/java/org/collectionspace/services/common/api/ZipTools.java @@ -1,156 +1,156 @@ -/** - * 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.api; - -import java.io.*; -import java.util.*; -import java.util.zip.*; - -/** - * User: laramie - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ -public class ZipTools { - - public static final void copyInputStream(InputStream in, OutputStream out) throws IOException { - try { - byte[] buffer = new byte[1024]; - int len; - while ((len = in.read(buffer)) >= 0) { - out.write(buffer, 0, len); - } - } finally { - in.close(); - out.close(); - } - } - - public static void forceParentDirectories(String filename) throws Exception { - File theFile = new File(filename); - String parent = theFile.getParent(); - if (parent != null) { - File p = new File(parent); - p.mkdirs(); - System.out.println("Making directory: " + p.getCanonicalPath()); - } - } - - /** - * It is HIGHLY recommended to use a baseOutputDir, such as "./", or - * a local directory you know, such as "/tmp/foo", to prevent - * files from being unzipped in your root directory. - */ - public static final void unzip(String zipfileName, String baseOutputDir) { - Enumeration entries; - ZipFile zipFile; - try { - zipFile = new ZipFile(zipfileName); - entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry entry = (ZipEntry) entries.nextElement(); - String entryName = entry.getName(); - String theName = baseOutputDir + '/' + entryName; - if (entry.isDirectory()) { - // Assume directories are stored parents first then children. - System.out.println("Extracting directory: " + entry.getName()); - // This is not robust, just for demonstration purposes. - (new File(theName)).mkdirs(); - continue; - } - //(new File(theName)).mkdirs(); - forceParentDirectories(theName); - System.out.println("Extracting file: " + theName); - copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(theName))); - } - zipFile.close(); - } catch (Exception ioe) { - System.err.println("Unhandled exception:"); - ioe.printStackTrace(); - return; - } - } - - public static void zipDiveDirectory(int stripLeadingPathChars, String directory, String zipFilename) throws Exception { - ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilename)); - zipDir(stripLeadingPathChars, directory, zos); - zos.close(); - } - - public static void zipDir(int stripLeadingPathChars, String dir2zip, ZipOutputStream zos) throws Exception { - File fzipDir = new File(dir2zip); - if (!fzipDir.exists()) { - System.out.println("dir doesn't exist: " + dir2zip); - return; - } - String[] dirList = fzipDir.list(); //get a listing of the directory content - byte[] readBuffer = new byte[2156]; - int bytesIn = 0; - //loop through dirList, and zip the files - for (int i = 0; i < dirList.length; i++) { - File f = new File(fzipDir, dirList[i]); - if (f.isDirectory()) { - //if the File object is a directory, call this function again to add its content recursively - zipDir(stripLeadingPathChars, f.getPath(), zos); //DIVE! - continue; - } - //if we reached here, the File object f was not a directory - String fpath = f.getPath(); - String nameInArchive = fpath.substring(stripLeadingPathChars, fpath.length()); - addToZip(zos, fpath, nameInArchive); - } - } - - public static void addToZip(ZipOutputStream zos, String filename, String nameInArchive) throws Exception { - File file = new File(filename); - if (!file.exists()) { - System.err.println("File does not exist, skipping: " + filename); - return; - } - BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); - int bytesRead; - byte[] buffer = new byte[1024]; - CRC32 crc = new CRC32(); - crc.reset(); - while ((bytesRead = bis.read(buffer)) != -1) { - crc.update(buffer, 0, bytesRead); - } - bis.close(); - // Reset to beginning of input stream - bis = new BufferedInputStream(new FileInputStream(file)); - String nameInArchiveFixed = nameInArchive.replace("\\", "/"); - ZipEntry entry = new ZipEntry(nameInArchiveFixed); - entry.setMethod(ZipEntry.STORED); - entry.setCompressedSize(file.length()); - entry.setSize(file.length()); - entry.setCrc(crc.getValue()); - zos.putNextEntry(entry); - while ((bytesRead = bis.read(buffer)) != -1) { - zos.write(buffer, 0, bytesRead); - } - bis.close(); - } - -} - +/** + * 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.api; + +import java.io.*; +import java.util.*; +import java.util.zip.*; + +/** + * User: laramie + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public class ZipTools { + + public static final void copyInputStream(InputStream in, OutputStream out) throws IOException { + try { + byte[] buffer = new byte[1024]; + int len; + while ((len = in.read(buffer)) >= 0) { + out.write(buffer, 0, len); + } + } finally { + in.close(); + out.close(); + } + } + + public static void forceParentDirectories(String filename) throws Exception { + File theFile = new File(filename); + String parent = theFile.getParent(); + if (parent != null) { + File p = new File(parent); + p.mkdirs(); + System.out.println("Making directory: " + p.getCanonicalPath()); + } + } + + /** + * It is HIGHLY recommended to use a baseOutputDir, such as "./", or + * a local directory you know, such as "/tmp/foo", to prevent + * files from being unzipped in your root directory. + */ + public static final void unzip(String zipfileName, String baseOutputDir) { + Enumeration entries; + ZipFile zipFile; + try { + zipFile = new ZipFile(zipfileName); + entries = zipFile.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = (ZipEntry) entries.nextElement(); + String entryName = entry.getName(); + String theName = baseOutputDir + '/' + entryName; + if (entry.isDirectory()) { + // Assume directories are stored parents first then children. + System.out.println("Extracting directory: " + entry.getName()); + // This is not robust, just for demonstration purposes. + (new File(theName)).mkdirs(); + continue; + } + //(new File(theName)).mkdirs(); + forceParentDirectories(theName); + System.out.println("Extracting file: " + theName); + copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(theName))); + } + zipFile.close(); + } catch (Exception ioe) { + System.err.println("Unhandled exception:"); + ioe.printStackTrace(); + return; + } + } + + public static void zipDiveDirectory(int stripLeadingPathChars, String directory, String zipFilename) throws Exception { + ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilename)); + zipDir(stripLeadingPathChars, directory, zos); + zos.close(); + } + + public static void zipDir(int stripLeadingPathChars, String dir2zip, ZipOutputStream zos) throws Exception { + File fzipDir = new File(dir2zip); + if (!fzipDir.exists()) { + System.out.println("dir doesn't exist: " + dir2zip); + return; + } + String[] dirList = fzipDir.list(); //get a listing of the directory content + byte[] readBuffer = new byte[2156]; + int bytesIn = 0; + //loop through dirList, and zip the files + for (int i = 0; i < dirList.length; i++) { + File f = new File(fzipDir, dirList[i]); + if (f.isDirectory()) { + //if the File object is a directory, call this function again to add its content recursively + zipDir(stripLeadingPathChars, f.getPath(), zos); //DIVE! + continue; + } + //if we reached here, the File object f was not a directory + String fpath = f.getPath(); + String nameInArchive = fpath.substring(stripLeadingPathChars, fpath.length()); + addToZip(zos, fpath, nameInArchive); + } + } + + public static void addToZip(ZipOutputStream zos, String filename, String nameInArchive) throws Exception { + File file = new File(filename); + if (!file.exists()) { + System.err.println("File does not exist, skipping: " + filename); + return; + } + BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); + int bytesRead; + byte[] buffer = new byte[1024]; + CRC32 crc = new CRC32(); + crc.reset(); + while ((bytesRead = bis.read(buffer)) != -1) { + crc.update(buffer, 0, bytesRead); + } + bis.close(); + // Reset to beginning of input stream + bis = new BufferedInputStream(new FileInputStream(file)); + String nameInArchiveFixed = nameInArchive.replace("\\", "/"); + ZipEntry entry = new ZipEntry(nameInArchiveFixed); + entry.setMethod(ZipEntry.STORED); + entry.setCompressedSize(file.length()); + entry.setSize(file.length()); + entry.setCrc(crc.getValue()); + zos.putNextEntry(entry); + while ((bytesRead = bis.read(buffer)) != -1) { + zos.write(buffer, 0, bytesRead); + } + bis.close(); + } + +} + diff --git a/services/common-api/src/test/java/org/collectionspace/services/common/api/test/RefNameTest.java b/services/common-api/src/test/java/org/collectionspace/services/common/api/test/RefNameTest.java index a91162f34..17dc32807 100644 --- a/services/common-api/src/test/java/org/collectionspace/services/common/api/test/RefNameTest.java +++ b/services/common-api/src/test/java/org/collectionspace/services/common/api/test/RefNameTest.java @@ -1,174 +1,174 @@ -/** - * 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 (c) 2009 Regents of the University of California - * - * 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.api.test; - -import org.collectionspace.services.common.api.RefName; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -/** - * User: laramie $LastChangedRevision: $ $LastChangedDate: $ - */ -public class RefNameTest { - - private static final Logger logger = LoggerFactory.getLogger(RefName.class); - - public static final String AUTHORITY_EXAMPLE = "urn:cspace:collectionspace.org:Loansin:name(shortID)'displayName'"; - public static final String AUTHORITY_EXAMPLE2 = "urn:cspace:collectionspace.org:Loansin:name(shortID)"; - public static final String AUTHORITY_ITEM_EXAMPLE = "urn:cspace:collectionspace.org:Loansin:name(shortID):item:name(itemShortID)'itemDisplayName'"; - public static final String TENANT_DOMAIN_NAME = "collectionspace.org"; - public static final String RESOURCE = "Loansin"; - public static final String SHORT_IDENTIFIER = "shortID"; - public static final String DISPLAY_NAME = "displayName"; - public static final String ITEM_SHORT_IDENTIFIER = "itemShortID"; - public static final String ITEM_DISPLAY_NAME = "itemDisplayName"; - public static final String DISPLAY_NAME_WITH_COLONS = "itemDisplayName:itemDisplayName2:itemDisplayName3"; - public static final String DISPLAY_NAME_WITH_PARENS = "itemDisplayName (in parens) and more"; - public static final String DISPLAY_NAME_WITH_APOSTROPHE = "itemDisplayName O'Reilly"; - - - - private void testBanner(String msg) { - String BANNER = "-------------------------------------------------------"; - logger.debug("\r" + BANNER + "\r\n" + this.getClass().getName() + "\r\n" + msg + "\r\n" + BANNER); - } - - private void check(String one, String two, String msg) { - if (one == null || two == null || !(one.equals(two))) { - logger.debug("equals check FAILED. (msg: " + msg + ")\r\none: " + one + "\r\ntwo: " + two + "\r\n"); - } else { - logger.debug("equals check OK. (msg: " + msg + ")\r\none: " + one + "\r\ntwo: " + two + "\r\n"); - } - Assert.assertEquals(one, two, msg); - } - - @Test - public void testRoundTrip() { - testBanner("testRoundTrip"); - RefName.AuthorityItem item = RefName.AuthorityItem.parse(AUTHORITY_ITEM_EXAMPLE); - check(item.toString(), AUTHORITY_ITEM_EXAMPLE, "Item refName"); - check(item.displayName, ITEM_DISPLAY_NAME, "Item display name"); - check(item.shortIdentifier, ITEM_SHORT_IDENTIFIER, "Item short identifier"); - check(item.inAuthority.displayName, "", "displayName from inAuthority should be empty"); - - RefName.Authority authority = RefName.Authority.parse(AUTHORITY_EXAMPLE); - check(authority.toString(), AUTHORITY_EXAMPLE, "Authority refName"); - check(authority.tenantName, TENANT_DOMAIN_NAME, "Authority tenant domain name"); - check(authority.resource, RESOURCE, "Authority resource"); - check(authority.displayName, DISPLAY_NAME, "Authority display name"); - check(authority.shortIdentifier, SHORT_IDENTIFIER, "Authority short identifier"); - - Assert.assertEquals(authority, item.inAuthority, "inAuthority from AuthorityItem.parse() matches Authority from Authority.parse()"); - } - - @Test - public void testConstructors() { - testBanner("testConstructors"); - RefName.AuthorityItem item = RefName.buildAuthorityItem(AUTHORITY_EXAMPLE2, - ITEM_SHORT_IDENTIFIER, - ITEM_DISPLAY_NAME); - RefName.AuthorityItem itemParsed = RefName.AuthorityItem.parse(AUTHORITY_ITEM_EXAMPLE); - check(item.toString(), itemParsed.toString(), "buildAuthorityItem from AUTHORITY_EXAMPLE2 vs. parse(AUTHORITY_ITEM_EXAMPLE)"); - Assert.assertEquals(item, itemParsed); - - - - RefName.Authority authority2 = RefName.Authority.parse(AUTHORITY_EXAMPLE2); - RefName.AuthorityItem item3 = RefName.buildAuthorityItem(authority2, - ITEM_SHORT_IDENTIFIER, - ITEM_DISPLAY_NAME); - check(item.toString(), item3.toString(), "buildAuthorityItem(Authority,str,str) from AUTHORITY_EXAMPLE2 vs. AUTHORITY_ITEM_EXAMPLE"); - Assert.assertEquals(item, item3); - } - - /** - * Test convenience getters that return short identifiers for authorities - * and authority items. - */ - @Test - public void testShortIDGetters() { - testBanner("testShortIDGetters"); - RefName.Authority authority = RefName.Authority.parse(AUTHORITY_EXAMPLE); - Assert.assertEquals(authority.getShortIdentifier(), SHORT_IDENTIFIER, - "Short identifier from parsing parent authority refName does not match value of Authority.getShortIdentifier()."); - - RefName.AuthorityItem item = RefName.buildAuthorityItem(AUTHORITY_EXAMPLE, - ITEM_SHORT_IDENTIFIER, - ITEM_DISPLAY_NAME); - Assert.assertEquals(item.getParentShortIdentifier(), SHORT_IDENTIFIER, - "Parent short identifier from parsing authority refName does not match value of AuthorityItem.getParentShortIdentifier()."); - Assert.assertEquals(item.getShortIdentifier(), ITEM_SHORT_IDENTIFIER, - "Short identifier from item does not match value of AuthorityItem.getShortIdentifier()."); - - RefName.AuthorityItem parsedItem = RefName.AuthorityItem.parse(AUTHORITY_ITEM_EXAMPLE); - Assert.assertEquals(parsedItem.getParentShortIdentifier(), SHORT_IDENTIFIER, - "Parent short identifier from parsing item refName does not match value of AuthorityItem.getParentShortIdentifier()."); - Assert.assertEquals(parsedItem.getShortIdentifier(), ITEM_SHORT_IDENTIFIER, - "Short identifier from parsing item refName does not match value of AuthorityItem.getShortIdentifier()."); - - } - - /** - * Test display names containing refName separator characters, such as - * colons and parens, to ensure that these characters may be validly used - * in display names without adversely impacting refName parsing. - */ - @Test - public void testSeparatorsInDisplayNames() { - testBanner("testSeparatorsInDisplayNames"); - - RefName.AuthorityItem itemWithDisplayNameColons = - RefName.buildAuthorityItem(AUTHORITY_EXAMPLE2, - ITEM_SHORT_IDENTIFIER, - DISPLAY_NAME_WITH_COLONS); - Assert.assertEquals(itemWithDisplayNameColons.getShortIdentifier(), ITEM_SHORT_IDENTIFIER, - "Short identifier from item " + itemWithDisplayNameColons.getShortIdentifier() - + "does not match expected value " + ITEM_SHORT_IDENTIFIER); - Assert.assertEquals(itemWithDisplayNameColons.displayName, DISPLAY_NAME_WITH_COLONS, - "Display name from item " + itemWithDisplayNameColons.displayName - + "does not match expected value " + DISPLAY_NAME_WITH_COLONS); - - RefName.AuthorityItem itemWithDisplayNameParens = - RefName.buildAuthorityItem(AUTHORITY_EXAMPLE2, - ITEM_SHORT_IDENTIFIER, - DISPLAY_NAME_WITH_PARENS); - Assert.assertEquals(itemWithDisplayNameParens.getShortIdentifier(), ITEM_SHORT_IDENTIFIER, - "Short identifier from item " + itemWithDisplayNameParens.getShortIdentifier() - + "does not match expected value " + ITEM_SHORT_IDENTIFIER); - Assert.assertEquals(itemWithDisplayNameParens.displayName, DISPLAY_NAME_WITH_PARENS, - "Display name from item " + itemWithDisplayNameParens.displayName - + "does not match expected value " + DISPLAY_NAME_WITH_PARENS); - - RefName.AuthorityItem itemWithDisplayNameApostrophe = - RefName.buildAuthorityItem(AUTHORITY_EXAMPLE2, - ITEM_SHORT_IDENTIFIER, - DISPLAY_NAME_WITH_APOSTROPHE); - Assert.assertEquals(itemWithDisplayNameApostrophe.getShortIdentifier(), ITEM_SHORT_IDENTIFIER, - "Short identifier from item " + itemWithDisplayNameApostrophe.getShortIdentifier() - + "does not match expected value " + ITEM_SHORT_IDENTIFIER); - Assert.assertEquals(itemWithDisplayNameApostrophe.displayName, DISPLAY_NAME_WITH_APOSTROPHE, - "Display name from item " + itemWithDisplayNameApostrophe.displayName - + "does not match expected value " + DISPLAY_NAME_WITH_APOSTROPHE); - } -} +/** + * 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 (c) 2009 Regents of the University of California + * + * 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.api.test; + +import org.collectionspace.services.common.api.RefName; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.Test; + +/** + * User: laramie $LastChangedRevision: $ $LastChangedDate: $ + */ +public class RefNameTest { + + private static final Logger logger = LoggerFactory.getLogger(RefName.class); + + public static final String AUTHORITY_EXAMPLE = "urn:cspace:collectionspace.org:Loansin:name(shortID)'displayName'"; + public static final String AUTHORITY_EXAMPLE2 = "urn:cspace:collectionspace.org:Loansin:name(shortID)"; + public static final String AUTHORITY_ITEM_EXAMPLE = "urn:cspace:collectionspace.org:Loansin:name(shortID):item:name(itemShortID)'itemDisplayName'"; + public static final String TENANT_DOMAIN_NAME = "collectionspace.org"; + public static final String RESOURCE = "Loansin"; + public static final String SHORT_IDENTIFIER = "shortID"; + public static final String DISPLAY_NAME = "displayName"; + public static final String ITEM_SHORT_IDENTIFIER = "itemShortID"; + public static final String ITEM_DISPLAY_NAME = "itemDisplayName"; + public static final String DISPLAY_NAME_WITH_COLONS = "itemDisplayName:itemDisplayName2:itemDisplayName3"; + public static final String DISPLAY_NAME_WITH_PARENS = "itemDisplayName (in parens) and more"; + public static final String DISPLAY_NAME_WITH_APOSTROPHE = "itemDisplayName O'Reilly"; + + + + private void testBanner(String msg) { + String BANNER = "-------------------------------------------------------"; + logger.debug("\r" + BANNER + "\r\n" + this.getClass().getName() + "\r\n" + msg + "\r\n" + BANNER); + } + + private void check(String one, String two, String msg) { + if (one == null || two == null || !(one.equals(two))) { + logger.debug("equals check FAILED. (msg: " + msg + ")\r\none: " + one + "\r\ntwo: " + two + "\r\n"); + } else { + logger.debug("equals check OK. (msg: " + msg + ")\r\none: " + one + "\r\ntwo: " + two + "\r\n"); + } + Assert.assertEquals(one, two, msg); + } + + @Test + public void testRoundTrip() { + testBanner("testRoundTrip"); + RefName.AuthorityItem item = RefName.AuthorityItem.parse(AUTHORITY_ITEM_EXAMPLE); + check(item.toString(), AUTHORITY_ITEM_EXAMPLE, "Item refName"); + check(item.displayName, ITEM_DISPLAY_NAME, "Item display name"); + check(item.shortIdentifier, ITEM_SHORT_IDENTIFIER, "Item short identifier"); + check(item.inAuthority.displayName, "", "displayName from inAuthority should be empty"); + + RefName.Authority authority = RefName.Authority.parse(AUTHORITY_EXAMPLE); + check(authority.toString(), AUTHORITY_EXAMPLE, "Authority refName"); + check(authority.tenantName, TENANT_DOMAIN_NAME, "Authority tenant domain name"); + check(authority.resource, RESOURCE, "Authority resource"); + check(authority.displayName, DISPLAY_NAME, "Authority display name"); + check(authority.shortIdentifier, SHORT_IDENTIFIER, "Authority short identifier"); + + Assert.assertEquals(authority, item.inAuthority, "inAuthority from AuthorityItem.parse() matches Authority from Authority.parse()"); + } + + @Test + public void testConstructors() { + testBanner("testConstructors"); + RefName.AuthorityItem item = RefName.buildAuthorityItem(AUTHORITY_EXAMPLE2, + ITEM_SHORT_IDENTIFIER, + ITEM_DISPLAY_NAME); + RefName.AuthorityItem itemParsed = RefName.AuthorityItem.parse(AUTHORITY_ITEM_EXAMPLE); + check(item.toString(), itemParsed.toString(), "buildAuthorityItem from AUTHORITY_EXAMPLE2 vs. parse(AUTHORITY_ITEM_EXAMPLE)"); + Assert.assertEquals(item, itemParsed); + + + + RefName.Authority authority2 = RefName.Authority.parse(AUTHORITY_EXAMPLE2); + RefName.AuthorityItem item3 = RefName.buildAuthorityItem(authority2, + ITEM_SHORT_IDENTIFIER, + ITEM_DISPLAY_NAME); + check(item.toString(), item3.toString(), "buildAuthorityItem(Authority,str,str) from AUTHORITY_EXAMPLE2 vs. AUTHORITY_ITEM_EXAMPLE"); + Assert.assertEquals(item, item3); + } + + /** + * Test convenience getters that return short identifiers for authorities + * and authority items. + */ + @Test + public void testShortIDGetters() { + testBanner("testShortIDGetters"); + RefName.Authority authority = RefName.Authority.parse(AUTHORITY_EXAMPLE); + Assert.assertEquals(authority.getShortIdentifier(), SHORT_IDENTIFIER, + "Short identifier from parsing parent authority refName does not match value of Authority.getShortIdentifier()."); + + RefName.AuthorityItem item = RefName.buildAuthorityItem(AUTHORITY_EXAMPLE, + ITEM_SHORT_IDENTIFIER, + ITEM_DISPLAY_NAME); + Assert.assertEquals(item.getParentShortIdentifier(), SHORT_IDENTIFIER, + "Parent short identifier from parsing authority refName does not match value of AuthorityItem.getParentShortIdentifier()."); + Assert.assertEquals(item.getShortIdentifier(), ITEM_SHORT_IDENTIFIER, + "Short identifier from item does not match value of AuthorityItem.getShortIdentifier()."); + + RefName.AuthorityItem parsedItem = RefName.AuthorityItem.parse(AUTHORITY_ITEM_EXAMPLE); + Assert.assertEquals(parsedItem.getParentShortIdentifier(), SHORT_IDENTIFIER, + "Parent short identifier from parsing item refName does not match value of AuthorityItem.getParentShortIdentifier()."); + Assert.assertEquals(parsedItem.getShortIdentifier(), ITEM_SHORT_IDENTIFIER, + "Short identifier from parsing item refName does not match value of AuthorityItem.getShortIdentifier()."); + + } + + /** + * Test display names containing refName separator characters, such as + * colons and parens, to ensure that these characters may be validly used + * in display names without adversely impacting refName parsing. + */ + @Test + public void testSeparatorsInDisplayNames() { + testBanner("testSeparatorsInDisplayNames"); + + RefName.AuthorityItem itemWithDisplayNameColons = + RefName.buildAuthorityItem(AUTHORITY_EXAMPLE2, + ITEM_SHORT_IDENTIFIER, + DISPLAY_NAME_WITH_COLONS); + Assert.assertEquals(itemWithDisplayNameColons.getShortIdentifier(), ITEM_SHORT_IDENTIFIER, + "Short identifier from item " + itemWithDisplayNameColons.getShortIdentifier() + + "does not match expected value " + ITEM_SHORT_IDENTIFIER); + Assert.assertEquals(itemWithDisplayNameColons.displayName, DISPLAY_NAME_WITH_COLONS, + "Display name from item " + itemWithDisplayNameColons.displayName + + "does not match expected value " + DISPLAY_NAME_WITH_COLONS); + + RefName.AuthorityItem itemWithDisplayNameParens = + RefName.buildAuthorityItem(AUTHORITY_EXAMPLE2, + ITEM_SHORT_IDENTIFIER, + DISPLAY_NAME_WITH_PARENS); + Assert.assertEquals(itemWithDisplayNameParens.getShortIdentifier(), ITEM_SHORT_IDENTIFIER, + "Short identifier from item " + itemWithDisplayNameParens.getShortIdentifier() + + "does not match expected value " + ITEM_SHORT_IDENTIFIER); + Assert.assertEquals(itemWithDisplayNameParens.displayName, DISPLAY_NAME_WITH_PARENS, + "Display name from item " + itemWithDisplayNameParens.displayName + + "does not match expected value " + DISPLAY_NAME_WITH_PARENS); + + RefName.AuthorityItem itemWithDisplayNameApostrophe = + RefName.buildAuthorityItem(AUTHORITY_EXAMPLE2, + ITEM_SHORT_IDENTIFIER, + DISPLAY_NAME_WITH_APOSTROPHE); + Assert.assertEquals(itemWithDisplayNameApostrophe.getShortIdentifier(), ITEM_SHORT_IDENTIFIER, + "Short identifier from item " + itemWithDisplayNameApostrophe.getShortIdentifier() + + "does not match expected value " + ITEM_SHORT_IDENTIFIER); + Assert.assertEquals(itemWithDisplayNameApostrophe.displayName, DISPLAY_NAME_WITH_APOSTROPHE, + "Display name from item " + itemWithDisplayNameApostrophe.displayName + + "does not match expected value " + DISPLAY_NAME_WITH_APOSTROPHE); + } +} diff --git a/services/common-test/src/test/resources/log4j.properties b/services/common-test/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/common-test/src/test/resources/log4j.properties +++ b/services/common-test/src/test/resources/log4j.properties @@ -1,23 +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 +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/common/pom.xml b/services/common/pom.xml index 315fd3bf3..c27710e59 100644 --- a/services/common/pom.xml +++ b/services/common/pom.xml @@ -1,410 +1,410 @@ - - - - org.collectionspace.services - org.collectionspace.services.main - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.common - services.common - jar - - - - - org.collectionspace.services - org.collectionspace.services.config - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.3rdparty.nuxeo.thumbnail - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.common-api - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authorization-mgt.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.relation.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.publicitem.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.publicitem.jaxb - ${project.version} - - - - org.collectionspace.services - org.collectionspace.services.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authority.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.hyperjaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authentication.jaxb - ${project.version} - provided - - - org.collectionspace.services - org.collectionspace.services.authentication.service - ${project.version} - provided - - - org.collectionspace.services - org.collectionspace.services.authorization.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authorization.service - ${project.version} - - - - - - org.restlet - org.restlet - 1.0.7 - - - com.noelios.restlet - com.noelios.restlet.ext.httpclient - 1.0.7 - - - com.noelios.restlet - com.noelios.restlet - 1.0.7 - - - - org.slf4j - slf4j-api - provided - - - org.slf4j - slf4j-log4j12 - provided - - - log4j - log4j - 1.2.14 - provided - - - org.apache.commons - commons-jexl - 2.0.1 - - - commons-dbcp - commons-dbcp - 1.3-RC1 - provided - - - commons-codec - commons-codec - 1.4 - - - commons-lang - commons-lang - 2.6 - - - org.apache.tomcat - dbcp - 6.0.33 - provided - - - org.apache.tomcat - catalina - 6.0.33 - provided - - - - - javax.servlet - servlet-api - provided - - - - javax.security - jaas - 1.0.01 - provided - - - javax.security - jacc - 1.0 - provided - - - - mysql - mysql-connector-java - provided - - - postgresql - postgresql - provided - - - javax.persistence - persistence-api - - - - - org.jboss.resteasy - jaxrs-api - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - org.hibernate - hibernate-entitymanager - - - - org.jboss.security - jbosssx - 2.0.3.SP1 - provided - - - org.jboss.remoting - jboss-remoting - provided - - - - org.nuxeo.runtime - nuxeo-runtime-launcher - ${nuxeo.platform.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-mimetype-api - ${nuxeo.platform.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-mimetype-core - ${nuxeo.platform.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-types-api - ${nuxeo.platform.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-types-core - ${nuxeo.platform.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-imaging-core - ${nuxeo.platform.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-imaging-api - ${nuxeo.platform.version} - - - org.nuxeo.ecm.platform - nuxeo-platform-filemanager-api - ${nuxeo.platform.version} - - - org.nuxeo.common - nuxeo-common - ${nuxeo.core.version} - provided - - - org.nuxeo.runtime - nuxeo-runtime - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-api - - - org.nuxeo.ecm.core - nuxeo-core-client - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-query - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-schema - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-storage-sql - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-storage-sql-ra - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-io - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-core-convert - ${nuxeo.core.version} - - - - org.nuxeo.runtime - nuxeo-runtime-osgi - ${nuxeo.core.version} - - - org.nuxeo.ecm.core - nuxeo-opencmis-bindings - ${nuxeo.core.version} - - - org.apache.chemistry.opencmis - chemistry-opencmis-server-bindings - 0.6.0 - classes - - - org.osgi - org.osgi.core - 4.1.0 - - - - commons-fileupload - commons-fileupload - 1.2 - - - ch.elca.el4j.modules - module-xml_merge-common - 3.1 - provided - - - commons-io - commons-io - - - org.springframework.security - spring-security-acl - ${spring.security.version} - provided - - - org.springframework - spring-aop - ${spring.version} - - - - - collectionspace-services-common - install - - - org.jvnet.jaxb2.maven2 - maven-jaxb2-plugin - - - - - + + + + org.collectionspace.services + org.collectionspace.services.main + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.common + services.common + jar + + + + + org.collectionspace.services + org.collectionspace.services.config + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.3rdparty.nuxeo.thumbnail + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.common-api + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authorization-mgt.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.relation.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.publicitem.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.publicitem.jaxb + ${project.version} + + + + org.collectionspace.services + org.collectionspace.services.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authority.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.hyperjaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authentication.jaxb + ${project.version} + provided + + + org.collectionspace.services + org.collectionspace.services.authentication.service + ${project.version} + provided + + + org.collectionspace.services + org.collectionspace.services.authorization.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authorization.service + ${project.version} + + + + + + org.restlet + org.restlet + 1.0.7 + + + com.noelios.restlet + com.noelios.restlet.ext.httpclient + 1.0.7 + + + com.noelios.restlet + com.noelios.restlet + 1.0.7 + + + + org.slf4j + slf4j-api + provided + + + org.slf4j + slf4j-log4j12 + provided + + + log4j + log4j + 1.2.14 + provided + + + org.apache.commons + commons-jexl + 2.0.1 + + + commons-dbcp + commons-dbcp + 1.3-RC1 + provided + + + commons-codec + commons-codec + 1.4 + + + commons-lang + commons-lang + 2.6 + + + org.apache.tomcat + dbcp + 6.0.33 + provided + + + org.apache.tomcat + catalina + 6.0.33 + provided + + + + + javax.servlet + servlet-api + provided + + + + javax.security + jaas + 1.0.01 + provided + + + javax.security + jacc + 1.0 + provided + + + + mysql + mysql-connector-java + provided + + + postgresql + postgresql + provided + + + javax.persistence + persistence-api + + + + + org.jboss.resteasy + jaxrs-api + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + org.hibernate + hibernate-entitymanager + + + + org.jboss.security + jbosssx + 2.0.3.SP1 + provided + + + org.jboss.remoting + jboss-remoting + provided + + + + org.nuxeo.runtime + nuxeo-runtime-launcher + ${nuxeo.platform.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-mimetype-api + ${nuxeo.platform.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-mimetype-core + ${nuxeo.platform.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-types-api + ${nuxeo.platform.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-types-core + ${nuxeo.platform.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-imaging-core + ${nuxeo.platform.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-imaging-api + ${nuxeo.platform.version} + + + org.nuxeo.ecm.platform + nuxeo-platform-filemanager-api + ${nuxeo.platform.version} + + + org.nuxeo.common + nuxeo-common + ${nuxeo.core.version} + provided + + + org.nuxeo.runtime + nuxeo-runtime + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-api + + + org.nuxeo.ecm.core + nuxeo-core-client + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-query + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-schema + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-storage-sql + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-storage-sql-ra + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-io + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-core-convert + ${nuxeo.core.version} + + + + org.nuxeo.runtime + nuxeo-runtime-osgi + ${nuxeo.core.version} + + + org.nuxeo.ecm.core + nuxeo-opencmis-bindings + ${nuxeo.core.version} + + + org.apache.chemistry.opencmis + chemistry-opencmis-server-bindings + 0.6.0 + classes + + + org.osgi + org.osgi.core + 4.1.0 + + + + commons-fileupload + commons-fileupload + 1.2 + + + ch.elca.el4j.modules + module-xml_merge-common + 3.1 + provided + + + commons-io + commons-io + + + org.springframework.security + spring-security-acl + ${spring.security.version} + provided + + + org.springframework + spring-aop + ${spring.version} + + + + + collectionspace-services-common + install + + + org.jvnet.jaxb2.maven2 + maven-jaxb2-plugin + + + + + diff --git a/services/common/src/main/java/org/collectionspace/services/common/AbstractCollectionSpaceResourceImpl.java b/services/common/src/main/java/org/collectionspace/services/common/AbstractCollectionSpaceResourceImpl.java index d85062628..e4ff2d089 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/AbstractCollectionSpaceResourceImpl.java +++ b/services/common/src/main/java/org/collectionspace/services/common/AbstractCollectionSpaceResourceImpl.java @@ -1,511 +1,511 @@ -/** - * 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; - -import java.util.List; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -import org.collectionspace.services.common.CSWebApplicationException; -import org.collectionspace.services.common.api.Tools; -import org.collectionspace.services.common.context.ServiceContext; -import org.collectionspace.services.common.context.ServiceContextProperties; -import org.collectionspace.services.common.document.BadRequestException; -import org.collectionspace.services.common.document.DocumentException; -import org.collectionspace.services.common.document.DocumentHandler; -import org.collectionspace.services.common.document.DocumentNotFoundException; -import org.collectionspace.services.common.document.TransactionException; -import org.collectionspace.services.common.repository.RepositoryClient; -import org.collectionspace.services.common.repository.RepositoryClientFactory; -import org.collectionspace.services.common.security.UnauthorizedException; -import org.collectionspace.services.common.storage.StorageClient; -import org.collectionspace.services.common.storage.jpa.JpaStorageClientImpl; - -import org.jboss.resteasy.core.ResourceMethod; -import org.jboss.resteasy.spi.HttpRequest; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The Class AbstractCollectionSpaceResourceImpl. - * - * @param the generic type - * @param the generic type - */ -public abstract class AbstractCollectionSpaceResourceImpl - implements CollectionSpaceResource { - - protected final Logger logger = LoggerFactory.getLogger(this.getClass()); - - - // Fields for default client factory and client - /** The repository client factory. */ - private RepositoryClientFactory repositoryClientFactory; - - /** The repository client. */ - private RepositoryClient repositoryClient; - - /** The storage client. */ - private StorageClient storageClient; - - /** - * Extract id. - * - * @param res the res - * @return the string - */ - protected static String extractId(Response res) { - MultivaluedMap mvm = res.getMetadata(); - String uri = (String) ((List) mvm.get("Location")).get(0); - String[] segments = uri.split("/"); - String id = segments[segments.length - 1]; - return id; - } - - /** - * Instantiates a new abstract collection space resource. - */ - public AbstractCollectionSpaceResourceImpl() { - repositoryClientFactory = RepositoryClientFactory.getInstance(); - } - - /* (non-Javadoc) - * @see org.collectionspace.services.common.CollectionSpaceResource#getServiceName() - */ - @Override - abstract public String getServiceName(); - - - /* (non-Javadoc) - * @see org.collectionspace.services.common.CollectionSpaceResource#getRepositoryClient(org.collectionspace.services.common.context.ServiceContext) - */ - @Override - synchronized public RepositoryClient getRepositoryClient(ServiceContext ctx) { - if(repositoryClient != null){ - return repositoryClient; - } - repositoryClient = repositoryClientFactory.getClient(ctx.getRepositoryClientName()); - return repositoryClient; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.common.CollectionSpaceResource#getStorageClient(org.collectionspace.services.common.context.ServiceContext) - */ - @Override - synchronized public StorageClient getStorageClient(ServiceContext ctx) { - if(storageClient != null) { - return storageClient; - } - storageClient = new JpaStorageClientImpl(); - return storageClient; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.common.CollectionSpaceResource#createDocumentHandler(org.collectionspace.services.common.context.ServiceContext) - */ - @Override - public DocumentHandler createDocumentHandler(ServiceContext ctx) throws Exception { - DocumentHandler docHandler = createDocumentHandler(ctx, ctx.getInput()); - return docHandler; - } - - /** - * Creates the document handler. - * - * @param ctx the ctx - * @param commonPart the common part - * - * @return the document handler - * - * @throws Exception the exception - */ - public DocumentHandler createDocumentHandler(ServiceContext ctx, - Object commonPart) throws Exception { - DocumentHandler docHandler = ctx.getDocumentHandler(); - docHandler.setCommonPart(commonPart); - return docHandler; - } - - /** - * Creates the service context. - * - * @return the service context< i t, o t> - * - * @throws Exception the exception - */ - protected ServiceContext createServiceContext() throws Exception { - ServiceContext ctx = createServiceContext(this.getServiceName(), - (IT)null, //inputType - null, // The resource map - (UriInfo)null, // The query params - this.getCommonPartClass()); - return ctx; - } - - /** - * Creates the service context. - * - * @param serviceName the service name - * - * @return the service context< i t, o t> - * - * @throws Exception the exception - */ - protected ServiceContext createServiceContext(String serviceName) throws Exception { - ServiceContext ctx = createServiceContext( - serviceName, - (IT)null, // The input part - null, // The resource map - (UriInfo)null, // The queryParams - (Class)null /*input type's Class*/); - return ctx; - } - - protected ServiceContext createServiceContext(String serviceName, UriInfo ui) throws Exception { - ServiceContext ctx = createServiceContext( - serviceName, - (IT)null, // The input part - null, // The resource map - (UriInfo)null, // The queryParams - (Class)null /*input type's Class*/); - ctx.setUriInfo(ui); - return ctx; - } - - /** - * Creates the service context. - * - * @param serviceName the service name - * @param input the input - * - * @return the service context< i t, o t> - * - * @throws Exception the exception - */ - protected ServiceContext createServiceContext(String serviceName, - IT input) throws Exception { - ServiceContext ctx = createServiceContext(serviceName, - input, - null, // The resource map - (UriInfo)null, /*queryParams*/ - (Class)null /*input type's Class*/); - return ctx; - } - - protected ServiceContext createServiceContext(String serviceName, - IT input, - UriInfo uriInfo) throws Exception { - ServiceContext ctx = createServiceContext(serviceName, - input, - null, // The resource map - uriInfo, /*queryParams*/ - (Class)null /*input type's Class*/); - return ctx; - } - - protected ServiceContext createServiceContext(UriInfo uriInfo) throws Exception { - ServiceContext ctx = createServiceContext( - (IT)null, /*input*/ - uriInfo, - (Class)null /*input type's Class*/); - return ctx; - } - - /** - * Creates the service context. - * - * @param input the input - * - * @return the service context< i t, o t> - * - * @throws Exception the exception - */ - protected ServiceContext createServiceContext(IT input) throws Exception { - ServiceContext ctx = createServiceContext( - input, - (Class)null /*input type's Class*/); - return ctx; - } - - protected ServiceContext createServiceContext(IT input, UriInfo uriInfo) throws Exception { - ServiceContext ctx = createServiceContext( - input, - uriInfo, - null ); // The class param/argument - return ctx; - } - - /** - * Creates the service context. - * - * @param input the input - * @param theClass the the class - * - * @return the service context - * - * @throws Exception the exception - */ - protected ServiceContext createServiceContext(IT input, Class theClass) throws Exception { - ServiceContext ctx = createServiceContext( - input, - (UriInfo)null, //queryParams, - theClass); - return ctx; - } - - protected ServiceContext createServiceContext(IT input, Class theClass, UriInfo uriInfo) throws Exception { - ServiceContext ctx = createServiceContext( - input, - uriInfo, - theClass); - return ctx; - } - - protected ServiceContext createServiceContext( - String serviceName, - ResourceMap resourceMap, - UriInfo uriInfo) throws Exception { - ServiceContext ctx = createServiceContext( - serviceName, - null, // The input object - resourceMap, - uriInfo, - null /* the class of the input type */); - return ctx; - } - - protected ServiceContext createServiceContext( - IT input, - ResourceMap resourceMap, - UriInfo uriInfo) throws Exception { - ServiceContext ctx = createServiceContext( - this.getServiceName(), - input, - resourceMap, - uriInfo, - null /* the class of the input type */); - return ctx; - } - - protected ServiceContext createServiceContext( - String serviceName, - IT input, - ResourceMap resourceMap, - UriInfo uriInfo) throws Exception { - ServiceContext ctx = createServiceContext( - serviceName, - input, - resourceMap, - uriInfo, - null /* the class of the input type */); - return ctx; - } - - /** - * Creates the service context. - * - * @param input the input - * @param queryParams the query params - * @param theClass the the class - * - * @return the service context< i t, o t> - * - * @throws Exception the exception - */ - private ServiceContext createServiceContext( - IT input, - UriInfo uriInfo, - Class theClass) throws Exception { - return createServiceContext(this.getServiceName(), - input, - null, // The resource map - uriInfo, - theClass); - } - - /** - * Creates the service context. - * - * @param serviceName the service name - * @param input the input - * @param queryParams the query params - * @param theClass the the class - * - * @return the service context< i t, o t> - * - * @throws Exception the exception - */ - private ServiceContext createServiceContext( - String serviceName, - IT input, - ResourceMap resourceMap, - UriInfo uriInfo, - Class theClass) throws Exception { - ServiceContext ctx = getServiceContextFactory().createServiceContext( - serviceName, - input, - resourceMap, - uriInfo, - theClass != null ? theClass.getPackage().getName() : null, - theClass != null ? theClass.getName() : null); - if (theClass != null) { - ctx.setProperty(ServiceContextProperties.ENTITY_CLASS, theClass); - } - - return ctx; - } - - /** - * Gets the version string. - * - * @return the version string - */ - abstract protected String getVersionString(); - - /** - * Gets the version. - * - * @return the version - */ - @GET - @Path("/version") - @Produces("application/xml") - public Version getVersion() { - Version result = new Version(); - - result.setVersionString(getVersionString()); - - return result; - } - - public void checkResult(Object resultToCheck, String csid, String serviceMessage) throws CSWebApplicationException { - if (resultToCheck == null) { - Response response = Response.status(Response.Status.NOT_FOUND).entity( - serviceMessage + "csid=" + csid - + ": was not found.").type( - "text/plain").build(); - throw new CSWebApplicationException(response); - } - } - - protected void ensureCSID(String csid, String crudType) throws CSWebApplicationException { - ensureCSID(csid, crudType, "csid"); - } - - protected void ensureCSID(String csid, String crudType, String whichCsid) throws CSWebApplicationException { - if (logger.isDebugEnabled()) { - logger.debug(crudType + " for " + getClass().getName() + " with csid=" + csid); - } - if (csid == null || "".equals(csid)) { - logger.error(crudType + " for " + getClass().getName() + " missing csid!"); - Response response = Response.status(Response.Status.BAD_REQUEST).entity(crudType + " failed on " + getClass().getName() + ' '+whichCsid+'=' + csid).type("text/plain").build(); - throw new CSWebApplicationException(response); - } - } - - protected CSWebApplicationException bigReThrow(Exception e, String serviceMsg) throws CSWebApplicationException { - return bigReThrow(e, serviceMsg, ""); - } - - protected CSWebApplicationException bigReThrow(Exception e, String serviceMsg, String csid) throws CSWebApplicationException { - boolean logException = true; - CSWebApplicationException result = null; - Response response; - String detail = Tools.errorToString(e, true); - String detailNoTrace = Tools.errorToString(e, true, 3); - - if (e instanceof UnauthorizedException) { - response = Response.status(Response.Status.UNAUTHORIZED).entity(serviceMsg + e.getMessage()).type("text/plain").build(); - result = new CSWebApplicationException(e, response); - - } else if (e instanceof DocumentNotFoundException) { - // - // Don't log this error unless we're in 'trace' mode - // - logException = false; - response = Response.status(Response.Status.NOT_FOUND).entity(serviceMsg + " on " + getClass().getName() + " csid=" + csid).type("text/plain").build(); - result = new CSWebApplicationException(e, response); - - } else if (e instanceof TransactionException) { - int code = ((TransactionException) e).getErrorCode(); - response = Response.status(code).entity(e.getMessage()).type("text/plain").build(); - result = new CSWebApplicationException(e, response); - - } else if (e instanceof BadRequestException) { - int code = ((BadRequestException) e).getErrorCode(); - if (code == 0) { - code = Response.Status.BAD_REQUEST.getStatusCode(); - } - // CSPACE-1110 - response = Response.status(code).entity(serviceMsg + e.getMessage()).type("text/plain").build(); - // return new WebApplicationException(e, code); - result = new CSWebApplicationException(e, response); - - } else if (e instanceof DocumentException) { - int code = ((DocumentException) e).getErrorCode(); - if (code == 0){ - code = Response.Status.BAD_REQUEST.getStatusCode(); - } - // CSPACE-1110 - response = Response.status(code).entity(serviceMsg + e.getMessage()).type("text/plain").build(); - // return new WebApplicationException(e, code); - result = new CSWebApplicationException(e, response); - - } else if (e instanceof CSWebApplicationException) { - // subresource may have already thrown this exception - // so just pass it on - result = (CSWebApplicationException) e; - - } else { // e is now instanceof Exception - response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(serviceMsg + " detail: " + detailNoTrace).type("text/plain").build(); - result = new CSWebApplicationException(e, response); - } - // - // Some exceptions like DocumentNotFoundException won't be logged unless we're in 'trace' mode - // - boolean traceEnabled = logger.isTraceEnabled(); - if (logException == true || traceEnabled == true) { - if (traceEnabled == true) { - logger.error(getClass().getName() + " detail: " + detail, e); - } else { - logger.error(getClass().getName() + " detail: " + detailNoTrace); - } - } - - return result; - } - - @Override - public boolean allowAnonymousAccess(HttpRequest request, - ResourceMethod method) { - return false; - } -} +/** + * 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; + +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.collectionspace.services.common.CSWebApplicationException; +import org.collectionspace.services.common.api.Tools; +import org.collectionspace.services.common.context.ServiceContext; +import org.collectionspace.services.common.context.ServiceContextProperties; +import org.collectionspace.services.common.document.BadRequestException; +import org.collectionspace.services.common.document.DocumentException; +import org.collectionspace.services.common.document.DocumentHandler; +import org.collectionspace.services.common.document.DocumentNotFoundException; +import org.collectionspace.services.common.document.TransactionException; +import org.collectionspace.services.common.repository.RepositoryClient; +import org.collectionspace.services.common.repository.RepositoryClientFactory; +import org.collectionspace.services.common.security.UnauthorizedException; +import org.collectionspace.services.common.storage.StorageClient; +import org.collectionspace.services.common.storage.jpa.JpaStorageClientImpl; + +import org.jboss.resteasy.core.ResourceMethod; +import org.jboss.resteasy.spi.HttpRequest; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The Class AbstractCollectionSpaceResourceImpl. + * + * @param the generic type + * @param the generic type + */ +public abstract class AbstractCollectionSpaceResourceImpl + implements CollectionSpaceResource { + + protected final Logger logger = LoggerFactory.getLogger(this.getClass()); + + + // Fields for default client factory and client + /** The repository client factory. */ + private RepositoryClientFactory repositoryClientFactory; + + /** The repository client. */ + private RepositoryClient repositoryClient; + + /** The storage client. */ + private StorageClient storageClient; + + /** + * Extract id. + * + * @param res the res + * @return the string + */ + protected static String extractId(Response res) { + MultivaluedMap mvm = res.getMetadata(); + String uri = (String) ((List) mvm.get("Location")).get(0); + String[] segments = uri.split("/"); + String id = segments[segments.length - 1]; + return id; + } + + /** + * Instantiates a new abstract collection space resource. + */ + public AbstractCollectionSpaceResourceImpl() { + repositoryClientFactory = RepositoryClientFactory.getInstance(); + } + + /* (non-Javadoc) + * @see org.collectionspace.services.common.CollectionSpaceResource#getServiceName() + */ + @Override + abstract public String getServiceName(); + + + /* (non-Javadoc) + * @see org.collectionspace.services.common.CollectionSpaceResource#getRepositoryClient(org.collectionspace.services.common.context.ServiceContext) + */ + @Override + synchronized public RepositoryClient getRepositoryClient(ServiceContext ctx) { + if(repositoryClient != null){ + return repositoryClient; + } + repositoryClient = repositoryClientFactory.getClient(ctx.getRepositoryClientName()); + return repositoryClient; + } + + /* (non-Javadoc) + * @see org.collectionspace.services.common.CollectionSpaceResource#getStorageClient(org.collectionspace.services.common.context.ServiceContext) + */ + @Override + synchronized public StorageClient getStorageClient(ServiceContext ctx) { + if(storageClient != null) { + return storageClient; + } + storageClient = new JpaStorageClientImpl(); + return storageClient; + } + + /* (non-Javadoc) + * @see org.collectionspace.services.common.CollectionSpaceResource#createDocumentHandler(org.collectionspace.services.common.context.ServiceContext) + */ + @Override + public DocumentHandler createDocumentHandler(ServiceContext ctx) throws Exception { + DocumentHandler docHandler = createDocumentHandler(ctx, ctx.getInput()); + return docHandler; + } + + /** + * Creates the document handler. + * + * @param ctx the ctx + * @param commonPart the common part + * + * @return the document handler + * + * @throws Exception the exception + */ + public DocumentHandler createDocumentHandler(ServiceContext ctx, + Object commonPart) throws Exception { + DocumentHandler docHandler = ctx.getDocumentHandler(); + docHandler.setCommonPart(commonPart); + return docHandler; + } + + /** + * Creates the service context. + * + * @return the service context< i t, o t> + * + * @throws Exception the exception + */ + protected ServiceContext createServiceContext() throws Exception { + ServiceContext ctx = createServiceContext(this.getServiceName(), + (IT)null, //inputType + null, // The resource map + (UriInfo)null, // The query params + this.getCommonPartClass()); + return ctx; + } + + /** + * Creates the service context. + * + * @param serviceName the service name + * + * @return the service context< i t, o t> + * + * @throws Exception the exception + */ + protected ServiceContext createServiceContext(String serviceName) throws Exception { + ServiceContext ctx = createServiceContext( + serviceName, + (IT)null, // The input part + null, // The resource map + (UriInfo)null, // The queryParams + (Class)null /*input type's Class*/); + return ctx; + } + + protected ServiceContext createServiceContext(String serviceName, UriInfo ui) throws Exception { + ServiceContext ctx = createServiceContext( + serviceName, + (IT)null, // The input part + null, // The resource map + (UriInfo)null, // The queryParams + (Class)null /*input type's Class*/); + ctx.setUriInfo(ui); + return ctx; + } + + /** + * Creates the service context. + * + * @param serviceName the service name + * @param input the input + * + * @return the service context< i t, o t> + * + * @throws Exception the exception + */ + protected ServiceContext createServiceContext(String serviceName, + IT input) throws Exception { + ServiceContext ctx = createServiceContext(serviceName, + input, + null, // The resource map + (UriInfo)null, /*queryParams*/ + (Class)null /*input type's Class*/); + return ctx; + } + + protected ServiceContext createServiceContext(String serviceName, + IT input, + UriInfo uriInfo) throws Exception { + ServiceContext ctx = createServiceContext(serviceName, + input, + null, // The resource map + uriInfo, /*queryParams*/ + (Class)null /*input type's Class*/); + return ctx; + } + + protected ServiceContext createServiceContext(UriInfo uriInfo) throws Exception { + ServiceContext ctx = createServiceContext( + (IT)null, /*input*/ + uriInfo, + (Class)null /*input type's Class*/); + return ctx; + } + + /** + * Creates the service context. + * + * @param input the input + * + * @return the service context< i t, o t> + * + * @throws Exception the exception + */ + protected ServiceContext createServiceContext(IT input) throws Exception { + ServiceContext ctx = createServiceContext( + input, + (Class)null /*input type's Class*/); + return ctx; + } + + protected ServiceContext createServiceContext(IT input, UriInfo uriInfo) throws Exception { + ServiceContext ctx = createServiceContext( + input, + uriInfo, + null ); // The class param/argument + return ctx; + } + + /** + * Creates the service context. + * + * @param input the input + * @param theClass the the class + * + * @return the service context + * + * @throws Exception the exception + */ + protected ServiceContext createServiceContext(IT input, Class theClass) throws Exception { + ServiceContext ctx = createServiceContext( + input, + (UriInfo)null, //queryParams, + theClass); + return ctx; + } + + protected ServiceContext createServiceContext(IT input, Class theClass, UriInfo uriInfo) throws Exception { + ServiceContext ctx = createServiceContext( + input, + uriInfo, + theClass); + return ctx; + } + + protected ServiceContext createServiceContext( + String serviceName, + ResourceMap resourceMap, + UriInfo uriInfo) throws Exception { + ServiceContext ctx = createServiceContext( + serviceName, + null, // The input object + resourceMap, + uriInfo, + null /* the class of the input type */); + return ctx; + } + + protected ServiceContext createServiceContext( + IT input, + ResourceMap resourceMap, + UriInfo uriInfo) throws Exception { + ServiceContext ctx = createServiceContext( + this.getServiceName(), + input, + resourceMap, + uriInfo, + null /* the class of the input type */); + return ctx; + } + + protected ServiceContext createServiceContext( + String serviceName, + IT input, + ResourceMap resourceMap, + UriInfo uriInfo) throws Exception { + ServiceContext ctx = createServiceContext( + serviceName, + input, + resourceMap, + uriInfo, + null /* the class of the input type */); + return ctx; + } + + /** + * Creates the service context. + * + * @param input the input + * @param queryParams the query params + * @param theClass the the class + * + * @return the service context< i t, o t> + * + * @throws Exception the exception + */ + private ServiceContext createServiceContext( + IT input, + UriInfo uriInfo, + Class theClass) throws Exception { + return createServiceContext(this.getServiceName(), + input, + null, // The resource map + uriInfo, + theClass); + } + + /** + * Creates the service context. + * + * @param serviceName the service name + * @param input the input + * @param queryParams the query params + * @param theClass the the class + * + * @return the service context< i t, o t> + * + * @throws Exception the exception + */ + private ServiceContext createServiceContext( + String serviceName, + IT input, + ResourceMap resourceMap, + UriInfo uriInfo, + Class theClass) throws Exception { + ServiceContext ctx = getServiceContextFactory().createServiceContext( + serviceName, + input, + resourceMap, + uriInfo, + theClass != null ? theClass.getPackage().getName() : null, + theClass != null ? theClass.getName() : null); + if (theClass != null) { + ctx.setProperty(ServiceContextProperties.ENTITY_CLASS, theClass); + } + + return ctx; + } + + /** + * Gets the version string. + * + * @return the version string + */ + abstract protected String getVersionString(); + + /** + * Gets the version. + * + * @return the version + */ + @GET + @Path("/version") + @Produces("application/xml") + public Version getVersion() { + Version result = new Version(); + + result.setVersionString(getVersionString()); + + return result; + } + + public void checkResult(Object resultToCheck, String csid, String serviceMessage) throws CSWebApplicationException { + if (resultToCheck == null) { + Response response = Response.status(Response.Status.NOT_FOUND).entity( + serviceMessage + "csid=" + csid + + ": was not found.").type( + "text/plain").build(); + throw new CSWebApplicationException(response); + } + } + + protected void ensureCSID(String csid, String crudType) throws CSWebApplicationException { + ensureCSID(csid, crudType, "csid"); + } + + protected void ensureCSID(String csid, String crudType, String whichCsid) throws CSWebApplicationException { + if (logger.isDebugEnabled()) { + logger.debug(crudType + " for " + getClass().getName() + " with csid=" + csid); + } + if (csid == null || "".equals(csid)) { + logger.error(crudType + " for " + getClass().getName() + " missing csid!"); + Response response = Response.status(Response.Status.BAD_REQUEST).entity(crudType + " failed on " + getClass().getName() + ' '+whichCsid+'=' + csid).type("text/plain").build(); + throw new CSWebApplicationException(response); + } + } + + protected CSWebApplicationException bigReThrow(Exception e, String serviceMsg) throws CSWebApplicationException { + return bigReThrow(e, serviceMsg, ""); + } + + protected CSWebApplicationException bigReThrow(Exception e, String serviceMsg, String csid) throws CSWebApplicationException { + boolean logException = true; + CSWebApplicationException result = null; + Response response; + String detail = Tools.errorToString(e, true); + String detailNoTrace = Tools.errorToString(e, true, 3); + + if (e instanceof UnauthorizedException) { + response = Response.status(Response.Status.UNAUTHORIZED).entity(serviceMsg + e.getMessage()).type("text/plain").build(); + result = new CSWebApplicationException(e, response); + + } else if (e instanceof DocumentNotFoundException) { + // + // Don't log this error unless we're in 'trace' mode + // + logException = false; + response = Response.status(Response.Status.NOT_FOUND).entity(serviceMsg + " on " + getClass().getName() + " csid=" + csid).type("text/plain").build(); + result = new CSWebApplicationException(e, response); + + } else if (e instanceof TransactionException) { + int code = ((TransactionException) e).getErrorCode(); + response = Response.status(code).entity(e.getMessage()).type("text/plain").build(); + result = new CSWebApplicationException(e, response); + + } else if (e instanceof BadRequestException) { + int code = ((BadRequestException) e).getErrorCode(); + if (code == 0) { + code = Response.Status.BAD_REQUEST.getStatusCode(); + } + // CSPACE-1110 + response = Response.status(code).entity(serviceMsg + e.getMessage()).type("text/plain").build(); + // return new WebApplicationException(e, code); + result = new CSWebApplicationException(e, response); + + } else if (e instanceof DocumentException) { + int code = ((DocumentException) e).getErrorCode(); + if (code == 0){ + code = Response.Status.BAD_REQUEST.getStatusCode(); + } + // CSPACE-1110 + response = Response.status(code).entity(serviceMsg + e.getMessage()).type("text/plain").build(); + // return new WebApplicationException(e, code); + result = new CSWebApplicationException(e, response); + + } else if (e instanceof CSWebApplicationException) { + // subresource may have already thrown this exception + // so just pass it on + result = (CSWebApplicationException) e; + + } else { // e is now instanceof Exception + response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(serviceMsg + " detail: " + detailNoTrace).type("text/plain").build(); + result = new CSWebApplicationException(e, response); + } + // + // Some exceptions like DocumentNotFoundException won't be logged unless we're in 'trace' mode + // + boolean traceEnabled = logger.isTraceEnabled(); + if (logException == true || traceEnabled == true) { + if (traceEnabled == true) { + logger.error(getClass().getName() + " detail: " + detail, e); + } else { + logger.error(getClass().getName() + " detail: " + detailNoTrace); + } + } + + return result; + } + + @Override + public boolean allowAnonymousAccess(HttpRequest request, + ResourceMethod method) { + return false; + } +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/AbstractMultiPartCollectionSpaceResourceImpl.java b/services/common/src/main/java/org/collectionspace/services/common/AbstractMultiPartCollectionSpaceResourceImpl.java index 726b1420d..1dcc3db35 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/AbstractMultiPartCollectionSpaceResourceImpl.java +++ b/services/common/src/main/java/org/collectionspace/services/common/AbstractMultiPartCollectionSpaceResourceImpl.java @@ -1,279 +1,279 @@ -/** - * AbstractMultiPartCollectionSpaceResourceImpl.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; - -import java.util.Iterator; -import java.util.List; - -import javax.ws.rs.GET; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.UriInfo; - -import org.collectionspace.services.client.PayloadOutputPart; -import org.collectionspace.services.client.PoxPayloadIn; -import org.collectionspace.services.client.PoxPayloadOut; -import org.collectionspace.services.client.workflow.WorkflowClient; -import org.collectionspace.services.common.context.MultipartServiceContext; -import org.collectionspace.services.common.context.MultipartServiceContextFactory; -import org.collectionspace.services.common.context.ServiceContext; -import org.collectionspace.services.common.context.ServiceContextFactory; -import org.collectionspace.services.common.document.DocumentHandler; -import org.collectionspace.services.common.workflow.service.nuxeo.WorkflowDocumentModelHandler; -import org.collectionspace.services.lifecycle.Lifecycle; -import org.collectionspace.services.lifecycle.TransitionDef; -import org.collectionspace.services.workflow.WorkflowCommon; -import org.dom4j.DocumentException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The Class AbstractMultiPartCollectionSpaceResourceImpl. - */ -public abstract class AbstractMultiPartCollectionSpaceResourceImpl extends AbstractCollectionSpaceResourceImpl { - - protected final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Override - public ServiceContextFactory getServiceContextFactory() { - return MultipartServiceContextFactory.get(); - } - - abstract protected String getOrderByField(ServiceContext ctx); - - abstract protected String getPartialTermMatchField(ServiceContext ctx); - - @Override - public DocumentHandler createDocumentHandler(ServiceContext ctx) throws Exception { - return createDocumentHandler(ctx, ctx.getCommonPartLabel(), getCommonPartClass()); - } - - /** - * Creates the document handler. - * - * @param serviceContext the service context - * @param schemaName the schema name - * @param commonClass the common class - * - * @return the document handler - * - * @throws Exception the exception - */ - public DocumentHandler createDocumentHandler(ServiceContext serviceContext, - String schemaName, - Class commonClass) throws Exception { - DocumentHandler result = null; - - MultipartServiceContext ctx = (MultipartServiceContext) serviceContext; - Object commonPart = null; - if (ctx.getInput() != null) { - commonPart = ctx.getInputPart(schemaName); - } - result = super.createDocumentHandler(ctx, commonPart); - - return result; - } - - /** - * Creates the document handler. - * - * @param ctx the ctx - * @param commonClass the common class - * - * @return the document handler - * - * @throws Exception the exception - */ - public DocumentHandler createDocumentHandler( - ServiceContext ctx, - Class commonClass) throws Exception { - return createDocumentHandler(ctx, ctx.getCommonPartLabel(), commonClass); - } - - /** - * Creates the contact document handler. - * - * @param ctx the ctx - * @param inAuthority the in authority - * @param inItem the in item - * - * @return the document handler - * - * @throws Exception the exception - */ - protected WorkflowDocumentModelHandler createWorkflowDocumentHandler( - ServiceContext ctx) throws Exception { - - WorkflowDocumentModelHandler docHandler = (WorkflowDocumentModelHandler) createDocumentHandler(ctx, - WorkflowClient.SERVICE_COMMONPART_NAME, - WorkflowCommon.class); - - return docHandler; - } - - /* - * JAX-RS Annotated methods - */ - @GET - @Path(WorkflowClient.SERVICE_PATH) - public Lifecycle getWorkflow(@Context UriInfo uriInfo) { - Lifecycle result; - - String documentType = "undefined"; - MultipartServiceContext ctx = null; - try { - ctx = (MultipartServiceContext) createServiceContext(uriInfo); - DocumentHandler handler = ctx.getDocumentHandler(); - result = handler.getLifecycle(); - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, ctx.getDocumentType()); - } - - if (result == null) { - result = new Lifecycle(); - result.setName("No life cycle defined for:" + documentType); - } - - return result; - } - - /* - * JAX-RS Annotated methods - */ - - /* - * We should change this method. The RepositoryClient (from call to getRepositoryClient) should support a call getWorkflowTransition() instead. - */ - @GET - @Path("{csid}" + WorkflowClient.SERVICE_PATH) - public byte[] getWorkflow( - @Context UriInfo uriInfo, - @PathParam("csid") String csid) { - PoxPayloadOut result = null; - - try { - ServiceContext parentCtx = createServiceContext(uriInfo); - String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName(); - - MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, uriInfo); - WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx); - ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace - getRepositoryClient(ctx).get(ctx, csid, handler); - result = ctx.getOutput(); - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid); - } - - return result.getBytes(); - } - - protected TransitionDef getTransitionDef(ServiceContext ctx, String transition) { - TransitionDef result = null; - - try { - Lifecycle lifecycle = ctx.getDocumentHandler().getLifecycle(); - List transitionDefList = lifecycle.getTransitionDefList().getTransitionDef(); - Iterator iter = transitionDefList.iterator(); - boolean found = false; - while (iter.hasNext() && found == false) { - TransitionDef transitionDef = iter.next(); - if (transitionDef.getName().equalsIgnoreCase(transition)) { - result = transitionDef; - found = true; - } - } - } catch (Exception e) { - logger.error("Exception trying to retreive life cycle information for: " + ctx.getDocumentType()); - } - - return result; - } - - private PoxPayloadIn synthEmptyWorkflowInput() { - PoxPayloadIn result = null; - - PoxPayloadOut output = new PoxPayloadOut(WorkflowClient.SERVICE_PAYLOAD_NAME); - WorkflowCommon workflowCommons = new WorkflowCommon(); - PayloadOutputPart commonPart = output.addPart(WorkflowClient.SERVICE_COMMONPART_NAME, workflowCommons); - String payloadXML = output.toXML(); - try { - result = new PoxPayloadIn(payloadXML); - } catch (DocumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return result; - } - - /* - * We should change this code. The RepositoryClient (from call to getRepositoryClient) should support a call doWorkflowTransition() instead. - */ - //FIXME: This method is almost identical to the method org.collectionspace.services.common.vocabulary.updateWorkflowWithTransition() so - // they should be consolidated -be DRY (don't repeat yourself). - - @PUT - @Path("{csid}" + WorkflowClient.SERVICE_PATH + "/" + "{transition}") - public byte[] updateWorkflowWithTransition( - @Context UriInfo uriInfo, - @PathParam("csid") String csid, - @PathParam("transition") String transition) { - PoxPayloadOut result = null; - - try { - // - // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context - PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(), - WorkflowClient.SERVICE_COMMONPART_NAME); - MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input, uriInfo); - - // Create a service context and document handler for the parent resource. - ServiceContext parentCtx = createServiceContext(uriInfo); - DocumentHandler parentDocHandler = this.createDocumentHandler(parentCtx); - ctx.setProperty(WorkflowClient.PARENT_DOCHANDLER, parentDocHandler); //added as a context param for the workflow document handler -it will call the parent's dochandler "prepareForWorkflowTranstion" method - - // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name - String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName(); - ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace - - // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler - TransitionDef transitionDef = getTransitionDef(parentCtx, transition); - ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef); - - WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx); - getRepositoryClient(ctx).update(ctx, csid, handler); - result = ctx.getOutput(); - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid); - } - return result.getBytes(); - } - -} +/** + * AbstractMultiPartCollectionSpaceResourceImpl.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; + +import java.util.Iterator; +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.UriInfo; + +import org.collectionspace.services.client.PayloadOutputPart; +import org.collectionspace.services.client.PoxPayloadIn; +import org.collectionspace.services.client.PoxPayloadOut; +import org.collectionspace.services.client.workflow.WorkflowClient; +import org.collectionspace.services.common.context.MultipartServiceContext; +import org.collectionspace.services.common.context.MultipartServiceContextFactory; +import org.collectionspace.services.common.context.ServiceContext; +import org.collectionspace.services.common.context.ServiceContextFactory; +import org.collectionspace.services.common.document.DocumentHandler; +import org.collectionspace.services.common.workflow.service.nuxeo.WorkflowDocumentModelHandler; +import org.collectionspace.services.lifecycle.Lifecycle; +import org.collectionspace.services.lifecycle.TransitionDef; +import org.collectionspace.services.workflow.WorkflowCommon; +import org.dom4j.DocumentException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The Class AbstractMultiPartCollectionSpaceResourceImpl. + */ +public abstract class AbstractMultiPartCollectionSpaceResourceImpl extends AbstractCollectionSpaceResourceImpl { + + protected final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Override + public ServiceContextFactory getServiceContextFactory() { + return MultipartServiceContextFactory.get(); + } + + abstract protected String getOrderByField(ServiceContext ctx); + + abstract protected String getPartialTermMatchField(ServiceContext ctx); + + @Override + public DocumentHandler createDocumentHandler(ServiceContext ctx) throws Exception { + return createDocumentHandler(ctx, ctx.getCommonPartLabel(), getCommonPartClass()); + } + + /** + * Creates the document handler. + * + * @param serviceContext the service context + * @param schemaName the schema name + * @param commonClass the common class + * + * @return the document handler + * + * @throws Exception the exception + */ + public DocumentHandler createDocumentHandler(ServiceContext serviceContext, + String schemaName, + Class commonClass) throws Exception { + DocumentHandler result = null; + + MultipartServiceContext ctx = (MultipartServiceContext) serviceContext; + Object commonPart = null; + if (ctx.getInput() != null) { + commonPart = ctx.getInputPart(schemaName); + } + result = super.createDocumentHandler(ctx, commonPart); + + return result; + } + + /** + * Creates the document handler. + * + * @param ctx the ctx + * @param commonClass the common class + * + * @return the document handler + * + * @throws Exception the exception + */ + public DocumentHandler createDocumentHandler( + ServiceContext ctx, + Class commonClass) throws Exception { + return createDocumentHandler(ctx, ctx.getCommonPartLabel(), commonClass); + } + + /** + * Creates the contact document handler. + * + * @param ctx the ctx + * @param inAuthority the in authority + * @param inItem the in item + * + * @return the document handler + * + * @throws Exception the exception + */ + protected WorkflowDocumentModelHandler createWorkflowDocumentHandler( + ServiceContext ctx) throws Exception { + + WorkflowDocumentModelHandler docHandler = (WorkflowDocumentModelHandler) createDocumentHandler(ctx, + WorkflowClient.SERVICE_COMMONPART_NAME, + WorkflowCommon.class); + + return docHandler; + } + + /* + * JAX-RS Annotated methods + */ + @GET + @Path(WorkflowClient.SERVICE_PATH) + public Lifecycle getWorkflow(@Context UriInfo uriInfo) { + Lifecycle result; + + String documentType = "undefined"; + MultipartServiceContext ctx = null; + try { + ctx = (MultipartServiceContext) createServiceContext(uriInfo); + DocumentHandler handler = ctx.getDocumentHandler(); + result = handler.getLifecycle(); + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, ctx.getDocumentType()); + } + + if (result == null) { + result = new Lifecycle(); + result.setName("No life cycle defined for:" + documentType); + } + + return result; + } + + /* + * JAX-RS Annotated methods + */ + + /* + * We should change this method. The RepositoryClient (from call to getRepositoryClient) should support a call getWorkflowTransition() instead. + */ + @GET + @Path("{csid}" + WorkflowClient.SERVICE_PATH) + public byte[] getWorkflow( + @Context UriInfo uriInfo, + @PathParam("csid") String csid) { + PoxPayloadOut result = null; + + try { + ServiceContext parentCtx = createServiceContext(uriInfo); + String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName(); + + MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, uriInfo); + WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx); + ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace + getRepositoryClient(ctx).get(ctx, csid, handler); + result = ctx.getOutput(); + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid); + } + + return result.getBytes(); + } + + protected TransitionDef getTransitionDef(ServiceContext ctx, String transition) { + TransitionDef result = null; + + try { + Lifecycle lifecycle = ctx.getDocumentHandler().getLifecycle(); + List transitionDefList = lifecycle.getTransitionDefList().getTransitionDef(); + Iterator iter = transitionDefList.iterator(); + boolean found = false; + while (iter.hasNext() && found == false) { + TransitionDef transitionDef = iter.next(); + if (transitionDef.getName().equalsIgnoreCase(transition)) { + result = transitionDef; + found = true; + } + } + } catch (Exception e) { + logger.error("Exception trying to retreive life cycle information for: " + ctx.getDocumentType()); + } + + return result; + } + + private PoxPayloadIn synthEmptyWorkflowInput() { + PoxPayloadIn result = null; + + PoxPayloadOut output = new PoxPayloadOut(WorkflowClient.SERVICE_PAYLOAD_NAME); + WorkflowCommon workflowCommons = new WorkflowCommon(); + PayloadOutputPart commonPart = output.addPart(WorkflowClient.SERVICE_COMMONPART_NAME, workflowCommons); + String payloadXML = output.toXML(); + try { + result = new PoxPayloadIn(payloadXML); + } catch (DocumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return result; + } + + /* + * We should change this code. The RepositoryClient (from call to getRepositoryClient) should support a call doWorkflowTransition() instead. + */ + //FIXME: This method is almost identical to the method org.collectionspace.services.common.vocabulary.updateWorkflowWithTransition() so + // they should be consolidated -be DRY (don't repeat yourself). + + @PUT + @Path("{csid}" + WorkflowClient.SERVICE_PATH + "/" + "{transition}") + public byte[] updateWorkflowWithTransition( + @Context UriInfo uriInfo, + @PathParam("csid") String csid, + @PathParam("transition") String transition) { + PoxPayloadOut result = null; + + try { + // + // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context + PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(), + WorkflowClient.SERVICE_COMMONPART_NAME); + MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input, uriInfo); + + // Create a service context and document handler for the parent resource. + ServiceContext parentCtx = createServiceContext(uriInfo); + DocumentHandler parentDocHandler = this.createDocumentHandler(parentCtx); + ctx.setProperty(WorkflowClient.PARENT_DOCHANDLER, parentDocHandler); //added as a context param for the workflow document handler -it will call the parent's dochandler "prepareForWorkflowTranstion" method + + // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name + String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName(); + ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace + + // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler + TransitionDef transitionDef = getTransitionDef(parentCtx, transition); + ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef); + + WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx); + getRepositoryClient(ctx).update(ctx, csid, handler); + result = ctx.getOutput(); + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid); + } + return result.getBytes(); + } + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/ConfigurationException.java b/services/common/src/main/java/org/collectionspace/services/common/ConfigurationException.java index 53477a4bc..078988fe4 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/ConfigurationException.java +++ b/services/common/src/main/java/org/collectionspace/services/common/ConfigurationException.java @@ -1,65 +1,65 @@ -package org.collectionspace.services.common; - -public class ConfigurationException extends ServiceException { - /** - * - */ - private static final long serialVersionUID = -6399176494104282779L; - - final public static int HTTP_CODE = 500; - - /** - * Creates a new instance of BadRequestException without detail message. - */ - public ConfigurationException() { - super(HTTP_CODE); - } - - /** - * Constructs an instance of BadRequestException with the specified detail message. - * @param msg the detail message. - */ - public ConfigurationException(String msg) { - super(msg); - setErrorCode(HTTP_CODE); - } - - /** - * Constructs a new exception with the specified detail message and - * cause.

Note that the detail message associated with - * cause is not automatically incorporated in - * this exception's detail message. - * - * @param message the detail message (which is saved for later retrieval - * by the {@link #getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.4 - */ - public ConfigurationException(String message, Throwable cause) { - super(message, cause); - setErrorCode(HTTP_CODE); - } - - /** - * Constructs a new exception with the specified cause and a detail - * message of (cause==null ? null : cause.toString()) (which - * typically contains the class and detail message of cause). - * This constructor is useful for exceptions that are little more than - * wrappers for other throwables (for example, {@link - * java.security.PrivilegedActionException}). - * - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.4 - */ - public ConfigurationException(Throwable cause) { - super(cause); - setErrorCode(HTTP_CODE); - } - -} +package org.collectionspace.services.common; + +public class ConfigurationException extends ServiceException { + /** + * + */ + private static final long serialVersionUID = -6399176494104282779L; + + final public static int HTTP_CODE = 500; + + /** + * Creates a new instance of BadRequestException without detail message. + */ + public ConfigurationException() { + super(HTTP_CODE); + } + + /** + * Constructs an instance of BadRequestException with the specified detail message. + * @param msg the detail message. + */ + public ConfigurationException(String msg) { + super(msg); + setErrorCode(HTTP_CODE); + } + + /** + * Constructs a new exception with the specified detail message and + * cause.

Note that the detail message associated with + * cause is not automatically incorporated in + * this exception's detail message. + * + * @param message the detail message (which is saved for later retrieval + * by the {@link #getMessage()} method). + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.4 + */ + public ConfigurationException(String message, Throwable cause) { + super(message, cause); + setErrorCode(HTTP_CODE); + } + + /** + * Constructs a new exception with the specified cause and a detail + * message of (cause==null ? null : cause.toString()) (which + * typically contains the class and detail message of cause). + * This constructor is useful for exceptions that are little more than + * wrappers for other throwables (for example, {@link + * java.security.PrivilegedActionException}). + * + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.4 + */ + public ConfigurationException(Throwable cause) { + super(cause); + setErrorCode(HTTP_CODE); + } + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/Download.java b/services/common/src/main/java/org/collectionspace/services/common/Download.java index e4fd7cb72..c3750ce5c 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/Download.java +++ b/services/common/src/main/java/org/collectionspace/services/common/Download.java @@ -1,283 +1,283 @@ -package org.collectionspace.services.common; -import java.io.*; -import java.net.*; -import java.util.*; - -// This class downloads a file from a URL. -public class Download extends Observable implements Runnable { - - public static URL verifyUrl(String url) { - // Only allow HTTP URLs. - if (!url.toLowerCase().startsWith("http://")) - return null; - - // Verify format of URL. - URL verifiedUrl = null; - try { - verifiedUrl = new URL(url); - } catch (Exception e) { - return null; - } - - // Make sure URL specifies a file. - if (verifiedUrl.getFile().length() < 2) - return null; - - return verifiedUrl; - } - - // Max size of download buffer. - private static final int MAX_BUFFER_SIZE = 1024; - - // These are the status names. - public static final String STATUSES[] = {"Downloading", - "Paused", "Complete", "Cancelled", "Error"}; - - // These are the status codes. - public static final int DOWNLOADING = 0; - public static final int PAUSED = 1; - public static final int COMPLETE = 2; - public static final int CANCELLED = 3; - public static final int ERROR = 4; - - private String errorMessage = null; - private String filePath = null; - private File downloadedFile = null; - private String destDir = null; // the location of the downloaded file - private URL url; // download URL - private int size; // size of download in bytes - private int downloaded; // number of bytes downloaded - private int status; // current status of download - - private void doDownload(URL url, String destDir) { - size = -1; - downloaded = 0; - status = DOWNLOADING; - this.url = url; - setDestDir(destDir); - - // Begin the download. - download(); - } - - public Download(URL url, String destDir) { - doDownload(url, destDir); - } - - // Constructor for Download. File is uploaded to system temp directory. - public Download(URL url) { - String tmpdir = System.getProperty("java.io.tmpdir"); - if (tmpdir.endsWith(File.separator) == false) { - tmpdir = tmpdir + File.separator; - } - doDownload(url, tmpdir - + UUID.randomUUID() + File.separator); - } - - private void setDestDir(String destDir) { - if (destDir.endsWith(File.separator) != true) { - destDir = destDir + File.separator; - } - // - // Check if the destDir exists, if not try to create it. - // - File destDirFile = new File(destDir); - boolean destDirExists = destDirFile.exists(); - if (destDirExists == false) { - destDirExists = destDirFile.mkdir(); - } else { - destDirExists = destDirFile.isDirectory(); - } - // - // If we couldn't create the directory or if it is already a file then fail. - // - if (destDirExists = true) { - this.destDir = destDir; - } else { - error("Could not download file to: " + destDir); - } - } - - - public File getFile() { - return this.downloadedFile; - } - - public String getFilePath() { - return this.filePath; - } - - public String getDestDir() { - return this.destDir; - } - - // Get this download's URL. - public String getUrl() { - return url.toString(); - } - - // Get this download's size. - public int getSize() { - return size; - } - - // Get this download's progress. - public float getProgress() { - return ((float) downloaded / size) * 100; - } - - // Get this download's status. - public int getStatus() { - return status; - } - - // Pause this download. - public void pause() { - status = PAUSED; - stateChanged(); - } - - // Resume this download. - public void resume() { - status = DOWNLOADING; - stateChanged(); - download(); - } - - // Cancel this download. - public void cancel() { - status = CANCELLED; - stateChanged(); - } - - // Mark this download as having an error. - private void error() { - status = ERROR; - stateChanged(); - } - - // Mark this download as having an error. - private void error(String message) { - this.errorMessage = message; - error(); - } - - // Start or resume downloading. - private void download() { -// Thread thread = new Thread(this); -// thread.start(); - run(); - } - - // Get file name portion of URL. - private String getFileName(URL url) { - String result = null; - - String destDir = this.getDestDir(); - String fileName = url.getFile(); - fileName = fileName.substring(fileName.lastIndexOf('/') + 1); - result = filePath = destDir + fileName; - - return result; - } - - // Download file. - public void run() { - RandomAccessFile file = null; - InputStream stream = null; - - try { - // Open connection to URL. - HttpURLConnection connection = - (HttpURLConnection) url.openConnection(); - - // Specify what portion of file to download. - connection.setRequestProperty("Range", - "bytes=" + downloaded + "-"); - - // Connect to server. - connection.connect(); - - // Make sure response code is in the 200 range. - int responseCode = connection.getResponseCode(); - if (responseCode / 100 != 2) { - error(); - } - - // Check for valid content length. - int contentLength = connection.getContentLength(); - if (contentLength < 1) { - error(); - } - - /* Set the size for this download if it - hasn't been already set. */ - if (size == -1) { - size = contentLength; - stateChanged(); - } - - // Open file and seek to the end of it. - File javaFile = new File(getFileName(url)); - file = new RandomAccessFile(javaFile, "rw"); - file.seek(downloaded); - - stream = connection.getInputStream(); - while (status == DOWNLOADING) { - /* Size buffer according to how much of the - file is left to download. */ - byte buffer[]; - if (size - downloaded > MAX_BUFFER_SIZE) { - buffer = new byte[MAX_BUFFER_SIZE]; - } else { - buffer = new byte[size - downloaded]; - } - - // Read from server into buffer. - int read = stream.read(buffer); - if (read == -1) - break; - - // Write buffer to file. - file.write(buffer, 0, read); - downloaded += read; - stateChanged(); - } - - /* Change status to complete if this point was - reached because downloading has finished. */ - if (status == DOWNLOADING) { - status = COMPLETE; - downloadedFile = new File(this.getFilePath()); - stateChanged(); - } - } catch (Exception e) { - e.printStackTrace(); - error(); - } finally { - // Close file. - if (file != null) { - try { - file.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - // Close connection to server. - if (stream != null) { - try { - stream.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } - - // Notify observers that this download's status has changed. - private void stateChanged() { - setChanged(); - notifyObservers(); - } +package org.collectionspace.services.common; +import java.io.*; +import java.net.*; +import java.util.*; + +// This class downloads a file from a URL. +public class Download extends Observable implements Runnable { + + public static URL verifyUrl(String url) { + // Only allow HTTP URLs. + if (!url.toLowerCase().startsWith("http://")) + return null; + + // Verify format of URL. + URL verifiedUrl = null; + try { + verifiedUrl = new URL(url); + } catch (Exception e) { + return null; + } + + // Make sure URL specifies a file. + if (verifiedUrl.getFile().length() < 2) + return null; + + return verifiedUrl; + } + + // Max size of download buffer. + private static final int MAX_BUFFER_SIZE = 1024; + + // These are the status names. + public static final String STATUSES[] = {"Downloading", + "Paused", "Complete", "Cancelled", "Error"}; + + // These are the status codes. + public static final int DOWNLOADING = 0; + public static final int PAUSED = 1; + public static final int COMPLETE = 2; + public static final int CANCELLED = 3; + public static final int ERROR = 4; + + private String errorMessage = null; + private String filePath = null; + private File downloadedFile = null; + private String destDir = null; // the location of the downloaded file + private URL url; // download URL + private int size; // size of download in bytes + private int downloaded; // number of bytes downloaded + private int status; // current status of download + + private void doDownload(URL url, String destDir) { + size = -1; + downloaded = 0; + status = DOWNLOADING; + this.url = url; + setDestDir(destDir); + + // Begin the download. + download(); + } + + public Download(URL url, String destDir) { + doDownload(url, destDir); + } + + // Constructor for Download. File is uploaded to system temp directory. + public Download(URL url) { + String tmpdir = System.getProperty("java.io.tmpdir"); + if (tmpdir.endsWith(File.separator) == false) { + tmpdir = tmpdir + File.separator; + } + doDownload(url, tmpdir + + UUID.randomUUID() + File.separator); + } + + private void setDestDir(String destDir) { + if (destDir.endsWith(File.separator) != true) { + destDir = destDir + File.separator; + } + // + // Check if the destDir exists, if not try to create it. + // + File destDirFile = new File(destDir); + boolean destDirExists = destDirFile.exists(); + if (destDirExists == false) { + destDirExists = destDirFile.mkdir(); + } else { + destDirExists = destDirFile.isDirectory(); + } + // + // If we couldn't create the directory or if it is already a file then fail. + // + if (destDirExists = true) { + this.destDir = destDir; + } else { + error("Could not download file to: " + destDir); + } + } + + + public File getFile() { + return this.downloadedFile; + } + + public String getFilePath() { + return this.filePath; + } + + public String getDestDir() { + return this.destDir; + } + + // Get this download's URL. + public String getUrl() { + return url.toString(); + } + + // Get this download's size. + public int getSize() { + return size; + } + + // Get this download's progress. + public float getProgress() { + return ((float) downloaded / size) * 100; + } + + // Get this download's status. + public int getStatus() { + return status; + } + + // Pause this download. + public void pause() { + status = PAUSED; + stateChanged(); + } + + // Resume this download. + public void resume() { + status = DOWNLOADING; + stateChanged(); + download(); + } + + // Cancel this download. + public void cancel() { + status = CANCELLED; + stateChanged(); + } + + // Mark this download as having an error. + private void error() { + status = ERROR; + stateChanged(); + } + + // Mark this download as having an error. + private void error(String message) { + this.errorMessage = message; + error(); + } + + // Start or resume downloading. + private void download() { +// Thread thread = new Thread(this); +// thread.start(); + run(); + } + + // Get file name portion of URL. + private String getFileName(URL url) { + String result = null; + + String destDir = this.getDestDir(); + String fileName = url.getFile(); + fileName = fileName.substring(fileName.lastIndexOf('/') + 1); + result = filePath = destDir + fileName; + + return result; + } + + // Download file. + public void run() { + RandomAccessFile file = null; + InputStream stream = null; + + try { + // Open connection to URL. + HttpURLConnection connection = + (HttpURLConnection) url.openConnection(); + + // Specify what portion of file to download. + connection.setRequestProperty("Range", + "bytes=" + downloaded + "-"); + + // Connect to server. + connection.connect(); + + // Make sure response code is in the 200 range. + int responseCode = connection.getResponseCode(); + if (responseCode / 100 != 2) { + error(); + } + + // Check for valid content length. + int contentLength = connection.getContentLength(); + if (contentLength < 1) { + error(); + } + + /* Set the size for this download if it + hasn't been already set. */ + if (size == -1) { + size = contentLength; + stateChanged(); + } + + // Open file and seek to the end of it. + File javaFile = new File(getFileName(url)); + file = new RandomAccessFile(javaFile, "rw"); + file.seek(downloaded); + + stream = connection.getInputStream(); + while (status == DOWNLOADING) { + /* Size buffer according to how much of the + file is left to download. */ + byte buffer[]; + if (size - downloaded > MAX_BUFFER_SIZE) { + buffer = new byte[MAX_BUFFER_SIZE]; + } else { + buffer = new byte[size - downloaded]; + } + + // Read from server into buffer. + int read = stream.read(buffer); + if (read == -1) + break; + + // Write buffer to file. + file.write(buffer, 0, read); + downloaded += read; + stateChanged(); + } + + /* Change status to complete if this point was + reached because downloading has finished. */ + if (status == DOWNLOADING) { + status = COMPLETE; + downloadedFile = new File(this.getFilePath()); + stateChanged(); + } + } catch (Exception e) { + e.printStackTrace(); + error(); + } finally { + // Close file. + if (file != null) { + try { + file.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + // Close connection to server. + if (stream != null) { + try { + stream.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + // Notify observers that this download's status has changed. + private void stateChanged() { + setChanged(); + notifyObservers(); + } } \ No newline at end of file diff --git a/services/common/src/main/java/org/collectionspace/services/common/FileUtils.java b/services/common/src/main/java/org/collectionspace/services/common/FileUtils.java index 7727fbc69..1b59b5880 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/FileUtils.java +++ b/services/common/src/main/java/org/collectionspace/services/common/FileUtils.java @@ -1,239 +1,239 @@ -/** - * 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; - -//import java.io.*; -import javax.servlet.http.HttpServletRequest; - -import java.io.*; -import java.util.Iterator; -import java.util.List; -import java.util.UUID; - -//import java.io.IOException; - -//import java.util.UUID; -//import java.util.regex.Pattern; -//import java.util.regex.Matcher; - -//import javax.servlet.ServletException; -//import javax.servlet.http.HttpServlet; - -import net.sf.jmimemagic.Magic; -import net.sf.jmimemagic.MagicException; -import net.sf.jmimemagic.MagicMatch; -import net.sf.jmimemagic.MagicMatchNotFoundException; -import net.sf.jmimemagic.MagicParseException; - -import org.apache.commons.fileupload.FileItemFactory; -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -// TODO: Auto-generated Javadoc -/** - * The Class FileUtils. - */ -public class FileUtils { - /** The Constant logger. */ - private static final Logger logger = LoggerFactory.getLogger(FileUtils.class); - - /** The Constant TMP_FILE_PREFIX. */ - public static final String TMP_BLOB_PREFIX = "cspace_blob_"; - public static final String DEFAULT_BLOB_NAME = "blob"; - private static final String FILE_FORM_FIELD = "file"; - - public static String getExtension(File file) { - return getExtension(file.getName()); - } - - // Call this method to get the extension by passing the file name - public static String getExtension(String fileName) { - if (fileName == null) { - return null; - } - - int index = fileName.lastIndexOf("."); - if (index == -1) { - return ""; - } - - return fileName.substring(index + 1); - } - - /* - * Creates a copy of the srcFile to a temp file - */ - static public File createTmpFile(File srcFile, String prefix) throws Exception { - String fileExtension = FileUtils.getExtension(srcFile); - File result = createTmpFile(new FileInputStream(srcFile), prefix, fileExtension); - return result; - } - - /** - * Creates the tmp file. - * - * @param streamIn the stream in - * @param filePrefix the file prefix - * @return the file - */ - static public File createTmpFile(InputStream streamIn, - String filePrefix) { - return createTmpFile(streamIn, filePrefix, null); - } - - /** - * Creates the tmp file. - * - * @param streamIn the stream in - * @param filePrefix the file prefix - * @param fileExtension the file extension - * @return the file - */ - static public File createTmpFile(InputStream streamIn, - String filePrefix, String fileExtension) { - File result = null; - - filePrefix = filePrefix != null ? filePrefix : ""; - fileExtension = fileExtension != null ? "." + fileExtension : ""; - String tmpDir = System.getProperty("java.io.tmpdir"); - result = new File(tmpDir, filePrefix + UUID.randomUUID().toString() + fileExtension); - if (logger.isDebugEnabled() == true) { - logger.debug("Creating temp file at:" + result.getAbsolutePath()); - } - - try { - FileOutputStream streamOut = new FileOutputStream(result); - int c; - while ((c = streamIn.read()) != -1) - { - streamOut.write(c); - } - - streamIn.close(); - streamOut.close(); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - - return result; - } - - static public String getMimeType(File file) { - String result = null; - - Magic parser = new Magic() ; - // getMagicMatch accepts Files or byte[], - // which is nice if you want to test streams - MagicMatch match = null; - try { - match = parser.getMagicMatch(file, true); - } catch (MagicParseException e) { - logger.debug("MagicParseException encountered trying to get MIME type for " - + file.getAbsolutePath(), e); - } catch (MagicMatchNotFoundException e) { - logger.debug("MagicMatchNotFoundException encountered trying to get MIME type for " - + file.getAbsolutePath(), e); - } catch (MagicException e) { - logger.debug("MagicException encountered trying to get MIME type for " - + file.getAbsolutePath(), e); - } - - if (match != null) { - result = match.getMimeType(); - } - - return result; - } - - /** - * Look for an uploaded file from the HTTP request of type "multipart/form-data". - * - * @param request the request - * @return the file - */ - static public File createTmpFile(HttpServletRequest request) { - File result = null; - - FileItemFactory factory = new DiskFileItemFactory(); - ServletFileUpload upload = new ServletFileUpload(factory); - - try { - List items = upload.parseRequest(request); - Iterator iter = items.iterator(); - - while (iter.hasNext()) { - FileItem item = iter.next(); - String formFieldName = item.getFieldName(); - if (logger.isTraceEnabled() == true) { - logger.trace("HTTP Request form field:" + formFieldName); - } - if (formFieldName.equalsIgnoreCase(FILE_FORM_FIELD)) { - if (item.isFormField() == true) { - logger.warn("Form field '" + FILE_FORM_FIELD + "': part is marked as a form field."); - } - String fileName = item.getName(); - if (logger.isTraceEnabled() == true) { - logger.trace("Uploaded File Name:" + (fileName != null ? fileName : "")); - } - if (fileName == null) { - fileName = DEFAULT_BLOB_NAME; //if there's no file name then set it to an empty string - logger.warn("File was posted to the services without a file name."); - } - // - // To avoid name collisions and to preserve the posted file name, create a temp directory for the - // file. - // - File tmpDir = new File(System.getProperty("java.io.tmpdir")); - String fileTmpDirPath = tmpDir.getPath() + File.separatorChar + UUID.randomUUID(); - File fileTmpDir = new File(fileTmpDirPath); - File savedFile = null; - if (fileTmpDir.mkdir() == true) { - savedFile = new File(fileTmpDirPath + File.separatorChar + fileName); - if (savedFile.createNewFile() == false) { - savedFile = null; - } - } - - if (savedFile != null) { - item.write(savedFile); -// item.getInputStream();//FIXME: REM - We should make a version of this method that returns the input stream - result = savedFile; - } else { - logger.error("Could not create temporary file: " + fileTmpDirPath + - File.separatorChar + fileName); - } - } - } - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - - return result; - } - -} +/** + * 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; + +//import java.io.*; +import javax.servlet.http.HttpServletRequest; + +import java.io.*; +import java.util.Iterator; +import java.util.List; +import java.util.UUID; + +//import java.io.IOException; + +//import java.util.UUID; +//import java.util.regex.Pattern; +//import java.util.regex.Matcher; + +//import javax.servlet.ServletException; +//import javax.servlet.http.HttpServlet; + +import net.sf.jmimemagic.Magic; +import net.sf.jmimemagic.MagicException; +import net.sf.jmimemagic.MagicMatch; +import net.sf.jmimemagic.MagicMatchNotFoundException; +import net.sf.jmimemagic.MagicParseException; + +import org.apache.commons.fileupload.FileItemFactory; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +// TODO: Auto-generated Javadoc +/** + * The Class FileUtils. + */ +public class FileUtils { + /** The Constant logger. */ + private static final Logger logger = LoggerFactory.getLogger(FileUtils.class); + + /** The Constant TMP_FILE_PREFIX. */ + public static final String TMP_BLOB_PREFIX = "cspace_blob_"; + public static final String DEFAULT_BLOB_NAME = "blob"; + private static final String FILE_FORM_FIELD = "file"; + + public static String getExtension(File file) { + return getExtension(file.getName()); + } + + // Call this method to get the extension by passing the file name + public static String getExtension(String fileName) { + if (fileName == null) { + return null; + } + + int index = fileName.lastIndexOf("."); + if (index == -1) { + return ""; + } + + return fileName.substring(index + 1); + } + + /* + * Creates a copy of the srcFile to a temp file + */ + static public File createTmpFile(File srcFile, String prefix) throws Exception { + String fileExtension = FileUtils.getExtension(srcFile); + File result = createTmpFile(new FileInputStream(srcFile), prefix, fileExtension); + return result; + } + + /** + * Creates the tmp file. + * + * @param streamIn the stream in + * @param filePrefix the file prefix + * @return the file + */ + static public File createTmpFile(InputStream streamIn, + String filePrefix) { + return createTmpFile(streamIn, filePrefix, null); + } + + /** + * Creates the tmp file. + * + * @param streamIn the stream in + * @param filePrefix the file prefix + * @param fileExtension the file extension + * @return the file + */ + static public File createTmpFile(InputStream streamIn, + String filePrefix, String fileExtension) { + File result = null; + + filePrefix = filePrefix != null ? filePrefix : ""; + fileExtension = fileExtension != null ? "." + fileExtension : ""; + String tmpDir = System.getProperty("java.io.tmpdir"); + result = new File(tmpDir, filePrefix + UUID.randomUUID().toString() + fileExtension); + if (logger.isDebugEnabled() == true) { + logger.debug("Creating temp file at:" + result.getAbsolutePath()); + } + + try { + FileOutputStream streamOut = new FileOutputStream(result); + int c; + while ((c = streamIn.read()) != -1) + { + streamOut.write(c); + } + + streamIn.close(); + streamOut.close(); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + + return result; + } + + static public String getMimeType(File file) { + String result = null; + + Magic parser = new Magic() ; + // getMagicMatch accepts Files or byte[], + // which is nice if you want to test streams + MagicMatch match = null; + try { + match = parser.getMagicMatch(file, true); + } catch (MagicParseException e) { + logger.debug("MagicParseException encountered trying to get MIME type for " + + file.getAbsolutePath(), e); + } catch (MagicMatchNotFoundException e) { + logger.debug("MagicMatchNotFoundException encountered trying to get MIME type for " + + file.getAbsolutePath(), e); + } catch (MagicException e) { + logger.debug("MagicException encountered trying to get MIME type for " + + file.getAbsolutePath(), e); + } + + if (match != null) { + result = match.getMimeType(); + } + + return result; + } + + /** + * Look for an uploaded file from the HTTP request of type "multipart/form-data". + * + * @param request the request + * @return the file + */ + static public File createTmpFile(HttpServletRequest request) { + File result = null; + + FileItemFactory factory = new DiskFileItemFactory(); + ServletFileUpload upload = new ServletFileUpload(factory); + + try { + List items = upload.parseRequest(request); + Iterator iter = items.iterator(); + + while (iter.hasNext()) { + FileItem item = iter.next(); + String formFieldName = item.getFieldName(); + if (logger.isTraceEnabled() == true) { + logger.trace("HTTP Request form field:" + formFieldName); + } + if (formFieldName.equalsIgnoreCase(FILE_FORM_FIELD)) { + if (item.isFormField() == true) { + logger.warn("Form field '" + FILE_FORM_FIELD + "': part is marked as a form field."); + } + String fileName = item.getName(); + if (logger.isTraceEnabled() == true) { + logger.trace("Uploaded File Name:" + (fileName != null ? fileName : "")); + } + if (fileName == null) { + fileName = DEFAULT_BLOB_NAME; //if there's no file name then set it to an empty string + logger.warn("File was posted to the services without a file name."); + } + // + // To avoid name collisions and to preserve the posted file name, create a temp directory for the + // file. + // + File tmpDir = new File(System.getProperty("java.io.tmpdir")); + String fileTmpDirPath = tmpDir.getPath() + File.separatorChar + UUID.randomUUID(); + File fileTmpDir = new File(fileTmpDirPath); + File savedFile = null; + if (fileTmpDir.mkdir() == true) { + savedFile = new File(fileTmpDirPath + File.separatorChar + fileName); + if (savedFile.createNewFile() == false) { + savedFile = null; + } + } + + if (savedFile != null) { + item.write(savedFile); +// item.getInputStream();//FIXME: REM - We should make a version of this method that returns the input stream + result = savedFile; + } else { + logger.error("Could not create temporary file: " + fileTmpDirPath + + File.separatorChar + fileName); + } + } + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + + return result; + } + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/IFragmentHandler.java b/services/common/src/main/java/org/collectionspace/services/common/IFragmentHandler.java index 5a31f4919..15dbf6326 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/IFragmentHandler.java +++ b/services/common/src/main/java/org/collectionspace/services/common/IFragmentHandler.java @@ -1,56 +1,56 @@ -/** - * 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 2011 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; - -import org.dom4j.Document; -import org.dom4j.Element; - -/** Define this interface to listen for events from the driving class: - * org.collectionspace.services.common.XmlSaxFragmenter , so that - * the XmlSaxFragmenter class may be passed a large file or InputSource (stream) - * and it will be parsed with SAX, but you will get fragments from it that you can - * parse with DOM. - * - * You will be passed a Document context, which is a Dom4j document that represents the - * skeleton of the document you started with, but without any fragments, so the Document - * will just be context information of how the XmlSaxFragmenter found this fragment. - * - * You will receive onFragmentReady() events whenever a fragment is parsed completely. - * the fragment parameter will be just the inner XML String of fragmentParent, and will - * not be represented in the DOM of the Document context. - * - * @author Laramie Crocker - */ -public interface IFragmentHandler { - /** @param fragmentIndex is the zero-based index of the current fragment; you will first get this event - * on fragmentIndex==0, which is a fragmentCount of 1. */ - public void onFragmentReady(Document context, - Element fragmentParent, - String currentPath, - int fragmentIndex, - String fragment); - - /** @param fragmentCount is the count of fragments processed - a value of 1 means 1 fragment was found. */ - public void onEndDocument(Document context, int fragmentCount); -} +/** + * 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 2011 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; + +import org.dom4j.Document; +import org.dom4j.Element; + +/** Define this interface to listen for events from the driving class: + * org.collectionspace.services.common.XmlSaxFragmenter , so that + * the XmlSaxFragmenter class may be passed a large file or InputSource (stream) + * and it will be parsed with SAX, but you will get fragments from it that you can + * parse with DOM. + * + * You will be passed a Document context, which is a Dom4j document that represents the + * skeleton of the document you started with, but without any fragments, so the Document + * will just be context information of how the XmlSaxFragmenter found this fragment. + * + * You will receive onFragmentReady() events whenever a fragment is parsed completely. + * the fragment parameter will be just the inner XML String of fragmentParent, and will + * not be represented in the DOM of the Document context. + * + * @author Laramie Crocker + */ +public interface IFragmentHandler { + /** @param fragmentIndex is the zero-based index of the current fragment; you will first get this event + * on fragmentIndex==0, which is a fragmentCount of 1. */ + public void onFragmentReady(Document context, + Element fragmentParent, + String currentPath, + int fragmentIndex, + String fragment); + + /** @param fragmentCount is the count of fragments processed - a value of 1 means 1 fragment was found. */ + public void onEndDocument(Document context, int fragmentCount); +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/ReflectionMapper.java b/services/common/src/main/java/org/collectionspace/services/common/ReflectionMapper.java index b7780a657..fee1cde93 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/ReflectionMapper.java +++ b/services/common/src/main/java/org/collectionspace/services/common/ReflectionMapper.java @@ -1,126 +1,126 @@ -/** - * 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 - */ -package org.collectionspace.services.common; - -import org.collectionspace.services.common.api.Tools; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; - -/** User: laramie - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ -public class ReflectionMapper { - - public static boolean isSetter(Method method) { - if (!method.getName().startsWith("set")) return false; - if (method.getParameterTypes().length != 1) return false; - return true; - } - - public static Object fireSetMethod(Method setMethod, Object target, Object arg) throws Exception { - if (target != null && setMethod != null) { - return setMethod.invoke(target, arg); - } - return null; - } - - public static Object fireGetMethod(Method getMethod, Object target) throws Exception { - if (target != null && getMethod != null) { - Object[] arg = new Object[0]; - //System.out.println("\r\n~~~~~~~~ fireGetMethod("+getMethod+")"); - return getMethod.invoke(target, arg); - } - return null; - } - - public static enum STATUS {OK, NO_SUCH_METHOD, EXCEPTION}; - - public static STATUS callSetterUncaught(Object target, String name, Object arg) throws Exception { - if (Tools.isEmpty(name)){ - return STATUS.NO_SUCH_METHOD; - } - if (target==null){ - return STATUS.EXCEPTION; - } - Class aClass = target.getClass(); - Method m; - - Class[] cls = new Class[1]; - cls[0] = String.class; - try { - m = aClass.getMethod(name, cls); - } catch (NoSuchMethodException nsm){ - m = null; - } - if (m==null){ - m = aClass.getMethod(name, Object.class); //throws NoSuchMethodException if not found. - } - //todo: if m==null, call callSetterCaseInsensitive(). - fireSetMethod(m, target, arg); - return STATUS.OK; - } - - public static STATUS callSetter(Object target, String name, Object arg) { - try { - callSetterUncaught(target, name, arg); - } catch (NoSuchMethodException nsm) { - System.out.println("ERROR in ReflectionMapper.callSetter(target:"+target+", name:"+name+", arg:"+arg+"): "+nsm); - return STATUS.NO_SUCH_METHOD; - } catch (Exception e) { - System.out.println("ERROR in ReflectionMapper.callSetter(target:"+target+", name:"+name+", arg:"+arg+"): "+e); - return STATUS.EXCEPTION; - } - return STATUS.OK; - } - - public static Object instantiate(String classname) throws Exception { - if (classname == null) { - throw new Exception("classname was null in ReflectionMapper.instantiate()"); - } - classname = classname.trim(); - Class cl = Class.forName(classname); - Class [] classParm = null; - Object [] objectParm = null; - Constructor co = cl.getConstructor(classParm); - Object item = co.newInstance(objectParm); - return item; - } - - // EXPERIMENTAL: - public static void callSetterCaseInsensitive(Class aClass, Object target, Object args){ - boolean showInheritedMethods = false; - Method[] methods = aClass.getMethods(); - for (Method method : methods) { - Class dc = method.getDeclaringClass(); - boolean sameClass = aClass.equals(dc); - if (showInheritedMethods || sameClass) { - if (isSetter(method) && method.getParameterTypes().length==1) { - String id = method.getName(); - Method setMethod = method; - String dataClass = method.getParameterTypes()[0].getName(); - - args = "MyNewValue"; - //todo: fireSetMethod(setMethod, target, args); - System.out.println("setter: " + method + " in class: " + dc); - } - } - } - } -} +/** + * 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 + */ +package org.collectionspace.services.common; + +import org.collectionspace.services.common.api.Tools; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; + +/** User: laramie + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public class ReflectionMapper { + + public static boolean isSetter(Method method) { + if (!method.getName().startsWith("set")) return false; + if (method.getParameterTypes().length != 1) return false; + return true; + } + + public static Object fireSetMethod(Method setMethod, Object target, Object arg) throws Exception { + if (target != null && setMethod != null) { + return setMethod.invoke(target, arg); + } + return null; + } + + public static Object fireGetMethod(Method getMethod, Object target) throws Exception { + if (target != null && getMethod != null) { + Object[] arg = new Object[0]; + //System.out.println("\r\n~~~~~~~~ fireGetMethod("+getMethod+")"); + return getMethod.invoke(target, arg); + } + return null; + } + + public static enum STATUS {OK, NO_SUCH_METHOD, EXCEPTION}; + + public static STATUS callSetterUncaught(Object target, String name, Object arg) throws Exception { + if (Tools.isEmpty(name)){ + return STATUS.NO_SUCH_METHOD; + } + if (target==null){ + return STATUS.EXCEPTION; + } + Class aClass = target.getClass(); + Method m; + + Class[] cls = new Class[1]; + cls[0] = String.class; + try { + m = aClass.getMethod(name, cls); + } catch (NoSuchMethodException nsm){ + m = null; + } + if (m==null){ + m = aClass.getMethod(name, Object.class); //throws NoSuchMethodException if not found. + } + //todo: if m==null, call callSetterCaseInsensitive(). + fireSetMethod(m, target, arg); + return STATUS.OK; + } + + public static STATUS callSetter(Object target, String name, Object arg) { + try { + callSetterUncaught(target, name, arg); + } catch (NoSuchMethodException nsm) { + System.out.println("ERROR in ReflectionMapper.callSetter(target:"+target+", name:"+name+", arg:"+arg+"): "+nsm); + return STATUS.NO_SUCH_METHOD; + } catch (Exception e) { + System.out.println("ERROR in ReflectionMapper.callSetter(target:"+target+", name:"+name+", arg:"+arg+"): "+e); + return STATUS.EXCEPTION; + } + return STATUS.OK; + } + + public static Object instantiate(String classname) throws Exception { + if (classname == null) { + throw new Exception("classname was null in ReflectionMapper.instantiate()"); + } + classname = classname.trim(); + Class cl = Class.forName(classname); + Class [] classParm = null; + Object [] objectParm = null; + Constructor co = cl.getConstructor(classParm); + Object item = co.newInstance(objectParm); + return item; + } + + // EXPERIMENTAL: + public static void callSetterCaseInsensitive(Class aClass, Object target, Object args){ + boolean showInheritedMethods = false; + Method[] methods = aClass.getMethods(); + for (Method method : methods) { + Class dc = method.getDeclaringClass(); + boolean sameClass = aClass.equals(dc); + if (showInheritedMethods || sameClass) { + if (isSetter(method) && method.getParameterTypes().length==1) { + String id = method.getName(); + Method setMethod = method; + String dataClass = method.getParameterTypes()[0].getName(); + + args = "MyNewValue"; + //todo: fireSetMethod(setMethod, target, args); + System.out.println("setter: " + method + " in class: " + dc); + } + } + } + } +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/ResourceBase.java b/services/common/src/main/java/org/collectionspace/services/common/ResourceBase.java index 92bb9d816..4ded3611f 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/ResourceBase.java +++ b/services/common/src/main/java/org/collectionspace/services/common/ResourceBase.java @@ -1,629 +1,629 @@ -/** - * 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 2010 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; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.*; -import javax.ws.rs.core.*; - -import org.collectionspace.services.client.IClientQueryParams; -import org.collectionspace.services.client.IQueryManager; -import org.collectionspace.services.client.PoxPayloadIn; -import org.collectionspace.services.client.PoxPayloadOut; -import org.collectionspace.services.common.api.RefName; -import org.collectionspace.services.common.api.Tools; -import org.collectionspace.services.common.authorityref.AuthorityRefList; -import org.collectionspace.services.common.config.ServiceConfigUtils; -import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl; -import org.collectionspace.services.common.context.RemoteServiceContext; -import org.collectionspace.services.common.context.ServiceContext; -import org.collectionspace.services.common.document.DocumentFilter; -import org.collectionspace.services.common.document.DocumentHandler; -import org.collectionspace.services.common.document.DocumentNotFoundException; -import org.collectionspace.services.common.query.QueryManager; -import org.collectionspace.services.common.vocabulary.RefNameServiceUtils; -import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthRefConfigInfo; -import org.collectionspace.services.config.ClientType; -import org.collectionspace.services.config.service.DocHandlerParams; -import org.collectionspace.services.config.service.ListResultField; -import org.collectionspace.services.config.service.ServiceBindingType; -import org.collectionspace.services.jaxb.AbstractCommonList; -import org.collectionspace.services.nuxeo.client.java.DocumentModelHandler; -import org.collectionspace.services.nuxeo.client.java.RepositoryInstanceInterface; -import org.collectionspace.services.nuxeo.util.NuxeoUtils; -import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; -import org.jboss.resteasy.util.HttpResponseCodes; -import org.nuxeo.ecm.core.api.DocumentModel; -import org.nuxeo.ecm.core.api.DocumentModelList; -import org.nuxeo.ecm.core.api.repository.RepositoryInstance; - - -/** - * $LastChangedRevision: $ - * $LastChangedDate: $ - * Author: Laramie Crocker - */ -public abstract class ResourceBase - extends AbstractMultiPartCollectionSpaceResourceImpl { - - public static final String CREATE = "create"; - public static final String READ = "get"; - public static final String UPDATE = "update"; - public static final String DELETE = "delete"; - public static final String LIST = "list"; - //FIXME retrieve client type from configuration - static ClientType CLIENT_TYPE; - - /* - * REM - 11/14/2011 - I discovered this static block of code and don't understand why it exists. However, a side-effect of this static block is that ServiceMain is trying - * to create a valid instance of entire CSpace services include an embedded Nuxeo instance. This block of code seems goofy and unnecessary and probably should be removed? - */ - static { - try { - // I put this in a try-catch static block instead of file-level static var initializer so that static methods of - // *Resource classes may be called statically from test cases. - // Without this catch, you can't even access static methods of a *Resource class for testing. - CLIENT_TYPE = ServiceMain.getInstance().getClientType(); - //System.out.println("Static initializer in ResourceBase. CLIENT_TYPE:"+CLIENT_TYPE); - } catch (Throwable t) { - System.out.println("Static initializer failed in ResourceBase because not running from deployment. OK to use Resource classes statically for tests."); - } - } - - //======================= CREATE ==================================================== - - @POST - public Response create( - @Context ResourceMap resourceMap, - @Context UriInfo ui, - String xmlPayload) { - return this.create(null, resourceMap, ui, xmlPayload); - } - - public Response create(ServiceContext parentCtx, // REM: 8/13/2012 - Some sub-classes will override this method -e.g., MediaResource does. - ResourceMap resourceMap, - UriInfo uriInfo, - String xmlPayload) { - Response result = null; - - try { - PoxPayloadIn input = new PoxPayloadIn(xmlPayload); - ServiceContext ctx = createServiceContext(input, resourceMap, uriInfo); - ctx.setResourceMap(resourceMap); - if (parentCtx != null && parentCtx.getCurrentRepositorySession() != null) { - ctx.setCurrentRepositorySession(parentCtx.getCurrentRepositorySession()); // Reuse the current repo session if one exists - } - result = create(input, ctx); - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.CREATE_FAILED); - } - - return result; - } - - protected Response create(PoxPayloadIn input, ServiceContext ctx) { - try { - DocumentHandler handler = createDocumentHandler(ctx); - UriBuilder path = UriBuilder.fromResource(this.getClass()); - return create(input, ctx, handler, path); //==> CALL implementation method, which subclasses may override. - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.CREATE_FAILED); - } - } - - /** Subclasses may override this overload, which gets called from @see #create(MultipartInput) */ - protected Response create(PoxPayloadIn input, - ServiceContext ctx, - DocumentHandler handler, - UriBuilder path) - throws Exception { - String csid = getRepositoryClient(ctx).create(ctx, handler); - path.path("" + csid); - Response response = Response.created(path.build()).build(); - return response; - } - - //======================= UPDATE ==================================================== - @PUT - @Path("{csid}") - public byte[] update(@Context ResourceMap resourceMap, - @Context UriInfo uriInfo, - @PathParam("csid") String csid, - String xmlPayload) { - return this.update(null, resourceMap, uriInfo, csid, xmlPayload); - } - - public byte[] update(ServiceContext parentCtx, // REM: 8/13/2012 - Some sub-classes will override this method -e.g., MediaResource does. - @Context ResourceMap resourceMap, - @Context UriInfo uriInfo, - @PathParam("csid") String csid, - String xmlPayload) { - PoxPayloadOut result = null; - ensureCSID(csid, UPDATE); - try { - PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload); - ServiceContext ctx = createServiceContext(theUpdate, uriInfo); - ctx.setResourceMap(resourceMap); - if (parentCtx != null && parentCtx.getCurrentRepositorySession() != null) { - ctx.setCurrentRepositorySession(parentCtx.getCurrentRepositorySession()); // Reuse the current repo session if one exists - } - result = update(csid, theUpdate, ctx); //==> CALL implementation method, which subclasses may override. - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.UPDATE_FAILED, csid); - } - return result.getBytes(); - } - - /** Subclasses may override this overload, which gets called from #udpate(String,MultipartInput) */ - protected PoxPayloadOut update(String csid, - PoxPayloadIn theUpdate, - ServiceContext ctx) - throws Exception { - DocumentHandler handler = createDocumentHandler(ctx); - getRepositoryClient(ctx).update(ctx, csid, handler); - return ctx.getOutput(); - } - - /** Subclasses may override this overload, which gets called from #udpate(String,MultipartInput) */ - protected PoxPayloadOut update(String csid, - MultipartInput theUpdate, - ServiceContext ctx, - DocumentHandler handler) - throws Exception { - getRepositoryClient(ctx).update(ctx, csid, handler); - return ctx.getOutput(); - } - - //======================= DELETE ==================================================== - @DELETE - @Path("{csid}") - public Response delete(@PathParam("csid") String csid) { - ensureCSID(csid, DELETE); - try { - ServiceContext ctx = createServiceContext(); - return delete(ctx, csid); //==> CALL implementation method, which subclasses may override. - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid); - } - } - - /** subclasses may override this method, which is called from #delete(String) - * which handles setup of ServiceContext, and does Exception handling. */ - protected Response delete(ServiceContext ctx, String csid) - throws Exception { - DocumentHandler handler = createDocumentHandler(ctx); - getRepositoryClient(ctx).delete(ctx, csid, handler); - return Response.status(HttpResponseCodes.SC_OK).build(); - } - - public Response deleteWithParentCtx(ServiceContext parentCtx, - String csid) - throws Exception { - ensureCSID(csid, DELETE); - try { - ServiceContext ctx = createServiceContext(); - if (parentCtx != null && parentCtx.getCurrentRepositorySession() != null) { - ctx.setCurrentRepositorySession(parentCtx.getCurrentRepositorySession()); // reuse the repo session if one exists - } - return delete(ctx, csid); //==> CALL implementation method, which subclasses may override. - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid); - } - } - - //======================= GET ==================================================== - @GET - @Path("{csid}") - public byte[] get( - @Context Request request, - @Context UriInfo uriInfo, - @PathParam("csid") String csid) { - PoxPayloadOut result = null; - ensureCSID(csid, READ); - try { - RemoteServiceContext ctx = (RemoteServiceContext) createServiceContext(uriInfo); - result = get(csid, ctx);// ==> CALL implementation method, which subclasses may override. - if (result == null) { - Response response = Response.status(Response.Status.NOT_FOUND).entity( - ServiceMessages.READ_FAILED + ServiceMessages.resourceNotFoundMsg(csid)).type("text/plain").build(); - throw new CSWebApplicationException(response); - } - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.READ_FAILED, csid); - } - - return result.getBytes(); - } - - protected PoxPayloadOut get(@PathParam("csid") String csid, - ServiceContext ctx) throws Exception { - PoxPayloadOut result = null; - - ensureCSID(csid, READ); - DocumentHandler handler = createDocumentHandler(ctx); - result = get(csid, ctx, handler); - if (result == null) { - String msg = "Could not find document with id = " + csid; - if (logger.isErrorEnabled() == true) { - logger.error(msg); - } - throw new DocumentNotFoundException(msg); - } - - return result; - } - - /** subclasses may override this method, which is called from #get(String) - * which handles setup of ServiceContext and DocumentHandler, and Exception handling.*/ - protected PoxPayloadOut get(String csid, - ServiceContext ctx, - DocumentHandler handler) - throws Exception { - getRepositoryClient(ctx).get(ctx, csid, handler); - return ctx.getOutput(); - } - - protected boolean isGetAllRequest(MultivaluedMap queryParams) { - boolean result = false; - - String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW); - String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS); - String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM); - - if (Tools.isBlank(keywords) && Tools.isBlank(advancedSearch) && Tools.isBlank(partialTerm)) { - result = true; - } - - return result; - } - - //======================= GET without csid. List, search, etc. ===================================== - @GET - public AbstractCommonList getList(@Context UriInfo ui) { - AbstractCommonList list = null; - - MultivaluedMap queryParams = ui.getQueryParameters(); - if (isGetAllRequest(queryParams) == false) { - String orderBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM); - String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW); - String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS); - String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM); - list = search(ui, orderBy, keywords, advancedSearch, partialTerm); - } else { - list = getCommonList(ui); - } - - return list; - } - - protected AbstractCommonList getCommonList(UriInfo uriInfo) { - try { - ServiceContext ctx = createServiceContext(uriInfo); - DocumentHandler handler = createDocumentHandler(ctx); - getRepositoryClient(ctx).getFiltered(ctx, handler); - AbstractCommonList list = (AbstractCommonList) handler.getCommonPartList(); - return list; - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.LIST_FAILED); - } - } - - protected AbstractCommonList finish_getList(ServiceContext ctx, DocumentHandler handler) { - try { - getRepositoryClient(ctx).getFiltered(ctx, handler); // REM - Side effect of this call sets the handler's common part list value - return (AbstractCommonList) handler.getCommonPartList(); - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.LIST_FAILED); - } - } - - protected AbstractCommonList search( - ServiceContext ctx, - DocumentHandler handler, - UriInfo ui, - String orderBy, - String keywords, - String advancedSearch, - String partialTerm) throws Exception { - DocumentFilter docFilter = handler.getDocumentFilter(); - if (orderBy == null || orderBy.isEmpty()) { - String orderByField = getOrderByField(ctx); - docFilter.setOrderByClause(orderByField); - } - - // - // NOTE: Partial-term (PT) queries are mutually exclusive to keyword and - // partial-term queries trump keyword queries. - // - if (partialTerm != null && !partialTerm.isEmpty()) { - String partialTermMatchField = getPartialTermMatchField(ctx); - String ptClause = QueryManager.createWhereClauseForPartialMatch(ctx, partialTermMatchField, - partialTerm); - docFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND); - } else if (keywords != null && !keywords.isEmpty()) { - String whereClause = QueryManager.createWhereClauseFromKeywords(keywords); - if (Tools.isEmpty(whereClause) == false) { - docFilter.appendWhereClause(whereClause, IQueryManager.SEARCH_QUALIFIER_AND); - if (logger.isDebugEnabled()) { - logger.debug("The WHERE clause is: " + docFilter.getWhereClause()); - } - } else { - if (logger.isWarnEnabled()) { - logger.warn("The WHERE clause is empty for keywords: ["+keywords+"]"); - } - } - } - - // - // Add an advance search clause if one was specified -even if PT search was requested? - // - if (advancedSearch != null && !advancedSearch.isEmpty()) { - String whereClause = QueryManager.createWhereClauseFromAdvancedSearch(advancedSearch); - docFilter.appendWhereClause(whereClause, IQueryManager.SEARCH_QUALIFIER_AND); - if (logger.isDebugEnabled()) { - logger.debug("The WHERE clause is: " + docFilter.getWhereClause()); - } - } - - getRepositoryClient(ctx).getFiltered(ctx, handler); - return (AbstractCommonList) handler.getCommonPartList(); - } - - private AbstractCommonList search( - UriInfo uriInfo, - String orderBy, - String keywords, - String advancedSearch, - String partialTerm) { - AbstractCommonList result = null; - - ServiceContext ctx; - try { - ctx = createServiceContext(uriInfo); - DocumentHandler handler = createDocumentHandler(ctx); - result = search(ctx, handler, uriInfo, orderBy, keywords, advancedSearch, partialTerm); - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.SEARCH_FAILED); - } - - return result; - } - - //FIXME: REM - This should not be @Deprecated since we may want to implement this -it has been on the wish list. - @Deprecated - public AbstractCommonList getList(List csidList) { - try { - ServiceContext ctx = createServiceContext(); - DocumentHandler handler = createDocumentHandler(ctx); - getRepositoryClient(ctx).get(ctx, csidList, handler); - return (AbstractCommonList) handler.getCommonPartList(); - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.LIST_FAILED); - } - } - - //======================== GET : getAuthorityRefs ======================================== - @GET - @Path("{csid}/authorityrefs") - @Produces("application/xml") - public AuthorityRefList getAuthorityRefs( - @PathParam("csid") String csid, - @Context UriInfo uriInfo) { - AuthorityRefList authRefList = null; - try { - ServiceContext ctx = createServiceContext(uriInfo); - DocumentModelHandler handler = (DocumentModelHandler) createDocumentHandler(ctx); - List authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx); - authRefList = handler.getAuthorityRefs(csid, authRefsInfo); - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.AUTH_REFS_FAILED, csid); - } - return authRefList; - } - - //======================== UTILITY : getDocModelForRefName ======================================== - - /* - * Used get the order by field for list results if one is not specified with an HTTP query param. - * - * (non-Javadoc) - * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#getOrderByField() - */ - @Override - protected String getOrderByField(ServiceContext ctx) { - String result = null; - - // We only want to use the partial term field to order the results if a PT query param exists - String partialTerm = ctx.getQueryParams().getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM); - if (Tools.notBlank(partialTerm) == true) { - DocHandlerParams.Params params = null; - try { - result = getPartialTermMatchField(ctx); - if (result == null) { - throw new Exception(); - } - } catch (Exception e) { - if (logger.isWarnEnabled()) { - logger.warn(String.format("Call failed to getOrderByField() for class %s", this.getClass().getName())); - } - } - } - - return result; - } - - @Override - protected String getPartialTermMatchField(ServiceContext ctx) { - String result = null; - - DocHandlerParams.Params params = null; - try { - params = ServiceConfigUtils.getDocHandlerParams(ctx); - ListResultField field = params.getRefnameDisplayNameField(); - String schema = field.getSchema(); - if (schema == null || schema.trim().isEmpty()) { - schema = ctx.getCommonPartLabel(); - } - result = schema + ":" + field.getXpath(); - } catch (Exception e) { - if (logger.isWarnEnabled()) { - logger.warn(String.format("Call failed to getPartialTermMatchField() for class %s", this.getClass().getName())); - } - } - - return result; - } - - /* - * ResourceBase create and update calls will set the resourceMap into the service context - * for all inheriting resource classes. Just use ServiceContext.getResourceMap() to get - * the map, and pass it in. - */ - public static DocumentModel getDocModelForRefName(RepositoryInstanceInterface repoSession, String refName, ResourceMap resourceMap) - throws Exception, DocumentNotFoundException { - RefName.AuthorityItem item = RefName.AuthorityItem.parse(refName); - if(item != null) { - ResourceBase resource = resourceMap.get(item.inAuthority.resource); - return resource.getDocModelForAuthorityItem(repoSession, item); - } - RefName.Authority authority = RefName.Authority.parse(refName); - // Handle case of objects refNames, which must be csid based. - if(authority != null && !Tools.isEmpty(authority.csid)) { - ResourceBase resource = resourceMap.get(authority.resource); - // Ensure we have the right context. - ServiceContext ctx = - resource.createServiceContext(authority.resource); - // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here! - DocumentModel docModel = NuxeoUtils.getDocFromCsid(ctx, repoSession, authority.csid); - return docModel; - } - return null; - } - - // THis is ugly, but prevents us parsing the refName twice. Once we make refName a little more - // general, and less Authority(Item) specific, this will look better. - public DocumentModel getDocModelForAuthorityItem(RepositoryInstanceInterface repoSession, RefName.AuthorityItem item) - throws Exception, DocumentNotFoundException { - logger.warn("Default (ResourceBase) getDocModelForAuthorityItem called - should not happen!"); - return null; - } - - public DocumentModel getDocModelForRefName(RepositoryInstanceInterface repoSession, String refName) - throws Exception, DocumentNotFoundException { - return getDocModelForAuthorityItem(repoSession, RefName.AuthorityItem.parse(refName)); - } - - protected String getDocType(String tenantId) { - return getDocType(tenantId, getServiceName()); - } - - /** - * Returns the Nuxeo document type associated with a specified service, within a specified tenant. - * - * @param tenantId a tenant ID - * @param serviceName a service name - * @return the Nuxeo document type associated with that service and tenant. - */ - // FIXME: This method may properly belong in a different services package or class. - // Also, we need to check for any existing methods that may duplicate this one. - protected String getDocType(String tenantId, String serviceName) { - String docType = ""; - if (Tools.isBlank(tenantId)) { - return docType; - } - ServiceBindingType sb = getTenantBindingsReader().getServiceBinding(tenantId, serviceName); - if (sb == null) { - return docType; - } - docType = sb.getObject().getName(); // Reads the Nuxeo Document Type from tenant bindings configuration - return docType; - } - - /** - * Returns a UriRegistry entry: a map of tenant-qualified URI templates - * for the current resource, for all tenants - * - * @return a map of URI templates for the current resource, for all tenants - */ - public Map getUriRegistryEntries() { - Map uriRegistryEntriesMap = - new HashMap(); - List tenantIds = getTenantBindingsReader().getTenantIds(); - for (String tenantId : tenantIds) { - uriRegistryEntriesMap.putAll(getUriRegistryEntries(tenantId, getDocType(tenantId), UriTemplateFactory.RESOURCE)); - } - return uriRegistryEntriesMap; - } - - /** - * Returns a UriRegistry entry: a map of tenant-qualified URI templates - * for the current resource, for a specified tenants - * - * @return a map of URI templates for the current resource, for a specified tenant - */ - protected Map getUriRegistryEntries(String tenantId, - String docType, UriTemplateFactory.UriTemplateType type) { - Map uriRegistryEntriesMap = - new HashMap(); - UriTemplateRegistryKey key; - if (Tools.isBlank(tenantId) || Tools.isBlank(docType)) { - return uriRegistryEntriesMap; - } - key = new UriTemplateRegistryKey(); - key.setTenantId(tenantId); - key.setDocType(docType); - uriRegistryEntriesMap.put(key, getUriTemplate(type)); - return uriRegistryEntriesMap; - } - - /** - * Returns a URI template of the appropriate type, populated with the - * current service name as one of its stored values. - * * - * @param type a URI template type - * @return a URI template of the appropriate type. - */ - protected StoredValuesUriTemplate getUriTemplate(UriTemplateFactory.UriTemplateType type) { - Map storedValuesMap = new HashMap(); - storedValuesMap.put(UriTemplateFactory.SERVICENAME_VAR, getServiceName()); - StoredValuesUriTemplate template = - UriTemplateFactory.getURITemplate(type, storedValuesMap); - return template; - } - - /** - * Returns a reader for reading values from tenant bindings configuration - * - * @return a tenant bindings configuration reader - */ - protected TenantBindingConfigReaderImpl getTenantBindingsReader() { - return ServiceMain.getInstance().getTenantBindingConfigReader(); - } - - - -} +/** + * 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 2010 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; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.*; +import javax.ws.rs.core.*; + +import org.collectionspace.services.client.IClientQueryParams; +import org.collectionspace.services.client.IQueryManager; +import org.collectionspace.services.client.PoxPayloadIn; +import org.collectionspace.services.client.PoxPayloadOut; +import org.collectionspace.services.common.api.RefName; +import org.collectionspace.services.common.api.Tools; +import org.collectionspace.services.common.authorityref.AuthorityRefList; +import org.collectionspace.services.common.config.ServiceConfigUtils; +import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl; +import org.collectionspace.services.common.context.RemoteServiceContext; +import org.collectionspace.services.common.context.ServiceContext; +import org.collectionspace.services.common.document.DocumentFilter; +import org.collectionspace.services.common.document.DocumentHandler; +import org.collectionspace.services.common.document.DocumentNotFoundException; +import org.collectionspace.services.common.query.QueryManager; +import org.collectionspace.services.common.vocabulary.RefNameServiceUtils; +import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthRefConfigInfo; +import org.collectionspace.services.config.ClientType; +import org.collectionspace.services.config.service.DocHandlerParams; +import org.collectionspace.services.config.service.ListResultField; +import org.collectionspace.services.config.service.ServiceBindingType; +import org.collectionspace.services.jaxb.AbstractCommonList; +import org.collectionspace.services.nuxeo.client.java.DocumentModelHandler; +import org.collectionspace.services.nuxeo.client.java.RepositoryInstanceInterface; +import org.collectionspace.services.nuxeo.util.NuxeoUtils; +import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; +import org.jboss.resteasy.util.HttpResponseCodes; +import org.nuxeo.ecm.core.api.DocumentModel; +import org.nuxeo.ecm.core.api.DocumentModelList; +import org.nuxeo.ecm.core.api.repository.RepositoryInstance; + + +/** + * $LastChangedRevision: $ + * $LastChangedDate: $ + * Author: Laramie Crocker + */ +public abstract class ResourceBase + extends AbstractMultiPartCollectionSpaceResourceImpl { + + public static final String CREATE = "create"; + public static final String READ = "get"; + public static final String UPDATE = "update"; + public static final String DELETE = "delete"; + public static final String LIST = "list"; + //FIXME retrieve client type from configuration + static ClientType CLIENT_TYPE; + + /* + * REM - 11/14/2011 - I discovered this static block of code and don't understand why it exists. However, a side-effect of this static block is that ServiceMain is trying + * to create a valid instance of entire CSpace services include an embedded Nuxeo instance. This block of code seems goofy and unnecessary and probably should be removed? + */ + static { + try { + // I put this in a try-catch static block instead of file-level static var initializer so that static methods of + // *Resource classes may be called statically from test cases. + // Without this catch, you can't even access static methods of a *Resource class for testing. + CLIENT_TYPE = ServiceMain.getInstance().getClientType(); + //System.out.println("Static initializer in ResourceBase. CLIENT_TYPE:"+CLIENT_TYPE); + } catch (Throwable t) { + System.out.println("Static initializer failed in ResourceBase because not running from deployment. OK to use Resource classes statically for tests."); + } + } + + //======================= CREATE ==================================================== + + @POST + public Response create( + @Context ResourceMap resourceMap, + @Context UriInfo ui, + String xmlPayload) { + return this.create(null, resourceMap, ui, xmlPayload); + } + + public Response create(ServiceContext parentCtx, // REM: 8/13/2012 - Some sub-classes will override this method -e.g., MediaResource does. + ResourceMap resourceMap, + UriInfo uriInfo, + String xmlPayload) { + Response result = null; + + try { + PoxPayloadIn input = new PoxPayloadIn(xmlPayload); + ServiceContext ctx = createServiceContext(input, resourceMap, uriInfo); + ctx.setResourceMap(resourceMap); + if (parentCtx != null && parentCtx.getCurrentRepositorySession() != null) { + ctx.setCurrentRepositorySession(parentCtx.getCurrentRepositorySession()); // Reuse the current repo session if one exists + } + result = create(input, ctx); + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.CREATE_FAILED); + } + + return result; + } + + protected Response create(PoxPayloadIn input, ServiceContext ctx) { + try { + DocumentHandler handler = createDocumentHandler(ctx); + UriBuilder path = UriBuilder.fromResource(this.getClass()); + return create(input, ctx, handler, path); //==> CALL implementation method, which subclasses may override. + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.CREATE_FAILED); + } + } + + /** Subclasses may override this overload, which gets called from @see #create(MultipartInput) */ + protected Response create(PoxPayloadIn input, + ServiceContext ctx, + DocumentHandler handler, + UriBuilder path) + throws Exception { + String csid = getRepositoryClient(ctx).create(ctx, handler); + path.path("" + csid); + Response response = Response.created(path.build()).build(); + return response; + } + + //======================= UPDATE ==================================================== + @PUT + @Path("{csid}") + public byte[] update(@Context ResourceMap resourceMap, + @Context UriInfo uriInfo, + @PathParam("csid") String csid, + String xmlPayload) { + return this.update(null, resourceMap, uriInfo, csid, xmlPayload); + } + + public byte[] update(ServiceContext parentCtx, // REM: 8/13/2012 - Some sub-classes will override this method -e.g., MediaResource does. + @Context ResourceMap resourceMap, + @Context UriInfo uriInfo, + @PathParam("csid") String csid, + String xmlPayload) { + PoxPayloadOut result = null; + ensureCSID(csid, UPDATE); + try { + PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload); + ServiceContext ctx = createServiceContext(theUpdate, uriInfo); + ctx.setResourceMap(resourceMap); + if (parentCtx != null && parentCtx.getCurrentRepositorySession() != null) { + ctx.setCurrentRepositorySession(parentCtx.getCurrentRepositorySession()); // Reuse the current repo session if one exists + } + result = update(csid, theUpdate, ctx); //==> CALL implementation method, which subclasses may override. + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.UPDATE_FAILED, csid); + } + return result.getBytes(); + } + + /** Subclasses may override this overload, which gets called from #udpate(String,MultipartInput) */ + protected PoxPayloadOut update(String csid, + PoxPayloadIn theUpdate, + ServiceContext ctx) + throws Exception { + DocumentHandler handler = createDocumentHandler(ctx); + getRepositoryClient(ctx).update(ctx, csid, handler); + return ctx.getOutput(); + } + + /** Subclasses may override this overload, which gets called from #udpate(String,MultipartInput) */ + protected PoxPayloadOut update(String csid, + MultipartInput theUpdate, + ServiceContext ctx, + DocumentHandler handler) + throws Exception { + getRepositoryClient(ctx).update(ctx, csid, handler); + return ctx.getOutput(); + } + + //======================= DELETE ==================================================== + @DELETE + @Path("{csid}") + public Response delete(@PathParam("csid") String csid) { + ensureCSID(csid, DELETE); + try { + ServiceContext ctx = createServiceContext(); + return delete(ctx, csid); //==> CALL implementation method, which subclasses may override. + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid); + } + } + + /** subclasses may override this method, which is called from #delete(String) + * which handles setup of ServiceContext, and does Exception handling. */ + protected Response delete(ServiceContext ctx, String csid) + throws Exception { + DocumentHandler handler = createDocumentHandler(ctx); + getRepositoryClient(ctx).delete(ctx, csid, handler); + return Response.status(HttpResponseCodes.SC_OK).build(); + } + + public Response deleteWithParentCtx(ServiceContext parentCtx, + String csid) + throws Exception { + ensureCSID(csid, DELETE); + try { + ServiceContext ctx = createServiceContext(); + if (parentCtx != null && parentCtx.getCurrentRepositorySession() != null) { + ctx.setCurrentRepositorySession(parentCtx.getCurrentRepositorySession()); // reuse the repo session if one exists + } + return delete(ctx, csid); //==> CALL implementation method, which subclasses may override. + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid); + } + } + + //======================= GET ==================================================== + @GET + @Path("{csid}") + public byte[] get( + @Context Request request, + @Context UriInfo uriInfo, + @PathParam("csid") String csid) { + PoxPayloadOut result = null; + ensureCSID(csid, READ); + try { + RemoteServiceContext ctx = (RemoteServiceContext) createServiceContext(uriInfo); + result = get(csid, ctx);// ==> CALL implementation method, which subclasses may override. + if (result == null) { + Response response = Response.status(Response.Status.NOT_FOUND).entity( + ServiceMessages.READ_FAILED + ServiceMessages.resourceNotFoundMsg(csid)).type("text/plain").build(); + throw new CSWebApplicationException(response); + } + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.READ_FAILED, csid); + } + + return result.getBytes(); + } + + protected PoxPayloadOut get(@PathParam("csid") String csid, + ServiceContext ctx) throws Exception { + PoxPayloadOut result = null; + + ensureCSID(csid, READ); + DocumentHandler handler = createDocumentHandler(ctx); + result = get(csid, ctx, handler); + if (result == null) { + String msg = "Could not find document with id = " + csid; + if (logger.isErrorEnabled() == true) { + logger.error(msg); + } + throw new DocumentNotFoundException(msg); + } + + return result; + } + + /** subclasses may override this method, which is called from #get(String) + * which handles setup of ServiceContext and DocumentHandler, and Exception handling.*/ + protected PoxPayloadOut get(String csid, + ServiceContext ctx, + DocumentHandler handler) + throws Exception { + getRepositoryClient(ctx).get(ctx, csid, handler); + return ctx.getOutput(); + } + + protected boolean isGetAllRequest(MultivaluedMap queryParams) { + boolean result = false; + + String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW); + String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS); + String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM); + + if (Tools.isBlank(keywords) && Tools.isBlank(advancedSearch) && Tools.isBlank(partialTerm)) { + result = true; + } + + return result; + } + + //======================= GET without csid. List, search, etc. ===================================== + @GET + public AbstractCommonList getList(@Context UriInfo ui) { + AbstractCommonList list = null; + + MultivaluedMap queryParams = ui.getQueryParameters(); + if (isGetAllRequest(queryParams) == false) { + String orderBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM); + String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW); + String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS); + String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM); + list = search(ui, orderBy, keywords, advancedSearch, partialTerm); + } else { + list = getCommonList(ui); + } + + return list; + } + + protected AbstractCommonList getCommonList(UriInfo uriInfo) { + try { + ServiceContext ctx = createServiceContext(uriInfo); + DocumentHandler handler = createDocumentHandler(ctx); + getRepositoryClient(ctx).getFiltered(ctx, handler); + AbstractCommonList list = (AbstractCommonList) handler.getCommonPartList(); + return list; + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.LIST_FAILED); + } + } + + protected AbstractCommonList finish_getList(ServiceContext ctx, DocumentHandler handler) { + try { + getRepositoryClient(ctx).getFiltered(ctx, handler); // REM - Side effect of this call sets the handler's common part list value + return (AbstractCommonList) handler.getCommonPartList(); + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.LIST_FAILED); + } + } + + protected AbstractCommonList search( + ServiceContext ctx, + DocumentHandler handler, + UriInfo ui, + String orderBy, + String keywords, + String advancedSearch, + String partialTerm) throws Exception { + DocumentFilter docFilter = handler.getDocumentFilter(); + if (orderBy == null || orderBy.isEmpty()) { + String orderByField = getOrderByField(ctx); + docFilter.setOrderByClause(orderByField); + } + + // + // NOTE: Partial-term (PT) queries are mutually exclusive to keyword and + // partial-term queries trump keyword queries. + // + if (partialTerm != null && !partialTerm.isEmpty()) { + String partialTermMatchField = getPartialTermMatchField(ctx); + String ptClause = QueryManager.createWhereClauseForPartialMatch(ctx, partialTermMatchField, + partialTerm); + docFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND); + } else if (keywords != null && !keywords.isEmpty()) { + String whereClause = QueryManager.createWhereClauseFromKeywords(keywords); + if (Tools.isEmpty(whereClause) == false) { + docFilter.appendWhereClause(whereClause, IQueryManager.SEARCH_QUALIFIER_AND); + if (logger.isDebugEnabled()) { + logger.debug("The WHERE clause is: " + docFilter.getWhereClause()); + } + } else { + if (logger.isWarnEnabled()) { + logger.warn("The WHERE clause is empty for keywords: ["+keywords+"]"); + } + } + } + + // + // Add an advance search clause if one was specified -even if PT search was requested? + // + if (advancedSearch != null && !advancedSearch.isEmpty()) { + String whereClause = QueryManager.createWhereClauseFromAdvancedSearch(advancedSearch); + docFilter.appendWhereClause(whereClause, IQueryManager.SEARCH_QUALIFIER_AND); + if (logger.isDebugEnabled()) { + logger.debug("The WHERE clause is: " + docFilter.getWhereClause()); + } + } + + getRepositoryClient(ctx).getFiltered(ctx, handler); + return (AbstractCommonList) handler.getCommonPartList(); + } + + private AbstractCommonList search( + UriInfo uriInfo, + String orderBy, + String keywords, + String advancedSearch, + String partialTerm) { + AbstractCommonList result = null; + + ServiceContext ctx; + try { + ctx = createServiceContext(uriInfo); + DocumentHandler handler = createDocumentHandler(ctx); + result = search(ctx, handler, uriInfo, orderBy, keywords, advancedSearch, partialTerm); + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.SEARCH_FAILED); + } + + return result; + } + + //FIXME: REM - This should not be @Deprecated since we may want to implement this -it has been on the wish list. + @Deprecated + public AbstractCommonList getList(List csidList) { + try { + ServiceContext ctx = createServiceContext(); + DocumentHandler handler = createDocumentHandler(ctx); + getRepositoryClient(ctx).get(ctx, csidList, handler); + return (AbstractCommonList) handler.getCommonPartList(); + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.LIST_FAILED); + } + } + + //======================== GET : getAuthorityRefs ======================================== + @GET + @Path("{csid}/authorityrefs") + @Produces("application/xml") + public AuthorityRefList getAuthorityRefs( + @PathParam("csid") String csid, + @Context UriInfo uriInfo) { + AuthorityRefList authRefList = null; + try { + ServiceContext ctx = createServiceContext(uriInfo); + DocumentModelHandler handler = (DocumentModelHandler) createDocumentHandler(ctx); + List authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx); + authRefList = handler.getAuthorityRefs(csid, authRefsInfo); + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.AUTH_REFS_FAILED, csid); + } + return authRefList; + } + + //======================== UTILITY : getDocModelForRefName ======================================== + + /* + * Used get the order by field for list results if one is not specified with an HTTP query param. + * + * (non-Javadoc) + * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#getOrderByField() + */ + @Override + protected String getOrderByField(ServiceContext ctx) { + String result = null; + + // We only want to use the partial term field to order the results if a PT query param exists + String partialTerm = ctx.getQueryParams().getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM); + if (Tools.notBlank(partialTerm) == true) { + DocHandlerParams.Params params = null; + try { + result = getPartialTermMatchField(ctx); + if (result == null) { + throw new Exception(); + } + } catch (Exception e) { + if (logger.isWarnEnabled()) { + logger.warn(String.format("Call failed to getOrderByField() for class %s", this.getClass().getName())); + } + } + } + + return result; + } + + @Override + protected String getPartialTermMatchField(ServiceContext ctx) { + String result = null; + + DocHandlerParams.Params params = null; + try { + params = ServiceConfigUtils.getDocHandlerParams(ctx); + ListResultField field = params.getRefnameDisplayNameField(); + String schema = field.getSchema(); + if (schema == null || schema.trim().isEmpty()) { + schema = ctx.getCommonPartLabel(); + } + result = schema + ":" + field.getXpath(); + } catch (Exception e) { + if (logger.isWarnEnabled()) { + logger.warn(String.format("Call failed to getPartialTermMatchField() for class %s", this.getClass().getName())); + } + } + + return result; + } + + /* + * ResourceBase create and update calls will set the resourceMap into the service context + * for all inheriting resource classes. Just use ServiceContext.getResourceMap() to get + * the map, and pass it in. + */ + public static DocumentModel getDocModelForRefName(RepositoryInstanceInterface repoSession, String refName, ResourceMap resourceMap) + throws Exception, DocumentNotFoundException { + RefName.AuthorityItem item = RefName.AuthorityItem.parse(refName); + if(item != null) { + ResourceBase resource = resourceMap.get(item.inAuthority.resource); + return resource.getDocModelForAuthorityItem(repoSession, item); + } + RefName.Authority authority = RefName.Authority.parse(refName); + // Handle case of objects refNames, which must be csid based. + if(authority != null && !Tools.isEmpty(authority.csid)) { + ResourceBase resource = resourceMap.get(authority.resource); + // Ensure we have the right context. + ServiceContext ctx = + resource.createServiceContext(authority.resource); + // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here! + DocumentModel docModel = NuxeoUtils.getDocFromCsid(ctx, repoSession, authority.csid); + return docModel; + } + return null; + } + + // THis is ugly, but prevents us parsing the refName twice. Once we make refName a little more + // general, and less Authority(Item) specific, this will look better. + public DocumentModel getDocModelForAuthorityItem(RepositoryInstanceInterface repoSession, RefName.AuthorityItem item) + throws Exception, DocumentNotFoundException { + logger.warn("Default (ResourceBase) getDocModelForAuthorityItem called - should not happen!"); + return null; + } + + public DocumentModel getDocModelForRefName(RepositoryInstanceInterface repoSession, String refName) + throws Exception, DocumentNotFoundException { + return getDocModelForAuthorityItem(repoSession, RefName.AuthorityItem.parse(refName)); + } + + protected String getDocType(String tenantId) { + return getDocType(tenantId, getServiceName()); + } + + /** + * Returns the Nuxeo document type associated with a specified service, within a specified tenant. + * + * @param tenantId a tenant ID + * @param serviceName a service name + * @return the Nuxeo document type associated with that service and tenant. + */ + // FIXME: This method may properly belong in a different services package or class. + // Also, we need to check for any existing methods that may duplicate this one. + protected String getDocType(String tenantId, String serviceName) { + String docType = ""; + if (Tools.isBlank(tenantId)) { + return docType; + } + ServiceBindingType sb = getTenantBindingsReader().getServiceBinding(tenantId, serviceName); + if (sb == null) { + return docType; + } + docType = sb.getObject().getName(); // Reads the Nuxeo Document Type from tenant bindings configuration + return docType; + } + + /** + * Returns a UriRegistry entry: a map of tenant-qualified URI templates + * for the current resource, for all tenants + * + * @return a map of URI templates for the current resource, for all tenants + */ + public Map getUriRegistryEntries() { + Map uriRegistryEntriesMap = + new HashMap(); + List tenantIds = getTenantBindingsReader().getTenantIds(); + for (String tenantId : tenantIds) { + uriRegistryEntriesMap.putAll(getUriRegistryEntries(tenantId, getDocType(tenantId), UriTemplateFactory.RESOURCE)); + } + return uriRegistryEntriesMap; + } + + /** + * Returns a UriRegistry entry: a map of tenant-qualified URI templates + * for the current resource, for a specified tenants + * + * @return a map of URI templates for the current resource, for a specified tenant + */ + protected Map getUriRegistryEntries(String tenantId, + String docType, UriTemplateFactory.UriTemplateType type) { + Map uriRegistryEntriesMap = + new HashMap(); + UriTemplateRegistryKey key; + if (Tools.isBlank(tenantId) || Tools.isBlank(docType)) { + return uriRegistryEntriesMap; + } + key = new UriTemplateRegistryKey(); + key.setTenantId(tenantId); + key.setDocType(docType); + uriRegistryEntriesMap.put(key, getUriTemplate(type)); + return uriRegistryEntriesMap; + } + + /** + * Returns a URI template of the appropriate type, populated with the + * current service name as one of its stored values. + * * + * @param type a URI template type + * @return a URI template of the appropriate type. + */ + protected StoredValuesUriTemplate getUriTemplate(UriTemplateFactory.UriTemplateType type) { + Map storedValuesMap = new HashMap(); + storedValuesMap.put(UriTemplateFactory.SERVICENAME_VAR, getServiceName()); + StoredValuesUriTemplate template = + UriTemplateFactory.getURITemplate(type, storedValuesMap); + return template; + } + + /** + * Returns a reader for reading values from tenant bindings configuration + * + * @return a tenant bindings configuration reader + */ + protected TenantBindingConfigReaderImpl getTenantBindingsReader() { + return ServiceMain.getInstance().getTenantBindingConfigReader(); + } + + + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/ResourceMap.java b/services/common/src/main/java/org/collectionspace/services/common/ResourceMap.java index eecf51c6c..d1d990cb3 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/ResourceMap.java +++ b/services/common/src/main/java/org/collectionspace/services/common/ResourceMap.java @@ -1,10 +1,10 @@ -package org.collectionspace.services.common; - -import java.util.Map; - -/* - * Maps service names to Resource instances. Use the Service Client Class to get the service name. - */ -public interface ResourceMap extends Map { - -} +package org.collectionspace.services.common; + +import java.util.Map; + +/* + * Maps service names to Resource instances. Use the Service Client Class to get the service name. + */ +public interface ResourceMap extends Map { + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/ResourceMapHolder.java b/services/common/src/main/java/org/collectionspace/services/common/ResourceMapHolder.java index 7bb298669..950ec7c3a 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/ResourceMapHolder.java +++ b/services/common/src/main/java/org/collectionspace/services/common/ResourceMapHolder.java @@ -1,5 +1,5 @@ -package org.collectionspace.services.common; - -public interface ResourceMapHolder { - public ResourceMap getResourceMap(); -} +package org.collectionspace.services.common; + +public interface ResourceMapHolder { + public ResourceMap getResourceMap(); +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/ResourceMapImpl.java b/services/common/src/main/java/org/collectionspace/services/common/ResourceMapImpl.java index 4845d9971..a49b6865b 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/ResourceMapImpl.java +++ b/services/common/src/main/java/org/collectionspace/services/common/ResourceMapImpl.java @@ -1,7 +1,7 @@ -package org.collectionspace.services.common; - -import java.util.HashMap; - -public class ResourceMapImpl extends HashMap implements ResourceMap { - -} +package org.collectionspace.services.common; + +import java.util.HashMap; + +public class ResourceMapImpl extends HashMap implements ResourceMap { + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/ServiceMain.java b/services/common/src/main/java/org/collectionspace/services/common/ServiceMain.java index b38e41d3b..db2ee3fbd 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/ServiceMain.java +++ b/services/common/src/main/java/org/collectionspace/services/common/ServiceMain.java @@ -1,990 +1,990 @@ -/** - * Copyright 2009-2010 University of California at Berkeley - */ -package org.collectionspace.services.common; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.*; - -import javax.naming.NamingException; -import javax.servlet.ServletContext; -import javax.sql.DataSource; - -import org.apache.tomcat.dbcp.dbcp.BasicDataSource; -import org.collectionspace.authentication.AuthN; -import org.collectionspace.services.common.api.JEEServerDeployment; -import org.collectionspace.services.common.api.FileTools; -import org.collectionspace.services.common.api.Tools; -import org.collectionspace.services.common.authorization_mgt.AuthorizationCommon; -import org.collectionspace.services.common.config.ConfigReader; -import org.collectionspace.services.common.config.ConfigUtils; -import org.collectionspace.services.common.config.ServicesConfigReaderImpl; -import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl; -import org.collectionspace.services.common.context.ServiceBindingUtils; -import org.collectionspace.services.common.init.AddIndices; -import org.collectionspace.services.config.service.InitHandler.Params.Field; -import org.collectionspace.services.common.init.IInitHandler; -import org.collectionspace.services.common.storage.DatabaseProductType; -import org.collectionspace.services.common.storage.JDBCTools; -import org.collectionspace.services.config.ClientType; -import org.collectionspace.services.config.ServiceConfig; -import org.collectionspace.services.config.service.ServiceBindingType; -import org.collectionspace.services.config.tenant.RepositoryDomainType; -import org.collectionspace.services.config.tenant.TenantBindingType; -import org.collectionspace.services.config.types.PropertyItemType; -import org.collectionspace.services.config.types.PropertyType; -import org.collectionspace.services.nuxeo.client.java.NuxeoConnectorEmbedded; -import org.collectionspace.services.nuxeo.client.java.TenantRepository; -import org.jboss.resteasy.spi.ResteasyProviderFactory; -import org.dom4j.Document; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Main class for Services layer. It reads configuration and performs service - * level initialization. It is a singleton. - * @author - */ -public class ServiceMain { - - final Logger logger = LoggerFactory.getLogger(ServiceMain.class); - /** - * volatile is used here to assume about ordering (post JDK 1.5) - */ - private static volatile ServiceMain instance = null; - private static volatile boolean initFailed = false; - - private static final String SERVER_HOME_PROPERTY = "catalina.home"; - private static final boolean USE_APP_GENERATED_CONFIG = true; - - private static ServletContext servletContext = null; - - private NuxeoConnectorEmbedded nuxeoConnector; - private String serverRootDir = null; - private ServicesConfigReaderImpl servicesConfigReader; - private TenantBindingConfigReaderImpl tenantBindingConfigReader; - private UriTemplateRegistry uriTemplateRegistry = new UriTemplateRegistry(); - - - private static final String COMPONENT_EXTENSION_XPATH = "/component/extension[@point='%s']"; - private static final String REPOSITORY_EXTENSION_POINT_XPATH = - String.format(COMPONENT_EXTENSION_XPATH, "repository"); - private static final String REPOSITORIES_EXTENSION_POINT_XPATH = - String.format(COMPONENT_EXTENSION_XPATH, "repositories"); - - private static final String DROP_DATABASE_SQL_CMD = "DROP DATABASE"; - private static final String DROP_DATABASE_IF_EXISTS_SQL_CMD = DROP_DATABASE_SQL_CMD + " IF EXISTS %s;"; - private static final String DROP_USER_SQL_CMD = "DROP USER"; - private static final String DROP_USER_IF_EXISTS_SQL_CMD = DROP_USER_SQL_CMD + " IF EXISTS %s;"; - private static final String DROP_OBJECTS_SQL_COMMENT = "-- drop all the objects before dropping roles"; - - - private ServiceMain() { - //empty - } - - /* - * - * Set this singletons ServletContext without any call to initialize - */ - private static void setServletContext(ServletContext servletContext) { - if (servletContext != null) { - synchronized (ServiceMain.class) { - ServiceMain.servletContext = servletContext; - } - } - } - - public String getCspaceDatabaseName() { - return getServiceConfig().getDbCspaceName(); - } - - public boolean inServletContext() { - return ServiceMain.servletContext != null; - } - - public static ServiceMain getInstance(ServletContext servletContext) { - setServletContext(servletContext); - return ServiceMain.getInstance(); - } - - /** - * getInstance returns the ServiceMain singleton instance after proper - * initialization in a thread-safe manner - * @return - */ - public static ServiceMain getInstance() { - if (instance == null && initFailed == false) { - synchronized (ServiceMain.class) { - if (instance == null && initFailed == false) { - ServiceMain newInstance = new ServiceMain(); - try { - //assume the worse - initFailed = true; - newInstance.initialize(); - //celebrate success - initFailed = false; - } catch (Exception e) { - instance = null; - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } else { - throw new RuntimeException(e); - } - } - instance = newInstance; - } - } - } - - if (instance == null) { - throw new RuntimeException("Could not initialize the CollectionSpace services. Please see the CollectionSpace services log file(s) for details."); - } - - return instance; - } - - private void initialize() throws Exception { - // set our root directory - setServerRootDir(); - - // read in and set our Services config - readAndSetServicesConfig(); - - // Set our AuthN's datasource to for the cspaceDataSource - AuthN.setDataSource(JDBCTools.getDataSource(JDBCTools.CSPACE_DATASOURCE_NAME)); - - // In each tenant, set properties that don't already have values - // to their default values. - propagateConfiguredProperties(); - - // Create or update Nuxeo's per-repository configuration files. - createOrUpdateNuxeoRepositoryConfigFiles(); - - // Create the Nuxeo-managed databases, along with the requisite - // access rights to each. - HashSet dbsCheckedOrCreated = createNuxeoDatabases(); - - // Update the SQL script that drops databases and users, - // to include DROP statements for each of the Nuxeo-managed - // database names and for each relevant datasource user. - String[] dataSourceNames = {JDBCTools.NUXEO_DATASOURCE_NAME, JDBCTools.NUXEO_READER_DATASOURCE_NAME}; - updateInitializationScript(getNuxeoDatabasesInitScriptFilename(), - dbsCheckedOrCreated, dataSourceNames); - - // - // Start up and initialize our embedded Nuxeo instance. - // - if (getClientType().equals(ClientType.JAVA)) { - nuxeoConnector = NuxeoConnectorEmbedded.getInstance(); - nuxeoConnector.initialize( - getServerRootDir(), - getServicesConfigReader().getConfiguration().getRepositoryClient(), - ServiceMain.servletContext); - } else { - // - // Exit if we don't have the correct/known client type - // - throw new RuntimeException("Unknown CollectionSpace services client type: " + getClientType()); - } - // - // Create all the default user accounts and permissions. Since some of our "cspace" database config files - // for Spring need to be created at build time, the "cspace" database already will be suffixed with the - // correct 'cspaceInstanceId' so we don't need to pass it to the JDBCTools methods. - // - try { - AuthorizationCommon.createDefaultWorkflowPermissions(tenantBindingConfigReader); - String cspaceDatabaseName = getCspaceDatabaseName(); - DatabaseProductType databaseProductType = JDBCTools.getDatabaseProductType(JDBCTools.CSPACE_DATASOURCE_NAME, - cspaceDatabaseName); - AuthorizationCommon.createDefaultAccounts(tenantBindingConfigReader, databaseProductType, - cspaceDatabaseName); - } catch (Exception e) { - logger.error("Default accounts and permissions setup failed with exception(s): " + - e.getLocalizedMessage(), e); - throw e; - } - - /* - * This might be useful for something, but the reader grants are better handled in the ReportPostInitHandler. - try { - handlePostNuxeoInitDBTasks(); - } catch(Throwable e) { - logger.error("handlePostNuxeoInitDBTasks failed with exception(s): " + e.getLocalizedMessage(), e); - } - */ - } - - /** - * release releases all resources occupied by service layer infrastructure - * but not necessarily those occupied by individual services - */ - public void release() { - try { - if (nuxeoConnector != null) { - nuxeoConnector.release(); - } - instance = null; - } catch (Exception e) { - e.printStackTrace(); - //gobble it - } - } - - private void readAndSetServicesConfig() throws Exception { - //read service config - servicesConfigReader = new ServicesConfigReaderImpl(getServerRootDir()); - servicesConfigReader.read(USE_APP_GENERATED_CONFIG); - - Boolean useAppGeneratedBindings = servicesConfigReader.getConfiguration().isUseAppGeneratedTenantBindings(); - tenantBindingConfigReader = new TenantBindingConfigReaderImpl(getServerRootDir()); - tenantBindingConfigReader.read(useAppGeneratedBindings); - } - - private void propagateConfiguredProperties() { - List repoPropListHolder = - servicesConfigReader.getConfiguration().getRepositoryClient().getProperties(); - if (repoPropListHolder != null && !repoPropListHolder.isEmpty()) { - List propList = repoPropListHolder.get(0).getItem(); - if (propList != null && !propList.isEmpty()) { - tenantBindingConfigReader.setDefaultPropertiesOnTenants(propList, true); - } - } - } - - /** - * Create required indexes (aka indices) in database tables not associated - * with any specific tenant. - * - * We need to loop over each repository/db declared in the tenant bindings. - * The assumption here is that each repo/db is a Nuxeo repo/DB. - * - * @throws Exception - */ - void createRequiredIndices() throws Exception { - Hashtable tenantBindingTypeMap = tenantBindingConfigReader.getTenantBindings(); - - // - //Loop through all tenants in tenant-bindings.xml - // - String cspaceInstanceId = getCspaceInstanceId(); - for (TenantBindingType tbt : tenantBindingTypeMap.values()) { - List repositoryNameList = ConfigUtils.getRepositoryNameList(tbt); - if (repositoryNameList != null && repositoryNameList.isEmpty() == false) { - // - // Loop through each repo/DB defined in a tenant bindings file - // - for (String repositoryName : repositoryNameList) { - // Define a set of columns (fields) and their associated - // tables, on which database indexes should always be created - final String COLLECTIONSPACE_CORE_TABLE_NAME = "collectionspace_core"; - final String NUXEO_FULLTEXT_TABLE_NAME = "fulltext"; - final String NUXEO_HIERARCHY_TABLE_NAME = "hierarchy"; - - Map> fieldsToIndex = new HashMap>(); - fieldsToIndex.put(1, new ArrayList(Arrays.asList(COLLECTIONSPACE_CORE_TABLE_NAME, "tenantid"))); - fieldsToIndex.put(2, new ArrayList(Arrays.asList(COLLECTIONSPACE_CORE_TABLE_NAME, "updatedat"))); - fieldsToIndex.put(3, new ArrayList(Arrays.asList(NUXEO_FULLTEXT_TABLE_NAME, "jobid"))); - fieldsToIndex.put(4, new ArrayList(Arrays.asList(NUXEO_HIERARCHY_TABLE_NAME, "name"))); - - // Invoke existing post-init code to create these indexes, - // sending in the set of values above, in contrast to - // drawing these values from per-tenant configuration. -// DataSource dataSource = JDBCTools.getDataSource(JDBCTools.NUXEO_DATASOURCE_NAME); - AddIndices addindices = new AddIndices(); - List fields = new ArrayList(); - for (Map.Entry> entry : fieldsToIndex.entrySet()) { - Field field = new Field(); - field.setTable(entry.getValue().get(0)); // Table name from List - // item 0 - field.setCol(entry.getValue().get(1)); // Column name from List item - // 1 - fields.add(field); - } - addindices.onRepositoryInitialized(JDBCTools.NUXEO_DATASOURCE_NAME, repositoryName, cspaceInstanceId, - null, fields, null); - } - } else { - String errMsg = "repositoryNameList was empty or null."; - logger.error(errMsg); - throw new Exception(errMsg); - } - } - } - - public void firePostInitHandlers() throws Exception { - Hashtable tenantBindingTypeMap = tenantBindingConfigReader.getTenantBindings(); - // - //Loop through all tenants in tenant-bindings.xml - // - String cspaceInstanceId = getCspaceInstanceId(); - for (TenantBindingType tbt : tenantBindingTypeMap.values()) { - // - //Loop through all the services in this tenant - // - List sbtList = tbt.getServiceBindings(); - for (ServiceBindingType sbt: sbtList) { - String repositoryName = null; - if (sbt.getType().equalsIgnoreCase(ServiceBindingUtils.SERVICE_TYPE_SECURITY) == false) { - repositoryName = ConfigUtils.getRepositoryName(tbt, sbt.getRepositoryDomain()); // Each service can have a different repo domain - } - //Get the list of InitHandler elements, extract the first one (only one supported right now) and fire it using reflection. - List list = sbt.getInitHandler(); - if (list != null && list.size() > 0) { - org.collectionspace.services.config.service.InitHandler handlerType = list.get(0); // REM - 12/2012: We might want to think about supporting multiple post-init handlers - String initHandlerClassname = handlerType.getClassname(); - if (Tools.isEmpty(initHandlerClassname)) { - continue; - } - if (logger.isInfoEnabled()) { - logger.info(String.format("Firing post-init handler %s ...", initHandlerClassname)); - } - - List - fields = handlerType.getParams().getField(); - - List - props = handlerType.getParams().getProperty(); - - //org.collectionspace.services.common.service.InitHandler.Fields ft = handlerType.getFields(); - //List fields = ft.getField(); - Object o = instantiate(initHandlerClassname, IInitHandler.class); - if (o != null && o instanceof IInitHandler){ - IInitHandler handler = (IInitHandler)o; - handler.onRepositoryInitialized(JDBCTools.NUXEO_DATASOURCE_NAME, repositoryName, cspaceInstanceId, - sbt, fields, props); - //The InitHandler may be the default one, - // or specialized classes which still implement this interface and are registered in tenant-bindings.xml. - } - } - } - } - } - - /* - * A generic mechanism for instantiating a instance/object from a class name. - */ - public Object instantiate(String clazz, Class castTo) throws Exception { - ClassLoader tccl = Thread.currentThread().getContextClassLoader(); - clazz = clazz.trim(); - Class c = tccl.loadClass(clazz); - if (castTo.isAssignableFrom(c)) { - return c.newInstance(); - } - return null; - } - - void retrieveAllWorkspaceIds() throws Exception { - //all configs are read, connector is initialized, retrieve workspaceids - Hashtable tenantBindings = - tenantBindingConfigReader.getTenantBindings(); - TenantRepository.get().setup(tenantBindings); - } - - /** - * getWorkspaceId returns workspace id for given tenant and service name - * @param tenantId - * @param serviceName - * @return - */ - public String getWorkspaceId(String tenantId, String serviceName) { - return TenantRepository.get().getWorkspaceId(tenantId, serviceName); - } - - /** - * @return the nuxeoConnector - */ - public NuxeoConnectorEmbedded getNuxeoConnector() { - return nuxeoConnector; - } - - /** - * @return the serverRootDir - */ - public String getServerRootDir() { - return serverRootDir; - } - - private String getCspaceServicesConfigDir() { - return getServerRootDir() + File.separator + JEEServerDeployment.CSPACE_CONFIG_SERVICES_DIR_PATH; - } - - private String getNuxeoConfigDir() { - return getServerRootDir() + File.separator + JEEServerDeployment.NUXEO_SERVER_CONFIG_DIR; - } - - private String getNuxeoProtoConfigFilename() { - return JEEServerDeployment.NUXEO_PROTOTYPE_CONFIG_FILENAME; - } - - private String getNuxeoConfigFilename(String reponame) { - return reponame + JEEServerDeployment.NUXEO_REPO_CONFIG_FILENAME_SUFFIX; - } - - private String getDatabaseScriptsPath() { - DatabaseProductType dbType; - String databaseProductName; - String databaseScriptsPath = ""; - try { - // This call makes a connection to the database server, using a default database - // name and retrieves the database product name from metadata provided by the server. - dbType = JDBCTools.getDatabaseProductType(JDBCTools.CSADMIN_DATASOURCE_NAME, - getServiceConfig().getDbCsadminName()); - databaseProductName = dbType.getName(); - databaseScriptsPath = getServerRootDir() + File.separator - + JEEServerDeployment.DATABASE_SCRIPTS_DIR_PATH + File.separator + databaseProductName; - // An Exception occurring here will cause an empty path to be returned, ultimately - // resulting in a failure to find the Nuxeo databases initialization script file. - } catch (Exception e) { - logger.warn(String.format("Could not get database product type: %s", e.getMessage())); - } - return databaseScriptsPath; - - } - - /** - * Returns the full filesystem path to the Nuxeo databases initialization script file. - * - * @return the full path to the Nuxeo databases initialization script file. - * Returns an empty String for the path if the database scripts path is null or empty. - */ - private String getNuxeoDatabasesInitScriptFilename() { - return Tools.notBlank(getDatabaseScriptsPath()) ? - getDatabaseScriptsPath() + File.separator + JEEServerDeployment.NUXEO_DB_INIT_SCRIPT_FILENAME : ""; - } - - /** - * @return the server resources path - */ - public String getServerResourcesPath() { - return getServerRootDir() + File.separator + ConfigReader.RESOURCES_DIR_PATH + File.separator; - } - - public InputStream getResourceAsStream(String resourceName) throws FileNotFoundException { - InputStream result = new FileInputStream(new File(getServerResourcesPath() + resourceName)); - return result; - } - - public String getCspaceInstanceId() { - String result = getServiceConfig().getCspaceInstanceId(); - - if (result == null || result.trim().isEmpty()) { - result = ""; //empty string - } - - return result; - } - /* - * Look through the tenant bindings and create the required Nuxeo databases -each tenant can declare - * their own Nuxeo repository/database. - * Get the NuxeoDS info and create the necessary databases. - * Consider the tenant bindings to find and get the data sources for each tenant. - * There may be only one, one per tenant, or something in between. - * - */ - private HashSet createNuxeoDatabases() throws Exception { - String nuxeoUser = getBasicDataSourceUsername(JDBCTools.NUXEO_DATASOURCE_NAME); - String nuxeoPW = getBasicDataSourcePassword(JDBCTools.NUXEO_DATASOURCE_NAME); - - String readerUser = getBasicDataSourceUsername(JDBCTools.NUXEO_READER_DATASOURCE_NAME); - String readerPW = getBasicDataSourcePassword(JDBCTools.NUXEO_READER_DATASOURCE_NAME); - - DatabaseProductType dbType = JDBCTools.getDatabaseProductType(JDBCTools.CSADMIN_DATASOURCE_NAME, - getServiceConfig().getDbCsadminName()); - - Hashtable tenantBindings = - tenantBindingConfigReader.getTenantBindings(); - HashSet nuxeoDBsChecked = new HashSet(); - - // First check and create the roles as needed. (nuxeo and reader) - for (TenantBindingType tenantBinding : tenantBindings.values()) { - String tId = tenantBinding.getId(); - String tName = tenantBinding.getName(); - List repoDomainList = tenantBinding.getRepositoryDomain(); - for (RepositoryDomainType repoDomain : repoDomainList) { - String repoDomainName = repoDomain.getName(); - String repositoryName = repoDomain.getRepositoryName(); - String cspaceInstanceId = getCspaceInstanceId(); - String dbName = JDBCTools.getDatabaseName(repositoryName, cspaceInstanceId); - if (nuxeoDBsChecked.contains(dbName)) { - if (logger.isDebugEnabled()) { - logger.debug("Another user of db: " + dbName + ": Repo: " + repoDomainName - + " and tenant: " + tName + " (id:" + tId + ")"); - } - } else { - if (logger.isDebugEnabled()) { - logger.debug("Need to prepare db: " + dbName + " for Repo: " + repoDomainName - + " and tenant: " + tName + " (id:" + tId + ")"); - } - boolean dbExists = JDBCTools.hasDatabase(dbType, dbName); - if (dbExists) { - if (logger.isDebugEnabled()) { - logger.debug("Database: " + dbName + " already exists."); - } - } else { - // Create the user as needed - JDBCTools.createNewDatabaseUser(JDBCTools.CSADMIN_DATASOURCE_NAME, repositoryName, cspaceInstanceId, dbType, nuxeoUser, nuxeoPW); - if (readerUser != null) { - JDBCTools.createNewDatabaseUser(JDBCTools.CSADMIN_DATASOURCE_NAME, repositoryName, cspaceInstanceId, dbType, readerUser, readerPW); - } - // Create the database - createDatabaseWithRights(dbType, dbName, nuxeoUser, nuxeoPW, readerUser, readerPW); - } - nuxeoDBsChecked.add(dbName); - } - } // Loop on repos for tenant - } // Loop on tenants - - return nuxeoDBsChecked; - - } - - /** - * Creates a Nuxeo-managed database, sets up an owner for that - * database, and adds (at least) connection privileges to a reader - * of that database. - * - * @param conn - * @param dbType - * @param dbName - * @param ownerName - * @param ownerPW - * @param readerName - * @param readerPW - * @throws Exception - */ - private void createDatabaseWithRights(DatabaseProductType dbType, String dbName, String ownerName, - String ownerPW, String readerName, String readerPW) throws Exception { - Connection conn = null; - Statement stmt = null; - try { - DataSource csadminDataSource = JDBCTools.getDataSource(JDBCTools.CSADMIN_DATASOURCE_NAME); - conn = csadminDataSource.getConnection(); - stmt = conn.createStatement(); - if (dbType == DatabaseProductType.POSTGRESQL) { - // PostgreSQL does not need passwords in grant statements. - String sql = "CREATE DATABASE " + dbName + " ENCODING 'UTF8' OWNER " + ownerName; - stmt.executeUpdate(sql); - if (logger.isDebugEnabled()) { - logger.debug("Created db: '" + dbName + "' with owner: '" + ownerName + "'"); - } - if (readerName != null) { - sql = "GRANT CONNECT ON DATABASE " + dbName + " TO " + readerName; - stmt.executeUpdate(sql); - if (logger.isDebugEnabled()) { - logger.debug(" Granted connect rights on: '" + dbName + "' to reader: '" + readerName + "'"); - } - } - // Note that select rights for reader must be granted after - // Nuxeo startup. - } else if (dbType == DatabaseProductType.MYSQL) { - String sql = "CREATE database " + dbName + " DEFAULT CHARACTER SET utf8"; - stmt.executeUpdate(sql); - sql = "GRANT ALL PRIVILEGES ON " + dbName + ".* TO '" + ownerName + "'@'localhost' IDENTIFIED BY '" - + ownerPW + "' WITH GRANT OPTION"; - stmt.executeUpdate(sql); - if (logger.isDebugEnabled()) { - logger.debug("Created db: '" + dbName + "' with owner: '" + ownerName + "'"); - } - if (readerName != null) { - sql = "GRANT SELECT ON " + dbName + ".* TO '" + readerName + "'@'localhost' IDENTIFIED BY '" - + readerPW + "' WITH GRANT OPTION"; - stmt.executeUpdate(sql); - if (logger.isDebugEnabled()) { - logger.debug(" Granted SELECT rights on: '" + dbName + "' to reader: '" + readerName + "'"); - } - } - } else { - throw new UnsupportedOperationException("createDatabaseWithRights only supports PSQL - MySQL NYI!"); - } - } catch (Exception e) { - logger.error("createDatabaseWithRights failed on exception: " + e.getLocalizedMessage()); - throw e; // propagate - } finally { // close resources - try { - if (stmt != null) { - stmt.close(); - } - if (conn != null) { - conn.close(); - } - } catch (SQLException se) { - se.printStackTrace(); - } - } - - } - - private BasicDataSource getBasicDataSource(String dataSourceName) { - BasicDataSource basicDataSource = null; - if (Tools.isBlank(dataSourceName)) { - return basicDataSource; - } - try { - DataSource dataSource = JDBCTools.getDataSource(dataSourceName); - basicDataSource = (BasicDataSource) dataSource; - } catch (NamingException ne) { - logger.warn("Error attempting to retrieve basic datasource '%s': %s", - dataSourceName, ne.getMessage()); - return basicDataSource; - } - return basicDataSource; - } - - private String getBasicDataSourceUsername(String dataSourceName) { - String username = null; - BasicDataSource basicDataSource = getBasicDataSource(dataSourceName); - if (basicDataSource == null) { - return username; - } - username = basicDataSource.getUsername(); - return username; - } - - private String getBasicDataSourcePassword(String dataSourceName) { - String password = null; - BasicDataSource basicDataSource = getBasicDataSource(dataSourceName); - if (basicDataSource == null) { - return password; - } - password = basicDataSource.getPassword(); - return password; - } - - /* - * This might be useful for something, but the reader grants are better handled in the ReportPostInitHandler. - * - * - */ -/* - private void handlePostNuxeoInitDBTasks() throws Exception { - Statement stmt = null; - Connection conn = null; - - try { - DataSource nuxeoMgrDataSource = JDBCTools.getDataSource(JDBCTools.NUXEO_MANAGER_DATASOURCE_NAME); - DataSource nuxeoReaderDataSource = JDBCTools.getDataSource(JDBCTools.NUXEO_READER_DATASOURCE_NAME); - - if(nuxeoReaderDataSource!=null) { - // We need to fetch the user name and password from the nuxeoDataSource, to do grants below - org.apache.tomcat.dbcp.dbcp.BasicDataSource tomcatDataSource = - (org.apache.tomcat.dbcp.dbcp.BasicDataSource)nuxeoReaderDataSource; - // Get the template URL value from the JNDI datasource and substitute the databaseName - String readerUser = tomcatDataSource.getUsername(); - DatabaseProductType dbType = JDBCTools.getDatabaseProductType( - JDBCTools.CSPACE_DATASOURCE_NAME, - JDBCTools.DEFAULT_CSPACE_DATABASE_NAME); // only returns PG or MYSQL - - conn = nuxeoMgrDataSource.getConnection(); - stmt = conn.createStatement(); - if(dbType==DatabaseProductType.POSTGRESQL) { - // Note that select rights for reader must be granted after Nuxeo startup. - String sql = "GRANT SELECT ON ALL TABLES IN SCHEMA public TO "+readerUser; - stmt.executeUpdate(sql); - if (logger.isDebugEnabled()) { - logger.debug(" Granted SELECT rights on all public tables to reader: '"+readerUser+"'"); - } - } else if(dbType==DatabaseProductType.MYSQL) { - } else { - throw new UnsupportedOperationException("handlePostNuxeoInitDBTasks only supports Postgres/MySQL."); - } - } - } catch(Exception e) { - logger.error("handlePostNuxeoInitDBTasks failed on exception: " + e.getLocalizedMessage()); - throw e; // propagate - } finally { //close resources - try { - if(stmt!=null) { - stmt.close(); - } - } catch(SQLException se) { - // nothing we can do - } - } - - } -*/ - - private void setServerRootDir() { - serverRootDir = System.getProperty(SERVER_HOME_PROPERTY); - if (serverRootDir == null) { - serverRootDir = "."; //assume server is started from server root, e.g. server/cspace - String msg = String.format("System property '%s' was not set. Using '%s' instead.", - SERVER_HOME_PROPERTY, serverRootDir); - logger.warn(msg); - } - } - - - /** - * @return the serviceConfig - */ - public ServiceConfig getServiceConfig() { - return getServicesConfigReader().getConfiguration(); - } - - /** - * @return the clientType - */ - public ClientType getClientType() { - return getServicesConfigReader().getClientType(); - } - - /** - * @return the servicesConfigReader - */ - public ServicesConfigReaderImpl getServicesConfigReader() { - return servicesConfigReader; - } - - /** - * @return the tenantBindingConfigReader - */ - public TenantBindingConfigReaderImpl getTenantBindingConfigReader() { - return tenantBindingConfigReader; - } - - /** - * Populate a registry of URI templates by querying each resource - * for its own entries in the registry. - * - * These entries consist of one or more URI templates associated - * with that resource, for building URIs to access that resource. - */ - private synchronized void populateUriTemplateRegistry() { - if (uriTemplateRegistry.isEmpty()) { - ResourceBase resource = null; - ResourceMap resourceMap = ResteasyProviderFactory.getContextData(ResourceMap.class); - for (Map.Entry entry : resourceMap.entrySet()) { - resource = entry.getValue(); - Map entries = - resource.getUriRegistryEntries(); - uriTemplateRegistry.putAll(entries); - } - - // FIXME: Contacts itself should not have an entry in the URI template registry; - // there should be a Contacts entry in that registry only for use in - // building URIs for resources that have contacts as a sub-resource - // (This may also fall out during implementation of CSPACE-2698.) - } - } - - public UriTemplateRegistry getUriTemplateRegistry() { - if (uriTemplateRegistry.isEmpty()) { - populateUriTemplateRegistry(); - } - return uriTemplateRegistry; - } - /** - * Ensure that Nuxeo repository configuration files exist for each repository - * specified in tenant bindings. Create or update these files, as needed. - */ - private void createOrUpdateNuxeoRepositoryConfigFiles() throws Exception { - - // Get the prototype copy of the Nuxeo repository config file. - File prototypeNuxeoConfigFile = - new File(getCspaceServicesConfigDir() + File.separator + getNuxeoProtoConfigFilename()); - // FIXME: Consider checking for the presence of existing configuration files, - // rather than always failing outright if the prototype file for creating - // new or updated files can't be located. - if (! prototypeNuxeoConfigFile.canRead()) { - String msg = String.format("Could not find and/or read the prototype Nuxeo config file '%s'. " - + "Please redeploy this file by running 'ant deploy' from the Services layer source code's '3rdparty/nuxeo' module.", - prototypeNuxeoConfigFile.getCanonicalPath()); - throw new RuntimeException(msg); - } - if (logger.isTraceEnabled()) { - logger.trace("Found and can read prototype Nuxeo config file at path %s", prototypeNuxeoConfigFile.getAbsolutePath()); - } - Document prototypeConfigDoc = XmlTools.fileToXMLDocument(prototypeNuxeoConfigFile); - Document repositoryConfigDoc = null; - // FIXME: Can the variable below reasonably be made a class variable? Its value - // is used in at least one other method in this class. - Hashtable tenantBindingTypeMap = tenantBindingConfigReader.getTenantBindings(); - for (TenantBindingType tbt : tenantBindingTypeMap.values()) { - List repositoryNameList = ConfigUtils.getRepositoryNameList(tbt); - if (logger.isTraceEnabled()) { - logger.trace("Getting repository name(s) for tenant " + tbt.getName()); - } - if (repositoryNameList == null || repositoryNameList.isEmpty() == true) { - logger.warn(String.format("Could not get repository name(s) for tenant %s", tbt.getName())); - continue; //break out of loop - } else { - for (String repositoryName : repositoryNameList) { - if (Tools.isBlank(repositoryName)) { - continue; - } - if (logger.isTraceEnabled()) { - logger.trace(String.format("Repository name is %s", repositoryName)); - } - // FIXME: As per above, we might check for the presence of an existing - // config file for this repository and, if present, not fail even if - // the code below fails to update that file on any given system startup. - // - // Clone the prototype copy of the Nuxeo repository config file, - // thus creating a separate config file for the current repository. - repositoryConfigDoc = (Document) prototypeConfigDoc.clone(); - // Update this config file by inserting values pertinent to the - // current repository. - String binaryStorePath = tbt.getBinaryStorePath(); - repositoryConfigDoc = updateRepositoryConfigDoc(repositoryConfigDoc, repositoryName, - this.getCspaceInstanceId(), binaryStorePath); - if (logger.isTraceEnabled()) { - logger.trace("Updated Nuxeo repo config file contents=\n" + repositoryConfigDoc.asXML()); - } - // Write this config file to the Nuxeo server config directory. - File repofile = new File(getNuxeoConfigDir() + File.separator + - repositoryName + JEEServerDeployment.NUXEO_REPO_CONFIG_FILENAME_SUFFIX); - if (logger.isTraceEnabled()) { - logger.trace(String.format("Attempting to write Nuxeo repo config file to %s", repofile.getAbsolutePath())); - } - XmlTools.xmlDocumentToFile(repositoryConfigDoc, repofile); - } - } - } - } - - /* - * This method is filling out the proto-repo-config.xml file with tenant specific repository information. - */ - private Document updateRepositoryConfigDoc(Document repoConfigDoc, String repositoryName, - String cspaceInstanceId, String binaryStorePath) { - String databaseName = JDBCTools.getDatabaseName(repositoryName, cspaceInstanceId); - - repoConfigDoc = XmlTools.setAttributeValue(repoConfigDoc, "/component", "name", - String.format("config:%s-repository", repositoryName)); - - // Text substitutions within first extension point, "repository" - repoConfigDoc = XmlTools.setAttributeValue(repoConfigDoc, - REPOSITORY_EXTENSION_POINT_XPATH + "/repository", "name", - repositoryName); - - repoConfigDoc = XmlTools.setAttributeValue(repoConfigDoc, - REPOSITORY_EXTENSION_POINT_XPATH + "/repository/repository", "name", - repositoryName); - - repoConfigDoc = XmlTools.setAttributeValue(repoConfigDoc, - REPOSITORY_EXTENSION_POINT_XPATH + "/repository/repository/binaryStore", "path", - Tools.isBlank(binaryStorePath) ? repositoryName : binaryStorePath); // Can be either partial or full path. Partial path will be relative to Nuxeo's data directory - - /* Create the JDBC url options if any exist */ - String jdbcOptions = XmlTools.getElementValue(repoConfigDoc, - REPOSITORY_EXTENSION_POINT_XPATH + "/repository/repository/property[@name='JDBCOptions']"); - jdbcOptions = Tools.isBlank(jdbcOptions) ? "" : "?" + jdbcOptions; - - repoConfigDoc = XmlTools.setElementValue(repoConfigDoc, - REPOSITORY_EXTENSION_POINT_XPATH + "/repository/repository/property[@name='DatabaseName']", - databaseName + jdbcOptions); - - // Text substitutions within second extension point, "repositories" - repoConfigDoc = XmlTools.setElementValue(repoConfigDoc, - REPOSITORIES_EXTENSION_POINT_XPATH + "/documentation", - String.format("The %s repository", repositoryName)); - - repoConfigDoc = XmlTools.setAttributeValue(repoConfigDoc, - REPOSITORIES_EXTENSION_POINT_XPATH + "/repository", "name", - repositoryName); - - repoConfigDoc = XmlTools.setAttributeValue(repoConfigDoc, - REPOSITORIES_EXTENSION_POINT_XPATH + "/repository", "label", - String.format("%s Repository", repositoryName)); - - return repoConfigDoc; - } - - /** - * Update the current copy of the Nuxeo databases initialization script file by - * - *

    - *
  • Removing all existing DROP DATABASE commands
  • - *
  • Removing all existing DROP USER commands
  • - *
  • Adding a DROP DATABASE command for each current database, at the top of that file.
  • - *
  • Adding DROP USER commands for each provided datasource, following the DROP DATABASE commands.
  • - *
- * - * @param dbInitializationScriptFilePath - * @param dbsCheckedOrCreated - */ - private void updateInitializationScript(String dbInitializationScriptFilePath, - HashSet dbsCheckedOrCreated, String[] dataSourceNames) { - // Get the current copy of the Nuxeo databases initialization script file, - // if that file exists, and read all of its lines except for those which - // drop databases. - List lines = null; - // "If the given string" for the pathname provided here "is the empty string, then the - // result is the empty abstract pathname," according to Oracle's Javadoc for File. - // An empty path string might be provided here if a call to get the database product name failed earlier. - File nuxeoDatabasesInitScriptFile = new File(dbInitializationScriptFilePath); - try { - if (! nuxeoDatabasesInitScriptFile.canRead()) { - String msg = String.format("Could not find and/or read the Nuxeo databases initialization script file '%s'", - nuxeoDatabasesInitScriptFile.getCanonicalPath()); - logger.warn(msg); - } else { - // Note: Exceptions are written only to the console, not thrown, by - // the readFileAsLines() method in the common-api package. - lines = FileTools.readFileAsLines(dbInitializationScriptFilePath); - Iterator linesIterator = lines.iterator(); - String currentLine; - while (linesIterator.hasNext()) { - currentLine = linesIterator.next(); - // Elide all existing DROP DATABASE statements. - if (currentLine.toLowerCase().contains(DROP_DATABASE_SQL_CMD.toLowerCase())) { - linesIterator.remove(); - } - // Elide a comment pertaining to the existing - // DROP DATABASE statements. - if (currentLine.toLowerCase().contains(DROP_OBJECTS_SQL_COMMENT.toLowerCase())) { - linesIterator.remove(); - } - // Elide all existing DROP USER statements. - if (currentLine.toLowerCase().contains(DROP_USER_SQL_CMD.toLowerCase())) { - linesIterator.remove(); - } - } - } - List replacementLines = new ArrayList(); - // Add back the comment elided above - replacementLines.add(DROP_OBJECTS_SQL_COMMENT); - // Add new DROP DATABASE lines for every Nuxeo-managed database. - for (String dbName : dbsCheckedOrCreated) { - if (Tools.notBlank(dbName)) { - replacementLines.add(String.format(DROP_DATABASE_IF_EXISTS_SQL_CMD, dbName)); - } - } - // Add new DROP USER commands for every provided datasource. - String username; - for (String dataSourceName : dataSourceNames) { - username = getBasicDataSourceUsername(dataSourceName); - if (Tools.notBlank(username)) { - replacementLines.add(String.format(DROP_USER_IF_EXISTS_SQL_CMD, username)); - } - } - // Now append all existing lines from that file, except for - // any lines that were elided above. - if (lines != null && ! lines.isEmpty()) { - replacementLines.addAll(lines); - } - if (! nuxeoDatabasesInitScriptFile.canWrite()) { - String msg = String.format("Could not find and/or write the Nuxeo databases initialization script file '%s'", - nuxeoDatabasesInitScriptFile.getCanonicalPath()); - logger.warn(msg); - } else { - // Note: Exceptions are written only to the console, not thrown, by - // the writeFileFromLines() method in the common-api package. - FileTools.writeFileFromLines(dbInitializationScriptFilePath, replacementLines); - } - } catch (Exception e) { - - } - - } -} +/** + * Copyright 2009-2010 University of California at Berkeley + */ +package org.collectionspace.services.common; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.*; + +import javax.naming.NamingException; +import javax.servlet.ServletContext; +import javax.sql.DataSource; + +import org.apache.tomcat.dbcp.dbcp.BasicDataSource; +import org.collectionspace.authentication.AuthN; +import org.collectionspace.services.common.api.JEEServerDeployment; +import org.collectionspace.services.common.api.FileTools; +import org.collectionspace.services.common.api.Tools; +import org.collectionspace.services.common.authorization_mgt.AuthorizationCommon; +import org.collectionspace.services.common.config.ConfigReader; +import org.collectionspace.services.common.config.ConfigUtils; +import org.collectionspace.services.common.config.ServicesConfigReaderImpl; +import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl; +import org.collectionspace.services.common.context.ServiceBindingUtils; +import org.collectionspace.services.common.init.AddIndices; +import org.collectionspace.services.config.service.InitHandler.Params.Field; +import org.collectionspace.services.common.init.IInitHandler; +import org.collectionspace.services.common.storage.DatabaseProductType; +import org.collectionspace.services.common.storage.JDBCTools; +import org.collectionspace.services.config.ClientType; +import org.collectionspace.services.config.ServiceConfig; +import org.collectionspace.services.config.service.ServiceBindingType; +import org.collectionspace.services.config.tenant.RepositoryDomainType; +import org.collectionspace.services.config.tenant.TenantBindingType; +import org.collectionspace.services.config.types.PropertyItemType; +import org.collectionspace.services.config.types.PropertyType; +import org.collectionspace.services.nuxeo.client.java.NuxeoConnectorEmbedded; +import org.collectionspace.services.nuxeo.client.java.TenantRepository; +import org.jboss.resteasy.spi.ResteasyProviderFactory; +import org.dom4j.Document; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Main class for Services layer. It reads configuration and performs service + * level initialization. It is a singleton. + * @author + */ +public class ServiceMain { + + final Logger logger = LoggerFactory.getLogger(ServiceMain.class); + /** + * volatile is used here to assume about ordering (post JDK 1.5) + */ + private static volatile ServiceMain instance = null; + private static volatile boolean initFailed = false; + + private static final String SERVER_HOME_PROPERTY = "catalina.home"; + private static final boolean USE_APP_GENERATED_CONFIG = true; + + private static ServletContext servletContext = null; + + private NuxeoConnectorEmbedded nuxeoConnector; + private String serverRootDir = null; + private ServicesConfigReaderImpl servicesConfigReader; + private TenantBindingConfigReaderImpl tenantBindingConfigReader; + private UriTemplateRegistry uriTemplateRegistry = new UriTemplateRegistry(); + + + private static final String COMPONENT_EXTENSION_XPATH = "/component/extension[@point='%s']"; + private static final String REPOSITORY_EXTENSION_POINT_XPATH = + String.format(COMPONENT_EXTENSION_XPATH, "repository"); + private static final String REPOSITORIES_EXTENSION_POINT_XPATH = + String.format(COMPONENT_EXTENSION_XPATH, "repositories"); + + private static final String DROP_DATABASE_SQL_CMD = "DROP DATABASE"; + private static final String DROP_DATABASE_IF_EXISTS_SQL_CMD = DROP_DATABASE_SQL_CMD + " IF EXISTS %s;"; + private static final String DROP_USER_SQL_CMD = "DROP USER"; + private static final String DROP_USER_IF_EXISTS_SQL_CMD = DROP_USER_SQL_CMD + " IF EXISTS %s;"; + private static final String DROP_OBJECTS_SQL_COMMENT = "-- drop all the objects before dropping roles"; + + + private ServiceMain() { + //empty + } + + /* + * + * Set this singletons ServletContext without any call to initialize + */ + private static void setServletContext(ServletContext servletContext) { + if (servletContext != null) { + synchronized (ServiceMain.class) { + ServiceMain.servletContext = servletContext; + } + } + } + + public String getCspaceDatabaseName() { + return getServiceConfig().getDbCspaceName(); + } + + public boolean inServletContext() { + return ServiceMain.servletContext != null; + } + + public static ServiceMain getInstance(ServletContext servletContext) { + setServletContext(servletContext); + return ServiceMain.getInstance(); + } + + /** + * getInstance returns the ServiceMain singleton instance after proper + * initialization in a thread-safe manner + * @return + */ + public static ServiceMain getInstance() { + if (instance == null && initFailed == false) { + synchronized (ServiceMain.class) { + if (instance == null && initFailed == false) { + ServiceMain newInstance = new ServiceMain(); + try { + //assume the worse + initFailed = true; + newInstance.initialize(); + //celebrate success + initFailed = false; + } catch (Exception e) { + instance = null; + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } else { + throw new RuntimeException(e); + } + } + instance = newInstance; + } + } + } + + if (instance == null) { + throw new RuntimeException("Could not initialize the CollectionSpace services. Please see the CollectionSpace services log file(s) for details."); + } + + return instance; + } + + private void initialize() throws Exception { + // set our root directory + setServerRootDir(); + + // read in and set our Services config + readAndSetServicesConfig(); + + // Set our AuthN's datasource to for the cspaceDataSource + AuthN.setDataSource(JDBCTools.getDataSource(JDBCTools.CSPACE_DATASOURCE_NAME)); + + // In each tenant, set properties that don't already have values + // to their default values. + propagateConfiguredProperties(); + + // Create or update Nuxeo's per-repository configuration files. + createOrUpdateNuxeoRepositoryConfigFiles(); + + // Create the Nuxeo-managed databases, along with the requisite + // access rights to each. + HashSet dbsCheckedOrCreated = createNuxeoDatabases(); + + // Update the SQL script that drops databases and users, + // to include DROP statements for each of the Nuxeo-managed + // database names and for each relevant datasource user. + String[] dataSourceNames = {JDBCTools.NUXEO_DATASOURCE_NAME, JDBCTools.NUXEO_READER_DATASOURCE_NAME}; + updateInitializationScript(getNuxeoDatabasesInitScriptFilename(), + dbsCheckedOrCreated, dataSourceNames); + + // + // Start up and initialize our embedded Nuxeo instance. + // + if (getClientType().equals(ClientType.JAVA)) { + nuxeoConnector = NuxeoConnectorEmbedded.getInstance(); + nuxeoConnector.initialize( + getServerRootDir(), + getServicesConfigReader().getConfiguration().getRepositoryClient(), + ServiceMain.servletContext); + } else { + // + // Exit if we don't have the correct/known client type + // + throw new RuntimeException("Unknown CollectionSpace services client type: " + getClientType()); + } + // + // Create all the default user accounts and permissions. Since some of our "cspace" database config files + // for Spring need to be created at build time, the "cspace" database already will be suffixed with the + // correct 'cspaceInstanceId' so we don't need to pass it to the JDBCTools methods. + // + try { + AuthorizationCommon.createDefaultWorkflowPermissions(tenantBindingConfigReader); + String cspaceDatabaseName = getCspaceDatabaseName(); + DatabaseProductType databaseProductType = JDBCTools.getDatabaseProductType(JDBCTools.CSPACE_DATASOURCE_NAME, + cspaceDatabaseName); + AuthorizationCommon.createDefaultAccounts(tenantBindingConfigReader, databaseProductType, + cspaceDatabaseName); + } catch (Exception e) { + logger.error("Default accounts and permissions setup failed with exception(s): " + + e.getLocalizedMessage(), e); + throw e; + } + + /* + * This might be useful for something, but the reader grants are better handled in the ReportPostInitHandler. + try { + handlePostNuxeoInitDBTasks(); + } catch(Throwable e) { + logger.error("handlePostNuxeoInitDBTasks failed with exception(s): " + e.getLocalizedMessage(), e); + } + */ + } + + /** + * release releases all resources occupied by service layer infrastructure + * but not necessarily those occupied by individual services + */ + public void release() { + try { + if (nuxeoConnector != null) { + nuxeoConnector.release(); + } + instance = null; + } catch (Exception e) { + e.printStackTrace(); + //gobble it + } + } + + private void readAndSetServicesConfig() throws Exception { + //read service config + servicesConfigReader = new ServicesConfigReaderImpl(getServerRootDir()); + servicesConfigReader.read(USE_APP_GENERATED_CONFIG); + + Boolean useAppGeneratedBindings = servicesConfigReader.getConfiguration().isUseAppGeneratedTenantBindings(); + tenantBindingConfigReader = new TenantBindingConfigReaderImpl(getServerRootDir()); + tenantBindingConfigReader.read(useAppGeneratedBindings); + } + + private void propagateConfiguredProperties() { + List repoPropListHolder = + servicesConfigReader.getConfiguration().getRepositoryClient().getProperties(); + if (repoPropListHolder != null && !repoPropListHolder.isEmpty()) { + List propList = repoPropListHolder.get(0).getItem(); + if (propList != null && !propList.isEmpty()) { + tenantBindingConfigReader.setDefaultPropertiesOnTenants(propList, true); + } + } + } + + /** + * Create required indexes (aka indices) in database tables not associated + * with any specific tenant. + * + * We need to loop over each repository/db declared in the tenant bindings. + * The assumption here is that each repo/db is a Nuxeo repo/DB. + * + * @throws Exception + */ + void createRequiredIndices() throws Exception { + Hashtable tenantBindingTypeMap = tenantBindingConfigReader.getTenantBindings(); + + // + //Loop through all tenants in tenant-bindings.xml + // + String cspaceInstanceId = getCspaceInstanceId(); + for (TenantBindingType tbt : tenantBindingTypeMap.values()) { + List repositoryNameList = ConfigUtils.getRepositoryNameList(tbt); + if (repositoryNameList != null && repositoryNameList.isEmpty() == false) { + // + // Loop through each repo/DB defined in a tenant bindings file + // + for (String repositoryName : repositoryNameList) { + // Define a set of columns (fields) and their associated + // tables, on which database indexes should always be created + final String COLLECTIONSPACE_CORE_TABLE_NAME = "collectionspace_core"; + final String NUXEO_FULLTEXT_TABLE_NAME = "fulltext"; + final String NUXEO_HIERARCHY_TABLE_NAME = "hierarchy"; + + Map> fieldsToIndex = new HashMap>(); + fieldsToIndex.put(1, new ArrayList(Arrays.asList(COLLECTIONSPACE_CORE_TABLE_NAME, "tenantid"))); + fieldsToIndex.put(2, new ArrayList(Arrays.asList(COLLECTIONSPACE_CORE_TABLE_NAME, "updatedat"))); + fieldsToIndex.put(3, new ArrayList(Arrays.asList(NUXEO_FULLTEXT_TABLE_NAME, "jobid"))); + fieldsToIndex.put(4, new ArrayList(Arrays.asList(NUXEO_HIERARCHY_TABLE_NAME, "name"))); + + // Invoke existing post-init code to create these indexes, + // sending in the set of values above, in contrast to + // drawing these values from per-tenant configuration. +// DataSource dataSource = JDBCTools.getDataSource(JDBCTools.NUXEO_DATASOURCE_NAME); + AddIndices addindices = new AddIndices(); + List fields = new ArrayList(); + for (Map.Entry> entry : fieldsToIndex.entrySet()) { + Field field = new Field(); + field.setTable(entry.getValue().get(0)); // Table name from List + // item 0 + field.setCol(entry.getValue().get(1)); // Column name from List item + // 1 + fields.add(field); + } + addindices.onRepositoryInitialized(JDBCTools.NUXEO_DATASOURCE_NAME, repositoryName, cspaceInstanceId, + null, fields, null); + } + } else { + String errMsg = "repositoryNameList was empty or null."; + logger.error(errMsg); + throw new Exception(errMsg); + } + } + } + + public void firePostInitHandlers() throws Exception { + Hashtable tenantBindingTypeMap = tenantBindingConfigReader.getTenantBindings(); + // + //Loop through all tenants in tenant-bindings.xml + // + String cspaceInstanceId = getCspaceInstanceId(); + for (TenantBindingType tbt : tenantBindingTypeMap.values()) { + // + //Loop through all the services in this tenant + // + List sbtList = tbt.getServiceBindings(); + for (ServiceBindingType sbt: sbtList) { + String repositoryName = null; + if (sbt.getType().equalsIgnoreCase(ServiceBindingUtils.SERVICE_TYPE_SECURITY) == false) { + repositoryName = ConfigUtils.getRepositoryName(tbt, sbt.getRepositoryDomain()); // Each service can have a different repo domain + } + //Get the list of InitHandler elements, extract the first one (only one supported right now) and fire it using reflection. + List list = sbt.getInitHandler(); + if (list != null && list.size() > 0) { + org.collectionspace.services.config.service.InitHandler handlerType = list.get(0); // REM - 12/2012: We might want to think about supporting multiple post-init handlers + String initHandlerClassname = handlerType.getClassname(); + if (Tools.isEmpty(initHandlerClassname)) { + continue; + } + if (logger.isInfoEnabled()) { + logger.info(String.format("Firing post-init handler %s ...", initHandlerClassname)); + } + + List + fields = handlerType.getParams().getField(); + + List + props = handlerType.getParams().getProperty(); + + //org.collectionspace.services.common.service.InitHandler.Fields ft = handlerType.getFields(); + //List fields = ft.getField(); + Object o = instantiate(initHandlerClassname, IInitHandler.class); + if (o != null && o instanceof IInitHandler){ + IInitHandler handler = (IInitHandler)o; + handler.onRepositoryInitialized(JDBCTools.NUXEO_DATASOURCE_NAME, repositoryName, cspaceInstanceId, + sbt, fields, props); + //The InitHandler may be the default one, + // or specialized classes which still implement this interface and are registered in tenant-bindings.xml. + } + } + } + } + } + + /* + * A generic mechanism for instantiating a instance/object from a class name. + */ + public Object instantiate(String clazz, Class castTo) throws Exception { + ClassLoader tccl = Thread.currentThread().getContextClassLoader(); + clazz = clazz.trim(); + Class c = tccl.loadClass(clazz); + if (castTo.isAssignableFrom(c)) { + return c.newInstance(); + } + return null; + } + + void retrieveAllWorkspaceIds() throws Exception { + //all configs are read, connector is initialized, retrieve workspaceids + Hashtable tenantBindings = + tenantBindingConfigReader.getTenantBindings(); + TenantRepository.get().setup(tenantBindings); + } + + /** + * getWorkspaceId returns workspace id for given tenant and service name + * @param tenantId + * @param serviceName + * @return + */ + public String getWorkspaceId(String tenantId, String serviceName) { + return TenantRepository.get().getWorkspaceId(tenantId, serviceName); + } + + /** + * @return the nuxeoConnector + */ + public NuxeoConnectorEmbedded getNuxeoConnector() { + return nuxeoConnector; + } + + /** + * @return the serverRootDir + */ + public String getServerRootDir() { + return serverRootDir; + } + + private String getCspaceServicesConfigDir() { + return getServerRootDir() + File.separator + JEEServerDeployment.CSPACE_CONFIG_SERVICES_DIR_PATH; + } + + private String getNuxeoConfigDir() { + return getServerRootDir() + File.separator + JEEServerDeployment.NUXEO_SERVER_CONFIG_DIR; + } + + private String getNuxeoProtoConfigFilename() { + return JEEServerDeployment.NUXEO_PROTOTYPE_CONFIG_FILENAME; + } + + private String getNuxeoConfigFilename(String reponame) { + return reponame + JEEServerDeployment.NUXEO_REPO_CONFIG_FILENAME_SUFFIX; + } + + private String getDatabaseScriptsPath() { + DatabaseProductType dbType; + String databaseProductName; + String databaseScriptsPath = ""; + try { + // This call makes a connection to the database server, using a default database + // name and retrieves the database product name from metadata provided by the server. + dbType = JDBCTools.getDatabaseProductType(JDBCTools.CSADMIN_DATASOURCE_NAME, + getServiceConfig().getDbCsadminName()); + databaseProductName = dbType.getName(); + databaseScriptsPath = getServerRootDir() + File.separator + + JEEServerDeployment.DATABASE_SCRIPTS_DIR_PATH + File.separator + databaseProductName; + // An Exception occurring here will cause an empty path to be returned, ultimately + // resulting in a failure to find the Nuxeo databases initialization script file. + } catch (Exception e) { + logger.warn(String.format("Could not get database product type: %s", e.getMessage())); + } + return databaseScriptsPath; + + } + + /** + * Returns the full filesystem path to the Nuxeo databases initialization script file. + * + * @return the full path to the Nuxeo databases initialization script file. + * Returns an empty String for the path if the database scripts path is null or empty. + */ + private String getNuxeoDatabasesInitScriptFilename() { + return Tools.notBlank(getDatabaseScriptsPath()) ? + getDatabaseScriptsPath() + File.separator + JEEServerDeployment.NUXEO_DB_INIT_SCRIPT_FILENAME : ""; + } + + /** + * @return the server resources path + */ + public String getServerResourcesPath() { + return getServerRootDir() + File.separator + ConfigReader.RESOURCES_DIR_PATH + File.separator; + } + + public InputStream getResourceAsStream(String resourceName) throws FileNotFoundException { + InputStream result = new FileInputStream(new File(getServerResourcesPath() + resourceName)); + return result; + } + + public String getCspaceInstanceId() { + String result = getServiceConfig().getCspaceInstanceId(); + + if (result == null || result.trim().isEmpty()) { + result = ""; //empty string + } + + return result; + } + /* + * Look through the tenant bindings and create the required Nuxeo databases -each tenant can declare + * their own Nuxeo repository/database. + * Get the NuxeoDS info and create the necessary databases. + * Consider the tenant bindings to find and get the data sources for each tenant. + * There may be only one, one per tenant, or something in between. + * + */ + private HashSet createNuxeoDatabases() throws Exception { + String nuxeoUser = getBasicDataSourceUsername(JDBCTools.NUXEO_DATASOURCE_NAME); + String nuxeoPW = getBasicDataSourcePassword(JDBCTools.NUXEO_DATASOURCE_NAME); + + String readerUser = getBasicDataSourceUsername(JDBCTools.NUXEO_READER_DATASOURCE_NAME); + String readerPW = getBasicDataSourcePassword(JDBCTools.NUXEO_READER_DATASOURCE_NAME); + + DatabaseProductType dbType = JDBCTools.getDatabaseProductType(JDBCTools.CSADMIN_DATASOURCE_NAME, + getServiceConfig().getDbCsadminName()); + + Hashtable tenantBindings = + tenantBindingConfigReader.getTenantBindings(); + HashSet nuxeoDBsChecked = new HashSet(); + + // First check and create the roles as needed. (nuxeo and reader) + for (TenantBindingType tenantBinding : tenantBindings.values()) { + String tId = tenantBinding.getId(); + String tName = tenantBinding.getName(); + List repoDomainList = tenantBinding.getRepositoryDomain(); + for (RepositoryDomainType repoDomain : repoDomainList) { + String repoDomainName = repoDomain.getName(); + String repositoryName = repoDomain.getRepositoryName(); + String cspaceInstanceId = getCspaceInstanceId(); + String dbName = JDBCTools.getDatabaseName(repositoryName, cspaceInstanceId); + if (nuxeoDBsChecked.contains(dbName)) { + if (logger.isDebugEnabled()) { + logger.debug("Another user of db: " + dbName + ": Repo: " + repoDomainName + + " and tenant: " + tName + " (id:" + tId + ")"); + } + } else { + if (logger.isDebugEnabled()) { + logger.debug("Need to prepare db: " + dbName + " for Repo: " + repoDomainName + + " and tenant: " + tName + " (id:" + tId + ")"); + } + boolean dbExists = JDBCTools.hasDatabase(dbType, dbName); + if (dbExists) { + if (logger.isDebugEnabled()) { + logger.debug("Database: " + dbName + " already exists."); + } + } else { + // Create the user as needed + JDBCTools.createNewDatabaseUser(JDBCTools.CSADMIN_DATASOURCE_NAME, repositoryName, cspaceInstanceId, dbType, nuxeoUser, nuxeoPW); + if (readerUser != null) { + JDBCTools.createNewDatabaseUser(JDBCTools.CSADMIN_DATASOURCE_NAME, repositoryName, cspaceInstanceId, dbType, readerUser, readerPW); + } + // Create the database + createDatabaseWithRights(dbType, dbName, nuxeoUser, nuxeoPW, readerUser, readerPW); + } + nuxeoDBsChecked.add(dbName); + } + } // Loop on repos for tenant + } // Loop on tenants + + return nuxeoDBsChecked; + + } + + /** + * Creates a Nuxeo-managed database, sets up an owner for that + * database, and adds (at least) connection privileges to a reader + * of that database. + * + * @param conn + * @param dbType + * @param dbName + * @param ownerName + * @param ownerPW + * @param readerName + * @param readerPW + * @throws Exception + */ + private void createDatabaseWithRights(DatabaseProductType dbType, String dbName, String ownerName, + String ownerPW, String readerName, String readerPW) throws Exception { + Connection conn = null; + Statement stmt = null; + try { + DataSource csadminDataSource = JDBCTools.getDataSource(JDBCTools.CSADMIN_DATASOURCE_NAME); + conn = csadminDataSource.getConnection(); + stmt = conn.createStatement(); + if (dbType == DatabaseProductType.POSTGRESQL) { + // PostgreSQL does not need passwords in grant statements. + String sql = "CREATE DATABASE " + dbName + " ENCODING 'UTF8' OWNER " + ownerName; + stmt.executeUpdate(sql); + if (logger.isDebugEnabled()) { + logger.debug("Created db: '" + dbName + "' with owner: '" + ownerName + "'"); + } + if (readerName != null) { + sql = "GRANT CONNECT ON DATABASE " + dbName + " TO " + readerName; + stmt.executeUpdate(sql); + if (logger.isDebugEnabled()) { + logger.debug(" Granted connect rights on: '" + dbName + "' to reader: '" + readerName + "'"); + } + } + // Note that select rights for reader must be granted after + // Nuxeo startup. + } else if (dbType == DatabaseProductType.MYSQL) { + String sql = "CREATE database " + dbName + " DEFAULT CHARACTER SET utf8"; + stmt.executeUpdate(sql); + sql = "GRANT ALL PRIVILEGES ON " + dbName + ".* TO '" + ownerName + "'@'localhost' IDENTIFIED BY '" + + ownerPW + "' WITH GRANT OPTION"; + stmt.executeUpdate(sql); + if (logger.isDebugEnabled()) { + logger.debug("Created db: '" + dbName + "' with owner: '" + ownerName + "'"); + } + if (readerName != null) { + sql = "GRANT SELECT ON " + dbName + ".* TO '" + readerName + "'@'localhost' IDENTIFIED BY '" + + readerPW + "' WITH GRANT OPTION"; + stmt.executeUpdate(sql); + if (logger.isDebugEnabled()) { + logger.debug(" Granted SELECT rights on: '" + dbName + "' to reader: '" + readerName + "'"); + } + } + } else { + throw new UnsupportedOperationException("createDatabaseWithRights only supports PSQL - MySQL NYI!"); + } + } catch (Exception e) { + logger.error("createDatabaseWithRights failed on exception: " + e.getLocalizedMessage()); + throw e; // propagate + } finally { // close resources + try { + if (stmt != null) { + stmt.close(); + } + if (conn != null) { + conn.close(); + } + } catch (SQLException se) { + se.printStackTrace(); + } + } + + } + + private BasicDataSource getBasicDataSource(String dataSourceName) { + BasicDataSource basicDataSource = null; + if (Tools.isBlank(dataSourceName)) { + return basicDataSource; + } + try { + DataSource dataSource = JDBCTools.getDataSource(dataSourceName); + basicDataSource = (BasicDataSource) dataSource; + } catch (NamingException ne) { + logger.warn("Error attempting to retrieve basic datasource '%s': %s", + dataSourceName, ne.getMessage()); + return basicDataSource; + } + return basicDataSource; + } + + private String getBasicDataSourceUsername(String dataSourceName) { + String username = null; + BasicDataSource basicDataSource = getBasicDataSource(dataSourceName); + if (basicDataSource == null) { + return username; + } + username = basicDataSource.getUsername(); + return username; + } + + private String getBasicDataSourcePassword(String dataSourceName) { + String password = null; + BasicDataSource basicDataSource = getBasicDataSource(dataSourceName); + if (basicDataSource == null) { + return password; + } + password = basicDataSource.getPassword(); + return password; + } + + /* + * This might be useful for something, but the reader grants are better handled in the ReportPostInitHandler. + * + * + */ +/* + private void handlePostNuxeoInitDBTasks() throws Exception { + Statement stmt = null; + Connection conn = null; + + try { + DataSource nuxeoMgrDataSource = JDBCTools.getDataSource(JDBCTools.NUXEO_MANAGER_DATASOURCE_NAME); + DataSource nuxeoReaderDataSource = JDBCTools.getDataSource(JDBCTools.NUXEO_READER_DATASOURCE_NAME); + + if(nuxeoReaderDataSource!=null) { + // We need to fetch the user name and password from the nuxeoDataSource, to do grants below + org.apache.tomcat.dbcp.dbcp.BasicDataSource tomcatDataSource = + (org.apache.tomcat.dbcp.dbcp.BasicDataSource)nuxeoReaderDataSource; + // Get the template URL value from the JNDI datasource and substitute the databaseName + String readerUser = tomcatDataSource.getUsername(); + DatabaseProductType dbType = JDBCTools.getDatabaseProductType( + JDBCTools.CSPACE_DATASOURCE_NAME, + JDBCTools.DEFAULT_CSPACE_DATABASE_NAME); // only returns PG or MYSQL + + conn = nuxeoMgrDataSource.getConnection(); + stmt = conn.createStatement(); + if(dbType==DatabaseProductType.POSTGRESQL) { + // Note that select rights for reader must be granted after Nuxeo startup. + String sql = "GRANT SELECT ON ALL TABLES IN SCHEMA public TO "+readerUser; + stmt.executeUpdate(sql); + if (logger.isDebugEnabled()) { + logger.debug(" Granted SELECT rights on all public tables to reader: '"+readerUser+"'"); + } + } else if(dbType==DatabaseProductType.MYSQL) { + } else { + throw new UnsupportedOperationException("handlePostNuxeoInitDBTasks only supports Postgres/MySQL."); + } + } + } catch(Exception e) { + logger.error("handlePostNuxeoInitDBTasks failed on exception: " + e.getLocalizedMessage()); + throw e; // propagate + } finally { //close resources + try { + if(stmt!=null) { + stmt.close(); + } + } catch(SQLException se) { + // nothing we can do + } + } + + } +*/ + + private void setServerRootDir() { + serverRootDir = System.getProperty(SERVER_HOME_PROPERTY); + if (serverRootDir == null) { + serverRootDir = "."; //assume server is started from server root, e.g. server/cspace + String msg = String.format("System property '%s' was not set. Using '%s' instead.", + SERVER_HOME_PROPERTY, serverRootDir); + logger.warn(msg); + } + } + + + /** + * @return the serviceConfig + */ + public ServiceConfig getServiceConfig() { + return getServicesConfigReader().getConfiguration(); + } + + /** + * @return the clientType + */ + public ClientType getClientType() { + return getServicesConfigReader().getClientType(); + } + + /** + * @return the servicesConfigReader + */ + public ServicesConfigReaderImpl getServicesConfigReader() { + return servicesConfigReader; + } + + /** + * @return the tenantBindingConfigReader + */ + public TenantBindingConfigReaderImpl getTenantBindingConfigReader() { + return tenantBindingConfigReader; + } + + /** + * Populate a registry of URI templates by querying each resource + * for its own entries in the registry. + * + * These entries consist of one or more URI templates associated + * with that resource, for building URIs to access that resource. + */ + private synchronized void populateUriTemplateRegistry() { + if (uriTemplateRegistry.isEmpty()) { + ResourceBase resource = null; + ResourceMap resourceMap = ResteasyProviderFactory.getContextData(ResourceMap.class); + for (Map.Entry entry : resourceMap.entrySet()) { + resource = entry.getValue(); + Map entries = + resource.getUriRegistryEntries(); + uriTemplateRegistry.putAll(entries); + } + + // FIXME: Contacts itself should not have an entry in the URI template registry; + // there should be a Contacts entry in that registry only for use in + // building URIs for resources that have contacts as a sub-resource + // (This may also fall out during implementation of CSPACE-2698.) + } + } + + public UriTemplateRegistry getUriTemplateRegistry() { + if (uriTemplateRegistry.isEmpty()) { + populateUriTemplateRegistry(); + } + return uriTemplateRegistry; + } + /** + * Ensure that Nuxeo repository configuration files exist for each repository + * specified in tenant bindings. Create or update these files, as needed. + */ + private void createOrUpdateNuxeoRepositoryConfigFiles() throws Exception { + + // Get the prototype copy of the Nuxeo repository config file. + File prototypeNuxeoConfigFile = + new File(getCspaceServicesConfigDir() + File.separator + getNuxeoProtoConfigFilename()); + // FIXME: Consider checking for the presence of existing configuration files, + // rather than always failing outright if the prototype file for creating + // new or updated files can't be located. + if (! prototypeNuxeoConfigFile.canRead()) { + String msg = String.format("Could not find and/or read the prototype Nuxeo config file '%s'. " + + "Please redeploy this file by running 'ant deploy' from the Services layer source code's '3rdparty/nuxeo' module.", + prototypeNuxeoConfigFile.getCanonicalPath()); + throw new RuntimeException(msg); + } + if (logger.isTraceEnabled()) { + logger.trace("Found and can read prototype Nuxeo config file at path %s", prototypeNuxeoConfigFile.getAbsolutePath()); + } + Document prototypeConfigDoc = XmlTools.fileToXMLDocument(prototypeNuxeoConfigFile); + Document repositoryConfigDoc = null; + // FIXME: Can the variable below reasonably be made a class variable? Its value + // is used in at least one other method in this class. + Hashtable tenantBindingTypeMap = tenantBindingConfigReader.getTenantBindings(); + for (TenantBindingType tbt : tenantBindingTypeMap.values()) { + List repositoryNameList = ConfigUtils.getRepositoryNameList(tbt); + if (logger.isTraceEnabled()) { + logger.trace("Getting repository name(s) for tenant " + tbt.getName()); + } + if (repositoryNameList == null || repositoryNameList.isEmpty() == true) { + logger.warn(String.format("Could not get repository name(s) for tenant %s", tbt.getName())); + continue; //break out of loop + } else { + for (String repositoryName : repositoryNameList) { + if (Tools.isBlank(repositoryName)) { + continue; + } + if (logger.isTraceEnabled()) { + logger.trace(String.format("Repository name is %s", repositoryName)); + } + // FIXME: As per above, we might check for the presence of an existing + // config file for this repository and, if present, not fail even if + // the code below fails to update that file on any given system startup. + // + // Clone the prototype copy of the Nuxeo repository config file, + // thus creating a separate config file for the current repository. + repositoryConfigDoc = (Document) prototypeConfigDoc.clone(); + // Update this config file by inserting values pertinent to the + // current repository. + String binaryStorePath = tbt.getBinaryStorePath(); + repositoryConfigDoc = updateRepositoryConfigDoc(repositoryConfigDoc, repositoryName, + this.getCspaceInstanceId(), binaryStorePath); + if (logger.isTraceEnabled()) { + logger.trace("Updated Nuxeo repo config file contents=\n" + repositoryConfigDoc.asXML()); + } + // Write this config file to the Nuxeo server config directory. + File repofile = new File(getNuxeoConfigDir() + File.separator + + repositoryName + JEEServerDeployment.NUXEO_REPO_CONFIG_FILENAME_SUFFIX); + if (logger.isTraceEnabled()) { + logger.trace(String.format("Attempting to write Nuxeo repo config file to %s", repofile.getAbsolutePath())); + } + XmlTools.xmlDocumentToFile(repositoryConfigDoc, repofile); + } + } + } + } + + /* + * This method is filling out the proto-repo-config.xml file with tenant specific repository information. + */ + private Document updateRepositoryConfigDoc(Document repoConfigDoc, String repositoryName, + String cspaceInstanceId, String binaryStorePath) { + String databaseName = JDBCTools.getDatabaseName(repositoryName, cspaceInstanceId); + + repoConfigDoc = XmlTools.setAttributeValue(repoConfigDoc, "/component", "name", + String.format("config:%s-repository", repositoryName)); + + // Text substitutions within first extension point, "repository" + repoConfigDoc = XmlTools.setAttributeValue(repoConfigDoc, + REPOSITORY_EXTENSION_POINT_XPATH + "/repository", "name", + repositoryName); + + repoConfigDoc = XmlTools.setAttributeValue(repoConfigDoc, + REPOSITORY_EXTENSION_POINT_XPATH + "/repository/repository", "name", + repositoryName); + + repoConfigDoc = XmlTools.setAttributeValue(repoConfigDoc, + REPOSITORY_EXTENSION_POINT_XPATH + "/repository/repository/binaryStore", "path", + Tools.isBlank(binaryStorePath) ? repositoryName : binaryStorePath); // Can be either partial or full path. Partial path will be relative to Nuxeo's data directory + + /* Create the JDBC url options if any exist */ + String jdbcOptions = XmlTools.getElementValue(repoConfigDoc, + REPOSITORY_EXTENSION_POINT_XPATH + "/repository/repository/property[@name='JDBCOptions']"); + jdbcOptions = Tools.isBlank(jdbcOptions) ? "" : "?" + jdbcOptions; + + repoConfigDoc = XmlTools.setElementValue(repoConfigDoc, + REPOSITORY_EXTENSION_POINT_XPATH + "/repository/repository/property[@name='DatabaseName']", + databaseName + jdbcOptions); + + // Text substitutions within second extension point, "repositories" + repoConfigDoc = XmlTools.setElementValue(repoConfigDoc, + REPOSITORIES_EXTENSION_POINT_XPATH + "/documentation", + String.format("The %s repository", repositoryName)); + + repoConfigDoc = XmlTools.setAttributeValue(repoConfigDoc, + REPOSITORIES_EXTENSION_POINT_XPATH + "/repository", "name", + repositoryName); + + repoConfigDoc = XmlTools.setAttributeValue(repoConfigDoc, + REPOSITORIES_EXTENSION_POINT_XPATH + "/repository", "label", + String.format("%s Repository", repositoryName)); + + return repoConfigDoc; + } + + /** + * Update the current copy of the Nuxeo databases initialization script file by + * + *
    + *
  • Removing all existing DROP DATABASE commands
  • + *
  • Removing all existing DROP USER commands
  • + *
  • Adding a DROP DATABASE command for each current database, at the top of that file.
  • + *
  • Adding DROP USER commands for each provided datasource, following the DROP DATABASE commands.
  • + *
+ * + * @param dbInitializationScriptFilePath + * @param dbsCheckedOrCreated + */ + private void updateInitializationScript(String dbInitializationScriptFilePath, + HashSet dbsCheckedOrCreated, String[] dataSourceNames) { + // Get the current copy of the Nuxeo databases initialization script file, + // if that file exists, and read all of its lines except for those which + // drop databases. + List lines = null; + // "If the given string" for the pathname provided here "is the empty string, then the + // result is the empty abstract pathname," according to Oracle's Javadoc for File. + // An empty path string might be provided here if a call to get the database product name failed earlier. + File nuxeoDatabasesInitScriptFile = new File(dbInitializationScriptFilePath); + try { + if (! nuxeoDatabasesInitScriptFile.canRead()) { + String msg = String.format("Could not find and/or read the Nuxeo databases initialization script file '%s'", + nuxeoDatabasesInitScriptFile.getCanonicalPath()); + logger.warn(msg); + } else { + // Note: Exceptions are written only to the console, not thrown, by + // the readFileAsLines() method in the common-api package. + lines = FileTools.readFileAsLines(dbInitializationScriptFilePath); + Iterator linesIterator = lines.iterator(); + String currentLine; + while (linesIterator.hasNext()) { + currentLine = linesIterator.next(); + // Elide all existing DROP DATABASE statements. + if (currentLine.toLowerCase().contains(DROP_DATABASE_SQL_CMD.toLowerCase())) { + linesIterator.remove(); + } + // Elide a comment pertaining to the existing + // DROP DATABASE statements. + if (currentLine.toLowerCase().contains(DROP_OBJECTS_SQL_COMMENT.toLowerCase())) { + linesIterator.remove(); + } + // Elide all existing DROP USER statements. + if (currentLine.toLowerCase().contains(DROP_USER_SQL_CMD.toLowerCase())) { + linesIterator.remove(); + } + } + } + List replacementLines = new ArrayList(); + // Add back the comment elided above + replacementLines.add(DROP_OBJECTS_SQL_COMMENT); + // Add new DROP DATABASE lines for every Nuxeo-managed database. + for (String dbName : dbsCheckedOrCreated) { + if (Tools.notBlank(dbName)) { + replacementLines.add(String.format(DROP_DATABASE_IF_EXISTS_SQL_CMD, dbName)); + } + } + // Add new DROP USER commands for every provided datasource. + String username; + for (String dataSourceName : dataSourceNames) { + username = getBasicDataSourceUsername(dataSourceName); + if (Tools.notBlank(username)) { + replacementLines.add(String.format(DROP_USER_IF_EXISTS_SQL_CMD, username)); + } + } + // Now append all existing lines from that file, except for + // any lines that were elided above. + if (lines != null && ! lines.isEmpty()) { + replacementLines.addAll(lines); + } + if (! nuxeoDatabasesInitScriptFile.canWrite()) { + String msg = String.format("Could not find and/or write the Nuxeo databases initialization script file '%s'", + nuxeoDatabasesInitScriptFile.getCanonicalPath()); + logger.warn(msg); + } else { + // Note: Exceptions are written only to the console, not thrown, by + // the writeFileFromLines() method in the common-api package. + FileTools.writeFileFromLines(dbInitializationScriptFilePath, replacementLines); + } + } catch (Exception e) { + + } + + } +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/ServletTools.java b/services/common/src/main/java/org/collectionspace/services/common/ServletTools.java index 2d126652a..44622c02b 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/ServletTools.java +++ b/services/common/src/main/java/org/collectionspace/services/common/ServletTools.java @@ -1,384 +1,384 @@ -package org.collectionspace.services.common; - - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.Enumeration; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -public class ServletTools { - - public final static int BROWSER_NOT_SET = -1; - public final static int BROWSER_UNKNOWN = 0; - public final static int BROWSER_IE4 = 1; - public final static int BROWSER_NETSCAPE_COMPATIBLE = 20; - public final static int BROWSER_NETSCAPE_4 = 21; - public final static int BROWSER_NETSCAPE_5 = 22; - public final static int BROWSER_NETSCAPE_6 = 23; - public final static int BROWSER_IE = 24; - public final static int BROWSER_DYNAMIDE_TEXT = 50; - - public final static String BROWSER_STRING_UNKNOWN = "*"; - public final static String BROWSER_STRING_IE = "IE"; - public final static String BROWSER_STRING_NETSCAPE_COMPATIBLE = "NS"; - - public final static String getBrowserStringFromID(int id){ - switch ( id ) { - case BROWSER_UNKNOWN : return BROWSER_STRING_UNKNOWN; - case BROWSER_IE : return BROWSER_STRING_IE; - case BROWSER_NETSCAPE_COMPATIBLE : return BROWSER_STRING_NETSCAPE_COMPATIBLE; - default: return BROWSER_STRING_UNKNOWN; - } - } - - /** Different from ServletRequest.getParameter in that this function will never return a null, always and empty string if param not found. - */ - public static String getParameterValue(HttpServletRequest request, String paramName){ - if (request == null){ - return ""; - } - String value = request.getParameter(paramName); - value = (value == null) ? "" : value; - return value; - } - - public static String getURL(HttpServletRequest request){ - if (request == null){ - return ""; - } - String qs = request.getQueryString(); - String qstr = (qs != null && qs.length() > 0) - ? "?"+qs - : ""; - return request.getRequestURI()+qstr; - } - - public static String getFullURL(HttpServletRequest request){ - return getProtoHostPort(request)+getURL(request); - } - - /** @return "http" or "https", without the "://" part. - */ - public static String getProto(HttpServletRequest request){ - if (request==null){ - return ""; - } - String prot = request.getAuthType(); - String protocol = prot != null && prot.equals("SSL") ? "https" : "http"; - return protocol; - } - - public static String getProtoHostPort(HttpServletRequest request){ - if (request==null){ - return ""; - } - String protocol = getProto(request); - int port = request.getServerPort(); - String portstr; - if ( protocol.equals("https") ) { - portstr = (port != 443) ? ":"+port : ""; - } else { - portstr = (port != 80) ? ":"+port : ""; - } - return protocol+"://"+request.getServerName()+portstr; - } - - public static String getProtoHostPort(java.net.URL url){ - if (url==null){ - return ""; - } - String protocol = url.getProtocol(); - int port = url.getPort(); - String portstr; - if ( protocol.equals("https") ) { - portstr = (port != 443) ? ":"+port : ""; - } else { - portstr = (port != 80) ? ":"+port : ""; - } - return protocol+"://"+url.getHost()+portstr; - } - - public static String decodeURLString(HttpServletRequest request, String paramName) throws UnsupportedEncodingException{ - if ( request == null ) { - return ""; - } - String value = request.getParameter(paramName); - return decodeURLString(value); - } - - public static String decodeURLString(String URLString) throws UnsupportedEncodingException{ - if ( URLString == null ) { - return ""; - } - return URLDecoder.decode(URLString, "UTF-8"); - } - - public static String encodeURLString(String s){ - return URLEncoder.encode(s); - } - - public static String dumpRequestInfo(HttpServletRequest request){ - return dumpRequestInfo(request, true, "#FFAD00", true); - } - - public static String dumpRequestInfo(HttpServletRequest request, boolean html, String headerColor, boolean dumpHeaders){ - if (request==null){ - return "NULL REQUEST"; - } - String result; - if (dumpHeaders){ - result = dumpRequestHeaders(request, html); - } else { - result = "URL: " + getFullURL(request); - } - - if ( html ) { - result = result + "\r\n
Params: "; - } else { - result = result + "\r\nParams: "; - } - result = result + dumpRequestParams(request, html, headerColor); - return result; - } - - public static String dumpRequestHeaders(HttpServletRequest request, boolean html){ - if (request==null){ - return "NULL REQUEST"; - } - String headers = ""; - String nl = html ? "\r\n
" : "\r\n"; - for(Enumeration headernames = request.getHeaderNames(); headernames.hasMoreElements();){ - String headername = (String)headernames.nextElement(); - headers += nl + headername+": "+request.getHeader(headername); - } - String result; - if ( html ) { - result = "
";
-        } else {
-            result = "";
-        }
-        result = result + "\r\nHeaders: "+ headers
-          +"\r\nmethod: " + request.getMethod()
-          +"\r\nProtocol: " + getProto(request)
-          +"\r\nURL: " +  getFullURL(request);
-          //+"\r\nQuery String: " +  getQueryString()
-          //+"\r\nContent: " + getContent();
-          if ( html ) {
-            result = result + "
"; - } - return result; - } - - public static String dumpRequestParams(HttpServletRequest request){ - return dumpRequestParams(request, true, "#FFAD00"); - } - public static String dumpRequestParams(HttpServletRequest request, boolean html, String headerColor){ - if (request==null){ - return "NULL REQUEST"; - } - StringBuffer result = new StringBuffer(); - if (html) result.append( "\n" + - "\n" + - ""); - Enumeration paramNames = request.getParameterNames(); - while(paramNames.hasMoreElements()) { - String paramName = (String)paramNames.nextElement(); - - if (html) result.append("\r\n\r\n"); - else result.append("\r\n"); - } - if (html) result.append("
Parameter NameParameter Value(s)
" + paramName + "\r\n"); - else result.append(paramName).append("="); - - String[] paramValues = request.getParameterValues(paramName); - if (paramValues.length == 1) { - String paramValue = paramValues[0]; - if (paramValue.length() == 0){ - if (html) result.append("No Value"); - else result.append("\"\""); - } else { - if (html) result.append(paramValue); - else result.append('\"'+paramValue+'\"'); - } - } else { - if (html) result.append("
    "); - for(int i=0; i" + paramValues[i]+""); - else result.append('\"'+paramValues[i]+'\"'); - } - if (html) result.append("
"); - } - if (html) result.append("
"); - return result.toString(); - } - - - - public static class UserIDPassword { - public String user_id = ""; - public String password = ""; - } - - /* - - public String getUserName(){ - String remoteUserName = getRemoteUser().user_id; - if (remoteUserName.length() > 0){ - return remoteUserName; - } else { - String name = getFieldValue("USER"); - if ( name != null && name.length()>0 ) { - return name; - } - } - return ""; - } - */ - public static UserIDPassword getRemoteUser(HttpServletRequest request){ - return getRemoteUser(request.getHeader("Authorization")); - } - - protected static UserIDPassword getRemoteUser(String authString){ - UserIDPassword uip = new UserIDPassword(); - try { // Decode and decompose the Authorization headervalue - if (authString == null){ - return uip; - } - authString = authString.substring(6).trim(); - byte mydata[]; -// sun.misc.BASE64Decoder base64 = new sun.misc.BASE64Decoder(); - org.apache.commons.codec.binary.Base64 base64 = new org.apache.commons.codec.binary.Base64(); -// mydata = base64.decodeBuffer(authString); - mydata = base64.decode(authString); - String loginInfo = new String(mydata); - int index = loginInfo.indexOf(":"); - if( index != -1 ){ - uip.password = loginInfo.substring(index +1); - uip.user_id = loginInfo.substring(0, index); - } - } catch(Exception e) { - //result will have empty user name - System.out.println("ServletTools.getRemoteUser() failed to obtain Authorization info"); - } - return uip; - } - - public static String browserVersion(HttpServletRequest request){ - String agent = request.getHeader("User-Agent"); - //Examples: - //curl/7.5.1 - //Mozilla/4.0 - //Mozilla/4.08 [en] (Win95; U ;Nav) - //Mozilla/4.0 (compatible; MSIE 5.01; Windows NT; FMRCo cfg. 5.01.2.1a) - //Mozilla/4.0 (compatible; MSIE 5.01; Windows NT; FMRCo cfg. 5.01.2.1a) - if ( agent == null ) { - return "null";//don't just return "" since this value may be used in a Tcl eval, and it would then disappear. - } - int start, stop; - if ( agent.indexOf("MSIE ") > -1 ) { - start = agent.indexOf("MSIE "); - stop = agent.indexOf(";", start); - stop = stop > -1 ? stop : agent.length(); //safety - return agent.substring(start+5, stop).trim(); - } else { - start = agent.indexOf("/"); - stop = agent.indexOf(" "); - stop = stop > -1 ? stop : agent.length(); //for JSSE, there is no space: User-Agent: Java1.3.0_02 - return agent.substring(start+1, stop).trim(); - } - } - - - /** - * Mozilla/4.79 [en] (Windows NT 5.0; U) - * Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4b) Gecko/20030516 Mozilla Firebird/0.6 - * Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:0.9.4) Gecko/20011128 Netscape6/6.2.1 - * Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.3705) - */ - public static int findBrowserID(HttpServletRequest request){ - String browserString = request.getHeader("User-Agent"); - if (browserString == null) - return BROWSER_UNKNOWN; - if (browserString.indexOf("MSIE") > -1) - return BROWSER_IE4; - int iMozilla = browserString.indexOf("Mozilla"); - if (iMozilla > -1){ - String ver = browserString.substring(iMozilla + ("Mozilla/".length()) ); - int iSpace = ver.indexOf(" "); - if (iSpace>-1){ - ver = ver.substring(0, iSpace); - } - try { - Double majorminor = new Double(ver); - if (majorminor.longValue()==4){ - return BROWSER_NETSCAPE_4; - } - if (majorminor.longValue()==5){ - return BROWSER_NETSCAPE_5; - } - if (majorminor.longValue()==6){ - return BROWSER_NETSCAPE_6; - } - } catch (Exception e) { - System.out.println("ERROR: silent after catching error converting browser minor version."+browserString); - return BROWSER_NETSCAPE_COMPATIBLE; - } - return BROWSER_NETSCAPE_COMPATIBLE; - } - return BROWSER_UNKNOWN; - } - - public static boolean isBrowserIE(int bid){ - return (bid == BROWSER_IE4 || bid == BROWSER_IE) ? true : false ; - } - - public static boolean isBrowserNS4x(int bid){ - return (bid == BROWSER_NETSCAPE_4) ; - } - - public static String getCookieValue(HttpServletRequest request, String name ){ - Cookie result = findCookie(request, name); - if ( result != null ) { - return result.getValue(); - } - return ""; - } - - public static Cookie findCookie(HttpServletRequest request, String name ){ - if (request == null || name == null) { - return null; - } - Cookie [] cookies = request.getCookies(); - if ( cookies == null ) { - return null; - } - int cookies_len = cookies.length; - for (int i=0; i < cookies_len; i++) { - Cookie cookie = cookies[i]; - if (cookie != null && name.equals(cookie.getName())){ - return cookie; - } - } - return null; - } - - public static Cookie setCookie(HttpServletResponse response, String name, String value){ - return setCookie(response, name, value, "/", 365*24*60*60); - } - - public static Cookie setCookie(HttpServletResponse response, String name, String value, String path, int maxAge){ - Cookie cookie = new javax.servlet.http.Cookie(name, value); - cookie.setMaxAge(maxAge); - cookie.setPath(path); - response.addCookie(cookie); - return cookie; - } - - - -} - +package org.collectionspace.services.common; + + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.Enumeration; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class ServletTools { + + public final static int BROWSER_NOT_SET = -1; + public final static int BROWSER_UNKNOWN = 0; + public final static int BROWSER_IE4 = 1; + public final static int BROWSER_NETSCAPE_COMPATIBLE = 20; + public final static int BROWSER_NETSCAPE_4 = 21; + public final static int BROWSER_NETSCAPE_5 = 22; + public final static int BROWSER_NETSCAPE_6 = 23; + public final static int BROWSER_IE = 24; + public final static int BROWSER_DYNAMIDE_TEXT = 50; + + public final static String BROWSER_STRING_UNKNOWN = "*"; + public final static String BROWSER_STRING_IE = "IE"; + public final static String BROWSER_STRING_NETSCAPE_COMPATIBLE = "NS"; + + public final static String getBrowserStringFromID(int id){ + switch ( id ) { + case BROWSER_UNKNOWN : return BROWSER_STRING_UNKNOWN; + case BROWSER_IE : return BROWSER_STRING_IE; + case BROWSER_NETSCAPE_COMPATIBLE : return BROWSER_STRING_NETSCAPE_COMPATIBLE; + default: return BROWSER_STRING_UNKNOWN; + } + } + + /** Different from ServletRequest.getParameter in that this function will never return a null, always and empty string if param not found. + */ + public static String getParameterValue(HttpServletRequest request, String paramName){ + if (request == null){ + return ""; + } + String value = request.getParameter(paramName); + value = (value == null) ? "" : value; + return value; + } + + public static String getURL(HttpServletRequest request){ + if (request == null){ + return ""; + } + String qs = request.getQueryString(); + String qstr = (qs != null && qs.length() > 0) + ? "?"+qs + : ""; + return request.getRequestURI()+qstr; + } + + public static String getFullURL(HttpServletRequest request){ + return getProtoHostPort(request)+getURL(request); + } + + /** @return "http" or "https", without the "://" part. + */ + public static String getProto(HttpServletRequest request){ + if (request==null){ + return ""; + } + String prot = request.getAuthType(); + String protocol = prot != null && prot.equals("SSL") ? "https" : "http"; + return protocol; + } + + public static String getProtoHostPort(HttpServletRequest request){ + if (request==null){ + return ""; + } + String protocol = getProto(request); + int port = request.getServerPort(); + String portstr; + if ( protocol.equals("https") ) { + portstr = (port != 443) ? ":"+port : ""; + } else { + portstr = (port != 80) ? ":"+port : ""; + } + return protocol+"://"+request.getServerName()+portstr; + } + + public static String getProtoHostPort(java.net.URL url){ + if (url==null){ + return ""; + } + String protocol = url.getProtocol(); + int port = url.getPort(); + String portstr; + if ( protocol.equals("https") ) { + portstr = (port != 443) ? ":"+port : ""; + } else { + portstr = (port != 80) ? ":"+port : ""; + } + return protocol+"://"+url.getHost()+portstr; + } + + public static String decodeURLString(HttpServletRequest request, String paramName) throws UnsupportedEncodingException{ + if ( request == null ) { + return ""; + } + String value = request.getParameter(paramName); + return decodeURLString(value); + } + + public static String decodeURLString(String URLString) throws UnsupportedEncodingException{ + if ( URLString == null ) { + return ""; + } + return URLDecoder.decode(URLString, "UTF-8"); + } + + public static String encodeURLString(String s){ + return URLEncoder.encode(s); + } + + public static String dumpRequestInfo(HttpServletRequest request){ + return dumpRequestInfo(request, true, "#FFAD00", true); + } + + public static String dumpRequestInfo(HttpServletRequest request, boolean html, String headerColor, boolean dumpHeaders){ + if (request==null){ + return "NULL REQUEST"; + } + String result; + if (dumpHeaders){ + result = dumpRequestHeaders(request, html); + } else { + result = "URL: " + getFullURL(request); + } + + if ( html ) { + result = result + "\r\n
Params: "; + } else { + result = result + "\r\nParams: "; + } + result = result + dumpRequestParams(request, html, headerColor); + return result; + } + + public static String dumpRequestHeaders(HttpServletRequest request, boolean html){ + if (request==null){ + return "NULL REQUEST"; + } + String headers = ""; + String nl = html ? "\r\n
" : "\r\n"; + for(Enumeration headernames = request.getHeaderNames(); headernames.hasMoreElements();){ + String headername = (String)headernames.nextElement(); + headers += nl + headername+": "+request.getHeader(headername); + } + String result; + if ( html ) { + result = "
";
+        } else {
+            result = "";
+        }
+        result = result + "\r\nHeaders: "+ headers
+          +"\r\nmethod: " + request.getMethod()
+          +"\r\nProtocol: " + getProto(request)
+          +"\r\nURL: " +  getFullURL(request);
+          //+"\r\nQuery String: " +  getQueryString()
+          //+"\r\nContent: " + getContent();
+          if ( html ) {
+            result = result + "
"; + } + return result; + } + + public static String dumpRequestParams(HttpServletRequest request){ + return dumpRequestParams(request, true, "#FFAD00"); + } + public static String dumpRequestParams(HttpServletRequest request, boolean html, String headerColor){ + if (request==null){ + return "NULL REQUEST"; + } + StringBuffer result = new StringBuffer(); + if (html) result.append( "\n" + + "\n" + + ""); + Enumeration paramNames = request.getParameterNames(); + while(paramNames.hasMoreElements()) { + String paramName = (String)paramNames.nextElement(); + + if (html) result.append("\r\n\r\n"); + else result.append("\r\n"); + } + if (html) result.append("
Parameter NameParameter Value(s)
" + paramName + "\r\n"); + else result.append(paramName).append("="); + + String[] paramValues = request.getParameterValues(paramName); + if (paramValues.length == 1) { + String paramValue = paramValues[0]; + if (paramValue.length() == 0){ + if (html) result.append("No Value"); + else result.append("\"\""); + } else { + if (html) result.append(paramValue); + else result.append('\"'+paramValue+'\"'); + } + } else { + if (html) result.append("
    "); + for(int i=0; i" + paramValues[i]+""); + else result.append('\"'+paramValues[i]+'\"'); + } + if (html) result.append("
"); + } + if (html) result.append("
"); + return result.toString(); + } + + + + public static class UserIDPassword { + public String user_id = ""; + public String password = ""; + } + + /* + + public String getUserName(){ + String remoteUserName = getRemoteUser().user_id; + if (remoteUserName.length() > 0){ + return remoteUserName; + } else { + String name = getFieldValue("USER"); + if ( name != null && name.length()>0 ) { + return name; + } + } + return ""; + } + */ + public static UserIDPassword getRemoteUser(HttpServletRequest request){ + return getRemoteUser(request.getHeader("Authorization")); + } + + protected static UserIDPassword getRemoteUser(String authString){ + UserIDPassword uip = new UserIDPassword(); + try { // Decode and decompose the Authorization headervalue + if (authString == null){ + return uip; + } + authString = authString.substring(6).trim(); + byte mydata[]; +// sun.misc.BASE64Decoder base64 = new sun.misc.BASE64Decoder(); + org.apache.commons.codec.binary.Base64 base64 = new org.apache.commons.codec.binary.Base64(); +// mydata = base64.decodeBuffer(authString); + mydata = base64.decode(authString); + String loginInfo = new String(mydata); + int index = loginInfo.indexOf(":"); + if( index != -1 ){ + uip.password = loginInfo.substring(index +1); + uip.user_id = loginInfo.substring(0, index); + } + } catch(Exception e) { + //result will have empty user name + System.out.println("ServletTools.getRemoteUser() failed to obtain Authorization info"); + } + return uip; + } + + public static String browserVersion(HttpServletRequest request){ + String agent = request.getHeader("User-Agent"); + //Examples: + //curl/7.5.1 + //Mozilla/4.0 + //Mozilla/4.08 [en] (Win95; U ;Nav) + //Mozilla/4.0 (compatible; MSIE 5.01; Windows NT; FMRCo cfg. 5.01.2.1a) + //Mozilla/4.0 (compatible; MSIE 5.01; Windows NT; FMRCo cfg. 5.01.2.1a) + if ( agent == null ) { + return "null";//don't just return "" since this value may be used in a Tcl eval, and it would then disappear. + } + int start, stop; + if ( agent.indexOf("MSIE ") > -1 ) { + start = agent.indexOf("MSIE "); + stop = agent.indexOf(";", start); + stop = stop > -1 ? stop : agent.length(); //safety + return agent.substring(start+5, stop).trim(); + } else { + start = agent.indexOf("/"); + stop = agent.indexOf(" "); + stop = stop > -1 ? stop : agent.length(); //for JSSE, there is no space: User-Agent: Java1.3.0_02 + return agent.substring(start+1, stop).trim(); + } + } + + + /** + * Mozilla/4.79 [en] (Windows NT 5.0; U) + * Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4b) Gecko/20030516 Mozilla Firebird/0.6 + * Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:0.9.4) Gecko/20011128 Netscape6/6.2.1 + * Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.3705) + */ + public static int findBrowserID(HttpServletRequest request){ + String browserString = request.getHeader("User-Agent"); + if (browserString == null) + return BROWSER_UNKNOWN; + if (browserString.indexOf("MSIE") > -1) + return BROWSER_IE4; + int iMozilla = browserString.indexOf("Mozilla"); + if (iMozilla > -1){ + String ver = browserString.substring(iMozilla + ("Mozilla/".length()) ); + int iSpace = ver.indexOf(" "); + if (iSpace>-1){ + ver = ver.substring(0, iSpace); + } + try { + Double majorminor = new Double(ver); + if (majorminor.longValue()==4){ + return BROWSER_NETSCAPE_4; + } + if (majorminor.longValue()==5){ + return BROWSER_NETSCAPE_5; + } + if (majorminor.longValue()==6){ + return BROWSER_NETSCAPE_6; + } + } catch (Exception e) { + System.out.println("ERROR: silent after catching error converting browser minor version."+browserString); + return BROWSER_NETSCAPE_COMPATIBLE; + } + return BROWSER_NETSCAPE_COMPATIBLE; + } + return BROWSER_UNKNOWN; + } + + public static boolean isBrowserIE(int bid){ + return (bid == BROWSER_IE4 || bid == BROWSER_IE) ? true : false ; + } + + public static boolean isBrowserNS4x(int bid){ + return (bid == BROWSER_NETSCAPE_4) ; + } + + public static String getCookieValue(HttpServletRequest request, String name ){ + Cookie result = findCookie(request, name); + if ( result != null ) { + return result.getValue(); + } + return ""; + } + + public static Cookie findCookie(HttpServletRequest request, String name ){ + if (request == null || name == null) { + return null; + } + Cookie [] cookies = request.getCookies(); + if ( cookies == null ) { + return null; + } + int cookies_len = cookies.length; + for (int i=0; i < cookies_len; i++) { + Cookie cookie = cookies[i]; + if (cookie != null && name.equals(cookie.getName())){ + return cookie; + } + } + return null; + } + + public static Cookie setCookie(HttpServletResponse response, String name, String value){ + return setCookie(response, name, value, "/", 365*24*60*60); + } + + public static Cookie setCookie(HttpServletResponse response, String name, String value, String path, int maxAge){ + Cookie cookie = new javax.servlet.http.Cookie(name, value); + cookie.setMaxAge(maxAge); + cookie.setPath(path); + response.addCookie(cookie); + return cookie; + } + + + +} + diff --git a/services/common/src/main/java/org/collectionspace/services/common/UriTemplate.java b/services/common/src/main/java/org/collectionspace/services/common/UriTemplate.java index 30e265a97..2fe719c98 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/UriTemplate.java +++ b/services/common/src/main/java/org/collectionspace/services/common/UriTemplate.java @@ -1,119 +1,119 @@ -/** - * 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-2012 University of California, 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; - -import java.net.URI; -import java.util.Map; -import javax.ws.rs.core.UriBuilder; -import javax.ws.rs.core.UriBuilderException; -import org.collectionspace.services.common.api.Tools; -import org.collectionspace.services.common.UriTemplateFactory.UriTemplateType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * UriTemplate.java - * - * Generates URI strings by combining a URI template with provided values, which - * replace variables within the template. - */ -public abstract class UriTemplate { - - private static final Logger logger = LoggerFactory.getLogger(UriTemplate.class); - private UriTemplateType uriTemplateType = null; - private String uriPath = ""; - private UriBuilder builder = null; - private final static String EMPTY_STRING = ""; - - - public UriTemplate(UriTemplateType type, String path) { - setUriTemplateType(type); - setUriPath(path); - setBuilder(); - } - - private void setUriTemplateType(UriTemplateType type) { - if (type != null) { - this.uriTemplateType = type; - } - } - - public UriTemplateType getUriTemplateType() { - return this.uriTemplateType; - } - - private void setUriPath(String path) { - if (Tools.notBlank(path)) { - this.uriPath = path; - } - } - - private String getUriPath() { - return this.uriPath; - } - - private void setBuilder() { - if (builder == null) { - try { - builder = UriBuilder.fromPath(getUriPath()); - } catch (IllegalArgumentException iae) { - logger.warn("URI path was null when attempting to creating new UriTemplate."); - // No other checking of path format, other than for null values, - // is performed automatically by this Exception handling. - } - } - } - - private UriBuilder getBuilder() { - if (builder == null) { - setBuilder(); - } - return builder; - } - - @Override - public String toString() { - return getUriPath(); - } - - public String buildUri(Map valuesMap) { - URI uri = null; - try { - if (valuesMap == null || valuesMap.isEmpty()) { - throw new IllegalArgumentException("Map of values for building URI string was null or empty"); - } - uri = getBuilder().buildFromMap(valuesMap); - } catch (IllegalArgumentException iae) { - logger.warn("One or more required values were missing " - + "when building URI string: " + iae.getMessage()); - } catch (UriBuilderException ube) { - logger.warn("URI string can't be constructed due to state of URIBuilder: " + ube.getMessage()); - } finally { - if (uri != null) { - return uri.toString(); - } else { - return EMPTY_STRING; - } - } - } +/** + * 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-2012 University of California, 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; + +import java.net.URI; +import java.util.Map; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriBuilderException; +import org.collectionspace.services.common.api.Tools; +import org.collectionspace.services.common.UriTemplateFactory.UriTemplateType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * UriTemplate.java + * + * Generates URI strings by combining a URI template with provided values, which + * replace variables within the template. + */ +public abstract class UriTemplate { + + private static final Logger logger = LoggerFactory.getLogger(UriTemplate.class); + private UriTemplateType uriTemplateType = null; + private String uriPath = ""; + private UriBuilder builder = null; + private final static String EMPTY_STRING = ""; + + + public UriTemplate(UriTemplateType type, String path) { + setUriTemplateType(type); + setUriPath(path); + setBuilder(); + } + + private void setUriTemplateType(UriTemplateType type) { + if (type != null) { + this.uriTemplateType = type; + } + } + + public UriTemplateType getUriTemplateType() { + return this.uriTemplateType; + } + + private void setUriPath(String path) { + if (Tools.notBlank(path)) { + this.uriPath = path; + } + } + + private String getUriPath() { + return this.uriPath; + } + + private void setBuilder() { + if (builder == null) { + try { + builder = UriBuilder.fromPath(getUriPath()); + } catch (IllegalArgumentException iae) { + logger.warn("URI path was null when attempting to creating new UriTemplate."); + // No other checking of path format, other than for null values, + // is performed automatically by this Exception handling. + } + } + } + + private UriBuilder getBuilder() { + if (builder == null) { + setBuilder(); + } + return builder; + } + + @Override + public String toString() { + return getUriPath(); + } + + public String buildUri(Map valuesMap) { + URI uri = null; + try { + if (valuesMap == null || valuesMap.isEmpty()) { + throw new IllegalArgumentException("Map of values for building URI string was null or empty"); + } + uri = getBuilder().buildFromMap(valuesMap); + } catch (IllegalArgumentException iae) { + logger.warn("One or more required values were missing " + + "when building URI string: " + iae.getMessage()); + } catch (UriBuilderException ube) { + logger.warn("URI string can't be constructed due to state of URIBuilder: " + ube.getMessage()); + } finally { + if (uri != null) { + return uri.toString(); + } else { + return EMPTY_STRING; + } + } + } } \ No newline at end of file diff --git a/services/common/src/main/java/org/collectionspace/services/common/UriTemplateFactory.java b/services/common/src/main/java/org/collectionspace/services/common/UriTemplateFactory.java index 4876c15b5..183be45b1 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/UriTemplateFactory.java +++ b/services/common/src/main/java/org/collectionspace/services/common/UriTemplateFactory.java @@ -1,100 +1,100 @@ -/** - * 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-2012 University of California, 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; - -import java.util.Map; -import org.collectionspace.services.client.AuthorityClient; - -/** - * UriTemplateFactory.java - * - * A factory for building instances of subclasses of URITemplate, based on a - * provided template type. - */ -public class UriTemplateFactory { - - // For coding convenience, each item in the enum is also available as a field - // in the enclosing class. - public final static UriTemplateType RESOURCE = UriTemplateType.RESOURCE; - public final static UriTemplateType ITEM = UriTemplateType.ITEM; - public final static UriTemplateType CONTACT = UriTemplateType.CONTACT; - - public enum UriTemplateType { - - RESOURCE, ITEM, CONTACT - }; - - public final static String SERVICENAME_VAR = "servicename"; - public final static String IDENTIFIER_VAR = "identifier"; - public final static String ITEM_IDENTIFIER_VAR = "itemIdentifier"; - public final static String CONTACT_IDENTIFIER_VAR = "contactIdentifier"; - - public final static String AUTHORITY_ITEM_PATH_COMPONENT = AuthorityClient.ITEMS; - // FIXME: Get this currently hard-coded value from an external authoritative source. - // The only candidate so far identified is ContactClient.SERVICE_PATH_COMPONENT; - // is this appropriate? - public final static String CONTACT_PATH_COMPONENT = "contacts"; - - public final static String RESOURCE_PATH_PATTERN = - "/" - + "{" + SERVICENAME_VAR + "}" - + "/" - + "{" + IDENTIFIER_VAR + "}"; - public final static String ITEM_PATH_PATTERN = - RESOURCE_PATH_PATTERN - + "/" - + AUTHORITY_ITEM_PATH_COMPONENT - + "/" - + "{" + ITEM_IDENTIFIER_VAR + "}"; - public final static String CONTACT_PATH_PATTERN = - ITEM_PATH_PATTERN - + "/" - + CONTACT_PATH_COMPONENT - + "/" - + "{" + CONTACT_IDENTIFIER_VAR + "}"; - - public static StoredValuesUriTemplate getURITemplate(UriTemplateType type) { - return new StoredValuesUriTemplate(type, getUriPathPattern(type)); - } - - public static StoredValuesUriTemplate getURITemplate(UriTemplateType type, Map storedValuesMap) { - return new StoredValuesUriTemplate(type, getUriPathPattern(type), storedValuesMap); - } - - private static String getUriPathPattern(UriTemplateType type) { - switch (type) { - case RESOURCE: - return RESOURCE_PATH_PATTERN; - - case ITEM: - return ITEM_PATH_PATTERN; - - case CONTACT: - return CONTACT_PATH_PATTERN; - - default: - return RESOURCE_PATH_PATTERN; - } - } - +/** + * 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-2012 University of California, 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; + +import java.util.Map; +import org.collectionspace.services.client.AuthorityClient; + +/** + * UriTemplateFactory.java + * + * A factory for building instances of subclasses of URITemplate, based on a + * provided template type. + */ +public class UriTemplateFactory { + + // For coding convenience, each item in the enum is also available as a field + // in the enclosing class. + public final static UriTemplateType RESOURCE = UriTemplateType.RESOURCE; + public final static UriTemplateType ITEM = UriTemplateType.ITEM; + public final static UriTemplateType CONTACT = UriTemplateType.CONTACT; + + public enum UriTemplateType { + + RESOURCE, ITEM, CONTACT + }; + + public final static String SERVICENAME_VAR = "servicename"; + public final static String IDENTIFIER_VAR = "identifier"; + public final static String ITEM_IDENTIFIER_VAR = "itemIdentifier"; + public final static String CONTACT_IDENTIFIER_VAR = "contactIdentifier"; + + public final static String AUTHORITY_ITEM_PATH_COMPONENT = AuthorityClient.ITEMS; + // FIXME: Get this currently hard-coded value from an external authoritative source. + // The only candidate so far identified is ContactClient.SERVICE_PATH_COMPONENT; + // is this appropriate? + public final static String CONTACT_PATH_COMPONENT = "contacts"; + + public final static String RESOURCE_PATH_PATTERN = + "/" + + "{" + SERVICENAME_VAR + "}" + + "/" + + "{" + IDENTIFIER_VAR + "}"; + public final static String ITEM_PATH_PATTERN = + RESOURCE_PATH_PATTERN + + "/" + + AUTHORITY_ITEM_PATH_COMPONENT + + "/" + + "{" + ITEM_IDENTIFIER_VAR + "}"; + public final static String CONTACT_PATH_PATTERN = + ITEM_PATH_PATTERN + + "/" + + CONTACT_PATH_COMPONENT + + "/" + + "{" + CONTACT_IDENTIFIER_VAR + "}"; + + public static StoredValuesUriTemplate getURITemplate(UriTemplateType type) { + return new StoredValuesUriTemplate(type, getUriPathPattern(type)); + } + + public static StoredValuesUriTemplate getURITemplate(UriTemplateType type, Map storedValuesMap) { + return new StoredValuesUriTemplate(type, getUriPathPattern(type), storedValuesMap); + } + + private static String getUriPathPattern(UriTemplateType type) { + switch (type) { + case RESOURCE: + return RESOURCE_PATH_PATTERN; + + case ITEM: + return ITEM_PATH_PATTERN; + + case CONTACT: + return CONTACT_PATH_PATTERN; + + default: + return RESOURCE_PATH_PATTERN; + } + } + } \ No newline at end of file diff --git a/services/common/src/main/java/org/collectionspace/services/common/UriTemplateRegistry.java b/services/common/src/main/java/org/collectionspace/services/common/UriTemplateRegistry.java index 9d438b3c0..ed2075959 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/UriTemplateRegistry.java +++ b/services/common/src/main/java/org/collectionspace/services/common/UriTemplateRegistry.java @@ -1,64 +1,64 @@ -/** - * 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-2012 University of California, 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; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import org.collectionspace.services.common.UriTemplateRegistryKey; - -/** - * UriTemplateRegistry.java - * - * Maps document types to templates for building URIs, per tenant. - */ -public class UriTemplateRegistry extends HashMap { - - /** - * Dumps all registry settings for debugging purposes. - */ - public void dump() { - System.out.println(this.toString()); - } - - /** - * Dumps all registry settings for debugging purposes. - * @return a String representation of the URI Template Registry settings - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(""); - for (Map.Entry uriTemplateEntry : this.entrySet()) { - sb.append("Tenant : DocType = "); - sb.append(uriTemplateEntry.getKey().getTenantId()); - sb.append(" : "); - sb.append(uriTemplateEntry.getKey().getDocType()); - sb.append('\n'); - sb.append(" Value of Template = "); - sb.append(" "); - sb.append(uriTemplateEntry.getValue().toString()); - sb.append('\n'); - } - return sb.toString(); - } -} +/** + * 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-2012 University of California, 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; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import org.collectionspace.services.common.UriTemplateRegistryKey; + +/** + * UriTemplateRegistry.java + * + * Maps document types to templates for building URIs, per tenant. + */ +public class UriTemplateRegistry extends HashMap { + + /** + * Dumps all registry settings for debugging purposes. + */ + public void dump() { + System.out.println(this.toString()); + } + + /** + * Dumps all registry settings for debugging purposes. + * @return a String representation of the URI Template Registry settings + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(""); + for (Map.Entry uriTemplateEntry : this.entrySet()) { + sb.append("Tenant : DocType = "); + sb.append(uriTemplateEntry.getKey().getTenantId()); + sb.append(" : "); + sb.append(uriTemplateEntry.getKey().getDocType()); + sb.append('\n'); + sb.append(" Value of Template = "); + sb.append(" "); + sb.append(uriTemplateEntry.getValue().toString()); + sb.append('\n'); + } + return sb.toString(); + } +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/XmlSaxFragmenter.java b/services/common/src/main/java/org/collectionspace/services/common/XmlSaxFragmenter.java index b7973c1cc..c5a5a40e1 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/XmlSaxFragmenter.java +++ b/services/common/src/main/java/org/collectionspace/services/common/XmlSaxFragmenter.java @@ -1,309 +1,309 @@ -/** - * 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 2011 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; - -import org.collectionspace.services.common.api.Tools; -import org.dom4j.Document; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.io.HTMLWriter; -import org.dom4j.io.OutputFormat; -import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; -import org.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.Locator; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; -import org.xml.sax.ext.Locator2; -import java.io.StringWriter; - -/** Use XmlSaxFragmenter to parse a large file or InputSource (stream) - * with SAX, and pass in an instance of IFragmentHandler to parse() so that you can - * get fragments back that you can parse with DOM or other processing. - * - * You would typically instantiate and run this class like so: - * - * IFragmentHandler callback = new MyFragmentHandlerImpl(); //define the interface somewhere. - * XmlSaxFragmenter.parse("C:\\tmp\\imports.xml", "/document/schema", callback); - * - * Then, given an XML document like this: - * <document repository="default" id="123"> - * <schema name="collectionobjects_naturalhistory"> - * <nh-int/> - * <nh-note/> - * </schema> - * <schema name="collectionobjects_common"> - * <distinguishingFeatures/> - * </schema> - * </document> - * - * you'll get two onFragmentReady() events: the first will pass String fragment = - * <schema name="collectionobjects_naturalhistory"> <nh-int/> - * <nh-note/> - * plus some context information, and the second will pass String fragment = - * <distinguishingFeatures/> - * - * - * @author Laramie Crocker - */ -public class XmlSaxFragmenter implements ContentHandler, ErrorHandler { - - //=============== ContentHandler ==================================================== - - public void setDocumentLocator(Locator locator) { - if (xmlDeclarationDone){ - return; - } - if (locator instanceof Locator2){ - Locator2 l2 = ((Locator2) locator); - String enc = l2.getEncoding(); - String ver = l2.getXMLVersion(); - append("\r\n"); - xmlDeclarationDone = true; - } else { - //System.err.println("Locator2 not found."); - append("\r\n"); - xmlDeclarationDone = true; - } - //more info available from Locator if needed: locator.getPublicId(), locator.getSystemId(); - } - - public void startDocument() throws SAXException { - document = DocumentHelper.createDocument(); - } - - public void endDocument() throws SAXException { - if (fragmentHandler!=null) { - fragmentHandler.onEndDocument(document, fragmentIndex + 1); - } - } - - public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { - String attsString = attsToStr(atts); - append("<" + name(qName, localName) + attsString + ">"); - if (inFragment){ - inFragmentDepth++; - return; - } - if (currentElement == null){ - currentElement = document.addElement(qName); - } else { - Element element = DocumentHelper.createElement(qName); - currentElement.add(element); - previousElement = currentElement; - currentElement = element; - } - addAttributes(currentElement, atts); - String currentPath = currentElement.getPath(); - if (currentPath.equals(chopPath)){ - buffer = new StringBuffer(); - inFragment = true; - if (includeParent){ - append("<" + name(qName, localName) + attsString + ">"); - } - } - } - - public void endElement(String uri, String localName, String qName) throws SAXException { - if (inFragment && (inFragmentDepth>0)){ - append("'); - } else if (inFragment && inFragmentDepth == 0 && includeParent){ - append("'); - } - if (inFragment && (inFragmentDepth==0)){ - if (fragmentHandler!=null) { - fragmentIndex++; - fragmentHandler.onFragmentReady(document, - currentElement, - currentElement.getPath(), - fragmentIndex, - buffer.toString()); - } - inFragment = false; - currentElement = previousElement; - } - if (inFragment){ - inFragmentDepth--; - } - } - - public void characters(char ch[], int start, int length) throws SAXException { - String chars = new String(ch, start, length); - append(chars); - } - - public void startPrefixMapping(String prefix, String uri) throws SAXException { - } - public void endPrefixMapping(String prefix) throws SAXException { - } - public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { - } - public void processingInstruction(String target, String data) throws SAXException { - } - public void skippedEntity(String name) throws SAXException { - } - - //=============== ErrorHandler ==================================================== - - public void error(SAXParseException exception){ - System.err.println("ERROR:"+exception); - } - public void fatalError(SAXParseException exception){ - System.err.println("FATAL_ERROR:"+exception); - } - public void warning(SAXParseException exception){ - System.err.println("WARNING:"+exception); - } - - //================ Helper Methods =================================================== - - private Document document; - private Element currentElement; - private Element previousElement; - private StringBuffer buffer = new StringBuffer(); - - private boolean xmlDeclarationDone = false; - private boolean inFragment = false; - private int inFragmentDepth = 0; - private int fragmentIndex = -1; //zero-based. Used for informational purposes only, to report to the IFragmentHandler. - - private String chopPath = ""; - public String getChopPath() { - return chopPath; - } - /** You should not set the chopPath directly; instead you must set it in the call to parse(). */ - protected void setChopPath(String chopPath) { - this.chopPath = chopPath; - } - - private boolean includeParent = false; - public boolean isIncludeParent() { - return includeParent; - } - public void setIncludeParent(boolean includeParent) { - this.includeParent = includeParent; - } - - - private IFragmentHandler fragmentHandler; - public IFragmentHandler getFragmentHandler() { - return fragmentHandler; - } - /** You should not set the FragmentHandler directly; instead you must set it in the call to parse(). */ - protected void setFragmentHandler(IFragmentHandler fragmentHandler) { - this.fragmentHandler = fragmentHandler; - } - - protected void append(String str){ - buffer.append(str); - } - - protected String name(String qn, String ln){ - if (Tools.isEmpty(qn)){ - return ln; - } - if (qn.equals(ln)){ - return ln; - } - return qn; - } - - //NOTE: we don't deal with this here because we don't need to - // actually understand the namespace uri: - // a.getURI(i) - protected String attsToStr(Attributes a){ - StringBuffer b = new StringBuffer(); - String qn, ln; - int attsLen = a.getLength(); - for (int i=0; i + * <schema name="collectionobjects_naturalhistory"> + * <nh-int/> + * <nh-note/> + * </schema> + * <schema name="collectionobjects_common"> + * <distinguishingFeatures/> + * </schema> + * </document> + * + * you'll get two onFragmentReady() events: the first will pass String fragment = + * <schema name="collectionobjects_naturalhistory"> <nh-int/> + * <nh-note/> + * plus some context information, and the second will pass String fragment = + * <distinguishingFeatures/> + * + * + * @author Laramie Crocker + */ +public class XmlSaxFragmenter implements ContentHandler, ErrorHandler { + + //=============== ContentHandler ==================================================== + + public void setDocumentLocator(Locator locator) { + if (xmlDeclarationDone){ + return; + } + if (locator instanceof Locator2){ + Locator2 l2 = ((Locator2) locator); + String enc = l2.getEncoding(); + String ver = l2.getXMLVersion(); + append("\r\n"); + xmlDeclarationDone = true; + } else { + //System.err.println("Locator2 not found."); + append("\r\n"); + xmlDeclarationDone = true; + } + //more info available from Locator if needed: locator.getPublicId(), locator.getSystemId(); + } + + public void startDocument() throws SAXException { + document = DocumentHelper.createDocument(); + } + + public void endDocument() throws SAXException { + if (fragmentHandler!=null) { + fragmentHandler.onEndDocument(document, fragmentIndex + 1); + } + } + + public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { + String attsString = attsToStr(atts); + append("<" + name(qName, localName) + attsString + ">"); + if (inFragment){ + inFragmentDepth++; + return; + } + if (currentElement == null){ + currentElement = document.addElement(qName); + } else { + Element element = DocumentHelper.createElement(qName); + currentElement.add(element); + previousElement = currentElement; + currentElement = element; + } + addAttributes(currentElement, atts); + String currentPath = currentElement.getPath(); + if (currentPath.equals(chopPath)){ + buffer = new StringBuffer(); + inFragment = true; + if (includeParent){ + append("<" + name(qName, localName) + attsString + ">"); + } + } + } + + public void endElement(String uri, String localName, String qName) throws SAXException { + if (inFragment && (inFragmentDepth>0)){ + append("'); + } else if (inFragment && inFragmentDepth == 0 && includeParent){ + append("'); + } + if (inFragment && (inFragmentDepth==0)){ + if (fragmentHandler!=null) { + fragmentIndex++; + fragmentHandler.onFragmentReady(document, + currentElement, + currentElement.getPath(), + fragmentIndex, + buffer.toString()); + } + inFragment = false; + currentElement = previousElement; + } + if (inFragment){ + inFragmentDepth--; + } + } + + public void characters(char ch[], int start, int length) throws SAXException { + String chars = new String(ch, start, length); + append(chars); + } + + public void startPrefixMapping(String prefix, String uri) throws SAXException { + } + public void endPrefixMapping(String prefix) throws SAXException { + } + public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { + } + public void processingInstruction(String target, String data) throws SAXException { + } + public void skippedEntity(String name) throws SAXException { + } + + //=============== ErrorHandler ==================================================== + + public void error(SAXParseException exception){ + System.err.println("ERROR:"+exception); + } + public void fatalError(SAXParseException exception){ + System.err.println("FATAL_ERROR:"+exception); + } + public void warning(SAXParseException exception){ + System.err.println("WARNING:"+exception); + } + + //================ Helper Methods =================================================== + + private Document document; + private Element currentElement; + private Element previousElement; + private StringBuffer buffer = new StringBuffer(); + + private boolean xmlDeclarationDone = false; + private boolean inFragment = false; + private int inFragmentDepth = 0; + private int fragmentIndex = -1; //zero-based. Used for informational purposes only, to report to the IFragmentHandler. + + private String chopPath = ""; + public String getChopPath() { + return chopPath; + } + /** You should not set the chopPath directly; instead you must set it in the call to parse(). */ + protected void setChopPath(String chopPath) { + this.chopPath = chopPath; + } + + private boolean includeParent = false; + public boolean isIncludeParent() { + return includeParent; + } + public void setIncludeParent(boolean includeParent) { + this.includeParent = includeParent; + } + + + private IFragmentHandler fragmentHandler; + public IFragmentHandler getFragmentHandler() { + return fragmentHandler; + } + /** You should not set the FragmentHandler directly; instead you must set it in the call to parse(). */ + protected void setFragmentHandler(IFragmentHandler fragmentHandler) { + this.fragmentHandler = fragmentHandler; + } + + protected void append(String str){ + buffer.append(str); + } + + protected String name(String qn, String ln){ + if (Tools.isEmpty(qn)){ + return ln; + } + if (qn.equals(ln)){ + return ln; + } + return qn; + } + + //NOTE: we don't deal with this here because we don't need to + // actually understand the namespace uri: + // a.getURI(i) + protected String attsToStr(Attributes a){ + StringBuffer b = new StringBuffer(); + String qn, ln; + int attsLen = a.getLength(); + for (int i=0; i pas = new ArrayList(); - perm.setAction(pas); - for (ActionType actionType : actionGroup.actions) { - PermissionAction permAction = createPermissionAction(perm, actionType); - pas.add(permAction); - } - - return perm; - } - - private static Permission createWorkflowPermission(TenantBindingType tenantBinding, - ServiceBindingType serviceBinding, - TransitionDef transitionDef, - ActionGroup actionGroup) - { - Permission result = null; - String workFlowServiceSuffix; - String transitionName; - if (transitionDef != null) { - transitionName = transitionDef.getName(); - workFlowServiceSuffix = WorkflowClient.SERVICE_AUTHZ_SUFFIX; - } else { - transitionName = ""; //since the transitionDef was null, we're assuming that this is the base workflow permission to be created - workFlowServiceSuffix = WorkflowClient.SERVICE_PATH; - } - - String tenantId = tenantBinding.getId(); - String resourceName = "/" - + serviceBinding.getName().toLowerCase().trim() - + workFlowServiceSuffix - + transitionName; - String description = "A generated workflow permission for actiongroup " + actionGroup.name; - result = createPermission(tenantId, resourceName, description, actionGroup); - - if (logger.isDebugEnabled() == true) { - logger.debug("Generated a workflow permission: " - + result.getResourceName() - + ":" + transitionName - + ":" + "tenant id=" + result.getTenantId() - + ":" + actionGroup.name); - } - - return result; - } - - private static PermissionRole createPermissionRole(EntityManager em, - Permission permission, - Role role, - boolean enforceTenancy) throws Exception - { - PermissionRole permRole = new PermissionRole(); - // Check to see if the tenant ID of the permission and the tenant ID of the role match - boolean tenantIdsMatch = role.getTenantId().equalsIgnoreCase(permission.getTenantId()); - if (tenantIdsMatch == false && enforceTenancy == false) { - tenantIdsMatch = true; // If we don't need to enforce tenancy then we'll just consider them matched. - } - - if (tenantIdsMatch == true) { - permRole.setSubject(SubjectType.ROLE); - // - // Set of the permission value list of the permrole - // - List permValues = new ArrayList(); - PermissionValue permValue = new PermissionValue(); - permValue.setPermissionId(permission.getCsid()); - permValue.setResourceName(permission.getResourceName().toLowerCase()); - permValue.setActionGroup(permission.getActionGroup()); - permValues.add(permValue); - permRole.setPermission(permValues); - // - // Set of the role value list of the permrole - // - List roleValues = new ArrayList(); - RoleValue rv = new RoleValue(); - // This needs to use the qualified name, not the display name - rv.setRoleName(role.getRoleName()); - rv.setRoleId(role.getCsid()); - roleValues.add(rv); - permRole.setRole(roleValues); - } else { - String errMsg = "The tenant ID of the role: " + role.getTenantId() - + " did not match the tenant ID of the permission: " + permission.getTenantId(); - throw new Exception(errMsg); - } - - return permRole; - } - - private static Hashtable getTenantNamesFromConfig(TenantBindingConfigReaderImpl tenantBindingConfigReader) { - - // Note that this only handles tenants not marked as "createDisabled" - Hashtable tenantBindings = - tenantBindingConfigReader.getTenantBindings(); - Hashtable tenantInfo = new Hashtable(); - for (TenantBindingType tenantBinding : tenantBindings.values()) { - String tId = tenantBinding.getId(); - String tName = tenantBinding.getName(); - tenantInfo.put(tId, tName); - if (logger.isDebugEnabled()) { - logger.debug("getTenantNamesFromConfig found configured tenant id: "+tId+" name: "+tName); - } - } - return tenantInfo; - } - - private static ArrayList compileExistingTenants(Connection conn, Hashtable tenantInfo) - throws SQLException, Exception { - Statement stmt = null; - ArrayList existingTenants = new ArrayList(); - // First find or create the tenants - final String queryTenantSQL = "SELECT id,name FROM tenants"; - try { - stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery(queryTenantSQL); - while (rs.next()) { - String tId = rs.getString("id"); - String tName = rs.getString("name"); - if(tenantInfo.containsKey(tId)) { - existingTenants.add(tId); - if(!tenantInfo.get(tId).equalsIgnoreCase(tName)) { - logger.warn("Configured name for tenant: " - +tId+" in repository: "+tName - +" does not match config'd name: "+ tenantInfo.get(tId)); - } - } - } - rs.close(); - } catch(Exception e) { - throw e; - } finally { - if(stmt!=null) - stmt.close(); - } - - return existingTenants; - } - - private static void createMissingTenants(Connection conn, Hashtable tenantInfo, - ArrayList existingTenants) throws SQLException, Exception { - // Need to define and look for a createDisabled attribute in tenant config - final String insertTenantSQL = - "INSERT INTO tenants (id,name,disabled,created_at) VALUES (?,?,FALSE,now())"; - PreparedStatement pstmt = null; - try { - pstmt = conn.prepareStatement(insertTenantSQL); // create a statement - for(String tId : tenantInfo.keySet()) { - if(existingTenants.contains(tId)) { - if (logger.isDebugEnabled()) { - logger.debug("createMissingTenants: tenant exists (skipping): " - +tenantInfo.get(tId)); - } - continue; - } - pstmt.setString(1, tId); // set id param - pstmt.setString(2, tenantInfo.get(tId)); // set name param - if (logger.isDebugEnabled()) { - logger.debug("createMissingTenants adding entry for tenant: "+tId); - } - pstmt.executeUpdate(); - } - pstmt.close(); - } catch(Exception e) { - throw e; - } finally { - if(pstmt!=null) - pstmt.close(); - } - } - - private static ArrayList findOrCreateDefaultUsers(Connection conn, Hashtable tenantInfo) - throws SQLException, Exception { - // Second find or create the users - Statement stmt = null; - PreparedStatement pstmt = null; - ArrayList usersInRepo = new ArrayList(); - try { - stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery(QUERY_USERS_SQL); - while (rs.next()) { - String uName = rs.getString("username"); - usersInRepo.add(uName); - } - rs.close(); - pstmt = conn.prepareStatement(INSERT_USER_SQL); // create a statement - for(String tName : tenantInfo.values()) { - String adminAcctName = getDefaultAdminUserID(tName); - if(!usersInRepo.contains(adminAcctName)) { - String secEncPasswd = SecurityUtils.createPasswordHash( - adminAcctName, DEFAULT_ADMIN_PASSWORD); - pstmt.setString(1, adminAcctName); // set username param - pstmt.setString(2, secEncPasswd); // set passwd param - if (logger.isDebugEnabled()) { - logger.debug("createDefaultUsersAndAccounts adding user: " - +adminAcctName+" for tenant: "+tName); - } - pstmt.executeUpdate(); - } else if (logger.isDebugEnabled()) { - logger.debug("createDefaultUsersAndAccounts: user: "+adminAcctName - +" already exists - skipping."); - } - - - String readerAcctName = getDefaultReaderUserID(tName); - if(!usersInRepo.contains(readerAcctName)) { - String secEncPasswd = SecurityUtils.createPasswordHash( - readerAcctName, DEFAULT_READER_PASSWORD); - pstmt.setString(1, readerAcctName); // set username param - pstmt.setString(2, secEncPasswd); // set passwd param - if (logger.isDebugEnabled()) { - logger.debug("createDefaultUsersAndAccounts adding user: " - +readerAcctName+" for tenant: "+tName); - } - pstmt.executeUpdate(); - } else if (logger.isDebugEnabled()) { - logger.debug("createDefaultUsersAndAccounts: user: "+readerAcctName - +" already exists - skipping."); - } - } - pstmt.close(); - } catch(Exception e) { - throw e; - } finally { - if(stmt!=null) - stmt.close(); - if(pstmt!=null) - pstmt.close(); - } - return usersInRepo; - } - - private static void findOrCreateDefaultAccounts(Connection conn, Hashtable tenantInfo, - ArrayList usersInRepo, - Hashtable tenantAdminAcctCSIDs, Hashtable tenantReaderAcctCSIDs) - throws SQLException, Exception { - // Third, create the accounts. Assume that if the users were already there, - // then the accounts were as well - PreparedStatement pstmt = null; - try { - pstmt = conn.prepareStatement(INSERT_ACCOUNT_SQL); // create a statement - for(String tId : tenantInfo.keySet()) { - String tName = tenantInfo.get(tId); - String adminCSID = UUID.randomUUID().toString(); - tenantAdminAcctCSIDs.put(tId, adminCSID); - String adminAcctName = getDefaultAdminUserID(tName); - if(!usersInRepo.contains(adminAcctName)) { - pstmt.setString(1, adminCSID); // set csid param - pstmt.setString(2, adminAcctName); // set email param (bogus) - pstmt.setString(3, adminAcctName); // set userid param - pstmt.setString(4, "Administrator");// set screen name param - if (logger.isDebugEnabled()) { - logger.debug("createDefaultAccounts adding account: " - +adminAcctName+" for tenant: "+tName); - } - pstmt.executeUpdate(); - } else if (logger.isDebugEnabled()) { - logger.debug("createDefaultAccounts: user: "+adminAcctName - +" already exists - skipping account generation."); - } - - String readerCSID = UUID.randomUUID().toString(); - tenantReaderAcctCSIDs.put(tId, readerCSID); - String readerAcctName = getDefaultReaderUserID(tName); - if(!usersInRepo.contains(readerAcctName)) { - pstmt.setString(1, readerCSID); // set csid param - pstmt.setString(2, readerAcctName); // set email param (bogus) - pstmt.setString(3, readerAcctName); // set userid param - pstmt.setString(4, "Reader"); // set screen name param - if (logger.isDebugEnabled()) { - logger.debug("createDefaultAccounts adding account: " - +readerAcctName+" for tenant: "+tName); - } - pstmt.executeUpdate(); - } else if (logger.isDebugEnabled()) { - logger.debug("createDefaultAccounts: user: "+readerAcctName - +" already exists - skipping account creation."); - } - } - pstmt.close(); - } catch(Exception e) { - throw e; - } finally { - if(pstmt!=null) - pstmt.close(); - } - } - - private static boolean findOrCreateTenantManagerUserAndAccount(Connection conn) - throws SQLException, Exception { - // Find or create the special tenant manager account. - // Later can make the user name for tenant manager be configurable, settable. - Statement stmt = null; - PreparedStatement pstmt = null; - boolean created = false; - try { - boolean foundTMgrUser = false; - stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery(QUERY_TENANT_MGR_USER_SQL); - // Should only find one - only consider it - if(rs.next()) { - String uName = rs.getString("username"); - foundTMgrUser = uName.equals(TENANT_MANAGER_USER); - } - rs.close(); - if(!foundTMgrUser) { - pstmt = conn.prepareStatement(INSERT_USER_SQL); // create a statement - String secEncPasswd = SecurityUtils.createPasswordHash( - TENANT_MANAGER_USER, DEFAULT_TENANT_MANAGER_PASSWORD); - pstmt.setString(1, TENANT_MANAGER_USER); // set username param - pstmt.setString(2, secEncPasswd); // set passwd param - if (logger.isDebugEnabled()) { - logger.debug("findOrCreateTenantManagerUserAndAccount adding tenant manager user: " - +TENANT_MANAGER_USER); - } - pstmt.executeUpdate(); - pstmt.close(); - // Now create the account to match - pstmt = conn.prepareStatement(INSERT_ACCOUNT_SQL); // create a statement - pstmt.setString(1, AuthN.TENANT_MANAGER_ACCT_ID); // set csid param - pstmt.setString(2, DEFAULT_TENANT_MANAGER_EMAIL); // set email param (bogus) - pstmt.setString(3, TENANT_MANAGER_USER); // set userid param - pstmt.setString(4, TENANT_MANAGER_SCREEN_NAME);// set screen name param - if (logger.isDebugEnabled()) { - logger.debug("findOrCreateTenantManagerUserAndAccount adding tenant manager account: " - +TENANT_MANAGER_USER); - } - pstmt.executeUpdate(); - pstmt.close(); - created = true; - } else if (logger.isDebugEnabled()) { - logger.debug("findOrCreateTenantManagerUserAndAccount: tenant manager: "+TENANT_MANAGER_USER - +" already exists."); - } - } catch(Exception e) { - throw e; - } finally { - if(stmt!=null) - stmt.close(); - if(pstmt!=null) - pstmt.close(); - } - return created; - } - - private static void bindDefaultAccountsToTenants(Connection conn, DatabaseProductType databaseProductType, - Hashtable tenantInfo, ArrayList usersInRepo, - Hashtable tenantAdminAcctCSIDs, Hashtable tenantReaderAcctCSIDs) - throws SQLException, Exception { - // Fourth, bind accounts to tenants. Assume that if the users were already there, - // then the accounts were bound to tenants correctly - PreparedStatement pstmt = null; - try { - String insertAccountTenantSQL; - if (databaseProductType == DatabaseProductType.MYSQL) { - insertAccountTenantSQL = - "INSERT INTO accounts_tenants (TENANTS_ACCOUNTSCOMMON_CSID,tenant_id) " - + " VALUES(?, ?)"; - } else if (databaseProductType == DatabaseProductType.POSTGRESQL) { - insertAccountTenantSQL = - "INSERT INTO accounts_tenants (HJID, TENANTS_ACCOUNTSCOMMON_CSID,tenant_id) " - + " VALUES(nextval('hibernate_sequence'), ?, ?)"; - } else { - throw new Exception("Unrecognized database system."); - } - pstmt = conn.prepareStatement(insertAccountTenantSQL); // create a statement - for(String tId : tenantInfo.keySet()) { - String tName = tenantInfo.get(tId); - if(!usersInRepo.contains(getDefaultAdminUserID(tName))) { - String adminAcct = tenantAdminAcctCSIDs.get(tId); - pstmt.setString(1, adminAcct); // set acct CSID param - pstmt.setString(2, tId); // set tenant_id param - if (logger.isDebugEnabled()) { - logger.debug("createDefaultAccounts binding account id: " - +adminAcct+" to tenant id: "+tId); - } - pstmt.executeUpdate(); - } - if(!usersInRepo.contains(getDefaultReaderUserID(tName))) { - String readerAcct = tenantReaderAcctCSIDs.get(tId); - pstmt.setString(1, readerAcct); // set acct CSID param - pstmt.setString(2, tId); // set tenant_id param - if (logger.isDebugEnabled()) { - logger.debug("createDefaultAccounts binding account id: " - +readerAcct+" to tenant id: "+tId); - } - pstmt.executeUpdate(); - } - } - pstmt.close(); - } catch(Exception e) { - throw e; - } finally { - if(pstmt!=null) - pstmt.close(); - } - } - - - private static String findOrCreateDefaultRoles(Connection conn, Hashtable tenantInfo, - Hashtable tenantAdminRoleCSIDs, Hashtable tenantReaderRoleCSIDs) - throws SQLException, Exception { - // Fifth, fetch and save the default roles - String springAdminRoleCSID = null; - Statement stmt = null; - PreparedStatement pstmt = null; - try { - final String querySpringRole = - "SELECT csid from roles WHERE rolename='"+SPRING_ADMIN_ROLE+"'"; - stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery(querySpringRole); - if(rs.next()) { - springAdminRoleCSID = rs.getString(1); - if (logger.isDebugEnabled()) { - logger.debug("createDefaultAccounts found Spring Admin role: " - +springAdminRoleCSID); - } - } else { - final String insertSpringAdminRoleSQL = - "INSERT INTO roles (csid, rolename, displayName, rolegroup, created_at, tenant_id) " - + "VALUES ('-1', 'ROLE_SPRING_ADMIN', 'SPRING_ADMIN', 'Spring Security Administrator', now(), '0')"; - stmt.executeUpdate(insertSpringAdminRoleSQL); - springAdminRoleCSID = "-1"; - if (logger.isDebugEnabled()) { - logger.debug("createDefaultAccounts CREATED Spring Admin role: " - +springAdminRoleCSID); - } - } - rs.close(); - final String getRoleCSIDSql = - "SELECT csid from roles WHERE tenant_id=? and rolename=?"; - pstmt = conn.prepareStatement(getRoleCSIDSql); // create a statement - rs = null; - for(String tId : tenantInfo.keySet()) { - pstmt.setString(1, tId); // set tenant_id param - pstmt.setString(2, getDefaultAdminRole(tId)); // set rolename param - rs = pstmt.executeQuery(); - // extract data from the ResultSet - if(!rs.next()) { - throw new RuntimeException("Cannot find role: "+getDefaultAdminRole(tId) - +" for tenant id: "+tId+" in roles!"); - } - String tenantAdminRoleCSID = rs.getString(1); - if (logger.isDebugEnabled()) { - logger.debug("createDefaultAccounts found role: " - +getDefaultAdminRole(tId)+"("+tenantAdminRoleCSID - +") for tenant id: "+tId); - } - tenantAdminRoleCSIDs.put(tId, tenantAdminRoleCSID); - pstmt.setString(1, tId); // set tenant_id param - pstmt.setString(2, getDefaultReaderRole(tId)); // set rolename param - rs.close(); - rs = pstmt.executeQuery(); - // extract data from the ResultSet - if(!rs.next()) { - throw new RuntimeException("Cannot find role: "+getDefaultReaderRole(tId) - +" for tenant id: "+tId+" in roles!"); - } - String tenantReaderRoleCSID = rs.getString(1); - if (logger.isDebugEnabled()) { - logger.debug("createDefaultAccounts found role: " - +getDefaultReaderRole(tId)+"("+tenantReaderRoleCSID - +") for tenant id: "+tId); - } - tenantReaderRoleCSIDs.put(tId, tenantReaderRoleCSID); - rs.close(); - } - pstmt.close(); - } catch(Exception e) { - throw e; - } finally { - if(stmt!=null) - stmt.close(); - if(pstmt!=null) - pstmt.close(); - } - return springAdminRoleCSID; - } - - private static String findTenantManagerRole(Connection conn ) - throws SQLException, RuntimeException, Exception { - String tenantMgrRoleCSID = null; - PreparedStatement pstmt = null; - try { - String rolename = getQualifiedRoleName(ALL_TENANTS_MANAGER_TENANT_ID, - ROLE_ALL_TENANTS_MANAGER); - pstmt = conn.prepareStatement(GET_TENANT_MGR_ROLE_SQL); // create a statement - ResultSet rs = null; - pstmt.setString(1, rolename); // set rolename param - rs = pstmt.executeQuery(); - if(rs.next()) { - tenantMgrRoleCSID = rs.getString(1); - if (logger.isDebugEnabled()) { - logger.debug("findTenantManagerRole found Tenant Mgr role: " - +tenantMgrRoleCSID); - } - } - rs.close(); - } catch(Exception e) { - throw e; - } finally { - if(pstmt!=null) - pstmt.close(); - } - if(tenantMgrRoleCSID==null) - throw new RuntimeException("findTenantManagerRole: Cound not find tenant Manager Role!"); - return tenantMgrRoleCSID; - } - - private static void bindAccountsToRoles(Connection conn, DatabaseProductType databaseProductType, - Hashtable tenantInfo, ArrayList usersInRepo, - String springAdminRoleCSID, - Hashtable tenantAdminRoleCSIDs, Hashtable tenantReaderRoleCSIDs, - Hashtable tenantAdminAcctCSIDs, Hashtable tenantReaderAcctCSIDs) - throws SQLException, Exception { - // Sixth, bind the accounts to roles. If the users already existed, - // we'll assume they were set up correctly. - PreparedStatement pstmt = null; - try { - String insertAccountRoleSQL; - if (databaseProductType == DatabaseProductType.MYSQL) { - insertAccountRoleSQL = INSERT_ACCOUNT_ROLE_SQL_MYSQL; - } else if (databaseProductType == DatabaseProductType.POSTGRESQL) { - insertAccountRoleSQL = INSERT_ACCOUNT_ROLE_SQL_POSTGRES; - } else { - throw new Exception("Unrecognized database system."); - } - if (logger.isDebugEnabled()) { - logger.debug("createDefaultAccounts binding accounts to roles with SQL:\n" - +insertAccountRoleSQL); - } - pstmt = conn.prepareStatement(insertAccountRoleSQL); // create a statement - for(String tId : tenantInfo.keySet()) { - String adminUserId = getDefaultAdminUserID(tenantInfo.get(tId)); - if(!usersInRepo.contains(adminUserId)) { - String adminAcct = tenantAdminAcctCSIDs.get(tId); - String adminRoleId = tenantAdminRoleCSIDs.get(tId); - pstmt.setString(1, adminAcct); // set acct CSID param - pstmt.setString(2, adminUserId); // set user_id param - pstmt.setString(3, adminRoleId); // set role_id param - pstmt.setString(4, getDefaultAdminRole(tId)); // set rolename param - if (logger.isDebugEnabled()) { - logger.debug("createDefaultAccounts binding account: " - +adminUserId+" to Admin role("+adminRoleId - +") for tenant id: "+tId); - } - pstmt.executeUpdate(); - // Now add the Spring Admin Role to the admin accounts - pstmt.setString(3, springAdminRoleCSID); // set role_id param - pstmt.setString(4, SPRING_ADMIN_ROLE); // set rolename param - if (logger.isDebugEnabled()) { - logger.debug("createDefaultAccounts binding account: " - +adminUserId+" to Spring Admin role: "+springAdminRoleCSID); - } - pstmt.executeUpdate(); - } - String readerUserId = getDefaultReaderUserID(tenantInfo.get(tId)); - if(!usersInRepo.contains(readerUserId)) { - String readerAcct = tenantReaderAcctCSIDs.get(tId); - String readerRoleId = tenantReaderRoleCSIDs.get(tId); - pstmt.setString(1, readerAcct); // set acct CSID param - pstmt.setString(2, readerUserId); // set user_id param - pstmt.setString(3, readerRoleId); // set role_id param - pstmt.setString(4, getDefaultReaderRole(tId)); // set rolename param - if (logger.isDebugEnabled()) { - logger.debug("createDefaultAccounts binding account: " - +readerUserId+" to Reader role("+readerRoleId - +") for tenant id: "+tId); - } - pstmt.executeUpdate(); - } - } - pstmt.close(); - } catch(Exception e) { - throw e; - } finally { - if(pstmt!=null) - pstmt.close(); - } - } - - private static void bindTenantManagerAccountRole(Connection conn, DatabaseProductType databaseProductType, - String tenantManagerUserID, String tenantManagerAccountID, String tenantManagerRoleID, String tenantManagerRoleName ) - throws SQLException, Exception { - PreparedStatement pstmt = null; - try { - String insertAccountRoleSQL; - if (databaseProductType == DatabaseProductType.MYSQL) { - insertAccountRoleSQL = INSERT_ACCOUNT_ROLE_SQL_MYSQL; - } else if (databaseProductType == DatabaseProductType.POSTGRESQL) { - insertAccountRoleSQL = INSERT_ACCOUNT_ROLE_SQL_POSTGRES; - } else { - throw new Exception("Unrecognized database system."); - } - if (logger.isDebugEnabled()) { - logger.debug("bindTenantManagerAccountRole binding account to role with SQL:\n" - +insertAccountRoleSQL); - } - pstmt = conn.prepareStatement(insertAccountRoleSQL); // create a statement - pstmt.setString(1, tenantManagerAccountID); // set acct CSID param - pstmt.setString(2, tenantManagerUserID); // set user_id param - pstmt.setString(3, tenantManagerRoleID); // set role_id param - pstmt.setString(4, tenantManagerRoleName); // set rolename param - if (logger.isDebugEnabled()) { - logger.debug("bindTenantManagerAccountRole binding user: " - +tenantManagerUserID+" to Admin role("+tenantManagerRoleName+")"); - } - pstmt.executeUpdate(); - /* At this point, tenant manager should not need the Spring Admin Role - pstmt.setString(3, springAdminRoleCSID); // set role_id param - pstmt.setString(4, SPRING_ADMIN_ROLE); // set rolename param - if (logger.isDebugEnabled()) { - logger.debug("createDefaultAccounts binding account: " - +adminUserId+" to Spring Admin role: "+springAdminRoleCSID); - } - pstmt.executeUpdate(); - */ - pstmt.close(); - } catch(Exception e) { - throw e; - } finally { - if(pstmt!=null) - pstmt.close(); - } - } - - public static void createDefaultAccounts( - TenantBindingConfigReaderImpl tenantBindingConfigReader, - DatabaseProductType databaseProductType, - String cspaceDatabaseName) throws Exception { - - logger.debug("ServiceMain.createDefaultAccounts starting..."); - - Hashtable tenantInfo = getTenantNamesFromConfig(tenantBindingConfigReader); - Connection conn = null; - // TODO - need to put in tests for existence first. - // We could just look for the accounts per tenant up front, and assume that - // the rest is there if the accounts are. - // Could add a sql script to remove these if need be - Spring only does roles, - // and we're not touching that, so we could safely toss the - // accounts, users, account-tenants, account-roles, and start over. - try { - conn = getConnection(cspaceDatabaseName); - ArrayList existingTenants = compileExistingTenants(conn, tenantInfo); - - // Note that this only creates tenants not marked as "createDisabled" - createMissingTenants(conn, tenantInfo, existingTenants); - - ArrayList usersInRepo = findOrCreateDefaultUsers(conn, tenantInfo); - - Hashtable tenantAdminAcctCSIDs = new Hashtable(); - Hashtable tenantReaderAcctCSIDs = new Hashtable(); - findOrCreateDefaultAccounts(conn, tenantInfo, usersInRepo, - tenantAdminAcctCSIDs, tenantReaderAcctCSIDs); - - bindDefaultAccountsToTenants(conn, databaseProductType, tenantInfo, usersInRepo, - tenantAdminAcctCSIDs, tenantReaderAcctCSIDs); - - Hashtable tenantAdminRoleCSIDs = new Hashtable(); - Hashtable tenantReaderRoleCSIDs = new Hashtable(); - String springAdminRoleCSID = findOrCreateDefaultRoles(conn, tenantInfo, - tenantAdminRoleCSIDs, tenantReaderRoleCSIDs); - - bindAccountsToRoles(conn, databaseProductType, - tenantInfo, usersInRepo, springAdminRoleCSID, - tenantAdminRoleCSIDs, tenantReaderRoleCSIDs, - tenantAdminAcctCSIDs, tenantReaderAcctCSIDs); - - boolean createdTenantMgrAccount = findOrCreateTenantManagerUserAndAccount(conn); - if(createdTenantMgrAccount) { - // If we created the account, we need to create the bindings. Otherwise, assume they - // are all set (from previous initialization). - String tenantManagerRoleCSID = findTenantManagerRole(conn); - bindTenantManagerAccountRole(conn, databaseProductType, - TENANT_MANAGER_USER, AuthN.TENANT_MANAGER_ACCT_ID, - tenantManagerRoleCSID, ROLE_ALL_TENANTS_MANAGER); - } - } catch (Exception e) { - logger.debug("Exception in createDefaultAccounts: " + e.getLocalizedMessage()); - throw e; - } finally { - try { - if (conn != null) - conn.close(); - } catch (SQLException sqle) { - if (logger.isDebugEnabled()) { - logger.debug("SQL Exception closing statement/connection: " + sqle.getLocalizedMessage()); - } - } - } - } - - private static String getDefaultAdminRole(String tenantId) { - return ROLE_PREFIX+tenantId+TENANT_ADMIN_ROLE_SUFFIX; - } - - private static String getDefaultReaderRole(String tenantId) { - return ROLE_PREFIX+tenantId+TENANT_READER_ROLE_SUFFIX; - } - - private static String getDefaultAdminUserID(String tenantName) { - return TENANT_ADMIN_ACCT_PREFIX+tenantName; - } - - private static String getDefaultReaderUserID(String tenantName) { - return TENANT_READER_ACCT_PREFIX+tenantName; - } - - static public PermissionAction createPermissionAction(Permission perm, - ActionType actionType) { - PermissionAction pa = new PermissionAction(); - - CSpaceAction action = URIResourceImpl.getAction(actionType); - URIResourceImpl uriRes = new URIResourceImpl(perm.getTenantId(), - perm.getResourceName(), action); - pa.setName(actionType); - pa.setObjectIdentity(uriRes.getHashedId().toString()); - pa.setObjectIdentityResource(uriRes.getId()); - - return pa; - } - - static public PermissionAction update(Permission perm, PermissionAction permAction) { - PermissionAction pa = new PermissionAction(); - - CSpaceAction action = URIResourceImpl.getAction(permAction.getName()); - URIResourceImpl uriRes = new URIResourceImpl(perm.getTenantId(), - perm.getResourceName(), action); - pa.setObjectIdentity(uriRes.getHashedId().toString()); - pa.setObjectIdentityResource(uriRes.getId()); - - return pa; - } - - private static TransitionDefList getTransitionDefList(TenantBindingType tenantBinding, ServiceBindingType serviceBinding) { - TransitionDefList result = null; - try { - String serviceObjectName = serviceBinding.getObject().getName(); - DocumentHandler docHandler = ServiceConfigUtils.createDocumentHandlerInstance( - tenantBinding, serviceBinding); - Lifecycle lifecycle = docHandler.getLifecycle(serviceObjectName); - if (lifecycle != null) { - result = lifecycle.getTransitionDefList(); - } - } catch (Exception e) { - // Ignore this exception and return an empty non-null TransitionDefList - } - - if (result == null) { - if (serviceBinding.getType().equalsIgnoreCase(ServiceBindingUtils.SERVICE_TYPE_SECURITY) == false) { - logger.warn("Could not retrieve a lifecycle transition definition list from: " - + serviceBinding.getName() - + " with tenant ID = " - + tenantBinding.getId()); - } - // return an empty list - result = new TransitionDefList(); - } else { - logger.debug("Successfully retrieved a lifecycle transition definition list from: " - + serviceBinding.getName() - + " with tenant ID = " - + tenantBinding.getId()); - } - - return result; - } - - public static void createDefaultWorkflowPermissions(TenantBindingConfigReaderImpl tenantBindingConfigReader) throws Exception //FIXME: REM - 4/11/2012 - Rename to createWorkflowPermissions - { - AuthZ.get().login(); //login to Spring Security manager - - EntityManagerFactory emf = JpaStorageUtils.getEntityManagerFactory(JpaStorageUtils.CS_PERSISTENCE_UNIT); - EntityManager em = null; - - try { - em = emf.createEntityManager(); - - Hashtable tenantBindings = - tenantBindingConfigReader.getTenantBindings(); - for (String tenantId : tenantBindings.keySet()) { - TenantBindingType tenantBinding = tenantBindings.get(tenantId); - Role adminRole = AuthorizationCommon.getRole(em, tenantBinding.getId(), ROLE_TENANT_ADMINISTRATOR); - Role readonlyRole = AuthorizationCommon.getRole(em, tenantBinding.getId(), ROLE_TENANT_READER); - for (ServiceBindingType serviceBinding : tenantBinding.getServiceBindings()) { - String prop = ServiceBindingUtils.getPropertyValue(serviceBinding, REFRESH_AUTZ_PROP); - if (prop == null ? true : Boolean.parseBoolean(prop)) { - try { - em.getTransaction().begin(); - TransitionDefList transitionDefList = getTransitionDefList(tenantBinding, serviceBinding); - for (TransitionDef transitionDef : transitionDefList.getTransitionDef()) { - // - // Create the permission for the admin role - Permission adminPerm = createWorkflowPermission(tenantBinding, serviceBinding, transitionDef, ACTIONGROUP_CRUDL); - persist(em, adminPerm, adminRole, true); - // - // Create the permission for the read-only role - Permission readonlyPerm = createWorkflowPermission(tenantBinding, serviceBinding, transitionDef, ACTIONGROUP_RL); - - Profiler profiler = new Profiler(AuthorizationCommon.class, 1); - profiler.start("createDefaultPermissions started:" + readonlyPerm.getCsid()); - persist(em, readonlyPerm, readonlyRole, true); // Persist/store the permission and permrole records and related Spring Security info - profiler.stop(); - logger.debug("Finished full perm generation for " - + ":" + tenantBinding.getId() - + ":" + serviceBinding.getName() - + ":" + transitionDef.getName() - + ":" + ACTIONGROUP_RL - + ":" + profiler.getCumulativeTime()); - } - em.getTransaction().commit(); - } catch (IllegalStateException e) { - logger.debug(e.getLocalizedMessage(), e); //We end up here if there is no document handler for the service -this is ok for some of the services. - } - } else { - logger.warn("AuthZ refresh service binding property is set to FALSE so default permissions will NOT be refreshed for: " - + serviceBinding.getName()); - } - } - } - em.close(); - } catch (Exception e) { - if (em != null && em.getTransaction().isActive()) { - em.getTransaction().rollback(); - } - if (logger.isDebugEnabled()) { - logger.debug("Caught exception and rolling back permission creation: ", e); - } - throw e; - } finally { - if (em != null) { - JpaStorageUtils.releaseEntityManagerFactory(emf); - } - } - } - - private static PermissionRoleRel findPermRoleRel(EntityManager em, String permissionId, String RoleId) { - PermissionRoleRel result = null; - - try { - String whereClause = "where permissionId = :id and roleId = :roleId"; - HashMap params = new HashMap(); - params.put("id", permissionId); - params.put("roleId", RoleId); - - result = (PermissionRoleRel) JpaStorageUtils.getEntity(em, - PermissionRoleRel.class.getCanonicalName(), whereClause, params); - } catch (Exception e) { - //Do nothing. Will return null; - } - - return result; - } - - /* - * Persists the Permission, PermissionRoleRel, and Spring Security table entries all in one transaction - */ - private static void persist(EntityManager em, Permission permission, Role role, boolean enforceTenancy) throws Exception { - AuthorizationStore authzStore = new AuthorizationStore(); - // First persist the Permission record - authzStore.store(em, permission); - - // If the PermRoleRel doesn't already exists then relate the permission and the role in a new PermissionRole (the service payload) - // Create a PermissionRoleRel (the database relation table for the permission and role) - PermissionRoleRel permRoleRel = findPermRoleRel(em, permission.getCsid(), role.getCsid()); - if (permRoleRel == null) { - PermissionRole permRole = createPermissionRole(em, permission, role, enforceTenancy); - List permRoleRels = new ArrayList(); - PermissionRoleUtil.buildPermissionRoleRel(em, permRole, SubjectType.ROLE, permRoleRels, false /*not for delete*/); - for (PermissionRoleRel prr : permRoleRels) { - authzStore.store(em, prr); - } - Profiler profiler = new Profiler(AuthorizationCommon.class, 2); - profiler.start(); - // Add a corresponding entry in the Spring Security Tables - addPermissionsForUri(permission, permRole); - profiler.stop(); - logger.debug("Finished full perm generation for " - + ":" + permission.getTenantId() - + ":" + permission.getResourceName() - + ":" + ACTIONGROUP_RL - + ":" + profiler.getCumulativeTime()); - } - - } - -} +package org.collectionspace.services.common.authorization_mgt; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.List; +import java.util.UUID; + +import javax.naming.NamingException; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; + +import org.collectionspace.authentication.AuthN; +import org.collectionspace.services.authorization.AuthZ; +import org.collectionspace.services.authorization.CSpaceAction; +import org.collectionspace.services.authorization.PermissionException; +import org.collectionspace.services.authorization.PermissionRole; +import org.collectionspace.services.authorization.PermissionRoleRel; +import org.collectionspace.services.authorization.PermissionValue; +import org.collectionspace.services.authorization.Role; +import org.collectionspace.services.authorization.RoleValue; +import org.collectionspace.services.authorization.SubjectType; +import org.collectionspace.services.authorization.URIResourceImpl; +import org.collectionspace.services.authorization.perms.ActionType; +import org.collectionspace.services.authorization.perms.EffectType; +import org.collectionspace.services.authorization.perms.Permission; +import org.collectionspace.services.authorization.perms.PermissionAction; + +import org.collectionspace.services.client.Profiler; +import org.collectionspace.services.client.RoleClient; +import org.collectionspace.services.client.workflow.WorkflowClient; +import org.collectionspace.services.common.config.ServiceConfigUtils; +import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl; +import org.collectionspace.services.common.context.ServiceBindingUtils; +import org.collectionspace.services.common.document.DocumentHandler; +import org.collectionspace.services.common.security.SecurityUtils; +import org.collectionspace.services.common.storage.DatabaseProductType; +import org.collectionspace.services.common.storage.JDBCTools; +import org.collectionspace.services.common.storage.jpa.JpaStorageUtils; +import org.collectionspace.services.config.service.ServiceBindingType; +import org.collectionspace.services.config.tenant.TenantBindingType; + +import org.collectionspace.services.lifecycle.Lifecycle; +import org.collectionspace.services.lifecycle.TransitionDef; +import org.collectionspace.services.lifecycle.TransitionDefList; + +//import org.mortbay.log.Log; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.security.acls.model.AlreadyExistsException; + + +public class AuthorizationCommon { + + final public static String REFRESH_AUTZ_PROP = "refreshAuthZOnStartup"; + // + // ActionGroup labels/constants + // + + // for READ-WRITE + final public static String ACTIONGROUP_CRUDL_NAME = "CRUDL"; + final public static ActionType[] ACTIONSET_CRUDL = {ActionType.CREATE, ActionType.READ, ActionType.UPDATE, ActionType.DELETE, ActionType.SEARCH}; + // for READ-ONLY + final public static String ACTIONGROUP_RL_NAME = "RL"; + final public static ActionType[] ACTIONSET_RL = {ActionType.READ, ActionType.SEARCH}; + + + /* + * Inner class to deal with predefined ADMIN and READER action groupds + */ + public class ActionGroup { + String name; + ActionType[] actions; + } + + static ActionGroup ACTIONGROUP_CRUDL; + static ActionGroup ACTIONGROUP_RL; + + // A static block to initialize the predefined action groups + static { + AuthorizationCommon ac = new AuthorizationCommon(); + // For admin + ACTIONGROUP_CRUDL = ac.new ActionGroup(); + ACTIONGROUP_CRUDL.name = ACTIONGROUP_CRUDL_NAME; + ACTIONGROUP_CRUDL.actions = ACTIONSET_CRUDL; + // For reader + ACTIONGROUP_RL = ac.new ActionGroup(); + ACTIONGROUP_RL.name = ACTIONGROUP_RL_NAME; + ACTIONGROUP_RL.actions = ACTIONSET_RL; + + } + + final static Logger logger = LoggerFactory.getLogger(AuthorizationCommon.class); + + // + // The "super" role has a predefined ID of "0" and a tenant ID of "0"; + // + final public static String ROLE_ALL_TENANTS_MANAGER = "ALL_TENANTS_MANAGER"; + final public static String ROLE_ALL_TENANTS_MANAGER_ID = "0"; + final public static String ALL_TENANTS_MANAGER_TENANT_ID = "0"; + + final public static String ROLE_TENANT_ADMINISTRATOR = "TENANT_ADMINISTRATOR"; + final public static String ROLE_TENANT_READER = "TENANT_READER"; + + public static final String TENANT_MANAGER_USER = "tenantManager"; + public static final String TENANT_MANAGER_SCREEN_NAME = TENANT_MANAGER_USER; + public static final String DEFAULT_TENANT_MANAGER_PASSWORD = "manage"; + public static final String DEFAULT_TENANT_MANAGER_EMAIL = "tenantManager@collectionspace.org"; + + public static final String TENANT_ADMIN_ACCT_PREFIX = "admin@"; + public static final String TENANT_READER_ACCT_PREFIX = "reader@"; + public static final String ROLE_PREFIX = "ROLE_"; + public static final String SPRING_ADMIN_ROLE = "ROLE_SPRING_ADMIN"; + public static final String TENANT_ADMIN_ROLE_SUFFIX = "_TENANT_ADMINISTRATOR"; + public static final String TENANT_READER_ROLE_SUFFIX = "_TENANT_READER"; + public static final String DEFAULT_ADMIN_PASSWORD = "Administrator"; + public static final String DEFAULT_READER_PASSWORD = "reader"; + + public static final String ROLE_SPRING_ADMIN_ID = "-1"; + public static final String ROLE_SPRING_ADMIN_NAME = "ROLE_SPRING_ADMIN"; + + // SQL for init tasks + final private static String INSERT_ACCOUNT_ROLE_SQL_MYSQL = + "INSERT INTO accounts_roles(account_id, user_id, role_id, role_name, created_at)" + +" VALUES(?, ?, ?, ?, now())"; + final private static String INSERT_ACCOUNT_ROLE_SQL_POSTGRES = + "INSERT INTO accounts_roles(HJID, account_id, user_id, role_id, role_name, created_at)" + +" VALUES(nextval('hibernate_sequence'), ?, ?, ?, ?, now())"; + final private static String QUERY_USERS_SQL = + "SELECT username FROM users WHERE username LIKE '" + +TENANT_ADMIN_ACCT_PREFIX+"%' OR username LIKE '"+TENANT_READER_ACCT_PREFIX+"%'"; + final private static String INSERT_USER_SQL = + "INSERT INTO users (username,passwd, created_at) VALUES (?,?, now())"; + final private static String INSERT_ACCOUNT_SQL = + "INSERT INTO accounts_common " + + "(csid, email, userid, status, screen_name, metadata_protection, roles_protection, created_at) " + + "VALUES (?,?,?,'ACTIVE',?, 'immutable', 'immutable', now())"; + + // TENANT MANAGER specific SQL + final private static String QUERY_TENANT_MGR_USER_SQL = + "SELECT username FROM users WHERE username = '"+TENANT_MANAGER_USER+"'"; + final private static String GET_TENANT_MGR_ROLE_SQL = + "SELECT csid from roles WHERE tenant_id='"+ALL_TENANTS_MANAGER_TENANT_ID+"' and rolename=?"; + + public static Role getRole(String tenantId, String displayName) { + Role role = null; + + String roleName = AuthorizationCommon.getQualifiedRoleName(tenantId, displayName); + role = AuthorizationStore.getRoleByName(roleName, tenantId); + + return role; + } + + public static Role getRole(EntityManager em, String tenantId, String displayName) { + Role role = null; + + String roleName = AuthorizationCommon.getQualifiedRoleName(tenantId, displayName); + role = AuthorizationStore.getRoleByName(em, roleName, tenantId); + + return role; + } + + + public static Role createRole(String tenantId, String name, String description) { + return createRole(tenantId, name, description, false /* mutable by default */); + } + + public static Role createRole(String tenantId, String name, String description, boolean immutable) { + Role role = new Role(); + + role.setCreatedAtItem(new Date()); + role.setDisplayName(name); + String roleName = AuthorizationCommon.getQualifiedRoleName(tenantId, name); + role.setRoleName(roleName); + String id = UUID.randomUUID().toString(); //FIXME: The qualified role name should be unique enough to use as an ID/key + role.setCsid(id); + role.setDescription(description); + role.setTenantId(tenantId); + if (immutable == true) { + role.setMetadataProtection(RoleClient.IMMUTABLE); + role.setPermsProtection(RoleClient.IMMUTABLE); + } + + return role; + } + + /** + * Add permission to the Spring Security tables + * with assumption that resource is of type URI + * @param permission configuration + */ + public static void addPermissionsForUri(Permission perm, + PermissionRole permRole) throws PermissionException { + // + // First check the integrity of the incoming arguments. + // + if (!perm.getCsid().equals(permRole.getPermission().get(0).getPermissionId())) { + throw new IllegalArgumentException("permission ids do not" + + " match for role=" + permRole.getRole().get(0).getRoleName() + + " with permissionId=" + permRole.getPermission().get(0).getPermissionId() + + " for permission with csid=" + perm.getCsid()); + } + + List principals = new ArrayList(); + for (RoleValue roleValue : permRole.getRole()) { + principals.add(roleValue.getRoleName()); + } + List permActions = perm.getAction(); + for (PermissionAction permAction : permActions) { + try { + CSpaceAction action = URIResourceImpl.getAction(permAction.getName()); + URIResourceImpl uriRes = new URIResourceImpl(perm.getTenantId(), + perm.getResourceName(), action); + boolean grant = perm.getEffect().equals(EffectType.PERMIT) ? true : false; + AuthZ.get().addPermissions(uriRes, principals.toArray(new String[0]), grant);//CSPACE-4967 + } catch (PermissionException e) { + // + // Only throw the exception if it is *not* an already-exists exception + // + if (e.getCause() instanceof AlreadyExistsException == false) { + throw e; + } + } + } + } + + private static Connection getConnection(String databaseName) throws NamingException, SQLException { + return JDBCTools.getConnection(JDBCTools.CSPACE_DATASOURCE_NAME, + databaseName); + } + + /* + * Spring security seems to require that all of our role names start + * with the ROLE_PREFIX string. + */ + public static String getQualifiedRoleName(String tenantId, String name) { + String result = name; + + String qualifiedName = ROLE_PREFIX + tenantId.toUpperCase() + "_" + name.toUpperCase(); + if (name.equals(qualifiedName) == false) { + result = qualifiedName; + } + + return result; + } + + private static ActionGroup getActionGroup(String actionGroupStr) { + ActionGroup result = null; + + if (actionGroupStr.equalsIgnoreCase(ACTIONGROUP_CRUDL_NAME)) { + result = ACTIONGROUP_CRUDL; + } else if (actionGroupStr.equalsIgnoreCase(ACTIONGROUP_RL_NAME)) { + result = ACTIONGROUP_RL; + } + + return result; + } + + public static Permission createPermission(String tenantId, + String resourceName, + String description, + String actionGroupStr) { + Permission result = null; + + ActionGroup actionGroup = getActionGroup(actionGroupStr); + result = createPermission(tenantId, resourceName, description, actionGroup); + + return result; + } + + private static Permission createPermission(String tenantId, + String resourceName, + String description, + ActionGroup actionGroup) { + String id = tenantId + + "-" + resourceName.replace('/', '_') // Remove the slashes so the ID can be used in a URI/URL + + "-" + actionGroup.name; + Permission perm = new Permission(); + perm.setCsid(id); + perm.setDescription(description); + perm.setCreatedAtItem(new Date()); + perm.setResourceName(resourceName.toLowerCase().trim()); + perm.setEffect(EffectType.PERMIT); + perm.setTenantId(tenantId); + + perm.setActionGroup(actionGroup.name); + ArrayList pas = new ArrayList(); + perm.setAction(pas); + for (ActionType actionType : actionGroup.actions) { + PermissionAction permAction = createPermissionAction(perm, actionType); + pas.add(permAction); + } + + return perm; + } + + private static Permission createWorkflowPermission(TenantBindingType tenantBinding, + ServiceBindingType serviceBinding, + TransitionDef transitionDef, + ActionGroup actionGroup) + { + Permission result = null; + String workFlowServiceSuffix; + String transitionName; + if (transitionDef != null) { + transitionName = transitionDef.getName(); + workFlowServiceSuffix = WorkflowClient.SERVICE_AUTHZ_SUFFIX; + } else { + transitionName = ""; //since the transitionDef was null, we're assuming that this is the base workflow permission to be created + workFlowServiceSuffix = WorkflowClient.SERVICE_PATH; + } + + String tenantId = tenantBinding.getId(); + String resourceName = "/" + + serviceBinding.getName().toLowerCase().trim() + + workFlowServiceSuffix + + transitionName; + String description = "A generated workflow permission for actiongroup " + actionGroup.name; + result = createPermission(tenantId, resourceName, description, actionGroup); + + if (logger.isDebugEnabled() == true) { + logger.debug("Generated a workflow permission: " + + result.getResourceName() + + ":" + transitionName + + ":" + "tenant id=" + result.getTenantId() + + ":" + actionGroup.name); + } + + return result; + } + + private static PermissionRole createPermissionRole(EntityManager em, + Permission permission, + Role role, + boolean enforceTenancy) throws Exception + { + PermissionRole permRole = new PermissionRole(); + // Check to see if the tenant ID of the permission and the tenant ID of the role match + boolean tenantIdsMatch = role.getTenantId().equalsIgnoreCase(permission.getTenantId()); + if (tenantIdsMatch == false && enforceTenancy == false) { + tenantIdsMatch = true; // If we don't need to enforce tenancy then we'll just consider them matched. + } + + if (tenantIdsMatch == true) { + permRole.setSubject(SubjectType.ROLE); + // + // Set of the permission value list of the permrole + // + List permValues = new ArrayList(); + PermissionValue permValue = new PermissionValue(); + permValue.setPermissionId(permission.getCsid()); + permValue.setResourceName(permission.getResourceName().toLowerCase()); + permValue.setActionGroup(permission.getActionGroup()); + permValues.add(permValue); + permRole.setPermission(permValues); + // + // Set of the role value list of the permrole + // + List roleValues = new ArrayList(); + RoleValue rv = new RoleValue(); + // This needs to use the qualified name, not the display name + rv.setRoleName(role.getRoleName()); + rv.setRoleId(role.getCsid()); + roleValues.add(rv); + permRole.setRole(roleValues); + } else { + String errMsg = "The tenant ID of the role: " + role.getTenantId() + + " did not match the tenant ID of the permission: " + permission.getTenantId(); + throw new Exception(errMsg); + } + + return permRole; + } + + private static Hashtable getTenantNamesFromConfig(TenantBindingConfigReaderImpl tenantBindingConfigReader) { + + // Note that this only handles tenants not marked as "createDisabled" + Hashtable tenantBindings = + tenantBindingConfigReader.getTenantBindings(); + Hashtable tenantInfo = new Hashtable(); + for (TenantBindingType tenantBinding : tenantBindings.values()) { + String tId = tenantBinding.getId(); + String tName = tenantBinding.getName(); + tenantInfo.put(tId, tName); + if (logger.isDebugEnabled()) { + logger.debug("getTenantNamesFromConfig found configured tenant id: "+tId+" name: "+tName); + } + } + return tenantInfo; + } + + private static ArrayList compileExistingTenants(Connection conn, Hashtable tenantInfo) + throws SQLException, Exception { + Statement stmt = null; + ArrayList existingTenants = new ArrayList(); + // First find or create the tenants + final String queryTenantSQL = "SELECT id,name FROM tenants"; + try { + stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery(queryTenantSQL); + while (rs.next()) { + String tId = rs.getString("id"); + String tName = rs.getString("name"); + if(tenantInfo.containsKey(tId)) { + existingTenants.add(tId); + if(!tenantInfo.get(tId).equalsIgnoreCase(tName)) { + logger.warn("Configured name for tenant: " + +tId+" in repository: "+tName + +" does not match config'd name: "+ tenantInfo.get(tId)); + } + } + } + rs.close(); + } catch(Exception e) { + throw e; + } finally { + if(stmt!=null) + stmt.close(); + } + + return existingTenants; + } + + private static void createMissingTenants(Connection conn, Hashtable tenantInfo, + ArrayList existingTenants) throws SQLException, Exception { + // Need to define and look for a createDisabled attribute in tenant config + final String insertTenantSQL = + "INSERT INTO tenants (id,name,disabled,created_at) VALUES (?,?,FALSE,now())"; + PreparedStatement pstmt = null; + try { + pstmt = conn.prepareStatement(insertTenantSQL); // create a statement + for(String tId : tenantInfo.keySet()) { + if(existingTenants.contains(tId)) { + if (logger.isDebugEnabled()) { + logger.debug("createMissingTenants: tenant exists (skipping): " + +tenantInfo.get(tId)); + } + continue; + } + pstmt.setString(1, tId); // set id param + pstmt.setString(2, tenantInfo.get(tId)); // set name param + if (logger.isDebugEnabled()) { + logger.debug("createMissingTenants adding entry for tenant: "+tId); + } + pstmt.executeUpdate(); + } + pstmt.close(); + } catch(Exception e) { + throw e; + } finally { + if(pstmt!=null) + pstmt.close(); + } + } + + private static ArrayList findOrCreateDefaultUsers(Connection conn, Hashtable tenantInfo) + throws SQLException, Exception { + // Second find or create the users + Statement stmt = null; + PreparedStatement pstmt = null; + ArrayList usersInRepo = new ArrayList(); + try { + stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery(QUERY_USERS_SQL); + while (rs.next()) { + String uName = rs.getString("username"); + usersInRepo.add(uName); + } + rs.close(); + pstmt = conn.prepareStatement(INSERT_USER_SQL); // create a statement + for(String tName : tenantInfo.values()) { + String adminAcctName = getDefaultAdminUserID(tName); + if(!usersInRepo.contains(adminAcctName)) { + String secEncPasswd = SecurityUtils.createPasswordHash( + adminAcctName, DEFAULT_ADMIN_PASSWORD); + pstmt.setString(1, adminAcctName); // set username param + pstmt.setString(2, secEncPasswd); // set passwd param + if (logger.isDebugEnabled()) { + logger.debug("createDefaultUsersAndAccounts adding user: " + +adminAcctName+" for tenant: "+tName); + } + pstmt.executeUpdate(); + } else if (logger.isDebugEnabled()) { + logger.debug("createDefaultUsersAndAccounts: user: "+adminAcctName + +" already exists - skipping."); + } + + + String readerAcctName = getDefaultReaderUserID(tName); + if(!usersInRepo.contains(readerAcctName)) { + String secEncPasswd = SecurityUtils.createPasswordHash( + readerAcctName, DEFAULT_READER_PASSWORD); + pstmt.setString(1, readerAcctName); // set username param + pstmt.setString(2, secEncPasswd); // set passwd param + if (logger.isDebugEnabled()) { + logger.debug("createDefaultUsersAndAccounts adding user: " + +readerAcctName+" for tenant: "+tName); + } + pstmt.executeUpdate(); + } else if (logger.isDebugEnabled()) { + logger.debug("createDefaultUsersAndAccounts: user: "+readerAcctName + +" already exists - skipping."); + } + } + pstmt.close(); + } catch(Exception e) { + throw e; + } finally { + if(stmt!=null) + stmt.close(); + if(pstmt!=null) + pstmt.close(); + } + return usersInRepo; + } + + private static void findOrCreateDefaultAccounts(Connection conn, Hashtable tenantInfo, + ArrayList usersInRepo, + Hashtable tenantAdminAcctCSIDs, Hashtable tenantReaderAcctCSIDs) + throws SQLException, Exception { + // Third, create the accounts. Assume that if the users were already there, + // then the accounts were as well + PreparedStatement pstmt = null; + try { + pstmt = conn.prepareStatement(INSERT_ACCOUNT_SQL); // create a statement + for(String tId : tenantInfo.keySet()) { + String tName = tenantInfo.get(tId); + String adminCSID = UUID.randomUUID().toString(); + tenantAdminAcctCSIDs.put(tId, adminCSID); + String adminAcctName = getDefaultAdminUserID(tName); + if(!usersInRepo.contains(adminAcctName)) { + pstmt.setString(1, adminCSID); // set csid param + pstmt.setString(2, adminAcctName); // set email param (bogus) + pstmt.setString(3, adminAcctName); // set userid param + pstmt.setString(4, "Administrator");// set screen name param + if (logger.isDebugEnabled()) { + logger.debug("createDefaultAccounts adding account: " + +adminAcctName+" for tenant: "+tName); + } + pstmt.executeUpdate(); + } else if (logger.isDebugEnabled()) { + logger.debug("createDefaultAccounts: user: "+adminAcctName + +" already exists - skipping account generation."); + } + + String readerCSID = UUID.randomUUID().toString(); + tenantReaderAcctCSIDs.put(tId, readerCSID); + String readerAcctName = getDefaultReaderUserID(tName); + if(!usersInRepo.contains(readerAcctName)) { + pstmt.setString(1, readerCSID); // set csid param + pstmt.setString(2, readerAcctName); // set email param (bogus) + pstmt.setString(3, readerAcctName); // set userid param + pstmt.setString(4, "Reader"); // set screen name param + if (logger.isDebugEnabled()) { + logger.debug("createDefaultAccounts adding account: " + +readerAcctName+" for tenant: "+tName); + } + pstmt.executeUpdate(); + } else if (logger.isDebugEnabled()) { + logger.debug("createDefaultAccounts: user: "+readerAcctName + +" already exists - skipping account creation."); + } + } + pstmt.close(); + } catch(Exception e) { + throw e; + } finally { + if(pstmt!=null) + pstmt.close(); + } + } + + private static boolean findOrCreateTenantManagerUserAndAccount(Connection conn) + throws SQLException, Exception { + // Find or create the special tenant manager account. + // Later can make the user name for tenant manager be configurable, settable. + Statement stmt = null; + PreparedStatement pstmt = null; + boolean created = false; + try { + boolean foundTMgrUser = false; + stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery(QUERY_TENANT_MGR_USER_SQL); + // Should only find one - only consider it + if(rs.next()) { + String uName = rs.getString("username"); + foundTMgrUser = uName.equals(TENANT_MANAGER_USER); + } + rs.close(); + if(!foundTMgrUser) { + pstmt = conn.prepareStatement(INSERT_USER_SQL); // create a statement + String secEncPasswd = SecurityUtils.createPasswordHash( + TENANT_MANAGER_USER, DEFAULT_TENANT_MANAGER_PASSWORD); + pstmt.setString(1, TENANT_MANAGER_USER); // set username param + pstmt.setString(2, secEncPasswd); // set passwd param + if (logger.isDebugEnabled()) { + logger.debug("findOrCreateTenantManagerUserAndAccount adding tenant manager user: " + +TENANT_MANAGER_USER); + } + pstmt.executeUpdate(); + pstmt.close(); + // Now create the account to match + pstmt = conn.prepareStatement(INSERT_ACCOUNT_SQL); // create a statement + pstmt.setString(1, AuthN.TENANT_MANAGER_ACCT_ID); // set csid param + pstmt.setString(2, DEFAULT_TENANT_MANAGER_EMAIL); // set email param (bogus) + pstmt.setString(3, TENANT_MANAGER_USER); // set userid param + pstmt.setString(4, TENANT_MANAGER_SCREEN_NAME);// set screen name param + if (logger.isDebugEnabled()) { + logger.debug("findOrCreateTenantManagerUserAndAccount adding tenant manager account: " + +TENANT_MANAGER_USER); + } + pstmt.executeUpdate(); + pstmt.close(); + created = true; + } else if (logger.isDebugEnabled()) { + logger.debug("findOrCreateTenantManagerUserAndAccount: tenant manager: "+TENANT_MANAGER_USER + +" already exists."); + } + } catch(Exception e) { + throw e; + } finally { + if(stmt!=null) + stmt.close(); + if(pstmt!=null) + pstmt.close(); + } + return created; + } + + private static void bindDefaultAccountsToTenants(Connection conn, DatabaseProductType databaseProductType, + Hashtable tenantInfo, ArrayList usersInRepo, + Hashtable tenantAdminAcctCSIDs, Hashtable tenantReaderAcctCSIDs) + throws SQLException, Exception { + // Fourth, bind accounts to tenants. Assume that if the users were already there, + // then the accounts were bound to tenants correctly + PreparedStatement pstmt = null; + try { + String insertAccountTenantSQL; + if (databaseProductType == DatabaseProductType.MYSQL) { + insertAccountTenantSQL = + "INSERT INTO accounts_tenants (TENANTS_ACCOUNTSCOMMON_CSID,tenant_id) " + + " VALUES(?, ?)"; + } else if (databaseProductType == DatabaseProductType.POSTGRESQL) { + insertAccountTenantSQL = + "INSERT INTO accounts_tenants (HJID, TENANTS_ACCOUNTSCOMMON_CSID,tenant_id) " + + " VALUES(nextval('hibernate_sequence'), ?, ?)"; + } else { + throw new Exception("Unrecognized database system."); + } + pstmt = conn.prepareStatement(insertAccountTenantSQL); // create a statement + for(String tId : tenantInfo.keySet()) { + String tName = tenantInfo.get(tId); + if(!usersInRepo.contains(getDefaultAdminUserID(tName))) { + String adminAcct = tenantAdminAcctCSIDs.get(tId); + pstmt.setString(1, adminAcct); // set acct CSID param + pstmt.setString(2, tId); // set tenant_id param + if (logger.isDebugEnabled()) { + logger.debug("createDefaultAccounts binding account id: " + +adminAcct+" to tenant id: "+tId); + } + pstmt.executeUpdate(); + } + if(!usersInRepo.contains(getDefaultReaderUserID(tName))) { + String readerAcct = tenantReaderAcctCSIDs.get(tId); + pstmt.setString(1, readerAcct); // set acct CSID param + pstmt.setString(2, tId); // set tenant_id param + if (logger.isDebugEnabled()) { + logger.debug("createDefaultAccounts binding account id: " + +readerAcct+" to tenant id: "+tId); + } + pstmt.executeUpdate(); + } + } + pstmt.close(); + } catch(Exception e) { + throw e; + } finally { + if(pstmt!=null) + pstmt.close(); + } + } + + + private static String findOrCreateDefaultRoles(Connection conn, Hashtable tenantInfo, + Hashtable tenantAdminRoleCSIDs, Hashtable tenantReaderRoleCSIDs) + throws SQLException, Exception { + // Fifth, fetch and save the default roles + String springAdminRoleCSID = null; + Statement stmt = null; + PreparedStatement pstmt = null; + try { + final String querySpringRole = + "SELECT csid from roles WHERE rolename='"+SPRING_ADMIN_ROLE+"'"; + stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery(querySpringRole); + if(rs.next()) { + springAdminRoleCSID = rs.getString(1); + if (logger.isDebugEnabled()) { + logger.debug("createDefaultAccounts found Spring Admin role: " + +springAdminRoleCSID); + } + } else { + final String insertSpringAdminRoleSQL = + "INSERT INTO roles (csid, rolename, displayName, rolegroup, created_at, tenant_id) " + + "VALUES ('-1', 'ROLE_SPRING_ADMIN', 'SPRING_ADMIN', 'Spring Security Administrator', now(), '0')"; + stmt.executeUpdate(insertSpringAdminRoleSQL); + springAdminRoleCSID = "-1"; + if (logger.isDebugEnabled()) { + logger.debug("createDefaultAccounts CREATED Spring Admin role: " + +springAdminRoleCSID); + } + } + rs.close(); + final String getRoleCSIDSql = + "SELECT csid from roles WHERE tenant_id=? and rolename=?"; + pstmt = conn.prepareStatement(getRoleCSIDSql); // create a statement + rs = null; + for(String tId : tenantInfo.keySet()) { + pstmt.setString(1, tId); // set tenant_id param + pstmt.setString(2, getDefaultAdminRole(tId)); // set rolename param + rs = pstmt.executeQuery(); + // extract data from the ResultSet + if(!rs.next()) { + throw new RuntimeException("Cannot find role: "+getDefaultAdminRole(tId) + +" for tenant id: "+tId+" in roles!"); + } + String tenantAdminRoleCSID = rs.getString(1); + if (logger.isDebugEnabled()) { + logger.debug("createDefaultAccounts found role: " + +getDefaultAdminRole(tId)+"("+tenantAdminRoleCSID + +") for tenant id: "+tId); + } + tenantAdminRoleCSIDs.put(tId, tenantAdminRoleCSID); + pstmt.setString(1, tId); // set tenant_id param + pstmt.setString(2, getDefaultReaderRole(tId)); // set rolename param + rs.close(); + rs = pstmt.executeQuery(); + // extract data from the ResultSet + if(!rs.next()) { + throw new RuntimeException("Cannot find role: "+getDefaultReaderRole(tId) + +" for tenant id: "+tId+" in roles!"); + } + String tenantReaderRoleCSID = rs.getString(1); + if (logger.isDebugEnabled()) { + logger.debug("createDefaultAccounts found role: " + +getDefaultReaderRole(tId)+"("+tenantReaderRoleCSID + +") for tenant id: "+tId); + } + tenantReaderRoleCSIDs.put(tId, tenantReaderRoleCSID); + rs.close(); + } + pstmt.close(); + } catch(Exception e) { + throw e; + } finally { + if(stmt!=null) + stmt.close(); + if(pstmt!=null) + pstmt.close(); + } + return springAdminRoleCSID; + } + + private static String findTenantManagerRole(Connection conn ) + throws SQLException, RuntimeException, Exception { + String tenantMgrRoleCSID = null; + PreparedStatement pstmt = null; + try { + String rolename = getQualifiedRoleName(ALL_TENANTS_MANAGER_TENANT_ID, + ROLE_ALL_TENANTS_MANAGER); + pstmt = conn.prepareStatement(GET_TENANT_MGR_ROLE_SQL); // create a statement + ResultSet rs = null; + pstmt.setString(1, rolename); // set rolename param + rs = pstmt.executeQuery(); + if(rs.next()) { + tenantMgrRoleCSID = rs.getString(1); + if (logger.isDebugEnabled()) { + logger.debug("findTenantManagerRole found Tenant Mgr role: " + +tenantMgrRoleCSID); + } + } + rs.close(); + } catch(Exception e) { + throw e; + } finally { + if(pstmt!=null) + pstmt.close(); + } + if(tenantMgrRoleCSID==null) + throw new RuntimeException("findTenantManagerRole: Cound not find tenant Manager Role!"); + return tenantMgrRoleCSID; + } + + private static void bindAccountsToRoles(Connection conn, DatabaseProductType databaseProductType, + Hashtable tenantInfo, ArrayList usersInRepo, + String springAdminRoleCSID, + Hashtable tenantAdminRoleCSIDs, Hashtable tenantReaderRoleCSIDs, + Hashtable tenantAdminAcctCSIDs, Hashtable tenantReaderAcctCSIDs) + throws SQLException, Exception { + // Sixth, bind the accounts to roles. If the users already existed, + // we'll assume they were set up correctly. + PreparedStatement pstmt = null; + try { + String insertAccountRoleSQL; + if (databaseProductType == DatabaseProductType.MYSQL) { + insertAccountRoleSQL = INSERT_ACCOUNT_ROLE_SQL_MYSQL; + } else if (databaseProductType == DatabaseProductType.POSTGRESQL) { + insertAccountRoleSQL = INSERT_ACCOUNT_ROLE_SQL_POSTGRES; + } else { + throw new Exception("Unrecognized database system."); + } + if (logger.isDebugEnabled()) { + logger.debug("createDefaultAccounts binding accounts to roles with SQL:\n" + +insertAccountRoleSQL); + } + pstmt = conn.prepareStatement(insertAccountRoleSQL); // create a statement + for(String tId : tenantInfo.keySet()) { + String adminUserId = getDefaultAdminUserID(tenantInfo.get(tId)); + if(!usersInRepo.contains(adminUserId)) { + String adminAcct = tenantAdminAcctCSIDs.get(tId); + String adminRoleId = tenantAdminRoleCSIDs.get(tId); + pstmt.setString(1, adminAcct); // set acct CSID param + pstmt.setString(2, adminUserId); // set user_id param + pstmt.setString(3, adminRoleId); // set role_id param + pstmt.setString(4, getDefaultAdminRole(tId)); // set rolename param + if (logger.isDebugEnabled()) { + logger.debug("createDefaultAccounts binding account: " + +adminUserId+" to Admin role("+adminRoleId + +") for tenant id: "+tId); + } + pstmt.executeUpdate(); + // Now add the Spring Admin Role to the admin accounts + pstmt.setString(3, springAdminRoleCSID); // set role_id param + pstmt.setString(4, SPRING_ADMIN_ROLE); // set rolename param + if (logger.isDebugEnabled()) { + logger.debug("createDefaultAccounts binding account: " + +adminUserId+" to Spring Admin role: "+springAdminRoleCSID); + } + pstmt.executeUpdate(); + } + String readerUserId = getDefaultReaderUserID(tenantInfo.get(tId)); + if(!usersInRepo.contains(readerUserId)) { + String readerAcct = tenantReaderAcctCSIDs.get(tId); + String readerRoleId = tenantReaderRoleCSIDs.get(tId); + pstmt.setString(1, readerAcct); // set acct CSID param + pstmt.setString(2, readerUserId); // set user_id param + pstmt.setString(3, readerRoleId); // set role_id param + pstmt.setString(4, getDefaultReaderRole(tId)); // set rolename param + if (logger.isDebugEnabled()) { + logger.debug("createDefaultAccounts binding account: " + +readerUserId+" to Reader role("+readerRoleId + +") for tenant id: "+tId); + } + pstmt.executeUpdate(); + } + } + pstmt.close(); + } catch(Exception e) { + throw e; + } finally { + if(pstmt!=null) + pstmt.close(); + } + } + + private static void bindTenantManagerAccountRole(Connection conn, DatabaseProductType databaseProductType, + String tenantManagerUserID, String tenantManagerAccountID, String tenantManagerRoleID, String tenantManagerRoleName ) + throws SQLException, Exception { + PreparedStatement pstmt = null; + try { + String insertAccountRoleSQL; + if (databaseProductType == DatabaseProductType.MYSQL) { + insertAccountRoleSQL = INSERT_ACCOUNT_ROLE_SQL_MYSQL; + } else if (databaseProductType == DatabaseProductType.POSTGRESQL) { + insertAccountRoleSQL = INSERT_ACCOUNT_ROLE_SQL_POSTGRES; + } else { + throw new Exception("Unrecognized database system."); + } + if (logger.isDebugEnabled()) { + logger.debug("bindTenantManagerAccountRole binding account to role with SQL:\n" + +insertAccountRoleSQL); + } + pstmt = conn.prepareStatement(insertAccountRoleSQL); // create a statement + pstmt.setString(1, tenantManagerAccountID); // set acct CSID param + pstmt.setString(2, tenantManagerUserID); // set user_id param + pstmt.setString(3, tenantManagerRoleID); // set role_id param + pstmt.setString(4, tenantManagerRoleName); // set rolename param + if (logger.isDebugEnabled()) { + logger.debug("bindTenantManagerAccountRole binding user: " + +tenantManagerUserID+" to Admin role("+tenantManagerRoleName+")"); + } + pstmt.executeUpdate(); + /* At this point, tenant manager should not need the Spring Admin Role + pstmt.setString(3, springAdminRoleCSID); // set role_id param + pstmt.setString(4, SPRING_ADMIN_ROLE); // set rolename param + if (logger.isDebugEnabled()) { + logger.debug("createDefaultAccounts binding account: " + +adminUserId+" to Spring Admin role: "+springAdminRoleCSID); + } + pstmt.executeUpdate(); + */ + pstmt.close(); + } catch(Exception e) { + throw e; + } finally { + if(pstmt!=null) + pstmt.close(); + } + } + + public static void createDefaultAccounts( + TenantBindingConfigReaderImpl tenantBindingConfigReader, + DatabaseProductType databaseProductType, + String cspaceDatabaseName) throws Exception { + + logger.debug("ServiceMain.createDefaultAccounts starting..."); + + Hashtable tenantInfo = getTenantNamesFromConfig(tenantBindingConfigReader); + Connection conn = null; + // TODO - need to put in tests for existence first. + // We could just look for the accounts per tenant up front, and assume that + // the rest is there if the accounts are. + // Could add a sql script to remove these if need be - Spring only does roles, + // and we're not touching that, so we could safely toss the + // accounts, users, account-tenants, account-roles, and start over. + try { + conn = getConnection(cspaceDatabaseName); + ArrayList existingTenants = compileExistingTenants(conn, tenantInfo); + + // Note that this only creates tenants not marked as "createDisabled" + createMissingTenants(conn, tenantInfo, existingTenants); + + ArrayList usersInRepo = findOrCreateDefaultUsers(conn, tenantInfo); + + Hashtable tenantAdminAcctCSIDs = new Hashtable(); + Hashtable tenantReaderAcctCSIDs = new Hashtable(); + findOrCreateDefaultAccounts(conn, tenantInfo, usersInRepo, + tenantAdminAcctCSIDs, tenantReaderAcctCSIDs); + + bindDefaultAccountsToTenants(conn, databaseProductType, tenantInfo, usersInRepo, + tenantAdminAcctCSIDs, tenantReaderAcctCSIDs); + + Hashtable tenantAdminRoleCSIDs = new Hashtable(); + Hashtable tenantReaderRoleCSIDs = new Hashtable(); + String springAdminRoleCSID = findOrCreateDefaultRoles(conn, tenantInfo, + tenantAdminRoleCSIDs, tenantReaderRoleCSIDs); + + bindAccountsToRoles(conn, databaseProductType, + tenantInfo, usersInRepo, springAdminRoleCSID, + tenantAdminRoleCSIDs, tenantReaderRoleCSIDs, + tenantAdminAcctCSIDs, tenantReaderAcctCSIDs); + + boolean createdTenantMgrAccount = findOrCreateTenantManagerUserAndAccount(conn); + if(createdTenantMgrAccount) { + // If we created the account, we need to create the bindings. Otherwise, assume they + // are all set (from previous initialization). + String tenantManagerRoleCSID = findTenantManagerRole(conn); + bindTenantManagerAccountRole(conn, databaseProductType, + TENANT_MANAGER_USER, AuthN.TENANT_MANAGER_ACCT_ID, + tenantManagerRoleCSID, ROLE_ALL_TENANTS_MANAGER); + } + } catch (Exception e) { + logger.debug("Exception in createDefaultAccounts: " + e.getLocalizedMessage()); + throw e; + } finally { + try { + if (conn != null) + conn.close(); + } catch (SQLException sqle) { + if (logger.isDebugEnabled()) { + logger.debug("SQL Exception closing statement/connection: " + sqle.getLocalizedMessage()); + } + } + } + } + + private static String getDefaultAdminRole(String tenantId) { + return ROLE_PREFIX+tenantId+TENANT_ADMIN_ROLE_SUFFIX; + } + + private static String getDefaultReaderRole(String tenantId) { + return ROLE_PREFIX+tenantId+TENANT_READER_ROLE_SUFFIX; + } + + private static String getDefaultAdminUserID(String tenantName) { + return TENANT_ADMIN_ACCT_PREFIX+tenantName; + } + + private static String getDefaultReaderUserID(String tenantName) { + return TENANT_READER_ACCT_PREFIX+tenantName; + } + + static public PermissionAction createPermissionAction(Permission perm, + ActionType actionType) { + PermissionAction pa = new PermissionAction(); + + CSpaceAction action = URIResourceImpl.getAction(actionType); + URIResourceImpl uriRes = new URIResourceImpl(perm.getTenantId(), + perm.getResourceName(), action); + pa.setName(actionType); + pa.setObjectIdentity(uriRes.getHashedId().toString()); + pa.setObjectIdentityResource(uriRes.getId()); + + return pa; + } + + static public PermissionAction update(Permission perm, PermissionAction permAction) { + PermissionAction pa = new PermissionAction(); + + CSpaceAction action = URIResourceImpl.getAction(permAction.getName()); + URIResourceImpl uriRes = new URIResourceImpl(perm.getTenantId(), + perm.getResourceName(), action); + pa.setObjectIdentity(uriRes.getHashedId().toString()); + pa.setObjectIdentityResource(uriRes.getId()); + + return pa; + } + + private static TransitionDefList getTransitionDefList(TenantBindingType tenantBinding, ServiceBindingType serviceBinding) { + TransitionDefList result = null; + try { + String serviceObjectName = serviceBinding.getObject().getName(); + DocumentHandler docHandler = ServiceConfigUtils.createDocumentHandlerInstance( + tenantBinding, serviceBinding); + Lifecycle lifecycle = docHandler.getLifecycle(serviceObjectName); + if (lifecycle != null) { + result = lifecycle.getTransitionDefList(); + } + } catch (Exception e) { + // Ignore this exception and return an empty non-null TransitionDefList + } + + if (result == null) { + if (serviceBinding.getType().equalsIgnoreCase(ServiceBindingUtils.SERVICE_TYPE_SECURITY) == false) { + logger.warn("Could not retrieve a lifecycle transition definition list from: " + + serviceBinding.getName() + + " with tenant ID = " + + tenantBinding.getId()); + } + // return an empty list + result = new TransitionDefList(); + } else { + logger.debug("Successfully retrieved a lifecycle transition definition list from: " + + serviceBinding.getName() + + " with tenant ID = " + + tenantBinding.getId()); + } + + return result; + } + + public static void createDefaultWorkflowPermissions(TenantBindingConfigReaderImpl tenantBindingConfigReader) throws Exception //FIXME: REM - 4/11/2012 - Rename to createWorkflowPermissions + { + AuthZ.get().login(); //login to Spring Security manager + + EntityManagerFactory emf = JpaStorageUtils.getEntityManagerFactory(JpaStorageUtils.CS_PERSISTENCE_UNIT); + EntityManager em = null; + + try { + em = emf.createEntityManager(); + + Hashtable tenantBindings = + tenantBindingConfigReader.getTenantBindings(); + for (String tenantId : tenantBindings.keySet()) { + TenantBindingType tenantBinding = tenantBindings.get(tenantId); + Role adminRole = AuthorizationCommon.getRole(em, tenantBinding.getId(), ROLE_TENANT_ADMINISTRATOR); + Role readonlyRole = AuthorizationCommon.getRole(em, tenantBinding.getId(), ROLE_TENANT_READER); + for (ServiceBindingType serviceBinding : tenantBinding.getServiceBindings()) { + String prop = ServiceBindingUtils.getPropertyValue(serviceBinding, REFRESH_AUTZ_PROP); + if (prop == null ? true : Boolean.parseBoolean(prop)) { + try { + em.getTransaction().begin(); + TransitionDefList transitionDefList = getTransitionDefList(tenantBinding, serviceBinding); + for (TransitionDef transitionDef : transitionDefList.getTransitionDef()) { + // + // Create the permission for the admin role + Permission adminPerm = createWorkflowPermission(tenantBinding, serviceBinding, transitionDef, ACTIONGROUP_CRUDL); + persist(em, adminPerm, adminRole, true); + // + // Create the permission for the read-only role + Permission readonlyPerm = createWorkflowPermission(tenantBinding, serviceBinding, transitionDef, ACTIONGROUP_RL); + + Profiler profiler = new Profiler(AuthorizationCommon.class, 1); + profiler.start("createDefaultPermissions started:" + readonlyPerm.getCsid()); + persist(em, readonlyPerm, readonlyRole, true); // Persist/store the permission and permrole records and related Spring Security info + profiler.stop(); + logger.debug("Finished full perm generation for " + + ":" + tenantBinding.getId() + + ":" + serviceBinding.getName() + + ":" + transitionDef.getName() + + ":" + ACTIONGROUP_RL + + ":" + profiler.getCumulativeTime()); + } + em.getTransaction().commit(); + } catch (IllegalStateException e) { + logger.debug(e.getLocalizedMessage(), e); //We end up here if there is no document handler for the service -this is ok for some of the services. + } + } else { + logger.warn("AuthZ refresh service binding property is set to FALSE so default permissions will NOT be refreshed for: " + + serviceBinding.getName()); + } + } + } + em.close(); + } catch (Exception e) { + if (em != null && em.getTransaction().isActive()) { + em.getTransaction().rollback(); + } + if (logger.isDebugEnabled()) { + logger.debug("Caught exception and rolling back permission creation: ", e); + } + throw e; + } finally { + if (em != null) { + JpaStorageUtils.releaseEntityManagerFactory(emf); + } + } + } + + private static PermissionRoleRel findPermRoleRel(EntityManager em, String permissionId, String RoleId) { + PermissionRoleRel result = null; + + try { + String whereClause = "where permissionId = :id and roleId = :roleId"; + HashMap params = new HashMap(); + params.put("id", permissionId); + params.put("roleId", RoleId); + + result = (PermissionRoleRel) JpaStorageUtils.getEntity(em, + PermissionRoleRel.class.getCanonicalName(), whereClause, params); + } catch (Exception e) { + //Do nothing. Will return null; + } + + return result; + } + + /* + * Persists the Permission, PermissionRoleRel, and Spring Security table entries all in one transaction + */ + private static void persist(EntityManager em, Permission permission, Role role, boolean enforceTenancy) throws Exception { + AuthorizationStore authzStore = new AuthorizationStore(); + // First persist the Permission record + authzStore.store(em, permission); + + // If the PermRoleRel doesn't already exists then relate the permission and the role in a new PermissionRole (the service payload) + // Create a PermissionRoleRel (the database relation table for the permission and role) + PermissionRoleRel permRoleRel = findPermRoleRel(em, permission.getCsid(), role.getCsid()); + if (permRoleRel == null) { + PermissionRole permRole = createPermissionRole(em, permission, role, enforceTenancy); + List permRoleRels = new ArrayList(); + PermissionRoleUtil.buildPermissionRoleRel(em, permRole, SubjectType.ROLE, permRoleRels, false /*not for delete*/); + for (PermissionRoleRel prr : permRoleRels) { + authzStore.store(em, prr); + } + Profiler profiler = new Profiler(AuthorizationCommon.class, 2); + profiler.start(); + // Add a corresponding entry in the Spring Security Tables + addPermissionsForUri(permission, permRole); + profiler.stop(); + logger.debug("Finished full perm generation for " + + ":" + permission.getTenantId() + + ":" + permission.getResourceName() + + ":" + ACTIONGROUP_RL + + ":" + profiler.getCumulativeTime()); + } + + } + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/authorization_mgt/AuthorizationRoleRel.java b/services/common/src/main/java/org/collectionspace/services/common/authorization_mgt/AuthorizationRoleRel.java index b2828e936..c61560505 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/authorization_mgt/AuthorizationRoleRel.java +++ b/services/common/src/main/java/org/collectionspace/services/common/authorization_mgt/AuthorizationRoleRel.java @@ -1,71 +1,71 @@ -package org.collectionspace.services.common.authorization_mgt; - -import org.collectionspace.services.authorization.AccountValue; -import org.collectionspace.services.authorization.PermissionRoleRel; -import org.collectionspace.services.authorization.AccountRoleRel; -import org.collectionspace.services.authorization.PermissionValue; -import org.collectionspace.services.authorization.RoleValue; - -public class AuthorizationRoleRel { - - /** - * Builds the account value. - * - * @param arr the arr - * @return the account value - */ - static public AccountValue buildAccountValue(AccountRoleRel arr) { - AccountValue av = new AccountValue(); - av.setAccountId(arr.getAccountId()); - av.setUserId(arr.getUserId()); - av.setScreenName(arr.getScreenName()); - return av; - } - - /** - * Builds the role value. - * - * @param arr the arr - * @return the role account value - */ - static public RoleValue buildRoleValue(AccountRoleRel arr) { - RoleValue rv = null; - if (arr.getRoleId().equals(AuthorizationCommon.ROLE_SPRING_ADMIN_ID) == false) { - rv = new RoleValue(); - rv.setRoleId(arr.getRoleId()); - rv.setRoleName(arr.getRoleName()); - rv.setRoleRelationshipId(arr.getHjid().toString()); - } - return rv; - } - - /** - * Builds the permission value. - * - * @param prr the prr - * @return the permission value - */ - static public PermissionValue buildPermissionValue(PermissionRoleRel prr) { - PermissionValue pv = new PermissionValue(); - pv.setPermissionId(prr.getPermissionId()); - pv.setResourceName(prr.getPermissionResource()); - pv.setActionGroup(prr.getActionGroup()); - pv.setPermRelationshipId(prr.getHjid().toString()); - return pv; - } - - /** - * Builds the role value. - * - * @param prr the prr - * @return the role value - */ - static public RoleValue buildRoleValue(PermissionRoleRel prr) { - RoleValue rv = new RoleValue(); - rv.setRoleId(prr.getRoleId()); - rv.setRoleName(prr.getRoleName()); - rv.setRoleRelationshipId(prr.getHjid().toString()); - return rv; - } - -} +package org.collectionspace.services.common.authorization_mgt; + +import org.collectionspace.services.authorization.AccountValue; +import org.collectionspace.services.authorization.PermissionRoleRel; +import org.collectionspace.services.authorization.AccountRoleRel; +import org.collectionspace.services.authorization.PermissionValue; +import org.collectionspace.services.authorization.RoleValue; + +public class AuthorizationRoleRel { + + /** + * Builds the account value. + * + * @param arr the arr + * @return the account value + */ + static public AccountValue buildAccountValue(AccountRoleRel arr) { + AccountValue av = new AccountValue(); + av.setAccountId(arr.getAccountId()); + av.setUserId(arr.getUserId()); + av.setScreenName(arr.getScreenName()); + return av; + } + + /** + * Builds the role value. + * + * @param arr the arr + * @return the role account value + */ + static public RoleValue buildRoleValue(AccountRoleRel arr) { + RoleValue rv = null; + if (arr.getRoleId().equals(AuthorizationCommon.ROLE_SPRING_ADMIN_ID) == false) { + rv = new RoleValue(); + rv.setRoleId(arr.getRoleId()); + rv.setRoleName(arr.getRoleName()); + rv.setRoleRelationshipId(arr.getHjid().toString()); + } + return rv; + } + + /** + * Builds the permission value. + * + * @param prr the prr + * @return the permission value + */ + static public PermissionValue buildPermissionValue(PermissionRoleRel prr) { + PermissionValue pv = new PermissionValue(); + pv.setPermissionId(prr.getPermissionId()); + pv.setResourceName(prr.getPermissionResource()); + pv.setActionGroup(prr.getActionGroup()); + pv.setPermRelationshipId(prr.getHjid().toString()); + return pv; + } + + /** + * Builds the role value. + * + * @param prr the prr + * @return the role value + */ + static public RoleValue buildRoleValue(PermissionRoleRel prr) { + RoleValue rv = new RoleValue(); + rv.setRoleId(prr.getRoleId()); + rv.setRoleName(prr.getRoleName()); + rv.setRoleRelationshipId(prr.getHjid().toString()); + return rv; + } + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/blob/BlobInput.java b/services/common/src/main/java/org/collectionspace/services/common/blob/BlobInput.java index 8cd38fb8e..5bc9eea7b 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/blob/BlobInput.java +++ b/services/common/src/main/java/org/collectionspace/services/common/blob/BlobInput.java @@ -1,230 +1,230 @@ -package org.collectionspace.services.common.blob; - -import java.io.File; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.servlet.http.HttpServletRequest; - -import org.collectionspace.services.nuxeo.client.java.CommonList; -import org.collectionspace.services.common.Download; -import org.collectionspace.services.common.document.DocumentException; -import org.collectionspace.services.common.imaging.nuxeo.NuxeoBlobUtils; - -import org.apache.commons.io.FileUtils; - -public class BlobInput { - private final Logger logger = LoggerFactory.getLogger(BlobInput.class); - private final static String FILE_ACCESS_ERROR = "The following file is either missing or cannot be read: "; - private final static String URL_DOWNLOAD_FAILED = "Could not download file from the following URL: "; - - private String blobCsid = null; - private File blobFile = null; - private String blobUri = null; - private String blobMimeType = null; - private String originalFileName = null; - - private String derivativeTerm; - private boolean derivativeListRequested = false; - private CommonList derivativeList; - - private boolean contentRequested = false; - private InputStream contentStream; - - private boolean schemaRequested = false; - - public static final String URI_CONTENT_PATH = "content"; - public static final String URI_DERIVATIVES_PATH = "derivatives"; - - /* - * Constructors - */ - public BlobInput() { - /* Empty constructor */ - } - - public BlobInput(File blobFile, String blobUri) { - this.blobFile = blobFile; - this.blobUri = blobUri; - } - - /* - * Save the original file name in case we rename it because of illegal Nuxeo file name characters - */ - private void setBlobFileName(String fileName) throws Exception { - String sanitizedResult = NuxeoBlobUtils.getSanizitedFilename(fileName); - if (fileName.equals(sanitizedResult) == true) { - originalFileName = null; // - } else { - originalFileName = fileName; - } - } - - public String getBlobFilename() throws Exception { - String result = null; - - if (originalFileName != null && originalFileName.trim().isEmpty() == false) { - result = originalFileName; - } else { - File theBlobFile = this.getBlobFile(); - if (theBlobFile != null) { - result = theBlobFile.getName(); - } - } - - // - // Add a log warning if the blob file name fails Nuxeo's file name restrictions. - // - String sanitizedResult = NuxeoBlobUtils.getSanizitedFilename(result); - if (result.equals(sanitizedResult) == false) { - logger.warn(String.format("The file name '%s' contains characters that Nuxeo deems illegal.", - result)); - } - - return result; - } - - /* - * Getters and Setters - */ - public boolean isSchemaRequested() { - return schemaRequested; - } - - public void setSchemaRequested(boolean schemaRequested) { - this.schemaRequested = schemaRequested; - } - - public String getBlobCsid() { - return blobCsid; - } - - public void setBlobCsid(String blobCsid) { - this.blobCsid = blobCsid; - } - - public File getBlobFile() { - return blobFile; - } - - public void setBlobFile(File blobFile) throws Exception { - this.blobFile = blobFile; - if (blobFile != null) { - String fileName = blobFile.getName(); - setBlobFileName(fileName); - } - } - - public String getBlobUri() { - return blobUri; - } - - public void setBlobUri(String blobUri) { - this.blobUri = blobUri; - } - - public String getDerivativeTerm() { - return derivativeTerm; - } - - public void setDerivativeTerm(String derivativeTerm) { - this.derivativeTerm = derivativeTerm; - } - - public boolean isDerivativeListRequested() { - return derivativeListRequested; - } - - public void setDerivativeListRequested(boolean derivativesRequested) { - this.derivativeListRequested = derivativesRequested; - } - - public CommonList getDerivativeList() { - return derivativeList; - } - - public void setDerivativeList(CommonList derivativeList) { - this.derivativeList = derivativeList; - } - - public InputStream getContentStream() { - return contentStream; - } - - public void setContentStream(InputStream contentStream) { - this.contentStream = contentStream; - } - - public boolean isContentRequested() { - return contentRequested; - } - - public void setContentRequested(boolean contentRequested) { - this.contentRequested = contentRequested; - } - /* - * End of setters and getters - */ - - // - // FIXME: REM - The callers of this method are sending us a multipart form-data post, so why - // are we also receiving the blobUri? - // - public void createBlobFile(HttpServletRequest req, String blobUri) throws Exception { - File tmpFile = org.collectionspace.services.common.FileUtils.createTmpFile(req); - this.setBlobFile(tmpFile); - this.setBlobUri(blobUri); - } - - public void createBlobFile(String theBlobUri) throws MalformedURLException, Exception { - URL blobUrl = new URL(theBlobUri); - File theBlobFile = null; - - if (blobUrl.getProtocol().equalsIgnoreCase("http")) { //REM: Add support for https as well - Download fetchedFile = new Download(blobUrl); - if (logger.isDebugEnabled() == true) { - logger.debug("Starting blob download into temp file:" + fetchedFile.getFilePath()); - } - while (fetchedFile.getStatus() == Download.DOWNLOADING) { - // Do nothing while we wait for the file to download - } - if (logger.isDebugEnabled() == true) { - logger.debug("Finished blob download into temp file: " + fetchedFile.getFilePath()); - } - - int status = fetchedFile.getStatus(); - if (status == Download.COMPLETE) { - theBlobFile = fetchedFile.getFile(); - } else { - String msg = URL_DOWNLOAD_FAILED + theBlobUri; - logger.error(msg); - throw new DocumentException(msg); - } - } else if (blobUrl.getProtocol().equalsIgnoreCase("file")) { - theBlobFile = FileUtils.toFile(blobUrl); - if (theBlobFile.exists() == false || theBlobFile.canRead() == false) { - String msg = FILE_ACCESS_ERROR + theBlobFile.getAbsolutePath(); - logger.error(msg); - throw new DocumentException(msg); - } - } else { - throw new MalformedURLException("Could not create a blob file from: " + blobUrl); - } - this.setBlobFile(theBlobFile); - this.setBlobUri(blobUri); - } - - public String getMimeType() { - return blobMimeType; - } - - public void setMimeType(String mimeType) { - this.blobMimeType = mimeType; - } - -} - +package org.collectionspace.services.common.blob; + +import java.io.File; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.http.HttpServletRequest; + +import org.collectionspace.services.nuxeo.client.java.CommonList; +import org.collectionspace.services.common.Download; +import org.collectionspace.services.common.document.DocumentException; +import org.collectionspace.services.common.imaging.nuxeo.NuxeoBlobUtils; + +import org.apache.commons.io.FileUtils; + +public class BlobInput { + private final Logger logger = LoggerFactory.getLogger(BlobInput.class); + private final static String FILE_ACCESS_ERROR = "The following file is either missing or cannot be read: "; + private final static String URL_DOWNLOAD_FAILED = "Could not download file from the following URL: "; + + private String blobCsid = null; + private File blobFile = null; + private String blobUri = null; + private String blobMimeType = null; + private String originalFileName = null; + + private String derivativeTerm; + private boolean derivativeListRequested = false; + private CommonList derivativeList; + + private boolean contentRequested = false; + private InputStream contentStream; + + private boolean schemaRequested = false; + + public static final String URI_CONTENT_PATH = "content"; + public static final String URI_DERIVATIVES_PATH = "derivatives"; + + /* + * Constructors + */ + public BlobInput() { + /* Empty constructor */ + } + + public BlobInput(File blobFile, String blobUri) { + this.blobFile = blobFile; + this.blobUri = blobUri; + } + + /* + * Save the original file name in case we rename it because of illegal Nuxeo file name characters + */ + private void setBlobFileName(String fileName) throws Exception { + String sanitizedResult = NuxeoBlobUtils.getSanizitedFilename(fileName); + if (fileName.equals(sanitizedResult) == true) { + originalFileName = null; // + } else { + originalFileName = fileName; + } + } + + public String getBlobFilename() throws Exception { + String result = null; + + if (originalFileName != null && originalFileName.trim().isEmpty() == false) { + result = originalFileName; + } else { + File theBlobFile = this.getBlobFile(); + if (theBlobFile != null) { + result = theBlobFile.getName(); + } + } + + // + // Add a log warning if the blob file name fails Nuxeo's file name restrictions. + // + String sanitizedResult = NuxeoBlobUtils.getSanizitedFilename(result); + if (result.equals(sanitizedResult) == false) { + logger.warn(String.format("The file name '%s' contains characters that Nuxeo deems illegal.", + result)); + } + + return result; + } + + /* + * Getters and Setters + */ + public boolean isSchemaRequested() { + return schemaRequested; + } + + public void setSchemaRequested(boolean schemaRequested) { + this.schemaRequested = schemaRequested; + } + + public String getBlobCsid() { + return blobCsid; + } + + public void setBlobCsid(String blobCsid) { + this.blobCsid = blobCsid; + } + + public File getBlobFile() { + return blobFile; + } + + public void setBlobFile(File blobFile) throws Exception { + this.blobFile = blobFile; + if (blobFile != null) { + String fileName = blobFile.getName(); + setBlobFileName(fileName); + } + } + + public String getBlobUri() { + return blobUri; + } + + public void setBlobUri(String blobUri) { + this.blobUri = blobUri; + } + + public String getDerivativeTerm() { + return derivativeTerm; + } + + public void setDerivativeTerm(String derivativeTerm) { + this.derivativeTerm = derivativeTerm; + } + + public boolean isDerivativeListRequested() { + return derivativeListRequested; + } + + public void setDerivativeListRequested(boolean derivativesRequested) { + this.derivativeListRequested = derivativesRequested; + } + + public CommonList getDerivativeList() { + return derivativeList; + } + + public void setDerivativeList(CommonList derivativeList) { + this.derivativeList = derivativeList; + } + + public InputStream getContentStream() { + return contentStream; + } + + public void setContentStream(InputStream contentStream) { + this.contentStream = contentStream; + } + + public boolean isContentRequested() { + return contentRequested; + } + + public void setContentRequested(boolean contentRequested) { + this.contentRequested = contentRequested; + } + /* + * End of setters and getters + */ + + // + // FIXME: REM - The callers of this method are sending us a multipart form-data post, so why + // are we also receiving the blobUri? + // + public void createBlobFile(HttpServletRequest req, String blobUri) throws Exception { + File tmpFile = org.collectionspace.services.common.FileUtils.createTmpFile(req); + this.setBlobFile(tmpFile); + this.setBlobUri(blobUri); + } + + public void createBlobFile(String theBlobUri) throws MalformedURLException, Exception { + URL blobUrl = new URL(theBlobUri); + File theBlobFile = null; + + if (blobUrl.getProtocol().equalsIgnoreCase("http")) { //REM: Add support for https as well + Download fetchedFile = new Download(blobUrl); + if (logger.isDebugEnabled() == true) { + logger.debug("Starting blob download into temp file:" + fetchedFile.getFilePath()); + } + while (fetchedFile.getStatus() == Download.DOWNLOADING) { + // Do nothing while we wait for the file to download + } + if (logger.isDebugEnabled() == true) { + logger.debug("Finished blob download into temp file: " + fetchedFile.getFilePath()); + } + + int status = fetchedFile.getStatus(); + if (status == Download.COMPLETE) { + theBlobFile = fetchedFile.getFile(); + } else { + String msg = URL_DOWNLOAD_FAILED + theBlobUri; + logger.error(msg); + throw new DocumentException(msg); + } + } else if (blobUrl.getProtocol().equalsIgnoreCase("file")) { + theBlobFile = FileUtils.toFile(blobUrl); + if (theBlobFile.exists() == false || theBlobFile.canRead() == false) { + String msg = FILE_ACCESS_ERROR + theBlobFile.getAbsolutePath(); + logger.error(msg); + throw new DocumentException(msg); + } + } else { + throw new MalformedURLException("Could not create a blob file from: " + blobUrl); + } + this.setBlobFile(theBlobFile); + this.setBlobUri(blobUri); + } + + public String getMimeType() { + return blobMimeType; + } + + public void setMimeType(String mimeType) { + this.blobMimeType = mimeType; + } + +} + diff --git a/services/common/src/main/java/org/collectionspace/services/common/blob/BlobOutput.java b/services/common/src/main/java/org/collectionspace/services/common/blob/BlobOutput.java index a9325d853..6acb2a327 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/blob/BlobOutput.java +++ b/services/common/src/main/java/org/collectionspace/services/common/blob/BlobOutput.java @@ -1,29 +1,29 @@ -package org.collectionspace.services.common.blob; - -import java.io.InputStream; -import org.collectionspace.services.blob.BlobsCommon; - -public class BlobOutput { - private String mimeType; - private BlobsCommon blobsCommon; - private InputStream blobInputStream; - - public BlobsCommon getBlobsCommon() { - return blobsCommon; - } - public void setBlobsCommon(BlobsCommon blobsCommon) { - this.blobsCommon = blobsCommon; - } - public InputStream getBlobInputStream() { - return blobInputStream; - } - public void setBlobInputStream(InputStream blobInputStream) { - this.blobInputStream = blobInputStream; - } - public String getMimeType() { - return mimeType; - } - public void setMimeType(String mimeType) { - this.mimeType = mimeType; - } -} +package org.collectionspace.services.common.blob; + +import java.io.InputStream; +import org.collectionspace.services.blob.BlobsCommon; + +public class BlobOutput { + private String mimeType; + private BlobsCommon blobsCommon; + private InputStream blobInputStream; + + public BlobsCommon getBlobsCommon() { + return blobsCommon; + } + public void setBlobsCommon(BlobsCommon blobsCommon) { + this.blobsCommon = blobsCommon; + } + public InputStream getBlobInputStream() { + return blobInputStream; + } + public void setBlobInputStream(InputStream blobInputStream) { + this.blobInputStream = blobInputStream; + } + public String getMimeType() { + return mimeType; + } + public void setMimeType(String mimeType) { + this.mimeType = mimeType; + } +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/blob/BlobUtil.java b/services/common/src/main/java/org/collectionspace/services/common/blob/BlobUtil.java index bd45a7784..39d271206 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/blob/BlobUtil.java +++ b/services/common/src/main/java/org/collectionspace/services/common/blob/BlobUtil.java @@ -1,36 +1,36 @@ -package org.collectionspace.services.common.blob; - -import org.collectionspace.services.client.PoxPayloadIn; -import org.collectionspace.services.client.PoxPayloadOut; -import org.collectionspace.services.common.context.ServiceContext; -//import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; -//import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class BlobUtil { - // - // - private static final Logger logger = LoggerFactory.getLogger(BlobUtil.class); - - public static BlobInput getBlobInput(ServiceContext ctx) { - BlobInput result = (BlobInput)ctx.getProperty(BlobInput.class.getName()); - if (result == null) { - result = new BlobInput(); - setBlobInput(ctx, result); - } - return result; - } - - public static BlobInput resetBlobInput(ServiceContext ctx) { - BlobInput blobInput = new BlobInput(); - setBlobInput(ctx, blobInput); - return blobInput; - } - - public static void setBlobInput(ServiceContext ctx, - BlobInput blobInput) { - ctx.setProperty(BlobInput.class.getName(), blobInput); - } - -} +package org.collectionspace.services.common.blob; + +import org.collectionspace.services.client.PoxPayloadIn; +import org.collectionspace.services.client.PoxPayloadOut; +import org.collectionspace.services.common.context.ServiceContext; +//import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; +//import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class BlobUtil { + // + // + private static final Logger logger = LoggerFactory.getLogger(BlobUtil.class); + + public static BlobInput getBlobInput(ServiceContext ctx) { + BlobInput result = (BlobInput)ctx.getProperty(BlobInput.class.getName()); + if (result == null) { + result = new BlobInput(); + setBlobInput(ctx, result); + } + return result; + } + + public static BlobInput resetBlobInput(ServiceContext ctx) { + BlobInput blobInput = new BlobInput(); + setBlobInput(ctx, blobInput); + return blobInput; + } + + public static void setBlobInput(ServiceContext ctx, + BlobInput blobInput) { + ctx.setProperty(BlobInput.class.getName(), blobInput); + } + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/config/ServiceConfigUtils.java b/services/common/src/main/java/org/collectionspace/services/common/config/ServiceConfigUtils.java index e79d3dc80..53f57b468 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/config/ServiceConfigUtils.java +++ b/services/common/src/main/java/org/collectionspace/services/common/config/ServiceConfigUtils.java @@ -1,144 +1,144 @@ -/** - * 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.config; - -import java.util.ArrayList; -import java.util.List; - -import org.collectionspace.services.common.context.ServiceContext; -import org.collectionspace.services.common.document.DocumentException; -import org.collectionspace.services.common.document.DocumentHandler; -import org.collectionspace.services.config.RepositoryClientConfigType; -import org.collectionspace.services.config.ServiceConfig; -import org.collectionspace.services.config.service.DocHandlerParams; -import org.collectionspace.services.config.service.ServiceBindingType; -import org.collectionspace.services.config.tenant.TenantBindingType; -import org.collectionspace.services.config.types.PropertyItemType; -import org.collectionspace.services.config.types.PropertyType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author pschmitz - * - */ -public class ServiceConfigUtils { - - final static Logger logger = LoggerFactory.getLogger(ServiceConfigUtils.class); - - /* - * Returns the document handler parameters that were loaded at startup from the - * tenant bindings config file. - */ - public static DocHandlerParams.Params getDocHandlerParams(ServiceContext ctx) throws DocumentException { - ServiceBindingType sb = ctx.getServiceBinding(); - DocHandlerParams dhb = sb.getDocHandlerParams(); - if (dhb != null && dhb.getParams() != null) { - return dhb.getParams(); - } - throw new DocumentException("No DocHandlerParams configured for: " - + sb.getName()); - } - - /** - * Creates the document handler instance. - * - * @return the document handler - * - * @throws Exception the exception - */ - public static DocumentHandler createDocumentHandlerInstance(TenantBindingType tenantBinding, - ServiceBindingType serviceBinding) throws Exception { - DocumentHandler docHandler = null; - - ClassLoader tccl = Thread.currentThread().getContextClassLoader(); - Class c = tccl.loadClass(getDocumentHandlerClass(tenantBinding, serviceBinding)); - if (DocumentHandler.class.isAssignableFrom(c)) { - docHandler = (DocumentHandler) c.newInstance(); - if (logger.isDebugEnabled()) { - logger.debug("Created an instance of the DocumentHandler for: " + getDocumentHandlerClass(tenantBinding, serviceBinding)); - } - } else { - throw new IllegalArgumentException("Not of type " - + DocumentHandler.class.getCanonicalName()); - } - - return docHandler; - } - - /** - * Gets the document handler class. - * - * @return the document handler class - */ - private static String getDocumentHandlerClass(TenantBindingType tenantBinding, - ServiceBindingType serviceBinding) { - if (serviceBinding.getDocumentHandler() == null - || serviceBinding.getDocumentHandler().isEmpty()) { - String msg = "Missing documentHandler in service binding for service name \"" - + serviceBinding.getName() + "\" for tenant id=" + tenantBinding.getId() - + " name=" + tenantBinding.getName(); - logger.warn(msg); - throw new IllegalStateException(msg); - } - return serviceBinding.getDocumentHandler().trim(); - } - - /** - * Gets the values of a configured property for a service. - * - * @param serviceConfiga tenant binding - * @param propName the property to fetch (can return multiple values for this property). - * @return a list of values for the supplied property. - */ - public static List getPropertyValues(ServiceConfig serviceConfig, - String propName) { - List propValues = null; - if(propName==null) { - throw new IllegalArgumentException("ServiceConfilUtils.getPropertyValues: null property name!"); - } - RepositoryClientConfigType repoClient = serviceConfig.getRepositoryClient(); - if(repoClient==null) { - throw new RuntimeException("ServiceConfilUtils.getPropertyValues: serviceConfig has NULL repoClient!"); - } - List propList = repoClient.getProperties(); - if(propList!=null && propList.size()>0) { - List propItems = propList.get(0).getItem(); - for(PropertyItemType propItem:propItems) { - if(propName.equals(propItem.getKey())) { - String value = propItem.getValue(); - if(value!=null) { - if(propValues==null) { - propValues = new ArrayList(); - } - propValues.add(value); - } - } - } - } - return propValues; - } - - -} +/** + * 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.config; + +import java.util.ArrayList; +import java.util.List; + +import org.collectionspace.services.common.context.ServiceContext; +import org.collectionspace.services.common.document.DocumentException; +import org.collectionspace.services.common.document.DocumentHandler; +import org.collectionspace.services.config.RepositoryClientConfigType; +import org.collectionspace.services.config.ServiceConfig; +import org.collectionspace.services.config.service.DocHandlerParams; +import org.collectionspace.services.config.service.ServiceBindingType; +import org.collectionspace.services.config.tenant.TenantBindingType; +import org.collectionspace.services.config.types.PropertyItemType; +import org.collectionspace.services.config.types.PropertyType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author pschmitz + * + */ +public class ServiceConfigUtils { + + final static Logger logger = LoggerFactory.getLogger(ServiceConfigUtils.class); + + /* + * Returns the document handler parameters that were loaded at startup from the + * tenant bindings config file. + */ + public static DocHandlerParams.Params getDocHandlerParams(ServiceContext ctx) throws DocumentException { + ServiceBindingType sb = ctx.getServiceBinding(); + DocHandlerParams dhb = sb.getDocHandlerParams(); + if (dhb != null && dhb.getParams() != null) { + return dhb.getParams(); + } + throw new DocumentException("No DocHandlerParams configured for: " + + sb.getName()); + } + + /** + * Creates the document handler instance. + * + * @return the document handler + * + * @throws Exception the exception + */ + public static DocumentHandler createDocumentHandlerInstance(TenantBindingType tenantBinding, + ServiceBindingType serviceBinding) throws Exception { + DocumentHandler docHandler = null; + + ClassLoader tccl = Thread.currentThread().getContextClassLoader(); + Class c = tccl.loadClass(getDocumentHandlerClass(tenantBinding, serviceBinding)); + if (DocumentHandler.class.isAssignableFrom(c)) { + docHandler = (DocumentHandler) c.newInstance(); + if (logger.isDebugEnabled()) { + logger.debug("Created an instance of the DocumentHandler for: " + getDocumentHandlerClass(tenantBinding, serviceBinding)); + } + } else { + throw new IllegalArgumentException("Not of type " + + DocumentHandler.class.getCanonicalName()); + } + + return docHandler; + } + + /** + * Gets the document handler class. + * + * @return the document handler class + */ + private static String getDocumentHandlerClass(TenantBindingType tenantBinding, + ServiceBindingType serviceBinding) { + if (serviceBinding.getDocumentHandler() == null + || serviceBinding.getDocumentHandler().isEmpty()) { + String msg = "Missing documentHandler in service binding for service name \"" + + serviceBinding.getName() + "\" for tenant id=" + tenantBinding.getId() + + " name=" + tenantBinding.getName(); + logger.warn(msg); + throw new IllegalStateException(msg); + } + return serviceBinding.getDocumentHandler().trim(); + } + + /** + * Gets the values of a configured property for a service. + * + * @param serviceConfiga tenant binding + * @param propName the property to fetch (can return multiple values for this property). + * @return a list of values for the supplied property. + */ + public static List getPropertyValues(ServiceConfig serviceConfig, + String propName) { + List propValues = null; + if(propName==null) { + throw new IllegalArgumentException("ServiceConfilUtils.getPropertyValues: null property name!"); + } + RepositoryClientConfigType repoClient = serviceConfig.getRepositoryClient(); + if(repoClient==null) { + throw new RuntimeException("ServiceConfilUtils.getPropertyValues: serviceConfig has NULL repoClient!"); + } + List propList = repoClient.getProperties(); + if(propList!=null && propList.size()>0) { + List propItems = propList.get(0).getItem(); + for(PropertyItemType propItem:propItems) { + if(propName.equals(propItem.getKey())) { + String value = propItem.getValue(); + if(value!=null) { + if(propValues==null) { + propValues = new ArrayList(); + } + propValues.add(value); + } + } + } + } + return propValues; + } + + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/config/TenantBindingUtils.java b/services/common/src/main/java/org/collectionspace/services/common/config/TenantBindingUtils.java index 142c4ba64..48718a6e5 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/config/TenantBindingUtils.java +++ b/services/common/src/main/java/org/collectionspace/services/common/config/TenantBindingUtils.java @@ -1,115 +1,115 @@ -package org.collectionspace.services.common.config; - -import java.util.ArrayList; -import java.util.List; - -import org.collectionspace.services.common.context.ServiceBindingUtils; -import org.collectionspace.services.config.service.ServiceBindingType; -import org.collectionspace.services.config.tenant.TenantBindingType; -import org.collectionspace.services.config.types.PropertyItemType; -import org.collectionspace.services.config.types.PropertyType; - - -public class TenantBindingUtils { - - public static final boolean SET_PROP_IF_MISSING = true; - public static final boolean SET_PROP_ALWAYS = false; - - /** - * @param tenantBinding - * @param propName the property to fetch - * @return the String value of the named property - */ - public static String getPropertyValue(TenantBindingType tenantBinding, - String propName) { - if (propName == null) { - throw new IllegalArgumentException("TenantBindingUtils.getPropertyValue: null property name!"); - } - List tenantPropList = tenantBinding.getProperties(); - return PropertyItemUtils.getPropertyValueByNameFromNodeList(tenantPropList, propName); - } - - /** - * Gets the values of a configured property for a tenant. - * - * @param tenantBinding a tenant binding - * @param propName the property to fetch (can return multiple values for this property). - * @return a list of values for the supplied property. - */ - public static List getPropertyValues(TenantBindingType tenantBinding, - String propName) { - List propValues = null; - List propList = tenantBinding.getProperties(); - if (propList != null && propList.size() > 0) { - List propItems = propList.get(0).getItem(); - for (PropertyItemType propItem : propItems) { - if (propName.equals(propItem.getKey())) { - String value = propItem.getValue(); - if (value != null) { - if (propValues == null) { - propValues = new ArrayList(); - } - propValues.add(value); - } - } - } - } - return propValues; - } - - /** - * @param service - * @param propName the property to fetch - * @param value the new value to set - * @param onlyIfNotSet if true, will not override an existing value - * @return true if set, false if an existing value was left as is. - */ - public static boolean setPropertyValue(TenantBindingType tenantBinding, - PropertyItemType prop, boolean onlyIfNotSet) { - if (prop == null) { - throw new IllegalArgumentException( - "TenantBindingUtils.setPropertyValue: null property!"); - } - return setPropertyValue(tenantBinding, prop.getKey(), prop.getValue(), - onlyIfNotSet); - } - - /** - * @param tenantBinding - * @param propName the property to fetch - * @param value the new value to set - * @param onlyIfNotSet if true, will not override an existing value - * @return true if set, false if an existing value was left as is. - */ - public static boolean setPropertyValue(TenantBindingType tenantBinding, - String propName, String value, - boolean onlyIfNotSet) { - boolean valueFound = false; - boolean valueSet = false; - if (propName == null) { - throw new IllegalArgumentException("TenantBindingUtils.setPropertyValue: null property name!"); - } - List tenantPropertiesNode = tenantBinding.getProperties(); - return PropertyItemUtils.setPropertyValueInNodeList(tenantPropertiesNode, - propName, value, onlyIfNotSet); - } - - /** - * @param tenantBinding - * @param propName the property to fetch - * @param value the new value to set - * @param onlyIfNotSet if true, will not override an existing value - * @return true if set, false if an existing value was left as is. - */ - public static void propagatePropertiesToServices( - TenantBindingType tenantBinding, boolean onlyIfNotSet) { - List tenantPropList = - tenantBinding.getProperties().get(0).getItem(); - for (PropertyItemType tenantPropItem : tenantPropList) { - for (ServiceBindingType service : tenantBinding.getServiceBindings()) { - ServiceBindingUtils.setPropertyValue(service, - tenantPropItem, onlyIfNotSet); - } - } - } -} +package org.collectionspace.services.common.config; + +import java.util.ArrayList; +import java.util.List; + +import org.collectionspace.services.common.context.ServiceBindingUtils; +import org.collectionspace.services.config.service.ServiceBindingType; +import org.collectionspace.services.config.tenant.TenantBindingType; +import org.collectionspace.services.config.types.PropertyItemType; +import org.collectionspace.services.config.types.PropertyType; + + +public class TenantBindingUtils { + + public static final boolean SET_PROP_IF_MISSING = true; + public static final boolean SET_PROP_ALWAYS = false; + + /** + * @param tenantBinding + * @param propName the property to fetch + * @return the String value of the named property + */ + public static String getPropertyValue(TenantBindingType tenantBinding, + String propName) { + if (propName == null) { + throw new IllegalArgumentException("TenantBindingUtils.getPropertyValue: null property name!"); + } + List tenantPropList = tenantBinding.getProperties(); + return PropertyItemUtils.getPropertyValueByNameFromNodeList(tenantPropList, propName); + } + + /** + * Gets the values of a configured property for a tenant. + * + * @param tenantBinding a tenant binding + * @param propName the property to fetch (can return multiple values for this property). + * @return a list of values for the supplied property. + */ + public static List getPropertyValues(TenantBindingType tenantBinding, + String propName) { + List propValues = null; + List propList = tenantBinding.getProperties(); + if (propList != null && propList.size() > 0) { + List propItems = propList.get(0).getItem(); + for (PropertyItemType propItem : propItems) { + if (propName.equals(propItem.getKey())) { + String value = propItem.getValue(); + if (value != null) { + if (propValues == null) { + propValues = new ArrayList(); + } + propValues.add(value); + } + } + } + } + return propValues; + } + + /** + * @param service + * @param propName the property to fetch + * @param value the new value to set + * @param onlyIfNotSet if true, will not override an existing value + * @return true if set, false if an existing value was left as is. + */ + public static boolean setPropertyValue(TenantBindingType tenantBinding, + PropertyItemType prop, boolean onlyIfNotSet) { + if (prop == null) { + throw new IllegalArgumentException( + "TenantBindingUtils.setPropertyValue: null property!"); + } + return setPropertyValue(tenantBinding, prop.getKey(), prop.getValue(), + onlyIfNotSet); + } + + /** + * @param tenantBinding + * @param propName the property to fetch + * @param value the new value to set + * @param onlyIfNotSet if true, will not override an existing value + * @return true if set, false if an existing value was left as is. + */ + public static boolean setPropertyValue(TenantBindingType tenantBinding, + String propName, String value, + boolean onlyIfNotSet) { + boolean valueFound = false; + boolean valueSet = false; + if (propName == null) { + throw new IllegalArgumentException("TenantBindingUtils.setPropertyValue: null property name!"); + } + List tenantPropertiesNode = tenantBinding.getProperties(); + return PropertyItemUtils.setPropertyValueInNodeList(tenantPropertiesNode, + propName, value, onlyIfNotSet); + } + + /** + * @param tenantBinding + * @param propName the property to fetch + * @param value the new value to set + * @param onlyIfNotSet if true, will not override an existing value + * @return true if set, false if an existing value was left as is. + */ + public static void propagatePropertiesToServices( + TenantBindingType tenantBinding, boolean onlyIfNotSet) { + List tenantPropList = + tenantBinding.getProperties().get(0).getItem(); + for (PropertyItemType tenantPropItem : tenantPropList) { + for (ServiceBindingType service : tenantBinding.getServiceBindings()) { + ServiceBindingUtils.setPropertyValue(service, + tenantPropItem, onlyIfNotSet); + } + } + } +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/context/JaxRsContext.java b/services/common/src/main/java/org/collectionspace/services/common/context/JaxRsContext.java index af105c112..4ff8c5c22 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/context/JaxRsContext.java +++ b/services/common/src/main/java/org/collectionspace/services/common/context/JaxRsContext.java @@ -1,22 +1,22 @@ -package org.collectionspace.services.common.context; - -import javax.ws.rs.core.Request; -import javax.ws.rs.core.UriInfo; - -public class JaxRsContext { - private Request request; - private UriInfo uriInfo; - - public JaxRsContext(Request theRequest, UriInfo theUriInfo) { - this.request = theRequest; - this.uriInfo = theUriInfo; - } - - public Request getRequest() { - return request; - } - - public UriInfo getUriInfo() { - return uriInfo; - } -} +package org.collectionspace.services.common.context; + +import javax.ws.rs.core.Request; +import javax.ws.rs.core.UriInfo; + +public class JaxRsContext { + private Request request; + private UriInfo uriInfo; + + public JaxRsContext(Request theRequest, UriInfo theUriInfo) { + this.request = theRequest; + this.uriInfo = theUriInfo; + } + + public Request getRequest() { + return request; + } + + public UriInfo getUriInfo() { + return uriInfo; + } +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/context/RemoteServiceContextFactory.java b/services/common/src/main/java/org/collectionspace/services/common/context/RemoteServiceContextFactory.java index 2f23e54e6..f312ad729 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/context/RemoteServiceContextFactory.java +++ b/services/common/src/main/java/org/collectionspace/services/common/context/RemoteServiceContextFactory.java @@ -1,112 +1,112 @@ -/** - * RemoteServiceContextFactory.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.context; - -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.UriInfo; - -import org.collectionspace.services.common.ResourceMap; - - -/** - * A factory for creating RemoteServiceContext objects. - */ -public class RemoteServiceContextFactory - implements ServiceContextFactory{ - - // create a Factory singleton - /** The Constant self. */ - final private static RemoteServiceContextFactory self = new RemoteServiceContextFactory(); - - /** - * Instantiates a new remote service context factory. - */ - private RemoteServiceContextFactory() {} // private constructor - - /** - * Gets the. - * - * @return the remote service context factory - */ - public static RemoteServiceContextFactory get() { - return self; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.common.context.ServiceContextFactory#createServiceContext(java.lang.String) - */ - @Override - public ServiceContext createServiceContext(String serviceName, UriInfo uriInfo) throws Exception { - RemoteServiceContext ctx = new RemoteServiceContextImpl(serviceName, uriInfo); - return ctx; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.common.context.ServiceContextFactory#createServiceContext(java.lang.String, java.lang.Object) - */ - @Override - public ServiceContext createServiceContext(String serviceName, - IT theInput, UriInfo uriInfo) throws Exception { - RemoteServiceContext ctx = new RemoteServiceContextImpl(serviceName, theInput, uriInfo); - return ctx; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.common.context.ServiceContextFactory#createServiceContext(java.lang.String, java.lang.Object, javax.ws.rs.core.MultivaluedMap) - */ - @Override - public ServiceContext createServiceContext( - String serviceName, - IT theInput, - ResourceMap resourceMap, - UriInfo uriInfo) throws Exception { - ServiceContext ctx = new RemoteServiceContextImpl(serviceName, - theInput, - resourceMap, - uriInfo); - - return ctx; - } - - @Override - public ServiceContext createServiceContext(String serviceName, - IT input, - ResourceMap resourceMap, - UriInfo uriInfo, - String documentType, - String entityName) throws Exception { - ServiceContext ctx = createServiceContext( - serviceName, - input, - resourceMap, - uriInfo); - ctx.setDocumentType(documentType); //persistence unit - ctx.setProperty(ServiceContextProperties.ENTITY_NAME, entityName); - return ctx; - } - -} +/** + * RemoteServiceContextFactory.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.context; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriInfo; + +import org.collectionspace.services.common.ResourceMap; + + +/** + * A factory for creating RemoteServiceContext objects. + */ +public class RemoteServiceContextFactory + implements ServiceContextFactory{ + + // create a Factory singleton + /** The Constant self. */ + final private static RemoteServiceContextFactory self = new RemoteServiceContextFactory(); + + /** + * Instantiates a new remote service context factory. + */ + private RemoteServiceContextFactory() {} // private constructor + + /** + * Gets the. + * + * @return the remote service context factory + */ + public static RemoteServiceContextFactory get() { + return self; + } + + /* (non-Javadoc) + * @see org.collectionspace.services.common.context.ServiceContextFactory#createServiceContext(java.lang.String) + */ + @Override + public ServiceContext createServiceContext(String serviceName, UriInfo uriInfo) throws Exception { + RemoteServiceContext ctx = new RemoteServiceContextImpl(serviceName, uriInfo); + return ctx; + } + + /* (non-Javadoc) + * @see org.collectionspace.services.common.context.ServiceContextFactory#createServiceContext(java.lang.String, java.lang.Object) + */ + @Override + public ServiceContext createServiceContext(String serviceName, + IT theInput, UriInfo uriInfo) throws Exception { + RemoteServiceContext ctx = new RemoteServiceContextImpl(serviceName, theInput, uriInfo); + return ctx; + } + + /* (non-Javadoc) + * @see org.collectionspace.services.common.context.ServiceContextFactory#createServiceContext(java.lang.String, java.lang.Object, javax.ws.rs.core.MultivaluedMap) + */ + @Override + public ServiceContext createServiceContext( + String serviceName, + IT theInput, + ResourceMap resourceMap, + UriInfo uriInfo) throws Exception { + ServiceContext ctx = new RemoteServiceContextImpl(serviceName, + theInput, + resourceMap, + uriInfo); + + return ctx; + } + + @Override + public ServiceContext createServiceContext(String serviceName, + IT input, + ResourceMap resourceMap, + UriInfo uriInfo, + String documentType, + String entityName) throws Exception { + ServiceContext ctx = createServiceContext( + serviceName, + input, + resourceMap, + uriInfo); + ctx.setDocumentType(documentType); //persistence unit + ctx.setProperty(ServiceContextProperties.ENTITY_NAME, entityName); + return ctx; + } + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/context/ServiceBindingUtils.java b/services/common/src/main/java/org/collectionspace/services/common/context/ServiceBindingUtils.java index 6ab6e4975..9c5be602b 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/context/ServiceBindingUtils.java +++ b/services/common/src/main/java/org/collectionspace/services/common/context/ServiceBindingUtils.java @@ -1,236 +1,236 @@ -package org.collectionspace.services.common.context; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -import org.collectionspace.services.common.config.PropertyItemUtils; -import org.collectionspace.services.config.service.ObjectPartType; -import org.collectionspace.services.config.service.ServiceBindingType; -import org.collectionspace.services.config.service.ServiceObjectType; -import org.collectionspace.services.config.types.PropertyItemType; -import org.collectionspace.services.config.types.PropertyType; -import org.collectionspace.services.nuxeo.util.NuxeoUtils; -import org.nuxeo.ecm.core.api.ClientException; -import org.nuxeo.ecm.core.api.DocumentModel; -import java.lang.IndexOutOfBoundsException; -import org.collectionspace.services.common.api.Tools; -import org.collectionspace.services.common.document.DocumentUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -public class ServiceBindingUtils { - public static final boolean QUALIFIED_PROP_NAMES = true; - public static final boolean UNQUALIFIED_PROP_NAMES = false; - public static final String AUTH_REF_PROP = "authRef"; - public static final String TERM_REF_PROP = "termRef"; - public static final String OBJ_NUMBER_PROP = "objectNumberProperty"; - public static final String OBJ_NAME_PROP = "objectNameProperty"; - public static final String SERVICE_TYPE_PROP = "type"; - public static final String SERVICE_TYPE_OBJECT = "object"; - public static final String SERVICE_TYPE_PROCEDURE = "procedure"; - public static final String SERVICE_TYPE_AUTHORITY = "authority"; - public static final String SERVICE_TYPE_UTILITY = "utility"; - public static final String SERVICE_TYPE_SECURITY = "security"; - - private static final String TENANT_EXTENSION_PATTERN = "(.*)"+ServiceContext.TENANT_SUFFIX+"[\\d]+$"; - private static final String TENANT_REPLACEMENT_PATTERN = "$1"; - private static Pattern tenantSuffixPattern = null; - - private static final Logger logger = LoggerFactory.getLogger(ServiceBindingUtils.class); - - public static String getTenantQualifiedDocType(String tenantId, String docType) { - String result = docType + ServiceContext.TENANT_SUFFIX + tenantId; - return result; - } - - public static String getUnqualifiedTenantDocType(String docType) { - try { - if(tenantSuffixPattern == null ) { - tenantSuffixPattern = Pattern.compile(TENANT_EXTENSION_PATTERN); - } - Matcher tenantSuffixMatcher = tenantSuffixPattern.matcher(docType); - return tenantSuffixMatcher.replaceFirst(TENANT_REPLACEMENT_PATTERN); - } catch (PatternSyntaxException pe) { - logger.warn("TENANT_EXTENSION_PATTERN regex pattern '" + TENANT_EXTENSION_PATTERN - + "' could not be compiled: " + pe.getMessage()); - // If reached, method will return a value of false. - } - return docType; - } - - // TODO consider building up a hashTable of the properties for each - // service binding. There will be generic properties, as well as - // properties on each part. Could build up a key from tenant id, - // servicename, (partname for those props), propName - - public static void getPartsMetadata(ServiceBindingType serviceBinding, - Map objectPartMap) { - ServiceObjectType objectType = serviceBinding.getObject(); - List objectPartTypes = objectType.getPart(); - for (ObjectPartType objectPartType : objectPartTypes) { - objectPartMap.put(objectPartType.getLabel(), objectPartType); - } - } - - private static List getPropertiesForPart(ServiceBindingType serviceBinding, - String partLabel) { - ServiceObjectType objectType = serviceBinding.getObject(); - List objectPartTypes = objectType.getPart(); - for (ObjectPartType objectPartType : objectPartTypes) { - if(partLabel.equals(objectPartType.getLabel())) { - List propNodeList = objectPartType.getProperties(); - return propNodeList.isEmpty()?null:propNodeList.get(0).getItem(); - } - } - throw new RuntimeException("No such part found: "+partLabel); - } - - public static List getPropertyValuesForPart(ServiceBindingType serviceBinding, - String partLabel, String propName, boolean qualify) { - List partProps = getPropertiesForPart(serviceBinding, partLabel); - return PropertyItemUtils.getPropertyValuesByName(partProps, propName, - (qualify?(partLabel+":"):null)); - } - - /** - * @param serviceBinding the service to work from - * @param propName the name of the property of interest - * @param qualify if QUALIFIED_PROP_NAMES, will prefix all values with the part label - * @return a list of (qualified) - */ - public static List getAllPartsPropertyValues(ServiceBindingType serviceBinding, - String propName, boolean qualify) { - List values = new ArrayList(); - ServiceObjectType objectType = serviceBinding.getObject(); - List objectPartTypes = objectType.getPart(); - for (ObjectPartType objectPartType : objectPartTypes) { - List propNodeList = objectPartType.getProperties(); - PropertyItemUtils.getPropertyValuesByNameInNodeList(propNodeList, - propName, (qualify?(objectPartType.getLabel()+":"):null), values); - } - return values; - } - - /** - * @param service - * @param propName the property to fetch - * @return the String value of the named property - */ - public static String getPropertyValue(ServiceBindingType service, - String propName) { - if(propName==null) { - throw new IllegalArgumentException("ServiceBindingUtils.getPropertyValues: null property name!"); - } - List servicePropList = service.getProperties(); - return PropertyItemUtils.getPropertyValueByNameFromNodeList(servicePropList, propName ); - } - - /** - * @param service - * @param propName the property to set - * @param value the new value to set - * @param onlyIfNotSet if true, will not override an existing value - * @return true if set, false if an existing value was left as is. - */ - public static boolean setPropertyValue(ServiceBindingType service, - PropertyItemType prop, boolean onlyIfNotSet) { - if(prop==null) { - throw new IllegalArgumentException( - "ServiceBindingUtils.setPropertyValue: null property!"); - } - return setPropertyValue(service, prop.getKey(), prop.getValue(), - onlyIfNotSet); - } - - /** - * @param service - * @param propName the property to set - * @param value the new value to set - * @param onlyIfNotSet if true, will not override an existing value - * @return true if set, false if an existing value was left as is. - */ - public static boolean setPropertyValue(ServiceBindingType service, - String propName, String value, - boolean onlyIfNotSet) { - if(propName==null) { - throw new IllegalArgumentException("ServiceBindingUtils.setPropertyValue: null property name!"); - } - List servicePropertiesNode = service.getProperties(); - return PropertyItemUtils.setPropertyValueInNodeList(servicePropertiesNode, - propName, value, onlyIfNotSet); - } - - public static String getMappedFieldInDoc( ServiceBindingType sb, - String logicalFieldName, DocumentModel docModel ) { - // Now we have to get the number, which is configured as some field - // on each docType - /* If we go to qualified field names, we'll need this - String[] strings = qPropName.split(":"); - if(strings.length!=2) { - throw new RuntimeException( - "getMappedFieldInDoc: Bad configuration of " - +logicalFieldName+" field for: "+docModel.getDocumentType().getName()); - } - */ - String propName = getPropertyValue(sb, logicalFieldName); - if(Tools.isBlank(propName)) { - logger.warn("Property name is empty for property " + logicalFieldName + " in service " + sb.getName()); - logger.warn("This may be due to an improperly configured or missing " - + "generic property (objectNameProperty, objectNumberProperty ...) in tenant bindings configuration"); - return ""; - } - try { - Object obj = docModel.getPropertyValue(propName); - return DocumentUtils.propertyValueAsString(obj, docModel, propName); - } catch(IndexOutOfBoundsException ioobe) { - // Should not happen, but may with certain array forms - if(logger.isTraceEnabled()) { - logger.trace("SBUtils.getMappedField caught OOB exc, for Prop: "+propName - + " in: " + docModel.getDocumentType().getName() - + " csid: " + NuxeoUtils.getCsid(docModel)); - } - return null; - } catch(ClientException ce) { - throw new RuntimeException( - "getMappedFieldInDoc: Problem fetching: "+propName+" logicalfieldName: "+logicalFieldName+" docModel: "+docModel, ce); - } - } - - private static ArrayList commonProcedureServiceTypes = null; - - public static ArrayList getCommonServiceTypes(boolean includeAuthorities) { - ArrayList commonServiceTypes = new ArrayList(); - if (includeAuthorities == true) { - commonServiceTypes.add(SERVICE_TYPE_AUTHORITY); // REM - CSPACE-5359: Added back authorities on demand to resolve this issue. - } - commonServiceTypes.add(SERVICE_TYPE_OBJECT); - commonServiceTypes.add(SERVICE_TYPE_PROCEDURE); - - return commonServiceTypes; - } - - // Temporary workaround for CSPACE-4983, to help reduce the - // number of service types searched for authority references - // in AuthorityResource.getReferencingObjects(), to in turn - // help reduce database query complexity. - // - // FIXME; this method is intended to be temporary. It was added in part to - // make the effect of the workaround more explicit, and in part to avoid - // breaking the use of the getCommonServiceTypes method in ServiceGroups. - @Deprecated - public static ArrayList getCommonProcedureServiceTypes() { - if(commonProcedureServiceTypes == null) { - commonProcedureServiceTypes = new ArrayList(); - commonProcedureServiceTypes.add(SERVICE_TYPE_PROCEDURE); - } - return commonProcedureServiceTypes; - } - - - -} +package org.collectionspace.services.common.context; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +import org.collectionspace.services.common.config.PropertyItemUtils; +import org.collectionspace.services.config.service.ObjectPartType; +import org.collectionspace.services.config.service.ServiceBindingType; +import org.collectionspace.services.config.service.ServiceObjectType; +import org.collectionspace.services.config.types.PropertyItemType; +import org.collectionspace.services.config.types.PropertyType; +import org.collectionspace.services.nuxeo.util.NuxeoUtils; +import org.nuxeo.ecm.core.api.ClientException; +import org.nuxeo.ecm.core.api.DocumentModel; +import java.lang.IndexOutOfBoundsException; +import org.collectionspace.services.common.api.Tools; +import org.collectionspace.services.common.document.DocumentUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class ServiceBindingUtils { + public static final boolean QUALIFIED_PROP_NAMES = true; + public static final boolean UNQUALIFIED_PROP_NAMES = false; + public static final String AUTH_REF_PROP = "authRef"; + public static final String TERM_REF_PROP = "termRef"; + public static final String OBJ_NUMBER_PROP = "objectNumberProperty"; + public static final String OBJ_NAME_PROP = "objectNameProperty"; + public static final String SERVICE_TYPE_PROP = "type"; + public static final String SERVICE_TYPE_OBJECT = "object"; + public static final String SERVICE_TYPE_PROCEDURE = "procedure"; + public static final String SERVICE_TYPE_AUTHORITY = "authority"; + public static final String SERVICE_TYPE_UTILITY = "utility"; + public static final String SERVICE_TYPE_SECURITY = "security"; + + private static final String TENANT_EXTENSION_PATTERN = "(.*)"+ServiceContext.TENANT_SUFFIX+"[\\d]+$"; + private static final String TENANT_REPLACEMENT_PATTERN = "$1"; + private static Pattern tenantSuffixPattern = null; + + private static final Logger logger = LoggerFactory.getLogger(ServiceBindingUtils.class); + + public static String getTenantQualifiedDocType(String tenantId, String docType) { + String result = docType + ServiceContext.TENANT_SUFFIX + tenantId; + return result; + } + + public static String getUnqualifiedTenantDocType(String docType) { + try { + if(tenantSuffixPattern == null ) { + tenantSuffixPattern = Pattern.compile(TENANT_EXTENSION_PATTERN); + } + Matcher tenantSuffixMatcher = tenantSuffixPattern.matcher(docType); + return tenantSuffixMatcher.replaceFirst(TENANT_REPLACEMENT_PATTERN); + } catch (PatternSyntaxException pe) { + logger.warn("TENANT_EXTENSION_PATTERN regex pattern '" + TENANT_EXTENSION_PATTERN + + "' could not be compiled: " + pe.getMessage()); + // If reached, method will return a value of false. + } + return docType; + } + + // TODO consider building up a hashTable of the properties for each + // service binding. There will be generic properties, as well as + // properties on each part. Could build up a key from tenant id, + // servicename, (partname for those props), propName + + public static void getPartsMetadata(ServiceBindingType serviceBinding, + Map objectPartMap) { + ServiceObjectType objectType = serviceBinding.getObject(); + List objectPartTypes = objectType.getPart(); + for (ObjectPartType objectPartType : objectPartTypes) { + objectPartMap.put(objectPartType.getLabel(), objectPartType); + } + } + + private static List getPropertiesForPart(ServiceBindingType serviceBinding, + String partLabel) { + ServiceObjectType objectType = serviceBinding.getObject(); + List objectPartTypes = objectType.getPart(); + for (ObjectPartType objectPartType : objectPartTypes) { + if(partLabel.equals(objectPartType.getLabel())) { + List propNodeList = objectPartType.getProperties(); + return propNodeList.isEmpty()?null:propNodeList.get(0).getItem(); + } + } + throw new RuntimeException("No such part found: "+partLabel); + } + + public static List getPropertyValuesForPart(ServiceBindingType serviceBinding, + String partLabel, String propName, boolean qualify) { + List partProps = getPropertiesForPart(serviceBinding, partLabel); + return PropertyItemUtils.getPropertyValuesByName(partProps, propName, + (qualify?(partLabel+":"):null)); + } + + /** + * @param serviceBinding the service to work from + * @param propName the name of the property of interest + * @param qualify if QUALIFIED_PROP_NAMES, will prefix all values with the part label + * @return a list of (qualified) + */ + public static List getAllPartsPropertyValues(ServiceBindingType serviceBinding, + String propName, boolean qualify) { + List values = new ArrayList(); + ServiceObjectType objectType = serviceBinding.getObject(); + List objectPartTypes = objectType.getPart(); + for (ObjectPartType objectPartType : objectPartTypes) { + List propNodeList = objectPartType.getProperties(); + PropertyItemUtils.getPropertyValuesByNameInNodeList(propNodeList, + propName, (qualify?(objectPartType.getLabel()+":"):null), values); + } + return values; + } + + /** + * @param service + * @param propName the property to fetch + * @return the String value of the named property + */ + public static String getPropertyValue(ServiceBindingType service, + String propName) { + if(propName==null) { + throw new IllegalArgumentException("ServiceBindingUtils.getPropertyValues: null property name!"); + } + List servicePropList = service.getProperties(); + return PropertyItemUtils.getPropertyValueByNameFromNodeList(servicePropList, propName ); + } + + /** + * @param service + * @param propName the property to set + * @param value the new value to set + * @param onlyIfNotSet if true, will not override an existing value + * @return true if set, false if an existing value was left as is. + */ + public static boolean setPropertyValue(ServiceBindingType service, + PropertyItemType prop, boolean onlyIfNotSet) { + if(prop==null) { + throw new IllegalArgumentException( + "ServiceBindingUtils.setPropertyValue: null property!"); + } + return setPropertyValue(service, prop.getKey(), prop.getValue(), + onlyIfNotSet); + } + + /** + * @param service + * @param propName the property to set + * @param value the new value to set + * @param onlyIfNotSet if true, will not override an existing value + * @return true if set, false if an existing value was left as is. + */ + public static boolean setPropertyValue(ServiceBindingType service, + String propName, String value, + boolean onlyIfNotSet) { + if(propName==null) { + throw new IllegalArgumentException("ServiceBindingUtils.setPropertyValue: null property name!"); + } + List servicePropertiesNode = service.getProperties(); + return PropertyItemUtils.setPropertyValueInNodeList(servicePropertiesNode, + propName, value, onlyIfNotSet); + } + + public static String getMappedFieldInDoc( ServiceBindingType sb, + String logicalFieldName, DocumentModel docModel ) { + // Now we have to get the number, which is configured as some field + // on each docType + /* If we go to qualified field names, we'll need this + String[] strings = qPropName.split(":"); + if(strings.length!=2) { + throw new RuntimeException( + "getMappedFieldInDoc: Bad configuration of " + +logicalFieldName+" field for: "+docModel.getDocumentType().getName()); + } + */ + String propName = getPropertyValue(sb, logicalFieldName); + if(Tools.isBlank(propName)) { + logger.warn("Property name is empty for property " + logicalFieldName + " in service " + sb.getName()); + logger.warn("This may be due to an improperly configured or missing " + + "generic property (objectNameProperty, objectNumberProperty ...) in tenant bindings configuration"); + return ""; + } + try { + Object obj = docModel.getPropertyValue(propName); + return DocumentUtils.propertyValueAsString(obj, docModel, propName); + } catch(IndexOutOfBoundsException ioobe) { + // Should not happen, but may with certain array forms + if(logger.isTraceEnabled()) { + logger.trace("SBUtils.getMappedField caught OOB exc, for Prop: "+propName + + " in: " + docModel.getDocumentType().getName() + + " csid: " + NuxeoUtils.getCsid(docModel)); + } + return null; + } catch(ClientException ce) { + throw new RuntimeException( + "getMappedFieldInDoc: Problem fetching: "+propName+" logicalfieldName: "+logicalFieldName+" docModel: "+docModel, ce); + } + } + + private static ArrayList commonProcedureServiceTypes = null; + + public static ArrayList getCommonServiceTypes(boolean includeAuthorities) { + ArrayList commonServiceTypes = new ArrayList(); + if (includeAuthorities == true) { + commonServiceTypes.add(SERVICE_TYPE_AUTHORITY); // REM - CSPACE-5359: Added back authorities on demand to resolve this issue. + } + commonServiceTypes.add(SERVICE_TYPE_OBJECT); + commonServiceTypes.add(SERVICE_TYPE_PROCEDURE); + + return commonServiceTypes; + } + + // Temporary workaround for CSPACE-4983, to help reduce the + // number of service types searched for authority references + // in AuthorityResource.getReferencingObjects(), to in turn + // help reduce database query complexity. + // + // FIXME; this method is intended to be temporary. It was added in part to + // make the effect of the workaround more explicit, and in part to avoid + // breaking the use of the getCommonServiceTypes method in ServiceGroups. + @Deprecated + public static ArrayList getCommonProcedureServiceTypes() { + if(commonProcedureServiceTypes == null) { + commonProcedureServiceTypes = new ArrayList(); + commonProcedureServiceTypes.add(SERVICE_TYPE_PROCEDURE); + } + return commonProcedureServiceTypes; + } + + + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/document/DocumentFilter.java b/services/common/src/main/java/org/collectionspace/services/common/document/DocumentFilter.java index df1c25704..1168185d1 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/document/DocumentFilter.java +++ b/services/common/src/main/java/org/collectionspace/services/common/document/DocumentFilter.java @@ -1,457 +1,457 @@ -/** - * 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 - */ -package org.collectionspace.services.common.document; - -import java.util.ArrayList; -import java.util.List; -import javax.ws.rs.core.MultivaluedMap; -import org.collectionspace.authentication.AuthN; -import org.collectionspace.services.client.CollectionSpaceClient; -import org.collectionspace.services.client.IClientQueryParams; -import org.collectionspace.services.common.context.ServiceContext; - -/** - * The Class DocumentFilter. - */ -//FIXME: it would be nice to instantiate the doc filter with the service context -//so tenant context and other things available from the service context -//could be utilized while building the where clause. -public class DocumentFilter { - - /** The Constant DEFAULT_PAGE_SIZE_INIT. */ - public static final int DEFAULT_PAGE_SIZE_INIT = 40; - /** The Constant PAGE_SIZE_DEFAULT_PROPERTY. */ - public static final String PAGE_SIZE_DEFAULT_PROPERTY = "pageSizeDefault"; - /** The default page size. */ - public static int defaultPageSize = DEFAULT_PAGE_SIZE_INIT; - /** The where clause. */ - protected String whereClause; // Filtering clause. Omit the "WHERE". - /** The order by clause. */ - protected String orderByClause; // Filtering clause. Omit the "ORDER BY". - public static final String EMPTY_ORDER_BY_CLAUSE = ""; - public static final String ORDER_BY_LAST_UPDATED = CollectionSpaceClient.CORE_UPDATED_AT + " DESC"; - public static final String ORDER_BY_CREATED_AT = CollectionSpaceClient.CORE_CREATED_AT + " DESC"; - /** The start page. */ - protected int startPage; // Pagination offset for list results - /** The page size. */ - protected int pageSize; // Pagination limit for list results - //queryParams is not initialized as it would require a multi-valued map implementation - //unless it is used from opensource lib...this variable holds ref to - //implementation available in JBoss RESTeasy - /** The query params. */ - private MultivaluedMap queryParams = null; - - /** - * The Class ParamBinding. - */ - public static class ParamBinding { - - /** The name. */ - private String name; - /** The value. */ - private Object value; - - /** - * Instantiates a new param binding. - * - * @param theName the name - * @param theValue the value - */ - public ParamBinding(String theName, Object theValue) { - this.name = theName; - this.value = theValue; - } - - /** - * Gets the name. - * - * @return the name - */ - public String getName() { - return name; - } - - /** - * Sets the name. - * - * @param theName the new name - */ - public void setName(String theName) { - this.name = theName; - } - - /** - * Gets the value. - * - * @return the value - */ - public Object getValue() { - return value; - } - - /** - * Sets the value. - * - * @param theValue the new value - */ - public void setValue(Object theValue) { - this.value = theValue; - } - } - - /** - * Instantiates a new document filter. - * - * @param ctx the ctx - */ - public DocumentFilter(ServiceContext ctx) { - // Ignore errors - some contexts do not have proper service binding info - try { - String pageSizeString = ctx.getServiceBindingPropertyValue( - DocumentFilter.PAGE_SIZE_DEFAULT_PROPERTY); - this.setPageSize(pageSizeString); - } catch(Exception e) { - this.setPageSize(defaultPageSize); - } - } - - /** - * Instantiates a new document filter. - */ - public DocumentFilter() { - this("", 0, defaultPageSize); // Use empty string for easy concatenation - } - - /** - * Instantiates a new document filter. - * - * @param theWhereClause the where clause - * @param theStartPage the start page - * @param thePageSize the page size - */ - public DocumentFilter(String theWhereClause, int theStartPage, int thePageSize) { - this(theWhereClause, EMPTY_ORDER_BY_CLAUSE, theStartPage, thePageSize); - } - - /** - * Instantiates a new document filter. - * - * @param theWhereClause the where clause - * @param theOrderByClause the order by clause - * @param theStartPage the start page - * @param thePageSize the page size - */ - public DocumentFilter(String theWhereClause, String theOrderByClause, int theStartPage, int thePageSize) { - this.whereClause = theWhereClause; - this.orderByClause = theOrderByClause; - this.startPage = (theStartPage > 0) ? theStartPage : 0; - this.pageSize = (thePageSize > 0) ? thePageSize : defaultPageSize; - } - - /** - * Sets the pagination. - * - * @param theQueryParams the the query params - */ - public void setPagination(MultivaluedMap theQueryParams) { - // - // Bail if there are no params - // - if (theQueryParams == null) { - return; - } - // - // Set the page size - // - String pageSizeStr = null; - List list = theQueryParams.get(IClientQueryParams.PAGE_SIZE_PARAM); - if (list != null) { - pageSizeStr = list.get(0); - } - setPageSize(pageSizeStr); - // - // Set the start page - // - String startPageStr = null; - list = theQueryParams.get(IClientQueryParams.START_PAGE_PARAM); - if (list != null) { - startPageStr = list.get(0); - } - setStartPage(startPageStr); - } - - /** - * Gets the default page size. - * - * @return the default page size - */ - public static int getDefaultPageSize() { - return defaultPageSize; - } - - /** - * Sets the default page size. - * - * @param theDefaultPageSize the new default page size - */ - public static void setDefaultPageSize(int theDefaultPageSize) { - DocumentFilter.defaultPageSize = theDefaultPageSize; - } - - /** - * Gets the where clause. - * - * @return the where clause - */ - public String getWhereClause() { - return whereClause; - } - - /** - * Sets the where clause. - * - * @param theWhereClause the new where clause - */ - public void setWhereClause(String theWhereClause) { - this.whereClause = theWhereClause; - } - - /** - * Append where clause. - * - * @param theWhereClause the where clause - * @param conjunction the conjunction to insert between the current - * where clause, if any, and the additional where clause to be appended - */ - public void appendWhereClause(String theWhereClause, String conjunction) { - if (theWhereClause != null && ! theWhereClause.trim().isEmpty()) { - String currentClause = getWhereClause(); - if (currentClause != null) { - String newClause = currentClause.concat(conjunction + theWhereClause); - this.setWhereClause(newClause); - } else { - this.setWhereClause(theWhereClause); - } - } - } - - /** - * Builds the where for search. - * - * @param queryStrBldr the query str bldr - * @return the list - */ - public List buildWhereForSearch(StringBuilder queryStrBldr) { - return new ArrayList(); - } - - /** - * Builds the where. - * - * @param queryStrBldr the query str bldr - * @return the list - */ - public List buildWhere(StringBuilder queryStrBldr) { - return new ArrayList(); - } - - /** - * Sets the sort ordering. - * - * @param theQueryParams the query params - */ - public void setSortOrder(MultivaluedMap theQueryParams) { - // Bail if there are no params - if (theQueryParams == null) { - return; - } - // Set the order by clause - String orderByStr = null; - List list = theQueryParams.get(IClientQueryParams.ORDER_BY_PARAM); - if (list != null) { - orderByStr = list.get(0); - } - - // FIXME: Verify the format of the value(s) in the 'sort by' - // query param. - - setOrderByClause(orderByStr); - } - - /** - * Gets the order by clause. - * - * @return the order by clause - */ - public String getOrderByClause() { - return orderByClause; - } - - /** - * Sets the order by clause. - * - * @param theOrderByClause the new order by clause - */ - public void setOrderByClause(String theOrderByClause) { - this.orderByClause = theOrderByClause; - } - - /** - * Gets the start page. - * - * @return the start page - */ - public int getStartPage() { - return startPage; - } - - /** - * Sets the start page. - * - * @param theStartPage the new start page - */ - public void setStartPage(int theStartPage) { - this.startPage = theStartPage; - } - - /** - * Gets the page size. - * - * @return the page size - */ - public int getPageSize() { - return pageSize; - } - - /** - * Gets the page size dirty. - * - * @return the page size dirty - */ - public boolean getPageSizeDirty() { - return this.getPageSizeDirty(); - } - - /** - * Sets the page size. - * - * @param thePageSize the new page size - */ - public void setPageSize(int thePageSize) { - this.pageSize = thePageSize; - } - - /** - * Sets the page size. - * - * @param thePageSizeStr the new page size - */ - public void setPageSize(String thePageSizeStr) { - int newPageSize = DocumentFilter.defaultPageSize; - if (thePageSizeStr != null) { - try { - newPageSize = Integer.valueOf(thePageSizeStr); - } catch (NumberFormatException e) { - //FIXME This should cause a warning in the log file and should result in the - //FIXME page size being set to the default. We don't need to throw an exception here. - throw new NumberFormatException("Bad value for: " - + IClientQueryParams.PAGE_SIZE_PARAM); - } - } - - setPageSize(newPageSize); - } - - /** - * Sets the start page. - * - * @param startPageStr the new start page - */ - protected void setStartPage(String startPageStr) { - if (startPageStr != null) { - try { - startPage = Integer.valueOf(startPageStr); - } catch (NumberFormatException e) { - throw new NumberFormatException("Bad value for: " - + IClientQueryParams.START_PAGE_PARAM); - } - } - } - - /** - * Gets the offset. - * - * @return the offset - */ - public int getOffset() { - return pageSize * startPage; - } - - /** - * Adds the query param. - * - * @param key the key - * @param value the value - */ - public void addQueryParam(String key, String value) { - if (queryParams != null) { - queryParams.add(key, value); - } - } - - /** - * Gets the query param. - * - * @param key the key - * @return the query param - */ - public List getQueryParam(String key) { - if (queryParams != null) { - return queryParams.get(key); - } else { - return new ArrayList(); - } - } - - /** - * Gets the query params. - * - * @return the query params - */ - public MultivaluedMap getQueryParams() { - return queryParams; - } - - /** - * Sets the query params. - * - * @param theQueryParams the the query params - */ - public void setQueryParams(MultivaluedMap theQueryParams) { - this.queryParams = theQueryParams; - } - - /** - * getTenantId - * //FIXME: it would be nice to take tenantId from service context - * @return - */ - protected String getTenantId() { - return AuthN.get().getCurrentTenantId(); - } -} +/** + * 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 + */ +package org.collectionspace.services.common.document; + +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.MultivaluedMap; +import org.collectionspace.authentication.AuthN; +import org.collectionspace.services.client.CollectionSpaceClient; +import org.collectionspace.services.client.IClientQueryParams; +import org.collectionspace.services.common.context.ServiceContext; + +/** + * The Class DocumentFilter. + */ +//FIXME: it would be nice to instantiate the doc filter with the service context +//so tenant context and other things available from the service context +//could be utilized while building the where clause. +public class DocumentFilter { + + /** The Constant DEFAULT_PAGE_SIZE_INIT. */ + public static final int DEFAULT_PAGE_SIZE_INIT = 40; + /** The Constant PAGE_SIZE_DEFAULT_PROPERTY. */ + public static final String PAGE_SIZE_DEFAULT_PROPERTY = "pageSizeDefault"; + /** The default page size. */ + public static int defaultPageSize = DEFAULT_PAGE_SIZE_INIT; + /** The where clause. */ + protected String whereClause; // Filtering clause. Omit the "WHERE". + /** The order by clause. */ + protected String orderByClause; // Filtering clause. Omit the "ORDER BY". + public static final String EMPTY_ORDER_BY_CLAUSE = ""; + public static final String ORDER_BY_LAST_UPDATED = CollectionSpaceClient.CORE_UPDATED_AT + " DESC"; + public static final String ORDER_BY_CREATED_AT = CollectionSpaceClient.CORE_CREATED_AT + " DESC"; + /** The start page. */ + protected int startPage; // Pagination offset for list results + /** The page size. */ + protected int pageSize; // Pagination limit for list results + //queryParams is not initialized as it would require a multi-valued map implementation + //unless it is used from opensource lib...this variable holds ref to + //implementation available in JBoss RESTeasy + /** The query params. */ + private MultivaluedMap queryParams = null; + + /** + * The Class ParamBinding. + */ + public static class ParamBinding { + + /** The name. */ + private String name; + /** The value. */ + private Object value; + + /** + * Instantiates a new param binding. + * + * @param theName the name + * @param theValue the value + */ + public ParamBinding(String theName, Object theValue) { + this.name = theName; + this.value = theValue; + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Sets the name. + * + * @param theName the new name + */ + public void setName(String theName) { + this.name = theName; + } + + /** + * Gets the value. + * + * @return the value + */ + public Object getValue() { + return value; + } + + /** + * Sets the value. + * + * @param theValue the new value + */ + public void setValue(Object theValue) { + this.value = theValue; + } + } + + /** + * Instantiates a new document filter. + * + * @param ctx the ctx + */ + public DocumentFilter(ServiceContext ctx) { + // Ignore errors - some contexts do not have proper service binding info + try { + String pageSizeString = ctx.getServiceBindingPropertyValue( + DocumentFilter.PAGE_SIZE_DEFAULT_PROPERTY); + this.setPageSize(pageSizeString); + } catch(Exception e) { + this.setPageSize(defaultPageSize); + } + } + + /** + * Instantiates a new document filter. + */ + public DocumentFilter() { + this("", 0, defaultPageSize); // Use empty string for easy concatenation + } + + /** + * Instantiates a new document filter. + * + * @param theWhereClause the where clause + * @param theStartPage the start page + * @param thePageSize the page size + */ + public DocumentFilter(String theWhereClause, int theStartPage, int thePageSize) { + this(theWhereClause, EMPTY_ORDER_BY_CLAUSE, theStartPage, thePageSize); + } + + /** + * Instantiates a new document filter. + * + * @param theWhereClause the where clause + * @param theOrderByClause the order by clause + * @param theStartPage the start page + * @param thePageSize the page size + */ + public DocumentFilter(String theWhereClause, String theOrderByClause, int theStartPage, int thePageSize) { + this.whereClause = theWhereClause; + this.orderByClause = theOrderByClause; + this.startPage = (theStartPage > 0) ? theStartPage : 0; + this.pageSize = (thePageSize > 0) ? thePageSize : defaultPageSize; + } + + /** + * Sets the pagination. + * + * @param theQueryParams the the query params + */ + public void setPagination(MultivaluedMap theQueryParams) { + // + // Bail if there are no params + // + if (theQueryParams == null) { + return; + } + // + // Set the page size + // + String pageSizeStr = null; + List list = theQueryParams.get(IClientQueryParams.PAGE_SIZE_PARAM); + if (list != null) { + pageSizeStr = list.get(0); + } + setPageSize(pageSizeStr); + // + // Set the start page + // + String startPageStr = null; + list = theQueryParams.get(IClientQueryParams.START_PAGE_PARAM); + if (list != null) { + startPageStr = list.get(0); + } + setStartPage(startPageStr); + } + + /** + * Gets the default page size. + * + * @return the default page size + */ + public static int getDefaultPageSize() { + return defaultPageSize; + } + + /** + * Sets the default page size. + * + * @param theDefaultPageSize the new default page size + */ + public static void setDefaultPageSize(int theDefaultPageSize) { + DocumentFilter.defaultPageSize = theDefaultPageSize; + } + + /** + * Gets the where clause. + * + * @return the where clause + */ + public String getWhereClause() { + return whereClause; + } + + /** + * Sets the where clause. + * + * @param theWhereClause the new where clause + */ + public void setWhereClause(String theWhereClause) { + this.whereClause = theWhereClause; + } + + /** + * Append where clause. + * + * @param theWhereClause the where clause + * @param conjunction the conjunction to insert between the current + * where clause, if any, and the additional where clause to be appended + */ + public void appendWhereClause(String theWhereClause, String conjunction) { + if (theWhereClause != null && ! theWhereClause.trim().isEmpty()) { + String currentClause = getWhereClause(); + if (currentClause != null) { + String newClause = currentClause.concat(conjunction + theWhereClause); + this.setWhereClause(newClause); + } else { + this.setWhereClause(theWhereClause); + } + } + } + + /** + * Builds the where for search. + * + * @param queryStrBldr the query str bldr + * @return the list + */ + public List buildWhereForSearch(StringBuilder queryStrBldr) { + return new ArrayList(); + } + + /** + * Builds the where. + * + * @param queryStrBldr the query str bldr + * @return the list + */ + public List buildWhere(StringBuilder queryStrBldr) { + return new ArrayList(); + } + + /** + * Sets the sort ordering. + * + * @param theQueryParams the query params + */ + public void setSortOrder(MultivaluedMap theQueryParams) { + // Bail if there are no params + if (theQueryParams == null) { + return; + } + // Set the order by clause + String orderByStr = null; + List list = theQueryParams.get(IClientQueryParams.ORDER_BY_PARAM); + if (list != null) { + orderByStr = list.get(0); + } + + // FIXME: Verify the format of the value(s) in the 'sort by' + // query param. + + setOrderByClause(orderByStr); + } + + /** + * Gets the order by clause. + * + * @return the order by clause + */ + public String getOrderByClause() { + return orderByClause; + } + + /** + * Sets the order by clause. + * + * @param theOrderByClause the new order by clause + */ + public void setOrderByClause(String theOrderByClause) { + this.orderByClause = theOrderByClause; + } + + /** + * Gets the start page. + * + * @return the start page + */ + public int getStartPage() { + return startPage; + } + + /** + * Sets the start page. + * + * @param theStartPage the new start page + */ + public void setStartPage(int theStartPage) { + this.startPage = theStartPage; + } + + /** + * Gets the page size. + * + * @return the page size + */ + public int getPageSize() { + return pageSize; + } + + /** + * Gets the page size dirty. + * + * @return the page size dirty + */ + public boolean getPageSizeDirty() { + return this.getPageSizeDirty(); + } + + /** + * Sets the page size. + * + * @param thePageSize the new page size + */ + public void setPageSize(int thePageSize) { + this.pageSize = thePageSize; + } + + /** + * Sets the page size. + * + * @param thePageSizeStr the new page size + */ + public void setPageSize(String thePageSizeStr) { + int newPageSize = DocumentFilter.defaultPageSize; + if (thePageSizeStr != null) { + try { + newPageSize = Integer.valueOf(thePageSizeStr); + } catch (NumberFormatException e) { + //FIXME This should cause a warning in the log file and should result in the + //FIXME page size being set to the default. We don't need to throw an exception here. + throw new NumberFormatException("Bad value for: " + + IClientQueryParams.PAGE_SIZE_PARAM); + } + } + + setPageSize(newPageSize); + } + + /** + * Sets the start page. + * + * @param startPageStr the new start page + */ + protected void setStartPage(String startPageStr) { + if (startPageStr != null) { + try { + startPage = Integer.valueOf(startPageStr); + } catch (NumberFormatException e) { + throw new NumberFormatException("Bad value for: " + + IClientQueryParams.START_PAGE_PARAM); + } + } + } + + /** + * Gets the offset. + * + * @return the offset + */ + public int getOffset() { + return pageSize * startPage; + } + + /** + * Adds the query param. + * + * @param key the key + * @param value the value + */ + public void addQueryParam(String key, String value) { + if (queryParams != null) { + queryParams.add(key, value); + } + } + + /** + * Gets the query param. + * + * @param key the key + * @return the query param + */ + public List getQueryParam(String key) { + if (queryParams != null) { + return queryParams.get(key); + } else { + return new ArrayList(); + } + } + + /** + * Gets the query params. + * + * @return the query params + */ + public MultivaluedMap getQueryParams() { + return queryParams; + } + + /** + * Sets the query params. + * + * @param theQueryParams the the query params + */ + public void setQueryParams(MultivaluedMap theQueryParams) { + this.queryParams = theQueryParams; + } + + /** + * getTenantId + * //FIXME: it would be nice to take tenantId from service context + * @return + */ + protected String getTenantId() { + return AuthN.get().getCurrentTenantId(); + } +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/document/DocumentListWrapper.java b/services/common/src/main/java/org/collectionspace/services/common/document/DocumentListWrapper.java index 44562af17..2739df850 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/document/DocumentListWrapper.java +++ b/services/common/src/main/java/org/collectionspace/services/common/document/DocumentListWrapper.java @@ -1,40 +1,40 @@ -/** - * 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.document; - -import java.util.List; -/** - * - * DocumentWrapper wraps DocumentModel (java) or Representation (REST) - * - */ -public interface DocumentListWrapper { - - /** - * getWrappedObject - * @return wrapped object - */ - public List getWrappedObject(); -} +/** + * 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.document; + +import java.util.List; +/** + * + * DocumentWrapper wraps DocumentModel (java) or Representation (REST) + * + */ +public interface DocumentListWrapper { + + /** + * getWrappedObject + * @return wrapped object + */ + public List getWrappedObject(); +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/document/DocumentListWrapperImpl.java b/services/common/src/main/java/org/collectionspace/services/common/document/DocumentListWrapperImpl.java index 0ab43ea43..32ba48970 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/document/DocumentListWrapperImpl.java +++ b/services/common/src/main/java/org/collectionspace/services/common/document/DocumentListWrapperImpl.java @@ -1,55 +1,55 @@ -/** - * 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.document; - -import java.util.List; - -// TODO: Auto-generated Javadoc -/** - * The Class DocumentListWrapperImpl. - * - * @param the generic type - */ -public class DocumentListWrapperImpl implements DocumentListWrapper { - - /** The document list wrapper. */ - private List documentListWrapper; - - /** - * Instantiates a new document list wrapper impl. - * - * @param theDocumentListWrapper the the document list wrapper - */ - public DocumentListWrapperImpl(List theDocumentListWrapper) { - documentListWrapper = theDocumentListWrapper; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.common.document.DocumentListWrapper#getWrappedObject() - */ - public List getWrappedObject() { - return documentListWrapper; - } +/** + * 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.document; + +import java.util.List; + +// TODO: Auto-generated Javadoc +/** + * The Class DocumentListWrapperImpl. + * + * @param the generic type + */ +public class DocumentListWrapperImpl implements DocumentListWrapper { + + /** The document list wrapper. */ + private List documentListWrapper; + + /** + * Instantiates a new document list wrapper impl. + * + * @param theDocumentListWrapper the the document list wrapper + */ + public DocumentListWrapperImpl(List theDocumentListWrapper) { + documentListWrapper = theDocumentListWrapper; + } + + /* (non-Javadoc) + * @see org.collectionspace.services.common.document.DocumentListWrapper#getWrappedObject() + */ + public List getWrappedObject() { + return documentListWrapper; + } } \ No newline at end of file diff --git a/services/common/src/main/java/org/collectionspace/services/common/document/ValidatorHandlerImpl.java b/services/common/src/main/java/org/collectionspace/services/common/document/ValidatorHandlerImpl.java index eff2255e5..0239eee10 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/document/ValidatorHandlerImpl.java +++ b/services/common/src/main/java/org/collectionspace/services/common/document/ValidatorHandlerImpl.java @@ -1,152 +1,152 @@ -package org.collectionspace.services.common.document; - -import org.collectionspace.services.common.context.MultipartServiceContext; -import org.collectionspace.services.common.context.ServiceContext; -import org.collectionspace.services.common.document.DocumentHandler.Action; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -// TODO: Auto-generated Javadoc -/** - * The Class ValidatorHandlerImpl. - */ -public abstract class ValidatorHandlerImpl implements ValidatorHandler { - - /** - * The logger. - */ - private final Logger logger = LoggerFactory.getLogger(ValidatorHandlerImpl.class); - private ServiceContext ctx; - - protected ServiceContext getServiceContext() { - return ctx; - } - // gets reset by calls to setServiceContext() method - protected boolean enforceAsserts = true; - - public boolean getEnforceAsserts() { - return enforceAsserts; - } - - public void setEnforceAsserts(ServiceContext ctx) { - Boolean disableAssertsAttr = ctx.getServiceBinding().isDisableAsserts(); - if (disableAssertsAttr == null) { - enforceAsserts = true; - } else { - enforceAsserts = !disableAssertsAttr.booleanValue(); - } - } - - protected void setServiceContext(ServiceContext ctx) { - this.ctx = ctx; - - } - - protected void CS_ASSERT(boolean expression, String errorMsg) throws AssertionError { - if (expression != true) { - if (errorMsg == null) { - errorMsg = "Validation exception occurred in: " - + this.getClass().getName(); - } - throw new AssertionError(errorMsg); - } - } - - protected void CS_ASSERT(boolean expression) throws AssertionError { - CS_ASSERT(expression, null); - } - - private void init(ServiceContext ctx) { - setEnforceAsserts(ctx); - setServiceContext(ctx); - } - - /* - * (non-Javadoc) @see - * org.collectionspace.services.common.document.ValidatorHandler#validate(org.collectionspace.services.common.document.DocumentHandler.Action, - * org.collectionspace.services.common.context.ServiceContext) - */ - @Override - public void validate(Action action, ServiceContext ctx) - throws InvalidDocumentException { - init(ctx); - - switch (action) { - case CREATE: - handleCreate(); - break; - case GET: - handleGet(); - break; - case GET_ALL: - handleGetAll(); - break; - case UPDATE: - handleUpdate(); - break; - case DELETE: - handleDelete(); - break; - default: - throw new UnsupportedOperationException("ValidatorHandlerImpl: Unknown action = " - + action); - } - } - - protected boolean enforceAsserts() { - return !ctx.getServiceBinding().isDisableAsserts(); - } - - protected Object getCommonPart() { - Object result = null; - - try { - MultipartServiceContext multiPartCtx = (MultipartServiceContext) getServiceContext(); - result = multiPartCtx.getInputPart(ctx.getCommonPartLabel(), - getCommonPartClass()); - } catch (Exception e) { - if (logger.isDebugEnabled() == true) { - logger.debug("Could not extract common part from multipart input.", e); - } - } - - return result; - } - - abstract protected Class getCommonPartClass(); - - /** - * Handle create. - * - * @param ctx the ctx - */ - abstract protected void handleCreate() throws InvalidDocumentException; - - /** - * Handle get. - * - * @param ctx the ctx - */ - abstract protected void handleGet() throws InvalidDocumentException; - - /** - * Handle get all. - * - * @param ctx the ctx - */ - abstract protected void handleGetAll() throws InvalidDocumentException; - - /** - * Handle update. - * - * @param ctx the ctx - */ - abstract protected void handleUpdate() throws InvalidDocumentException; - - /** - * Handle delete. - * - * @param ctx the ctx - */ - abstract protected void handleDelete() throws InvalidDocumentException; +package org.collectionspace.services.common.document; + +import org.collectionspace.services.common.context.MultipartServiceContext; +import org.collectionspace.services.common.context.ServiceContext; +import org.collectionspace.services.common.document.DocumentHandler.Action; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +// TODO: Auto-generated Javadoc +/** + * The Class ValidatorHandlerImpl. + */ +public abstract class ValidatorHandlerImpl implements ValidatorHandler { + + /** + * The logger. + */ + private final Logger logger = LoggerFactory.getLogger(ValidatorHandlerImpl.class); + private ServiceContext ctx; + + protected ServiceContext getServiceContext() { + return ctx; + } + // gets reset by calls to setServiceContext() method + protected boolean enforceAsserts = true; + + public boolean getEnforceAsserts() { + return enforceAsserts; + } + + public void setEnforceAsserts(ServiceContext ctx) { + Boolean disableAssertsAttr = ctx.getServiceBinding().isDisableAsserts(); + if (disableAssertsAttr == null) { + enforceAsserts = true; + } else { + enforceAsserts = !disableAssertsAttr.booleanValue(); + } + } + + protected void setServiceContext(ServiceContext ctx) { + this.ctx = ctx; + + } + + protected void CS_ASSERT(boolean expression, String errorMsg) throws AssertionError { + if (expression != true) { + if (errorMsg == null) { + errorMsg = "Validation exception occurred in: " + + this.getClass().getName(); + } + throw new AssertionError(errorMsg); + } + } + + protected void CS_ASSERT(boolean expression) throws AssertionError { + CS_ASSERT(expression, null); + } + + private void init(ServiceContext ctx) { + setEnforceAsserts(ctx); + setServiceContext(ctx); + } + + /* + * (non-Javadoc) @see + * org.collectionspace.services.common.document.ValidatorHandler#validate(org.collectionspace.services.common.document.DocumentHandler.Action, + * org.collectionspace.services.common.context.ServiceContext) + */ + @Override + public void validate(Action action, ServiceContext ctx) + throws InvalidDocumentException { + init(ctx); + + switch (action) { + case CREATE: + handleCreate(); + break; + case GET: + handleGet(); + break; + case GET_ALL: + handleGetAll(); + break; + case UPDATE: + handleUpdate(); + break; + case DELETE: + handleDelete(); + break; + default: + throw new UnsupportedOperationException("ValidatorHandlerImpl: Unknown action = " + + action); + } + } + + protected boolean enforceAsserts() { + return !ctx.getServiceBinding().isDisableAsserts(); + } + + protected Object getCommonPart() { + Object result = null; + + try { + MultipartServiceContext multiPartCtx = (MultipartServiceContext) getServiceContext(); + result = multiPartCtx.getInputPart(ctx.getCommonPartLabel(), + getCommonPartClass()); + } catch (Exception e) { + if (logger.isDebugEnabled() == true) { + logger.debug("Could not extract common part from multipart input.", e); + } + } + + return result; + } + + abstract protected Class getCommonPartClass(); + + /** + * Handle create. + * + * @param ctx the ctx + */ + abstract protected void handleCreate() throws InvalidDocumentException; + + /** + * Handle get. + * + * @param ctx the ctx + */ + abstract protected void handleGet() throws InvalidDocumentException; + + /** + * Handle get all. + * + * @param ctx the ctx + */ + abstract protected void handleGetAll() throws InvalidDocumentException; + + /** + * Handle update. + * + * @param ctx the ctx + */ + abstract protected void handleUpdate() throws InvalidDocumentException; + + /** + * Handle delete. + * + * @param ctx the ctx + */ + abstract protected void handleDelete() throws InvalidDocumentException; } \ No newline at end of file diff --git a/services/common/src/main/java/org/collectionspace/services/common/imaging/nuxeo/NuxeoBlobUtils.java b/services/common/src/main/java/org/collectionspace/services/common/imaging/nuxeo/NuxeoBlobUtils.java index a6e514301..4e2b69512 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/imaging/nuxeo/NuxeoBlobUtils.java +++ b/services/common/src/main/java/org/collectionspace/services/common/imaging/nuxeo/NuxeoBlobUtils.java @@ -1,1418 +1,1418 @@ -/** - * NuxeoImageUtils.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.imaging.nuxeo; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.ByteArrayOutputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.Serializable; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.nuxeo.runtime.api.Framework; -//import org.nuxeo.runtime.api.ServiceManager; -//import org.nuxeo.runtime.api.ServiceDescriptor; - -//import org.nuxeo.common.utils.FileUtils; - -import org.nuxeo.ecm.platform.picture.api.ImageInfo; -import org.nuxeo.ecm.platform.picture.api.ImagingDocumentConstants; -import org.nuxeo.ecm.platform.picture.api.ImagingService; -import org.nuxeo.ecm.platform.picture.api.PictureView; -import org.nuxeo.ecm.platform.mimetype.MimetypeDetectionException; -import org.nuxeo.ecm.platform.mimetype.interfaces.MimetypeRegistry; -import org.nuxeo.ecm.platform.picture.api.adapters.PictureBlobHolder; -import org.nuxeo.ecm.platform.filemanager.api.FileManager; -import org.nuxeo.ecm.platform.filemanager.service.FileManagerService; -import org.nuxeo.ecm.platform.filemanager.service.extension.FileImporter; -import org.nuxeo.ecm.platform.filemanager.utils.FileManagerUtils; -import org.nuxeo.ecm.platform.types.TypeManager; -import org.nuxeo.ecm.core.repository.RepositoryDescriptor; -import org.nuxeo.ecm.core.repository.RepositoryManager; -import org.nuxeo.ecm.core.repository.RepositoryService; -import org.nuxeo.ecm.core.storage.sql.BinaryManager; -import org.nuxeo.ecm.core.storage.sql.DefaultBinaryManager; - -/* - * Keep these commented out import statements as reminders of Nuxeo's blob management -import org.nuxeo.runtime.model.ComponentManager; -import org.nuxeo.runtime.model.impl.ComponentManagerImpl; -import org.nuxeo.ecm.core.api.ejb.DocumentManagerBean; -import org.nuxeo.ecm.core.storage.sql.RepositoryImpl; -import org.nuxeo.ecm.core.storage.sql.Repository; -import org.nuxeo.ecm.core.storage.sql.Binary; -import org.nuxeo.ecm.core.storage.sql.RepositoryImpl; -import org.nuxeo.ecm.core.storage.sql.RepositoryResolver; -import org.nuxeo.ecm.core.storage.sql.coremodel.SQLBlob; -import org.nuxeo.ecm.core.storage.sql.coremodel.SQLRepository; -import org.nuxeo.ecm.core.storage.sql.RepositoryDescriptor; -import org.nuxeo.ecm.core.api.DocumentResolver; -*/ - -import org.nuxeo.ecm.core.api.IdRef; -import org.nuxeo.ecm.core.api.blobholder.BlobHolder; -import org.nuxeo.ecm.core.api.blobholder.DocumentBlobHolder; -import org.nuxeo.ecm.core.api.impl.blob.FileBlob; -import org.nuxeo.ecm.core.api.impl.blob.InputStreamBlob; -import org.nuxeo.ecm.core.api.impl.blob.StreamingBlob; -import org.nuxeo.ecm.core.api.impl.blob.ByteArrayBlob; -import org.nuxeo.ecm.core.api.repository.RepositoryInstance; -import org.nuxeo.ecm.core.api.repository.Repository; -import org.nuxeo.ecm.core.api.Blob; -import org.nuxeo.ecm.core.api.ClientException; -import org.nuxeo.ecm.core.api.DocumentModel; -import org.nuxeo.ecm.core.api.DocumentRef; -import org.nuxeo.ecm.core.event.EventServiceAdmin; -import org.nuxeo.ecm.core.schema.SchemaManager; -import org.nuxeo.ecm.core.schema.types.Schema; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -//import org.nuxeo.ecm.core.repository.jcr.testing.RepositoryOSGITestCase; - -import org.apache.commons.io.IOUtils; -import org.collectionspace.services.client.PoxPayloadIn; -import org.collectionspace.services.client.PoxPayloadOut; -import org.collectionspace.services.common.FileUtils; -import org.collectionspace.services.common.ServiceMain; -import org.collectionspace.services.common.blob.BlobInput; -import org.collectionspace.services.common.context.ServiceContext; -import org.collectionspace.services.common.document.TransactionException; -import org.collectionspace.services.common.repository.RepositoryClient; -import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils; -import org.collectionspace.services.common.blob.BlobOutput; -import org.collectionspace.services.blob.BlobsCommon; -import org.collectionspace.services.blob.DimensionSubGroup; -import org.collectionspace.services.blob.DimensionSubGroupList; -import org.collectionspace.services.blob.MeasuredPartGroup; -import org.collectionspace.services.blob.MeasuredPartGroupList; -import org.collectionspace.services.jaxb.BlobJAXBSchema; -import org.collectionspace.services.nuxeo.client.java.CommonList; -import org.collectionspace.services.nuxeo.client.java.RepositoryInstanceInterface; -import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl; -import org.collectionspace.services.nuxeo.extension.thumbnail.ThumbnailConstants; -import org.collectionspace.services.nuxeo.util.NuxeoUtils; -import org.collectionspace.services.config.service.ListResultField; - - -/** - * The Class NuxeoBlobUtils. - */ -public class NuxeoBlobUtils { - - /** The Constant logger. */ - private static final Logger logger = LoggerFactory - .getLogger(NuxeoBlobUtils.class); - - // - // A maximum byte size for the byte array used to hold an image. Images larger than this will - // be returned as FileInputStreams rather than ByteArrayInputStreams - // - private static final int MAX_IMAGE_BUFFER = 256 * 1024; // REM: 11/26/2013 - This should be set in a config/property file. - - // - // File name constants - // - private static final String NUXEO_FILENAME_BAD_CHARS = "[^a-zA-Z_0-9-.%:/\\ ]"; - private static final String NUXEO_FILENAME_VALID_STRING = "[a-zA-Z_0-9-.%:/\\ ]+"; - - public static final String DOCUMENT_PLACEHOLDER_IMAGE = "documentImage.jpg"; - public static final String DOCUMENT_MISSING_PLACEHOLDER_IMAGE = "documentImageMissing.jpg"; - public static final String MIME_JPEG = "image/jpeg"; - /* - * FIXME: REM - These constants should be coming from configuration and NOT - * hard coded. - */ - public static final String DERIVATIVE_ORIGINAL = "Original"; - public static final String DERIVATIVE_ORIGINAL_TAG = DERIVATIVE_ORIGINAL - + "_"; - - public static final String DERIVATIVE_ORIGINAL_JPEG = "OriginalJpeg"; - public static final String DERIVATIVE_ORIGINAL_JPEG_TAG = DERIVATIVE_ORIGINAL_JPEG - + "_"; - - public static final String DERIVATIVE_MEDIUM = "Medium"; - public static final String DERIVATIVE_MEDIUM_TAG = DERIVATIVE_MEDIUM + "_"; - - public static final String DERIVATIVE_THUMBNAIL = "Thumbnail"; - public static final String DERIVATIVE_THUMBNAIL_TAG = DERIVATIVE_THUMBNAIL - + "_"; - - public static final String DERIVATIVE_UNKNOWN = "_UNKNOWN_DERIVATIVE_NAME_"; - - // - // Image Dimension fields - // - public static final String PART_IMAGE = "digitalImage"; - public static final String PART_SUMMARY = "The dimensions of a digital image -width, height, and pixel depth."; - public static final String WIDTH = "width"; - public static final String HEIGHT = "height"; - public static final String DEPTH = "depth"; - public static final String UNIT_PIXELS = "pixels"; - public static final String UNIT_BITS = "bits"; - // - // Image Metadata schemas - These are Nuxeo defined schemas - // - public static final String SCHEMA_IPTC = "iptc"; - public static final String SCHEMA_IMAGE_METADATA = "image_metadata"; - - private static final int THUMB_SIZE_HEIGHT = 100; - private static final int THUMB_SIZE_WIDTH = 75; - - // static DefaultBinaryManager binaryManager = new DefaultBinaryManager(); - // //can we get this from Nuxeo? i.e., - // Framework.getService(BinaryManger.class) - - // /** The temp file name. */ - // static String tempFileName = "sunset.jpg"; - // - // /** The file separator. */ - // static String fileSeparator = System.getProperty("file.separator"); - // - // /** The cur dir. */ - // static String curDir = System.getProperty("user.dir"); - - /** - * Instantiates a new nuxeo image utils. - */ - NuxeoBlobUtils() { - // empty constructor - } - - /* - * Use this for debugging Nuxeo's PictureView class - */ - private static String toStringPictureView(PictureView pictureView) { - StringBuffer strBuffer = new StringBuffer(); - strBuffer.append("Description: " + pictureView.getDescription() + '\n'); - strBuffer.append("FileName: " + pictureView.getFilename() + '\n'); - strBuffer.append("Height: " + pictureView.getHeight() + '\n'); - strBuffer.append("Width: " + pictureView.getWidth() + '\n'); - strBuffer.append("Tag: " + pictureView.getTag() + '\n'); - strBuffer.append("Title: " + pictureView.getTitle() + '\n'); - return strBuffer.toString(); - } - - // FIXME: REM - This needs to be configuration-bases and NOT hard coded! - // FIXME: REM - Use MultiviewPicture adapter to get some of this information - static private String getDerivativeUri(String uri, String derivativeName) { - String result = DERIVATIVE_UNKNOWN; - - if (derivativeName.startsWith(DERIVATIVE_ORIGINAL_TAG) == true) { - result = DERIVATIVE_ORIGINAL; - } else if (derivativeName.startsWith(DERIVATIVE_ORIGINAL_JPEG_TAG) == true) { - result = DERIVATIVE_ORIGINAL_JPEG; - } else if (derivativeName.startsWith(DERIVATIVE_MEDIUM_TAG) == true) { - result = DERIVATIVE_MEDIUM; - } else if (derivativeName.startsWith(DERIVATIVE_THUMBNAIL_TAG) == true) { - result = DERIVATIVE_THUMBNAIL; - } - - return uri + result + "/" + BlobInput.URI_CONTENT_PATH; - } - - static private HashMap createBlobListItem(Blob blob, - String uri) { - HashMap item = new HashMap(); - - String value = blob.getEncoding(); - if (value != null && !value.trim().isEmpty()) { - item.put(BlobJAXBSchema.encoding, value); - } - value = Long.toString(blob.getLength()); - if (value != null && !value.trim().isEmpty()) { - item.put(BlobJAXBSchema.length, value); - } - value = blob.getMimeType(); - if (value != null && !value.trim().isEmpty()) { - item.put(BlobJAXBSchema.mimeType, value); - } - value = blob.getFilename(); - if (value != null && !value.trim().isEmpty()) { - item.put(BlobJAXBSchema.name, value); - } - value = getDerivativeUri(uri, blob.getFilename()); - if (value != null && !value.trim().isEmpty()) { - item.put(BlobJAXBSchema.uri, value); - } - - return item; - } - - static public String getSanizitedFilename(File srcFile) throws Exception { - return getSanizitedFilename(srcFile.getName()); - } - - /* - * Valid Nuxeo file names are a subset of *nix and Windows filenames, so we need to check. - */ - static public String getSanizitedFilename(String fileName) throws Exception { - String result = fileName; - - if (fileName != null && fileName.matches(NUXEO_FILENAME_VALID_STRING) == false) { - String fixedString = fileName.replaceAll(NUXEO_FILENAME_BAD_CHARS, "_"); // Replace "bad" chars with underscore character - if (fixedString.matches(NUXEO_FILENAME_VALID_STRING) == true) { - result = fixedString; - } else { - String errMsg = String.format("\tSorry, the sanizited string '%s' is still bad.", fixedString); - throw new Exception(errMsg); - } - } - - if (result != null && logger.isDebugEnabled() == true) { - if (result.equals(fileName) == false) { - logger.debug(String.format("The file name '%s' was sanizitized to '%s'.", fileName, result)); - } - } - - return result; - } - - static public CommonList getBlobDerivatives(RepositoryInstanceInterface repoSession, - String repositoryId, List resultsFields, String uri) - throws Exception { - CommonList commonList = new CommonList(); - int nFields = resultsFields.size() + 2; - String fields[] = new String[nFields];// FIXME: REM - Patrick needs to fix this hack. It is a "common list" issue - fields[0] = "csid"; - fields[1] = "uri"; - for (int i = 2; i < nFields; i++) { - ListResultField field = resultsFields.get(i - 2); - fields[i] = field.getElement(); - } - commonList.setFieldsReturned(fields); - - IdRef documentRef = new IdRef(repositoryId); - DocumentModel documentModel = repoSession.getDocument(documentRef); - DocumentBlobHolder docBlobHolder = (DocumentBlobHolder) documentModel - .getAdapter(BlobHolder.class); - List docBlobs = docBlobHolder.getBlobs(); - // List blobListItems = result.getBlobListItem(); - HashMap item = null; - for (Blob blob : docBlobs) { - if (blob != null) { - item = createBlobListItem(blob, uri); - commonList.addItem(item); - } - } - - return commonList; - } - - /* - * [dublincore, uid, picture, iptc, common, image_metadata] - */ - static private Map getMetadata(Blob nuxeoBlob) - throws Exception { - ImagingService service = Framework.getService(ImagingService.class); - Map metadataMap = service.getImageMetadata(nuxeoBlob); - return metadataMap; - } - - private static String[] imageTypes = {"jpeg", "bmp", "gif", "png", "tiff", "octet-stream"}; - static private boolean isImageMedia(Blob nuxeoBlob) { - boolean result = false; - - String mimeType = nuxeoBlob.getMimeType(); - if (mimeType != null) { - mimeType = mimeType.toLowerCase().trim(); - String[] parts = mimeType.split("/"); // split strings like "application/xml" into an array of two strings - if (parts.length == 2) { - for (String type : imageTypes) { - if (parts[1].equalsIgnoreCase(type)) { - result = true; - break; - } - } - } - } - - return result; - } - - static private MeasuredPartGroupList getDimensions( - DocumentModel documentModel, Blob nuxeoBlob) { - MeasuredPartGroupList result = null; - - if (isImageMedia(nuxeoBlob) == true) try { - ImagingService service = Framework.getService(ImagingService.class); - ImageInfo imageInfo = service.getImageInfo(nuxeoBlob); - Map metadataMap = getMetadata(nuxeoBlob); - - if (imageInfo != null) { - // - // Create a timestamp to add to all the image's dimensions - // - String valueDate = GregorianCalendarDateTimeUtils - .timestampUTC(); - - result = new MeasuredPartGroupList(); - List measuredPartGroupList = - (result).getMeasuredPartGroup(); - // - // Create a new measured part for the "image" - // - MeasuredPartGroup mpGroup = new MeasuredPartGroup(); - mpGroup.setMeasuredPart(PART_IMAGE); - mpGroup.setDimensionSummary(PART_SUMMARY); - mpGroup.setDimensionSubGroupList(new DimensionSubGroupList()); - List dimensionSubGroupList = mpGroup.getDimensionSubGroupList() - .getDimensionSubGroup(); - - // - // Set the width - // - DimensionSubGroup widthDimension = new DimensionSubGroup(); - widthDimension.setDimension(WIDTH); - widthDimension.setMeasurementUnit(UNIT_PIXELS); - widthDimension.setValue(intToBigDecimal(imageInfo.getWidth())); - widthDimension.setValueDate(valueDate); - dimensionSubGroupList.add(widthDimension); - // - // Set the height - // - DimensionSubGroup heightDimension = new DimensionSubGroup(); - heightDimension.setDimension(HEIGHT); - heightDimension.setMeasurementUnit(UNIT_PIXELS); - heightDimension - .setValue(intToBigDecimal(imageInfo.getHeight())); - heightDimension.setValueDate(valueDate); - dimensionSubGroupList.add(heightDimension); - // - // Set the depth - // - DimensionSubGroup depthDimension = new DimensionSubGroup(); - depthDimension.setDimension(DEPTH); - depthDimension.setMeasurementUnit(UNIT_BITS); - depthDimension.setValue(intToBigDecimal(imageInfo.getDepth())); - depthDimension.setValueDate(valueDate); - dimensionSubGroupList.add(depthDimension); - // - // Now set out result - // - measuredPartGroupList.add(mpGroup); - } else { - if (logger.isWarnEnabled() == true) { - logger.warn("Could not synthesize a dimension list of the blob: " - + documentModel.getName()); - } - } - } catch (Exception e) { - logger.warn("Could not extract image information for blob: " - + documentModel.getName(), e); - } - - return result; - } - - // FIXME: Add error checking here, as none of these calls return an - // Exception - static private BigDecimal intToBigDecimal(int i) { - BigInteger bigint = BigInteger.valueOf(i); - BigDecimal bigdec = new BigDecimal(bigint); - return bigdec; - } - - static private BlobsCommon createBlobsCommon(DocumentModel documentModel, - Blob nuxeoBlob) { - return createBlobsCommon(documentModel, nuxeoBlob, false); - } - - static private BlobsCommon createBlobsCommon(DocumentModel documentModel, - Blob nuxeoBlob, Boolean getContentFlag) { - BlobsCommon result = new BlobsCommon(); - - if (documentModel != null) { - result.setMimeType(nuxeoBlob.getMimeType()); - result.setName(nuxeoBlob.getFilename()); - result.setLength(Long.toString(nuxeoBlob.getLength())); - result.setRepositoryId(documentModel.getId()); - - // - // If getContentFlag is true then we're being asked for the blob's content, so we don't - // need the measurement info. Getting the measurement info requires a call to Nuxeo which in turn - // calls ImageMagick. - // - if (getContentFlag.booleanValue() == false) { - MeasuredPartGroupList measuredPartGroupList = getDimensions( - documentModel, nuxeoBlob); - if (measuredPartGroupList != null) { - result.setMeasuredPartGroupList(measuredPartGroupList); - } - } - - // Check to see if a thumbnail preview was created by Nuxeo - if (documentModel.hasFacet(ThumbnailConstants.THUMBNAIL_FACET)) { - String errorMsg = null; - String thumbnailName = null; - try { - thumbnailName = (String)documentModel.getProperty(ThumbnailConstants.THUMBNAIL_SCHEMA_NAME, - ThumbnailConstants.THUMBNAIL_FILENAME_PROPERTY_NAME); - Blob thumbnailBlob = (Blob)documentModel.getProperty(ThumbnailConstants.THUMBNAIL_SCHEMA_NAME, - ThumbnailConstants.THUMBNAIL_PROPERTY_NAME); - } catch (ClientException e) { - errorMsg = "Could not extract the name of the thumbnail preview image file."; - if (logger.isTraceEnabled()) { - logger.trace(errorMsg, e); - } - } - - if (errorMsg == null) { - logger.info("A thumbnail preview was created for this document blob: " + thumbnailName); - } else { - logger.warn(errorMsg); - } - } - } - - return result; - } - - /* - * This is a prototype method that is not currently used as of 1/1/2012. However, - * it may be useful now that we've transitioned to using an embedded Nuxeo server. - */ - static private File getBlobFile(RepositoryInstanceInterface ri, - DocumentModel documentModel, Blob blob) { - DefaultBinaryManager binaryManager = null; - RepositoryDescriptor descriptor = null; - File file = null; - - try { - RepositoryService repositoryService1 = (RepositoryService) Framework - .getRuntime().getComponent(RepositoryService.NAME); - - String repositoryName = documentModel.getRepositoryName(); - RepositoryManager repositoryManager = repositoryService1 - .getRepositoryManager(); - descriptor = repositoryManager.getDescriptor(repositoryName); - -// Keep this code around for future work/enhancements -// binaryManager = new DefaultBinaryManager(); -// -// File storageDir = binaryManager.getStorageDir(); -// // SQLBlob blob = (SQLBlob) -// // doc.getPropertyValue("schema:blobField"); -// File file = binaryManager.getFileForDigest(blob.getDigest(), false); - - } catch (Exception e) { - e.printStackTrace(); - } - -// Keep this code around for future work/enhancements -// try { -// binaryManager.initialize(SQLRepository.getDescriptor(descriptor)); -// } catch (IOException e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } catch (Exception e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } - -// Keep this code around for future work/enhancements -// File storageDir = binaryManager.getStorageDir(); -// SQLBlob blob = (SQLBlob) -// documentModel.getPropertyValue("schema:blobField"); -// File file = binaryManager.getFileForDigest(blob.getDigest(), false); - - return file; - } - - /** - * Returns a schema, given the name of a schema. Possibly usefule in the future - * - * @param schemaName - * a schema name. - * @return a schema. - */ - private static Schema getSchemaFromName(String schemaName) { - SchemaManager schemaManager = null; - try { - schemaManager = Framework.getService(SchemaManager.class); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return schemaManager != null ? schemaManager.getSchema(schemaName) - : null; - } - - /** - * Gets the blob. Not in use now, but might be useful in the future. - * - * @param nuxeoSession - * the nuxeo session - * @param id - * the id - * @return the blob - */ - static private Blob getBlob(RepositoryInstanceInterface repoSession, String id) { - Blob result = null; - - try { - Repository repository = repoSession.getRepositoryInstance().getRepository(); - // binaryManager.initialize(new RepositoryDescriptor()); - // binaryManager.getBinary("a4cac052ae0281979f2dcf5ab2e61a6c"); - // DocumentResolver.resolveReference(nuxeoSession, documentRef); - // binaryManager = repository.getBinaryManager(); - // documentModel.getr - } catch (Exception x) { - x.printStackTrace(); - } - - return result; - } - - static private Blob checkMimeType(Blob blob, String fullname) - throws ClientException { - final String mimeType = blob.getMimeType(); - if (mimeType != null && !mimeType.equals("application/octet-stream") - && !mimeType.equals("application/octetstream")) { - return blob; - } - String filename = FileManagerUtils.fetchFileName(fullname); - try { - blob = getMimeService().updateMimetype(blob, filename); - } catch (MimetypeDetectionException e) { - throw new ClientException(e); - } - return blob; - } - - /** - * Gets the type service. Not in use, but please keep for future reference - * - * @return the type service - * @throws ClientException - * the client exception - */ - private static TypeManager getTypeService() throws ClientException { - TypeManager typeService = null; - - try { - typeService = Framework.getService(TypeManager.class); - } catch (Exception e) { - throw new ClientException(e); - } - - return typeService; - } - - /** - * Gets the bytes. - * - * @param fis - * the fis - * @return the bytes - */ - private static byte[] getBytes(InputStream fis) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - byte[] buf = new byte[128 * 1024]; - try { - for (int readNum; (readNum = fis.read(buf)) != -1;) { - bos.write(buf, 0, readNum); - // no doubt here is 0 - /* - * Writes len bytes from the specified byte array starting at - * offset off to this byte array output stream. - */ - System.out.println("read " + readNum + " bytes,"); - } - } catch (IOException ex) { - logger.error(ex.getMessage(), ex); - } - byte[] bytes = bos.toByteArray(); - // bytes is the ByteArray we need - return bytes; - } - - /** - * Creates the serializable blob. We may need this code, do not remove. - * - * @param fileInputStream - * the file input stream - * @param filename - * the filename - * @param mimeType - * the mime type - * @return the blob - */ - private static Blob createSerializableBlob(InputStream fileInputStream, - String filename, String mimeType) { - Blob blob = null; - try { - // persisting the blob makes it possible to read the binary content - // of the request stream several times (mimetype sniffing, digest - // computation, core binary storage) - byte[] bytes = getBytes(fileInputStream); - blob = new ByteArrayBlob(bytes); - // filename - if (filename != null) { - filename = getCleanFileName(filename); - } - blob.setFilename(filename); - // mimetype detection - MimetypeRegistry mimeService = Framework - .getService(MimetypeRegistry.class); - String detectedMimeType = mimeService - .getMimetypeFromFilenameAndBlobWithDefault(filename, blob, - null); - if (detectedMimeType == null) { - if (mimeType != null) { - detectedMimeType = mimeType; - } else { - // default - detectedMimeType = "application/octet-stream"; - } - } - blob.setMimeType(detectedMimeType); - } catch (MimetypeDetectionException e) { - logger.error(String.format("could not fetch mimetype for file %s", - filename), e); - } catch (Exception e) { - logger.error("", e); - } - return blob; - } - - /** - * Creates a serializable blob from a stream, with filename and mimetype - * detection. - * - *

- * Creates an in-memory blob if data is under 64K, otherwise constructs a - * serializable FileBlob which stores data in a temporary file on the hard - * disk. - *

- * - * @param file - * the input stream holding data - * @param filename - * the file name. Will be set on the blob and will used for - * mimetype detection. - * @param mimeType - * the detected mimetype at upload. Can be null. Will be verified - * by the mimetype service. - * @return the blob - */ - private static Blob createStreamingBlob(File file, String filename, - String mimeType) { - Blob blob = null; - try { - // persisting the blob makes it possible to read the binary content - // of the request stream several times (mimetype sniffing, digest - // computation, core binary storage) - blob = StreamingBlob.createFromFile(file, mimeType).persist(); - // filename - if (filename != null) { - filename = getCleanFileName(filename); - } - blob.setFilename(filename); - // mimetype detection - MimetypeRegistry mimeService = Framework - .getService(MimetypeRegistry.class); - String detectedMimeType = mimeService - .getMimetypeFromFilenameAndBlobWithDefault(filename, blob, - null); - if (detectedMimeType == null) { - if (mimeType != null) { - detectedMimeType = mimeType; - } else { - // default - detectedMimeType = "application/octet-stream"; - } - } - blob.setMimeType(detectedMimeType); - } catch (MimetypeDetectionException e) { - logger.error(String.format("could not fetch mimetype for file %s", - filename), e); - } catch (IOException e) { - logger.error("", e); - } catch (Exception e) { - logger.error("", e); - } - return blob; - } - - private static Blob createNuxeoFileBasedBlob(File file) throws Exception { - return new FileBlob(file); - } - - /** - * Returns a clean filename, stripping upload path on client side. - *

- * Fixes NXP-544 - *

- * - * @param filename - * the filename - * @return the clean file name - */ - private static String getCleanFileName(String filename) { - String res = null; - int lastWinSeparator = filename.lastIndexOf('\\'); - int lastUnixSeparator = filename.lastIndexOf('/'); - int lastSeparator = Math.max(lastWinSeparator, lastUnixSeparator); - if (lastSeparator != -1) { - res = filename.substring(lastSeparator + 1, filename.length()); - } else { - res = filename; - } - return res; - } - - /** - * Gets Nuxeo's file manager service. - * - * @return the file manager service - * @throws ClientException - * the client exception - */ - private static FileManager getFileManager() throws ClientException { - FileManager result = null; - - try { - result = Framework.getService(FileManager.class); - } catch (Exception e) { - String msg = "Unable to get Nuxeo's FileManager service."; - logger.error(msg, e); - throw new ClientException("msg", e); - } - - return result; - } - - /** - * Gets Nuxeo's file manager service. - * - * @return the file manager service - * @throws ClientException - * the client exception - */ - private static FileManagerService getFileManagerService() throws ClientException { - FileManagerService result = null; - - try { - result = (FileManagerService)getFileManager(); - } catch (Exception e) { - String msg = "Unable to get Nuxeo's FileManager service."; - logger.error(msg, e); - throw new ClientException("msg", e); - } - - return result; - } - - /** - * Gets Nuxeo's file manager service. - * - * @return the file manager service - * @throws ClientException - * the client exception - */ - private static FileManager getFileManagerServicex() throws ClientException { - FileManager result = null; - try { - result = Framework.getService(FileManager.class); - } catch (Exception e) { - String msg = "Unable to get Nuxeo's FileManager service."; - logger.error(msg, e); - throw new ClientException("msg", e); - } - return result; - } - - private static EventServiceAdmin getEventServiceAdmin() throws ClientException { - EventServiceAdmin result = null; - try { - result = Framework.getService(EventServiceAdmin.class); - } catch (Exception e) { - String msg = "Unable to get Nuxeo's EventServiceAdmin service."; - logger.error(msg, e); - throw new ClientException("msg", e); - } - return result; - } - - private static BinaryManager getBinaryManagerService() throws ClientException { - BinaryManager result = null; - try { - result = Framework.getService(BinaryManager.class); - } catch (Exception e) { - String msg = "Unable to get Nuxeo's BinaryManager service."; - logger.error(msg, e); - throw new ClientException("msg", e); - } - return result; - } - - static private RepositoryInstanceInterface getRepositorySession(ServiceContext ctx, RepositoryClient repositoryClient) { - RepositoryInstanceInterface result = null; - RepositoryJavaClientImpl nuxeoClient = (RepositoryJavaClientImpl)repositoryClient; - - try { - result = nuxeoClient.getRepositorySession(ctx); - } catch (Exception e) { - logger.error("Could not get a repository session to the Nuxeo repository", e); - } - - return result; - } - - static private void releaseRepositorySession(ServiceContext ctx, RepositoryClient repositoryClient, RepositoryInstanceInterface repoSession) throws TransactionException { - RepositoryJavaClientImpl nuxeoClient = (RepositoryJavaClientImpl)repositoryClient; - nuxeoClient.releaseRepositorySession(ctx, repoSession); - } - - static private MimetypeRegistry getMimeService() throws ClientException { - MimetypeRegistry result = null; - - try { - result = Framework.getService(MimetypeRegistry.class); - } catch (Exception e) { - throw new ClientException(e); - } - - return result; - } - - private static DocumentModel createDocumentFromBlob( - RepositoryInstanceInterface repoSession, - Blob inputStreamBlob, - String blobLocation, - boolean overwrite, - String blobName, - boolean useNuxeoAdaptors) throws Exception { - DocumentModel result = null; - - if (useNuxeoAdaptors == true) { - // - // Use Nuxeo's high-level create method which looks for plugin adapters that match the MIME type. For example, - // for image blobs, Nuxeo's file manager will pick a special image plugin that will automatically generate - // image derivatives. - // - result = getFileManager().createDocumentFromBlob( - repoSession.getRepositoryInstance(), inputStreamBlob, blobLocation, true, blobName); - } else { - // - // User Nuxeo's default file importer/adapter explicitly. This avoids specialized functionality from happening like - // image derivative creation. - // - String digestAlgorithm = getFileManager() - .getDigestAlgorithm(); // Only call this because we seem to need some way of initializing Nuxeo's FileManager with a call. - - FileManagerService fileManagerService = getFileManagerService(); - inputStreamBlob = checkMimeType(inputStreamBlob, blobName); - - FileImporter defaultFileImporter = fileManagerService.getPluginByName("DefaultFileImporter"); - result = defaultFileImporter.create( - repoSession.getRepositoryInstance(), inputStreamBlob, blobLocation, true, blobName, getTypeService()); - } - - return result; - } - - static public BlobsCommon createBlobInRepository( - ServiceContext ctx, - RepositoryClient repositoryClient, - InputStream inputStream, - String blobName, - boolean useNuxeoAdaptors) throws TransactionException { - BlobsCommon result = null; - - boolean repoSessionCleanup = false; - RepositoryInstanceInterface repoSession = (RepositoryInstanceInterface)ctx.getCurrentRepositorySession(); - if (repoSession == null) { - repoSession = getRepositorySession(ctx, repositoryClient); - repoSessionCleanup = true; - } - - try { - // We'll store the blob inside the workspace directory of the calling service - String nuxeoWspaceId = ctx.getRepositoryWorkspaceId(); - DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId); - DocumentModel blobLocation = repoSession.getDocument(nuxeoWspace); - - Blob inputStreamBlob = new InputStreamBlob(inputStream); - DocumentModel documentModel = createDocumentFromBlob( - repoSession, - inputStreamBlob, - blobLocation.getPathAsString(), - true, - blobName, - useNuxeoAdaptors); - result = createBlobsCommon(documentModel, inputStreamBlob); // Now create the metadata about the Nuxeo blob document - } catch (Exception e) { - result = null; - logger.error("Could not create new Nuxeo blob document.", e); //FIXME: REM - This should probably be re-throwing the exception? - } finally { - if (repoSessionCleanup == true) { - releaseRepositorySession(ctx, repositoryClient, repoSession); - } - } - - return result; - } - - /** - * Creates the picture. - * - * @param ctx - * the ctx - * @param repoSession - * the repo session - * @param filePath - * the file path - * @return the string - * @throws Exception - */ - public static BlobsCommon createBlobInRepository( - ServiceContext ctx, - RepositoryInstanceInterface repoSession, - BlobInput blobInput, - boolean purgeOriginal, - boolean useNuxeoAdaptors) throws Exception { - BlobsCommon result = null; - - File originalFile = blobInput.getBlobFile(); - File targetFile = originalFile; - try { - // We'll store the blob inside the workspace directory of the calling service - String nuxeoWspaceId = ctx.getRepositoryWorkspaceId(); - DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId); - DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace); - // - // If the original file's name contains "illegal" characters, then we create a copy of the file to give Nuxeo. - // - String sanitizedName = NuxeoBlobUtils.getSanizitedFilename(originalFile); - if (sanitizedName.equals(originalFile.getName()) == false) { - targetFile = FileUtils.createTmpFile(originalFile, sanitizedName); - if (logger.isDebugEnabled() == true) { - logger.debug(String.format("The file '%s''s name has characters that Nuxeo can't deal with. Rather than renaming the file, we created a new temp file at '%s'", - originalFile.getName(), targetFile.getAbsolutePath())); - } - } - - result = createBlobInRepository(repoSession, - wspaceDoc, - purgeOriginal, - targetFile, - null, // MIME type - useNuxeoAdaptors); - // - // Make sure we're using the original file name in our BlobsCommon instance. If the original file's name - // contained illegal characters, then we created and handed a copy of the file to Nuxeo. We don't want the - // copy's file name stored in the BlobsCommon instance, we want the original file name instead. - // - if (targetFile.equals(originalFile) == false) { - result.setName(originalFile.getName()); - } - - } catch (Exception e) { - logger.error("Could not create image blob.", e); - throw e; - } finally { - // - // If we created a temp file then we should delete it. - // - if (targetFile.equals(originalFile) == false) { - if (targetFile.delete() == false) { - logger.warn(String.format("Attempt to delete temporary file '%s' failed.", targetFile.getAbsolutePath())); - } - } - } - - return result; - } - - /* - * Find out if this document's blob/file-contents are allowed to be purged. For instance, we currently - * only want to allow the purging the contents of Nuxeo "Picture" documents. - */ - static private boolean isPurgeAllowed(DocumentModel docModel) { - boolean result = false; - - if (docModel.hasFacet(ImagingDocumentConstants.PICTURE_FACET) == true) { - result = true; // Yes, delete/purge the original content - } - - return result; - } - - /** - * Creates the image blob. - * - * @param nuxeoSession - * the nuxeo session - * @param blobLocation - * the blob location - * @param file - * the file - * @param fileName - * the file name - * @param mimeType - * the mime type - * @return the string - */ - static private BlobsCommon createBlobInRepository(RepositoryInstanceInterface nuxeoSession, - DocumentModel blobLocation, - boolean purgeOriginal, - File file, - String mimeType, - boolean useNuxeoAdaptors) { - BlobsCommon result = null; - - try { - Blob fileBlob = createNuxeoFileBasedBlob(file); - - DocumentModel documentModel = createDocumentFromBlob( - nuxeoSession, fileBlob, - blobLocation.getPathAsString(), - true, - file.getName(), - useNuxeoAdaptors); - - result = createBlobsCommon(documentModel, fileBlob); // Now create our metadata resource document - - // If the sender wanted us to generate only derivatives, we need to purge/clear the original contents - if (purgeOriginal == true && isPurgeAllowed(documentModel) == true) { - // Empty the document model's "content" property -this does not delete the actual file/blob - documentModel.setPropertyValue("file:content", (Serializable) null); - - if (documentModel.hasFacet(ImagingDocumentConstants.PICTURE_FACET)) { - // Now with no content, the derivative listener wants to update the derivatives. So to - // prevent the listener, we remove the "Picture" facet from the document - NuxeoUtils.removeFacet(documentModel, ImagingDocumentConstants.PICTURE_FACET); // Removing this facet ensures the original derivatives are unchanged. - nuxeoSession.saveDocument(documentModel); - // Now that we've emptied the document model's content field, we can add back the Picture facet - NuxeoUtils.addFacet(documentModel, ImagingDocumentConstants.PICTURE_FACET); - } - - nuxeoSession.saveDocument(documentModel); - // Next, we need to remove the actual file from Nuxeo's data directory - DocumentBlobHolder docBlobHolder = (DocumentBlobHolder) documentModel - .getAdapter(BlobHolder.class); - Blob blob = docBlobHolder.getBlob(); - if(blob == null) { - logger.error("Could not get blob for original image. Trying to delete original for: {}", - file.getName()); - } else { - boolean deleteSuccess = NuxeoUtils.deleteFileOfBlob(docBlobHolder.getBlob()); - } - } - } catch (Exception e) { - result = null; - logger.error("Could not create new Nuxeo blob document.", e); //FIXME: REM - This should probably be re-throwing the exception? - } - - return result; - } - - // /* - // * This is an alternate approach to getting information about an image - // * and its corresponding derivatives. - // */ - // // MultiviewPictureAdapter multiviewPictureAdapter = - // documentModel.getAdapter(MultiviewPictureAdapter.class); - // MultiviewPictureAdapterFactory multiviewPictureAdapterFactory = new - // MultiviewPictureAdapterFactory(); - // MultiviewPictureAdapter multiviewPictureAdapter = - // (MultiviewPictureAdapter)multiviewPictureAdapterFactory.getAdapter(documentModel, - // null); - // if (multiviewPictureAdapter != null) { - // PictureView[] pictureViewArray = multiviewPictureAdapter.getViews(); - // for (PictureView pictureView : pictureViewArray) { - // if (logger.isDebugEnabled() == true) { - // logger.debug("-------------------------------------"); - // logger.debug(toStringPictureView(pictureView)); - // } - // } - // } - - public static InputStream getResource(String resourceName) { - InputStream result = null; - - try { - result = ServiceMain.getInstance().getResourceAsStream(resourceName); - } catch (FileNotFoundException e) { - logger.error("Missing Services resource: " + resourceName, e); - } - - return result; - } - - static public BlobOutput getBlobOutput(ServiceContext ctx, - RepositoryClient repositoryClient, - String repositoryId, - StringBuffer outMimeType) throws TransactionException { - BlobOutput result = null; - - boolean repoSessionCleanup = false; - RepositoryInstanceInterface repoSession = (RepositoryInstanceInterface)ctx.getCurrentRepositorySession(); - if (repoSession == null) { - repoSession = getRepositorySession(ctx, repositoryClient); - repoSessionCleanup = true; - } - - try { - result = getBlobOutput(ctx, repoSession, repositoryId, null, true, outMimeType); - if (outMimeType.length() == 0) { - BlobsCommon blobsCommon = result.getBlobsCommon(); - String mimeType = blobsCommon.getMimeType(); - outMimeType.append(mimeType); - } - } finally { - if (repoSessionCleanup == true) { - releaseRepositorySession(ctx, repositoryClient, repoSession); - } - } - - return result; - } - - // - // If the blob is not too big, we return a ByteArrayInputStream. Otherwise, we return Nuxeo's InputStream - // which is usually a FileInputStream. - // - static private InputStream getInputStream(BlobsCommon blobsCommon, Blob blob) { - InputStream result = null; - - try { - InputStream blobStream = blob.getStream(); // By default, the result will be whatever stream Nuxeo returns to us. - int blobSize = blobsCommon.getLength() != null ? Integer.parseInt(blobsCommon.getLength()) : 0; - if (blobSize > 0 && blobSize < MAX_IMAGE_BUFFER) { - byte[] bytes = IOUtils.toByteArray(blobStream); - blobStream.close(); // Close the InputStream that we got from Nuxeo since it's usually a FileInputStream -we definitely want FileInputStreams closed. - result = new ByteArrayInputStream(bytes); - } else { - result = blobStream; // The blob is too large to put into a ByteArrayStream. - } - } catch (Exception e) { - logger.error(String.format("Error getting the InputStream content for file %s.", blobsCommon.getName()), e); - if (result != null) { - try { - result.close(); - result = null; - } catch (Exception x) { - logger.debug(String.format("Exception encountered during InputStream cleanup of file %s", blobsCommon.getName()), x); - } - } - } - - return result; - } - - /** - * Gets the image. - * - * @param repoSession - * the repo session - * @param repositoryId - * the repository id - * @param derivativeTerm - * the derivative term - * @return the image - */ - static public BlobOutput getBlobOutput(ServiceContext ctx, - RepositoryInstanceInterface repoSession, - String repositoryId, - String derivativeTerm, - Boolean getContentFlag, - StringBuffer outMimeType) { - BlobOutput result = new BlobOutput(); - boolean isNonImageDerivative = false; - - if (repositoryId != null && repositoryId.isEmpty() == false) - try { - IdRef documentRef = new IdRef(repositoryId); - DocumentModel documentModel = repoSession.getDocument(documentRef); - - Blob docBlob = null; - DocumentBlobHolder docBlobHolder = (DocumentBlobHolder) documentModel - .getAdapter(BlobHolder.class); - if (docBlobHolder instanceof PictureBlobHolder) { - // if it is a PictureDocument then it has these - // Nuxeo schemas: [dublincore, uid, picture, iptc, common, image_metadata] - // - // Need to add the "MultiviewPictureAdapter" support here to - // get the view data, see above. - // - PictureBlobHolder pictureBlobHolder = (PictureBlobHolder) docBlobHolder; - if (derivativeTerm != null) { - docBlob = pictureBlobHolder.getBlob(derivativeTerm); - // Nuxeo derivatives are all JPEG - outMimeType.append(MIME_JPEG); // All Nuxeo image derivatives are JPEG images. - } else { - docBlob = pictureBlobHolder.getBlob(); - } - } else { - docBlob = docBlobHolder.getBlob(); - if (derivativeTerm != null) { // If its a derivative request on a non-image blob, then return just a document image thumnail - isNonImageDerivative = true; - } - } - - // - // Create the result instance that will contain the blob metadata - // and an InputStream with the bits if the 'getContentFlag' is - // set. - // - BlobsCommon blobsCommon = createBlobsCommon(documentModel, docBlob, getContentFlag); - result.setBlobsCommon(blobsCommon); - if (getContentFlag == true) { - InputStream remoteStream = null; - if (isNonImageDerivative == false) { - //remoteStream = docBlob.getStream(); - remoteStream = getInputStream(blobsCommon, docBlob); // CSPACE-6110 - For small files, return a byte array instead of a file stream - } else { - remoteStream = getResource(DOCUMENT_PLACEHOLDER_IMAGE); - outMimeType.append(MIME_JPEG); - } -// BufferedInputStream bufferedInputStream = new BufferedInputStream( -// remoteStream); -// result.setBlobInputStream(bufferedInputStream); - result.setBlobInputStream(remoteStream); - } - } catch (Exception e) { - if (logger.isErrorEnabled() == true) { - logger.error(e.getMessage(), e); - } - result = null; - } - - return result; - } - -} - -/* - * Notes and code snippets about Nuxeo's support for binaries and image - * documents. - */ - -/* - * - * - * MultiviewPictureAdapter org.nuxeo.ecm.platform.picture.api.adapters - * PictureResourceAdapter pictureResourceAdapter = (PictureResourceAdapter) - * documentModel.getAdapter(PictureResourceAdapter.class); String thumbnailPath - * = pictureResourceAdapter.getViewXPath("Thumbnail"); - * - * Map blobHolderProps = docBlobHolder.getProperties(); - * String filePath = docBlobHolder.getFilePath(); List docBlobs = - * docBlobHolder.getBlobs(); - * - * stream = new FileInputStream(fileUploadHolder.getTempFile()); - * - * public String addFile(InputStream fileUpload, String fileName) fileName = - * FileUtils.getCleanFileName(fileName); DocumentModel currentDocument = - * navigationContext.getCurrentDocument(); String path = - * currentDocument.getPathAsString(); Blob blob = - * FileUtils.createSerializableBlob(fileUpload, fileName, null); - * - * DocumentModel createdDoc = getFileManagerService().createDocumentFromBlob( - * documentManager, blob, path, true, fileName); - * eventManager.raiseEventsOnDocumentSelected(createdDoc); - * - * protected FileManager fileManager; - * - * protected FileManager getFileManagerService() throws ClientException { if - * (fileManager == null) { try { fileManager = - * Framework.getService(FileManager.class); } catch (Exception e) { - * log.error("Unable to get FileManager service ", e); throw new - * ClientException("Unable to get FileManager service ", e); } } return - * fileManager; } - */ - -/* - * RepositoryService repositoryService = (RepositoryService) - * Framework.getRuntime().getComponent( RepositoryService.NAME); - * RepositoryManager repositoryManager = - * repositoryService.getRepositoryManager(); RepositoryDescriptor descriptor = - * repositoryManager.getDescriptor(repositoryName); DefaultBinaryManager - * binaryManager = new DefaultBinaryManager( - * SQLRepository.getDescriptor(descriptor))); - * - * File storageDir = binaryManager.getStorageDir(); SQLBlob blob = (SQLBlob) - * doc.getPropertyValue("schema:blobField"); File file = - * binaryManager.getFileForDigest( blob.getBinary().getDigest(), false); - */ - -/* - * RepositoryInstance.getStreamURI() - * - * String getStreamURI(String blobPropertyId) throws ClientException - * - * Returns an URI identifying the stream given the blob property id. This method - * should be used by a client to download the data of a blob property. - * - * The blob is fetched from the repository and the blob stream is registered - * against the streaming service so the stream will be available remotely - * through stream service API. - * - * After the client has called this method, it will be able to download the - * stream using streaming server API. - * - * Returns: an URI identifying the remote stream Throws: ClientException - */ - -/* - * A blob contains usually large data. - * - * Document fields holding Blob data are by default fetched in a lazy manner. - * - * A Blob object hides the data source and it also describes data properties - * like the encoding or mime-type. - * - * The encoding is used to decode Unicode text content that was stored in an - * encoded form. If not encoding is specified, the default java encoding is - * used. The encoding is ignored for binary content. - * - * When retrieving the content from a document, it will be returned as source - * content instead of returning the content bytes. - * - * The same is true when setting the content for a document: you set a content - * source and not directly the content bytes. Ex: - * - * File file = new File("/tmp/index.html"); FileBlob fb = new FileBlob(file); - * fb.setMimeType("text/html"); fb.setEncoding("UTF-8"); // this specifies that - * content bytes will be stored as UTF-8 document.setProperty("file", "content", - * fb); - * - * - * Then you may want to retrieve the content as follow: - * - * Blob blob = document.getProperty("file:content"); htmlDoc = blob.getString(); - * // the content is decoded from UTF-8 into a java string - */ +/** + * NuxeoImageUtils.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.imaging.nuxeo; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.ByteArrayOutputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.Serializable; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.nuxeo.runtime.api.Framework; +//import org.nuxeo.runtime.api.ServiceManager; +//import org.nuxeo.runtime.api.ServiceDescriptor; + +//import org.nuxeo.common.utils.FileUtils; + +import org.nuxeo.ecm.platform.picture.api.ImageInfo; +import org.nuxeo.ecm.platform.picture.api.ImagingDocumentConstants; +import org.nuxeo.ecm.platform.picture.api.ImagingService; +import org.nuxeo.ecm.platform.picture.api.PictureView; +import org.nuxeo.ecm.platform.mimetype.MimetypeDetectionException; +import org.nuxeo.ecm.platform.mimetype.interfaces.MimetypeRegistry; +import org.nuxeo.ecm.platform.picture.api.adapters.PictureBlobHolder; +import org.nuxeo.ecm.platform.filemanager.api.FileManager; +import org.nuxeo.ecm.platform.filemanager.service.FileManagerService; +import org.nuxeo.ecm.platform.filemanager.service.extension.FileImporter; +import org.nuxeo.ecm.platform.filemanager.utils.FileManagerUtils; +import org.nuxeo.ecm.platform.types.TypeManager; +import org.nuxeo.ecm.core.repository.RepositoryDescriptor; +import org.nuxeo.ecm.core.repository.RepositoryManager; +import org.nuxeo.ecm.core.repository.RepositoryService; +import org.nuxeo.ecm.core.storage.sql.BinaryManager; +import org.nuxeo.ecm.core.storage.sql.DefaultBinaryManager; + +/* + * Keep these commented out import statements as reminders of Nuxeo's blob management +import org.nuxeo.runtime.model.ComponentManager; +import org.nuxeo.runtime.model.impl.ComponentManagerImpl; +import org.nuxeo.ecm.core.api.ejb.DocumentManagerBean; +import org.nuxeo.ecm.core.storage.sql.RepositoryImpl; +import org.nuxeo.ecm.core.storage.sql.Repository; +import org.nuxeo.ecm.core.storage.sql.Binary; +import org.nuxeo.ecm.core.storage.sql.RepositoryImpl; +import org.nuxeo.ecm.core.storage.sql.RepositoryResolver; +import org.nuxeo.ecm.core.storage.sql.coremodel.SQLBlob; +import org.nuxeo.ecm.core.storage.sql.coremodel.SQLRepository; +import org.nuxeo.ecm.core.storage.sql.RepositoryDescriptor; +import org.nuxeo.ecm.core.api.DocumentResolver; +*/ + +import org.nuxeo.ecm.core.api.IdRef; +import org.nuxeo.ecm.core.api.blobholder.BlobHolder; +import org.nuxeo.ecm.core.api.blobholder.DocumentBlobHolder; +import org.nuxeo.ecm.core.api.impl.blob.FileBlob; +import org.nuxeo.ecm.core.api.impl.blob.InputStreamBlob; +import org.nuxeo.ecm.core.api.impl.blob.StreamingBlob; +import org.nuxeo.ecm.core.api.impl.blob.ByteArrayBlob; +import org.nuxeo.ecm.core.api.repository.RepositoryInstance; +import org.nuxeo.ecm.core.api.repository.Repository; +import org.nuxeo.ecm.core.api.Blob; +import org.nuxeo.ecm.core.api.ClientException; +import org.nuxeo.ecm.core.api.DocumentModel; +import org.nuxeo.ecm.core.api.DocumentRef; +import org.nuxeo.ecm.core.event.EventServiceAdmin; +import org.nuxeo.ecm.core.schema.SchemaManager; +import org.nuxeo.ecm.core.schema.types.Schema; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +//import org.nuxeo.ecm.core.repository.jcr.testing.RepositoryOSGITestCase; + +import org.apache.commons.io.IOUtils; +import org.collectionspace.services.client.PoxPayloadIn; +import org.collectionspace.services.client.PoxPayloadOut; +import org.collectionspace.services.common.FileUtils; +import org.collectionspace.services.common.ServiceMain; +import org.collectionspace.services.common.blob.BlobInput; +import org.collectionspace.services.common.context.ServiceContext; +import org.collectionspace.services.common.document.TransactionException; +import org.collectionspace.services.common.repository.RepositoryClient; +import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils; +import org.collectionspace.services.common.blob.BlobOutput; +import org.collectionspace.services.blob.BlobsCommon; +import org.collectionspace.services.blob.DimensionSubGroup; +import org.collectionspace.services.blob.DimensionSubGroupList; +import org.collectionspace.services.blob.MeasuredPartGroup; +import org.collectionspace.services.blob.MeasuredPartGroupList; +import org.collectionspace.services.jaxb.BlobJAXBSchema; +import org.collectionspace.services.nuxeo.client.java.CommonList; +import org.collectionspace.services.nuxeo.client.java.RepositoryInstanceInterface; +import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl; +import org.collectionspace.services.nuxeo.extension.thumbnail.ThumbnailConstants; +import org.collectionspace.services.nuxeo.util.NuxeoUtils; +import org.collectionspace.services.config.service.ListResultField; + + +/** + * The Class NuxeoBlobUtils. + */ +public class NuxeoBlobUtils { + + /** The Constant logger. */ + private static final Logger logger = LoggerFactory + .getLogger(NuxeoBlobUtils.class); + + // + // A maximum byte size for the byte array used to hold an image. Images larger than this will + // be returned as FileInputStreams rather than ByteArrayInputStreams + // + private static final int MAX_IMAGE_BUFFER = 256 * 1024; // REM: 11/26/2013 - This should be set in a config/property file. + + // + // File name constants + // + private static final String NUXEO_FILENAME_BAD_CHARS = "[^a-zA-Z_0-9-.%:/\\ ]"; + private static final String NUXEO_FILENAME_VALID_STRING = "[a-zA-Z_0-9-.%:/\\ ]+"; + + public static final String DOCUMENT_PLACEHOLDER_IMAGE = "documentImage.jpg"; + public static final String DOCUMENT_MISSING_PLACEHOLDER_IMAGE = "documentImageMissing.jpg"; + public static final String MIME_JPEG = "image/jpeg"; + /* + * FIXME: REM - These constants should be coming from configuration and NOT + * hard coded. + */ + public static final String DERIVATIVE_ORIGINAL = "Original"; + public static final String DERIVATIVE_ORIGINAL_TAG = DERIVATIVE_ORIGINAL + + "_"; + + public static final String DERIVATIVE_ORIGINAL_JPEG = "OriginalJpeg"; + public static final String DERIVATIVE_ORIGINAL_JPEG_TAG = DERIVATIVE_ORIGINAL_JPEG + + "_"; + + public static final String DERIVATIVE_MEDIUM = "Medium"; + public static final String DERIVATIVE_MEDIUM_TAG = DERIVATIVE_MEDIUM + "_"; + + public static final String DERIVATIVE_THUMBNAIL = "Thumbnail"; + public static final String DERIVATIVE_THUMBNAIL_TAG = DERIVATIVE_THUMBNAIL + + "_"; + + public static final String DERIVATIVE_UNKNOWN = "_UNKNOWN_DERIVATIVE_NAME_"; + + // + // Image Dimension fields + // + public static final String PART_IMAGE = "digitalImage"; + public static final String PART_SUMMARY = "The dimensions of a digital image -width, height, and pixel depth."; + public static final String WIDTH = "width"; + public static final String HEIGHT = "height"; + public static final String DEPTH = "depth"; + public static final String UNIT_PIXELS = "pixels"; + public static final String UNIT_BITS = "bits"; + // + // Image Metadata schemas - These are Nuxeo defined schemas + // + public static final String SCHEMA_IPTC = "iptc"; + public static final String SCHEMA_IMAGE_METADATA = "image_metadata"; + + private static final int THUMB_SIZE_HEIGHT = 100; + private static final int THUMB_SIZE_WIDTH = 75; + + // static DefaultBinaryManager binaryManager = new DefaultBinaryManager(); + // //can we get this from Nuxeo? i.e., + // Framework.getService(BinaryManger.class) + + // /** The temp file name. */ + // static String tempFileName = "sunset.jpg"; + // + // /** The file separator. */ + // static String fileSeparator = System.getProperty("file.separator"); + // + // /** The cur dir. */ + // static String curDir = System.getProperty("user.dir"); + + /** + * Instantiates a new nuxeo image utils. + */ + NuxeoBlobUtils() { + // empty constructor + } + + /* + * Use this for debugging Nuxeo's PictureView class + */ + private static String toStringPictureView(PictureView pictureView) { + StringBuffer strBuffer = new StringBuffer(); + strBuffer.append("Description: " + pictureView.getDescription() + '\n'); + strBuffer.append("FileName: " + pictureView.getFilename() + '\n'); + strBuffer.append("Height: " + pictureView.getHeight() + '\n'); + strBuffer.append("Width: " + pictureView.getWidth() + '\n'); + strBuffer.append("Tag: " + pictureView.getTag() + '\n'); + strBuffer.append("Title: " + pictureView.getTitle() + '\n'); + return strBuffer.toString(); + } + + // FIXME: REM - This needs to be configuration-bases and NOT hard coded! + // FIXME: REM - Use MultiviewPicture adapter to get some of this information + static private String getDerivativeUri(String uri, String derivativeName) { + String result = DERIVATIVE_UNKNOWN; + + if (derivativeName.startsWith(DERIVATIVE_ORIGINAL_TAG) == true) { + result = DERIVATIVE_ORIGINAL; + } else if (derivativeName.startsWith(DERIVATIVE_ORIGINAL_JPEG_TAG) == true) { + result = DERIVATIVE_ORIGINAL_JPEG; + } else if (derivativeName.startsWith(DERIVATIVE_MEDIUM_TAG) == true) { + result = DERIVATIVE_MEDIUM; + } else if (derivativeName.startsWith(DERIVATIVE_THUMBNAIL_TAG) == true) { + result = DERIVATIVE_THUMBNAIL; + } + + return uri + result + "/" + BlobInput.URI_CONTENT_PATH; + } + + static private HashMap createBlobListItem(Blob blob, + String uri) { + HashMap item = new HashMap(); + + String value = blob.getEncoding(); + if (value != null && !value.trim().isEmpty()) { + item.put(BlobJAXBSchema.encoding, value); + } + value = Long.toString(blob.getLength()); + if (value != null && !value.trim().isEmpty()) { + item.put(BlobJAXBSchema.length, value); + } + value = blob.getMimeType(); + if (value != null && !value.trim().isEmpty()) { + item.put(BlobJAXBSchema.mimeType, value); + } + value = blob.getFilename(); + if (value != null && !value.trim().isEmpty()) { + item.put(BlobJAXBSchema.name, value); + } + value = getDerivativeUri(uri, blob.getFilename()); + if (value != null && !value.trim().isEmpty()) { + item.put(BlobJAXBSchema.uri, value); + } + + return item; + } + + static public String getSanizitedFilename(File srcFile) throws Exception { + return getSanizitedFilename(srcFile.getName()); + } + + /* + * Valid Nuxeo file names are a subset of *nix and Windows filenames, so we need to check. + */ + static public String getSanizitedFilename(String fileName) throws Exception { + String result = fileName; + + if (fileName != null && fileName.matches(NUXEO_FILENAME_VALID_STRING) == false) { + String fixedString = fileName.replaceAll(NUXEO_FILENAME_BAD_CHARS, "_"); // Replace "bad" chars with underscore character + if (fixedString.matches(NUXEO_FILENAME_VALID_STRING) == true) { + result = fixedString; + } else { + String errMsg = String.format("\tSorry, the sanizited string '%s' is still bad.", fixedString); + throw new Exception(errMsg); + } + } + + if (result != null && logger.isDebugEnabled() == true) { + if (result.equals(fileName) == false) { + logger.debug(String.format("The file name '%s' was sanizitized to '%s'.", fileName, result)); + } + } + + return result; + } + + static public CommonList getBlobDerivatives(RepositoryInstanceInterface repoSession, + String repositoryId, List resultsFields, String uri) + throws Exception { + CommonList commonList = new CommonList(); + int nFields = resultsFields.size() + 2; + String fields[] = new String[nFields];// FIXME: REM - Patrick needs to fix this hack. It is a "common list" issue + fields[0] = "csid"; + fields[1] = "uri"; + for (int i = 2; i < nFields; i++) { + ListResultField field = resultsFields.get(i - 2); + fields[i] = field.getElement(); + } + commonList.setFieldsReturned(fields); + + IdRef documentRef = new IdRef(repositoryId); + DocumentModel documentModel = repoSession.getDocument(documentRef); + DocumentBlobHolder docBlobHolder = (DocumentBlobHolder) documentModel + .getAdapter(BlobHolder.class); + List docBlobs = docBlobHolder.getBlobs(); + // List blobListItems = result.getBlobListItem(); + HashMap item = null; + for (Blob blob : docBlobs) { + if (blob != null) { + item = createBlobListItem(blob, uri); + commonList.addItem(item); + } + } + + return commonList; + } + + /* + * [dublincore, uid, picture, iptc, common, image_metadata] + */ + static private Map getMetadata(Blob nuxeoBlob) + throws Exception { + ImagingService service = Framework.getService(ImagingService.class); + Map metadataMap = service.getImageMetadata(nuxeoBlob); + return metadataMap; + } + + private static String[] imageTypes = {"jpeg", "bmp", "gif", "png", "tiff", "octet-stream"}; + static private boolean isImageMedia(Blob nuxeoBlob) { + boolean result = false; + + String mimeType = nuxeoBlob.getMimeType(); + if (mimeType != null) { + mimeType = mimeType.toLowerCase().trim(); + String[] parts = mimeType.split("/"); // split strings like "application/xml" into an array of two strings + if (parts.length == 2) { + for (String type : imageTypes) { + if (parts[1].equalsIgnoreCase(type)) { + result = true; + break; + } + } + } + } + + return result; + } + + static private MeasuredPartGroupList getDimensions( + DocumentModel documentModel, Blob nuxeoBlob) { + MeasuredPartGroupList result = null; + + if (isImageMedia(nuxeoBlob) == true) try { + ImagingService service = Framework.getService(ImagingService.class); + ImageInfo imageInfo = service.getImageInfo(nuxeoBlob); + Map metadataMap = getMetadata(nuxeoBlob); + + if (imageInfo != null) { + // + // Create a timestamp to add to all the image's dimensions + // + String valueDate = GregorianCalendarDateTimeUtils + .timestampUTC(); + + result = new MeasuredPartGroupList(); + List measuredPartGroupList = + (result).getMeasuredPartGroup(); + // + // Create a new measured part for the "image" + // + MeasuredPartGroup mpGroup = new MeasuredPartGroup(); + mpGroup.setMeasuredPart(PART_IMAGE); + mpGroup.setDimensionSummary(PART_SUMMARY); + mpGroup.setDimensionSubGroupList(new DimensionSubGroupList()); + List dimensionSubGroupList = mpGroup.getDimensionSubGroupList() + .getDimensionSubGroup(); + + // + // Set the width + // + DimensionSubGroup widthDimension = new DimensionSubGroup(); + widthDimension.setDimension(WIDTH); + widthDimension.setMeasurementUnit(UNIT_PIXELS); + widthDimension.setValue(intToBigDecimal(imageInfo.getWidth())); + widthDimension.setValueDate(valueDate); + dimensionSubGroupList.add(widthDimension); + // + // Set the height + // + DimensionSubGroup heightDimension = new DimensionSubGroup(); + heightDimension.setDimension(HEIGHT); + heightDimension.setMeasurementUnit(UNIT_PIXELS); + heightDimension + .setValue(intToBigDecimal(imageInfo.getHeight())); + heightDimension.setValueDate(valueDate); + dimensionSubGroupList.add(heightDimension); + // + // Set the depth + // + DimensionSubGroup depthDimension = new DimensionSubGroup(); + depthDimension.setDimension(DEPTH); + depthDimension.setMeasurementUnit(UNIT_BITS); + depthDimension.setValue(intToBigDecimal(imageInfo.getDepth())); + depthDimension.setValueDate(valueDate); + dimensionSubGroupList.add(depthDimension); + // + // Now set out result + // + measuredPartGroupList.add(mpGroup); + } else { + if (logger.isWarnEnabled() == true) { + logger.warn("Could not synthesize a dimension list of the blob: " + + documentModel.getName()); + } + } + } catch (Exception e) { + logger.warn("Could not extract image information for blob: " + + documentModel.getName(), e); + } + + return result; + } + + // FIXME: Add error checking here, as none of these calls return an + // Exception + static private BigDecimal intToBigDecimal(int i) { + BigInteger bigint = BigInteger.valueOf(i); + BigDecimal bigdec = new BigDecimal(bigint); + return bigdec; + } + + static private BlobsCommon createBlobsCommon(DocumentModel documentModel, + Blob nuxeoBlob) { + return createBlobsCommon(documentModel, nuxeoBlob, false); + } + + static private BlobsCommon createBlobsCommon(DocumentModel documentModel, + Blob nuxeoBlob, Boolean getContentFlag) { + BlobsCommon result = new BlobsCommon(); + + if (documentModel != null) { + result.setMimeType(nuxeoBlob.getMimeType()); + result.setName(nuxeoBlob.getFilename()); + result.setLength(Long.toString(nuxeoBlob.getLength())); + result.setRepositoryId(documentModel.getId()); + + // + // If getContentFlag is true then we're being asked for the blob's content, so we don't + // need the measurement info. Getting the measurement info requires a call to Nuxeo which in turn + // calls ImageMagick. + // + if (getContentFlag.booleanValue() == false) { + MeasuredPartGroupList measuredPartGroupList = getDimensions( + documentModel, nuxeoBlob); + if (measuredPartGroupList != null) { + result.setMeasuredPartGroupList(measuredPartGroupList); + } + } + + // Check to see if a thumbnail preview was created by Nuxeo + if (documentModel.hasFacet(ThumbnailConstants.THUMBNAIL_FACET)) { + String errorMsg = null; + String thumbnailName = null; + try { + thumbnailName = (String)documentModel.getProperty(ThumbnailConstants.THUMBNAIL_SCHEMA_NAME, + ThumbnailConstants.THUMBNAIL_FILENAME_PROPERTY_NAME); + Blob thumbnailBlob = (Blob)documentModel.getProperty(ThumbnailConstants.THUMBNAIL_SCHEMA_NAME, + ThumbnailConstants.THUMBNAIL_PROPERTY_NAME); + } catch (ClientException e) { + errorMsg = "Could not extract the name of the thumbnail preview image file."; + if (logger.isTraceEnabled()) { + logger.trace(errorMsg, e); + } + } + + if (errorMsg == null) { + logger.info("A thumbnail preview was created for this document blob: " + thumbnailName); + } else { + logger.warn(errorMsg); + } + } + } + + return result; + } + + /* + * This is a prototype method that is not currently used as of 1/1/2012. However, + * it may be useful now that we've transitioned to using an embedded Nuxeo server. + */ + static private File getBlobFile(RepositoryInstanceInterface ri, + DocumentModel documentModel, Blob blob) { + DefaultBinaryManager binaryManager = null; + RepositoryDescriptor descriptor = null; + File file = null; + + try { + RepositoryService repositoryService1 = (RepositoryService) Framework + .getRuntime().getComponent(RepositoryService.NAME); + + String repositoryName = documentModel.getRepositoryName(); + RepositoryManager repositoryManager = repositoryService1 + .getRepositoryManager(); + descriptor = repositoryManager.getDescriptor(repositoryName); + +// Keep this code around for future work/enhancements +// binaryManager = new DefaultBinaryManager(); +// +// File storageDir = binaryManager.getStorageDir(); +// // SQLBlob blob = (SQLBlob) +// // doc.getPropertyValue("schema:blobField"); +// File file = binaryManager.getFileForDigest(blob.getDigest(), false); + + } catch (Exception e) { + e.printStackTrace(); + } + +// Keep this code around for future work/enhancements +// try { +// binaryManager.initialize(SQLRepository.getDescriptor(descriptor)); +// } catch (IOException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } catch (Exception e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } + +// Keep this code around for future work/enhancements +// File storageDir = binaryManager.getStorageDir(); +// SQLBlob blob = (SQLBlob) +// documentModel.getPropertyValue("schema:blobField"); +// File file = binaryManager.getFileForDigest(blob.getDigest(), false); + + return file; + } + + /** + * Returns a schema, given the name of a schema. Possibly usefule in the future + * + * @param schemaName + * a schema name. + * @return a schema. + */ + private static Schema getSchemaFromName(String schemaName) { + SchemaManager schemaManager = null; + try { + schemaManager = Framework.getService(SchemaManager.class); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return schemaManager != null ? schemaManager.getSchema(schemaName) + : null; + } + + /** + * Gets the blob. Not in use now, but might be useful in the future. + * + * @param nuxeoSession + * the nuxeo session + * @param id + * the id + * @return the blob + */ + static private Blob getBlob(RepositoryInstanceInterface repoSession, String id) { + Blob result = null; + + try { + Repository repository = repoSession.getRepositoryInstance().getRepository(); + // binaryManager.initialize(new RepositoryDescriptor()); + // binaryManager.getBinary("a4cac052ae0281979f2dcf5ab2e61a6c"); + // DocumentResolver.resolveReference(nuxeoSession, documentRef); + // binaryManager = repository.getBinaryManager(); + // documentModel.getr + } catch (Exception x) { + x.printStackTrace(); + } + + return result; + } + + static private Blob checkMimeType(Blob blob, String fullname) + throws ClientException { + final String mimeType = blob.getMimeType(); + if (mimeType != null && !mimeType.equals("application/octet-stream") + && !mimeType.equals("application/octetstream")) { + return blob; + } + String filename = FileManagerUtils.fetchFileName(fullname); + try { + blob = getMimeService().updateMimetype(blob, filename); + } catch (MimetypeDetectionException e) { + throw new ClientException(e); + } + return blob; + } + + /** + * Gets the type service. Not in use, but please keep for future reference + * + * @return the type service + * @throws ClientException + * the client exception + */ + private static TypeManager getTypeService() throws ClientException { + TypeManager typeService = null; + + try { + typeService = Framework.getService(TypeManager.class); + } catch (Exception e) { + throw new ClientException(e); + } + + return typeService; + } + + /** + * Gets the bytes. + * + * @param fis + * the fis + * @return the bytes + */ + private static byte[] getBytes(InputStream fis) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + byte[] buf = new byte[128 * 1024]; + try { + for (int readNum; (readNum = fis.read(buf)) != -1;) { + bos.write(buf, 0, readNum); + // no doubt here is 0 + /* + * Writes len bytes from the specified byte array starting at + * offset off to this byte array output stream. + */ + System.out.println("read " + readNum + " bytes,"); + } + } catch (IOException ex) { + logger.error(ex.getMessage(), ex); + } + byte[] bytes = bos.toByteArray(); + // bytes is the ByteArray we need + return bytes; + } + + /** + * Creates the serializable blob. We may need this code, do not remove. + * + * @param fileInputStream + * the file input stream + * @param filename + * the filename + * @param mimeType + * the mime type + * @return the blob + */ + private static Blob createSerializableBlob(InputStream fileInputStream, + String filename, String mimeType) { + Blob blob = null; + try { + // persisting the blob makes it possible to read the binary content + // of the request stream several times (mimetype sniffing, digest + // computation, core binary storage) + byte[] bytes = getBytes(fileInputStream); + blob = new ByteArrayBlob(bytes); + // filename + if (filename != null) { + filename = getCleanFileName(filename); + } + blob.setFilename(filename); + // mimetype detection + MimetypeRegistry mimeService = Framework + .getService(MimetypeRegistry.class); + String detectedMimeType = mimeService + .getMimetypeFromFilenameAndBlobWithDefault(filename, blob, + null); + if (detectedMimeType == null) { + if (mimeType != null) { + detectedMimeType = mimeType; + } else { + // default + detectedMimeType = "application/octet-stream"; + } + } + blob.setMimeType(detectedMimeType); + } catch (MimetypeDetectionException e) { + logger.error(String.format("could not fetch mimetype for file %s", + filename), e); + } catch (Exception e) { + logger.error("", e); + } + return blob; + } + + /** + * Creates a serializable blob from a stream, with filename and mimetype + * detection. + * + *

+ * Creates an in-memory blob if data is under 64K, otherwise constructs a + * serializable FileBlob which stores data in a temporary file on the hard + * disk. + *

+ * + * @param file + * the input stream holding data + * @param filename + * the file name. Will be set on the blob and will used for + * mimetype detection. + * @param mimeType + * the detected mimetype at upload. Can be null. Will be verified + * by the mimetype service. + * @return the blob + */ + private static Blob createStreamingBlob(File file, String filename, + String mimeType) { + Blob blob = null; + try { + // persisting the blob makes it possible to read the binary content + // of the request stream several times (mimetype sniffing, digest + // computation, core binary storage) + blob = StreamingBlob.createFromFile(file, mimeType).persist(); + // filename + if (filename != null) { + filename = getCleanFileName(filename); + } + blob.setFilename(filename); + // mimetype detection + MimetypeRegistry mimeService = Framework + .getService(MimetypeRegistry.class); + String detectedMimeType = mimeService + .getMimetypeFromFilenameAndBlobWithDefault(filename, blob, + null); + if (detectedMimeType == null) { + if (mimeType != null) { + detectedMimeType = mimeType; + } else { + // default + detectedMimeType = "application/octet-stream"; + } + } + blob.setMimeType(detectedMimeType); + } catch (MimetypeDetectionException e) { + logger.error(String.format("could not fetch mimetype for file %s", + filename), e); + } catch (IOException e) { + logger.error("", e); + } catch (Exception e) { + logger.error("", e); + } + return blob; + } + + private static Blob createNuxeoFileBasedBlob(File file) throws Exception { + return new FileBlob(file); + } + + /** + * Returns a clean filename, stripping upload path on client side. + *

+ * Fixes NXP-544 + *

+ * + * @param filename + * the filename + * @return the clean file name + */ + private static String getCleanFileName(String filename) { + String res = null; + int lastWinSeparator = filename.lastIndexOf('\\'); + int lastUnixSeparator = filename.lastIndexOf('/'); + int lastSeparator = Math.max(lastWinSeparator, lastUnixSeparator); + if (lastSeparator != -1) { + res = filename.substring(lastSeparator + 1, filename.length()); + } else { + res = filename; + } + return res; + } + + /** + * Gets Nuxeo's file manager service. + * + * @return the file manager service + * @throws ClientException + * the client exception + */ + private static FileManager getFileManager() throws ClientException { + FileManager result = null; + + try { + result = Framework.getService(FileManager.class); + } catch (Exception e) { + String msg = "Unable to get Nuxeo's FileManager service."; + logger.error(msg, e); + throw new ClientException("msg", e); + } + + return result; + } + + /** + * Gets Nuxeo's file manager service. + * + * @return the file manager service + * @throws ClientException + * the client exception + */ + private static FileManagerService getFileManagerService() throws ClientException { + FileManagerService result = null; + + try { + result = (FileManagerService)getFileManager(); + } catch (Exception e) { + String msg = "Unable to get Nuxeo's FileManager service."; + logger.error(msg, e); + throw new ClientException("msg", e); + } + + return result; + } + + /** + * Gets Nuxeo's file manager service. + * + * @return the file manager service + * @throws ClientException + * the client exception + */ + private static FileManager getFileManagerServicex() throws ClientException { + FileManager result = null; + try { + result = Framework.getService(FileManager.class); + } catch (Exception e) { + String msg = "Unable to get Nuxeo's FileManager service."; + logger.error(msg, e); + throw new ClientException("msg", e); + } + return result; + } + + private static EventServiceAdmin getEventServiceAdmin() throws ClientException { + EventServiceAdmin result = null; + try { + result = Framework.getService(EventServiceAdmin.class); + } catch (Exception e) { + String msg = "Unable to get Nuxeo's EventServiceAdmin service."; + logger.error(msg, e); + throw new ClientException("msg", e); + } + return result; + } + + private static BinaryManager getBinaryManagerService() throws ClientException { + BinaryManager result = null; + try { + result = Framework.getService(BinaryManager.class); + } catch (Exception e) { + String msg = "Unable to get Nuxeo's BinaryManager service."; + logger.error(msg, e); + throw new ClientException("msg", e); + } + return result; + } + + static private RepositoryInstanceInterface getRepositorySession(ServiceContext ctx, RepositoryClient repositoryClient) { + RepositoryInstanceInterface result = null; + RepositoryJavaClientImpl nuxeoClient = (RepositoryJavaClientImpl)repositoryClient; + + try { + result = nuxeoClient.getRepositorySession(ctx); + } catch (Exception e) { + logger.error("Could not get a repository session to the Nuxeo repository", e); + } + + return result; + } + + static private void releaseRepositorySession(ServiceContext ctx, RepositoryClient repositoryClient, RepositoryInstanceInterface repoSession) throws TransactionException { + RepositoryJavaClientImpl nuxeoClient = (RepositoryJavaClientImpl)repositoryClient; + nuxeoClient.releaseRepositorySession(ctx, repoSession); + } + + static private MimetypeRegistry getMimeService() throws ClientException { + MimetypeRegistry result = null; + + try { + result = Framework.getService(MimetypeRegistry.class); + } catch (Exception e) { + throw new ClientException(e); + } + + return result; + } + + private static DocumentModel createDocumentFromBlob( + RepositoryInstanceInterface repoSession, + Blob inputStreamBlob, + String blobLocation, + boolean overwrite, + String blobName, + boolean useNuxeoAdaptors) throws Exception { + DocumentModel result = null; + + if (useNuxeoAdaptors == true) { + // + // Use Nuxeo's high-level create method which looks for plugin adapters that match the MIME type. For example, + // for image blobs, Nuxeo's file manager will pick a special image plugin that will automatically generate + // image derivatives. + // + result = getFileManager().createDocumentFromBlob( + repoSession.getRepositoryInstance(), inputStreamBlob, blobLocation, true, blobName); + } else { + // + // User Nuxeo's default file importer/adapter explicitly. This avoids specialized functionality from happening like + // image derivative creation. + // + String digestAlgorithm = getFileManager() + .getDigestAlgorithm(); // Only call this because we seem to need some way of initializing Nuxeo's FileManager with a call. + + FileManagerService fileManagerService = getFileManagerService(); + inputStreamBlob = checkMimeType(inputStreamBlob, blobName); + + FileImporter defaultFileImporter = fileManagerService.getPluginByName("DefaultFileImporter"); + result = defaultFileImporter.create( + repoSession.getRepositoryInstance(), inputStreamBlob, blobLocation, true, blobName, getTypeService()); + } + + return result; + } + + static public BlobsCommon createBlobInRepository( + ServiceContext ctx, + RepositoryClient repositoryClient, + InputStream inputStream, + String blobName, + boolean useNuxeoAdaptors) throws TransactionException { + BlobsCommon result = null; + + boolean repoSessionCleanup = false; + RepositoryInstanceInterface repoSession = (RepositoryInstanceInterface)ctx.getCurrentRepositorySession(); + if (repoSession == null) { + repoSession = getRepositorySession(ctx, repositoryClient); + repoSessionCleanup = true; + } + + try { + // We'll store the blob inside the workspace directory of the calling service + String nuxeoWspaceId = ctx.getRepositoryWorkspaceId(); + DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId); + DocumentModel blobLocation = repoSession.getDocument(nuxeoWspace); + + Blob inputStreamBlob = new InputStreamBlob(inputStream); + DocumentModel documentModel = createDocumentFromBlob( + repoSession, + inputStreamBlob, + blobLocation.getPathAsString(), + true, + blobName, + useNuxeoAdaptors); + result = createBlobsCommon(documentModel, inputStreamBlob); // Now create the metadata about the Nuxeo blob document + } catch (Exception e) { + result = null; + logger.error("Could not create new Nuxeo blob document.", e); //FIXME: REM - This should probably be re-throwing the exception? + } finally { + if (repoSessionCleanup == true) { + releaseRepositorySession(ctx, repositoryClient, repoSession); + } + } + + return result; + } + + /** + * Creates the picture. + * + * @param ctx + * the ctx + * @param repoSession + * the repo session + * @param filePath + * the file path + * @return the string + * @throws Exception + */ + public static BlobsCommon createBlobInRepository( + ServiceContext ctx, + RepositoryInstanceInterface repoSession, + BlobInput blobInput, + boolean purgeOriginal, + boolean useNuxeoAdaptors) throws Exception { + BlobsCommon result = null; + + File originalFile = blobInput.getBlobFile(); + File targetFile = originalFile; + try { + // We'll store the blob inside the workspace directory of the calling service + String nuxeoWspaceId = ctx.getRepositoryWorkspaceId(); + DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId); + DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace); + // + // If the original file's name contains "illegal" characters, then we create a copy of the file to give Nuxeo. + // + String sanitizedName = NuxeoBlobUtils.getSanizitedFilename(originalFile); + if (sanitizedName.equals(originalFile.getName()) == false) { + targetFile = FileUtils.createTmpFile(originalFile, sanitizedName); + if (logger.isDebugEnabled() == true) { + logger.debug(String.format("The file '%s''s name has characters that Nuxeo can't deal with. Rather than renaming the file, we created a new temp file at '%s'", + originalFile.getName(), targetFile.getAbsolutePath())); + } + } + + result = createBlobInRepository(repoSession, + wspaceDoc, + purgeOriginal, + targetFile, + null, // MIME type + useNuxeoAdaptors); + // + // Make sure we're using the original file name in our BlobsCommon instance. If the original file's name + // contained illegal characters, then we created and handed a copy of the file to Nuxeo. We don't want the + // copy's file name stored in the BlobsCommon instance, we want the original file name instead. + // + if (targetFile.equals(originalFile) == false) { + result.setName(originalFile.getName()); + } + + } catch (Exception e) { + logger.error("Could not create image blob.", e); + throw e; + } finally { + // + // If we created a temp file then we should delete it. + // + if (targetFile.equals(originalFile) == false) { + if (targetFile.delete() == false) { + logger.warn(String.format("Attempt to delete temporary file '%s' failed.", targetFile.getAbsolutePath())); + } + } + } + + return result; + } + + /* + * Find out if this document's blob/file-contents are allowed to be purged. For instance, we currently + * only want to allow the purging the contents of Nuxeo "Picture" documents. + */ + static private boolean isPurgeAllowed(DocumentModel docModel) { + boolean result = false; + + if (docModel.hasFacet(ImagingDocumentConstants.PICTURE_FACET) == true) { + result = true; // Yes, delete/purge the original content + } + + return result; + } + + /** + * Creates the image blob. + * + * @param nuxeoSession + * the nuxeo session + * @param blobLocation + * the blob location + * @param file + * the file + * @param fileName + * the file name + * @param mimeType + * the mime type + * @return the string + */ + static private BlobsCommon createBlobInRepository(RepositoryInstanceInterface nuxeoSession, + DocumentModel blobLocation, + boolean purgeOriginal, + File file, + String mimeType, + boolean useNuxeoAdaptors) { + BlobsCommon result = null; + + try { + Blob fileBlob = createNuxeoFileBasedBlob(file); + + DocumentModel documentModel = createDocumentFromBlob( + nuxeoSession, fileBlob, + blobLocation.getPathAsString(), + true, + file.getName(), + useNuxeoAdaptors); + + result = createBlobsCommon(documentModel, fileBlob); // Now create our metadata resource document + + // If the sender wanted us to generate only derivatives, we need to purge/clear the original contents + if (purgeOriginal == true && isPurgeAllowed(documentModel) == true) { + // Empty the document model's "content" property -this does not delete the actual file/blob + documentModel.setPropertyValue("file:content", (Serializable) null); + + if (documentModel.hasFacet(ImagingDocumentConstants.PICTURE_FACET)) { + // Now with no content, the derivative listener wants to update the derivatives. So to + // prevent the listener, we remove the "Picture" facet from the document + NuxeoUtils.removeFacet(documentModel, ImagingDocumentConstants.PICTURE_FACET); // Removing this facet ensures the original derivatives are unchanged. + nuxeoSession.saveDocument(documentModel); + // Now that we've emptied the document model's content field, we can add back the Picture facet + NuxeoUtils.addFacet(documentModel, ImagingDocumentConstants.PICTURE_FACET); + } + + nuxeoSession.saveDocument(documentModel); + // Next, we need to remove the actual file from Nuxeo's data directory + DocumentBlobHolder docBlobHolder = (DocumentBlobHolder) documentModel + .getAdapter(BlobHolder.class); + Blob blob = docBlobHolder.getBlob(); + if(blob == null) { + logger.error("Could not get blob for original image. Trying to delete original for: {}", + file.getName()); + } else { + boolean deleteSuccess = NuxeoUtils.deleteFileOfBlob(docBlobHolder.getBlob()); + } + } + } catch (Exception e) { + result = null; + logger.error("Could not create new Nuxeo blob document.", e); //FIXME: REM - This should probably be re-throwing the exception? + } + + return result; + } + + // /* + // * This is an alternate approach to getting information about an image + // * and its corresponding derivatives. + // */ + // // MultiviewPictureAdapter multiviewPictureAdapter = + // documentModel.getAdapter(MultiviewPictureAdapter.class); + // MultiviewPictureAdapterFactory multiviewPictureAdapterFactory = new + // MultiviewPictureAdapterFactory(); + // MultiviewPictureAdapter multiviewPictureAdapter = + // (MultiviewPictureAdapter)multiviewPictureAdapterFactory.getAdapter(documentModel, + // null); + // if (multiviewPictureAdapter != null) { + // PictureView[] pictureViewArray = multiviewPictureAdapter.getViews(); + // for (PictureView pictureView : pictureViewArray) { + // if (logger.isDebugEnabled() == true) { + // logger.debug("-------------------------------------"); + // logger.debug(toStringPictureView(pictureView)); + // } + // } + // } + + public static InputStream getResource(String resourceName) { + InputStream result = null; + + try { + result = ServiceMain.getInstance().getResourceAsStream(resourceName); + } catch (FileNotFoundException e) { + logger.error("Missing Services resource: " + resourceName, e); + } + + return result; + } + + static public BlobOutput getBlobOutput(ServiceContext ctx, + RepositoryClient repositoryClient, + String repositoryId, + StringBuffer outMimeType) throws TransactionException { + BlobOutput result = null; + + boolean repoSessionCleanup = false; + RepositoryInstanceInterface repoSession = (RepositoryInstanceInterface)ctx.getCurrentRepositorySession(); + if (repoSession == null) { + repoSession = getRepositorySession(ctx, repositoryClient); + repoSessionCleanup = true; + } + + try { + result = getBlobOutput(ctx, repoSession, repositoryId, null, true, outMimeType); + if (outMimeType.length() == 0) { + BlobsCommon blobsCommon = result.getBlobsCommon(); + String mimeType = blobsCommon.getMimeType(); + outMimeType.append(mimeType); + } + } finally { + if (repoSessionCleanup == true) { + releaseRepositorySession(ctx, repositoryClient, repoSession); + } + } + + return result; + } + + // + // If the blob is not too big, we return a ByteArrayInputStream. Otherwise, we return Nuxeo's InputStream + // which is usually a FileInputStream. + // + static private InputStream getInputStream(BlobsCommon blobsCommon, Blob blob) { + InputStream result = null; + + try { + InputStream blobStream = blob.getStream(); // By default, the result will be whatever stream Nuxeo returns to us. + int blobSize = blobsCommon.getLength() != null ? Integer.parseInt(blobsCommon.getLength()) : 0; + if (blobSize > 0 && blobSize < MAX_IMAGE_BUFFER) { + byte[] bytes = IOUtils.toByteArray(blobStream); + blobStream.close(); // Close the InputStream that we got from Nuxeo since it's usually a FileInputStream -we definitely want FileInputStreams closed. + result = new ByteArrayInputStream(bytes); + } else { + result = blobStream; // The blob is too large to put into a ByteArrayStream. + } + } catch (Exception e) { + logger.error(String.format("Error getting the InputStream content for file %s.", blobsCommon.getName()), e); + if (result != null) { + try { + result.close(); + result = null; + } catch (Exception x) { + logger.debug(String.format("Exception encountered during InputStream cleanup of file %s", blobsCommon.getName()), x); + } + } + } + + return result; + } + + /** + * Gets the image. + * + * @param repoSession + * the repo session + * @param repositoryId + * the repository id + * @param derivativeTerm + * the derivative term + * @return the image + */ + static public BlobOutput getBlobOutput(ServiceContext ctx, + RepositoryInstanceInterface repoSession, + String repositoryId, + String derivativeTerm, + Boolean getContentFlag, + StringBuffer outMimeType) { + BlobOutput result = new BlobOutput(); + boolean isNonImageDerivative = false; + + if (repositoryId != null && repositoryId.isEmpty() == false) + try { + IdRef documentRef = new IdRef(repositoryId); + DocumentModel documentModel = repoSession.getDocument(documentRef); + + Blob docBlob = null; + DocumentBlobHolder docBlobHolder = (DocumentBlobHolder) documentModel + .getAdapter(BlobHolder.class); + if (docBlobHolder instanceof PictureBlobHolder) { + // if it is a PictureDocument then it has these + // Nuxeo schemas: [dublincore, uid, picture, iptc, common, image_metadata] + // + // Need to add the "MultiviewPictureAdapter" support here to + // get the view data, see above. + // + PictureBlobHolder pictureBlobHolder = (PictureBlobHolder) docBlobHolder; + if (derivativeTerm != null) { + docBlob = pictureBlobHolder.getBlob(derivativeTerm); + // Nuxeo derivatives are all JPEG + outMimeType.append(MIME_JPEG); // All Nuxeo image derivatives are JPEG images. + } else { + docBlob = pictureBlobHolder.getBlob(); + } + } else { + docBlob = docBlobHolder.getBlob(); + if (derivativeTerm != null) { // If its a derivative request on a non-image blob, then return just a document image thumnail + isNonImageDerivative = true; + } + } + + // + // Create the result instance that will contain the blob metadata + // and an InputStream with the bits if the 'getContentFlag' is + // set. + // + BlobsCommon blobsCommon = createBlobsCommon(documentModel, docBlob, getContentFlag); + result.setBlobsCommon(blobsCommon); + if (getContentFlag == true) { + InputStream remoteStream = null; + if (isNonImageDerivative == false) { + //remoteStream = docBlob.getStream(); + remoteStream = getInputStream(blobsCommon, docBlob); // CSPACE-6110 - For small files, return a byte array instead of a file stream + } else { + remoteStream = getResource(DOCUMENT_PLACEHOLDER_IMAGE); + outMimeType.append(MIME_JPEG); + } +// BufferedInputStream bufferedInputStream = new BufferedInputStream( +// remoteStream); +// result.setBlobInputStream(bufferedInputStream); + result.setBlobInputStream(remoteStream); + } + } catch (Exception e) { + if (logger.isErrorEnabled() == true) { + logger.error(e.getMessage(), e); + } + result = null; + } + + return result; + } + +} + +/* + * Notes and code snippets about Nuxeo's support for binaries and image + * documents. + */ + +/* + * + * + * MultiviewPictureAdapter org.nuxeo.ecm.platform.picture.api.adapters + * PictureResourceAdapter pictureResourceAdapter = (PictureResourceAdapter) + * documentModel.getAdapter(PictureResourceAdapter.class); String thumbnailPath + * = pictureResourceAdapter.getViewXPath("Thumbnail"); + * + * Map blobHolderProps = docBlobHolder.getProperties(); + * String filePath = docBlobHolder.getFilePath(); List docBlobs = + * docBlobHolder.getBlobs(); + * + * stream = new FileInputStream(fileUploadHolder.getTempFile()); + * + * public String addFile(InputStream fileUpload, String fileName) fileName = + * FileUtils.getCleanFileName(fileName); DocumentModel currentDocument = + * navigationContext.getCurrentDocument(); String path = + * currentDocument.getPathAsString(); Blob blob = + * FileUtils.createSerializableBlob(fileUpload, fileName, null); + * + * DocumentModel createdDoc = getFileManagerService().createDocumentFromBlob( + * documentManager, blob, path, true, fileName); + * eventManager.raiseEventsOnDocumentSelected(createdDoc); + * + * protected FileManager fileManager; + * + * protected FileManager getFileManagerService() throws ClientException { if + * (fileManager == null) { try { fileManager = + * Framework.getService(FileManager.class); } catch (Exception e) { + * log.error("Unable to get FileManager service ", e); throw new + * ClientException("Unable to get FileManager service ", e); } } return + * fileManager; } + */ + +/* + * RepositoryService repositoryService = (RepositoryService) + * Framework.getRuntime().getComponent( RepositoryService.NAME); + * RepositoryManager repositoryManager = + * repositoryService.getRepositoryManager(); RepositoryDescriptor descriptor = + * repositoryManager.getDescriptor(repositoryName); DefaultBinaryManager + * binaryManager = new DefaultBinaryManager( + * SQLRepository.getDescriptor(descriptor))); + * + * File storageDir = binaryManager.getStorageDir(); SQLBlob blob = (SQLBlob) + * doc.getPropertyValue("schema:blobField"); File file = + * binaryManager.getFileForDigest( blob.getBinary().getDigest(), false); + */ + +/* + * RepositoryInstance.getStreamURI() + * + * String getStreamURI(String blobPropertyId) throws ClientException + * + * Returns an URI identifying the stream given the blob property id. This method + * should be used by a client to download the data of a blob property. + * + * The blob is fetched from the repository and the blob stream is registered + * against the streaming service so the stream will be available remotely + * through stream service API. + * + * After the client has called this method, it will be able to download the + * stream using streaming server API. + * + * Returns: an URI identifying the remote stream Throws: ClientException + */ + +/* + * A blob contains usually large data. + * + * Document fields holding Blob data are by default fetched in a lazy manner. + * + * A Blob object hides the data source and it also describes data properties + * like the encoding or mime-type. + * + * The encoding is used to decode Unicode text content that was stored in an + * encoded form. If not encoding is specified, the default java encoding is + * used. The encoding is ignored for binary content. + * + * When retrieving the content from a document, it will be returned as source + * content instead of returning the content bytes. + * + * The same is true when setting the content for a document: you set a content + * source and not directly the content bytes. Ex: + * + * File file = new File("/tmp/index.html"); FileBlob fb = new FileBlob(file); + * fb.setMimeType("text/html"); fb.setEncoding("UTF-8"); // this specifies that + * content bytes will be stored as UTF-8 document.setProperty("file", "content", + * fb); + * + * + * Then you may want to retrieve the content as follow: + * + * Blob blob = document.getProperty("file:content"); htmlDoc = blob.getString(); + * // the content is decoded from UTF-8 into a java string + */ diff --git a/services/common/src/main/java/org/collectionspace/services/common/init/AddIndices.java b/services/common/src/main/java/org/collectionspace/services/common/init/AddIndices.java index 376d59bfc..2f18d305b 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/init/AddIndices.java +++ b/services/common/src/main/java/org/collectionspace/services/common/init/AddIndices.java @@ -1,246 +1,246 @@ -/** - * 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 - */ -package org.collectionspace.services.common.init; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -import javax.sql.DataSource; - -import org.collectionspace.services.common.api.Tools; -import org.collectionspace.services.common.storage.DatabaseProductType; -import org.collectionspace.services.common.storage.JDBCTools; -import org.collectionspace.services.config.service.InitHandler.Params.Field; -import org.collectionspace.services.config.service.InitHandler.Params.Property; -import org.collectionspace.services.config.service.ServiceBindingType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * AddIndices, post-init action to add indexes to the database. - * - * In the configuration file, you may have sets of table names and column names, or you may use params to send a - * comma-separated list of column names and a table name. That is, both of these are equivalent: - * - * The single column per element version: - * - * - * <s:initHandler xmlns:s='http://collectionspace.org/services/common/service'> - <s:classname>org.collectionspace.services.common.init.AddIndices</s:classname> - <s:params> - <s:field> - <s:table>nuxeo.organizations_common</s:table> - <s:col>inAuthority</s:col> - </s:field> - <s:field> - <s:table>nuxeo.organizations_common</s:table> - <s:col>displayName</s:col> - </s:field> - <s:field> - <s:table>nuxeo.organizations_common</s:table> - <s:col>shortIdentifier</s:col> - </s:field> - </s:params> - </s:initHandler> - - The csv version: - - <s:initHandler xmlns:s='http://collectionspace.org/services/common/service'> - <s:classname>org.collectionspace.services.common.init.AddIndices</s:classname> - <s:params> - <s:field> - <s:table>nuxeo.organizations_common</s:table> - <s:param>inAuthority,displayName,shortIdentifier</s:param> - </s:field> - </s:params> - </s:initHandler> - * - * $LastChangedRevision$ - * $LastChangedDate$ - */ -public class AddIndices extends InitHandler implements IInitHandler { - - final Logger logger = LoggerFactory.getLogger(AddIndices.class); - private final static String INDEX_SEP = "_"; - private final static String INDEX_SUFFIX = INDEX_SEP + "idx"; - - - /** See the class javadoc for this class: it shows the syntax supported in the configuration params. - */ - @Override - public void onRepositoryInitialized(String dataSourceName, - String repositoryName, - String cspaceInstanceId, - ServiceBindingType sbt, - List fields, - List properties) throws Exception { - //todo: all post-init tasks for services, or delegate to services that override. - int rows = 0; - String sql = ""; - if (logger.isInfoEnabled() && sbt != null) { - logger.info("Creating indicies, as needed, for designated fields in " + sbt.getName() - + " for repository domain " + sbt.getRepositoryDomain().trim() + "..."); - } - - for (Field field : fields) { - String tableName = field.getTable(); - String fieldName = field.getCol(); - String param = field.getParam(); - if(Tools.notEmpty(param) && (param.indexOf(',')>-1)){ - String[] fieldNames = param.split(","); - for (String fn: fieldNames){ - rows = addOneIndex(dataSourceName, repositoryName, cspaceInstanceId, tableName, fn); - } - } else { - rows = addOneIndex(dataSourceName, repositoryName, cspaceInstanceId, tableName, fieldName); - } - } - } - - private int addOneIndex(String dataSourceName, - String repositoryName, - String cspaceInstanceId, - String tableName, - String columnName) { - int rows = 0; - String sql = ""; - String indexName = tableName + INDEX_SEP + columnName + INDEX_SUFFIX; - try { - DatabaseProductType databaseProductType = JDBCTools.getDatabaseProductType(dataSourceName, repositoryName); - if (indexExists(dataSourceName, repositoryName, cspaceInstanceId, databaseProductType, - tableName, columnName, indexName)) { - logger.trace("Index already exists for column " + columnName - + " in table " + tableName); - // FIXME: Can add the option to drop and re-create an index here. - // For example, see MySQL documentation on DROP INDEX. - return 0; - } - // TODO: Consider refactoring this 'if' statement to a general-purpose - // mechanism for retrieving and populating catalog/DDL-type SQL statements - // appropriate to a particular database product. - logger.info("Creating index for column " + columnName + " in table " + tableName); - if (databaseProductType == DatabaseProductType.MYSQL - || databaseProductType == DatabaseProductType.POSTGRESQL) { - sql = "CREATE INDEX " + indexName + " ON " - + tableName + " (" + columnName + ")"; - } else { - throw new Exception("Unrecognized database system " + databaseProductType); - } - if (sql != null && ! sql.trim().isEmpty()) { - // Assumes indicies will only be created at post-init time - // for the Nuxeo repository. - // - // To date, for the CSpace repository, indices have typically been - // created during the build process, via manual or generated - // DDL SQL scripts. - // - // If this assumption is no longer valid, we might instead - // identify the relevant repository from the table name here. - rows = JDBCTools.executeUpdate(dataSourceName, repositoryName, cspaceInstanceId, sql); - logger.trace("Index added to column ("+columnName+") on table ("+tableName+")"); - } - return rows; - } catch (Throwable e) { - logger.debug("Index NOT added to column ("+columnName+") on table ("+tableName+") SQL: "+sql+" ERROR: "+e); - return -1; - } - } - - private boolean indexExists(String dataSourceName, - String repositoryName, - String cspaceInstanceId, - DatabaseProductType databaseProductType, - String tableName, - String colName, - String indexName) { - - // FIXME: May need to qualify table name by database/catalog, - // as table names likely will not be globally unique across same - // (although index names *may* be unique within scope). - // - // If we do need to do this, we might: - // - Pass in the database name as a parameter to this method, retrieved - // via getDatabaseName(field) in onRepositoryInitialized, above. - // - Add 'IN databaseName' after tableName in MySQL variant, below. - // (PostgreSQL variant, below, uses a view that doesn't include - // a foreign key for associating a database/catalog to the index.) - - // FIXME: Consider instead substituting a database-agnostic - // JDBC mechanism for retrieving indexes; e.g. - // java.sql.DatabaseMetaData.getIndexInfo() - - boolean indexExists = false; - String sql = ""; - Connection conn = null; - Statement stmt = null; - ResultSet rs = null; - - if (databaseProductType == DatabaseProductType.MYSQL) { - sql = "SHOW INDEX FROM " + tableName + " WHERE key_name='" + indexName + "'"; - } else if (databaseProductType == DatabaseProductType.POSTGRESQL) { - // We want to see if any index on that column exists, not just ours... - sql = "SELECT indexname FROM pg_catalog.pg_indexes " - + "WHERE tablename = '" + tableName - + "' AND indexdef ILIKE '%("+colName+")'"; - } - - try { - // Assumes indices will only be created at post-init time - // for the Nuxeo repository. - // - // To date, for the CSpace repository, indices have typically been - // created during the build process, via manual or generated - // DDL SQL scripts. - // - // If this assumption is no longer valid, we might instead - // identify the relevant repository from the table name here. - conn = JDBCTools.getConnection(dataSourceName, repositoryName, cspaceInstanceId); - stmt = conn.createStatement(); - rs = stmt.executeQuery(sql); - if (rs.next()) { - indexExists = true; - } - rs.close(); - stmt.close(); - conn.close(); - } catch (Exception e) { - logger.debug("Error when identifying whether index exists in table " - + tableName + ":" + e.getMessage()); - } finally { - try { - if (rs != null) { - rs.close(); - } - if (stmt != null) { - stmt.close(); - } - if (conn != null) { - conn.close(); - } - } catch (SQLException sqle) { - logger.debug("SQL Exception closing statement/connection in AddIndices: " + sqle.getLocalizedMessage()); - } - } - return indexExists; - } - -} +/** + * 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 + */ +package org.collectionspace.services.common.init; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import javax.sql.DataSource; + +import org.collectionspace.services.common.api.Tools; +import org.collectionspace.services.common.storage.DatabaseProductType; +import org.collectionspace.services.common.storage.JDBCTools; +import org.collectionspace.services.config.service.InitHandler.Params.Field; +import org.collectionspace.services.config.service.InitHandler.Params.Property; +import org.collectionspace.services.config.service.ServiceBindingType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * AddIndices, post-init action to add indexes to the database. + * + * In the configuration file, you may have sets of table names and column names, or you may use params to send a + * comma-separated list of column names and a table name. That is, both of these are equivalent: + * + * The single column per element version: + * + * + * <s:initHandler xmlns:s='http://collectionspace.org/services/common/service'> + <s:classname>org.collectionspace.services.common.init.AddIndices</s:classname> + <s:params> + <s:field> + <s:table>nuxeo.organizations_common</s:table> + <s:col>inAuthority</s:col> + </s:field> + <s:field> + <s:table>nuxeo.organizations_common</s:table> + <s:col>displayName</s:col> + </s:field> + <s:field> + <s:table>nuxeo.organizations_common</s:table> + <s:col>shortIdentifier</s:col> + </s:field> + </s:params> + </s:initHandler> + + The csv version: + + <s:initHandler xmlns:s='http://collectionspace.org/services/common/service'> + <s:classname>org.collectionspace.services.common.init.AddIndices</s:classname> + <s:params> + <s:field> + <s:table>nuxeo.organizations_common</s:table> + <s:param>inAuthority,displayName,shortIdentifier</s:param> + </s:field> + </s:params> + </s:initHandler> + * + * $LastChangedRevision$ + * $LastChangedDate$ + */ +public class AddIndices extends InitHandler implements IInitHandler { + + final Logger logger = LoggerFactory.getLogger(AddIndices.class); + private final static String INDEX_SEP = "_"; + private final static String INDEX_SUFFIX = INDEX_SEP + "idx"; + + + /** See the class javadoc for this class: it shows the syntax supported in the configuration params. + */ + @Override + public void onRepositoryInitialized(String dataSourceName, + String repositoryName, + String cspaceInstanceId, + ServiceBindingType sbt, + List fields, + List properties) throws Exception { + //todo: all post-init tasks for services, or delegate to services that override. + int rows = 0; + String sql = ""; + if (logger.isInfoEnabled() && sbt != null) { + logger.info("Creating indicies, as needed, for designated fields in " + sbt.getName() + + " for repository domain " + sbt.getRepositoryDomain().trim() + "..."); + } + + for (Field field : fields) { + String tableName = field.getTable(); + String fieldName = field.getCol(); + String param = field.getParam(); + if(Tools.notEmpty(param) && (param.indexOf(',')>-1)){ + String[] fieldNames = param.split(","); + for (String fn: fieldNames){ + rows = addOneIndex(dataSourceName, repositoryName, cspaceInstanceId, tableName, fn); + } + } else { + rows = addOneIndex(dataSourceName, repositoryName, cspaceInstanceId, tableName, fieldName); + } + } + } + + private int addOneIndex(String dataSourceName, + String repositoryName, + String cspaceInstanceId, + String tableName, + String columnName) { + int rows = 0; + String sql = ""; + String indexName = tableName + INDEX_SEP + columnName + INDEX_SUFFIX; + try { + DatabaseProductType databaseProductType = JDBCTools.getDatabaseProductType(dataSourceName, repositoryName); + if (indexExists(dataSourceName, repositoryName, cspaceInstanceId, databaseProductType, + tableName, columnName, indexName)) { + logger.trace("Index already exists for column " + columnName + + " in table " + tableName); + // FIXME: Can add the option to drop and re-create an index here. + // For example, see MySQL documentation on DROP INDEX. + return 0; + } + // TODO: Consider refactoring this 'if' statement to a general-purpose + // mechanism for retrieving and populating catalog/DDL-type SQL statements + // appropriate to a particular database product. + logger.info("Creating index for column " + columnName + " in table " + tableName); + if (databaseProductType == DatabaseProductType.MYSQL + || databaseProductType == DatabaseProductType.POSTGRESQL) { + sql = "CREATE INDEX " + indexName + " ON " + + tableName + " (" + columnName + ")"; + } else { + throw new Exception("Unrecognized database system " + databaseProductType); + } + if (sql != null && ! sql.trim().isEmpty()) { + // Assumes indicies will only be created at post-init time + // for the Nuxeo repository. + // + // To date, for the CSpace repository, indices have typically been + // created during the build process, via manual or generated + // DDL SQL scripts. + // + // If this assumption is no longer valid, we might instead + // identify the relevant repository from the table name here. + rows = JDBCTools.executeUpdate(dataSourceName, repositoryName, cspaceInstanceId, sql); + logger.trace("Index added to column ("+columnName+") on table ("+tableName+")"); + } + return rows; + } catch (Throwable e) { + logger.debug("Index NOT added to column ("+columnName+") on table ("+tableName+") SQL: "+sql+" ERROR: "+e); + return -1; + } + } + + private boolean indexExists(String dataSourceName, + String repositoryName, + String cspaceInstanceId, + DatabaseProductType databaseProductType, + String tableName, + String colName, + String indexName) { + + // FIXME: May need to qualify table name by database/catalog, + // as table names likely will not be globally unique across same + // (although index names *may* be unique within scope). + // + // If we do need to do this, we might: + // - Pass in the database name as a parameter to this method, retrieved + // via getDatabaseName(field) in onRepositoryInitialized, above. + // - Add 'IN databaseName' after tableName in MySQL variant, below. + // (PostgreSQL variant, below, uses a view that doesn't include + // a foreign key for associating a database/catalog to the index.) + + // FIXME: Consider instead substituting a database-agnostic + // JDBC mechanism for retrieving indexes; e.g. + // java.sql.DatabaseMetaData.getIndexInfo() + + boolean indexExists = false; + String sql = ""; + Connection conn = null; + Statement stmt = null; + ResultSet rs = null; + + if (databaseProductType == DatabaseProductType.MYSQL) { + sql = "SHOW INDEX FROM " + tableName + " WHERE key_name='" + indexName + "'"; + } else if (databaseProductType == DatabaseProductType.POSTGRESQL) { + // We want to see if any index on that column exists, not just ours... + sql = "SELECT indexname FROM pg_catalog.pg_indexes " + + "WHERE tablename = '" + tableName + + "' AND indexdef ILIKE '%("+colName+")'"; + } + + try { + // Assumes indices will only be created at post-init time + // for the Nuxeo repository. + // + // To date, for the CSpace repository, indices have typically been + // created during the build process, via manual or generated + // DDL SQL scripts. + // + // If this assumption is no longer valid, we might instead + // identify the relevant repository from the table name here. + conn = JDBCTools.getConnection(dataSourceName, repositoryName, cspaceInstanceId); + stmt = conn.createStatement(); + rs = stmt.executeQuery(sql); + if (rs.next()) { + indexExists = true; + } + rs.close(); + stmt.close(); + conn.close(); + } catch (Exception e) { + logger.debug("Error when identifying whether index exists in table " + + tableName + ":" + e.getMessage()); + } finally { + try { + if (rs != null) { + rs.close(); + } + if (stmt != null) { + stmt.close(); + } + if (conn != null) { + conn.close(); + } + } catch (SQLException sqle) { + logger.debug("SQL Exception closing statement/connection in AddIndices: " + sqle.getLocalizedMessage()); + } + } + return indexExists; + } + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/init/IInitHandler.java b/services/common/src/main/java/org/collectionspace/services/common/init/IInitHandler.java index 27788d6ed..d227cd392 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/init/IInitHandler.java +++ b/services/common/src/main/java/org/collectionspace/services/common/init/IInitHandler.java @@ -1,22 +1,22 @@ -package org.collectionspace.services.common.init; - -import java.util.List; - -import org.collectionspace.services.config.service.InitHandler.Params.Field; -import org.collectionspace.services.config.service.InitHandler.Params.Property; -import org.collectionspace.services.config.service.ServiceBindingType; - -/** - * User: laramie - * $LastChangedRevision$ - * $LastChangedDate$ - */ - -public interface IInitHandler { - public void onRepositoryInitialized(String dataSourceName, - String repositoryName, - String cspaceInstanceId, - ServiceBindingType sbt, - List fields, - List property) throws Exception; -} +package org.collectionspace.services.common.init; + +import java.util.List; + +import org.collectionspace.services.config.service.InitHandler.Params.Field; +import org.collectionspace.services.config.service.InitHandler.Params.Property; +import org.collectionspace.services.config.service.ServiceBindingType; + +/** + * User: laramie + * $LastChangedRevision$ + * $LastChangedDate$ + */ + +public interface IInitHandler { + public void onRepositoryInitialized(String dataSourceName, + String repositoryName, + String cspaceInstanceId, + ServiceBindingType sbt, + List fields, + List property) throws Exception; +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/init/InitHandler.java b/services/common/src/main/java/org/collectionspace/services/common/init/InitHandler.java index e33c129f6..56a6a4ba1 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/init/InitHandler.java +++ b/services/common/src/main/java/org/collectionspace/services/common/init/InitHandler.java @@ -1,79 +1,79 @@ -/** - * 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 - */ -package org.collectionspace.services.common.init; - -import org.collectionspace.services.config.service.InitHandler.Params.Field; -import org.collectionspace.services.config.service.InitHandler.Params.Property; -import org.collectionspace.services.config.service.ServiceBindingType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; - -/** Concrete class which does nothing, but subclasses may override to do - * some action on the event onRepositoryInitialized(), such as sending JDBC - * calls to the repository to add indices, etc. - * @author Laramie - * $LastChangedRevision$ - * $LastChangedDate$ - */ -public class InitHandler implements IInitHandler { - - final Logger logger = LoggerFactory.getLogger(InitHandler.class); - - /** - * Callback procedure for performing post-initialization actions. - * - * See org.collectionspace.services.common.init.AddIndices for an implementation example. - * - * @param dataSourceName - * @param repositoryName - * @param sbt a service binding type. - * @param fields A list of fields and their attributes. - * @param properties A properties bag for additional properties. - * @throws Exception - */ - @Override - public void onRepositoryInitialized(String dataSourceName, - String repositoryName, - String cspaceInstanceId, - ServiceBindingType sbt, - List fields, - List properties) throws Exception { - - // For debugging. - /* - for (Field field : fields) { - System.out.println("InitHandler.fields:" - + "\r\n col: " + field.getCol() - + " table: " + field.getTable() - + " type: " + field.getType() - + " param: " + field.getParam()); - } - for (Property prop : properties) { - System.out.println("InitHandler.properties:" - + "\r\n key: " + prop.getKey() - + " value: " + prop.getValue()); - - } - * - */ - } - -} +/** + * 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 + */ +package org.collectionspace.services.common.init; + +import org.collectionspace.services.config.service.InitHandler.Params.Field; +import org.collectionspace.services.config.service.InitHandler.Params.Property; +import org.collectionspace.services.config.service.ServiceBindingType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +/** Concrete class which does nothing, but subclasses may override to do + * some action on the event onRepositoryInitialized(), such as sending JDBC + * calls to the repository to add indices, etc. + * @author Laramie + * $LastChangedRevision$ + * $LastChangedDate$ + */ +public class InitHandler implements IInitHandler { + + final Logger logger = LoggerFactory.getLogger(InitHandler.class); + + /** + * Callback procedure for performing post-initialization actions. + * + * See org.collectionspace.services.common.init.AddIndices for an implementation example. + * + * @param dataSourceName + * @param repositoryName + * @param sbt a service binding type. + * @param fields A list of fields and their attributes. + * @param properties A properties bag for additional properties. + * @throws Exception + */ + @Override + public void onRepositoryInitialized(String dataSourceName, + String repositoryName, + String cspaceInstanceId, + ServiceBindingType sbt, + List fields, + List properties) throws Exception { + + // For debugging. + /* + for (Field field : fields) { + System.out.println("InitHandler.fields:" + + "\r\n col: " + field.getCol() + + " table: " + field.getTable() + + " type: " + field.getType() + + " param: " + field.getParam()); + } + for (Property prop : properties) { + System.out.println("InitHandler.properties:" + + "\r\n key: " + prop.getKey() + + " value: " + prop.getValue()); + + } + * + */ + } + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/invocable/InvocableUtils.java b/services/common/src/main/java/org/collectionspace/services/common/invocable/InvocableUtils.java index 3f8d96959..8aebe1021 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/invocable/InvocableUtils.java +++ b/services/common/src/main/java/org/collectionspace/services/common/invocable/InvocableUtils.java @@ -1,32 +1,32 @@ -package org.collectionspace.services.common.invocable; - -import org.collectionspace.services.jaxb.InvocableJAXBSchema; - -public class InvocableUtils { - - /** - * Returns the standard property name for an invocable schema, given - * and invocation mode string. - * @param schema If not null, the returned property name will be qualified with - * this schema name. - * @param invocationMode one of Invocable.INVOCATION_MODE_* - * @return - */ - public static String getPropertyNameForInvocationMode(String schema, String invocationMode) { - String modeProperty = null; - if(Invocable.INVOCATION_MODE_SINGLE.equalsIgnoreCase(invocationMode)) { - modeProperty = InvocableJAXBSchema.SUPPORTS_SINGLE_DOC; - } else if(Invocable.INVOCATION_MODE_LIST.equalsIgnoreCase(invocationMode)) { - modeProperty = InvocableJAXBSchema.SUPPORTS_DOC_LIST; - } else if(Invocable.INVOCATION_MODE_GROUP.equalsIgnoreCase(invocationMode)) { - modeProperty = InvocableJAXBSchema.SUPPORTS_GROUP; - } else if(Invocable.INVOCATION_MODE_NO_CONTEXT.equalsIgnoreCase(invocationMode)) { - modeProperty = InvocableJAXBSchema.SUPPORTS_NO_CONTEXT; - } else { - throw new IllegalArgumentException("QueryManagerNuxeoImpl: unknown Invocation Mode: " - +invocationMode); - } - return (schema!=null)? (schema+":"+modeProperty):modeProperty; - } - -} +package org.collectionspace.services.common.invocable; + +import org.collectionspace.services.jaxb.InvocableJAXBSchema; + +public class InvocableUtils { + + /** + * Returns the standard property name for an invocable schema, given + * and invocation mode string. + * @param schema If not null, the returned property name will be qualified with + * this schema name. + * @param invocationMode one of Invocable.INVOCATION_MODE_* + * @return + */ + public static String getPropertyNameForInvocationMode(String schema, String invocationMode) { + String modeProperty = null; + if(Invocable.INVOCATION_MODE_SINGLE.equalsIgnoreCase(invocationMode)) { + modeProperty = InvocableJAXBSchema.SUPPORTS_SINGLE_DOC; + } else if(Invocable.INVOCATION_MODE_LIST.equalsIgnoreCase(invocationMode)) { + modeProperty = InvocableJAXBSchema.SUPPORTS_DOC_LIST; + } else if(Invocable.INVOCATION_MODE_GROUP.equalsIgnoreCase(invocationMode)) { + modeProperty = InvocableJAXBSchema.SUPPORTS_GROUP; + } else if(Invocable.INVOCATION_MODE_NO_CONTEXT.equalsIgnoreCase(invocationMode)) { + modeProperty = InvocableJAXBSchema.SUPPORTS_NO_CONTEXT; + } else { + throw new IllegalArgumentException("QueryManagerNuxeoImpl: unknown Invocation Mode: " + +invocationMode); + } + return (schema!=null)? (schema+":"+modeProperty):modeProperty; + } + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/profile/BufferedServletInputStream.java b/services/common/src/main/java/org/collectionspace/services/common/profile/BufferedServletInputStream.java index 513a94b07..4cf4585b0 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/profile/BufferedServletInputStream.java +++ b/services/common/src/main/java/org/collectionspace/services/common/profile/BufferedServletInputStream.java @@ -1,28 +1,28 @@ -package org.collectionspace.services.common.profile; - -import javax.servlet.ServletInputStream; -import java.io.ByteArrayInputStream; - -/* Subclass of ServletInputStream needed by the servlet engine. -All inputStream methods are wrapped and are delegated to -the ByteArrayInputStream (obtained as constructor parameter)!*/ - -public class BufferedServletInputStream extends ServletInputStream { - ByteArrayInputStream bais; - public BufferedServletInputStream(ByteArrayInputStream bais) { - this.bais = bais; - } - - public int available() { - return bais.available(); - } - - public int read() { - return bais.read(); - } - - public int read(byte[] buf, int off, int len) { - return bais.read(buf, off, len); - } -} - +package org.collectionspace.services.common.profile; + +import javax.servlet.ServletInputStream; +import java.io.ByteArrayInputStream; + +/* Subclass of ServletInputStream needed by the servlet engine. +All inputStream methods are wrapped and are delegated to +the ByteArrayInputStream (obtained as constructor parameter)!*/ + +public class BufferedServletInputStream extends ServletInputStream { + ByteArrayInputStream bais; + public BufferedServletInputStream(ByteArrayInputStream bais) { + this.bais = bais; + } + + public int available() { + return bais.available(); + } + + public int read() { + return bais.read(); + } + + public int read(byte[] buf, int off, int len) { + return bais.read(buf, off, len); + } +} + diff --git a/services/common/src/main/java/org/collectionspace/services/common/profile/BufferedServletOutputStream.java b/services/common/src/main/java/org/collectionspace/services/common/profile/BufferedServletOutputStream.java index 35993b9fb..9279de39e 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/profile/BufferedServletOutputStream.java +++ b/services/common/src/main/java/org/collectionspace/services/common/profile/BufferedServletOutputStream.java @@ -1,39 +1,39 @@ -package org.collectionspace.services.common.profile; - -import java.io.*; -import javax.servlet.*; - -public class BufferedServletOutputStream extends ServletOutputStream { - // the actual buffer - private ByteArrayOutputStream bos = new ByteArrayOutputStream( ); - - public String getAsString(){ - byte[] buf = bos.toByteArray(); - return new String(buf); - } - - /** - * @return the contents of the buffer. - */ - public byte[] getBuffer( ) { - return this.bos.toByteArray( ); - } - - /** - * This method must be defined for custom servlet output streams. - */ - public void write(int data) { - this.bos.write(data); - } - - // BufferedHttpResponseWrapper calls this method - public void reset( ) { - this.bos.reset( ); - } - - // BufferedHttpResponseWrapper calls this method - public void setBufferSize(int size) { - // no way to resize an existing ByteArrayOutputStream - this.bos = new ByteArrayOutputStream(size); - } +package org.collectionspace.services.common.profile; + +import java.io.*; +import javax.servlet.*; + +public class BufferedServletOutputStream extends ServletOutputStream { + // the actual buffer + private ByteArrayOutputStream bos = new ByteArrayOutputStream( ); + + public String getAsString(){ + byte[] buf = bos.toByteArray(); + return new String(buf); + } + + /** + * @return the contents of the buffer. + */ + public byte[] getBuffer( ) { + return this.bos.toByteArray( ); + } + + /** + * This method must be defined for custom servlet output streams. + */ + public void write(int data) { + this.bos.write(data); + } + + // BufferedHttpResponseWrapper calls this method + public void reset( ) { + this.bos.reset( ); + } + + // BufferedHttpResponseWrapper calls this method + public void setBufferSize(int size) { + // no way to resize an existing ByteArrayOutputStream + this.bos = new ByteArrayOutputStream(size); + } } \ No newline at end of file diff --git a/services/common/src/main/java/org/collectionspace/services/common/profile/CSpaceFilter.java b/services/common/src/main/java/org/collectionspace/services/common/profile/CSpaceFilter.java index fad825f92..e2b275869 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/profile/CSpaceFilter.java +++ b/services/common/src/main/java/org/collectionspace/services/common/profile/CSpaceFilter.java @@ -1,131 +1,131 @@ -/** - * 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.profile; - -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; - -import org.collectionspace.services.client.Profiler; -import org.collectionspace.services.common.ServletTools; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * CSpaceFilter.java - * - * A filter that performs specified actions at the time - * each new request is received by the servlet container. - * - * This filter is currently used for recording performance - * metrics for requests to the CollectionSpace services. - * - * $LastChangedRevision: $ - * $LastChangedDate: $ - * - */ -public class CSpaceFilter implements Filter { - final Logger logger = LoggerFactory.getLogger(CSpaceFilter.class); - - /** The filter config. */ - FilterConfig filterConfig = null; - private final String CLASS_NAME = this.getClass().getSimpleName(); - - /* (non-Javadoc) - * @see javax.servlet.Filter#destroy() - */ - @Override - public void destroy() { - // Empty method. - } - - /* (non-Javadoc) - * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) - */ - @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { - if (request != null) { - HttpServletRequest httpRequest = (HttpServletRequest) request; - - // Instantiate the CollectionSpace services profiler. - StringBuffer uri = new StringBuffer(httpRequest.getRequestURI()); - uri.append(':'); - uri.append(httpRequest.getMethod()); - Profiler profiler = new Profiler(uri.toString(), 0); - Profiler csvProfiler = new Profiler("org.collectionspace.perf.csv"); - - // Start timing. - profiler.start(); - - // Write a CSV-delimited message to the performance log, - // in a format intended to be interoperable with those - // generated by other system layers. - String csvMsg = - profiler.getStartTime() - + "," + profiler.getElapsedTime() - + "," + "request" - + "," + "app" - + "," + "svc" - + "," + httpRequest.getMethod() - + "," + ServletTools.getURL(httpRequest) - + "," + CLASS_NAME - + "," + Thread.currentThread().getName(); - final boolean FORMAT_LOG_MESSAGE = false; - profiler.log(csvMsg, FORMAT_LOG_MESSAGE); - - // Process the request. - chain.doFilter(request, response); - - // Stop timing and log performance-related metrics. - profiler.stop(); - - csvMsg = - profiler.getStopTime() - + "," + profiler.getElapsedTime() - + "," + "response" - + "," + "svc" - + "," + "app" - + "," + httpRequest.getMethod() - + "," + ServletTools.getURL(httpRequest) - + "," + CLASS_NAME - + "," + Thread.currentThread().getName(); - profiler.log(csvMsg, FORMAT_LOG_MESSAGE); - - profiler.reset(); - } - } - - /* (non-Javadoc) - * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) - */ - @Override - public void init(FilterConfig theFilterConfig) throws ServletException { - filterConfig = theFilterConfig; - if (filterConfig != null) { - // We can initialize using the init-params here which we defined in - // web.xml) - } - } -} +/** + * 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.profile; + +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; + +import org.collectionspace.services.client.Profiler; +import org.collectionspace.services.common.ServletTools; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * CSpaceFilter.java + * + * A filter that performs specified actions at the time + * each new request is received by the servlet container. + * + * This filter is currently used for recording performance + * metrics for requests to the CollectionSpace services. + * + * $LastChangedRevision: $ + * $LastChangedDate: $ + * + */ +public class CSpaceFilter implements Filter { + final Logger logger = LoggerFactory.getLogger(CSpaceFilter.class); + + /** The filter config. */ + FilterConfig filterConfig = null; + private final String CLASS_NAME = this.getClass().getSimpleName(); + + /* (non-Javadoc) + * @see javax.servlet.Filter#destroy() + */ + @Override + public void destroy() { + // Empty method. + } + + /* (non-Javadoc) + * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) + */ + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + if (request != null) { + HttpServletRequest httpRequest = (HttpServletRequest) request; + + // Instantiate the CollectionSpace services profiler. + StringBuffer uri = new StringBuffer(httpRequest.getRequestURI()); + uri.append(':'); + uri.append(httpRequest.getMethod()); + Profiler profiler = new Profiler(uri.toString(), 0); + Profiler csvProfiler = new Profiler("org.collectionspace.perf.csv"); + + // Start timing. + profiler.start(); + + // Write a CSV-delimited message to the performance log, + // in a format intended to be interoperable with those + // generated by other system layers. + String csvMsg = + profiler.getStartTime() + + "," + profiler.getElapsedTime() + + "," + "request" + + "," + "app" + + "," + "svc" + + "," + httpRequest.getMethod() + + "," + ServletTools.getURL(httpRequest) + + "," + CLASS_NAME + + "," + Thread.currentThread().getName(); + final boolean FORMAT_LOG_MESSAGE = false; + profiler.log(csvMsg, FORMAT_LOG_MESSAGE); + + // Process the request. + chain.doFilter(request, response); + + // Stop timing and log performance-related metrics. + profiler.stop(); + + csvMsg = + profiler.getStopTime() + + "," + profiler.getElapsedTime() + + "," + "response" + + "," + "svc" + + "," + "app" + + "," + httpRequest.getMethod() + + "," + ServletTools.getURL(httpRequest) + + "," + CLASS_NAME + + "," + Thread.currentThread().getName(); + profiler.log(csvMsg, FORMAT_LOG_MESSAGE); + + profiler.reset(); + } + } + + /* (non-Javadoc) + * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) + */ + @Override + public void init(FilterConfig theFilterConfig) throws ServletException { + filterConfig = theFilterConfig; + if (filterConfig != null) { + // We can initialize using the init-params here which we defined in + // web.xml) + } + } +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/profile/PayloadFilter.java b/services/common/src/main/java/org/collectionspace/services/common/profile/PayloadFilter.java index 1a8501c4b..939f07152 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/profile/PayloadFilter.java +++ b/services/common/src/main/java/org/collectionspace/services/common/profile/PayloadFilter.java @@ -1,115 +1,115 @@ -/** - * 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.profile; - -import java.io.IOException; -import java.io.StringReader; -import java.util.Enumeration; -import java.util.Map; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -//import javax.servlet.ServletContext; - -import org.collectionspace.services.common.ServletTools; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Install like this: - C:\src\trunk\services\JaxRsServiceProvider\src\main\webapp\WEB-INF\web.xml - - PayloadFilter - org.collectionspace.services.common.profile.PayloadFilter - - - PayloadFilter - /* - - */ -public class PayloadFilter implements Filter { - FilterConfig filterConfig = null; - - public String CRLF = "\r\n"; - - @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { - if (request != null) { - HttpServletRequest httpRequest = (HttpServletRequest) request; - //String uri = httpRequest.getRequestURI(); - //String method = httpRequest.getMethod(); - RequestWrapper requestWrapper = new RequestWrapper(httpRequest); - //ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response); - - java.io.PrintWriter out = response.getWriter(); - ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response); - - - - // pass the wrappers on to the next entry - chain.doFilter(requestWrapper, responseWrapper); - - - - //StringReader sr = new StringReader(new String(responseWrapper.getData())); - String rsp = responseWrapper.toString(); - response.setContentLength(rsp.length()); - out.write(rsp); - - StringBuffer rqd = new StringBuffer(); - StringBuffer rsd = new StringBuffer(); - - rqd.append(httpRequest.getMethod()+' '+ServletTools.getURL(httpRequest)+' '+httpRequest.getProtocol()+CRLF); - rqd.append(requestWrapper.getHeaderBlock()); - rqd.append(CRLF); - rqd.append(requestWrapper.getRequestAsString()); - System.out.println("request: =========="+CRLF+rqd.toString()); - - rsd.append(responseWrapper.getResponseLine()+CRLF); - rsd.append(responseWrapper.getHeaderBlock()); - rsd.append("Content-Length: "+rsp.length()); - rsd.append(CRLF); - rsd.append(rsp); - //responseWrapper.getContentType() + responseWrapper.getLocale() + responseWrapper.getResponse().) - System.out.println("response: =========="+CRLF+rsd.toString()); - } - } - - @Override - public void init(FilterConfig theFilterConfig) throws ServletException { - filterConfig = theFilterConfig; - if (filterConfig != null) { - // We can initialize using the init-params here which we defined in - // web.xml) - } - } - @Override - - public void destroy() { - // Empty method. - } - - - -} +/** + * 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.profile; + +import java.io.IOException; +import java.io.StringReader; +import java.util.Enumeration; +import java.util.Map; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +//import javax.servlet.ServletContext; + +import org.collectionspace.services.common.ServletTools; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Install like this: + C:\src\trunk\services\JaxRsServiceProvider\src\main\webapp\WEB-INF\web.xml + + PayloadFilter + org.collectionspace.services.common.profile.PayloadFilter + + + PayloadFilter + /* + + */ +public class PayloadFilter implements Filter { + FilterConfig filterConfig = null; + + public String CRLF = "\r\n"; + + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + if (request != null) { + HttpServletRequest httpRequest = (HttpServletRequest) request; + //String uri = httpRequest.getRequestURI(); + //String method = httpRequest.getMethod(); + RequestWrapper requestWrapper = new RequestWrapper(httpRequest); + //ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response); + + java.io.PrintWriter out = response.getWriter(); + ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response); + + + + // pass the wrappers on to the next entry + chain.doFilter(requestWrapper, responseWrapper); + + + + //StringReader sr = new StringReader(new String(responseWrapper.getData())); + String rsp = responseWrapper.toString(); + response.setContentLength(rsp.length()); + out.write(rsp); + + StringBuffer rqd = new StringBuffer(); + StringBuffer rsd = new StringBuffer(); + + rqd.append(httpRequest.getMethod()+' '+ServletTools.getURL(httpRequest)+' '+httpRequest.getProtocol()+CRLF); + rqd.append(requestWrapper.getHeaderBlock()); + rqd.append(CRLF); + rqd.append(requestWrapper.getRequestAsString()); + System.out.println("request: =========="+CRLF+rqd.toString()); + + rsd.append(responseWrapper.getResponseLine()+CRLF); + rsd.append(responseWrapper.getHeaderBlock()); + rsd.append("Content-Length: "+rsp.length()); + rsd.append(CRLF); + rsd.append(rsp); + //responseWrapper.getContentType() + responseWrapper.getLocale() + responseWrapper.getResponse().) + System.out.println("response: =========="+CRLF+rsd.toString()); + } + } + + @Override + public void init(FilterConfig theFilterConfig) throws ServletException { + filterConfig = theFilterConfig; + if (filterConfig != null) { + // We can initialize using the init-params here which we defined in + // web.xml) + } + } + @Override + + public void destroy() { + // Empty method. + } + + + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/profile/RequestWrapper.java b/services/common/src/main/java/org/collectionspace/services/common/profile/RequestWrapper.java index 0b0f4a9e0..0e1437738 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/profile/RequestWrapper.java +++ b/services/common/src/main/java/org/collectionspace/services/common/profile/RequestWrapper.java @@ -1,98 +1,98 @@ -package org.collectionspace.services.common.profile; - -import javax.servlet.*; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.http.HttpServletRequest; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Enumeration; - -public class RequestWrapper extends HttpServletRequestWrapper { - - ByteArrayInputStream bais; - ByteArrayOutputStream baos; - BufferedServletInputStream bufInputStream; - byte[] buffer; - HttpServletRequest originalRequest; - - public RequestWrapper(HttpServletRequest req) throws IOException { - super(req); - this.originalRequest = req; - // Read InputStream and store its content in a buffer. - java.io.InputStream is = req.getInputStream(); - baos = new ByteArrayOutputStream(); - byte buf[] = new byte[1024]; - int bytesRead; - while ((bytesRead = is.read(buf)) > 0) baos.write(buf, 0, bytesRead); - buffer = baos.toByteArray(); - } - - public ServletInputStream getInputStream() { - try { - // Generate a new InputStream by stored buffer - bais = new ByteArrayInputStream(buffer); - bufInputStream = new BufferedServletInputStream(bais); //BufferedServletInputStream is our custom class. - } - catch (Exception ex) { - ex.printStackTrace(); - } - finally { - return bufInputStream; - } - } - public String getRequestAsString(){ - return new String(buffer); - } - - public String getHeaderBlock() { - StringBuffer b = new StringBuffer(); - for (Enumeration headernames = originalRequest.getHeaderNames(); headernames.hasMoreElements();) { - String headername = (String) headernames.nextElement(); - b.append(headername + ": " + originalRequest.getHeader(headername) + "\r\n"); - } - return b.toString(); - } - -} - - - /* -public class POSTFilter { -public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { - try { - HttpServletRequest httpRequest = (HttpServletRequest) request; - RequestWrapper bufferedRequest = new RequestWrapper(httpRequest); - -//Here obtain InputStream to process POST data! - - InputStream is = bufferedRequest.getInputStream(); - -//... some kind of processing on "is"...... - -//chain.doFilter using wrapped request!!!! - - chain.doFilter(bufferedRequest, response); - -//When a chained servlet call request.getInputStream() - -//then the getInputStream() method of RequestWrapper will be invoked - -//and a new readable copy of the original inputStream will be returned!!! - - } - - catch (Exception ex) { - - ex.printStackTrace(); - - } - - } - -} */ - - - - - +package org.collectionspace.services.common.profile; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequestWrapper; +import javax.servlet.http.HttpServletRequest; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Enumeration; + +public class RequestWrapper extends HttpServletRequestWrapper { + + ByteArrayInputStream bais; + ByteArrayOutputStream baos; + BufferedServletInputStream bufInputStream; + byte[] buffer; + HttpServletRequest originalRequest; + + public RequestWrapper(HttpServletRequest req) throws IOException { + super(req); + this.originalRequest = req; + // Read InputStream and store its content in a buffer. + java.io.InputStream is = req.getInputStream(); + baos = new ByteArrayOutputStream(); + byte buf[] = new byte[1024]; + int bytesRead; + while ((bytesRead = is.read(buf)) > 0) baos.write(buf, 0, bytesRead); + buffer = baos.toByteArray(); + } + + public ServletInputStream getInputStream() { + try { + // Generate a new InputStream by stored buffer + bais = new ByteArrayInputStream(buffer); + bufInputStream = new BufferedServletInputStream(bais); //BufferedServletInputStream is our custom class. + } + catch (Exception ex) { + ex.printStackTrace(); + } + finally { + return bufInputStream; + } + } + public String getRequestAsString(){ + return new String(buffer); + } + + public String getHeaderBlock() { + StringBuffer b = new StringBuffer(); + for (Enumeration headernames = originalRequest.getHeaderNames(); headernames.hasMoreElements();) { + String headername = (String) headernames.nextElement(); + b.append(headername + ": " + originalRequest.getHeader(headername) + "\r\n"); + } + return b.toString(); + } + +} + + + /* +public class POSTFilter { +public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { + try { + HttpServletRequest httpRequest = (HttpServletRequest) request; + RequestWrapper bufferedRequest = new RequestWrapper(httpRequest); + +//Here obtain InputStream to process POST data! + + InputStream is = bufferedRequest.getInputStream(); + +//... some kind of processing on "is"...... + +//chain.doFilter using wrapped request!!!! + + chain.doFilter(bufferedRequest, response); + +//When a chained servlet call request.getInputStream() + +//then the getInputStream() method of RequestWrapper will be invoked + +//and a new readable copy of the original inputStream will be returned!!! + + } + + catch (Exception ex) { + + ex.printStackTrace(); + + } + + } + +} */ + + + + + diff --git a/services/common/src/main/java/org/collectionspace/services/common/profile/ResponseWrapper.java b/services/common/src/main/java/org/collectionspace/services/common/profile/ResponseWrapper.java index 53580f272..57f97939d 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/profile/ResponseWrapper.java +++ b/services/common/src/main/java/org/collectionspace/services/common/profile/ResponseWrapper.java @@ -1,176 +1,176 @@ -package org.collectionspace.services.common.profile; - -import java.io.*; -import java.util.HashMap; -import java.util.Map; -import javax.servlet.*; -import javax.servlet.http.*; - -public class ResponseWrapper extends HttpServletResponseWrapper { - private CharArrayWriter output; - private BufferedServletOutputStream os; - private boolean gotWriter = false; - private boolean gotStream = false; - private Map headers = new HashMap(); - private int statusCode = 0; - private String statusMessage = ""; - - public String toString() { - if (gotWriter) return output.toString(); - else { - String str = os.getAsString(); - return str; - } - } - - public ResponseWrapper(HttpServletResponse response) { - super(response); - output = new CharArrayWriter(); - os = new BufferedServletOutputStream(); - } - - public PrintWriter getWriter() { - gotWriter = true; - return new PrintWriter(output); - } - - public ServletOutputStream getOutputStream() { - gotStream = true; - return os; - } - - public void setHeader(String header, String value){ - System.out.println("###### setHeader ######################## header set: "+header+": "+value); - headers.put(header, value); - super.setHeader(header, value); - } - public void addHeader(java.lang.String name, java.lang.String value){ - super.addHeader(name, value); - System.out.println("### addHeader ########################### header set: "+name+": "+value); - - } - public void setIntHeader(java.lang.String name, int value){ - super.setIntHeader(name, value); - System.out.println("### setIntHeader ########################### header set: "+name+": "+value); - } - public void addIntHeader(java.lang.String name, int value){ - super.addIntHeader(name, value); - System.out.println("### addIntHeader ########################### header set: "+name+": "+value); - } - - - public void setStatus(int sc, String sm){ - super.setStatus(sc,sm); - this.statusCode = sc; - this.statusMessage = sm; - } - public void setStatus(int sc){ - super.setStatus(sc); - this.statusCode = sc; - } - public void sendError(int sc) throws java.io.IOException { - super.sendError(sc); - this.statusCode = sc; - } - public void sendError(int sc, String msg) throws java.io.IOException{ - super.sendError(sc, msg); - this.statusCode = sc; - this.statusMessage = msg; - } - - public String getStatusMessage(){ - return statusMessage; - } - public int getStatusCode(){ - return statusCode; - } - public Map getHeaders(){ - return headers; - } - public String getHeaderBlock(){ - StringBuffer b = new StringBuffer(); - for(Map.Entry e : headers.entrySet()){ - b.append(e.getKey()).append(": ").append(e.getValue()).append("\r\n"); - } - return b.toString(); - } - public String getResponseLine(){ - return "HTTP/1.1 "+statusCode+' '+statusMessage; - } - -} - -/** - * A custom response wrapper that captures all output in a buffer. - */ -/* -public class ResponseWrapper extends HttpServletResponseWrapper { - private BufferedServletOutputStream bufferedServletOut = new BufferedServletOutputStream( ); - private PrintWriter printWriter = null; - private ServletOutputStream outputStream = null; - - public ResponseWrapper(HttpServletResponse origResponse) { - super(origResponse); - } - - public String getResponseAsString(){ - return bufferedServletOut.getAsString(); - } - - public byte[] getBuffer( ) { - return this.bufferedServletOut.getBuffer( ); - } - - public PrintWriter getWriter( ) throws IOException { - if (this.outputStream != null) { - throw new IllegalStateException( - "The Servlet API forbids calling getWriter( ) after" - + " getOutputStream( ) has been called"); - } - - if (this.printWriter == null) { - this.printWriter = new PrintWriter(this.bufferedServletOut); - } - return this.printWriter; - } - - public ServletOutputStream getOutputStream( ) throws IOException { - if (this.printWriter != null) { - throw new IllegalStateException( - "The Servlet API forbids calling getOutputStream( ) after" - + " getWriter( ) has been called"); - } - - if (this.outputStream == null) { - this.outputStream = this.bufferedServletOut; - } - return this.outputStream; - } - - // override methods that deal with the response buffer - - public void flushBuffer( ) throws IOException { - if (this.outputStream != null) { - this.outputStream.flush( ); - } else if (this.printWriter != null) { - this.printWriter.flush( ); - } - } - - public int getBufferSize( ) { - return this.bufferedServletOut.getBuffer( ).length; - } - - public void reset( ) { - this.bufferedServletOut.reset( ); - } - - public void resetBuffer( ) { - this.bufferedServletOut.reset( ); - } - - public void setBufferSize(int size) { - this.bufferedServletOut.setBufferSize(size); - } -} +package org.collectionspace.services.common.profile; + +import java.io.*; +import java.util.HashMap; +import java.util.Map; +import javax.servlet.*; +import javax.servlet.http.*; + +public class ResponseWrapper extends HttpServletResponseWrapper { + private CharArrayWriter output; + private BufferedServletOutputStream os; + private boolean gotWriter = false; + private boolean gotStream = false; + private Map headers = new HashMap(); + private int statusCode = 0; + private String statusMessage = ""; + + public String toString() { + if (gotWriter) return output.toString(); + else { + String str = os.getAsString(); + return str; + } + } + + public ResponseWrapper(HttpServletResponse response) { + super(response); + output = new CharArrayWriter(); + os = new BufferedServletOutputStream(); + } + + public PrintWriter getWriter() { + gotWriter = true; + return new PrintWriter(output); + } + + public ServletOutputStream getOutputStream() { + gotStream = true; + return os; + } + + public void setHeader(String header, String value){ + System.out.println("###### setHeader ######################## header set: "+header+": "+value); + headers.put(header, value); + super.setHeader(header, value); + } + public void addHeader(java.lang.String name, java.lang.String value){ + super.addHeader(name, value); + System.out.println("### addHeader ########################### header set: "+name+": "+value); + + } + public void setIntHeader(java.lang.String name, int value){ + super.setIntHeader(name, value); + System.out.println("### setIntHeader ########################### header set: "+name+": "+value); + } + public void addIntHeader(java.lang.String name, int value){ + super.addIntHeader(name, value); + System.out.println("### addIntHeader ########################### header set: "+name+": "+value); + } + + + public void setStatus(int sc, String sm){ + super.setStatus(sc,sm); + this.statusCode = sc; + this.statusMessage = sm; + } + public void setStatus(int sc){ + super.setStatus(sc); + this.statusCode = sc; + } + public void sendError(int sc) throws java.io.IOException { + super.sendError(sc); + this.statusCode = sc; + } + public void sendError(int sc, String msg) throws java.io.IOException{ + super.sendError(sc, msg); + this.statusCode = sc; + this.statusMessage = msg; + } + + public String getStatusMessage(){ + return statusMessage; + } + public int getStatusCode(){ + return statusCode; + } + public Map getHeaders(){ + return headers; + } + public String getHeaderBlock(){ + StringBuffer b = new StringBuffer(); + for(Map.Entry e : headers.entrySet()){ + b.append(e.getKey()).append(": ").append(e.getValue()).append("\r\n"); + } + return b.toString(); + } + public String getResponseLine(){ + return "HTTP/1.1 "+statusCode+' '+statusMessage; + } + +} + +/** + * A custom response wrapper that captures all output in a buffer. + */ +/* +public class ResponseWrapper extends HttpServletResponseWrapper { + private BufferedServletOutputStream bufferedServletOut = new BufferedServletOutputStream( ); + private PrintWriter printWriter = null; + private ServletOutputStream outputStream = null; + + public ResponseWrapper(HttpServletResponse origResponse) { + super(origResponse); + } + + public String getResponseAsString(){ + return bufferedServletOut.getAsString(); + } + + public byte[] getBuffer( ) { + return this.bufferedServletOut.getBuffer( ); + } + + public PrintWriter getWriter( ) throws IOException { + if (this.outputStream != null) { + throw new IllegalStateException( + "The Servlet API forbids calling getWriter( ) after" + + " getOutputStream( ) has been called"); + } + + if (this.printWriter == null) { + this.printWriter = new PrintWriter(this.bufferedServletOut); + } + return this.printWriter; + } + + public ServletOutputStream getOutputStream( ) throws IOException { + if (this.printWriter != null) { + throw new IllegalStateException( + "The Servlet API forbids calling getOutputStream( ) after" + + " getWriter( ) has been called"); + } + + if (this.outputStream == null) { + this.outputStream = this.bufferedServletOut; + } + return this.outputStream; + } + + // override methods that deal with the response buffer + + public void flushBuffer( ) throws IOException { + if (this.outputStream != null) { + this.outputStream.flush( ); + } else if (this.printWriter != null) { + this.printWriter.flush( ); + } + } + + public int getBufferSize( ) { + return this.bufferedServletOut.getBuffer( ).length; + } + + public void reset( ) { + this.bufferedServletOut.reset( ); + } + + public void resetBuffer( ) { + this.bufferedServletOut.reset( ); + } + + public void setBufferSize(int size) { + this.bufferedServletOut.setBufferSize(size); + } +} */ \ No newline at end of file diff --git a/services/common/src/main/java/org/collectionspace/services/common/query/QueryContext.java b/services/common/src/main/java/org/collectionspace/services/common/query/QueryContext.java index b316d3c1b..1e99e9161 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/query/QueryContext.java +++ b/services/common/src/main/java/org/collectionspace/services/common/query/QueryContext.java @@ -1,169 +1,169 @@ -package org.collectionspace.services.common.query; - -import org.collectionspace.services.client.PoxPayloadIn; -import org.collectionspace.services.client.PoxPayloadOut; -import org.collectionspace.services.common.context.ServiceContext; -import org.collectionspace.services.common.document.DocumentException; -import org.collectionspace.services.common.document.DocumentFilter; -import org.collectionspace.services.common.document.DocumentHandler; -import org.collectionspace.services.common.document.DocumentNotFoundException; - -import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; -import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; - -// TODO: Auto-generated Javadoc -/** - * The Class QueryContext. - */ -public class QueryContext { - - /** The doc type. */ - String docType; - /** The doc filter. */ - DocumentFilter docFilter; - /** The where clause. */ - String whereClause; - /** The order by clause. */ - String orderByClause; - /** The domain. */ - String domain; - /** The tenant id. */ - String tenantId; - - static public final String getTenantQualifiedDoctype(QueryContext queryContext, String docType) { - return docType + ServiceContext.TENANT_SUFFIX + queryContext.getTenantId(); - } - - /** - * Instantiates a new query context. - * - * @param ctx the ctx - * @throws DocumentNotFoundException the document not found exception - * @throws DocumentException the document exception - */ - QueryContext(ServiceContext ctx) throws DocumentNotFoundException, DocumentException { - docType = ctx.getDocumentType(); - if (docType == null) { - throw new DocumentNotFoundException( - "Unable to find DocumentType for service " + ctx.getServiceName()); - } - domain = ctx.getRepositoryDomainStorageName(); - tenantId = ctx.getTenantId(); - if (tenantId == null) { - throw new IllegalArgumentException( - "Service context has no Tenant ID specified."); - } - } - - /** - * Instantiates a new query context. - * - * @param ctx the ctx - * @param theWhereClause the where clause - * @throws DocumentNotFoundException the document not found exception - * @throws DocumentException the document exception - */ - public QueryContext(ServiceContext ctx, - String theWhereClause) throws DocumentNotFoundException, DocumentException { - this(ctx); - whereClause = theWhereClause; - } - - /** - * Instantiates a new query context. - * - * @param ctx the ctx - * @param theWhereClause the where clause - * @param theOrderByClause the order by clause - * @throws DocumentNotFoundException the document not found exception - * @throws DocumentException the document exception - */ - public QueryContext(ServiceContext ctx, - String theWhereClause, String theOrderByClause) throws DocumentNotFoundException, DocumentException { - this(ctx); - whereClause = theWhereClause; - orderByClause = theOrderByClause; - } - - /** - * Instantiates a new query context. - * - * @param ctx the ctx - * @param handler the handler - * @throws DocumentNotFoundException the document not found exception - * @throws DocumentException the document exception - */ - public QueryContext(ServiceContext ctx, - DocumentHandler handler) throws DocumentNotFoundException, DocumentException { - this(ctx); - if (handler == null) { - throw new IllegalArgumentException( - "Document handler is missing."); - } - docFilter = handler.getDocumentFilter(); - if (docFilter == null) { - throw new IllegalArgumentException( - "Document handler has no Filter specified."); - } - whereClause = docFilter.getWhereClause(); - orderByClause = docFilter.getOrderByClause(); - } - - /** - * Gets the doc filter. - * - * @return the doc filter - */ - public DocumentFilter getDocFilter() { - return docFilter; - } - - /** - * Gets the where clause. - * - * @return the where clause - */ - public String getWhereClause() { - return whereClause; - } - - /** - * Gets the tenant id. - * - * @return the tenant id - */ - public String getTenantId() { - return this.tenantId; - } - - /** - * Gets the order by clause. - * - * @return the order by clause - */ - public String getOrderByClause() { - return this.orderByClause; - } - - /** - * Gets the doc type. - * - * @return the doc type - */ - public String getDocType() { - return this.docType; - } - - public final String getTenantQualifiedDoctype() { - return QueryContext.getTenantQualifiedDoctype(this, docType); - } - - /** - * Gets the doc type. - * - * @return the doc type - */ - public void setDocType(String theDocType) { - this.docType = theDocType; - } -} +package org.collectionspace.services.common.query; + +import org.collectionspace.services.client.PoxPayloadIn; +import org.collectionspace.services.client.PoxPayloadOut; +import org.collectionspace.services.common.context.ServiceContext; +import org.collectionspace.services.common.document.DocumentException; +import org.collectionspace.services.common.document.DocumentFilter; +import org.collectionspace.services.common.document.DocumentHandler; +import org.collectionspace.services.common.document.DocumentNotFoundException; + +import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; +import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; + +// TODO: Auto-generated Javadoc +/** + * The Class QueryContext. + */ +public class QueryContext { + + /** The doc type. */ + String docType; + /** The doc filter. */ + DocumentFilter docFilter; + /** The where clause. */ + String whereClause; + /** The order by clause. */ + String orderByClause; + /** The domain. */ + String domain; + /** The tenant id. */ + String tenantId; + + static public final String getTenantQualifiedDoctype(QueryContext queryContext, String docType) { + return docType + ServiceContext.TENANT_SUFFIX + queryContext.getTenantId(); + } + + /** + * Instantiates a new query context. + * + * @param ctx the ctx + * @throws DocumentNotFoundException the document not found exception + * @throws DocumentException the document exception + */ + QueryContext(ServiceContext ctx) throws DocumentNotFoundException, DocumentException { + docType = ctx.getDocumentType(); + if (docType == null) { + throw new DocumentNotFoundException( + "Unable to find DocumentType for service " + ctx.getServiceName()); + } + domain = ctx.getRepositoryDomainStorageName(); + tenantId = ctx.getTenantId(); + if (tenantId == null) { + throw new IllegalArgumentException( + "Service context has no Tenant ID specified."); + } + } + + /** + * Instantiates a new query context. + * + * @param ctx the ctx + * @param theWhereClause the where clause + * @throws DocumentNotFoundException the document not found exception + * @throws DocumentException the document exception + */ + public QueryContext(ServiceContext ctx, + String theWhereClause) throws DocumentNotFoundException, DocumentException { + this(ctx); + whereClause = theWhereClause; + } + + /** + * Instantiates a new query context. + * + * @param ctx the ctx + * @param theWhereClause the where clause + * @param theOrderByClause the order by clause + * @throws DocumentNotFoundException the document not found exception + * @throws DocumentException the document exception + */ + public QueryContext(ServiceContext ctx, + String theWhereClause, String theOrderByClause) throws DocumentNotFoundException, DocumentException { + this(ctx); + whereClause = theWhereClause; + orderByClause = theOrderByClause; + } + + /** + * Instantiates a new query context. + * + * @param ctx the ctx + * @param handler the handler + * @throws DocumentNotFoundException the document not found exception + * @throws DocumentException the document exception + */ + public QueryContext(ServiceContext ctx, + DocumentHandler handler) throws DocumentNotFoundException, DocumentException { + this(ctx); + if (handler == null) { + throw new IllegalArgumentException( + "Document handler is missing."); + } + docFilter = handler.getDocumentFilter(); + if (docFilter == null) { + throw new IllegalArgumentException( + "Document handler has no Filter specified."); + } + whereClause = docFilter.getWhereClause(); + orderByClause = docFilter.getOrderByClause(); + } + + /** + * Gets the doc filter. + * + * @return the doc filter + */ + public DocumentFilter getDocFilter() { + return docFilter; + } + + /** + * Gets the where clause. + * + * @return the where clause + */ + public String getWhereClause() { + return whereClause; + } + + /** + * Gets the tenant id. + * + * @return the tenant id + */ + public String getTenantId() { + return this.tenantId; + } + + /** + * Gets the order by clause. + * + * @return the order by clause + */ + public String getOrderByClause() { + return this.orderByClause; + } + + /** + * Gets the doc type. + * + * @return the doc type + */ + public String getDocType() { + return this.docType; + } + + public final String getTenantQualifiedDoctype() { + return QueryContext.getTenantQualifiedDoctype(this, docType); + } + + /** + * Gets the doc type. + * + * @return the doc type + */ + public void setDocType(String theDocType) { + this.docType = theDocType; + } +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/query/QueryManager.java b/services/common/src/main/java/org/collectionspace/services/common/query/QueryManager.java index d59b4a2d8..fb46ff2ce 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/query/QueryManager.java +++ b/services/common/src/main/java/org/collectionspace/services/common/query/QueryManager.java @@ -1,118 +1,118 @@ -/** - * QueryManager.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.query; - -import org.collectionspace.services.client.IQueryManager; -import org.collectionspace.services.common.ServiceMain; -import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl; -import org.collectionspace.services.common.config.TenantBindingUtils; -import org.collectionspace.services.common.context.ServiceContext; -import org.collectionspace.services.common.query.nuxeo.QueryManagerNuxeoImpl; -import org.collectionspace.services.config.tenant.TenantBindingType; - -public class QueryManager { - static private final IQueryManager queryManager = new QueryManagerNuxeoImpl(); - - /** - * Creates the where clause from keywords. - * - * @param keywords the keywords - * - * @return the string - */ - static public String createWhereClauseFromKeywords(String keywords) { - return queryManager.createWhereClauseFromKeywords(keywords); - } - - static public String createWhereClauseFromAdvancedSearch(String keywords) { - return queryManager.createWhereClauseFromAdvancedSearch(keywords); - } - - /** - * Creates the where clause for partial term match. - * - * @param field the qualified field to match on - * @param partialTerm the term to match against - * - * @return the string - */ - static public String createWhereClauseForPartialMatch(ServiceContext ctx, - String field, - String partialTerm) throws Exception { - String cspaceInstanceId = ServiceMain.getInstance().getCspaceInstanceId(); - String repositoryName = ctx.getRepositoryName(); - // Otherwise, generate that list and cache it for re-use. - TenantBindingConfigReaderImpl tReader = - ServiceMain.getInstance().getTenantBindingConfigReader(); - TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId()); - String ptStartingWildcardValue = TenantBindingUtils.getPropertyValue(tenantBinding, - IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM); - boolean ptStartingWildcard = (ptStartingWildcardValue==null) - || Boolean.parseBoolean(ptStartingWildcardValue); - - return queryManager.createWhereClauseForPartialMatch(queryManager.getDatasourceName(), - repositoryName, cspaceInstanceId, field, ptStartingWildcard, partialTerm); - } - - /** - * Creates a query to filter a qualified (string) field according to a list of string values. - * @param qualifiedField The schema-qualified field to filter on - * @param filterTerms the list of one or more strings to filter on - * @param fExclude If true, will require qualifiedField NOT match the filters strings. - * If false, will require qualifiedField does match one of the filters strings. - * @return queryString - */ - static public String createWhereClauseToFilterFromStringList(String qualifiedField, String[] filterTerms, boolean fExclude) { - return queryManager.createWhereClauseToFilterFromStringList(qualifiedField, filterTerms, fExclude); - } - - - /** - * Creates a filtering where clause from docType, for invocables. - * - * @param schema the schema name for this invocable type - * @param docType the docType - * - * @return the string - */ - static public String createWhereClauseForInvocableByDocType(String schema, String docType) { - return queryManager.createWhereClauseForInvocableByDocType(schema, docType); - } - - /** - * Creates a filtering where clause from invocation mode, for invocables. - * - * @param schema the schema name for this invocable type - * @param mode the mode - * - * @return the string - */ - static public String createWhereClauseForInvocableByMode(String schema, String mode) { - return queryManager.createWhereClauseForInvocableByMode(schema, mode); - } - -} +/** + * QueryManager.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.query; + +import org.collectionspace.services.client.IQueryManager; +import org.collectionspace.services.common.ServiceMain; +import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl; +import org.collectionspace.services.common.config.TenantBindingUtils; +import org.collectionspace.services.common.context.ServiceContext; +import org.collectionspace.services.common.query.nuxeo.QueryManagerNuxeoImpl; +import org.collectionspace.services.config.tenant.TenantBindingType; + +public class QueryManager { + static private final IQueryManager queryManager = new QueryManagerNuxeoImpl(); + + /** + * Creates the where clause from keywords. + * + * @param keywords the keywords + * + * @return the string + */ + static public String createWhereClauseFromKeywords(String keywords) { + return queryManager.createWhereClauseFromKeywords(keywords); + } + + static public String createWhereClauseFromAdvancedSearch(String keywords) { + return queryManager.createWhereClauseFromAdvancedSearch(keywords); + } + + /** + * Creates the where clause for partial term match. + * + * @param field the qualified field to match on + * @param partialTerm the term to match against + * + * @return the string + */ + static public String createWhereClauseForPartialMatch(ServiceContext ctx, + String field, + String partialTerm) throws Exception { + String cspaceInstanceId = ServiceMain.getInstance().getCspaceInstanceId(); + String repositoryName = ctx.getRepositoryName(); + // Otherwise, generate that list and cache it for re-use. + TenantBindingConfigReaderImpl tReader = + ServiceMain.getInstance().getTenantBindingConfigReader(); + TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId()); + String ptStartingWildcardValue = TenantBindingUtils.getPropertyValue(tenantBinding, + IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM); + boolean ptStartingWildcard = (ptStartingWildcardValue==null) + || Boolean.parseBoolean(ptStartingWildcardValue); + + return queryManager.createWhereClauseForPartialMatch(queryManager.getDatasourceName(), + repositoryName, cspaceInstanceId, field, ptStartingWildcard, partialTerm); + } + + /** + * Creates a query to filter a qualified (string) field according to a list of string values. + * @param qualifiedField The schema-qualified field to filter on + * @param filterTerms the list of one or more strings to filter on + * @param fExclude If true, will require qualifiedField NOT match the filters strings. + * If false, will require qualifiedField does match one of the filters strings. + * @return queryString + */ + static public String createWhereClauseToFilterFromStringList(String qualifiedField, String[] filterTerms, boolean fExclude) { + return queryManager.createWhereClauseToFilterFromStringList(qualifiedField, filterTerms, fExclude); + } + + + /** + * Creates a filtering where clause from docType, for invocables. + * + * @param schema the schema name for this invocable type + * @param docType the docType + * + * @return the string + */ + static public String createWhereClauseForInvocableByDocType(String schema, String docType) { + return queryManager.createWhereClauseForInvocableByDocType(schema, docType); + } + + /** + * Creates a filtering where clause from invocation mode, for invocables. + * + * @param schema the schema name for this invocable type + * @param mode the mode + * + * @return the string + */ + static public String createWhereClauseForInvocableByMode(String schema, String mode) { + return queryManager.createWhereClauseForInvocableByMode(schema, mode); + } + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/query/QueryResultList.java b/services/common/src/main/java/org/collectionspace/services/common/query/QueryResultList.java index 43ba37ff4..2cbb156a5 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/query/QueryResultList.java +++ b/services/common/src/main/java/org/collectionspace/services/common/query/QueryResultList.java @@ -1,54 +1,54 @@ -package org.collectionspace.services.common.query; - -import java.util.List; -import org.collectionspace.services.common.document.DocumentListWrapper; - -// TODO: Auto-generated Javadoc -/** - * The Class QueryResultList. - */ -public class QueryResultList { - - private long totalSize = 0; - - /** The wrapper object list. */ - private LISTTYPE wrapperObjectList; - - /** - * Instantiates a new query result list. - */ - private QueryResultList() { - //private constructor - } - - /** - * Instantiates a new query result list. - * - * @param theWrapperObjectList the the wrapper object list - */ - public QueryResultList(LISTTYPE theWrapperObjectList) { - wrapperObjectList = theWrapperObjectList; - } - - /** - * Gets the wrapper object list. - * - * @return the wrapper object list - */ - public LISTTYPE getWrapperObjectList() { - return this.wrapperObjectList; - } - - /** - * Sets the total size. This is the total size of the non-paged result set. - * - * @param theTotalResultSize the new total size - */ - public void setTotalSize(long theTotalSize) { - totalSize = theTotalSize; - } - - public long getTotalSize() { - return totalSize; - } -} +package org.collectionspace.services.common.query; + +import java.util.List; +import org.collectionspace.services.common.document.DocumentListWrapper; + +// TODO: Auto-generated Javadoc +/** + * The Class QueryResultList. + */ +public class QueryResultList { + + private long totalSize = 0; + + /** The wrapper object list. */ + private LISTTYPE wrapperObjectList; + + /** + * Instantiates a new query result list. + */ + private QueryResultList() { + //private constructor + } + + /** + * Instantiates a new query result list. + * + * @param theWrapperObjectList the the wrapper object list + */ + public QueryResultList(LISTTYPE theWrapperObjectList) { + wrapperObjectList = theWrapperObjectList; + } + + /** + * Gets the wrapper object list. + * + * @return the wrapper object list + */ + public LISTTYPE getWrapperObjectList() { + return this.wrapperObjectList; + } + + /** + * Sets the total size. This is the total size of the non-paged result set. + * + * @param theTotalResultSize the new total size + */ + public void setTotalSize(long theTotalSize) { + totalSize = theTotalSize; + } + + public long getTotalSize() { + return totalSize; + } +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/query/nuxeo/QueryManagerNuxeoImpl.java b/services/common/src/main/java/org/collectionspace/services/common/query/nuxeo/QueryManagerNuxeoImpl.java index e9e2f4cb2..604f2f28f 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/query/nuxeo/QueryManagerNuxeoImpl.java +++ b/services/common/src/main/java/org/collectionspace/services/common/query/nuxeo/QueryManagerNuxeoImpl.java @@ -1,357 +1,357 @@ -/** - * QueryManagerNuxeoImpl.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.query.nuxeo; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -//import org.nuxeo.ecm.core.client.NuxeoClient; - -import org.collectionspace.services.jaxb.InvocableJAXBSchema; -//import org.collectionspace.services.nuxeo.client.java.NuxeoConnector; -//import org.collectionspace.services.nuxeo.client.java.NxConnect; - -import org.collectionspace.services.client.IQueryManager; -import org.collectionspace.services.common.invocable.InvocableUtils; -import org.collectionspace.services.common.storage.DatabaseProductType; -import org.collectionspace.services.common.storage.JDBCTools; - -public class QueryManagerNuxeoImpl implements IQueryManager { - - private static String ECM_FULLTEXT_LIKE = "ecm:fulltext" - + SEARCH_TERM_SEPARATOR + IQueryManager.SEARCH_LIKE; - private static String SEARCH_LIKE_FORM = null; - - private final Logger logger = LoggerFactory - .getLogger(QueryManagerNuxeoImpl.class); - - // Consider that letters, letter-markers, numbers, '_' and apostrophe are - // words - private static Pattern nonWordChars = Pattern - .compile("[^\\p{L}\\p{M}\\p{N}_']"); - private static Pattern kwdTokenizer = Pattern.compile("(?:(['\"])(.*?)(?\\\\\\\\)*\\1|([^ ]+))"); - private static Pattern unescapedDblQuotes = Pattern.compile("(? '":" = '"); - filterClause.append(filterTerms[0]); - filterClause.append('\''); - } else { - filterClause.append(fExclude?" NOT IN (":" IN ("); - for(int i=0; i0) { - filterClause.append(','); - } - filterClause.append('\''); - filterClause.append(filterTerms[i]); - filterClause.append('\''); - } - filterClause.append(')'); - } - return filterClause.toString(); - } - -} +/** + * QueryManagerNuxeoImpl.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.query.nuxeo; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +//import org.nuxeo.ecm.core.client.NuxeoClient; + +import org.collectionspace.services.jaxb.InvocableJAXBSchema; +//import org.collectionspace.services.nuxeo.client.java.NuxeoConnector; +//import org.collectionspace.services.nuxeo.client.java.NxConnect; + +import org.collectionspace.services.client.IQueryManager; +import org.collectionspace.services.common.invocable.InvocableUtils; +import org.collectionspace.services.common.storage.DatabaseProductType; +import org.collectionspace.services.common.storage.JDBCTools; + +public class QueryManagerNuxeoImpl implements IQueryManager { + + private static String ECM_FULLTEXT_LIKE = "ecm:fulltext" + + SEARCH_TERM_SEPARATOR + IQueryManager.SEARCH_LIKE; + private static String SEARCH_LIKE_FORM = null; + + private final Logger logger = LoggerFactory + .getLogger(QueryManagerNuxeoImpl.class); + + // Consider that letters, letter-markers, numbers, '_' and apostrophe are + // words + private static Pattern nonWordChars = Pattern + .compile("[^\\p{L}\\p{M}\\p{N}_']"); + private static Pattern kwdTokenizer = Pattern.compile("(?:(['\"])(.*?)(?\\\\\\\\)*\\1|([^ ]+))"); + private static Pattern unescapedDblQuotes = Pattern.compile("(? '":" = '"); + filterClause.append(filterTerms[0]); + filterClause.append('\''); + } else { + filterClause.append(fExclude?" NOT IN (":" IN ("); + for(int i=0; i0) { + filterClause.append(','); + } + filterClause.append('\''); + filterClause.append(filterTerms[i]); + filterClause.append('\''); + } + filterClause.append(')'); + } + return filterClause.toString(); + } + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/relation/RelationJAXBSchema.java b/services/common/src/main/java/org/collectionspace/services/common/relation/RelationJAXBSchema.java index 3d4d01fa3..b125cc069 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/relation/RelationJAXBSchema.java +++ b/services/common/src/main/java/org/collectionspace/services/common/relation/RelationJAXBSchema.java @@ -1,64 +1,64 @@ -/** - * RelationJAXBSchema.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 (c) 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 org.collectionspace.services.client.IRelationsManager; - -/** - * The Interface RelationJAXBSchema. - */ -public interface RelationJAXBSchema { - - // The Nuxeo root element name for the relation entity. - /** The Constant REL_ROOT_ELEM_NAME. */ - final static String REL_ROOT_ELEM_NAME = "relationtype"; - // Need to fix conflict between the Nuxeo XSD and the JAX-B XSD for the "relation" entity - - /** The Constant CSID. */ - final static String CSID = "csid"; - - /** The Constant RELATIONSHIP_TYPE. */ - final static String RELATIONSHIP_TYPE = "relationshipType"; - - /** The Constant RELATIONSHIP_TYPE_DISPLAYNAME. */ - final static String RELATIONSHIP_TYPE_DISPLAYNAME = "predicateDisplayName"; - - final static String RELATIONSHIP_META_TYPE = "relationshipMetaType"; - - final static String SUBJECT_URI = "subjectUri"; - final static String SUBJECT_CSID = IRelationsManager.SUBJECT; - final static String SUBJECT_REFNAME = IRelationsManager.SUBJECT_REFNAME; - final static String SUBJECT_DOCTYPE = "subjectDocumentType"; - - final static String OBJECT_URI = "objectUri"; - final static String OBJECT_CSID = IRelationsManager.OBJECT; - final static String OBJECT_REFNAME = IRelationsManager.OBJECT_REFNAME; - final static String OBJECT_DOCTYPE = "objectDocumentType"; - -} - - +/** + * RelationJAXBSchema.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 (c) 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 org.collectionspace.services.client.IRelationsManager; + +/** + * The Interface RelationJAXBSchema. + */ +public interface RelationJAXBSchema { + + // The Nuxeo root element name for the relation entity. + /** The Constant REL_ROOT_ELEM_NAME. */ + final static String REL_ROOT_ELEM_NAME = "relationtype"; + // Need to fix conflict between the Nuxeo XSD and the JAX-B XSD for the "relation" entity + + /** The Constant CSID. */ + final static String CSID = "csid"; + + /** The Constant RELATIONSHIP_TYPE. */ + final static String RELATIONSHIP_TYPE = "relationshipType"; + + /** The Constant RELATIONSHIP_TYPE_DISPLAYNAME. */ + final static String RELATIONSHIP_TYPE_DISPLAYNAME = "predicateDisplayName"; + + final static String RELATIONSHIP_META_TYPE = "relationshipMetaType"; + + final static String SUBJECT_URI = "subjectUri"; + final static String SUBJECT_CSID = IRelationsManager.SUBJECT; + final static String SUBJECT_REFNAME = IRelationsManager.SUBJECT_REFNAME; + final static String SUBJECT_DOCTYPE = "subjectDocumentType"; + + final static String OBJECT_URI = "objectUri"; + final static String OBJECT_CSID = IRelationsManager.OBJECT; + final static String OBJECT_REFNAME = IRelationsManager.OBJECT_REFNAME; + final static String OBJECT_DOCTYPE = "objectDocumentType"; + +} + + diff --git a/services/common/src/main/java/org/collectionspace/services/common/relation/RelationListItemJAXBSchema.java b/services/common/src/main/java/org/collectionspace/services/common/relation/RelationListItemJAXBSchema.java index b044aa5ca..8eb6e01a7 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/relation/RelationListItemJAXBSchema.java +++ b/services/common/src/main/java/org/collectionspace/services/common/relation/RelationListItemJAXBSchema.java @@ -1,49 +1,49 @@ -/** - * RelationListItemJAXBSchema.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 (c) 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; - -/** - * The Interface RelationListItemJAXBSchema. - */ -public interface RelationListItemJAXBSchema { - - /** The Constant REL_ROOT_ELEM_NAME. */ - final static String REL_ROOT_ELEM_NAME = "relation-list"; - - /** The Constant CSID. */ - final static String CSID = "csid"; - - final static String SUBJECT_CSID = "subjectCsid"; - final static String RELATIONSHIP_TYPE = "relationshipType"; - final static String OBJECT_CSID = "objectCsid"; - - /** The Constant RELATIONSHIP_TYPE_DISPLAYNAME. */ - final static String RELATIONSHIP_TYPE_DISPLAYNAME = "predicateDisplayName"; - - /** The Constant URI. */ - final static String URI = "url"; -} +/** + * RelationListItemJAXBSchema.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 (c) 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; + +/** + * The Interface RelationListItemJAXBSchema. + */ +public interface RelationListItemJAXBSchema { + + /** The Constant REL_ROOT_ELEM_NAME. */ + final static String REL_ROOT_ELEM_NAME = "relation-list"; + + /** The Constant CSID. */ + final static String CSID = "csid"; + + final static String SUBJECT_CSID = "subjectCsid"; + final static String RELATIONSHIP_TYPE = "relationshipType"; + final static String OBJECT_CSID = "objectCsid"; + + /** The Constant RELATIONSHIP_TYPE_DISPLAYNAME. */ + final static String RELATIONSHIP_TYPE_DISPLAYNAME = "predicateDisplayName"; + + /** The Constant URI. */ + final static String URI = "url"; +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/storage/JDBCTools.java b/services/common/src/main/java/org/collectionspace/services/common/storage/JDBCTools.java index a647b0757..68045aed7 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/storage/JDBCTools.java +++ b/services/common/src/main/java/org/collectionspace/services/common/storage/JDBCTools.java @@ -1,771 +1,771 @@ -/** - * 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 - */ -package org.collectionspace.services.common.storage; - -import org.collectionspace.services.common.api.Tools; -import org.collectionspace.services.common.config.ConfigUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.sql.DataSource; - -import java.sql.DatabaseMetaData; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import javax.sql.rowset.CachedRowSet; -import javax.sql.rowset.RowSetFactory; -import javax.sql.rowset.RowSetProvider; - -import org.apache.tomcat.dbcp.dbcp.BasicDataSource; -import org.collectionspace.services.common.ServiceMain; - -/** - * User: laramie - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ -public class JDBCTools { - public static HashMap cachedDataSources = new HashMap(); - public static String CSPACE_DATASOURCE_NAME = "CspaceDS"; - public static String NUXEO_DATASOURCE_NAME = "NuxeoDS"; - // Default database names - // public static String DEFAULT_CSPACE_DATABASE_NAME = ConfigUtils.DEFAULT_CSPACE_DATABASE_NAME; - public static String DEFAULT_NUXEO_REPOSITORY_NAME = ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME; - public static String DEFAULT_NUXEO_DATABASE_NAME = ConfigUtils.DEFAULT_NUXEO_DATABASE_NAME; - public static String CSADMIN_DATASOURCE_NAME = "CsadminDS"; - public static String NUXEO_READER_DATASOURCE_NAME = "NuxeoReaderDS"; - public static String NUXEO_USER_NAME = "nuxeo"; - public static String SQL_WILDCARD = "%"; - public static String DATABASE_SELECT_PRIVILEGE_NAME = "SELECT"; - - - // - // Private constants - // - private static String DBProductName = null; - - //todo: make sure this will get instantiated in the right order - final static Logger logger = LoggerFactory.getLogger(JDBCTools.class); - private static final CharSequence URL_DATABASE_NAME = "${DatabaseName}"; - private static String JDBC_URL_DATABASE_SEPARATOR = "\\/"; - - // - // As a side-effect of calling JDBCTools.getDataSource(...), the DataSource instance will be - // cached in a static hash map of the JDBCTools class. This will speed up lookups as well as protect our - // code from JNDI lookup problems -for example, if the JNDI context gets stepped on or corrupted. - // - public static DataSource getDataSource(String dataSourceName) throws NamingException { - DataSource result = null; - - // - // First, see if we already have this DataSource instance cached - // - result = cachedDataSources.get(dataSourceName); - if (result == null) { - InitialContext ctx = new InitialContext(); - Context envCtx = null; - - if (logger.isDebugEnabled() == true) { - logger.debug("Looking up DataSource instance in JNDI with name: " + dataSourceName); - } - - try { - envCtx = (Context) ctx.lookup("java:comp/env"); - DataSource ds = (DataSource) envCtx.lookup("jdbc/" + dataSourceName); - if (ds == null) { - throw new IllegalArgumentException("DataSource instance not found: " + dataSourceName); - } else { - result = ds; - // now cache this DataSource instance for future references - cachedDataSources.put(dataSourceName, result); - } - } finally { - if (ctx != null) { - try { - ctx.close(); - } catch (Exception e) { - logger.error("Error getting DataSource for: " + dataSourceName, e); - } - } - if (envCtx != null) { - try { - envCtx.close(); - } catch (Exception e) { - logger.error("Error getting DataSource for: " + dataSourceName, e); - } - } - } - } - - if (result != null) { -// DataSource resultClone = result. - } - - return result; - } - - // - // Use this version of the getConnection() method when you don't want to qualify the database name - // with a CollectionSpace instance ID. - // - public static Connection getConnection(String dataSourceName, - String databaseName) throws NamingException, SQLException { - return getConnection(dataSourceName, databaseName, null); - } - - public static Connection getConnection(String dataSourceName, - String repositoryName, - String cspaceInstanceId) throws NamingException, SQLException { - Connection result = null; - - if (Tools.isEmpty(dataSourceName) || Tools.isEmpty(repositoryName)) { - String errMsg = String.format( - "The getConnection() method was called with an empty or null repository name = '%s' and/or data source name = '%s'.", - dataSourceName, repositoryName); - logger.error(errMsg); - throw new NamingException(errMsg); - } - - /* - * We synch this block as a workaround to not have separate DataSource instances for - * each Nuxeo repo/DB. Ideally, we should replace the need for this synch block by - * registering a separate DataSource for each repo/db at init/start-up time. - * - * We need to sync because we're changing the URL of the datasource inorder to get the correct - * connection. The synch prevents different threads from getting the incorrect connection -i.e., one pointing - * to the wrong URL. - */ - Connection conn = null; - synchronized (JDBCTools.class) { - BasicDataSource dataSource = (BasicDataSource)getDataSource(dataSourceName); - // Get the template URL value from the JNDI datasource and substitute the databaseName - String urlTemplate = dataSource.getUrl(); - String databaseName = getDatabaseName(repositoryName, cspaceInstanceId); - String connectionUrl = urlTemplate.replace(URL_DATABASE_NAME, databaseName); - - // ATTENTION! - // Turns out the Tomcat BasicDataSource used a connection pool, so changing the url does not - // get you a corresponding connection. Use the more basic implementation for now, unless - // and until we do things right by creating additional JNDI data sources. - - //dataSource.setUrl(connectionUrl); - String user = dataSource.getUsername(); - String password = dataSource.getPassword(); - - try { - //conn = dataSource.getConnection(); - conn = DriverManager.getConnection(connectionUrl, user, password); - result = conn; - if (logger.isTraceEnabled() == true && conn != null) { - logger.trace(String.format("Connection made to repository = '%s' using datasource = '%s'", repositoryName, dataSourceName)); - } - } finally { - dataSource.setUrl(urlTemplate); // Reset the data source URL value back to the template value - } - } - - return result; - } - - public static CachedRowSet executeQuery(String dataSourceName, String repositoryName, String cspaceInstanceId, String sql) throws Exception { - Connection conn = null; - Statement stmt = null; - try { - conn = getConnection(dataSourceName, repositoryName, cspaceInstanceId); - stmt = conn.createStatement(); - - RowSetFactory rowSetFactory = RowSetProvider.newFactory(); - CachedRowSet crs = rowSetFactory.createCachedRowSet(); - - stmt = conn.createStatement(); - try (ResultSet resultSet = stmt.executeQuery(sql)) { - crs.populate(resultSet); - } - return crs; - } catch (SQLException sqle) { - SQLException tempException = sqle; - while (null != tempException) { // SQLExceptions can be chained. Loop to log all. - logger.debug("SQL Exception: " + sqle.getLocalizedMessage()); - tempException = tempException.getNextException(); - } - throw new RuntimeException("SQL Exception in executeQuery: ", sqle); - } finally { - try { - if (stmt != null) { - stmt.close(); - } - if (conn != null) { - conn.close(); - } - } catch (SQLException sqle) { - logger.debug("SQL Exception closing statement/connection in executeQuery: " + sqle.getLocalizedMessage()); - return null; - } - } - } - - public static CachedRowSet executePreparedQuery(final PreparedStatementBuilder builder, - String dataSourceName, String repositoryName, String cspaceInstanceId) throws Exception { - Connection conn = null; - PreparedStatement ps = null; - try { - conn = getConnection(dataSourceName, repositoryName, cspaceInstanceId); - RowSetFactory rowSetFactory = RowSetProvider.newFactory(); - CachedRowSet crs = rowSetFactory.createCachedRowSet(); - ps = builder.build(conn); - // FIXME: transition this log statement to DEBUG level when appropriate - if (logger.isInfoEnabled()) { - logger.info("prepared statement=" + ps.toString()); - } - try (ResultSet resultSet = ps.executeQuery()) { - crs.populate(resultSet); - } - return crs; - } catch (SQLException sqle) { - SQLException tempException = sqle; - while (null != tempException) { // SQLExceptions can be chained. Loop to log all. - logger.debug("SQL Exception: " + sqle.getLocalizedMessage()); - tempException = tempException.getNextException(); - } - throw new RuntimeException("SQL Exception in executePreparedQuery: ", sqle); - } finally { - try { - if (ps != null) { - ps.close(); - } - if (conn != null) { - conn.close(); - } - } catch (SQLException sqle) { - logger.debug("SQL Exception closing statement/connection in executePreparedQuery: " + sqle.getLocalizedMessage()); - return null; - } - } - } - - // FIXME: This method's code significantly overlaps that of executePrepareQuery(), above, - // and the two could be refactored into a single method, if desired. - public static List executePreparedQueries(final List builders, - String dataSourceName, String repositoryName, String cspaceInstanceId, Boolean executeWithinTransaction) throws Exception { - Connection conn = null; - PreparedStatement ps = null; - List results = new ArrayList<>(); - try { - conn = getConnection(dataSourceName, repositoryName, cspaceInstanceId); - if (executeWithinTransaction) { - conn.setAutoCommit(false); - } - RowSetFactory rowSetFactory = RowSetProvider.newFactory(); - CachedRowSet crs = rowSetFactory.createCachedRowSet(); - int statementCount = 0; - for (PreparedStatementBuilder builder : builders) { - ps = builder.build(conn); - // FIXME: transition this log statement to DEBUG level when appropriate - if (logger.isInfoEnabled()) { - statementCount++; - logger.info("prepared statement " + statementCount + "=" + ps.toString()); - } - // Try executing each statement, first as a query, then as an update - try { - ResultSet resultSet = ps.executeQuery(); - if (resultSet != null) { - crs.populate(resultSet); - results.add(crs); - } - } catch (Exception e) { - int rowcount = ps.executeUpdate(); - logger.debug(String.format("Row count for builder %s is %d", ps.toString(), rowcount)); - // Throw uncaught exception here if update attempt also fails - } - } - return results; - } catch (SQLException sqle) { - if (executeWithinTransaction && conn != null) { - conn.rollback(); - } - SQLException tempException = sqle; - while (null != tempException) { // SQLExceptions can be chained. Loop to log all. - logger.debug("SQL Exception: " + sqle.getLocalizedMessage()); - tempException = tempException.getNextException(); - } - throw new RuntimeException("SQL Exception in executePreparedQueries: ", sqle); - } finally { - try { - if (ps != null) { - ps.close(); - } - if (conn != null) { - if (executeWithinTransaction) { - conn.commit(); - } - conn.close(); - } - } catch (SQLException sqle) { - logger.debug("SQL Exception closing statement/connection in executePreparedQueries: " + sqle.getLocalizedMessage()); - return null; - } - } - } - - public static int executeUpdate(String dataSourceName, - String repositoryName, - String cspaceInstanceId, - String sql) throws Exception { - Connection conn = null; - Statement stmt = null; - try { - conn = getConnection(dataSourceName, repositoryName, cspaceInstanceId); - stmt = conn.createStatement(); - int rows = stmt.executeUpdate(sql); - stmt.close(); - return rows; - } catch (RuntimeException rte) { - logger.debug("Exception in executeUpdate: " + rte.getLocalizedMessage()); - logger.debug(rte.getStackTrace().toString()); - throw rte; - } catch (SQLException sqle) { - SQLException tempException = sqle; - String msg = ""; - while (null != tempException) { // SQLExceptions can be chained. Loop to log all. - if (!msg.isEmpty()) { - msg = msg + "::next::"; - } - msg = msg + sqle.getLocalizedMessage(); - logger.debug("SQL Exception: " + msg); - tempException = tempException.getNextException(); - } - throw new RuntimeException("SQL Exception in executeUpdate: " + msg, sqle); - } finally { - try { - if (stmt != null) { - stmt.close(); - } - if (conn != null) { - conn.close(); - } - } catch (SQLException sqle) { - logger.debug("SQL Exception closing statement/connection in executeUpdate: " + sqle.getLocalizedMessage()); - return -1; - } - } - } - - /** - * Returns the database product name, from the metadata for a - * JDBC connection to the default repository. - * - * Assumes that the database product name will be the same for the - * default repository and for all other repositories to which JDBC - * connections will be made, through the methods of this class. - * - * @return the database product name - */ - public static String getDatabaseProductName(String dataSourceName, - String repositoryName, - String cspaceInstanceId) { - if (DBProductName == null) { - Connection conn = null; - try { - conn = getConnection(dataSourceName, repositoryName, cspaceInstanceId); - DBProductName = conn.getMetaData().getDatabaseProductName(); - } catch (Exception e) { - if (logger.isTraceEnabled() == true) { - logger.trace(String.format("Could not open a connection. DataSource='%s' DB='%s'.", - dataSourceName, repositoryName)); - } - } finally { - try { - if (conn != null) { - conn.close(); - } - } catch (SQLException sqle) { - logger.debug("SQL Exception closing statement/connection in getDatabaseProductName: " - + sqle.getLocalizedMessage()); - } - } - } - - return DBProductName; - } - - /** - * Returns an enumerated value uniquely identifying the database product type; - * e.g. MySQL, PostgreSQL, based on the database product name. - * - * @return an enumerated value identifying the database product type - * @throws Exception - */ - public static DatabaseProductType getDatabaseProductType(String dataSourceName, - String repositoryName, - String cspaceInstanceId) throws Exception { - DatabaseProductType result = DatabaseProductType.UNRECOGNIZED; - - String productName = getDatabaseProductName(dataSourceName, repositoryName, cspaceInstanceId); - if (productName.matches("(?i).*mysql.*")) { - result = DatabaseProductType.MYSQL; - } else if (productName.matches("(?i).*postgresql.*")) { - result = DatabaseProductType.POSTGRESQL; - } else { - throw new Exception("Unrecognized database system " + productName); - } - - return result; - } - - // - // Same as method above except the cspace instance ID is not needed. - // - public static DatabaseProductType getDatabaseProductType(String dataSourceName, - String repositoryName) throws Exception { - DatabaseProductType result = DatabaseProductType.UNRECOGNIZED; - - String productName = getDatabaseProductName(dataSourceName, repositoryName, null); - if (productName.matches("(?i).*mysql.*")) { - result = DatabaseProductType.MYSQL; - } else if (productName.matches("(?i).*postgresql.*")) { - result = DatabaseProductType.POSTGRESQL; - } else { - throw new Exception("Unrecognized database system " + productName); - } - - return result; - } - - /* - * By convention, the repository name and database name are the same. However, this - * call encapulates that convention and allows overrides. - */ - public static String getDatabaseName(String repoName, String cspaceInstanceId) { - String result = repoName; - - // - // Insert code here if you want to map the repo name to a database name -otherwise - // we'll assume they are the same thing. - // - if (repoName.equalsIgnoreCase(DEFAULT_NUXEO_REPOSITORY_NAME)) { - result = DEFAULT_NUXEO_DATABASE_NAME; - } - - // - // If we have a non-null 'cspaceInstanceId' instance ID then we need to append it - // as a suffix to the database name. - // - if (cspaceInstanceId != null && !cspaceInstanceId.trim().isEmpty()) { - if (result.endsWith(cspaceInstanceId) == false) { // ensure we don't already have the suffix - result = result + cspaceInstanceId; - } - } - - return result; - } - - /** - * Returns the catalog/database name for an open JDBC connection. - * - * @param conn an open JDBC Connection - * @return the catalog name. - * @throws SQLException - */ - public static String getDatabaseName(String dataSourceName, - String repositoryName, - String cspaceInstanceId, - Connection conn) throws Exception { - String databaseName = null; - - if (conn != null) { - DatabaseMetaData metadata = conn.getMetaData(); - String urlStr = metadata.getURL(); - - // Format of the PostgreSQL JDBC URL: - // http://jdbc.postgresql.org/documentation/80/connect.html - if (getDatabaseProductType(dataSourceName, repositoryName, cspaceInstanceId) == DatabaseProductType.POSTGRESQL) { - String tokens[] = urlStr.split(JDBC_URL_DATABASE_SEPARATOR); - databaseName = tokens[tokens.length - 1]; - // Format of the MySQL JDBC URL: - // http://dev.mysql.com/doc/refman/5.1/en/connector-j-reference-configuration-properties.html - // FIXME: the last token could contain optional parameters, not accounted for here. - } else if (getDatabaseProductType(dataSourceName, repositoryName, cspaceInstanceId) == DatabaseProductType.MYSQL) { - String tokens[] = urlStr.split(JDBC_URL_DATABASE_SEPARATOR); - databaseName = tokens[tokens.length - 1]; - } - } - - return databaseName; - } - - /** - * Grant a specified privilege to a database user. This privilege will - * be applied to all 'public' schema tables within the specified repository. - * - * @param dataSourceName a JDBC datasource name. - * @param repositoryName a repository (e.g. RDBMS database) name. - * @param cspaceInstanceId a CollectionSpace instance identifier. - * @param privilegeName a database privilege (e.g. SELECT) to be granted. - * @param databaseUserName a database user to receive the privilege grant. - */ - public static void grantPrivilegeToDatabaseUser(String dataSourceName, String repositoryName, - String cspaceInstanceId, String privilegeName, String databaseUserName) { - Statement stmt = null; - Connection conn = null; - String sql = String.format("GRANT %s ON ALL TABLES IN SCHEMA public TO %s", privilegeName, databaseUserName); - try { - DatabaseProductType databaseProductType = JDBCTools.getDatabaseProductType(dataSourceName, repositoryName, - cspaceInstanceId); - if (databaseProductType == DatabaseProductType.MYSQL) { - // Nothing to do here: MYSQL already does wildcard grants in init_db.sql - } else if(databaseProductType != DatabaseProductType.POSTGRESQL) { - throw new Exception("Unrecognized database system " + databaseProductType); - } else { - String databaseName = JDBCTools.getDatabaseName(repositoryName, cspaceInstanceId); - // Verify that the database user exists before executing the grant - if (hasDatabaseUser(dataSourceName, repositoryName, cspaceInstanceId, - databaseProductType, databaseUserName)) { - conn = getConnection(dataSourceName, repositoryName, cspaceInstanceId); - stmt = conn.createStatement(); - stmt.execute(sql); - } - } - - } catch (SQLException sqle) { - SQLException tempException = sqle; - // SQLExceptions can be chained. Loop to log all. - while (null != tempException) { - logger.debug("SQL Exception: " + sqle.getLocalizedMessage()); - tempException = tempException.getNextException(); - } - logger.debug("SQL problem in executeQuery: ", sqle); - } catch (Throwable e) { - logger.debug(String.format("Problem granting privileges to database user: %s SQL: %s ERROR: %s", - databaseUserName, sql, e)); - } finally { - try { - if (stmt != null) { - stmt.close(); - } - if (conn != null) { - conn.close(); - } - } catch (SQLException sqle) { - // nothing we can do here except log - logger.warn("SQL Exception when closing statement/connection: " + sqle.getLocalizedMessage()); - } - } - } - - /** - * Create a database user, if that user doesn't already exist. - * - * @param conn a database connection. - * @param dbType a database product type. - * @param username the name of the database user to create. - * @param userPW the initial password for that database user. - */ - public static void createNewDatabaseUser(String dataSourceName, String repositoryName, - String cspaceInstanceId, DatabaseProductType dbType, String username, String userPW) throws Exception { - Statement stmt = null; - Connection conn = null; - if (dbType != DatabaseProductType.POSTGRESQL) { - throw new UnsupportedOperationException("createNewDatabaseUser only supports PostgreSQL"); - } - try { - if (hasDatabaseUser(dataSourceName, repositoryName, cspaceInstanceId, dbType, username)) { - if (logger.isDebugEnabled()) { - logger.debug("User: " + username + " already exists."); - } - } else { - conn = getConnection(dataSourceName, repositoryName, cspaceInstanceId); - stmt = conn.createStatement(); - String sql = "CREATE ROLE " + username + " WITH PASSWORD '" + userPW + "' LOGIN"; - stmt.executeUpdate(sql); - if (logger.isDebugEnabled()) { - logger.debug("Created User: " + username); - } - } - } catch (Exception e) { - logger.error("createNewDatabaseUser failed on exception: " + e.getLocalizedMessage()); - throw e; - } finally { - try { - if (stmt != null) { - stmt.close(); - } - if (conn != null) { - conn.close(); - } - } catch (SQLException sqle) { - // nothing we can do here except log - logger.warn("SQL Exception when closing statement/connection: " + sqle.getLocalizedMessage()); - } - } - } - - /** - * Identify whether a database exists. - * - * @param dbType a database product type. - * @param dbName a database product name. - * @return true if a database with that name exists, false if that database does not exit. - * @throws Exception - */ - public static boolean hasDatabase(DatabaseProductType dbType, String dbName) throws Exception { - PreparedStatement pstmt = null; - Connection conn = null; - String dbExistsQuery = ""; - if (dbType == DatabaseProductType.POSTGRESQL) { - dbExistsQuery = "SELECT 1 AS result FROM pg_database WHERE datname=?"; - } else if (dbType == DatabaseProductType.MYSQL) { - dbExistsQuery = "SELECT 1 AS result FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=?"; - } else { - throw new UnsupportedOperationException("hasDatabase encountered unknown database product type"); - } - try { - DataSource csadminDataSource = JDBCTools.getDataSource(JDBCTools.CSADMIN_DATASOURCE_NAME); - conn = csadminDataSource.getConnection(); - pstmt = conn.prepareStatement(dbExistsQuery); // create a statement - pstmt.setString(1, dbName); // set dbName param - ResultSet rs = pstmt.executeQuery(); - // extract data from the ResultSet - boolean dbExists = rs.next(); // Will return a value of 1 if database exists - rs.close(); - return dbExists; - } catch (Exception e) { - logger.error("hasDatabase failed on exception: " + e.getLocalizedMessage()); - throw e; - } finally { - try { - if (pstmt != null) { - pstmt.close(); - } - if (conn != null) { - conn.close(); - } - } catch (SQLException sqle) { - // nothing we can do here except log - logger.warn("SQL Exception when closing statement/connection: " + sqle.getLocalizedMessage()); - } - } - } - - /** - * Identify whether a database user exists. - * - * @param dataSourceName a JDBC datasource name. - * @param repositoryName a repository (e.g. RDBMS database) name. - * @param cspaceInstanceId a CollectionSpace instance identifier. - * @param dbType a database product type. - * @param username the name of the database user to create. - * @param userPW the initial password for that database user. - * @return true if a database user with that name exists, false if that user does not exist. - * @throws Exception - */ - public static boolean hasDatabaseUser(String dataSourceName, String repositoryName, - String cspaceInstanceId, DatabaseProductType dbType, String username) throws Exception { - PreparedStatement pstmt = null; - Statement stmt = null; - Connection conn = null; - final String USER_EXISTS_QUERY_POSTGRESQL = "SELECT 1 AS result FROM pg_roles WHERE rolname=?"; - if (dbType != DatabaseProductType.POSTGRESQL) { - throw new UnsupportedOperationException("hasDatabaseUser only supports PostgreSQL"); - } - try { - conn = getConnection(dataSourceName, repositoryName, cspaceInstanceId); - pstmt = conn.prepareStatement(USER_EXISTS_QUERY_POSTGRESQL); - pstmt.setString(1, username); - ResultSet rs = pstmt.executeQuery(); - boolean userExists = rs.next(); // Will return a value of 1 if user exists - rs.close(); - return userExists; - } catch (Exception e) { - logger.error("hasDatabaseUser failed on exception: " + e.getLocalizedMessage()); - throw e; - } finally { - try { - if (pstmt != null) { - pstmt.close(); - } - if (stmt != null) { - stmt.close(); - } - if (conn != null) { - conn.close(); - } - } catch (SQLException sqle) { - // nothing we can do here except log - logger.warn("SQL Exception when closing statement/connection: " + sqle.getLocalizedMessage()); - } - } - } - - - // ----------------------------- - // Utility methods for debugging - // ----------------------------- - - /** - * Prints metadata, such as database username and connection URL, - * for an open JDBC connection. This is a utility method for use - * during debugging. - * - * @param conn an open JDBC Connection - * @throws SQLException - */ - private static void printConnectionMetaData(Connection conn) throws SQLException { - if (conn != null) { - DatabaseMetaData metadata = conn.getMetaData(); - // FIXME: Outputs via System.out, rather than Logger, for - // cases where this may be called during server startup. - System.out.println("username=" + metadata.getUserName()); - System.out.println("database url=" + metadata.getURL()); - } - } - - /** - * Prints metadata related to a JDBC ResultSet, such as column names. - * This is a utility method for use during debugging. - * - * @param rs a ResultSet. - * @throws SQLException - */ - public static void printResultSetMetaData(ResultSet rs) throws SQLException { - if (rs == null) { - return; - } - ResultSetMetaData metadata = rs.getMetaData(); - if (metadata == null) { - return; - } - int numberOfColumns = metadata.getColumnCount(); - for (int i = 1; i <= numberOfColumns; i++) { - logger.debug(metadata.getColumnName(i)); - // Insert other debug statements to retrieve additional per-column metadata here ... - } - } - -} +/** + * 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 + */ +package org.collectionspace.services.common.storage; + +import org.collectionspace.services.common.api.Tools; +import org.collectionspace.services.common.config.ConfigUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.sql.DataSource; + +import java.sql.DatabaseMetaData; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import javax.sql.rowset.CachedRowSet; +import javax.sql.rowset.RowSetFactory; +import javax.sql.rowset.RowSetProvider; + +import org.apache.tomcat.dbcp.dbcp.BasicDataSource; +import org.collectionspace.services.common.ServiceMain; + +/** + * User: laramie + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public class JDBCTools { + public static HashMap cachedDataSources = new HashMap(); + public static String CSPACE_DATASOURCE_NAME = "CspaceDS"; + public static String NUXEO_DATASOURCE_NAME = "NuxeoDS"; + // Default database names + // public static String DEFAULT_CSPACE_DATABASE_NAME = ConfigUtils.DEFAULT_CSPACE_DATABASE_NAME; + public static String DEFAULT_NUXEO_REPOSITORY_NAME = ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME; + public static String DEFAULT_NUXEO_DATABASE_NAME = ConfigUtils.DEFAULT_NUXEO_DATABASE_NAME; + public static String CSADMIN_DATASOURCE_NAME = "CsadminDS"; + public static String NUXEO_READER_DATASOURCE_NAME = "NuxeoReaderDS"; + public static String NUXEO_USER_NAME = "nuxeo"; + public static String SQL_WILDCARD = "%"; + public static String DATABASE_SELECT_PRIVILEGE_NAME = "SELECT"; + + + // + // Private constants + // + private static String DBProductName = null; + + //todo: make sure this will get instantiated in the right order + final static Logger logger = LoggerFactory.getLogger(JDBCTools.class); + private static final CharSequence URL_DATABASE_NAME = "${DatabaseName}"; + private static String JDBC_URL_DATABASE_SEPARATOR = "\\/"; + + // + // As a side-effect of calling JDBCTools.getDataSource(...), the DataSource instance will be + // cached in a static hash map of the JDBCTools class. This will speed up lookups as well as protect our + // code from JNDI lookup problems -for example, if the JNDI context gets stepped on or corrupted. + // + public static DataSource getDataSource(String dataSourceName) throws NamingException { + DataSource result = null; + + // + // First, see if we already have this DataSource instance cached + // + result = cachedDataSources.get(dataSourceName); + if (result == null) { + InitialContext ctx = new InitialContext(); + Context envCtx = null; + + if (logger.isDebugEnabled() == true) { + logger.debug("Looking up DataSource instance in JNDI with name: " + dataSourceName); + } + + try { + envCtx = (Context) ctx.lookup("java:comp/env"); + DataSource ds = (DataSource) envCtx.lookup("jdbc/" + dataSourceName); + if (ds == null) { + throw new IllegalArgumentException("DataSource instance not found: " + dataSourceName); + } else { + result = ds; + // now cache this DataSource instance for future references + cachedDataSources.put(dataSourceName, result); + } + } finally { + if (ctx != null) { + try { + ctx.close(); + } catch (Exception e) { + logger.error("Error getting DataSource for: " + dataSourceName, e); + } + } + if (envCtx != null) { + try { + envCtx.close(); + } catch (Exception e) { + logger.error("Error getting DataSource for: " + dataSourceName, e); + } + } + } + } + + if (result != null) { +// DataSource resultClone = result. + } + + return result; + } + + // + // Use this version of the getConnection() method when you don't want to qualify the database name + // with a CollectionSpace instance ID. + // + public static Connection getConnection(String dataSourceName, + String databaseName) throws NamingException, SQLException { + return getConnection(dataSourceName, databaseName, null); + } + + public static Connection getConnection(String dataSourceName, + String repositoryName, + String cspaceInstanceId) throws NamingException, SQLException { + Connection result = null; + + if (Tools.isEmpty(dataSourceName) || Tools.isEmpty(repositoryName)) { + String errMsg = String.format( + "The getConnection() method was called with an empty or null repository name = '%s' and/or data source name = '%s'.", + dataSourceName, repositoryName); + logger.error(errMsg); + throw new NamingException(errMsg); + } + + /* + * We synch this block as a workaround to not have separate DataSource instances for + * each Nuxeo repo/DB. Ideally, we should replace the need for this synch block by + * registering a separate DataSource for each repo/db at init/start-up time. + * + * We need to sync because we're changing the URL of the datasource inorder to get the correct + * connection. The synch prevents different threads from getting the incorrect connection -i.e., one pointing + * to the wrong URL. + */ + Connection conn = null; + synchronized (JDBCTools.class) { + BasicDataSource dataSource = (BasicDataSource)getDataSource(dataSourceName); + // Get the template URL value from the JNDI datasource and substitute the databaseName + String urlTemplate = dataSource.getUrl(); + String databaseName = getDatabaseName(repositoryName, cspaceInstanceId); + String connectionUrl = urlTemplate.replace(URL_DATABASE_NAME, databaseName); + + // ATTENTION! + // Turns out the Tomcat BasicDataSource used a connection pool, so changing the url does not + // get you a corresponding connection. Use the more basic implementation for now, unless + // and until we do things right by creating additional JNDI data sources. + + //dataSource.setUrl(connectionUrl); + String user = dataSource.getUsername(); + String password = dataSource.getPassword(); + + try { + //conn = dataSource.getConnection(); + conn = DriverManager.getConnection(connectionUrl, user, password); + result = conn; + if (logger.isTraceEnabled() == true && conn != null) { + logger.trace(String.format("Connection made to repository = '%s' using datasource = '%s'", repositoryName, dataSourceName)); + } + } finally { + dataSource.setUrl(urlTemplate); // Reset the data source URL value back to the template value + } + } + + return result; + } + + public static CachedRowSet executeQuery(String dataSourceName, String repositoryName, String cspaceInstanceId, String sql) throws Exception { + Connection conn = null; + Statement stmt = null; + try { + conn = getConnection(dataSourceName, repositoryName, cspaceInstanceId); + stmt = conn.createStatement(); + + RowSetFactory rowSetFactory = RowSetProvider.newFactory(); + CachedRowSet crs = rowSetFactory.createCachedRowSet(); + + stmt = conn.createStatement(); + try (ResultSet resultSet = stmt.executeQuery(sql)) { + crs.populate(resultSet); + } + return crs; + } catch (SQLException sqle) { + SQLException tempException = sqle; + while (null != tempException) { // SQLExceptions can be chained. Loop to log all. + logger.debug("SQL Exception: " + sqle.getLocalizedMessage()); + tempException = tempException.getNextException(); + } + throw new RuntimeException("SQL Exception in executeQuery: ", sqle); + } finally { + try { + if (stmt != null) { + stmt.close(); + } + if (conn != null) { + conn.close(); + } + } catch (SQLException sqle) { + logger.debug("SQL Exception closing statement/connection in executeQuery: " + sqle.getLocalizedMessage()); + return null; + } + } + } + + public static CachedRowSet executePreparedQuery(final PreparedStatementBuilder builder, + String dataSourceName, String repositoryName, String cspaceInstanceId) throws Exception { + Connection conn = null; + PreparedStatement ps = null; + try { + conn = getConnection(dataSourceName, repositoryName, cspaceInstanceId); + RowSetFactory rowSetFactory = RowSetProvider.newFactory(); + CachedRowSet crs = rowSetFactory.createCachedRowSet(); + ps = builder.build(conn); + // FIXME: transition this log statement to DEBUG level when appropriate + if (logger.isInfoEnabled()) { + logger.info("prepared statement=" + ps.toString()); + } + try (ResultSet resultSet = ps.executeQuery()) { + crs.populate(resultSet); + } + return crs; + } catch (SQLException sqle) { + SQLException tempException = sqle; + while (null != tempException) { // SQLExceptions can be chained. Loop to log all. + logger.debug("SQL Exception: " + sqle.getLocalizedMessage()); + tempException = tempException.getNextException(); + } + throw new RuntimeException("SQL Exception in executePreparedQuery: ", sqle); + } finally { + try { + if (ps != null) { + ps.close(); + } + if (conn != null) { + conn.close(); + } + } catch (SQLException sqle) { + logger.debug("SQL Exception closing statement/connection in executePreparedQuery: " + sqle.getLocalizedMessage()); + return null; + } + } + } + + // FIXME: This method's code significantly overlaps that of executePrepareQuery(), above, + // and the two could be refactored into a single method, if desired. + public static List executePreparedQueries(final List builders, + String dataSourceName, String repositoryName, String cspaceInstanceId, Boolean executeWithinTransaction) throws Exception { + Connection conn = null; + PreparedStatement ps = null; + List results = new ArrayList<>(); + try { + conn = getConnection(dataSourceName, repositoryName, cspaceInstanceId); + if (executeWithinTransaction) { + conn.setAutoCommit(false); + } + RowSetFactory rowSetFactory = RowSetProvider.newFactory(); + CachedRowSet crs = rowSetFactory.createCachedRowSet(); + int statementCount = 0; + for (PreparedStatementBuilder builder : builders) { + ps = builder.build(conn); + // FIXME: transition this log statement to DEBUG level when appropriate + if (logger.isInfoEnabled()) { + statementCount++; + logger.info("prepared statement " + statementCount + "=" + ps.toString()); + } + // Try executing each statement, first as a query, then as an update + try { + ResultSet resultSet = ps.executeQuery(); + if (resultSet != null) { + crs.populate(resultSet); + results.add(crs); + } + } catch (Exception e) { + int rowcount = ps.executeUpdate(); + logger.debug(String.format("Row count for builder %s is %d", ps.toString(), rowcount)); + // Throw uncaught exception here if update attempt also fails + } + } + return results; + } catch (SQLException sqle) { + if (executeWithinTransaction && conn != null) { + conn.rollback(); + } + SQLException tempException = sqle; + while (null != tempException) { // SQLExceptions can be chained. Loop to log all. + logger.debug("SQL Exception: " + sqle.getLocalizedMessage()); + tempException = tempException.getNextException(); + } + throw new RuntimeException("SQL Exception in executePreparedQueries: ", sqle); + } finally { + try { + if (ps != null) { + ps.close(); + } + if (conn != null) { + if (executeWithinTransaction) { + conn.commit(); + } + conn.close(); + } + } catch (SQLException sqle) { + logger.debug("SQL Exception closing statement/connection in executePreparedQueries: " + sqle.getLocalizedMessage()); + return null; + } + } + } + + public static int executeUpdate(String dataSourceName, + String repositoryName, + String cspaceInstanceId, + String sql) throws Exception { + Connection conn = null; + Statement stmt = null; + try { + conn = getConnection(dataSourceName, repositoryName, cspaceInstanceId); + stmt = conn.createStatement(); + int rows = stmt.executeUpdate(sql); + stmt.close(); + return rows; + } catch (RuntimeException rte) { + logger.debug("Exception in executeUpdate: " + rte.getLocalizedMessage()); + logger.debug(rte.getStackTrace().toString()); + throw rte; + } catch (SQLException sqle) { + SQLException tempException = sqle; + String msg = ""; + while (null != tempException) { // SQLExceptions can be chained. Loop to log all. + if (!msg.isEmpty()) { + msg = msg + "::next::"; + } + msg = msg + sqle.getLocalizedMessage(); + logger.debug("SQL Exception: " + msg); + tempException = tempException.getNextException(); + } + throw new RuntimeException("SQL Exception in executeUpdate: " + msg, sqle); + } finally { + try { + if (stmt != null) { + stmt.close(); + } + if (conn != null) { + conn.close(); + } + } catch (SQLException sqle) { + logger.debug("SQL Exception closing statement/connection in executeUpdate: " + sqle.getLocalizedMessage()); + return -1; + } + } + } + + /** + * Returns the database product name, from the metadata for a + * JDBC connection to the default repository. + * + * Assumes that the database product name will be the same for the + * default repository and for all other repositories to which JDBC + * connections will be made, through the methods of this class. + * + * @return the database product name + */ + public static String getDatabaseProductName(String dataSourceName, + String repositoryName, + String cspaceInstanceId) { + if (DBProductName == null) { + Connection conn = null; + try { + conn = getConnection(dataSourceName, repositoryName, cspaceInstanceId); + DBProductName = conn.getMetaData().getDatabaseProductName(); + } catch (Exception e) { + if (logger.isTraceEnabled() == true) { + logger.trace(String.format("Could not open a connection. DataSource='%s' DB='%s'.", + dataSourceName, repositoryName)); + } + } finally { + try { + if (conn != null) { + conn.close(); + } + } catch (SQLException sqle) { + logger.debug("SQL Exception closing statement/connection in getDatabaseProductName: " + + sqle.getLocalizedMessage()); + } + } + } + + return DBProductName; + } + + /** + * Returns an enumerated value uniquely identifying the database product type; + * e.g. MySQL, PostgreSQL, based on the database product name. + * + * @return an enumerated value identifying the database product type + * @throws Exception + */ + public static DatabaseProductType getDatabaseProductType(String dataSourceName, + String repositoryName, + String cspaceInstanceId) throws Exception { + DatabaseProductType result = DatabaseProductType.UNRECOGNIZED; + + String productName = getDatabaseProductName(dataSourceName, repositoryName, cspaceInstanceId); + if (productName.matches("(?i).*mysql.*")) { + result = DatabaseProductType.MYSQL; + } else if (productName.matches("(?i).*postgresql.*")) { + result = DatabaseProductType.POSTGRESQL; + } else { + throw new Exception("Unrecognized database system " + productName); + } + + return result; + } + + // + // Same as method above except the cspace instance ID is not needed. + // + public static DatabaseProductType getDatabaseProductType(String dataSourceName, + String repositoryName) throws Exception { + DatabaseProductType result = DatabaseProductType.UNRECOGNIZED; + + String productName = getDatabaseProductName(dataSourceName, repositoryName, null); + if (productName.matches("(?i).*mysql.*")) { + result = DatabaseProductType.MYSQL; + } else if (productName.matches("(?i).*postgresql.*")) { + result = DatabaseProductType.POSTGRESQL; + } else { + throw new Exception("Unrecognized database system " + productName); + } + + return result; + } + + /* + * By convention, the repository name and database name are the same. However, this + * call encapulates that convention and allows overrides. + */ + public static String getDatabaseName(String repoName, String cspaceInstanceId) { + String result = repoName; + + // + // Insert code here if you want to map the repo name to a database name -otherwise + // we'll assume they are the same thing. + // + if (repoName.equalsIgnoreCase(DEFAULT_NUXEO_REPOSITORY_NAME)) { + result = DEFAULT_NUXEO_DATABASE_NAME; + } + + // + // If we have a non-null 'cspaceInstanceId' instance ID then we need to append it + // as a suffix to the database name. + // + if (cspaceInstanceId != null && !cspaceInstanceId.trim().isEmpty()) { + if (result.endsWith(cspaceInstanceId) == false) { // ensure we don't already have the suffix + result = result + cspaceInstanceId; + } + } + + return result; + } + + /** + * Returns the catalog/database name for an open JDBC connection. + * + * @param conn an open JDBC Connection + * @return the catalog name. + * @throws SQLException + */ + public static String getDatabaseName(String dataSourceName, + String repositoryName, + String cspaceInstanceId, + Connection conn) throws Exception { + String databaseName = null; + + if (conn != null) { + DatabaseMetaData metadata = conn.getMetaData(); + String urlStr = metadata.getURL(); + + // Format of the PostgreSQL JDBC URL: + // http://jdbc.postgresql.org/documentation/80/connect.html + if (getDatabaseProductType(dataSourceName, repositoryName, cspaceInstanceId) == DatabaseProductType.POSTGRESQL) { + String tokens[] = urlStr.split(JDBC_URL_DATABASE_SEPARATOR); + databaseName = tokens[tokens.length - 1]; + // Format of the MySQL JDBC URL: + // http://dev.mysql.com/doc/refman/5.1/en/connector-j-reference-configuration-properties.html + // FIXME: the last token could contain optional parameters, not accounted for here. + } else if (getDatabaseProductType(dataSourceName, repositoryName, cspaceInstanceId) == DatabaseProductType.MYSQL) { + String tokens[] = urlStr.split(JDBC_URL_DATABASE_SEPARATOR); + databaseName = tokens[tokens.length - 1]; + } + } + + return databaseName; + } + + /** + * Grant a specified privilege to a database user. This privilege will + * be applied to all 'public' schema tables within the specified repository. + * + * @param dataSourceName a JDBC datasource name. + * @param repositoryName a repository (e.g. RDBMS database) name. + * @param cspaceInstanceId a CollectionSpace instance identifier. + * @param privilegeName a database privilege (e.g. SELECT) to be granted. + * @param databaseUserName a database user to receive the privilege grant. + */ + public static void grantPrivilegeToDatabaseUser(String dataSourceName, String repositoryName, + String cspaceInstanceId, String privilegeName, String databaseUserName) { + Statement stmt = null; + Connection conn = null; + String sql = String.format("GRANT %s ON ALL TABLES IN SCHEMA public TO %s", privilegeName, databaseUserName); + try { + DatabaseProductType databaseProductType = JDBCTools.getDatabaseProductType(dataSourceName, repositoryName, + cspaceInstanceId); + if (databaseProductType == DatabaseProductType.MYSQL) { + // Nothing to do here: MYSQL already does wildcard grants in init_db.sql + } else if(databaseProductType != DatabaseProductType.POSTGRESQL) { + throw new Exception("Unrecognized database system " + databaseProductType); + } else { + String databaseName = JDBCTools.getDatabaseName(repositoryName, cspaceInstanceId); + // Verify that the database user exists before executing the grant + if (hasDatabaseUser(dataSourceName, repositoryName, cspaceInstanceId, + databaseProductType, databaseUserName)) { + conn = getConnection(dataSourceName, repositoryName, cspaceInstanceId); + stmt = conn.createStatement(); + stmt.execute(sql); + } + } + + } catch (SQLException sqle) { + SQLException tempException = sqle; + // SQLExceptions can be chained. Loop to log all. + while (null != tempException) { + logger.debug("SQL Exception: " + sqle.getLocalizedMessage()); + tempException = tempException.getNextException(); + } + logger.debug("SQL problem in executeQuery: ", sqle); + } catch (Throwable e) { + logger.debug(String.format("Problem granting privileges to database user: %s SQL: %s ERROR: %s", + databaseUserName, sql, e)); + } finally { + try { + if (stmt != null) { + stmt.close(); + } + if (conn != null) { + conn.close(); + } + } catch (SQLException sqle) { + // nothing we can do here except log + logger.warn("SQL Exception when closing statement/connection: " + sqle.getLocalizedMessage()); + } + } + } + + /** + * Create a database user, if that user doesn't already exist. + * + * @param conn a database connection. + * @param dbType a database product type. + * @param username the name of the database user to create. + * @param userPW the initial password for that database user. + */ + public static void createNewDatabaseUser(String dataSourceName, String repositoryName, + String cspaceInstanceId, DatabaseProductType dbType, String username, String userPW) throws Exception { + Statement stmt = null; + Connection conn = null; + if (dbType != DatabaseProductType.POSTGRESQL) { + throw new UnsupportedOperationException("createNewDatabaseUser only supports PostgreSQL"); + } + try { + if (hasDatabaseUser(dataSourceName, repositoryName, cspaceInstanceId, dbType, username)) { + if (logger.isDebugEnabled()) { + logger.debug("User: " + username + " already exists."); + } + } else { + conn = getConnection(dataSourceName, repositoryName, cspaceInstanceId); + stmt = conn.createStatement(); + String sql = "CREATE ROLE " + username + " WITH PASSWORD '" + userPW + "' LOGIN"; + stmt.executeUpdate(sql); + if (logger.isDebugEnabled()) { + logger.debug("Created User: " + username); + } + } + } catch (Exception e) { + logger.error("createNewDatabaseUser failed on exception: " + e.getLocalizedMessage()); + throw e; + } finally { + try { + if (stmt != null) { + stmt.close(); + } + if (conn != null) { + conn.close(); + } + } catch (SQLException sqle) { + // nothing we can do here except log + logger.warn("SQL Exception when closing statement/connection: " + sqle.getLocalizedMessage()); + } + } + } + + /** + * Identify whether a database exists. + * + * @param dbType a database product type. + * @param dbName a database product name. + * @return true if a database with that name exists, false if that database does not exit. + * @throws Exception + */ + public static boolean hasDatabase(DatabaseProductType dbType, String dbName) throws Exception { + PreparedStatement pstmt = null; + Connection conn = null; + String dbExistsQuery = ""; + if (dbType == DatabaseProductType.POSTGRESQL) { + dbExistsQuery = "SELECT 1 AS result FROM pg_database WHERE datname=?"; + } else if (dbType == DatabaseProductType.MYSQL) { + dbExistsQuery = "SELECT 1 AS result FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=?"; + } else { + throw new UnsupportedOperationException("hasDatabase encountered unknown database product type"); + } + try { + DataSource csadminDataSource = JDBCTools.getDataSource(JDBCTools.CSADMIN_DATASOURCE_NAME); + conn = csadminDataSource.getConnection(); + pstmt = conn.prepareStatement(dbExistsQuery); // create a statement + pstmt.setString(1, dbName); // set dbName param + ResultSet rs = pstmt.executeQuery(); + // extract data from the ResultSet + boolean dbExists = rs.next(); // Will return a value of 1 if database exists + rs.close(); + return dbExists; + } catch (Exception e) { + logger.error("hasDatabase failed on exception: " + e.getLocalizedMessage()); + throw e; + } finally { + try { + if (pstmt != null) { + pstmt.close(); + } + if (conn != null) { + conn.close(); + } + } catch (SQLException sqle) { + // nothing we can do here except log + logger.warn("SQL Exception when closing statement/connection: " + sqle.getLocalizedMessage()); + } + } + } + + /** + * Identify whether a database user exists. + * + * @param dataSourceName a JDBC datasource name. + * @param repositoryName a repository (e.g. RDBMS database) name. + * @param cspaceInstanceId a CollectionSpace instance identifier. + * @param dbType a database product type. + * @param username the name of the database user to create. + * @param userPW the initial password for that database user. + * @return true if a database user with that name exists, false if that user does not exist. + * @throws Exception + */ + public static boolean hasDatabaseUser(String dataSourceName, String repositoryName, + String cspaceInstanceId, DatabaseProductType dbType, String username) throws Exception { + PreparedStatement pstmt = null; + Statement stmt = null; + Connection conn = null; + final String USER_EXISTS_QUERY_POSTGRESQL = "SELECT 1 AS result FROM pg_roles WHERE rolname=?"; + if (dbType != DatabaseProductType.POSTGRESQL) { + throw new UnsupportedOperationException("hasDatabaseUser only supports PostgreSQL"); + } + try { + conn = getConnection(dataSourceName, repositoryName, cspaceInstanceId); + pstmt = conn.prepareStatement(USER_EXISTS_QUERY_POSTGRESQL); + pstmt.setString(1, username); + ResultSet rs = pstmt.executeQuery(); + boolean userExists = rs.next(); // Will return a value of 1 if user exists + rs.close(); + return userExists; + } catch (Exception e) { + logger.error("hasDatabaseUser failed on exception: " + e.getLocalizedMessage()); + throw e; + } finally { + try { + if (pstmt != null) { + pstmt.close(); + } + if (stmt != null) { + stmt.close(); + } + if (conn != null) { + conn.close(); + } + } catch (SQLException sqle) { + // nothing we can do here except log + logger.warn("SQL Exception when closing statement/connection: " + sqle.getLocalizedMessage()); + } + } + } + + + // ----------------------------- + // Utility methods for debugging + // ----------------------------- + + /** + * Prints metadata, such as database username and connection URL, + * for an open JDBC connection. This is a utility method for use + * during debugging. + * + * @param conn an open JDBC Connection + * @throws SQLException + */ + private static void printConnectionMetaData(Connection conn) throws SQLException { + if (conn != null) { + DatabaseMetaData metadata = conn.getMetaData(); + // FIXME: Outputs via System.out, rather than Logger, for + // cases where this may be called during server startup. + System.out.println("username=" + metadata.getUserName()); + System.out.println("database url=" + metadata.getURL()); + } + } + + /** + * Prints metadata related to a JDBC ResultSet, such as column names. + * This is a utility method for use during debugging. + * + * @param rs a ResultSet. + * @throws SQLException + */ + public static void printResultSetMetaData(ResultSet rs) throws SQLException { + if (rs == null) { + return; + } + ResultSetMetaData metadata = rs.getMetaData(); + if (metadata == null) { + return; + } + int numberOfColumns = metadata.getColumnCount(); + for (int i = 1; i <= numberOfColumns; i++) { + logger.debug(metadata.getColumnName(i)); + // Insert other debug statements to retrieve additional per-column metadata here ... + } + } + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaDocumentHandler.java b/services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaDocumentHandler.java index 49e4f9155..65f577013 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaDocumentHandler.java +++ b/services/common/src/main/java/org/collectionspace/services/common/storage/jpa/JpaDocumentHandler.java @@ -1,74 +1,74 @@ -package org.collectionspace.services.common.storage.jpa; - -import java.util.List; - -import org.collectionspace.services.common.api.RefName; -import org.collectionspace.services.common.document.AbstractDocumentHandlerImpl; -import org.collectionspace.services.common.document.DocumentFilter; -import org.collectionspace.services.common.document.DocumentWrapper; -import org.collectionspace.services.jaxb.AbstractCommonList; -import org.collectionspace.services.lifecycle.Lifecycle; -import org.collectionspace.services.lifecycle.TransitionDef; -import org.nuxeo.ecm.core.api.DocumentModel; - -public abstract class JpaDocumentHandler - extends AbstractDocumentHandlerImpl{ - - @Override - protected String getRefnameDisplayName(DocumentWrapper wrapDoc) { - return ""; // Empty string since we don't yet support this feature in JPA documents - } - - @Override - public RefName.RefNameInterface getRefName(DocumentWrapper docWrapper, String tenantName, String serviceName) { - // - // Not implemented - // - return null; - } - - /** - * Extract paging info. - * - * @param commonsList the commons list - * @return the tL - * @throws Exception the exception - */ - public TL extractPagingInfo(TL theCommonList, DocumentWrapper wrapDoc) - throws Exception { - AbstractCommonList commonList = (AbstractCommonList) theCommonList; - - DocumentFilter docFilter = this.getDocumentFilter(); - long pageSize = docFilter.getPageSize(); - long pageNum = pageSize != 0 ? docFilter.getOffset() / pageSize : pageSize; - // set the page size and page number - commonList.setPageNum(pageNum); - commonList.setPageSize(pageSize); - List docList = (List)wrapDoc.getWrappedObject(); - // Set num of items in list. this is useful to our testing framework. - commonList.setItemsInPage(docList.size()); - // set the total result size - commonList.setTotalItems(docList.size()); - - return (TL) commonList; - } - - public Lifecycle getLifecycle(String docTypeName) { - Lifecycle result = new Lifecycle(); - result.setName("Life cycles are not supported by the JPA-based services."); - return result; // NOTE: As of 3/2012, none of the JPA-based services support a life cycle type. - } - - @Override - public Lifecycle getLifecycle() { - return getLifecycle(null); // NOTE: As of 3/2012, none of the JPA-based services support a life cycle type. - } - - @Override - public void handleWorkflowTransition( - DocumentWrapper wrapDoc, TransitionDef transitionDef) - throws Exception { - // Do nothing. JPA document handlers do not support workflow transitions yet. - } - -} +package org.collectionspace.services.common.storage.jpa; + +import java.util.List; + +import org.collectionspace.services.common.api.RefName; +import org.collectionspace.services.common.document.AbstractDocumentHandlerImpl; +import org.collectionspace.services.common.document.DocumentFilter; +import org.collectionspace.services.common.document.DocumentWrapper; +import org.collectionspace.services.jaxb.AbstractCommonList; +import org.collectionspace.services.lifecycle.Lifecycle; +import org.collectionspace.services.lifecycle.TransitionDef; +import org.nuxeo.ecm.core.api.DocumentModel; + +public abstract class JpaDocumentHandler + extends AbstractDocumentHandlerImpl{ + + @Override + protected String getRefnameDisplayName(DocumentWrapper wrapDoc) { + return ""; // Empty string since we don't yet support this feature in JPA documents + } + + @Override + public RefName.RefNameInterface getRefName(DocumentWrapper docWrapper, String tenantName, String serviceName) { + // + // Not implemented + // + return null; + } + + /** + * Extract paging info. + * + * @param commonsList the commons list + * @return the tL + * @throws Exception the exception + */ + public TL extractPagingInfo(TL theCommonList, DocumentWrapper wrapDoc) + throws Exception { + AbstractCommonList commonList = (AbstractCommonList) theCommonList; + + DocumentFilter docFilter = this.getDocumentFilter(); + long pageSize = docFilter.getPageSize(); + long pageNum = pageSize != 0 ? docFilter.getOffset() / pageSize : pageSize; + // set the page size and page number + commonList.setPageNum(pageNum); + commonList.setPageSize(pageSize); + List docList = (List)wrapDoc.getWrappedObject(); + // Set num of items in list. this is useful to our testing framework. + commonList.setItemsInPage(docList.size()); + // set the total result size + commonList.setTotalItems(docList.size()); + + return (TL) commonList; + } + + public Lifecycle getLifecycle(String docTypeName) { + Lifecycle result = new Lifecycle(); + result.setName("Life cycles are not supported by the JPA-based services."); + return result; // NOTE: As of 3/2012, none of the JPA-based services support a life cycle type. + } + + @Override + public Lifecycle getLifecycle() { + return getLifecycle(null); // NOTE: As of 3/2012, none of the JPA-based services support a life cycle type. + } + + @Override + public void handleWorkflowTransition( + DocumentWrapper wrapDoc, TransitionDef transitionDef) + throws Exception { + // Do nothing. JPA document handlers do not support workflow transitions yet. + } + +} diff --git a/services/common/src/main/java/org/collectionspace/services/common/vocabulary/RefNameServiceUtils.java b/services/common/src/main/java/org/collectionspace/services/common/vocabulary/RefNameServiceUtils.java index 96d6fc649..8f1174659 100644 --- a/services/common/src/main/java/org/collectionspace/services/common/vocabulary/RefNameServiceUtils.java +++ b/services/common/src/main/java/org/collectionspace/services/common/vocabulary/RefNameServiceUtils.java @@ -1,983 +1,983 @@ -/** - * 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.vocabulary; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -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.Property; -import org.nuxeo.ecm.core.api.model.PropertyException; -import org.nuxeo.ecm.core.api.model.PropertyNotFoundException; -import org.nuxeo.ecm.core.api.model.impl.primitives.StringProperty; -import org.nuxeo.ecm.core.api.repository.RepositoryInstance; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.collectionspace.services.client.CollectionSpaceClient; -import org.collectionspace.services.client.IQueryManager; -import org.collectionspace.services.client.IRelationsManager; -import org.collectionspace.services.client.PoxPayloadIn; -import org.collectionspace.services.client.PoxPayloadOut; -import org.collectionspace.services.common.ServiceMain; -import org.collectionspace.services.common.StoredValuesUriTemplate; -import org.collectionspace.services.common.UriTemplateFactory; -import org.collectionspace.services.common.UriTemplateRegistry; -import org.collectionspace.services.common.UriTemplateRegistryKey; -import org.collectionspace.services.common.context.ServiceContext; -import org.collectionspace.services.common.context.AbstractServiceContextImpl; -import org.collectionspace.services.common.api.RefNameUtils; -import org.collectionspace.services.common.api.Tools; -import org.collectionspace.services.common.api.RefNameUtils.AuthorityTermInfo; -import org.collectionspace.services.common.authorityref.AuthorityRefDocList; -import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl; -import org.collectionspace.services.common.context.ServiceBindingUtils; -import org.collectionspace.services.common.document.DocumentException; -import org.collectionspace.services.common.document.DocumentFilter; -import org.collectionspace.services.common.document.DocumentNotFoundException; -import org.collectionspace.services.common.document.DocumentUtils; -import org.collectionspace.services.common.document.DocumentWrapper; -import org.collectionspace.services.common.query.QueryManager; -import org.collectionspace.services.common.relation.RelationUtils; -import org.collectionspace.services.common.repository.RepositoryClient; -import org.collectionspace.services.nuxeo.client.java.DocHandlerBase; -import org.collectionspace.services.nuxeo.client.java.RepositoryInstanceInterface; -import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl; -import org.collectionspace.services.common.security.SecurityUtils; -import org.collectionspace.services.config.service.ServiceBindingType; -import org.collectionspace.services.jaxb.AbstractCommonList; -import org.collectionspace.services.nuxeo.util.NuxeoUtils; - -/** - * RefNameServiceUtils is a collection of services utilities related to refName - * usage. - * - * $LastChangedRevision: $ $LastChangedDate: $ - */ -public class RefNameServiceUtils { - - public static class AuthRefConfigInfo { - - public String getQualifiedDisplayName() { - return (Tools.isBlank(schema)) - ? displayName : DocumentUtils.appendSchemaName(schema, displayName); - } - - public String getDisplayName() { - return displayName; - } - - public void setDisplayName(String displayName) { - this.displayName = displayName; - } - String displayName; - String schema; - - public String getSchema() { - return schema; - } - - public void setSchema(String schema) { - this.schema = schema; - } - - public String getFullPath() { - return fullPath; - } - - public void setFullPath(String fullPath) { - this.fullPath = fullPath; - } - String fullPath; - protected String[] pathEls; - - public AuthRefConfigInfo(AuthRefConfigInfo arci) { - this.displayName = arci.displayName; - this.schema = arci.schema; - this.fullPath = arci.fullPath; - this.pathEls = arci.pathEls; - // Skip the pathElse check, since we are creatign from another (presumably valid) arci. - } - - public AuthRefConfigInfo(String displayName, String schema, String fullPath, String[] pathEls) { - this.displayName = displayName; - this.schema = schema; - this.fullPath = fullPath; - this.pathEls = pathEls; - checkPathEls(); - } - - // Split a config value string like "intakes_common:collector", or - // "collectionobjects_common:contentPeoples|contentPeople" - // "collectionobjects_common:assocEventGroupList/*/assocEventPlace" - // If has a pipe ('|') second part is a displayLabel, and first is path - // Otherwise, entry is a path, and can use the last pathElement as displayName - // Should be schema qualified. - public AuthRefConfigInfo(String configString) { - String[] pair = configString.split("\\|", 2); - String[] pathEls; - String displayName, fullPath; - if (pair.length == 1) { - // no label specifier, so we'll defer getting label - fullPath = pair[0]; - pathEls = pair[0].split("/"); - displayName = pathEls[pathEls.length - 1]; - } else { - fullPath = pair[0]; - pathEls = pair[0].split("/"); - displayName = pair[1]; - } - String[] schemaSplit = pathEls[0].split(":", 2); - String schema; - if (schemaSplit.length == 1) { // schema not specified - schema = null; - } else { - schema = schemaSplit[0]; - if (pair.length == 1 && pathEls.length == 1) { // simplest case of field in top level schema, no labelll - displayName = schemaSplit[1]; // Have to fix up displayName to have no schema - } - } - this.displayName = displayName; - this.schema = schema; - this.fullPath = fullPath; - this.pathEls = pathEls; - checkPathEls(); - } - - protected void checkPathEls() { - int len = pathEls.length; - if (len < 1) { - throw new InternalError("Bad values in authRef info - caller screwed up:" + fullPath); - } - // Handle case of them putting a leading slash on the path - if (len > 1 && pathEls[0].endsWith(":")) { - len--; - String[] newArray = new String[len]; - newArray[0] = pathEls[0] + pathEls[1]; - if (len >= 2) { - System.arraycopy(pathEls, 2, newArray, 1, len - 1); - } - pathEls = newArray; - } - } - } - - public static class AuthRefInfo extends AuthRefConfigInfo { - - public Property getProperty() { - return property; - } - - public void setProperty(Property property) { - this.property = property; - } - Property property; - - public AuthRefInfo(String displayName, String schema, String fullPath, String[] pathEls, Property prop) { - super(displayName, schema, fullPath, pathEls); - this.property = prop; - } - - public AuthRefInfo(AuthRefConfigInfo arci, Property prop) { - super(arci); - this.property = prop; - } - } - - private static final Logger logger = LoggerFactory.getLogger(RefNameServiceUtils.class); - private static ArrayList refNameServiceTypes = null; - - public static void updateRefNamesInRelations( - ServiceContext ctx, - RepositoryClient repoClient, - RepositoryInstanceInterface repoSession, - String oldRefName, - String newRefName) throws Exception { - // - // First, look for and update all the places where the refName is the "subject" of the relationship - // - RelationUtils.updateRefNamesInRelations(ctx, repoClient, repoSession, IRelationsManager.SUBJECT_REFNAME, oldRefName, newRefName); - - // - // Next, look for and update all the places where the refName is the "object" of the relationship - // - RelationUtils.updateRefNamesInRelations(ctx, repoClient, repoSession, IRelationsManager.OBJECT_REFNAME, oldRefName, newRefName); - } - - public static List getConfiguredAuthorityRefs(ServiceContext ctx) { - List authRefFields = - ((AbstractServiceContextImpl) ctx).getAllPartsPropertyValues( - ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES); - ArrayList authRefsInfo = new ArrayList(authRefFields.size()); - for (String spec : authRefFields) { - AuthRefConfigInfo arci = new AuthRefConfigInfo(spec); - authRefsInfo.add(arci); - } - return authRefsInfo; - } - - public static AuthorityRefDocList getAuthorityRefDocs( - RepositoryInstanceInterface repoSession, - ServiceContext ctx, - UriTemplateRegistry uriTemplateRegistry, - RepositoryClient repoClient, - List serviceTypes, - String refName, - String refPropName, // authRef or termRef, authorities or vocab terms. - DocumentFilter filter, boolean computeTotal) - throws DocumentException, DocumentNotFoundException { - AuthorityRefDocList wrapperList = new AuthorityRefDocList(); - AbstractCommonList commonList = (AbstractCommonList) wrapperList; - int pageNum = filter.getStartPage(); - int pageSize = filter.getPageSize(); - - List list = - wrapperList.getAuthorityRefDocItem(); - - Map queriedServiceBindings = new HashMap(); - Map> authRefFieldsByService = new HashMap>(); - - RepositoryJavaClientImpl nuxeoRepoClient = (RepositoryJavaClientImpl) repoClient; - try { - // Ignore any provided page size and number query parameters in - // the following call, as they pertain to the list of authority - // references to be returned, not to the list of documents to be - // scanned for those references. - - // Get a list of possibly referencing documents. This list is - // lazily loaded, page by page. Ideally, only one page will - // need to be loaded to fill one page of results. Some number - // of possibly referencing documents will be false positives, - // so use a page size of double the requested page size to - // account for those. - DocumentModelList docList = findAllAuthorityRefDocs(ctx, repoClient, repoSession, - serviceTypes, refName, refPropName, queriedServiceBindings, authRefFieldsByService, - filter.getWhereClause(), null, 2*pageSize, computeTotal); - - if (docList == null) { // found no authRef fields - nothing to process - return wrapperList; - } - - // set the fieldsReturned list. Even though this is a fixed schema, app layer treats - // this like other abstract common lists - /* - * - * - * - * - * - * - * - * - * - */ - String fieldList = "docType|docId|docNumber|docName|sourceField|uri|refName|updatedAt|workflowState"; - commonList.setFieldsReturned(fieldList); - - // As a side-effect, the method called below modifies the value of - // the 'list' variable, which holds the list of references to - // an authority item. - // - // There can be more than one reference to a particular authority - // item within any individual document scanned, so the number of - // authority references may potentially exceed the total number - // of documents scanned. - - // Strip off displayName and only match the base, so we get references to all - // the NPTs as well as the PT. - String strippedRefName = RefNameUtils.stripAuthorityTermDisplayName(refName); - - // *** Need to pass in pagination info here. - int nRefsFound = processRefObjsDocListForList(docList, ctx.getTenantId(), strippedRefName, - queriedServiceBindings, authRefFieldsByService, // the actual list size needs to be updated to the size of "list" - list, pageSize, pageNum); - - commonList.setPageSize(pageSize); - - // Values returned in the pagination block above the list items - // need to reflect the number of references to authority items - // returned, rather than the number of documents originally scanned - // to find such references. - // This will be an estimate only... - commonList.setPageNum(pageNum); - commonList.setTotalItems(nRefsFound); // Accurate if total was scanned, otherwise, just an estimate - commonList.setItemsInPage(list.size()); - - /* Pagination is now handled in the processing step - // Slice the list to return only the specified page of items - // in the list results. - // - // FIXME: There may well be a pattern-based way to do this - // in our framework, and if we can eliminate much of the - // non-DRY code below, that would be desirable. - - int startIndex = 0; - int endIndex = 0; - - // Return all results if pageSize is 0. - if (pageSize == 0) { - startIndex = 0; - endIndex = list.size(); - } else { - startIndex = pageNum * pageSize; - } - - // Return an empty list when the start of the requested page is - // beyond the last item in the list. - if (startIndex > list.size()) { - wrapperList.getAuthorityRefDocItem().clear(); - commonList.setItemsInPage(wrapperList.getAuthorityRefDocItem().size()); - return wrapperList; - } - - // Otherwise, return a list of items from the start of the specified - // page through the last item on that page, or otherwise through the - // last item in the entire list, if that occurs earlier than the end - // of the specified page. - if (endIndex == 0) { - int pageEndIndex = ((startIndex + pageSize)); - endIndex = (pageEndIndex > list.size()) ? list.size() : pageEndIndex; - } - - // Slice the list to return only the specified page of results. - // Note: the second argument to List.subList(), endIndex, is - // exclusive of the item at its index position, reflecting the - // zero-index nature of the list. - List currentPageList = - new ArrayList(list.subList(startIndex, endIndex)); - wrapperList.getAuthorityRefDocItem().clear(); - wrapperList.getAuthorityRefDocItem().addAll(currentPageList); - commonList.setItemsInPage(currentPageList.size()); - */ - - if (logger.isDebugEnabled() && (nRefsFound < docList.size())) { - logger.debug("Internal curiosity: got fewer matches of refs than # docs matched..."); // We found a ref to ourself and have excluded it. - } - } catch (Exception e) { - logger.error("Could not retrieve a list of documents referring to the specified authority item", e); - wrapperList = null; - } - - return wrapperList; - } - - private static ArrayList getRefNameServiceTypes() { - if (refNameServiceTypes == null) { - refNameServiceTypes = new ArrayList(); - refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_AUTHORITY); - refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_OBJECT); - refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_PROCEDURE); - } - return refNameServiceTypes; - } - - // Seems like a good value - no real data to set this well. - // Note: can set this value lower during debugging; e.g. to 3 - ADR 2012-07-10 - private static final int N_OBJS_TO_UPDATE_PER_LOOP = 100; - - public static int updateAuthorityRefDocs( - ServiceContext ctx, - RepositoryClient repoClient, - RepositoryInstanceInterface repoSession, - String oldRefName, - String newRefName, - String refPropName) throws Exception { - Map queriedServiceBindings = new HashMap(); - Map> authRefFieldsByService = new HashMap>(); - - int docsScanned = 0; - int nRefsFound = 0; - int currentPage = 0; - int docsInCurrentPage = 0; - final String WHERE_CLAUSE_ADDITIONS_VALUE = null; - final String ORDER_BY_VALUE = CollectionSpaceClient.CORE_CREATED_AT // "collectionspace_core:createdAt"; - + ", " + IQueryManager.NUXEO_UUID; // CSPACE-6333: Add secondary sort on uuid, in case records have the same createdAt timestamp. - - if (repoClient instanceof RepositoryJavaClientImpl == false) { - throw new InternalError("updateAuthorityRefDocs() called with unknown repoClient type!"); - } - - try { // REM - How can we deal with transaction and timeout issues here? - final int pageSize = N_OBJS_TO_UPDATE_PER_LOOP; - DocumentModelList docList; - boolean morePages = true; - while (morePages) { - - docList = findAuthorityRefDocs(ctx, repoClient, repoSession, - getRefNameServiceTypes(), oldRefName, refPropName, - queriedServiceBindings, authRefFieldsByService, WHERE_CLAUSE_ADDITIONS_VALUE, ORDER_BY_VALUE, pageSize, currentPage, false); - - if (docList == null) { - logger.debug("updateAuthorityRefDocs: no documents could be found that referenced the old refName"); - break; - } - docsInCurrentPage = docList.size(); - logger.debug("updateAuthorityRefDocs: current page=" + currentPage + " documents included in page=" + docsInCurrentPage); - if (docsInCurrentPage == 0) { - logger.debug("updateAuthorityRefDocs: no more documents requiring refName updates could be found"); - break; - } - if (docsInCurrentPage < pageSize) { - logger.debug("updateAuthorityRefDocs: assuming no more documents requiring refName updates will be found, as docsInCurrentPage < pageSize"); - morePages = false; - } - - // Only match complete refNames - unless and until we decide how to resolve changes - // to NPTs we will defer that and only change PTs or refNames as passed in. - int nRefsFoundThisPage = processRefObjsDocListForUpdate(docList, ctx.getTenantId(), oldRefName, - queriedServiceBindings, authRefFieldsByService, // Perform the refName updates on the list of document models - newRefName); - if (nRefsFoundThisPage > 0) { - ((RepositoryJavaClientImpl) repoClient).saveDocListWithoutHandlerProcessing(ctx, repoSession, docList, true); // Flush the document model list out to Nuxeo storage - nRefsFound += nRefsFoundThisPage; - } - - // FIXME: Per REM, set a limit of num objects - something like - // 1000K objects - and also add a log Warning after some threshold - docsScanned += docsInCurrentPage; - if (morePages) { - currentPage++; - } - - } - } catch (Exception e) { - logger.error("Internal error updating the AuthorityRefDocs: " + e.getLocalizedMessage()); - logger.debug(Tools.errorToString(e, true)); - throw e; - } - logger.debug("updateAuthorityRefDocs replaced a total of " + nRefsFound + " authority references, within as many as " + docsScanned + " scanned document(s)"); - return nRefsFound; - } - - private static DocumentModelList findAllAuthorityRefDocs( - ServiceContext ctx, - RepositoryClient repoClient, - RepositoryInstanceInterface repoSession, List serviceTypes, - String refName, - String refPropName, - Map queriedServiceBindings, - Map> authRefFieldsByService, - String whereClauseAdditions, - String orderByClause, - int pageSize, - boolean computeTotal) throws DocumentException, DocumentNotFoundException { - - return new LazyAuthorityRefDocList(ctx, repoClient, repoSession, - serviceTypes, refName, refPropName, queriedServiceBindings, authRefFieldsByService, - whereClauseAdditions, orderByClause, pageSize, computeTotal); - } - - protected static DocumentModelList findAuthorityRefDocs( - ServiceContext ctx, - RepositoryClient repoClient, - RepositoryInstanceInterface repoSession, List serviceTypes, - String refName, - String refPropName, - Map queriedServiceBindings, - Map> authRefFieldsByService, - String whereClauseAdditions, - String orderByClause, - int pageSize, - int pageNum, - boolean computeTotal) throws DocumentException, DocumentNotFoundException { - - // Get the service bindings for this tenant - TenantBindingConfigReaderImpl tReader = - ServiceMain.getInstance().getTenantBindingConfigReader(); - // We need to get all the procedures, authorities, and objects. - List servicebindings = tReader.getServiceBindingsByType(ctx.getTenantId(), serviceTypes); - if (servicebindings == null || servicebindings.isEmpty()) { - logger.error("RefNameServiceUtils.getAuthorityRefDocs: No services bindings found, cannot proceed!"); - return null; - } - // Filter the list for current user rights - servicebindings = SecurityUtils.getReadableServiceBindingsForCurrentUser(servicebindings); - - ArrayList docTypes = new ArrayList(); - - String query = computeWhereClauseForAuthorityRefDocs(refName, refPropName, docTypes, servicebindings, // REM - Side effect that docTypes array gets set. Any others? - queriedServiceBindings, authRefFieldsByService); - if (query == null) { // found no authRef fields - nothing to query - return null; - } - // Additional qualifications, like workflow state - if (Tools.notBlank(whereClauseAdditions)) { - query += " AND " + whereClauseAdditions; - } - // Now we have to issue the search - RepositoryJavaClientImpl nuxeoRepoClient = (RepositoryJavaClientImpl) repoClient; - DocumentWrapper docListWrapper = nuxeoRepoClient.findDocs(ctx, repoSession, - docTypes, query, orderByClause, pageSize, pageNum, computeTotal); - // Now we gather the info for each document into the list and return - DocumentModelList docList = docListWrapper.getWrappedObject(); - return docList; - } - private static final boolean READY_FOR_COMPLEX_QUERY = true; - - private static String computeWhereClauseForAuthorityRefDocs( - String refName, - String refPropName, - ArrayList docTypes, - List servicebindings, - Map queriedServiceBindings, - Map> authRefFieldsByService) { - - boolean fFirst = true; - List authRefFieldPaths; - for (ServiceBindingType sb : servicebindings) { - // Gets the property names for each part, qualified with the part label (which - // is also the table name, the way that the repository works). - authRefFieldPaths = - ServiceBindingUtils.getAllPartsPropertyValues(sb, - refPropName, ServiceBindingUtils.QUALIFIED_PROP_NAMES); - if (authRefFieldPaths.isEmpty()) { - continue; - } - ArrayList authRefsInfo = new ArrayList(); - for (String spec : authRefFieldPaths) { - AuthRefConfigInfo arci = new AuthRefConfigInfo(spec); - authRefsInfo.add(arci); - } - - String docType = sb.getObject().getName(); - queriedServiceBindings.put(docType, sb); - authRefFieldsByService.put(docType, authRefsInfo); - docTypes.add(docType); - fFirst = false; - } - if (fFirst) { // found no authRef fields - nothing to query - return null; - } - // We used to build a complete matches query, but that was too complex. - // Just build a keyword query based upon some key pieces - the urn syntax elements and the shortID - // Note that this will also match the Item itself, but that will get filtered out when - // we compute actual matches. - AuthorityTermInfo authTermInfo = RefNameUtils.parseAuthorityTermInfo(refName); - - String keywords = RefNameUtils.URN_PREFIX - + " AND " + (authTermInfo.inAuthority.name != null - ? authTermInfo.inAuthority.name : authTermInfo.inAuthority.csid) - + " AND " + (authTermInfo.name != null - ? authTermInfo.name : authTermInfo.csid); - - String whereClauseStr = QueryManager.createWhereClauseFromKeywords(keywords); - - if (logger.isTraceEnabled()) { - logger.trace("The 'where' clause to find refObjs is: ", whereClauseStr); - } - - return whereClauseStr; - } - - // TODO there are multiple copies of this that should be put somewhere common. - protected static String getRefname(DocumentModel docModel) throws ClientException { - String result = (String)docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA, - CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME); - return result; - } - - private static int processRefObjsDocListForUpdate( - DocumentModelList docList, - String tenantId, - String refName, - Map queriedServiceBindings, - Map> authRefFieldsByService, - String newAuthorityRefName) { - return processRefObjsDocList(docList, tenantId, refName, false, queriedServiceBindings, - authRefFieldsByService, null, 0, 0, newAuthorityRefName); - } - - private static int processRefObjsDocListForList( - DocumentModelList docList, - String tenantId, - String refName, - Map queriedServiceBindings, - Map> authRefFieldsByService, - List list, - int pageSize, int pageNum) { - return processRefObjsDocList(docList, tenantId, refName, true, queriedServiceBindings, - authRefFieldsByService, list, pageSize, pageNum, null); - } - - - /* - * Runs through the list of found docs, processing them. If list is - * non-null, then processing means gather the info for items. If list is - * null, and newRefName is non-null, then processing means replacing and - * updating. If processing/updating, this must be called in the context of - * an open session, and caller must release Session after calling this. - * - */ - private static int processRefObjsDocList( - DocumentModelList docList, - String tenantId, - String refName, - boolean matchBaseOnly, - Map queriedServiceBindings, - Map> authRefFieldsByService, - List list, - int pageSize, int pageNum, // Only used when constructing a list. - String newAuthorityRefName) { - UriTemplateRegistry registry = ServiceMain.getInstance().getUriTemplateRegistry(); - Iterator iter = docList.iterator(); - int nRefsFoundTotal = 0; - boolean foundSelf = false; - - // When paginating results, we have to guess at the total. First guess is the number of docs returned - // by the query. However, this returns some false positives, so may be high. - // In addition, we can match multiple fields per doc, so this may be low. Fun, eh? - int nDocsReturnedInQuery = (int)docList.totalSize(); - int nDocsProcessed = 0; - int firstItemInPage = pageNum*pageSize; - while (iter.hasNext()) { - DocumentModel docModel = iter.next(); - AuthorityRefDocList.AuthorityRefDocItem ilistItem; - - String docType = docModel.getDocumentType().getName(); // REM - This will be a tentant qualified document type - docType = ServiceBindingUtils.getUnqualifiedTenantDocType(docType); - ServiceBindingType sb = queriedServiceBindings.get(docType); - if (sb == null) { - throw new RuntimeException( - "getAuthorityRefDocs: No Service Binding for docType: " + docType); - } - - if (list == null) { // no list - should be update refName case. - if (newAuthorityRefName == null) { - throw new InternalError("processRefObjsDocList() called with neither an itemList nor a new RefName!"); - } - ilistItem = null; - pageSize = 0; - firstItemInPage = 0; // Do not paginate if updating, rather than building list - } else { // Have a list - refObjs case - if (newAuthorityRefName != null) { - throw new InternalError("processRefObjsDocList() called with both an itemList and a new RefName!"); - } - if(firstItemInPage > 100) { - logger.warn("Processing a large offset (size:{}, num:{}) for refObjs - will be expensive!!!", - pageSize, pageNum); - } - // Note that we have to go through check all the fields to determine the actual page start - ilistItem = new AuthorityRefDocList.AuthorityRefDocItem(); - String csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString()); - try { - String itemRefName = getRefname(docModel); - ilistItem.setRefName(itemRefName); - } catch (ClientException ce) { - throw new RuntimeException( - "processRefObjsDocList: Problem fetching refName from item Object: " - + ce.getLocalizedMessage()); - } - ilistItem.setDocId(csid); - String uri = ""; - UriTemplateRegistryKey key = new UriTemplateRegistryKey(tenantId, docType); - StoredValuesUriTemplate template = registry.get(key); - if (template != null) { - Map additionalValues = new HashMap(); - if (template.getUriTemplateType() == UriTemplateFactory.RESOURCE) { - additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, csid); - uri = template.buildUri(additionalValues); - } else if (template.getUriTemplateType() == UriTemplateFactory.ITEM) { - try { - String inAuthorityCsid = (String) docModel.getPropertyValue("inAuthority"); // AuthorityItemJAXBSchema.IN_AUTHORITY - additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, inAuthorityCsid); - additionalValues.put(UriTemplateFactory.ITEM_IDENTIFIER_VAR, csid); - uri = template.buildUri(additionalValues); - } catch (Exception e) { - logger.warn("Could not extract inAuthority property from authority item record: " + e.getMessage()); - } - } else if (template.getUriTemplateType() == UriTemplateFactory.CONTACT) { - // FIXME: Generating contact sub-resource URIs requires additional work, - // as a follow-on to CSPACE-5271 - ADR 2012-08-16 - // Sets the default (empty string) value for uri, for now - } else { - logger.warn("Unrecognized URI template type = " + template.getUriTemplateType()); - // Sets the default (empty string) value for uri - } - } else { // (if template == null) - logger.warn("Could not retrieve URI template from registry via tenant ID " - + tenantId + " and docType " + docType); - // Sets the default (empty string) value for uri - } - ilistItem.setUri(uri); - try { - ilistItem.setWorkflowState(docModel.getCurrentLifeCycleState()); - ilistItem.setUpdatedAt(DocHandlerBase.getUpdatedAtAsString(docModel)); - } catch (Exception e) { - logger.error("Error getting core values for doc [" + csid + "]: " + e.getLocalizedMessage()); - } - ilistItem.setDocType(docType); - ilistItem.setDocNumber( - ServiceBindingUtils.getMappedFieldInDoc(sb, ServiceBindingUtils.OBJ_NUMBER_PROP, docModel)); - ilistItem.setDocName( - ServiceBindingUtils.getMappedFieldInDoc(sb, ServiceBindingUtils.OBJ_NAME_PROP, docModel)); - } - // Now, we have to loop over the authRefFieldsByService to figure - // out which field(s) matched this. - List matchingAuthRefFields = authRefFieldsByService.get(docType); - if (matchingAuthRefFields == null || matchingAuthRefFields.isEmpty()) { - throw new RuntimeException( - "getAuthorityRefDocs: internal logic error: can't fetch authRefFields for DocType."); - } - //String authRefAncestorField = ""; - //String authRefDescendantField = ""; - //String sourceField = ""; - - ArrayList foundProps = new ArrayList(); - try { - findAuthRefPropertiesInDoc(docModel, matchingAuthRefFields, refName, matchBaseOnly, foundProps); // REM - side effect that foundProps is set - if(!foundProps.isEmpty()) { - int nRefsFoundInDoc = 0; - for (RefNameServiceUtils.AuthRefInfo ari : foundProps) { - if (ilistItem != null) { - // So this is a true positive, and not a false one. We have to consider pagination now. - if(nRefsFoundTotal >= firstItemInPage) { // skipped enough already - if (nRefsFoundInDoc == 0) { // First one? - ilistItem.setSourceField(ari.getQualifiedDisplayName()); - } else { // duplicates from one object - ilistItem = cloneAuthRefDocItem(ilistItem, ari.getQualifiedDisplayName()); - } - list.add(ilistItem); - nRefsFoundInDoc++; // Only increment if processed, or clone logic above will fail - } - } else { // update refName case - Property propToUpdate = ari.getProperty(); - propToUpdate.setValue(newAuthorityRefName); - } - nRefsFoundTotal++; // Whether we processed or not, we found - essential to pagination logic - } - } else if(ilistItem != null) { - String docRefName = ilistItem.getRefName(); - if (matchBaseOnly? - (docRefName!=null && docRefName.startsWith(refName)) - :refName.equals(docRefName)) { - // We found the self for an item - foundSelf = true; - logger.debug("getAuthorityRefDocs: Result: " - + docType + " [" + NuxeoUtils.getCsid(docModel) - + "] appears to be self for: [" - + refName + "]"); - } else { - logger.debug("getAuthorityRefDocs: Result: " - + docType + " [" + NuxeoUtils.getCsid(docModel) - + "] does not reference [" - + refName + "]"); - } - } - } catch (ClientException ce) { - throw new RuntimeException( - "getAuthorityRefDocs: Problem fetching values from repo: " + ce.getLocalizedMessage()); - } - nDocsProcessed++; - // Done processing that doc. Are we done with the whole page? - // Note pageSize <=0 means do them all - if((pageSize > 0) && ((nRefsFoundTotal-firstItemInPage)>=pageSize)) { - // Quitting early, so we need to estimate the total. Assume one per doc - // for the rest of the docs we matched in the query - int unprocessedDocs = nDocsReturnedInQuery - nDocsProcessed; - if(unprocessedDocs>0) { - // We generally match ourselves in the keyword search. If we already saw ourselves - // then do not try to correct for this. Otherwise, decrement the total. - // Yes, this is fairly goofy, but the whole estimation mechanism is goofy. - if(!foundSelf) - unprocessedDocs--; - nRefsFoundTotal += unprocessedDocs; - } - break; - } - } // close while(iterator) - return nRefsFoundTotal; - } - - private static AuthorityRefDocList.AuthorityRefDocItem cloneAuthRefDocItem( - AuthorityRefDocList.AuthorityRefDocItem ilistItem, String sourceField) { - AuthorityRefDocList.AuthorityRefDocItem newlistItem = new AuthorityRefDocList.AuthorityRefDocItem(); - newlistItem.setDocId(ilistItem.getDocId()); - newlistItem.setDocName(ilistItem.getDocName()); - newlistItem.setDocNumber(ilistItem.getDocNumber()); - newlistItem.setDocType(ilistItem.getDocType()); - newlistItem.setUri(ilistItem.getUri()); - newlistItem.setSourceField(sourceField); - return newlistItem; - } - - public static List findAuthRefPropertiesInDoc( - DocumentModel docModel, - List authRefFieldInfo, - String refNameToMatch, - List foundProps) { - return findAuthRefPropertiesInDoc(docModel, authRefFieldInfo, - refNameToMatch, false, foundProps); - } - - public static List findAuthRefPropertiesInDoc( - DocumentModel docModel, - List authRefFieldInfo, - String refNameToMatch, - boolean matchBaseOnly, - List foundProps) { - // Assume that authRefFieldInfo is keyed by the field name (possibly mapped for UI) - // and the values are elPaths to the field, where intervening group structures in - // lists of complex structures are replaced with "*". Thus, valid paths include - // the following (note that the ServiceBindingUtils prepend schema names to configured values): - // "schemaname:fieldname" - // "schemaname:scalarlistname" - // "schemaname:complexfieldname/fieldname" - // "schemaname:complexlistname/*/fieldname" - // "schemaname:complexlistname/*/scalarlistname" - // "schemaname:complexlistname/*/complexfieldname/fieldname" - // "schemaname:complexlistname/*/complexlistname/*/fieldname" - // etc. - for (AuthRefConfigInfo arci : authRefFieldInfo) { - try { - // Get first property and work down as needed. - Property prop = docModel.getProperty(arci.pathEls[0]); - findAuthRefPropertiesInProperty(foundProps, prop, arci, 0, refNameToMatch, matchBaseOnly); - } catch (Exception e) { - logger.error("Problem fetching property: " + arci.pathEls[0]); - } - } - return foundProps; - } - - private static List findAuthRefPropertiesInProperty( - List foundProps, - Property prop, - AuthRefConfigInfo arci, - int pathStartIndex, // Supports recursion and we work down the path - String refNameToMatch, - boolean matchBaseOnly ) { - if (pathStartIndex >= arci.pathEls.length) { - throw new ArrayIndexOutOfBoundsException("Index = " + pathStartIndex + " for path: " - + arci.pathEls.toString()); - } - AuthRefInfo ari = null; - if (prop == null) { - return foundProps; - } - - if (prop instanceof StringProperty) { // scalar string - addARIifMatches(refNameToMatch, matchBaseOnly, arci, prop, foundProps); - } else if (prop instanceof List) { - List propList = (List) prop; - // run through list. Must either be list of Strings, or Complex - for (Property listItemProp : propList) { - if (listItemProp instanceof StringProperty) { - if (arci.pathEls.length - pathStartIndex != 1) { - logger.error("Configuration for authRefs does not match schema structure: " - + arci.pathEls.toString()); - break; - } else { - addARIifMatches(refNameToMatch, matchBaseOnly, arci, listItemProp, foundProps); - } - } else if (listItemProp.isComplex()) { - // Just recurse to handle this. Note that since this is a list of complex, - // which should look like listName/*/... we add 2 to the path start index - findAuthRefPropertiesInProperty(foundProps, listItemProp, arci, - pathStartIndex + 2, refNameToMatch, matchBaseOnly); - } else { - logger.error("Configuration for authRefs does not match schema structure: " - + arci.pathEls.toString()); - break; - } - } - } else if (prop.isComplex()) { - String localPropName = arci.pathEls[pathStartIndex]; - try { - Property localProp = prop.get(localPropName); - // Now just recurse, pushing down the path 1 step - findAuthRefPropertiesInProperty(foundProps, localProp, arci, - pathStartIndex, refNameToMatch, matchBaseOnly); - } catch (PropertyNotFoundException pnfe) { - logger.error("Could not find property: [" + localPropName + "] in path: " - + arci.getFullPath()); - // Fall through - ari will be null and we will continue... - } - } else { - logger.error("Configuration for authRefs does not match schema structure: " - + arci.pathEls.toString()); - } - - if (ari != null) { - foundProps.add(ari); //FIXME: REM - This is dead code. 'ari' is never touched after being initalized to null. Why? - } - - return foundProps; - } - - private static void addARIifMatches( - String refNameToMatch, - boolean matchBaseOnly, - AuthRefConfigInfo arci, - Property prop, - List foundProps) { - // Need to either match a passed refName - // OR have no refName to match but be non-empty - try { - String value = (String) prop.getValue(); - if (((refNameToMatch != null) && - (matchBaseOnly? - (value!=null && value.startsWith(refNameToMatch)) - :refNameToMatch.equals(value))) - || ((refNameToMatch == null) && Tools.notBlank(value))) { - // Found a match - logger.debug("Found a match on property: " + prop.getPath() + " with value: [" + value + "]"); - AuthRefInfo ari = new AuthRefInfo(arci, prop); - foundProps.add(ari); - } - } catch (PropertyException pe) { - logger.debug("PropertyException on: " + prop.getPath() + pe.getLocalizedMessage()); - } - } - - /* - * Identifies whether the refName was found in the supplied field. If passed - * a new RefName, will set that into fields in which the old one was found. - * - * Only works for: * Scalar fields * Repeatable scalar fields (aka - * multi-valued fields) - * - * Does not work for: * Structured fields (complexTypes) * Repeatable - * structured fields (repeatable complexTypes) private static int - * refNameFoundInField(String oldRefName, Property fieldValue, String - * newRefName) { int nFound = 0; if (fieldValue instanceof List) { - * List fieldValueList = (List) fieldValue; for (Property - * listItemValue : fieldValueList) { try { if ((listItemValue instanceof - * StringProperty) && - * oldRefName.equalsIgnoreCase((String)listItemValue.getValue())) { - * nFound++; if(newRefName!=null) { fieldValue.setValue(newRefName); } else - * { // We cannot quit after the first, if we are replacing values. // If we - * are just looking (not replacing), finding one is enough. break; } } } - * catch( PropertyException pe ) {} } } else { try { if ((fieldValue - * instanceof StringProperty) && - * oldRefName.equalsIgnoreCase((String)fieldValue.getValue())) { nFound++; - * if(newRefName!=null) { fieldValue.setValue(newRefName); } } } catch( - * PropertyException pe ) {} } return nFound; } - */ -} +/** + * 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.vocabulary; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +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.Property; +import org.nuxeo.ecm.core.api.model.PropertyException; +import org.nuxeo.ecm.core.api.model.PropertyNotFoundException; +import org.nuxeo.ecm.core.api.model.impl.primitives.StringProperty; +import org.nuxeo.ecm.core.api.repository.RepositoryInstance; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.collectionspace.services.client.CollectionSpaceClient; +import org.collectionspace.services.client.IQueryManager; +import org.collectionspace.services.client.IRelationsManager; +import org.collectionspace.services.client.PoxPayloadIn; +import org.collectionspace.services.client.PoxPayloadOut; +import org.collectionspace.services.common.ServiceMain; +import org.collectionspace.services.common.StoredValuesUriTemplate; +import org.collectionspace.services.common.UriTemplateFactory; +import org.collectionspace.services.common.UriTemplateRegistry; +import org.collectionspace.services.common.UriTemplateRegistryKey; +import org.collectionspace.services.common.context.ServiceContext; +import org.collectionspace.services.common.context.AbstractServiceContextImpl; +import org.collectionspace.services.common.api.RefNameUtils; +import org.collectionspace.services.common.api.Tools; +import org.collectionspace.services.common.api.RefNameUtils.AuthorityTermInfo; +import org.collectionspace.services.common.authorityref.AuthorityRefDocList; +import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl; +import org.collectionspace.services.common.context.ServiceBindingUtils; +import org.collectionspace.services.common.document.DocumentException; +import org.collectionspace.services.common.document.DocumentFilter; +import org.collectionspace.services.common.document.DocumentNotFoundException; +import org.collectionspace.services.common.document.DocumentUtils; +import org.collectionspace.services.common.document.DocumentWrapper; +import org.collectionspace.services.common.query.QueryManager; +import org.collectionspace.services.common.relation.RelationUtils; +import org.collectionspace.services.common.repository.RepositoryClient; +import org.collectionspace.services.nuxeo.client.java.DocHandlerBase; +import org.collectionspace.services.nuxeo.client.java.RepositoryInstanceInterface; +import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl; +import org.collectionspace.services.common.security.SecurityUtils; +import org.collectionspace.services.config.service.ServiceBindingType; +import org.collectionspace.services.jaxb.AbstractCommonList; +import org.collectionspace.services.nuxeo.util.NuxeoUtils; + +/** + * RefNameServiceUtils is a collection of services utilities related to refName + * usage. + * + * $LastChangedRevision: $ $LastChangedDate: $ + */ +public class RefNameServiceUtils { + + public static class AuthRefConfigInfo { + + public String getQualifiedDisplayName() { + return (Tools.isBlank(schema)) + ? displayName : DocumentUtils.appendSchemaName(schema, displayName); + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + String displayName; + String schema; + + public String getSchema() { + return schema; + } + + public void setSchema(String schema) { + this.schema = schema; + } + + public String getFullPath() { + return fullPath; + } + + public void setFullPath(String fullPath) { + this.fullPath = fullPath; + } + String fullPath; + protected String[] pathEls; + + public AuthRefConfigInfo(AuthRefConfigInfo arci) { + this.displayName = arci.displayName; + this.schema = arci.schema; + this.fullPath = arci.fullPath; + this.pathEls = arci.pathEls; + // Skip the pathElse check, since we are creatign from another (presumably valid) arci. + } + + public AuthRefConfigInfo(String displayName, String schema, String fullPath, String[] pathEls) { + this.displayName = displayName; + this.schema = schema; + this.fullPath = fullPath; + this.pathEls = pathEls; + checkPathEls(); + } + + // Split a config value string like "intakes_common:collector", or + // "collectionobjects_common:contentPeoples|contentPeople" + // "collectionobjects_common:assocEventGroupList/*/assocEventPlace" + // If has a pipe ('|') second part is a displayLabel, and first is path + // Otherwise, entry is a path, and can use the last pathElement as displayName + // Should be schema qualified. + public AuthRefConfigInfo(String configString) { + String[] pair = configString.split("\\|", 2); + String[] pathEls; + String displayName, fullPath; + if (pair.length == 1) { + // no label specifier, so we'll defer getting label + fullPath = pair[0]; + pathEls = pair[0].split("/"); + displayName = pathEls[pathEls.length - 1]; + } else { + fullPath = pair[0]; + pathEls = pair[0].split("/"); + displayName = pair[1]; + } + String[] schemaSplit = pathEls[0].split(":", 2); + String schema; + if (schemaSplit.length == 1) { // schema not specified + schema = null; + } else { + schema = schemaSplit[0]; + if (pair.length == 1 && pathEls.length == 1) { // simplest case of field in top level schema, no labelll + displayName = schemaSplit[1]; // Have to fix up displayName to have no schema + } + } + this.displayName = displayName; + this.schema = schema; + this.fullPath = fullPath; + this.pathEls = pathEls; + checkPathEls(); + } + + protected void checkPathEls() { + int len = pathEls.length; + if (len < 1) { + throw new InternalError("Bad values in authRef info - caller screwed up:" + fullPath); + } + // Handle case of them putting a leading slash on the path + if (len > 1 && pathEls[0].endsWith(":")) { + len--; + String[] newArray = new String[len]; + newArray[0] = pathEls[0] + pathEls[1]; + if (len >= 2) { + System.arraycopy(pathEls, 2, newArray, 1, len - 1); + } + pathEls = newArray; + } + } + } + + public static class AuthRefInfo extends AuthRefConfigInfo { + + public Property getProperty() { + return property; + } + + public void setProperty(Property property) { + this.property = property; + } + Property property; + + public AuthRefInfo(String displayName, String schema, String fullPath, String[] pathEls, Property prop) { + super(displayName, schema, fullPath, pathEls); + this.property = prop; + } + + public AuthRefInfo(AuthRefConfigInfo arci, Property prop) { + super(arci); + this.property = prop; + } + } + + private static final Logger logger = LoggerFactory.getLogger(RefNameServiceUtils.class); + private static ArrayList refNameServiceTypes = null; + + public static void updateRefNamesInRelations( + ServiceContext ctx, + RepositoryClient repoClient, + RepositoryInstanceInterface repoSession, + String oldRefName, + String newRefName) throws Exception { + // + // First, look for and update all the places where the refName is the "subject" of the relationship + // + RelationUtils.updateRefNamesInRelations(ctx, repoClient, repoSession, IRelationsManager.SUBJECT_REFNAME, oldRefName, newRefName); + + // + // Next, look for and update all the places where the refName is the "object" of the relationship + // + RelationUtils.updateRefNamesInRelations(ctx, repoClient, repoSession, IRelationsManager.OBJECT_REFNAME, oldRefName, newRefName); + } + + public static List getConfiguredAuthorityRefs(ServiceContext ctx) { + List authRefFields = + ((AbstractServiceContextImpl) ctx).getAllPartsPropertyValues( + ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES); + ArrayList authRefsInfo = new ArrayList(authRefFields.size()); + for (String spec : authRefFields) { + AuthRefConfigInfo arci = new AuthRefConfigInfo(spec); + authRefsInfo.add(arci); + } + return authRefsInfo; + } + + public static AuthorityRefDocList getAuthorityRefDocs( + RepositoryInstanceInterface repoSession, + ServiceContext ctx, + UriTemplateRegistry uriTemplateRegistry, + RepositoryClient repoClient, + List serviceTypes, + String refName, + String refPropName, // authRef or termRef, authorities or vocab terms. + DocumentFilter filter, boolean computeTotal) + throws DocumentException, DocumentNotFoundException { + AuthorityRefDocList wrapperList = new AuthorityRefDocList(); + AbstractCommonList commonList = (AbstractCommonList) wrapperList; + int pageNum = filter.getStartPage(); + int pageSize = filter.getPageSize(); + + List list = + wrapperList.getAuthorityRefDocItem(); + + Map queriedServiceBindings = new HashMap(); + Map> authRefFieldsByService = new HashMap>(); + + RepositoryJavaClientImpl nuxeoRepoClient = (RepositoryJavaClientImpl) repoClient; + try { + // Ignore any provided page size and number query parameters in + // the following call, as they pertain to the list of authority + // references to be returned, not to the list of documents to be + // scanned for those references. + + // Get a list of possibly referencing documents. This list is + // lazily loaded, page by page. Ideally, only one page will + // need to be loaded to fill one page of results. Some number + // of possibly referencing documents will be false positives, + // so use a page size of double the requested page size to + // account for those. + DocumentModelList docList = findAllAuthorityRefDocs(ctx, repoClient, repoSession, + serviceTypes, refName, refPropName, queriedServiceBindings, authRefFieldsByService, + filter.getWhereClause(), null, 2*pageSize, computeTotal); + + if (docList == null) { // found no authRef fields - nothing to process + return wrapperList; + } + + // set the fieldsReturned list. Even though this is a fixed schema, app layer treats + // this like other abstract common lists + /* + * + * + * + * + * + * + * + * + * + */ + String fieldList = "docType|docId|docNumber|docName|sourceField|uri|refName|updatedAt|workflowState"; + commonList.setFieldsReturned(fieldList); + + // As a side-effect, the method called below modifies the value of + // the 'list' variable, which holds the list of references to + // an authority item. + // + // There can be more than one reference to a particular authority + // item within any individual document scanned, so the number of + // authority references may potentially exceed the total number + // of documents scanned. + + // Strip off displayName and only match the base, so we get references to all + // the NPTs as well as the PT. + String strippedRefName = RefNameUtils.stripAuthorityTermDisplayName(refName); + + // *** Need to pass in pagination info here. + int nRefsFound = processRefObjsDocListForList(docList, ctx.getTenantId(), strippedRefName, + queriedServiceBindings, authRefFieldsByService, // the actual list size needs to be updated to the size of "list" + list, pageSize, pageNum); + + commonList.setPageSize(pageSize); + + // Values returned in the pagination block above the list items + // need to reflect the number of references to authority items + // returned, rather than the number of documents originally scanned + // to find such references. + // This will be an estimate only... + commonList.setPageNum(pageNum); + commonList.setTotalItems(nRefsFound); // Accurate if total was scanned, otherwise, just an estimate + commonList.setItemsInPage(list.size()); + + /* Pagination is now handled in the processing step + // Slice the list to return only the specified page of items + // in the list results. + // + // FIXME: There may well be a pattern-based way to do this + // in our framework, and if we can eliminate much of the + // non-DRY code below, that would be desirable. + + int startIndex = 0; + int endIndex = 0; + + // Return all results if pageSize is 0. + if (pageSize == 0) { + startIndex = 0; + endIndex = list.size(); + } else { + startIndex = pageNum * pageSize; + } + + // Return an empty list when the start of the requested page is + // beyond the last item in the list. + if (startIndex > list.size()) { + wrapperList.getAuthorityRefDocItem().clear(); + commonList.setItemsInPage(wrapperList.getAuthorityRefDocItem().size()); + return wrapperList; + } + + // Otherwise, return a list of items from the start of the specified + // page through the last item on that page, or otherwise through the + // last item in the entire list, if that occurs earlier than the end + // of the specified page. + if (endIndex == 0) { + int pageEndIndex = ((startIndex + pageSize)); + endIndex = (pageEndIndex > list.size()) ? list.size() : pageEndIndex; + } + + // Slice the list to return only the specified page of results. + // Note: the second argument to List.subList(), endIndex, is + // exclusive of the item at its index position, reflecting the + // zero-index nature of the list. + List currentPageList = + new ArrayList(list.subList(startIndex, endIndex)); + wrapperList.getAuthorityRefDocItem().clear(); + wrapperList.getAuthorityRefDocItem().addAll(currentPageList); + commonList.setItemsInPage(currentPageList.size()); + */ + + if (logger.isDebugEnabled() && (nRefsFound < docList.size())) { + logger.debug("Internal curiosity: got fewer matches of refs than # docs matched..."); // We found a ref to ourself and have excluded it. + } + } catch (Exception e) { + logger.error("Could not retrieve a list of documents referring to the specified authority item", e); + wrapperList = null; + } + + return wrapperList; + } + + private static ArrayList getRefNameServiceTypes() { + if (refNameServiceTypes == null) { + refNameServiceTypes = new ArrayList(); + refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_AUTHORITY); + refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_OBJECT); + refNameServiceTypes.add(ServiceBindingUtils.SERVICE_TYPE_PROCEDURE); + } + return refNameServiceTypes; + } + + // Seems like a good value - no real data to set this well. + // Note: can set this value lower during debugging; e.g. to 3 - ADR 2012-07-10 + private static final int N_OBJS_TO_UPDATE_PER_LOOP = 100; + + public static int updateAuthorityRefDocs( + ServiceContext ctx, + RepositoryClient repoClient, + RepositoryInstanceInterface repoSession, + String oldRefName, + String newRefName, + String refPropName) throws Exception { + Map queriedServiceBindings = new HashMap(); + Map> authRefFieldsByService = new HashMap>(); + + int docsScanned = 0; + int nRefsFound = 0; + int currentPage = 0; + int docsInCurrentPage = 0; + final String WHERE_CLAUSE_ADDITIONS_VALUE = null; + final String ORDER_BY_VALUE = CollectionSpaceClient.CORE_CREATED_AT // "collectionspace_core:createdAt"; + + ", " + IQueryManager.NUXEO_UUID; // CSPACE-6333: Add secondary sort on uuid, in case records have the same createdAt timestamp. + + if (repoClient instanceof RepositoryJavaClientImpl == false) { + throw new InternalError("updateAuthorityRefDocs() called with unknown repoClient type!"); + } + + try { // REM - How can we deal with transaction and timeout issues here? + final int pageSize = N_OBJS_TO_UPDATE_PER_LOOP; + DocumentModelList docList; + boolean morePages = true; + while (morePages) { + + docList = findAuthorityRefDocs(ctx, repoClient, repoSession, + getRefNameServiceTypes(), oldRefName, refPropName, + queriedServiceBindings, authRefFieldsByService, WHERE_CLAUSE_ADDITIONS_VALUE, ORDER_BY_VALUE, pageSize, currentPage, false); + + if (docList == null) { + logger.debug("updateAuthorityRefDocs: no documents could be found that referenced the old refName"); + break; + } + docsInCurrentPage = docList.size(); + logger.debug("updateAuthorityRefDocs: current page=" + currentPage + " documents included in page=" + docsInCurrentPage); + if (docsInCurrentPage == 0) { + logger.debug("updateAuthorityRefDocs: no more documents requiring refName updates could be found"); + break; + } + if (docsInCurrentPage < pageSize) { + logger.debug("updateAuthorityRefDocs: assuming no more documents requiring refName updates will be found, as docsInCurrentPage < pageSize"); + morePages = false; + } + + // Only match complete refNames - unless and until we decide how to resolve changes + // to NPTs we will defer that and only change PTs or refNames as passed in. + int nRefsFoundThisPage = processRefObjsDocListForUpdate(docList, ctx.getTenantId(), oldRefName, + queriedServiceBindings, authRefFieldsByService, // Perform the refName updates on the list of document models + newRefName); + if (nRefsFoundThisPage > 0) { + ((RepositoryJavaClientImpl) repoClient).saveDocListWithoutHandlerProcessing(ctx, repoSession, docList, true); // Flush the document model list out to Nuxeo storage + nRefsFound += nRefsFoundThisPage; + } + + // FIXME: Per REM, set a limit of num objects - something like + // 1000K objects - and also add a log Warning after some threshold + docsScanned += docsInCurrentPage; + if (morePages) { + currentPage++; + } + + } + } catch (Exception e) { + logger.error("Internal error updating the AuthorityRefDocs: " + e.getLocalizedMessage()); + logger.debug(Tools.errorToString(e, true)); + throw e; + } + logger.debug("updateAuthorityRefDocs replaced a total of " + nRefsFound + " authority references, within as many as " + docsScanned + " scanned document(s)"); + return nRefsFound; + } + + private static DocumentModelList findAllAuthorityRefDocs( + ServiceContext ctx, + RepositoryClient repoClient, + RepositoryInstanceInterface repoSession, List serviceTypes, + String refName, + String refPropName, + Map queriedServiceBindings, + Map> authRefFieldsByService, + String whereClauseAdditions, + String orderByClause, + int pageSize, + boolean computeTotal) throws DocumentException, DocumentNotFoundException { + + return new LazyAuthorityRefDocList(ctx, repoClient, repoSession, + serviceTypes, refName, refPropName, queriedServiceBindings, authRefFieldsByService, + whereClauseAdditions, orderByClause, pageSize, computeTotal); + } + + protected static DocumentModelList findAuthorityRefDocs( + ServiceContext ctx, + RepositoryClient repoClient, + RepositoryInstanceInterface repoSession, List serviceTypes, + String refName, + String refPropName, + Map queriedServiceBindings, + Map> authRefFieldsByService, + String whereClauseAdditions, + String orderByClause, + int pageSize, + int pageNum, + boolean computeTotal) throws DocumentException, DocumentNotFoundException { + + // Get the service bindings for this tenant + TenantBindingConfigReaderImpl tReader = + ServiceMain.getInstance().getTenantBindingConfigReader(); + // We need to get all the procedures, authorities, and objects. + List servicebindings = tReader.getServiceBindingsByType(ctx.getTenantId(), serviceTypes); + if (servicebindings == null || servicebindings.isEmpty()) { + logger.error("RefNameServiceUtils.getAuthorityRefDocs: No services bindings found, cannot proceed!"); + return null; + } + // Filter the list for current user rights + servicebindings = SecurityUtils.getReadableServiceBindingsForCurrentUser(servicebindings); + + ArrayList docTypes = new ArrayList(); + + String query = computeWhereClauseForAuthorityRefDocs(refName, refPropName, docTypes, servicebindings, // REM - Side effect that docTypes array gets set. Any others? + queriedServiceBindings, authRefFieldsByService); + if (query == null) { // found no authRef fields - nothing to query + return null; + } + // Additional qualifications, like workflow state + if (Tools.notBlank(whereClauseAdditions)) { + query += " AND " + whereClauseAdditions; + } + // Now we have to issue the search + RepositoryJavaClientImpl nuxeoRepoClient = (RepositoryJavaClientImpl) repoClient; + DocumentWrapper docListWrapper = nuxeoRepoClient.findDocs(ctx, repoSession, + docTypes, query, orderByClause, pageSize, pageNum, computeTotal); + // Now we gather the info for each document into the list and return + DocumentModelList docList = docListWrapper.getWrappedObject(); + return docList; + } + private static final boolean READY_FOR_COMPLEX_QUERY = true; + + private static String computeWhereClauseForAuthorityRefDocs( + String refName, + String refPropName, + ArrayList docTypes, + List servicebindings, + Map queriedServiceBindings, + Map> authRefFieldsByService) { + + boolean fFirst = true; + List authRefFieldPaths; + for (ServiceBindingType sb : servicebindings) { + // Gets the property names for each part, qualified with the part label (which + // is also the table name, the way that the repository works). + authRefFieldPaths = + ServiceBindingUtils.getAllPartsPropertyValues(sb, + refPropName, ServiceBindingUtils.QUALIFIED_PROP_NAMES); + if (authRefFieldPaths.isEmpty()) { + continue; + } + ArrayList authRefsInfo = new ArrayList(); + for (String spec : authRefFieldPaths) { + AuthRefConfigInfo arci = new AuthRefConfigInfo(spec); + authRefsInfo.add(arci); + } + + String docType = sb.getObject().getName(); + queriedServiceBindings.put(docType, sb); + authRefFieldsByService.put(docType, authRefsInfo); + docTypes.add(docType); + fFirst = false; + } + if (fFirst) { // found no authRef fields - nothing to query + return null; + } + // We used to build a complete matches query, but that was too complex. + // Just build a keyword query based upon some key pieces - the urn syntax elements and the shortID + // Note that this will also match the Item itself, but that will get filtered out when + // we compute actual matches. + AuthorityTermInfo authTermInfo = RefNameUtils.parseAuthorityTermInfo(refName); + + String keywords = RefNameUtils.URN_PREFIX + + " AND " + (authTermInfo.inAuthority.name != null + ? authTermInfo.inAuthority.name : authTermInfo.inAuthority.csid) + + " AND " + (authTermInfo.name != null + ? authTermInfo.name : authTermInfo.csid); + + String whereClauseStr = QueryManager.createWhereClauseFromKeywords(keywords); + + if (logger.isTraceEnabled()) { + logger.trace("The 'where' clause to find refObjs is: ", whereClauseStr); + } + + return whereClauseStr; + } + + // TODO there are multiple copies of this that should be put somewhere common. + protected static String getRefname(DocumentModel docModel) throws ClientException { + String result = (String)docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA, + CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME); + return result; + } + + private static int processRefObjsDocListForUpdate( + DocumentModelList docList, + String tenantId, + String refName, + Map queriedServiceBindings, + Map> authRefFieldsByService, + String newAuthorityRefName) { + return processRefObjsDocList(docList, tenantId, refName, false, queriedServiceBindings, + authRefFieldsByService, null, 0, 0, newAuthorityRefName); + } + + private static int processRefObjsDocListForList( + DocumentModelList docList, + String tenantId, + String refName, + Map queriedServiceBindings, + Map> authRefFieldsByService, + List list, + int pageSize, int pageNum) { + return processRefObjsDocList(docList, tenantId, refName, true, queriedServiceBindings, + authRefFieldsByService, list, pageSize, pageNum, null); + } + + + /* + * Runs through the list of found docs, processing them. If list is + * non-null, then processing means gather the info for items. If list is + * null, and newRefName is non-null, then processing means replacing and + * updating. If processing/updating, this must be called in the context of + * an open session, and caller must release Session after calling this. + * + */ + private static int processRefObjsDocList( + DocumentModelList docList, + String tenantId, + String refName, + boolean matchBaseOnly, + Map queriedServiceBindings, + Map> authRefFieldsByService, + List list, + int pageSize, int pageNum, // Only used when constructing a list. + String newAuthorityRefName) { + UriTemplateRegistry registry = ServiceMain.getInstance().getUriTemplateRegistry(); + Iterator iter = docList.iterator(); + int nRefsFoundTotal = 0; + boolean foundSelf = false; + + // When paginating results, we have to guess at the total. First guess is the number of docs returned + // by the query. However, this returns some false positives, so may be high. + // In addition, we can match multiple fields per doc, so this may be low. Fun, eh? + int nDocsReturnedInQuery = (int)docList.totalSize(); + int nDocsProcessed = 0; + int firstItemInPage = pageNum*pageSize; + while (iter.hasNext()) { + DocumentModel docModel = iter.next(); + AuthorityRefDocList.AuthorityRefDocItem ilistItem; + + String docType = docModel.getDocumentType().getName(); // REM - This will be a tentant qualified document type + docType = ServiceBindingUtils.getUnqualifiedTenantDocType(docType); + ServiceBindingType sb = queriedServiceBindings.get(docType); + if (sb == null) { + throw new RuntimeException( + "getAuthorityRefDocs: No Service Binding for docType: " + docType); + } + + if (list == null) { // no list - should be update refName case. + if (newAuthorityRefName == null) { + throw new InternalError("processRefObjsDocList() called with neither an itemList nor a new RefName!"); + } + ilistItem = null; + pageSize = 0; + firstItemInPage = 0; // Do not paginate if updating, rather than building list + } else { // Have a list - refObjs case + if (newAuthorityRefName != null) { + throw new InternalError("processRefObjsDocList() called with both an itemList and a new RefName!"); + } + if(firstItemInPage > 100) { + logger.warn("Processing a large offset (size:{}, num:{}) for refObjs - will be expensive!!!", + pageSize, pageNum); + } + // Note that we have to go through check all the fields to determine the actual page start + ilistItem = new AuthorityRefDocList.AuthorityRefDocItem(); + String csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString()); + try { + String itemRefName = getRefname(docModel); + ilistItem.setRefName(itemRefName); + } catch (ClientException ce) { + throw new RuntimeException( + "processRefObjsDocList: Problem fetching refName from item Object: " + + ce.getLocalizedMessage()); + } + ilistItem.setDocId(csid); + String uri = ""; + UriTemplateRegistryKey key = new UriTemplateRegistryKey(tenantId, docType); + StoredValuesUriTemplate template = registry.get(key); + if (template != null) { + Map additionalValues = new HashMap(); + if (template.getUriTemplateType() == UriTemplateFactory.RESOURCE) { + additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, csid); + uri = template.buildUri(additionalValues); + } else if (template.getUriTemplateType() == UriTemplateFactory.ITEM) { + try { + String inAuthorityCsid = (String) docModel.getPropertyValue("inAuthority"); // AuthorityItemJAXBSchema.IN_AUTHORITY + additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, inAuthorityCsid); + additionalValues.put(UriTemplateFactory.ITEM_IDENTIFIER_VAR, csid); + uri = template.buildUri(additionalValues); + } catch (Exception e) { + logger.warn("Could not extract inAuthority property from authority item record: " + e.getMessage()); + } + } else if (template.getUriTemplateType() == UriTemplateFactory.CONTACT) { + // FIXME: Generating contact sub-resource URIs requires additional work, + // as a follow-on to CSPACE-5271 - ADR 2012-08-16 + // Sets the default (empty string) value for uri, for now + } else { + logger.warn("Unrecognized URI template type = " + template.getUriTemplateType()); + // Sets the default (empty string) value for uri + } + } else { // (if template == null) + logger.warn("Could not retrieve URI template from registry via tenant ID " + + tenantId + " and docType " + docType); + // Sets the default (empty string) value for uri + } + ilistItem.setUri(uri); + try { + ilistItem.setWorkflowState(docModel.getCurrentLifeCycleState()); + ilistItem.setUpdatedAt(DocHandlerBase.getUpdatedAtAsString(docModel)); + } catch (Exception e) { + logger.error("Error getting core values for doc [" + csid + "]: " + e.getLocalizedMessage()); + } + ilistItem.setDocType(docType); + ilistItem.setDocNumber( + ServiceBindingUtils.getMappedFieldInDoc(sb, ServiceBindingUtils.OBJ_NUMBER_PROP, docModel)); + ilistItem.setDocName( + ServiceBindingUtils.getMappedFieldInDoc(sb, ServiceBindingUtils.OBJ_NAME_PROP, docModel)); + } + // Now, we have to loop over the authRefFieldsByService to figure + // out which field(s) matched this. + List matchingAuthRefFields = authRefFieldsByService.get(docType); + if (matchingAuthRefFields == null || matchingAuthRefFields.isEmpty()) { + throw new RuntimeException( + "getAuthorityRefDocs: internal logic error: can't fetch authRefFields for DocType."); + } + //String authRefAncestorField = ""; + //String authRefDescendantField = ""; + //String sourceField = ""; + + ArrayList foundProps = new ArrayList(); + try { + findAuthRefPropertiesInDoc(docModel, matchingAuthRefFields, refName, matchBaseOnly, foundProps); // REM - side effect that foundProps is set + if(!foundProps.isEmpty()) { + int nRefsFoundInDoc = 0; + for (RefNameServiceUtils.AuthRefInfo ari : foundProps) { + if (ilistItem != null) { + // So this is a true positive, and not a false one. We have to consider pagination now. + if(nRefsFoundTotal >= firstItemInPage) { // skipped enough already + if (nRefsFoundInDoc == 0) { // First one? + ilistItem.setSourceField(ari.getQualifiedDisplayName()); + } else { // duplicates from one object + ilistItem = cloneAuthRefDocItem(ilistItem, ari.getQualifiedDisplayName()); + } + list.add(ilistItem); + nRefsFoundInDoc++; // Only increment if processed, or clone logic above will fail + } + } else { // update refName case + Property propToUpdate = ari.getProperty(); + propToUpdate.setValue(newAuthorityRefName); + } + nRefsFoundTotal++; // Whether we processed or not, we found - essential to pagination logic + } + } else if(ilistItem != null) { + String docRefName = ilistItem.getRefName(); + if (matchBaseOnly? + (docRefName!=null && docRefName.startsWith(refName)) + :refName.equals(docRefName)) { + // We found the self for an item + foundSelf = true; + logger.debug("getAuthorityRefDocs: Result: " + + docType + " [" + NuxeoUtils.getCsid(docModel) + + "] appears to be self for: [" + + refName + "]"); + } else { + logger.debug("getAuthorityRefDocs: Result: " + + docType + " [" + NuxeoUtils.getCsid(docModel) + + "] does not reference [" + + refName + "]"); + } + } + } catch (ClientException ce) { + throw new RuntimeException( + "getAuthorityRefDocs: Problem fetching values from repo: " + ce.getLocalizedMessage()); + } + nDocsProcessed++; + // Done processing that doc. Are we done with the whole page? + // Note pageSize <=0 means do them all + if((pageSize > 0) && ((nRefsFoundTotal-firstItemInPage)>=pageSize)) { + // Quitting early, so we need to estimate the total. Assume one per doc + // for the rest of the docs we matched in the query + int unprocessedDocs = nDocsReturnedInQuery - nDocsProcessed; + if(unprocessedDocs>0) { + // We generally match ourselves in the keyword search. If we already saw ourselves + // then do not try to correct for this. Otherwise, decrement the total. + // Yes, this is fairly goofy, but the whole estimation mechanism is goofy. + if(!foundSelf) + unprocessedDocs--; + nRefsFoundTotal += unprocessedDocs; + } + break; + } + } // close while(iterator) + return nRefsFoundTotal; + } + + private static AuthorityRefDocList.AuthorityRefDocItem cloneAuthRefDocItem( + AuthorityRefDocList.AuthorityRefDocItem ilistItem, String sourceField) { + AuthorityRefDocList.AuthorityRefDocItem newlistItem = new AuthorityRefDocList.AuthorityRefDocItem(); + newlistItem.setDocId(ilistItem.getDocId()); + newlistItem.setDocName(ilistItem.getDocName()); + newlistItem.setDocNumber(ilistItem.getDocNumber()); + newlistItem.setDocType(ilistItem.getDocType()); + newlistItem.setUri(ilistItem.getUri()); + newlistItem.setSourceField(sourceField); + return newlistItem; + } + + public static List findAuthRefPropertiesInDoc( + DocumentModel docModel, + List authRefFieldInfo, + String refNameToMatch, + List foundProps) { + return findAuthRefPropertiesInDoc(docModel, authRefFieldInfo, + refNameToMatch, false, foundProps); + } + + public static List findAuthRefPropertiesInDoc( + DocumentModel docModel, + List authRefFieldInfo, + String refNameToMatch, + boolean matchBaseOnly, + List foundProps) { + // Assume that authRefFieldInfo is keyed by the field name (possibly mapped for UI) + // and the values are elPaths to the field, where intervening group structures in + // lists of complex structures are replaced with "*". Thus, valid paths include + // the following (note that the ServiceBindingUtils prepend schema names to configured values): + // "schemaname:fieldname" + // "schemaname:scalarlistname" + // "schemaname:complexfieldname/fieldname" + // "schemaname:complexlistname/*/fieldname" + // "schemaname:complexlistname/*/scalarlistname" + // "schemaname:complexlistname/*/complexfieldname/fieldname" + // "schemaname:complexlistname/*/complexlistname/*/fieldname" + // etc. + for (AuthRefConfigInfo arci : authRefFieldInfo) { + try { + // Get first property and work down as needed. + Property prop = docModel.getProperty(arci.pathEls[0]); + findAuthRefPropertiesInProperty(foundProps, prop, arci, 0, refNameToMatch, matchBaseOnly); + } catch (Exception e) { + logger.error("Problem fetching property: " + arci.pathEls[0]); + } + } + return foundProps; + } + + private static List findAuthRefPropertiesInProperty( + List foundProps, + Property prop, + AuthRefConfigInfo arci, + int pathStartIndex, // Supports recursion and we work down the path + String refNameToMatch, + boolean matchBaseOnly ) { + if (pathStartIndex >= arci.pathEls.length) { + throw new ArrayIndexOutOfBoundsException("Index = " + pathStartIndex + " for path: " + + arci.pathEls.toString()); + } + AuthRefInfo ari = null; + if (prop == null) { + return foundProps; + } + + if (prop instanceof StringProperty) { // scalar string + addARIifMatches(refNameToMatch, matchBaseOnly, arci, prop, foundProps); + } else if (prop instanceof List) { + List propList = (List) prop; + // run through list. Must either be list of Strings, or Complex + for (Property listItemProp : propList) { + if (listItemProp instanceof StringProperty) { + if (arci.pathEls.length - pathStartIndex != 1) { + logger.error("Configuration for authRefs does not match schema structure: " + + arci.pathEls.toString()); + break; + } else { + addARIifMatches(refNameToMatch, matchBaseOnly, arci, listItemProp, foundProps); + } + } else if (listItemProp.isComplex()) { + // Just recurse to handle this. Note that since this is a list of complex, + // which should look like listName/*/... we add 2 to the path start index + findAuthRefPropertiesInProperty(foundProps, listItemProp, arci, + pathStartIndex + 2, refNameToMatch, matchBaseOnly); + } else { + logger.error("Configuration for authRefs does not match schema structure: " + + arci.pathEls.toString()); + break; + } + } + } else if (prop.isComplex()) { + String localPropName = arci.pathEls[pathStartIndex]; + try { + Property localProp = prop.get(localPropName); + // Now just recurse, pushing down the path 1 step + findAuthRefPropertiesInProperty(foundProps, localProp, arci, + pathStartIndex, refNameToMatch, matchBaseOnly); + } catch (PropertyNotFoundException pnfe) { + logger.error("Could not find property: [" + localPropName + "] in path: " + + arci.getFullPath()); + // Fall through - ari will be null and we will continue... + } + } else { + logger.error("Configuration for authRefs does not match schema structure: " + + arci.pathEls.toString()); + } + + if (ari != null) { + foundProps.add(ari); //FIXME: REM - This is dead code. 'ari' is never touched after being initalized to null. Why? + } + + return foundProps; + } + + private static void addARIifMatches( + String refNameToMatch, + boolean matchBaseOnly, + AuthRefConfigInfo arci, + Property prop, + List foundProps) { + // Need to either match a passed refName + // OR have no refName to match but be non-empty + try { + String value = (String) prop.getValue(); + if (((refNameToMatch != null) && + (matchBaseOnly? + (value!=null && value.startsWith(refNameToMatch)) + :refNameToMatch.equals(value))) + || ((refNameToMatch == null) && Tools.notBlank(value))) { + // Found a match + logger.debug("Found a match on property: " + prop.getPath() + " with value: [" + value + "]"); + AuthRefInfo ari = new AuthRefInfo(arci, prop); + foundProps.add(ari); + } + } catch (PropertyException pe) { + logger.debug("PropertyException on: " + prop.getPath() + pe.getLocalizedMessage()); + } + } + + /* + * Identifies whether the refName was found in the supplied field. If passed + * a new RefName, will set that into fields in which the old one was found. + * + * Only works for: * Scalar fields * Repeatable scalar fields (aka + * multi-valued fields) + * + * Does not work for: * Structured fields (complexTypes) * Repeatable + * structured fields (repeatable complexTypes) private static int + * refNameFoundInField(String oldRefName, Property fieldValue, String + * newRefName) { int nFound = 0; if (fieldValue instanceof List) { + * List fieldValueList = (List) fieldValue; for (Property + * listItemValue : fieldValueList) { try { if ((listItemValue instanceof + * StringProperty) && + * oldRefName.equalsIgnoreCase((String)listItemValue.getValue())) { + * nFound++; if(newRefName!=null) { fieldValue.setValue(newRefName); } else + * { // We cannot quit after the first, if we are replacing values. // If we + * are just looking (not replacing), finding one is enough. break; } } } + * catch( PropertyException pe ) {} } } else { try { if ((fieldValue + * instanceof StringProperty) && + * oldRefName.equalsIgnoreCase((String)fieldValue.getValue())) { nFound++; + * if(newRefName!=null) { fieldValue.setValue(newRefName); } } } catch( + * PropertyException pe ) {} } return nFound; } + */ +} diff --git a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/CommonList.java b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/CommonList.java index 629dfd00c..14d1f69e1 100644 --- a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/CommonList.java +++ b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/CommonList.java @@ -1,165 +1,165 @@ -/** - * 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.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; - -import org.collectionspace.services.common.api.Tools; -import org.collectionspace.services.jaxb.AbstractCommonList; - -import org.apache.commons.lang.builder.ToStringBuilder; -import org.jvnet.jaxb2_commons.lang.ToString; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlTransient; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.XmlSeeAlso; - -import org.slf4j.LoggerFactory; - -/** - * This class allows us to generically represent and marshall a set of list - * results for any object. The base information is provided by the - * AbstractCommonList.xsd and associated class, defining the list header. - * A array of itemInfo objects define the results-specific info, where - * each itemInfo is a map of Strings that represent the fields returned for - * each item. - * - * @author pschmitz - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ -@XmlAccessorType(XmlAccessType.NONE) -// We use the same root as the superclass, so unmarshalling will work (more or less) -@XmlRootElement(name = "abstract-common-list") -public class CommonList extends AbstractCommonList { - - /** The logger. */ - private final Logger logger = LoggerFactory.getLogger(CommonList.class); - @XmlTransient - private DocumentBuilderFactory factory; - @XmlTransient - private DocumentBuilder parser; - @XmlTransient - private Document doc; - - public CommonList() - throws javax.xml.parsers.ParserConfigurationException { - super(); - factory = DocumentBuilderFactory.newInstance(); - //Get the DocumentBuilder - parser = factory.newDocumentBuilder(); - //Create blank DOM Document - doc = parser.newDocument(); - } - - @XmlTransient - private String fieldKeys[] = null; - - //Add methods to add new items, and to set the fieldKeys. Could make - //them an array of strings rather than arraylist. - - /** - * @return the current set of fieldKeys. - */ - public String[] getFieldKeys() { - return fieldKeys; - } - - /** - * Sets the keys to assume when fetching fields from the itemInfo maps. - * As a side-effect, will build and set super.fieldsReturned. - * This MUST be called before attempting to add items (with addItem). - * - * @param fieldKeys the keys to use - * - */ - public void setFieldsReturned(String[] fieldKeys) { - this.fieldKeys = fieldKeys; - String fieldsImploded = Tools.implode(fieldKeys, "|"); - setFieldsReturned(fieldsImploded); - } - - private void addItem(List anyList, String key, Object value) { - if (value != null ) { - Element el = doc.createElement(key); - if (value instanceof String) { - el.setTextContent((String)value); - anyList.add(el); - } else if (value instanceof List) { - @SuppressWarnings("unchecked") // We expect and assume String values only here - List valueList = (List)value; - for (String val : valueList) { - addItem(anyList, key, val); - } - } else { - logger.error("Unknown value type found while processing common list results: " - + value.getClass().getCanonicalName()); - } - } else { - logger.trace("Null value encountered while processing common list results for key: " - + key); - } - } - - /** - * Adds an item to the results list. Each item should have fields - * associated to keys defined in the fieldKeys. - * Caller must call setFieldsReturned() before calling this. - * - * @param itemInfo - * @throws RuntimeException if this is called before fieldKeys has been set. - */ - public void addItem(HashMap itemInfo) { - if (fieldKeys == null) { - throw new RuntimeException( - "CommonList.addItem: Cannot add items before fieldKeys are set."); - } - List itemsList = getListItem(); - AbstractCommonList.ListItem listItem = new AbstractCommonList.ListItem(); - itemsList.add(listItem); - - List anyList = listItem.getAny(); - for (String key : fieldKeys) { - Object value = itemInfo.get(key); - addItem(anyList, key, value); - } - } - -} - - +/** + * 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.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import org.collectionspace.services.common.api.Tools; +import org.collectionspace.services.jaxb.AbstractCommonList; + +import org.apache.commons.lang.builder.ToStringBuilder; +import org.jvnet.jaxb2_commons.lang.ToString; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlTransient; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlSeeAlso; + +import org.slf4j.LoggerFactory; + +/** + * This class allows us to generically represent and marshall a set of list + * results for any object. The base information is provided by the + * AbstractCommonList.xsd and associated class, defining the list header. + * A array of itemInfo objects define the results-specific info, where + * each itemInfo is a map of Strings that represent the fields returned for + * each item. + * + * @author pschmitz + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +@XmlAccessorType(XmlAccessType.NONE) +// We use the same root as the superclass, so unmarshalling will work (more or less) +@XmlRootElement(name = "abstract-common-list") +public class CommonList extends AbstractCommonList { + + /** The logger. */ + private final Logger logger = LoggerFactory.getLogger(CommonList.class); + @XmlTransient + private DocumentBuilderFactory factory; + @XmlTransient + private DocumentBuilder parser; + @XmlTransient + private Document doc; + + public CommonList() + throws javax.xml.parsers.ParserConfigurationException { + super(); + factory = DocumentBuilderFactory.newInstance(); + //Get the DocumentBuilder + parser = factory.newDocumentBuilder(); + //Create blank DOM Document + doc = parser.newDocument(); + } + + @XmlTransient + private String fieldKeys[] = null; + + //Add methods to add new items, and to set the fieldKeys. Could make + //them an array of strings rather than arraylist. + + /** + * @return the current set of fieldKeys. + */ + public String[] getFieldKeys() { + return fieldKeys; + } + + /** + * Sets the keys to assume when fetching fields from the itemInfo maps. + * As a side-effect, will build and set super.fieldsReturned. + * This MUST be called before attempting to add items (with addItem). + * + * @param fieldKeys the keys to use + * + */ + public void setFieldsReturned(String[] fieldKeys) { + this.fieldKeys = fieldKeys; + String fieldsImploded = Tools.implode(fieldKeys, "|"); + setFieldsReturned(fieldsImploded); + } + + private void addItem(List anyList, String key, Object value) { + if (value != null ) { + Element el = doc.createElement(key); + if (value instanceof String) { + el.setTextContent((String)value); + anyList.add(el); + } else if (value instanceof List) { + @SuppressWarnings("unchecked") // We expect and assume String values only here + List valueList = (List)value; + for (String val : valueList) { + addItem(anyList, key, val); + } + } else { + logger.error("Unknown value type found while processing common list results: " + + value.getClass().getCanonicalName()); + } + } else { + logger.trace("Null value encountered while processing common list results for key: " + + key); + } + } + + /** + * Adds an item to the results list. Each item should have fields + * associated to keys defined in the fieldKeys. + * Caller must call setFieldsReturned() before calling this. + * + * @param itemInfo + * @throws RuntimeException if this is called before fieldKeys has been set. + */ + public void addItem(HashMap itemInfo) { + if (fieldKeys == null) { + throw new RuntimeException( + "CommonList.addItem: Cannot add items before fieldKeys are set."); + } + List itemsList = getListItem(); + AbstractCommonList.ListItem listItem = new AbstractCommonList.ListItem(); + itemsList.add(listItem); + + List anyList = listItem.getAny(); + for (String key : fieldKeys) { + Object value = itemInfo.get(key); + addItem(anyList, key, value); + } + } + +} + + diff --git a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/DocHandlerBase.java b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/DocHandlerBase.java index e60f1ee6a..337a3d37d 100644 --- a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/DocHandlerBase.java +++ b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/DocHandlerBase.java @@ -1,394 +1,394 @@ -/** - * 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.lang.reflect.Method; -import java.util.ArrayList; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; - -import javax.ws.rs.core.MultivaluedMap; - -import org.collectionspace.services.client.CollectionSpaceClient; -import org.collectionspace.services.client.IQueryManager; -import org.collectionspace.services.client.IRelationsManager; -import org.collectionspace.services.common.ReflectionMapper; -import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils; -import org.collectionspace.services.common.api.Tools; -import org.collectionspace.services.common.config.ServiceConfigUtils; -import org.collectionspace.services.common.context.AbstractServiceContextImpl; -import org.collectionspace.services.common.context.ServiceContext; -import org.collectionspace.services.common.document.DocumentException; -import org.collectionspace.services.common.document.DocumentWrapper; -import org.collectionspace.services.common.query.QueryContext; -import org.collectionspace.services.common.relation.nuxeo.RelationsUtils; -import org.collectionspace.services.config.service.DocHandlerParams; -import org.collectionspace.services.config.service.ListResultField; -import org.collectionspace.services.jaxb.AbstractCommonList; -import org.collectionspace.services.nuxeo.client.java.CommonList; -import org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl; -import org.collectionspace.services.nuxeo.util.NuxeoUtils; -import org.nuxeo.ecm.core.api.DocumentModel; -import org.nuxeo.ecm.core.api.DocumentModelList; -import org.nuxeo.ecm.core.api.repository.RepositoryInstance; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class is generified by the marker type T, - * where T is expected to map to something like BlobCommon, MediaCommon, ObjectexitCommon, etc., - * and so on for every JAXB-generated schema class. - * - * User: laramie - * $LastChangedRevision: $ - * $LastChangedDate: $ - * - */ -public abstract class DocHandlerBase extends RemoteDocumentModelHandlerImpl { - - /** The logger. */ - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - private AbstractCommonList commonList; - - protected static final int NUM_STANDARD_LIST_RESULT_FIELDS = 5; - protected static final String STANDARD_LIST_CSID_FIELD = "csid"; - protected static final String STANDARD_LIST_URI_FIELD = CollectionSpaceClient.COLLECTIONSPACE_CORE_URI; - protected static final String STANDARD_LIST_REFNAME_FIELD = CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME; - protected static final String STANDARD_LIST_UPDATED_AT_FIELD = CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_AT; - protected static final String STANDARD_LIST_WORKFLOW_FIELD = CollectionSpaceClient.COLLECTIONSPACE_CORE_WORKFLOWSTATE; - protected static final String STANDARD_LIST_MARK_RT_FIELD = "related"; - - @Override - public AbstractCommonList getCommonPartList() { - return commonList; - } - - @Override - public void setCommonPartList(AbstractCommonList aCommonList) { - this.commonList = aCommonList; - } - - private T commonPart; - - @Override - public T getCommonPart() { - return (T)commonPart; - } - - @Override - public void setCommonPart(T commonPart) { - this.commonPart = commonPart; - } - - - /** Subclass DocHandlers may override this method to control exact creation of the common list. - * This class instantiates an AbstractCommonList from the classname returned by getDocHandlerParams().AbstractCommonListClassname. - * @return - * @throws Exception - */ - public AbstractCommonList createAbstractCommonListImpl() throws Exception { - // String classname = this.commonList.getClass().getName(); - ServiceContext ctx = this.getServiceContext(); - String classname = ServiceConfigUtils.getDocHandlerParams(ctx).getAbstractCommonListClassname(); - if (classname == null){ - throw new Exception("in createAbstractCommonListImpl. getDocHandlerParams().getAbstractCommonListClassname() is null"); - } - classname = classname.trim(); - return (AbstractCommonList)(ReflectionMapper.instantiate(classname)); - } - - - /** DocHandlerBase calls this method with the CSID as id */ - public Object createItemForCommonList(DocumentModel docModel, String label, String id) throws Exception { - ServiceContext ctx = this.getServiceContext(); - return createItemForCommonList(ServiceConfigUtils.getDocHandlerParams(ctx).getCommonListItemClassname(), - docModel, label, id, true); - } - - public String getSummaryFields(AbstractCommonList theCommonList) throws DocumentException { - ServiceContext ctx = this.getServiceContext(); - return ServiceConfigUtils.getDocHandlerParams(ctx).getSummaryFields(); - } - - public void setListItemArrayExtended(boolean isExtended) throws DocumentException { - ServiceContext ctx = this.getServiceContext(); - ServiceConfigUtils.getDocHandlerParams(ctx).getListResultsFields().setExtended(isExtended); - } - - public boolean isListItemArrayExtended() throws DocumentException { - ServiceContext ctx = this.getServiceContext(); - return ServiceConfigUtils.getDocHandlerParams(ctx).getListResultsFields().isExtended(); - } - - public List getListItemsArray() throws DocumentException { - ServiceContext ctx = this.getServiceContext(); - return ServiceConfigUtils.getDocHandlerParams(ctx).getListResultsFields().getListResultField(); - } - - @Override - public T extractCommonPart(DocumentWrapper wrapDoc) throws Exception { - throw new UnsupportedOperationException(); - } - - @Override - public void fillCommonPart(T objectexitObject, DocumentWrapper wrapDoc) throws Exception { - throw new UnsupportedOperationException(); - } - - protected static String getRefname(DocumentModel docModel) throws Exception { - String result = (String)docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA, - CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME); - return result; - } - - public static String getUpdatedAtAsString(DocumentModel docModel) throws Exception { - GregorianCalendar cal = (GregorianCalendar) - docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA, - CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_AT); - String updatedAt = GregorianCalendarDateTimeUtils.formatAsISO8601Timestamp(cal); - return updatedAt; - } - - @Override - public AbstractCommonList extractCommonPartList(DocumentWrapper wrapDoc) throws Exception { - CommonList commonList = new CommonList(); - String markRtSbj = null; - RepositoryInstanceInterface repoSession = null; - RepositoryJavaClientImpl repoClient = null; - RepositoryJavaClientImpl nuxeoRepoClient = null; - boolean releaseRepoSession = false; - - AbstractServiceContextImpl sc = (AbstractServiceContextImpl)getServiceContext(); - MultivaluedMap queryParams = getServiceContext().getQueryParams(); - markRtSbj = queryParams.getFirst(IQueryManager.MARK_RELATED_TO_CSID_AS_SUBJECT); // REM - We need to document what this query param is for -i.e., what's its purpose? - if(markRtSbj!=null && markRtSbj.isEmpty()) - markRtSbj = null; - - try { - if(markRtSbj!=null) { - repoClient = (RepositoryJavaClientImpl)this.getRepositoryClient(sc); - nuxeoRepoClient = (RepositoryJavaClientImpl) repoClient; - repoSession = this.getRepositorySession(); - if (repoSession == null) { - repoSession = repoClient.getRepositorySession(sc); - releaseRepoSession = true; - } - } - - String commonSchema = getServiceContext().getCommonPartLabel(); - extractPagingInfo(commonList, wrapDoc); - List resultsFields = getListItemsArray(); - int nFields = resultsFields.size() + NUM_STANDARD_LIST_RESULT_FIELDS; - int baseFields = NUM_STANDARD_LIST_RESULT_FIELDS; - if(markRtSbj!=null) { - nFields++; - baseFields++; - } - String fields[] = new String[nFields]; // REM - Why can't this just be a static array defined once at the top? Then there'd be no need for these hardcoded "[x]" statements and no need for NUM_STANDARD_LIST_RESULT_FIELDS constant as well. - fields[0] = STANDARD_LIST_CSID_FIELD; - fields[1] = STANDARD_LIST_URI_FIELD; - fields[2] = STANDARD_LIST_REFNAME_FIELD; - fields[3] = STANDARD_LIST_UPDATED_AT_FIELD; - fields[4] = STANDARD_LIST_WORKFLOW_FIELD; - if(markRtSbj != null) { - fields[5] = STANDARD_LIST_MARK_RT_FIELD; - } - for(int i = baseFields; i < nFields; i++) { - ListResultField field = resultsFields.get(i - baseFields); - fields[i] = field.getElement(); - } - commonList.setFieldsReturned(fields); - Iterator iter = wrapDoc.getWrappedObject().iterator(); - HashMap item = new HashMap(); - while (iter.hasNext()) { - DocumentModel docModel = iter.next(); - String id = NuxeoUtils.getCsid(docModel); - item.put(STANDARD_LIST_CSID_FIELD, id); - if (markRtSbj != null) { - String relationClause = RelationsUtils.buildWhereClause( - markRtSbj, null, null, id, null); - String whereClause = relationClause - + IQueryManager.SEARCH_QUALIFIER_AND - + NuxeoUtils.buildWorkflowNotDeletedWhereClause(); - QueryContext queryContext = new QueryContext(sc, - whereClause); - queryContext.setDocType(IRelationsManager.DOC_TYPE); - String query = NuxeoUtils.buildNXQLQuery(sc, queryContext); - // Search for 1 relation that matches. 1 is enough to fail - // the filter - DocumentModelList docList = repoSession.query(query, null, - 1, 0, false); - item.put(STANDARD_LIST_MARK_RT_FIELD, - docList.isEmpty() ? "false" : "true"); - } - String uri = getUri(docModel); - item.put(STANDARD_LIST_URI_FIELD, uri); - item.put(STANDARD_LIST_REFNAME_FIELD, getRefname(docModel)); - item.put(STANDARD_LIST_UPDATED_AT_FIELD, - getUpdatedAtAsString(docModel)); - item.put(STANDARD_LIST_WORKFLOW_FIELD, - docModel.getCurrentLifeCycleState()); - - for (ListResultField field : resultsFields) { - String schema = field.getSchema(); - if (schema == null || schema.trim().isEmpty()) { - schema = commonSchema; - } - Object value = getListResultValue(docModel, schema, field); - if (value != null && value instanceof String) { // If it is String that is either null or empty, we set our value to null - String strValue = (String) value; - if (strValue.trim().isEmpty() == true) { - value = null; // We found an "empty" string value, so just set the value to null so we don't return anything. - } - } - if (value != null) { - item.put(field.getElement(), value); - } - } - commonList.addItem(item); - item.clear(); - } - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Caught exception ", e); - } - throw new DocumentException(e); - } finally { - // If we got/aquired a new session then we're responsible for releasing it. - if (releaseRepoSession && repoSession != null) { - repoClient.releaseRepositorySession(sc, repoSession); - } - } - - return commonList; - } - - // TODO - get rid of this if we can - appears to be unused. - @Override - public String getQProperty(String prop) throws DocumentException { - ServiceContext ctx = this.getServiceContext(); - return ServiceConfigUtils.getDocHandlerParams(ctx).getSchemaName() + ":" + prop; - } - - //============= dublin core handling ======================================= - - @Override - public void fillAllParts(DocumentWrapper wrapDoc, Action action) throws Exception { - super.fillAllParts(wrapDoc, action); - fillDublinCoreObject(wrapDoc); - } - - /** - * Fill dublin core object, but only if there are document handler parameters in the service - * bindings. - * - * @param wrapDoc the wrap doc - * @throws Exception the exception - */ - // TODO - Remove this? - // This look like it is never used in a sensible way. It just stuffs a static - // String that matches the service name into a bogus field. - protected void fillDublinCoreObject(DocumentWrapper wrapDoc) throws Exception { - DocHandlerParams.Params docHandlerParams = null; - try { - docHandlerParams = ServiceConfigUtils.getDocHandlerParams(getServiceContext()); - } catch (Exception e) { - logger.warn(e.getMessage()); - } - - if (docHandlerParams != null) { - String title = docHandlerParams.getDublinCoreTitle(); - if (Tools.isEmpty(title) == false){ - DocumentModel docModel = wrapDoc.getWrappedObject(); - docModel.setPropertyValue("dublincore:title", title); - } - } - } - - //================== UTILITY METHODS ================================================ - public static ReflectionMapper.STATUS callPropertySetterWithXPathValue(DocumentModel docModel, - Object listItem, - String setterName, - String schema, - String xpath) - throws Exception { - //Object prop = docModel.getProperty(label, elementName); - String value = (String)NuxeoUtils.getXPathValue(docModel, schema, xpath); - return ReflectionMapper.callSetter(listItem, setterName, value); - } - - public static ReflectionMapper.STATUS callSimplePropertySetter(Object target, String name, Object arg) { - return ReflectionMapper.callSetter(target, name, arg); - } - - /** @param commonListClassname is a package-qualified java classname, including inner class $ notation, such as - * "org.collectionspace.services.objectexit.ObjectexitCommonList$ObjectexitListItem". - * @param includeStdFields set to true to have the method set Uri and Csid automatically, based on id param. - */ - public Object createItemForCommonList(String commonListClassname, DocumentModel docModel, - String schema, String id, boolean includeStdFields) throws Exception { - //createItemForCommonList(docModel, label, id); - Object item = ReflectionMapper.instantiate(commonListClassname); - List resultsFields = getListItemsArray(); - for (ListResultField field : resultsFields ){ - callPropertySetterWithXPathValue(docModel, item, - field.getSetter(), schema, field.getXpath()); - } - if (includeStdFields){ - callSimplePropertySetter(item, "setCsid", id); - callSimplePropertySetter(item, "setUri", getServiceContextPath() + id); - } - return item; - } - - /** Subclasses should override this method if they don't want to automatically - * call List createItemsList(AbstractCommonList commonList, String listItemMethodName) - * which will use introspection to create a summary list, and will find the primary - * field for you if specified. - */ - public List createItemsList(AbstractCommonList commonList) throws Exception { - ServiceContext ctx = this.getServiceContext(); - return createItemsList(commonList, - ServiceConfigUtils.getDocHandlerParams(ctx).getListResultsItemMethodName()); - } - - /** e.g. createItemsList(commonList, "getObjectexitListItem" */ - public List createItemsList(AbstractCommonList commonList, String listItemMethodName) throws Exception { - Class commonListClass = commonList.getClass(); - Class[] types = new Class[] {}; - try { - Method m = commonListClass.getMethod(listItemMethodName, types); - return (List)(ReflectionMapper.fireGetMethod(m, commonList)); - } catch (NoSuchMethodException nsm){ - return new ArrayList(); - } - } - - - -} - +/** + * 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.lang.reflect.Method; +import java.util.ArrayList; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import javax.ws.rs.core.MultivaluedMap; + +import org.collectionspace.services.client.CollectionSpaceClient; +import org.collectionspace.services.client.IQueryManager; +import org.collectionspace.services.client.IRelationsManager; +import org.collectionspace.services.common.ReflectionMapper; +import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils; +import org.collectionspace.services.common.api.Tools; +import org.collectionspace.services.common.config.ServiceConfigUtils; +import org.collectionspace.services.common.context.AbstractServiceContextImpl; +import org.collectionspace.services.common.context.ServiceContext; +import org.collectionspace.services.common.document.DocumentException; +import org.collectionspace.services.common.document.DocumentWrapper; +import org.collectionspace.services.common.query.QueryContext; +import org.collectionspace.services.common.relation.nuxeo.RelationsUtils; +import org.collectionspace.services.config.service.DocHandlerParams; +import org.collectionspace.services.config.service.ListResultField; +import org.collectionspace.services.jaxb.AbstractCommonList; +import org.collectionspace.services.nuxeo.client.java.CommonList; +import org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl; +import org.collectionspace.services.nuxeo.util.NuxeoUtils; +import org.nuxeo.ecm.core.api.DocumentModel; +import org.nuxeo.ecm.core.api.DocumentModelList; +import org.nuxeo.ecm.core.api.repository.RepositoryInstance; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class is generified by the marker type T, + * where T is expected to map to something like BlobCommon, MediaCommon, ObjectexitCommon, etc., + * and so on for every JAXB-generated schema class. + * + * User: laramie + * $LastChangedRevision: $ + * $LastChangedDate: $ + * + */ +public abstract class DocHandlerBase extends RemoteDocumentModelHandlerImpl { + + /** The logger. */ + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private AbstractCommonList commonList; + + protected static final int NUM_STANDARD_LIST_RESULT_FIELDS = 5; + protected static final String STANDARD_LIST_CSID_FIELD = "csid"; + protected static final String STANDARD_LIST_URI_FIELD = CollectionSpaceClient.COLLECTIONSPACE_CORE_URI; + protected static final String STANDARD_LIST_REFNAME_FIELD = CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME; + protected static final String STANDARD_LIST_UPDATED_AT_FIELD = CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_AT; + protected static final String STANDARD_LIST_WORKFLOW_FIELD = CollectionSpaceClient.COLLECTIONSPACE_CORE_WORKFLOWSTATE; + protected static final String STANDARD_LIST_MARK_RT_FIELD = "related"; + + @Override + public AbstractCommonList getCommonPartList() { + return commonList; + } + + @Override + public void setCommonPartList(AbstractCommonList aCommonList) { + this.commonList = aCommonList; + } + + private T commonPart; + + @Override + public T getCommonPart() { + return (T)commonPart; + } + + @Override + public void setCommonPart(T commonPart) { + this.commonPart = commonPart; + } + + + /** Subclass DocHandlers may override this method to control exact creation of the common list. + * This class instantiates an AbstractCommonList from the classname returned by getDocHandlerParams().AbstractCommonListClassname. + * @return + * @throws Exception + */ + public AbstractCommonList createAbstractCommonListImpl() throws Exception { + // String classname = this.commonList.getClass().getName(); + ServiceContext ctx = this.getServiceContext(); + String classname = ServiceConfigUtils.getDocHandlerParams(ctx).getAbstractCommonListClassname(); + if (classname == null){ + throw new Exception("in createAbstractCommonListImpl. getDocHandlerParams().getAbstractCommonListClassname() is null"); + } + classname = classname.trim(); + return (AbstractCommonList)(ReflectionMapper.instantiate(classname)); + } + + + /** DocHandlerBase calls this method with the CSID as id */ + public Object createItemForCommonList(DocumentModel docModel, String label, String id) throws Exception { + ServiceContext ctx = this.getServiceContext(); + return createItemForCommonList(ServiceConfigUtils.getDocHandlerParams(ctx).getCommonListItemClassname(), + docModel, label, id, true); + } + + public String getSummaryFields(AbstractCommonList theCommonList) throws DocumentException { + ServiceContext ctx = this.getServiceContext(); + return ServiceConfigUtils.getDocHandlerParams(ctx).getSummaryFields(); + } + + public void setListItemArrayExtended(boolean isExtended) throws DocumentException { + ServiceContext ctx = this.getServiceContext(); + ServiceConfigUtils.getDocHandlerParams(ctx).getListResultsFields().setExtended(isExtended); + } + + public boolean isListItemArrayExtended() throws DocumentException { + ServiceContext ctx = this.getServiceContext(); + return ServiceConfigUtils.getDocHandlerParams(ctx).getListResultsFields().isExtended(); + } + + public List getListItemsArray() throws DocumentException { + ServiceContext ctx = this.getServiceContext(); + return ServiceConfigUtils.getDocHandlerParams(ctx).getListResultsFields().getListResultField(); + } + + @Override + public T extractCommonPart(DocumentWrapper wrapDoc) throws Exception { + throw new UnsupportedOperationException(); + } + + @Override + public void fillCommonPart(T objectexitObject, DocumentWrapper wrapDoc) throws Exception { + throw new UnsupportedOperationException(); + } + + protected static String getRefname(DocumentModel docModel) throws Exception { + String result = (String)docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA, + CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME); + return result; + } + + public static String getUpdatedAtAsString(DocumentModel docModel) throws Exception { + GregorianCalendar cal = (GregorianCalendar) + docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA, + CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_AT); + String updatedAt = GregorianCalendarDateTimeUtils.formatAsISO8601Timestamp(cal); + return updatedAt; + } + + @Override + public AbstractCommonList extractCommonPartList(DocumentWrapper wrapDoc) throws Exception { + CommonList commonList = new CommonList(); + String markRtSbj = null; + RepositoryInstanceInterface repoSession = null; + RepositoryJavaClientImpl repoClient = null; + RepositoryJavaClientImpl nuxeoRepoClient = null; + boolean releaseRepoSession = false; + + AbstractServiceContextImpl sc = (AbstractServiceContextImpl)getServiceContext(); + MultivaluedMap queryParams = getServiceContext().getQueryParams(); + markRtSbj = queryParams.getFirst(IQueryManager.MARK_RELATED_TO_CSID_AS_SUBJECT); // REM - We need to document what this query param is for -i.e., what's its purpose? + if(markRtSbj!=null && markRtSbj.isEmpty()) + markRtSbj = null; + + try { + if(markRtSbj!=null) { + repoClient = (RepositoryJavaClientImpl)this.getRepositoryClient(sc); + nuxeoRepoClient = (RepositoryJavaClientImpl) repoClient; + repoSession = this.getRepositorySession(); + if (repoSession == null) { + repoSession = repoClient.getRepositorySession(sc); + releaseRepoSession = true; + } + } + + String commonSchema = getServiceContext().getCommonPartLabel(); + extractPagingInfo(commonList, wrapDoc); + List resultsFields = getListItemsArray(); + int nFields = resultsFields.size() + NUM_STANDARD_LIST_RESULT_FIELDS; + int baseFields = NUM_STANDARD_LIST_RESULT_FIELDS; + if(markRtSbj!=null) { + nFields++; + baseFields++; + } + String fields[] = new String[nFields]; // REM - Why can't this just be a static array defined once at the top? Then there'd be no need for these hardcoded "[x]" statements and no need for NUM_STANDARD_LIST_RESULT_FIELDS constant as well. + fields[0] = STANDARD_LIST_CSID_FIELD; + fields[1] = STANDARD_LIST_URI_FIELD; + fields[2] = STANDARD_LIST_REFNAME_FIELD; + fields[3] = STANDARD_LIST_UPDATED_AT_FIELD; + fields[4] = STANDARD_LIST_WORKFLOW_FIELD; + if(markRtSbj != null) { + fields[5] = STANDARD_LIST_MARK_RT_FIELD; + } + for(int i = baseFields; i < nFields; i++) { + ListResultField field = resultsFields.get(i - baseFields); + fields[i] = field.getElement(); + } + commonList.setFieldsReturned(fields); + Iterator iter = wrapDoc.getWrappedObject().iterator(); + HashMap item = new HashMap(); + while (iter.hasNext()) { + DocumentModel docModel = iter.next(); + String id = NuxeoUtils.getCsid(docModel); + item.put(STANDARD_LIST_CSID_FIELD, id); + if (markRtSbj != null) { + String relationClause = RelationsUtils.buildWhereClause( + markRtSbj, null, null, id, null); + String whereClause = relationClause + + IQueryManager.SEARCH_QUALIFIER_AND + + NuxeoUtils.buildWorkflowNotDeletedWhereClause(); + QueryContext queryContext = new QueryContext(sc, + whereClause); + queryContext.setDocType(IRelationsManager.DOC_TYPE); + String query = NuxeoUtils.buildNXQLQuery(sc, queryContext); + // Search for 1 relation that matches. 1 is enough to fail + // the filter + DocumentModelList docList = repoSession.query(query, null, + 1, 0, false); + item.put(STANDARD_LIST_MARK_RT_FIELD, + docList.isEmpty() ? "false" : "true"); + } + String uri = getUri(docModel); + item.put(STANDARD_LIST_URI_FIELD, uri); + item.put(STANDARD_LIST_REFNAME_FIELD, getRefname(docModel)); + item.put(STANDARD_LIST_UPDATED_AT_FIELD, + getUpdatedAtAsString(docModel)); + item.put(STANDARD_LIST_WORKFLOW_FIELD, + docModel.getCurrentLifeCycleState()); + + for (ListResultField field : resultsFields) { + String schema = field.getSchema(); + if (schema == null || schema.trim().isEmpty()) { + schema = commonSchema; + } + Object value = getListResultValue(docModel, schema, field); + if (value != null && value instanceof String) { // If it is String that is either null or empty, we set our value to null + String strValue = (String) value; + if (strValue.trim().isEmpty() == true) { + value = null; // We found an "empty" string value, so just set the value to null so we don't return anything. + } + } + if (value != null) { + item.put(field.getElement(), value); + } + } + commonList.addItem(item); + item.clear(); + } + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Caught exception ", e); + } + throw new DocumentException(e); + } finally { + // If we got/aquired a new session then we're responsible for releasing it. + if (releaseRepoSession && repoSession != null) { + repoClient.releaseRepositorySession(sc, repoSession); + } + } + + return commonList; + } + + // TODO - get rid of this if we can - appears to be unused. + @Override + public String getQProperty(String prop) throws DocumentException { + ServiceContext ctx = this.getServiceContext(); + return ServiceConfigUtils.getDocHandlerParams(ctx).getSchemaName() + ":" + prop; + } + + //============= dublin core handling ======================================= + + @Override + public void fillAllParts(DocumentWrapper wrapDoc, Action action) throws Exception { + super.fillAllParts(wrapDoc, action); + fillDublinCoreObject(wrapDoc); + } + + /** + * Fill dublin core object, but only if there are document handler parameters in the service + * bindings. + * + * @param wrapDoc the wrap doc + * @throws Exception the exception + */ + // TODO - Remove this? + // This look like it is never used in a sensible way. It just stuffs a static + // String that matches the service name into a bogus field. + protected void fillDublinCoreObject(DocumentWrapper wrapDoc) throws Exception { + DocHandlerParams.Params docHandlerParams = null; + try { + docHandlerParams = ServiceConfigUtils.getDocHandlerParams(getServiceContext()); + } catch (Exception e) { + logger.warn(e.getMessage()); + } + + if (docHandlerParams != null) { + String title = docHandlerParams.getDublinCoreTitle(); + if (Tools.isEmpty(title) == false){ + DocumentModel docModel = wrapDoc.getWrappedObject(); + docModel.setPropertyValue("dublincore:title", title); + } + } + } + + //================== UTILITY METHODS ================================================ + public static ReflectionMapper.STATUS callPropertySetterWithXPathValue(DocumentModel docModel, + Object listItem, + String setterName, + String schema, + String xpath) + throws Exception { + //Object prop = docModel.getProperty(label, elementName); + String value = (String)NuxeoUtils.getXPathValue(docModel, schema, xpath); + return ReflectionMapper.callSetter(listItem, setterName, value); + } + + public static ReflectionMapper.STATUS callSimplePropertySetter(Object target, String name, Object arg) { + return ReflectionMapper.callSetter(target, name, arg); + } + + /** @param commonListClassname is a package-qualified java classname, including inner class $ notation, such as + * "org.collectionspace.services.objectexit.ObjectexitCommonList$ObjectexitListItem". + * @param includeStdFields set to true to have the method set Uri and Csid automatically, based on id param. + */ + public Object createItemForCommonList(String commonListClassname, DocumentModel docModel, + String schema, String id, boolean includeStdFields) throws Exception { + //createItemForCommonList(docModel, label, id); + Object item = ReflectionMapper.instantiate(commonListClassname); + List resultsFields = getListItemsArray(); + for (ListResultField field : resultsFields ){ + callPropertySetterWithXPathValue(docModel, item, + field.getSetter(), schema, field.getXpath()); + } + if (includeStdFields){ + callSimplePropertySetter(item, "setCsid", id); + callSimplePropertySetter(item, "setUri", getServiceContextPath() + id); + } + return item; + } + + /** Subclasses should override this method if they don't want to automatically + * call List createItemsList(AbstractCommonList commonList, String listItemMethodName) + * which will use introspection to create a summary list, and will find the primary + * field for you if specified. + */ + public List createItemsList(AbstractCommonList commonList) throws Exception { + ServiceContext ctx = this.getServiceContext(); + return createItemsList(commonList, + ServiceConfigUtils.getDocHandlerParams(ctx).getListResultsItemMethodName()); + } + + /** e.g. createItemsList(commonList, "getObjectexitListItem" */ + public List createItemsList(AbstractCommonList commonList, String listItemMethodName) throws Exception { + Class commonListClass = commonList.getClass(); + Class[] types = new Class[] {}; + try { + Method m = commonListClass.getMethod(listItemMethodName, types); + return (List)(ReflectionMapper.fireGetMethod(m, commonList)); + } catch (NoSuchMethodException nsm){ + return new ArrayList(); + } + } + + + +} + diff --git a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/NuxeoClientEmbedded.java b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/NuxeoClientEmbedded.java index 144450c81..7dbd1b9fa 100644 --- a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/NuxeoClientEmbedded.java +++ b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/NuxeoClientEmbedded.java @@ -1,294 +1,294 @@ -/* - * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the GNU Lesser General Public License - * (LGPL) version 2.1 which accompanies this distribution, and is available at - * http://www.gnu.org/licenses/lgpl.html - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * Contributors: - * bstefanescu, jcarsique - * - * $Id$ - */ - -package org.collectionspace.services.nuxeo.client.java; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; - -import org.collectionspace.services.common.repository.RepositoryInstanceWrapperAdvice; -import org.collectionspace.services.config.tenant.RepositoryDomainType; -import org.jboss.remoting.InvokerLocator; -import org.nuxeo.ecm.core.api.repository.Repository; -import org.nuxeo.ecm.core.api.repository.RepositoryInstance; -import org.nuxeo.ecm.core.api.repository.RepositoryInstanceHandler; -import org.nuxeo.ecm.core.api.repository.RepositoryManager; -import org.nuxeo.ecm.core.client.DefaultLoginHandler; -import org.nuxeo.ecm.core.client.LoginHandler; -import org.nuxeo.runtime.api.Framework; -import org.nuxeo.runtime.transaction.TransactionHelper; - -import javax.transaction.TransactionManager; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.aop.framework.ProxyFactory; - -/** - * @author Bogdan Stefanescu - * - */ -public final class NuxeoClientEmbedded { - - private Logger logger = LoggerFactory.getLogger(NuxeoClientEmbedded.class); - - private LoginHandler loginHandler; - - private final HashMap repositoryInstances; - - private InvokerLocator locator; - - private RepositoryManager repositoryMgr; - - private static final NuxeoClientEmbedded instance = new NuxeoClientEmbedded(); - - /** - * Constructs a new NuxeoClient. NOTE: Using {@link #getInstance()} instead - * of this constructor is recommended. - */ - private NuxeoClientEmbedded() { - loginHandler = loginHandler == null ? new DefaultLoginHandler() - : loginHandler; - repositoryInstances = new HashMap(); - } - - public static NuxeoClientEmbedded getInstance() { - return instance; - } - - public synchronized void tryDisconnect() throws Exception { - if (locator == null) { - return; // do nothing - } - doDisconnect(); - } - - private void doDisconnect() throws Exception { - locator = null; - // close repository sessions if any - Iterator> it = repositoryInstances.entrySet().iterator(); - while (it.hasNext()) { - Entry repo = it.next(); - try { - repo.getValue().close(); - } catch (Exception e) { - logger.debug("Error while trying to close " + repo, e); - } - it.remove(); - } - - repositoryMgr = null; - } - - public synchronized boolean isConnected() { - return true; - } - - public InvokerLocator getLocator() { - return locator; - } - - public synchronized LoginHandler getLoginHandler() { - return loginHandler; - } - - public synchronized void setLoginHandler(LoginHandler loginHandler) { - this.loginHandler = loginHandler; - } - - public RepositoryManager getRepositoryManager() throws Exception { - if (repositoryMgr == null) { - repositoryMgr = Framework.getService(RepositoryManager.class); - } - return repositoryMgr; - } - - /** - * Gets the repositories available on the connected server. - * - * @return the repositories - */ - public Repository[] getRepositories() throws Exception { - Collection repos = getRepositoryManager().getRepositories(); - return repos.toArray(new Repository[repos.size()]); - } - - public Repository getDefaultRepository() throws Exception { - return getRepositoryManager().getDefaultRepository(); - } - - public Repository getRepository(String name) throws Exception { - return getRepositoryManager().getRepository(name); - } - - /* - * Open a Nuxeo repo session using the passed in repoDomain and use the default tx timeout period - */ - public RepositoryInstanceInterface openRepository(RepositoryDomainType repoDomain) throws Exception { - return openRepository(repoDomain.getRepositoryName(), -1); - } - - /* - * Open a Nuxeo repo session using the passed in repoDomain and use the default tx timeout period - */ - public RepositoryInstanceInterface openRepository(String repoName) throws Exception { - return openRepository(repoName, -1); - } - - public RepositoryInstanceInterface openRepository(String repoName, int timeoutSeconds) throws Exception { - RepositoryInstanceInterface result = null; - - // - // If the called passed in a custom timeout setting, use it to configure Nuxeo's transaction manager. - // - if (timeoutSeconds > 0) { - TransactionManager transactionMgr = TransactionHelper.lookupTransactionManager(); - transactionMgr.setTransactionTimeout(timeoutSeconds); - if (logger.isInfoEnabled()) { - logger.info(String.format("Changing current request's transaction timeout period to %d seconds", - timeoutSeconds)); - } - } - - // - // Start a new Nuxeo transaction - // - boolean startedTransaction = false; - if (TransactionHelper.isTransactionActive() == false) { - startedTransaction = TransactionHelper.startTransaction(); - if (startedTransaction == false) { - String errMsg = "Could not start a Nuxeo transaction with the TransactionHelper class."; - logger.error(errMsg); - throw new Exception(errMsg); - } - } else { - logger.warn("A request to start a new transaction was made, but a transaction is already open."); - } - - // - // From the repository name that the caller passed in, get an instance of Nuxeo's Repository class. - // The Repository class is just a metadata description of the repository. - // - Repository repository; - if (repoName != null) { - repository = getRepositoryManager().getRepository(repoName); - } else { - repository = getRepositoryManager().getDefaultRepository(); - logger.warn(String.format("Using default repository '%s' because no name was specified.", repository.getName())); - } - - // - // Using the Repository class, get a Spring AOP proxied instance. We use Spring AOP to "wrap" all calls to the - // Nuxeo repository so we can check for network related failures and perform a series of retries. - // - if (repository != null) { - result = getRepositoryInstanceWrapper(repository); - logger.trace(String.format("A new transaction was started on thread '%d' : %s.", - Thread.currentThread().getId(), startedTransaction ? "true" : "false")); - logger.trace(String.format("Added a new repository instance to our repo list. Current count is now: %d", - repositoryInstances.size())); - } else { - String errMsg = String.format("Could not open a session to the Nuxeo repository='%s'", repoName); - logger.error(errMsg); - throw new Exception(errMsg); - } - - - return result; - } - - // - // Returns a proxied interface to a Nuxeo repository instance. Our proxy uses Spring AOP to - // wrap each call to the Nuxeo repo with code that catches network related errors/exceptions and - // re-attempts the calls to see if it recovers. - // - private RepositoryInstanceInterface getAOPProxy(RepositoryInstance repositoryInstance) { - RepositoryInstanceInterface result = null; - - try { - ProxyFactory factory = new ProxyFactory(new RepositoryInstanceWrapper(repositoryInstance)); - factory.addAdvice(new RepositoryInstanceWrapperAdvice()); - factory.setExposeProxy(true); - result = (RepositoryInstanceInterface)factory.getProxy(); - } catch (Exception e) { - logger.error("Could not create AOP proxy for: " + RepositoryInstanceWrapper.class.getName(), e); - } - - return result; - } - - /* - * From the Repository object (a description of the repository), get repository instance wrapper. Our wrapper - * will using the Spring AOP mechanism to intercept all calls to the repository. We will wrap all the calls to the - * Nuxeo repository and check for network related failures. We will retry all calls to the Nuxeo repo that fail because - * of network erros. - */ - private RepositoryInstanceInterface getRepositoryInstanceWrapper(Repository repository) throws Exception { - RepositoryInstanceInterface result = null; - - RepositoryInstance repositoryInstance = new RepositoryInstanceHandler(repository).getProxy(); // A Nuxeo repo instance handler proxy - if (repositoryInstance != null) { - result = this.getAOPProxy(repositoryInstance); // This is our AOP proxy - if (result != null) { - String key = result.getSessionId(); - repositoryInstances.put(key, result); - } else { - String errMsg = String.format("Could not instantiate a Spring AOP proxy for class '%s'.", - RepositoryInstanceWrapper.class.getName()); - logger.error(errMsg); - throw new Exception(errMsg); - } - } else { - String errMsg = String.format("Could not create a new repository instance for '%s' repository.", repository.getName()); - logger.error(errMsg); - throw new Exception(errMsg); - } - - return result; - } - - public void releaseRepository(RepositoryInstanceInterface repo) throws Exception { - String key = repo.getSessionId(); - - try { - repo.save(); - repo.close(); - } catch (Exception e) { - logger.error("Possible data loss. Could not save and/or release the repository.", e); - throw e; - } finally { - RepositoryInstanceInterface wasRemoved = repositoryInstances.remove(key); - if (logger.isTraceEnabled()) { - if (wasRemoved != null) { - logger.trace("Removed a repository instance from our repo list. Current count is now: " - + repositoryInstances.size()); - } else { - logger.trace("Could not remove a repository instance from our repo list. Current count is now: " - + repositoryInstances.size()); - } - } - if (TransactionHelper.isTransactionActiveOrMarkedRollback() == true) { - TransactionHelper.commitOrRollbackTransaction(); - logger.trace(String.format("Transaction closed on thread '%d'", Thread.currentThread().getId())); - } - } - } -} +/* + * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the GNU Lesser General Public License + * (LGPL) version 2.1 which accompanies this distribution, and is available at + * http://www.gnu.org/licenses/lgpl.html + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * Contributors: + * bstefanescu, jcarsique + * + * $Id$ + */ + +package org.collectionspace.services.nuxeo.client.java; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; + +import org.collectionspace.services.common.repository.RepositoryInstanceWrapperAdvice; +import org.collectionspace.services.config.tenant.RepositoryDomainType; +import org.jboss.remoting.InvokerLocator; +import org.nuxeo.ecm.core.api.repository.Repository; +import org.nuxeo.ecm.core.api.repository.RepositoryInstance; +import org.nuxeo.ecm.core.api.repository.RepositoryInstanceHandler; +import org.nuxeo.ecm.core.api.repository.RepositoryManager; +import org.nuxeo.ecm.core.client.DefaultLoginHandler; +import org.nuxeo.ecm.core.client.LoginHandler; +import org.nuxeo.runtime.api.Framework; +import org.nuxeo.runtime.transaction.TransactionHelper; + +import javax.transaction.TransactionManager; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.aop.framework.ProxyFactory; + +/** + * @author Bogdan Stefanescu + * + */ +public final class NuxeoClientEmbedded { + + private Logger logger = LoggerFactory.getLogger(NuxeoClientEmbedded.class); + + private LoginHandler loginHandler; + + private final HashMap repositoryInstances; + + private InvokerLocator locator; + + private RepositoryManager repositoryMgr; + + private static final NuxeoClientEmbedded instance = new NuxeoClientEmbedded(); + + /** + * Constructs a new NuxeoClient. NOTE: Using {@link #getInstance()} instead + * of this constructor is recommended. + */ + private NuxeoClientEmbedded() { + loginHandler = loginHandler == null ? new DefaultLoginHandler() + : loginHandler; + repositoryInstances = new HashMap(); + } + + public static NuxeoClientEmbedded getInstance() { + return instance; + } + + public synchronized void tryDisconnect() throws Exception { + if (locator == null) { + return; // do nothing + } + doDisconnect(); + } + + private void doDisconnect() throws Exception { + locator = null; + // close repository sessions if any + Iterator> it = repositoryInstances.entrySet().iterator(); + while (it.hasNext()) { + Entry repo = it.next(); + try { + repo.getValue().close(); + } catch (Exception e) { + logger.debug("Error while trying to close " + repo, e); + } + it.remove(); + } + + repositoryMgr = null; + } + + public synchronized boolean isConnected() { + return true; + } + + public InvokerLocator getLocator() { + return locator; + } + + public synchronized LoginHandler getLoginHandler() { + return loginHandler; + } + + public synchronized void setLoginHandler(LoginHandler loginHandler) { + this.loginHandler = loginHandler; + } + + public RepositoryManager getRepositoryManager() throws Exception { + if (repositoryMgr == null) { + repositoryMgr = Framework.getService(RepositoryManager.class); + } + return repositoryMgr; + } + + /** + * Gets the repositories available on the connected server. + * + * @return the repositories + */ + public Repository[] getRepositories() throws Exception { + Collection repos = getRepositoryManager().getRepositories(); + return repos.toArray(new Repository[repos.size()]); + } + + public Repository getDefaultRepository() throws Exception { + return getRepositoryManager().getDefaultRepository(); + } + + public Repository getRepository(String name) throws Exception { + return getRepositoryManager().getRepository(name); + } + + /* + * Open a Nuxeo repo session using the passed in repoDomain and use the default tx timeout period + */ + public RepositoryInstanceInterface openRepository(RepositoryDomainType repoDomain) throws Exception { + return openRepository(repoDomain.getRepositoryName(), -1); + } + + /* + * Open a Nuxeo repo session using the passed in repoDomain and use the default tx timeout period + */ + public RepositoryInstanceInterface openRepository(String repoName) throws Exception { + return openRepository(repoName, -1); + } + + public RepositoryInstanceInterface openRepository(String repoName, int timeoutSeconds) throws Exception { + RepositoryInstanceInterface result = null; + + // + // If the called passed in a custom timeout setting, use it to configure Nuxeo's transaction manager. + // + if (timeoutSeconds > 0) { + TransactionManager transactionMgr = TransactionHelper.lookupTransactionManager(); + transactionMgr.setTransactionTimeout(timeoutSeconds); + if (logger.isInfoEnabled()) { + logger.info(String.format("Changing current request's transaction timeout period to %d seconds", + timeoutSeconds)); + } + } + + // + // Start a new Nuxeo transaction + // + boolean startedTransaction = false; + if (TransactionHelper.isTransactionActive() == false) { + startedTransaction = TransactionHelper.startTransaction(); + if (startedTransaction == false) { + String errMsg = "Could not start a Nuxeo transaction with the TransactionHelper class."; + logger.error(errMsg); + throw new Exception(errMsg); + } + } else { + logger.warn("A request to start a new transaction was made, but a transaction is already open."); + } + + // + // From the repository name that the caller passed in, get an instance of Nuxeo's Repository class. + // The Repository class is just a metadata description of the repository. + // + Repository repository; + if (repoName != null) { + repository = getRepositoryManager().getRepository(repoName); + } else { + repository = getRepositoryManager().getDefaultRepository(); + logger.warn(String.format("Using default repository '%s' because no name was specified.", repository.getName())); + } + + // + // Using the Repository class, get a Spring AOP proxied instance. We use Spring AOP to "wrap" all calls to the + // Nuxeo repository so we can check for network related failures and perform a series of retries. + // + if (repository != null) { + result = getRepositoryInstanceWrapper(repository); + logger.trace(String.format("A new transaction was started on thread '%d' : %s.", + Thread.currentThread().getId(), startedTransaction ? "true" : "false")); + logger.trace(String.format("Added a new repository instance to our repo list. Current count is now: %d", + repositoryInstances.size())); + } else { + String errMsg = String.format("Could not open a session to the Nuxeo repository='%s'", repoName); + logger.error(errMsg); + throw new Exception(errMsg); + } + + + return result; + } + + // + // Returns a proxied interface to a Nuxeo repository instance. Our proxy uses Spring AOP to + // wrap each call to the Nuxeo repo with code that catches network related errors/exceptions and + // re-attempts the calls to see if it recovers. + // + private RepositoryInstanceInterface getAOPProxy(RepositoryInstance repositoryInstance) { + RepositoryInstanceInterface result = null; + + try { + ProxyFactory factory = new ProxyFactory(new RepositoryInstanceWrapper(repositoryInstance)); + factory.addAdvice(new RepositoryInstanceWrapperAdvice()); + factory.setExposeProxy(true); + result = (RepositoryInstanceInterface)factory.getProxy(); + } catch (Exception e) { + logger.error("Could not create AOP proxy for: " + RepositoryInstanceWrapper.class.getName(), e); + } + + return result; + } + + /* + * From the Repository object (a description of the repository), get repository instance wrapper. Our wrapper + * will using the Spring AOP mechanism to intercept all calls to the repository. We will wrap all the calls to the + * Nuxeo repository and check for network related failures. We will retry all calls to the Nuxeo repo that fail because + * of network erros. + */ + private RepositoryInstanceInterface getRepositoryInstanceWrapper(Repository repository) throws Exception { + RepositoryInstanceInterface result = null; + + RepositoryInstance repositoryInstance = new RepositoryInstanceHandler(repository).getProxy(); // A Nuxeo repo instance handler proxy + if (repositoryInstance != null) { + result = this.getAOPProxy(repositoryInstance); // This is our AOP proxy + if (result != null) { + String key = result.getSessionId(); + repositoryInstances.put(key, result); + } else { + String errMsg = String.format("Could not instantiate a Spring AOP proxy for class '%s'.", + RepositoryInstanceWrapper.class.getName()); + logger.error(errMsg); + throw new Exception(errMsg); + } + } else { + String errMsg = String.format("Could not create a new repository instance for '%s' repository.", repository.getName()); + logger.error(errMsg); + throw new Exception(errMsg); + } + + return result; + } + + public void releaseRepository(RepositoryInstanceInterface repo) throws Exception { + String key = repo.getSessionId(); + + try { + repo.save(); + repo.close(); + } catch (Exception e) { + logger.error("Possible data loss. Could not save and/or release the repository.", e); + throw e; + } finally { + RepositoryInstanceInterface wasRemoved = repositoryInstances.remove(key); + if (logger.isTraceEnabled()) { + if (wasRemoved != null) { + logger.trace("Removed a repository instance from our repo list. Current count is now: " + + repositoryInstances.size()); + } else { + logger.trace("Could not remove a repository instance from our repo list. Current count is now: " + + repositoryInstances.size()); + } + } + if (TransactionHelper.isTransactionActiveOrMarkedRollback() == true) { + TransactionHelper.commitOrRollbackTransaction(); + logger.trace(String.format("Transaction closed on thread '%d'", Thread.currentThread().getId())); + } + } + } +} diff --git a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/NuxeoConnectorEmbedded.java b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/NuxeoConnectorEmbedded.java index e1f509b1a..06900aad5 100644 --- a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/NuxeoConnectorEmbedded.java +++ b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/NuxeoConnectorEmbedded.java @@ -1,342 +1,342 @@ -package org.collectionspace.services.nuxeo.client.java; - -import java.io.File; -import java.io.IOException; -import java.util.Hashtable; -import java.util.Iterator; - -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.servlet.ServletContext; - -import org.collectionspace.services.common.api.JEEServerDeployment; -import org.collectionspace.services.config.RepositoryClientConfigType; -import org.collectionspace.services.config.tenant.RepositoryDomainType; -import org.collectionspace.services.nuxeo.util.NuxeoUtils; - -import org.nuxeo.ecm.core.NXCore; -import org.nuxeo.ecm.core.api.DocumentModel; -import org.nuxeo.ecm.core.api.DocumentModelList; -import org.nuxeo.ecm.core.model.Repository; -import org.nuxeo.osgi.application.FrameworkBootstrap; -import org.nuxeo.ecm.core.repository.RepositoryDescriptor; -import org.nuxeo.ecm.core.repository.RepositoryFactory; -import org.nuxeo.ecm.core.storage.sql.ra.ConnectionFactoryImpl; -import org.nuxeo.ecm.core.storage.sql.ra.ManagedConnectionFactoryImpl; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class NuxeoConnectorEmbedded { - /* - 127.0.0.1 - 62474 - */ - private Logger logger = LoggerFactory.getLogger(NuxeoConnectorEmbedded.class); - - public final static String NUXEO_CLIENT_DIR = JEEServerDeployment.NUXEO_CLIENT_DIR; - public final static String NUXEO_SERVER_DIR = JEEServerDeployment.NUXEO_SERVER_DIR; - private final static String ERROR_CONNECTOR_NOT_INITIALIZED = "NuxeoConnector is not initialized!"; - - private final static String CSPACE_JEESERVER_HOME = "CSPACE_CONTAINER"; - private final static String CSPACE_NUXEO_HOME = "CSPACE_NUXEO_HOME"; - - private static final NuxeoConnectorEmbedded self = new NuxeoConnectorEmbedded(); - private NuxeoClientEmbedded client; - private ServletContext servletContext = null; - private volatile boolean initialized = false; // use volatile for lazy - // initialization in - // singleton - private RepositoryClientConfigType repositoryClientConfig; - public FrameworkBootstrap fb; - - private NuxeoConnectorEmbedded() { - } - - public final static NuxeoConnectorEmbedded getInstance() { - return self; - } - - private String getNuxeoServerPath(String serverRootPath) throws IOException { - String result = null; - // - // Look for the CSPACE_NUXEO_HOME environment variable that might contain the fully qualified path of the - // Nuxeo EP configuration directory. - // - String prop = System.getenv(CSPACE_NUXEO_HOME); - if (prop != null && !prop.isEmpty()) { - result = prop; - } else { - // - // Could not find the 'CSPACE_NUXEO_HOME' environment variable, so using the default location instead. - // - result = serverRootPath + "/" + NUXEO_SERVER_DIR; - } - - return result; - } - - private File getNuxeoServerDir(String serverRootPath) throws IOException { - File result = null; - String errMsg = null; - - String path = getNuxeoServerPath(serverRootPath); - if (path != null) { - File temp = new File(path); - if (temp.exists() == true) { - result = temp; - } else { - errMsg = "The Nuxeo EP configuration directory is missing or inaccessible at: '" + path + "'."; - } - } - - if (result == null) { - if (errMsg == null) { - path = path != null ? path : ""; - errMsg = "Unknown error trying to find Nuxeo configuration: '" + - CSPACE_NUXEO_HOME + "' = " + - path; - } - throw new IOException(errMsg); - } - - return result; - } - - // - // Start/boot the Nuxeo EP server instance - // - private void startNuxeoEP(String serverRootPath) throws Exception { - File nuxeoHomeDir = getNuxeoServerDir(serverRootPath); - - if (logger.isInfoEnabled() == true) { - logger.info("Starting Nuxeo EP server from configuration at: " - + nuxeoHomeDir.getCanonicalPath()); - } - - fb = new FrameworkBootstrap(NuxeoConnectorEmbedded.class.getClassLoader(), - nuxeoHomeDir); - fb.initialize(); - fb.start(); - } - - /** - * release releases resources occupied by Nuxeo remoting client runtime - * - * @throws java.lang.Exception - */ - public void release() throws Exception { - if (initialized == true) { - try { - client.tryDisconnect(); - } catch (Exception e) { - logger.error("Failed to disconnect Nuxeo connection.", e); - throw e; - } - } - } - - public void initialize(String serverRootPath, - RepositoryClientConfigType repositoryClientConfig, - ServletContext servletContext) throws Exception { - if (initialized == false) { - synchronized (this) { - if (initialized == false) { - this.servletContext = servletContext; - this.repositoryClientConfig = repositoryClientConfig; - startNuxeoEP(serverRootPath); - client = NuxeoClientEmbedded.getInstance(); - initialized = true; - } - } - } - } - - public String getDatabaseName(String repoName) { - String result = null; - - try { - this.getRepositoryDescriptor(repoName); - } catch (Exception e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - - Repository repository = null; - try { - repository = this.lookupRepository(repoName); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - ConnectionFactoryImpl connectionFactory = (ConnectionFactoryImpl)repository; - ManagedConnectionFactoryImpl managedConnectionFactory = connectionFactory.getManagedConnectionFactory(); - String serverUrl = managedConnectionFactory.getServerURL(); - - return result; - } - - /** - * releaseRepositorySession releases given repository session - * - * @param repoSession - * @throws java.lang.Exception - */ - public void releaseRepositorySession(RepositoryInstanceInterface repoSession) - throws Exception { - if (repoSession != null) { - getClient().releaseRepository(repoSession); - - if (logger.isDebugEnabled()) { - logger.debug("releaseRepositorySession() released repository session"); - } - } - } - - /** - * getRepositorySession get session to default repository - * - * @return RepositoryInstance - * @throws java.lang.Exception - */ - public RepositoryInstanceInterface getRepositorySession(RepositoryDomainType repoDomain) throws Exception { - RepositoryInstanceInterface repoSession = getClient().openRepository(repoDomain); - - if (logger.isDebugEnabled() && repoSession != null) { - logger.debug("getRepositorySession() opened repository session"); - String repoName = repoDomain.getRepositoryName(); - String databaseName = this.getDatabaseName(repoName); // For debugging purposes only - } - - return repoSession; - } - - public Repository lookupRepository(String name) throws Exception { - Repository repo; - try { - // needed by glassfish - repo = (Repository) new InitialContext().lookup("NXRepository/" - + name); - } catch (NamingException e) { - try { - // needed by jboss - repo = (Repository) new InitialContext().lookup("java:NXRepository/" - + name); - } catch (NamingException ee) { - repo = (Repository) NXCore.getRepositoryService().getRepositoryManager().getRepository( - name); - } - } - if (repo == null) { - throw new IllegalArgumentException("Repository not found: " + name); - } - return repo; - } - - public RepositoryDescriptor getRepositoryDescriptor(String name) throws Exception { - RepositoryDescriptor repo = null; - Iterable descriptorsList = NXCore.getRepositoryService().getRepositoryManager().getDescriptors(); - for (RepositoryDescriptor descriptor : descriptorsList) { - String homeDir = descriptor.getHomeDirectory(); - String config = descriptor.getConfigurationFile(); - RepositoryFactory factor = descriptor.getFactory(); - } - - return repo; - } - - /** - * getClient get Nuxeo client for accessing Nuxeo services remotely using - * Nuxeo Java (EJB) Remote APIS - * - * @return NuxeoClient - * @throws java.lang.Exception - */ - public NuxeoClientEmbedded getClient() throws Exception { - if (initialized == true) { - if (client.isConnected()) { - return client; - } - } - // - // Nuxeo connection was not initialized - // - logger.error(ERROR_CONNECTOR_NOT_INITIALIZED); - throw new IllegalStateException(ERROR_CONNECTOR_NOT_INITIALIZED); - } - - void releaseClient() throws Exception { - if (initialized == true) { - // Do nothing. - } else { - // - // Nuxeo connection was not initialized - // - logger.error(ERROR_CONNECTOR_NOT_INITIALIZED); - throw new IllegalStateException(ERROR_CONNECTOR_NOT_INITIALIZED); - } - } - - /** - * retrieveWorkspaceIds retrieves all workspace ids from default repository - * - * @param repoDomain - * a repository domain for a given tenant - see the tenant bindings XML file for details - * @return - * @throws java.lang.Exception - */ - public Hashtable retrieveWorkspaceIds(RepositoryDomainType repoDomain) - throws Exception { - RepositoryInstanceInterface repoSession = null; - Hashtable workspaceIds = new Hashtable(); - try { - repoSession = getRepositorySession(repoDomain); - DocumentModel rootDoc = repoSession.getRootDocument(); - DocumentModelList rootChildrenList = repoSession.getChildren(rootDoc.getRef()); - Iterator diter = rootChildrenList.iterator(); - while (diter.hasNext()) { - DocumentModel domain = diter.next(); - String domainPath = "/" + repoDomain.getStorageName(); - if (!domain.getPathAsString().equalsIgnoreCase(domainPath)) { - continue; // If it's not our domain folder/directory then skip it - } - if (logger.isDebugEnabled()) { - logger.debug("domain=" + domain.toString()); - } - DocumentModelList domainChildrenList = repoSession.getChildren(domain.getRef()); - Iterator witer = domainChildrenList.iterator(); - while (witer.hasNext()) { - DocumentModel childNode = witer.next(); - if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) { - DocumentModelList workspaceList = repoSession - .getChildren(childNode.getRef()); - Iterator wsiter = workspaceList - .iterator(); - while (wsiter.hasNext()) { - DocumentModel workspace = wsiter.next(); - if (logger.isDebugEnabled()) { - logger.debug("workspace name=" - + workspace.getName() + " id=" - + workspace.getId()); - } - workspaceIds.put(workspace.getName().toLowerCase(), - workspace.getId()); - } - } - } - } - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("retrieveWorkspaceIds() caught exception ", e); - } - throw e; - } finally { - if (repoSession != null) { - releaseRepositorySession(repoSession); - } - } - - return workspaceIds; - } -} +package org.collectionspace.services.nuxeo.client.java; + +import java.io.File; +import java.io.IOException; +import java.util.Hashtable; +import java.util.Iterator; + +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.servlet.ServletContext; + +import org.collectionspace.services.common.api.JEEServerDeployment; +import org.collectionspace.services.config.RepositoryClientConfigType; +import org.collectionspace.services.config.tenant.RepositoryDomainType; +import org.collectionspace.services.nuxeo.util.NuxeoUtils; + +import org.nuxeo.ecm.core.NXCore; +import org.nuxeo.ecm.core.api.DocumentModel; +import org.nuxeo.ecm.core.api.DocumentModelList; +import org.nuxeo.ecm.core.model.Repository; +import org.nuxeo.osgi.application.FrameworkBootstrap; +import org.nuxeo.ecm.core.repository.RepositoryDescriptor; +import org.nuxeo.ecm.core.repository.RepositoryFactory; +import org.nuxeo.ecm.core.storage.sql.ra.ConnectionFactoryImpl; +import org.nuxeo.ecm.core.storage.sql.ra.ManagedConnectionFactoryImpl; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NuxeoConnectorEmbedded { + /* + 127.0.0.1 + 62474 + */ + private Logger logger = LoggerFactory.getLogger(NuxeoConnectorEmbedded.class); + + public final static String NUXEO_CLIENT_DIR = JEEServerDeployment.NUXEO_CLIENT_DIR; + public final static String NUXEO_SERVER_DIR = JEEServerDeployment.NUXEO_SERVER_DIR; + private final static String ERROR_CONNECTOR_NOT_INITIALIZED = "NuxeoConnector is not initialized!"; + + private final static String CSPACE_JEESERVER_HOME = "CSPACE_CONTAINER"; + private final static String CSPACE_NUXEO_HOME = "CSPACE_NUXEO_HOME"; + + private static final NuxeoConnectorEmbedded self = new NuxeoConnectorEmbedded(); + private NuxeoClientEmbedded client; + private ServletContext servletContext = null; + private volatile boolean initialized = false; // use volatile for lazy + // initialization in + // singleton + private RepositoryClientConfigType repositoryClientConfig; + public FrameworkBootstrap fb; + + private NuxeoConnectorEmbedded() { + } + + public final static NuxeoConnectorEmbedded getInstance() { + return self; + } + + private String getNuxeoServerPath(String serverRootPath) throws IOException { + String result = null; + // + // Look for the CSPACE_NUXEO_HOME environment variable that might contain the fully qualified path of the + // Nuxeo EP configuration directory. + // + String prop = System.getenv(CSPACE_NUXEO_HOME); + if (prop != null && !prop.isEmpty()) { + result = prop; + } else { + // + // Could not find the 'CSPACE_NUXEO_HOME' environment variable, so using the default location instead. + // + result = serverRootPath + "/" + NUXEO_SERVER_DIR; + } + + return result; + } + + private File getNuxeoServerDir(String serverRootPath) throws IOException { + File result = null; + String errMsg = null; + + String path = getNuxeoServerPath(serverRootPath); + if (path != null) { + File temp = new File(path); + if (temp.exists() == true) { + result = temp; + } else { + errMsg = "The Nuxeo EP configuration directory is missing or inaccessible at: '" + path + "'."; + } + } + + if (result == null) { + if (errMsg == null) { + path = path != null ? path : ""; + errMsg = "Unknown error trying to find Nuxeo configuration: '" + + CSPACE_NUXEO_HOME + "' = " + + path; + } + throw new IOException(errMsg); + } + + return result; + } + + // + // Start/boot the Nuxeo EP server instance + // + private void startNuxeoEP(String serverRootPath) throws Exception { + File nuxeoHomeDir = getNuxeoServerDir(serverRootPath); + + if (logger.isInfoEnabled() == true) { + logger.info("Starting Nuxeo EP server from configuration at: " + + nuxeoHomeDir.getCanonicalPath()); + } + + fb = new FrameworkBootstrap(NuxeoConnectorEmbedded.class.getClassLoader(), + nuxeoHomeDir); + fb.initialize(); + fb.start(); + } + + /** + * release releases resources occupied by Nuxeo remoting client runtime + * + * @throws java.lang.Exception + */ + public void release() throws Exception { + if (initialized == true) { + try { + client.tryDisconnect(); + } catch (Exception e) { + logger.error("Failed to disconnect Nuxeo connection.", e); + throw e; + } + } + } + + public void initialize(String serverRootPath, + RepositoryClientConfigType repositoryClientConfig, + ServletContext servletContext) throws Exception { + if (initialized == false) { + synchronized (this) { + if (initialized == false) { + this.servletContext = servletContext; + this.repositoryClientConfig = repositoryClientConfig; + startNuxeoEP(serverRootPath); + client = NuxeoClientEmbedded.getInstance(); + initialized = true; + } + } + } + } + + public String getDatabaseName(String repoName) { + String result = null; + + try { + this.getRepositoryDescriptor(repoName); + } catch (Exception e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + Repository repository = null; + try { + repository = this.lookupRepository(repoName); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + ConnectionFactoryImpl connectionFactory = (ConnectionFactoryImpl)repository; + ManagedConnectionFactoryImpl managedConnectionFactory = connectionFactory.getManagedConnectionFactory(); + String serverUrl = managedConnectionFactory.getServerURL(); + + return result; + } + + /** + * releaseRepositorySession releases given repository session + * + * @param repoSession + * @throws java.lang.Exception + */ + public void releaseRepositorySession(RepositoryInstanceInterface repoSession) + throws Exception { + if (repoSession != null) { + getClient().releaseRepository(repoSession); + + if (logger.isDebugEnabled()) { + logger.debug("releaseRepositorySession() released repository session"); + } + } + } + + /** + * getRepositorySession get session to default repository + * + * @return RepositoryInstance + * @throws java.lang.Exception + */ + public RepositoryInstanceInterface getRepositorySession(RepositoryDomainType repoDomain) throws Exception { + RepositoryInstanceInterface repoSession = getClient().openRepository(repoDomain); + + if (logger.isDebugEnabled() && repoSession != null) { + logger.debug("getRepositorySession() opened repository session"); + String repoName = repoDomain.getRepositoryName(); + String databaseName = this.getDatabaseName(repoName); // For debugging purposes only + } + + return repoSession; + } + + public Repository lookupRepository(String name) throws Exception { + Repository repo; + try { + // needed by glassfish + repo = (Repository) new InitialContext().lookup("NXRepository/" + + name); + } catch (NamingException e) { + try { + // needed by jboss + repo = (Repository) new InitialContext().lookup("java:NXRepository/" + + name); + } catch (NamingException ee) { + repo = (Repository) NXCore.getRepositoryService().getRepositoryManager().getRepository( + name); + } + } + if (repo == null) { + throw new IllegalArgumentException("Repository not found: " + name); + } + return repo; + } + + public RepositoryDescriptor getRepositoryDescriptor(String name) throws Exception { + RepositoryDescriptor repo = null; + Iterable descriptorsList = NXCore.getRepositoryService().getRepositoryManager().getDescriptors(); + for (RepositoryDescriptor descriptor : descriptorsList) { + String homeDir = descriptor.getHomeDirectory(); + String config = descriptor.getConfigurationFile(); + RepositoryFactory factor = descriptor.getFactory(); + } + + return repo; + } + + /** + * getClient get Nuxeo client for accessing Nuxeo services remotely using + * Nuxeo Java (EJB) Remote APIS + * + * @return NuxeoClient + * @throws java.lang.Exception + */ + public NuxeoClientEmbedded getClient() throws Exception { + if (initialized == true) { + if (client.isConnected()) { + return client; + } + } + // + // Nuxeo connection was not initialized + // + logger.error(ERROR_CONNECTOR_NOT_INITIALIZED); + throw new IllegalStateException(ERROR_CONNECTOR_NOT_INITIALIZED); + } + + void releaseClient() throws Exception { + if (initialized == true) { + // Do nothing. + } else { + // + // Nuxeo connection was not initialized + // + logger.error(ERROR_CONNECTOR_NOT_INITIALIZED); + throw new IllegalStateException(ERROR_CONNECTOR_NOT_INITIALIZED); + } + } + + /** + * retrieveWorkspaceIds retrieves all workspace ids from default repository + * + * @param repoDomain + * a repository domain for a given tenant - see the tenant bindings XML file for details + * @return + * @throws java.lang.Exception + */ + public Hashtable retrieveWorkspaceIds(RepositoryDomainType repoDomain) + throws Exception { + RepositoryInstanceInterface repoSession = null; + Hashtable workspaceIds = new Hashtable(); + try { + repoSession = getRepositorySession(repoDomain); + DocumentModel rootDoc = repoSession.getRootDocument(); + DocumentModelList rootChildrenList = repoSession.getChildren(rootDoc.getRef()); + Iterator diter = rootChildrenList.iterator(); + while (diter.hasNext()) { + DocumentModel domain = diter.next(); + String domainPath = "/" + repoDomain.getStorageName(); + if (!domain.getPathAsString().equalsIgnoreCase(domainPath)) { + continue; // If it's not our domain folder/directory then skip it + } + if (logger.isDebugEnabled()) { + logger.debug("domain=" + domain.toString()); + } + DocumentModelList domainChildrenList = repoSession.getChildren(domain.getRef()); + Iterator witer = domainChildrenList.iterator(); + while (witer.hasNext()) { + DocumentModel childNode = witer.next(); + if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) { + DocumentModelList workspaceList = repoSession + .getChildren(childNode.getRef()); + Iterator wsiter = workspaceList + .iterator(); + while (wsiter.hasNext()) { + DocumentModel workspace = wsiter.next(); + if (logger.isDebugEnabled()) { + logger.debug("workspace name=" + + workspace.getName() + " id=" + + workspace.getId()); + } + workspaceIds.put(workspace.getName().toLowerCase(), + workspace.getId()); + } + } + } + } + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("retrieveWorkspaceIds() caught exception ", e); + } + throw e; + } finally { + if (repoSession != null) { + releaseRepositorySession(repoSession); + } + } + + return workspaceIds; + } +} diff --git a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/ObjectFactory.java b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/ObjectFactory.java index ddbb49700..ec1d553ba 100644 --- a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/ObjectFactory.java +++ b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/ObjectFactory.java @@ -1,53 +1,53 @@ -/** - * 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 javax.xml.bind.annotation.XmlRegistry; - -/** - * ObjectFactory for CommonList - */ -@XmlRegistry -public class ObjectFactory { - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.collectionspace.services.jaxb - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link tCommonList } - * - */ - public CommonList createCommonList() { - try { - //-System.out.println("CL_ObjectFactory:createAbstractCommonList"); - return new CommonList(); - } catch(Exception e) { - return null; - } - } - -} +/** + * 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 javax.xml.bind.annotation.XmlRegistry; + +/** + * ObjectFactory for CommonList + */ +@XmlRegistry +public class ObjectFactory { + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.collectionspace.services.jaxb + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link tCommonList } + * + */ + public CommonList createCommonList() { + try { + //-System.out.println("CL_ObjectFactory:createAbstractCommonList"); + return new CommonList(); + } catch(Exception e) { + return null; + } + } + +} diff --git a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/RemoteSubItemDocumentModelHandlerImpl.java b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/RemoteSubItemDocumentModelHandlerImpl.java index 8ce7ccd12..a35db35b5 100644 --- a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/RemoteSubItemDocumentModelHandlerImpl.java +++ b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/RemoteSubItemDocumentModelHandlerImpl.java @@ -1,132 +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.nuxeo.client.java; - -import java.io.InputStream; -import java.io.ByteArrayInputStream; -import java.util.HashMap; -import java.util.Map; - -import org.collectionspace.services.client.PayloadInputPart; -import org.collectionspace.services.client.PoxPayloadIn; -import org.collectionspace.services.client.PoxPayloadOut; -import org.collectionspace.services.common.context.ServiceContext; -import org.collectionspace.services.common.document.DocumentUtils; -import org.collectionspace.services.config.service.ObjectPartType; - -import org.jboss.resteasy.plugins.providers.multipart.InputPart; -import javax.ws.rs.core.MediaType; -import org.nuxeo.ecm.core.api.DocumentModel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; - -/** - * RemoteDocumentModelHandler - * - * @author pschmitz - * $LastChangedRevision: $ - * $LastChangedDate: $ - * @param The {DocumentType}Common class - * @param The {DocumentType}CommonList class - */ -public abstract class RemoteSubItemDocumentModelHandlerImpl extends - RemoteDocumentModelHandlerImpl { - - private final Logger logger = LoggerFactory.getLogger(RemoteSubItemDocumentModelHandlerImpl.class); - private final String SI_LABEL = "subitem"; - // We must align this to the schema: - // - // - // - private final String[] fields = {"owner", "isPrimary", "order"}; - - /** - * Override fillPart to handle the Subitem XML part into the Subitem document model - * @param part to fill - * @param docModel for the given object - * @param partMeta metadata for the object to fill - * @throws Exception - */ - @Override - protected void fillPart(PayloadInputPart part, DocumentModel docModel, - ObjectPartType partMeta, Action action, ServiceContext ctx) - throws Exception { - ByteArrayInputStream bas = new ByteArrayInputStream(part.getElementBody().asXML().getBytes()); - InputStream payload = bas;//part.getBody(/*InputStream.class, null*/); - - //check if this is an xml part - // TODO - we could configure the parts that have subitem content, - // and then check that here, so skip other parts. - if(part.getMediaType().equals(MediaType.APPLICATION_XML_TYPE)){ - if(payload != null){ - Document document = DocumentUtils.parseDocument(payload, partMeta, - false /*don't validate*/); - //TODO: callback to handler if registered to validate the - //document - Map objectProps = DocumentUtils.parseProperties(document.getFirstChild()); - // Now pull out the subitem props and set them into the Subitem schema - Map subitemProps = null; - for(String key:fields){ - // Fetch and remove as we go, so can safely set remaining values below - String value = (String)(objectProps.remove(key)); - if(value!=null) { - if(subitemProps == null) { - subitemProps = new HashMap(); - } - subitemProps.put(key, value); - } - } - if(subitemProps != null) { - docModel.setProperties(SI_LABEL, subitemProps); - } - // Set all remaining values on the common part. - docModel.setProperties(partMeta.getLabel(), objectProps); - } - } - } - - /** - * extractPart extracts an XML object from given DocumentModel - * This overridden form checks for schemas that extend subitem, and merges - * in the subitem properties for that part. - * @param docModel - * @param schema of the object to extract - * @param partMeta metadata for the object to extract - * @throws Exception - */ - @Override - protected Map extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta) - throws Exception { - Map map = extractPart( docModel, schema, partMeta, null ); - if(schemaHasSubItem(schema)) { - extractPart(docModel, SI_LABEL, partMeta, map); - } - return map; - } - - // TODO HACK - should make this info be configured in the part metadata. - public abstract boolean schemaHasSubItem(String schema); - -} +/** + * 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.io.ByteArrayInputStream; +import java.util.HashMap; +import java.util.Map; + +import org.collectionspace.services.client.PayloadInputPart; +import org.collectionspace.services.client.PoxPayloadIn; +import org.collectionspace.services.client.PoxPayloadOut; +import org.collectionspace.services.common.context.ServiceContext; +import org.collectionspace.services.common.document.DocumentUtils; +import org.collectionspace.services.config.service.ObjectPartType; + +import org.jboss.resteasy.plugins.providers.multipart.InputPart; +import javax.ws.rs.core.MediaType; +import org.nuxeo.ecm.core.api.DocumentModel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; + +/** + * RemoteDocumentModelHandler + * + * @author pschmitz + * $LastChangedRevision: $ + * $LastChangedDate: $ + * @param The {DocumentType}Common class + * @param The {DocumentType}CommonList class + */ +public abstract class RemoteSubItemDocumentModelHandlerImpl extends + RemoteDocumentModelHandlerImpl { + + private final Logger logger = LoggerFactory.getLogger(RemoteSubItemDocumentModelHandlerImpl.class); + private final String SI_LABEL = "subitem"; + // We must align this to the schema: + // + // + // + private final String[] fields = {"owner", "isPrimary", "order"}; + + /** + * Override fillPart to handle the Subitem XML part into the Subitem document model + * @param part to fill + * @param docModel for the given object + * @param partMeta metadata for the object to fill + * @throws Exception + */ + @Override + protected void fillPart(PayloadInputPart part, DocumentModel docModel, + ObjectPartType partMeta, Action action, ServiceContext ctx) + throws Exception { + ByteArrayInputStream bas = new ByteArrayInputStream(part.getElementBody().asXML().getBytes()); + InputStream payload = bas;//part.getBody(/*InputStream.class, null*/); + + //check if this is an xml part + // TODO - we could configure the parts that have subitem content, + // and then check that here, so skip other parts. + if(part.getMediaType().equals(MediaType.APPLICATION_XML_TYPE)){ + if(payload != null){ + Document document = DocumentUtils.parseDocument(payload, partMeta, + false /*don't validate*/); + //TODO: callback to handler if registered to validate the + //document + Map objectProps = DocumentUtils.parseProperties(document.getFirstChild()); + // Now pull out the subitem props and set them into the Subitem schema + Map subitemProps = null; + for(String key:fields){ + // Fetch and remove as we go, so can safely set remaining values below + String value = (String)(objectProps.remove(key)); + if(value!=null) { + if(subitemProps == null) { + subitemProps = new HashMap(); + } + subitemProps.put(key, value); + } + } + if(subitemProps != null) { + docModel.setProperties(SI_LABEL, subitemProps); + } + // Set all remaining values on the common part. + docModel.setProperties(partMeta.getLabel(), objectProps); + } + } + } + + /** + * extractPart extracts an XML object from given DocumentModel + * This overridden form checks for schemas that extend subitem, and merges + * in the subitem properties for that part. + * @param docModel + * @param schema of the object to extract + * @param partMeta metadata for the object to extract + * @throws Exception + */ + @Override + protected Map extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta) + throws Exception { + Map map = extractPart( docModel, schema, partMeta, null ); + if(schemaHasSubItem(schema)) { + extractPart(docModel, SI_LABEL, partMeta, map); + } + return map; + } + + // TODO HACK - should make this info be configured in the part metadata. + public abstract boolean schemaHasSubItem(String schema); + +} diff --git a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/package-info.java b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/package-info.java index 272613476..648de4f71 100644 --- a/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/package-info.java +++ b/services/common/src/main/java/org/collectionspace/services/nuxeo/client/java/package-info.java @@ -1,3 +1,3 @@ -// We make the CommonList act like an AbstractCommonList, by setting its namespace -@javax.xml.bind.annotation.XmlSchema(namespace = "http://collectionspace.org/services/jaxb") -package org.collectionspace.services.nuxeo.client.java; +// We make the CommonList act like an AbstractCommonList, by setting its namespace +@javax.xml.bind.annotation.XmlSchema(namespace = "http://collectionspace.org/services/jaxb") +package org.collectionspace.services.nuxeo.client.java; diff --git a/services/common/src/main/resources/version.xsd b/services/common/src/main/resources/version.xsd index 2b2bfac6e..a5d184301 100644 --- a/services/common/src/main/resources/version.xsd +++ b/services/common/src/main/resources/version.xsd @@ -1,26 +1,26 @@ - - - - - - - - - - - - - - + + + + + + + + + + + + + + diff --git a/services/common/src/test/java/org/collectionspace/services/common/test/UriTemplateRegistryTest.java b/services/common/src/test/java/org/collectionspace/services/common/test/UriTemplateRegistryTest.java index ef3166317..8b67149c1 100644 --- a/services/common/src/test/java/org/collectionspace/services/common/test/UriTemplateRegistryTest.java +++ b/services/common/src/test/java/org/collectionspace/services/common/test/UriTemplateRegistryTest.java @@ -1,99 +1,99 @@ -/** - * 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 (c) 2012 Regents of the University of California - * - * 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.test; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import org.collectionspace.services.common.ServiceMain; -import org.collectionspace.services.common.StoredValuesUriTemplate; -import org.collectionspace.services.common.UriTemplateFactory; -import org.collectionspace.services.common.UriTemplateRegistry; -import org.collectionspace.services.common.UriTemplateRegistryKey; -import org.collectionspace.services.common.api.Tools; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; - -public class UriTemplateRegistryTest { - - private static final Logger logger = LoggerFactory.getLogger(UriTemplateRegistryTest.class); - UriTemplateRegistry registry; - final static String TEST_TENANT_ID = "1"; - final static String TEST_DOCTYPE_NAME = "Doctype"; - final static String TEST_TEMPATE = "/doctypes"; - final static UriTemplateFactory.UriTemplateType TEST_URI_TEMPLATE_TYPE = - UriTemplateFactory.RESOURCE; - - private void testBanner(String msg) { - String BANNER = "-------------------------------------------------------"; - logger.debug("\r" + BANNER + "\r\n" + this.getClass().getName() + "\r\n" + msg + "\r\n" + BANNER); - } - - /** - * Create a test entry in the registry. - */ - @BeforeSuite - private void setUp() { - UriTemplateRegistryKey key = new UriTemplateRegistryKey(TEST_TENANT_ID, TEST_DOCTYPE_NAME); - Map storedValues = new HashMap(); - StoredValuesUriTemplate template = new StoredValuesUriTemplate(TEST_URI_TEMPLATE_TYPE, TEST_TEMPATE, storedValues); - registry = new UriTemplateRegistry(); - registry.put(key, template); - } - - @Test - public void registryContainsEntries() { - testBanner("registryContainsEntries"); - Assert.assertNotNull(registry); - Assert.assertFalse(registry.isEmpty()); - } - - /** - * Identify a valid entry in the registry, then use its key to successfully - * retrieve the entry once again. - */ - @Test(dependsOnMethods = {"registryContainsEntries"}) - public void getRegistryEntryByKey() { - testBanner("getRegistryEntryByKey"); - UriTemplateRegistryKey key; - StoredValuesUriTemplate template; - boolean hasValidKey = false; - boolean hasValidTemplate = false; - for (Map.Entry entry : registry.entrySet()) { - key = entry.getKey(); - template = entry.getValue(); - if (key != null && Tools.notBlank(key.getTenantId()) && Tools.notBlank(key.getDocType())) { - hasValidKey = true; - } - if (template != null && template.getUriTemplateType() != null && Tools.notBlank(template.toString())) { - hasValidTemplate = true; - } - Assert.assertTrue(hasValidKey && hasValidTemplate); - StoredValuesUriTemplate retrievedTemplate = registry.get(key); - Assert.assertNotNull(retrievedTemplate); - Assert.assertEquals(template.toString(), retrievedTemplate.toString()); - } - } -} +/** + * 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 (c) 2012 Regents of the University of California + * + * 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.test; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import org.collectionspace.services.common.ServiceMain; +import org.collectionspace.services.common.StoredValuesUriTemplate; +import org.collectionspace.services.common.UriTemplateFactory; +import org.collectionspace.services.common.UriTemplateRegistry; +import org.collectionspace.services.common.UriTemplateRegistryKey; +import org.collectionspace.services.common.api.Tools; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; + +public class UriTemplateRegistryTest { + + private static final Logger logger = LoggerFactory.getLogger(UriTemplateRegistryTest.class); + UriTemplateRegistry registry; + final static String TEST_TENANT_ID = "1"; + final static String TEST_DOCTYPE_NAME = "Doctype"; + final static String TEST_TEMPATE = "/doctypes"; + final static UriTemplateFactory.UriTemplateType TEST_URI_TEMPLATE_TYPE = + UriTemplateFactory.RESOURCE; + + private void testBanner(String msg) { + String BANNER = "-------------------------------------------------------"; + logger.debug("\r" + BANNER + "\r\n" + this.getClass().getName() + "\r\n" + msg + "\r\n" + BANNER); + } + + /** + * Create a test entry in the registry. + */ + @BeforeSuite + private void setUp() { + UriTemplateRegistryKey key = new UriTemplateRegistryKey(TEST_TENANT_ID, TEST_DOCTYPE_NAME); + Map storedValues = new HashMap(); + StoredValuesUriTemplate template = new StoredValuesUriTemplate(TEST_URI_TEMPLATE_TYPE, TEST_TEMPATE, storedValues); + registry = new UriTemplateRegistry(); + registry.put(key, template); + } + + @Test + public void registryContainsEntries() { + testBanner("registryContainsEntries"); + Assert.assertNotNull(registry); + Assert.assertFalse(registry.isEmpty()); + } + + /** + * Identify a valid entry in the registry, then use its key to successfully + * retrieve the entry once again. + */ + @Test(dependsOnMethods = {"registryContainsEntries"}) + public void getRegistryEntryByKey() { + testBanner("getRegistryEntryByKey"); + UriTemplateRegistryKey key; + StoredValuesUriTemplate template; + boolean hasValidKey = false; + boolean hasValidTemplate = false; + for (Map.Entry entry : registry.entrySet()) { + key = entry.getKey(); + template = entry.getValue(); + if (key != null && Tools.notBlank(key.getTenantId()) && Tools.notBlank(key.getDocType())) { + hasValidKey = true; + } + if (template != null && template.getUriTemplateType() != null && Tools.notBlank(template.toString())) { + hasValidTemplate = true; + } + Assert.assertTrue(hasValidKey && hasValidTemplate); + StoredValuesUriTemplate retrievedTemplate = registry.get(key); + Assert.assertNotNull(retrievedTemplate); + Assert.assertEquals(template.toString(), retrievedTemplate.toString()); + } + } +} diff --git a/services/common/src/test/java/org/collectionspace/services/common/test/UriTemplateTest.java b/services/common/src/test/java/org/collectionspace/services/common/test/UriTemplateTest.java index b6fcbf5e6..68e12173d 100644 --- a/services/common/src/test/java/org/collectionspace/services/common/test/UriTemplateTest.java +++ b/services/common/src/test/java/org/collectionspace/services/common/test/UriTemplateTest.java @@ -1,168 +1,168 @@ -/** - * 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 (c) 2012 Regents of the University of California - * - * 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.test; - -import java.util.HashMap; -import java.util.Map; -import org.collectionspace.services.common.StoredValuesUriTemplate; -import org.collectionspace.services.common.UriTemplate; -import org.collectionspace.services.common.UriTemplateFactory; -import org.collectionspace.services.common.api.Tools; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -public class UriTemplateTest { - - private final static String EXAMPLE_SERVICE_NAME = "examples"; - private final static String EXAMPLE_CSID = "a87f6616-4146-4c17-a41a-048597cc12aa"; - private final static String EXAMPLE_ITEM_CSID = "5d1c2f45-6d02-4376-8852-71893eaf8b1b"; - private final static String EXAMPLE_CONTACT_CSID = "f01e9edb-4f9c-4716-a9cb-5e954fc29577"; - private final static HashMap EMPTY_VALUES_MAP = new HashMap(); - private static final Logger logger = LoggerFactory.getLogger(UriTemplateTest.class); - - private void testBanner(String msg) { - String BANNER = "-------------------------------------------------------"; - logger.debug("\r" + BANNER + "\r\n" + this.getClass().getName() + "\r\n" + msg + "\r\n" + BANNER); - } - - @Test - public void createResourceUriTemplate() { - testBanner("createResourceUriTemplate"); - UriTemplate resourceTemplate = UriTemplateFactory.getURITemplate(UriTemplateFactory.RESOURCE); - Assert.assertNotNull(resourceTemplate, "Resource template is null; it was not created successfully."); - logger.debug("Resource template URI path = " + resourceTemplate.toString()); - Assert.assertNotNull(resourceTemplate.getUriTemplateType(), "Resource template type is null; it was not set successfully."); - Assert.assertEquals(resourceTemplate.getUriTemplateType(), UriTemplateFactory.RESOURCE, - "Resource template type + " + resourceTemplate.getUriTemplateType() - + " doesn't match expected type: " + UriTemplateFactory.RESOURCE); - Assert.assertNotNull(resourceTemplate.toString(), "Resource template URI path is null; it was not set successfully."); - Assert.assertEquals(resourceTemplate.toString(), UriTemplateFactory.RESOURCE_PATH_PATTERN, - "Resource template URI path " + resourceTemplate.toString() - + " doesn't match expected path: " + UriTemplateFactory.RESOURCE_PATH_PATTERN); - } - - @Test(dependsOnMethods = {"createResourceUriTemplate"}) - public void buildResourceUri() { - testBanner("buildResourceUri"); - UriTemplate resourceTemplate = UriTemplateFactory.getURITemplate(UriTemplateFactory.RESOURCE); - Map resourceUriVars = new HashMap(); - resourceUriVars.put(UriTemplateFactory.SERVICENAME_VAR, EXAMPLE_SERVICE_NAME); - resourceUriVars.put(UriTemplateFactory.IDENTIFIER_VAR, EXAMPLE_CSID); - String uriStr = resourceTemplate.buildUri(resourceUriVars); - logger.debug("Generated URI string = " + uriStr); - Assert.assertFalse(Tools.isBlank(uriStr), "Generated URI string is null or blank."); - Assert.assertTrue(uriStr.contains(EXAMPLE_SERVICE_NAME), "Generated URI string does not contain expected service name value: " + EXAMPLE_SERVICE_NAME); - Assert.assertTrue(uriStr.contains(EXAMPLE_CSID), "Generated URI string does not contain expected identifier value: " + EXAMPLE_CSID); - } - - @Test(dependsOnMethods = {"buildResourceUri"}) - public void buildResourceUriWithStoredValues() { - testBanner("buildResourceUriWithStoredValues"); - Map storedValuesMap = new HashMap(); - storedValuesMap.put(UriTemplateFactory.SERVICENAME_VAR, EXAMPLE_SERVICE_NAME); - StoredValuesUriTemplate storedValuesResourceTemplate = - UriTemplateFactory.getURITemplate(UriTemplateFactory.RESOURCE, storedValuesMap); - Map additionalValues = new HashMap(); - additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, EXAMPLE_CSID); - String uriStr = storedValuesResourceTemplate.buildUri(additionalValues); - logger.debug("Generated URI string = " + uriStr); - Assert.assertTrue(Tools.notBlank(uriStr), "Generated URI string is null or blank."); - Assert.assertTrue(uriStr.contains(EXAMPLE_SERVICE_NAME), "Generated URI string does not contain expected service name value: " + EXAMPLE_SERVICE_NAME); - Assert.assertTrue(uriStr.contains(EXAMPLE_CSID), "Generated URI string does not contain expected identifier value: " + EXAMPLE_CSID); - } - - @Test(dependsOnMethods = {"buildResourceUriWithStoredValues"}) - public void buildItemUri() { - testBanner("buildItemUri"); - Map storedValuesMap = new HashMap(); - storedValuesMap.put(UriTemplateFactory.SERVICENAME_VAR, EXAMPLE_SERVICE_NAME); - StoredValuesUriTemplate itemTemplate = - UriTemplateFactory.getURITemplate(UriTemplateFactory.ITEM, storedValuesMap); - Map additionalValues = new HashMap(); - additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, EXAMPLE_CSID); - additionalValues.put(UriTemplateFactory.ITEM_IDENTIFIER_VAR, EXAMPLE_ITEM_CSID); - String uriStr = itemTemplate.buildUri(additionalValues); - logger.debug("Generated URI string = " + uriStr); - Assert.assertTrue(Tools.notBlank(uriStr), "Generated URI string is null or blank."); - Assert.assertTrue(uriStr.contains(EXAMPLE_SERVICE_NAME), "Generated URI string does not contain expected service name value: " + EXAMPLE_SERVICE_NAME); - Assert.assertTrue(uriStr.contains(EXAMPLE_CSID), "Generated URI string does not contain expected identifier value: " + EXAMPLE_CSID); - Assert.assertTrue(uriStr.contains(EXAMPLE_ITEM_CSID), "Generated URI string does not contain expected item identifier value: " + EXAMPLE_ITEM_CSID); - } - - @Test(dependsOnMethods = {"buildItemUri"}) - public void buildContactUri() { - testBanner("buildContactUri"); - StoredValuesUriTemplate contactTemplate = - UriTemplateFactory.getURITemplate(UriTemplateFactory.CONTACT); - Map additionalValues = new HashMap(); - additionalValues.put(UriTemplateFactory.SERVICENAME_VAR, EXAMPLE_SERVICE_NAME); - additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, EXAMPLE_CSID); - additionalValues.put(UriTemplateFactory.ITEM_IDENTIFIER_VAR, EXAMPLE_ITEM_CSID); - additionalValues.put(UriTemplateFactory.CONTACT_IDENTIFIER_VAR, EXAMPLE_CONTACT_CSID); - String uriStr = contactTemplate.buildUri(additionalValues); - logger.debug("Generated URI string = " + uriStr); - Assert.assertTrue(Tools.notBlank(uriStr), "Generated URI string is null or blank."); - Assert.assertTrue(uriStr.contains(EXAMPLE_SERVICE_NAME), "Generated URI string does not contain expected service name value: " + EXAMPLE_SERVICE_NAME); - Assert.assertTrue(uriStr.contains(EXAMPLE_CSID), "Generated URI string does not contain expected identifier value: " + EXAMPLE_CSID); - Assert.assertTrue(uriStr.contains(EXAMPLE_ITEM_CSID), "Generated URI string does not contain expected item identifier value: " + EXAMPLE_ITEM_CSID); - Assert.assertTrue(uriStr.contains(EXAMPLE_CONTACT_CSID), "Generated URI string does not contain expected contact identifier value: " + EXAMPLE_CONTACT_CSID); - } - - // Negative tests: errors are anticipated and checked for in each of the following tests - @Test(dependsOnMethods = {"buildResourceUri"}) - public void buildResourceUriWithMissingValue() { - testBanner("buildResourceUriWithMissingValue"); - UriTemplate resourceTemplate = UriTemplateFactory.getURITemplate(UriTemplateFactory.RESOURCE); - Map resourceUriVars = new HashMap(); - resourceUriVars.put(UriTemplateFactory.SERVICENAME_VAR, EXAMPLE_SERVICE_NAME); - // The required 'identifier' value is missing from the Map from which the URI will be built - logger.debug("This is a negative test, and an error message is expected here:"); - String uriStr = resourceTemplate.buildUri(resourceUriVars); - logger.debug("Generated URI string = " + uriStr); - Assert.assertTrue(Tools.isBlank(uriStr), "Generated URI string was not blank, but should have been."); - } - - @Test(dependsOnMethods = {"buildResourceUri"}) - public void buildResourceUriWithNullValue() { - testBanner("buildResourceUriWithNullValue"); - UriTemplate resourceTemplate = UriTemplateFactory.getURITemplate(UriTemplateFactory.RESOURCE); - Map resourceUriVars = new HashMap(); - resourceUriVars.put(UriTemplateFactory.SERVICENAME_VAR, EXAMPLE_SERVICE_NAME); - resourceUriVars.put(UriTemplateFactory.IDENTIFIER_VAR, null); - logger.debug("This is a negative test, and an error message is expected here:"); - String uriStr = resourceTemplate.buildUri(resourceUriVars); - logger.debug("Generated URI string = " + uriStr); - Assert.assertTrue(Tools.isBlank(uriStr), "Generated URI string was not blank, but should have been."); - } - - @Test(dependsOnMethods = {"buildResourceUri"}) - public void buildResourceUriWithEmptyValuesMap() { - testBanner("buildResourceUriWithEmptyValuesMap"); - UriTemplate resourceTemplate = UriTemplateFactory.getURITemplate(UriTemplateFactory.RESOURCE); - logger.debug("This is a negative test, and an error message is expected here:"); - String uriStr = resourceTemplate.buildUri(EMPTY_VALUES_MAP); - logger.debug("Generated URI string = " + uriStr); - Assert.assertTrue(Tools.isBlank(uriStr), "Generated URI string was not blank, but should have been."); - } -} +/** + * 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 (c) 2012 Regents of the University of California + * + * 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.test; + +import java.util.HashMap; +import java.util.Map; +import org.collectionspace.services.common.StoredValuesUriTemplate; +import org.collectionspace.services.common.UriTemplate; +import org.collectionspace.services.common.UriTemplateFactory; +import org.collectionspace.services.common.api.Tools; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class UriTemplateTest { + + private final static String EXAMPLE_SERVICE_NAME = "examples"; + private final static String EXAMPLE_CSID = "a87f6616-4146-4c17-a41a-048597cc12aa"; + private final static String EXAMPLE_ITEM_CSID = "5d1c2f45-6d02-4376-8852-71893eaf8b1b"; + private final static String EXAMPLE_CONTACT_CSID = "f01e9edb-4f9c-4716-a9cb-5e954fc29577"; + private final static HashMap EMPTY_VALUES_MAP = new HashMap(); + private static final Logger logger = LoggerFactory.getLogger(UriTemplateTest.class); + + private void testBanner(String msg) { + String BANNER = "-------------------------------------------------------"; + logger.debug("\r" + BANNER + "\r\n" + this.getClass().getName() + "\r\n" + msg + "\r\n" + BANNER); + } + + @Test + public void createResourceUriTemplate() { + testBanner("createResourceUriTemplate"); + UriTemplate resourceTemplate = UriTemplateFactory.getURITemplate(UriTemplateFactory.RESOURCE); + Assert.assertNotNull(resourceTemplate, "Resource template is null; it was not created successfully."); + logger.debug("Resource template URI path = " + resourceTemplate.toString()); + Assert.assertNotNull(resourceTemplate.getUriTemplateType(), "Resource template type is null; it was not set successfully."); + Assert.assertEquals(resourceTemplate.getUriTemplateType(), UriTemplateFactory.RESOURCE, + "Resource template type + " + resourceTemplate.getUriTemplateType() + + " doesn't match expected type: " + UriTemplateFactory.RESOURCE); + Assert.assertNotNull(resourceTemplate.toString(), "Resource template URI path is null; it was not set successfully."); + Assert.assertEquals(resourceTemplate.toString(), UriTemplateFactory.RESOURCE_PATH_PATTERN, + "Resource template URI path " + resourceTemplate.toString() + + " doesn't match expected path: " + UriTemplateFactory.RESOURCE_PATH_PATTERN); + } + + @Test(dependsOnMethods = {"createResourceUriTemplate"}) + public void buildResourceUri() { + testBanner("buildResourceUri"); + UriTemplate resourceTemplate = UriTemplateFactory.getURITemplate(UriTemplateFactory.RESOURCE); + Map resourceUriVars = new HashMap(); + resourceUriVars.put(UriTemplateFactory.SERVICENAME_VAR, EXAMPLE_SERVICE_NAME); + resourceUriVars.put(UriTemplateFactory.IDENTIFIER_VAR, EXAMPLE_CSID); + String uriStr = resourceTemplate.buildUri(resourceUriVars); + logger.debug("Generated URI string = " + uriStr); + Assert.assertFalse(Tools.isBlank(uriStr), "Generated URI string is null or blank."); + Assert.assertTrue(uriStr.contains(EXAMPLE_SERVICE_NAME), "Generated URI string does not contain expected service name value: " + EXAMPLE_SERVICE_NAME); + Assert.assertTrue(uriStr.contains(EXAMPLE_CSID), "Generated URI string does not contain expected identifier value: " + EXAMPLE_CSID); + } + + @Test(dependsOnMethods = {"buildResourceUri"}) + public void buildResourceUriWithStoredValues() { + testBanner("buildResourceUriWithStoredValues"); + Map storedValuesMap = new HashMap(); + storedValuesMap.put(UriTemplateFactory.SERVICENAME_VAR, EXAMPLE_SERVICE_NAME); + StoredValuesUriTemplate storedValuesResourceTemplate = + UriTemplateFactory.getURITemplate(UriTemplateFactory.RESOURCE, storedValuesMap); + Map additionalValues = new HashMap(); + additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, EXAMPLE_CSID); + String uriStr = storedValuesResourceTemplate.buildUri(additionalValues); + logger.debug("Generated URI string = " + uriStr); + Assert.assertTrue(Tools.notBlank(uriStr), "Generated URI string is null or blank."); + Assert.assertTrue(uriStr.contains(EXAMPLE_SERVICE_NAME), "Generated URI string does not contain expected service name value: " + EXAMPLE_SERVICE_NAME); + Assert.assertTrue(uriStr.contains(EXAMPLE_CSID), "Generated URI string does not contain expected identifier value: " + EXAMPLE_CSID); + } + + @Test(dependsOnMethods = {"buildResourceUriWithStoredValues"}) + public void buildItemUri() { + testBanner("buildItemUri"); + Map storedValuesMap = new HashMap(); + storedValuesMap.put(UriTemplateFactory.SERVICENAME_VAR, EXAMPLE_SERVICE_NAME); + StoredValuesUriTemplate itemTemplate = + UriTemplateFactory.getURITemplate(UriTemplateFactory.ITEM, storedValuesMap); + Map additionalValues = new HashMap(); + additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, EXAMPLE_CSID); + additionalValues.put(UriTemplateFactory.ITEM_IDENTIFIER_VAR, EXAMPLE_ITEM_CSID); + String uriStr = itemTemplate.buildUri(additionalValues); + logger.debug("Generated URI string = " + uriStr); + Assert.assertTrue(Tools.notBlank(uriStr), "Generated URI string is null or blank."); + Assert.assertTrue(uriStr.contains(EXAMPLE_SERVICE_NAME), "Generated URI string does not contain expected service name value: " + EXAMPLE_SERVICE_NAME); + Assert.assertTrue(uriStr.contains(EXAMPLE_CSID), "Generated URI string does not contain expected identifier value: " + EXAMPLE_CSID); + Assert.assertTrue(uriStr.contains(EXAMPLE_ITEM_CSID), "Generated URI string does not contain expected item identifier value: " + EXAMPLE_ITEM_CSID); + } + + @Test(dependsOnMethods = {"buildItemUri"}) + public void buildContactUri() { + testBanner("buildContactUri"); + StoredValuesUriTemplate contactTemplate = + UriTemplateFactory.getURITemplate(UriTemplateFactory.CONTACT); + Map additionalValues = new HashMap(); + additionalValues.put(UriTemplateFactory.SERVICENAME_VAR, EXAMPLE_SERVICE_NAME); + additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, EXAMPLE_CSID); + additionalValues.put(UriTemplateFactory.ITEM_IDENTIFIER_VAR, EXAMPLE_ITEM_CSID); + additionalValues.put(UriTemplateFactory.CONTACT_IDENTIFIER_VAR, EXAMPLE_CONTACT_CSID); + String uriStr = contactTemplate.buildUri(additionalValues); + logger.debug("Generated URI string = " + uriStr); + Assert.assertTrue(Tools.notBlank(uriStr), "Generated URI string is null or blank."); + Assert.assertTrue(uriStr.contains(EXAMPLE_SERVICE_NAME), "Generated URI string does not contain expected service name value: " + EXAMPLE_SERVICE_NAME); + Assert.assertTrue(uriStr.contains(EXAMPLE_CSID), "Generated URI string does not contain expected identifier value: " + EXAMPLE_CSID); + Assert.assertTrue(uriStr.contains(EXAMPLE_ITEM_CSID), "Generated URI string does not contain expected item identifier value: " + EXAMPLE_ITEM_CSID); + Assert.assertTrue(uriStr.contains(EXAMPLE_CONTACT_CSID), "Generated URI string does not contain expected contact identifier value: " + EXAMPLE_CONTACT_CSID); + } + + // Negative tests: errors are anticipated and checked for in each of the following tests + @Test(dependsOnMethods = {"buildResourceUri"}) + public void buildResourceUriWithMissingValue() { + testBanner("buildResourceUriWithMissingValue"); + UriTemplate resourceTemplate = UriTemplateFactory.getURITemplate(UriTemplateFactory.RESOURCE); + Map resourceUriVars = new HashMap(); + resourceUriVars.put(UriTemplateFactory.SERVICENAME_VAR, EXAMPLE_SERVICE_NAME); + // The required 'identifier' value is missing from the Map from which the URI will be built + logger.debug("This is a negative test, and an error message is expected here:"); + String uriStr = resourceTemplate.buildUri(resourceUriVars); + logger.debug("Generated URI string = " + uriStr); + Assert.assertTrue(Tools.isBlank(uriStr), "Generated URI string was not blank, but should have been."); + } + + @Test(dependsOnMethods = {"buildResourceUri"}) + public void buildResourceUriWithNullValue() { + testBanner("buildResourceUriWithNullValue"); + UriTemplate resourceTemplate = UriTemplateFactory.getURITemplate(UriTemplateFactory.RESOURCE); + Map resourceUriVars = new HashMap(); + resourceUriVars.put(UriTemplateFactory.SERVICENAME_VAR, EXAMPLE_SERVICE_NAME); + resourceUriVars.put(UriTemplateFactory.IDENTIFIER_VAR, null); + logger.debug("This is a negative test, and an error message is expected here:"); + String uriStr = resourceTemplate.buildUri(resourceUriVars); + logger.debug("Generated URI string = " + uriStr); + Assert.assertTrue(Tools.isBlank(uriStr), "Generated URI string was not blank, but should have been."); + } + + @Test(dependsOnMethods = {"buildResourceUri"}) + public void buildResourceUriWithEmptyValuesMap() { + testBanner("buildResourceUriWithEmptyValuesMap"); + UriTemplate resourceTemplate = UriTemplateFactory.getURITemplate(UriTemplateFactory.RESOURCE); + logger.debug("This is a negative test, and an error message is expected here:"); + String uriStr = resourceTemplate.buildUri(EMPTY_VALUES_MAP); + logger.debug("Generated URI string = " + uriStr); + Assert.assertTrue(Tools.isBlank(uriStr), "Generated URI string was not blank, but should have been."); + } +} diff --git a/services/common/src/test/resources/test-data/XmlSaxFragmenter-sample.xml b/services/common/src/test/resources/test-data/XmlSaxFragmenter-sample.xml index 5b774d78d..6a10fa2c8 100644 --- a/services/common/src/test/resources/test-data/XmlSaxFragmenter-sample.xml +++ b/services/common/src/test/resources/test-data/XmlSaxFragmenter-sample.xml @@ -1,11 +1,11 @@ - - - - - In test-data - - - - Male - - + + + + + In test-data + + + + Male + + diff --git a/services/config/src/main/java/org/collectionspace/services/common/config/PropertyItemUtils.java b/services/config/src/main/java/org/collectionspace/services/common/config/PropertyItemUtils.java index 154045b74..f09806fb6 100644 --- a/services/config/src/main/java/org/collectionspace/services/common/config/PropertyItemUtils.java +++ b/services/config/src/main/java/org/collectionspace/services/common/config/PropertyItemUtils.java @@ -1,160 +1,160 @@ -package org.collectionspace.services.common.config; - -import java.util.ArrayList; -import java.util.List; - -import org.collectionspace.services.config.types.PropertyItemType; -import org.collectionspace.services.config.types.PropertyType; - -public class PropertyItemUtils { - - /** - * @param propNodeList the wrapping list node from JAXB - * @param propName the property to fetch - * @return the String value of the named property - */ - public static String getPropertyValueByNameFromNodeList(List propNodeList, - String propName) { - if(propNodeList.isEmpty()) { - return null; - } - return getPropertyValueByName(propNodeList.get(0).getItem(), propName); - } - - - /** - * @param propList the list of properties. - * @param propName the property to fetch - * @return the String value of the named property - */ - public static String getPropertyValueByName(List propList, - String propName) { - if(propName==null) { - throw new IllegalArgumentException("PropertyItemUtils.getPropertyValues: null property name!"); - } - for(PropertyItemType propItem:propList) { - if(propName.equals(propItem.getKey())) { - return propItem.getValue(); - } - } - return null; - } - - /** - * @param propNodeList the JAXB wrapping node of for the list to search for the named property - * @param propName the name of the property of interest - * @param qualPrefix a namespace qualifier prefix (with ':') to prepend, or null - * @return a List of string values found for the named property - */ - public static List getPropertyValuesByNameInNodeList( - List propNodeList, String propName, String qualPrefix) { - return getPropertyValuesByNameInNodeList(propNodeList, propName, qualPrefix, null); - } - - /** - * @param propNodeList the JAXB wrapping node of for the list to search for the named property - * @param propName the name of the property of interest - * @param qualPrefix a namespace qualifier prefix (with ':') to prepend, or null - * @param values and existing list to append values to. If null, a new one will be created. - * @return values, or that is null, a new List of string values found for the named property - */ - public static List getPropertyValuesByNameInNodeList( - List propNodeList, String propName, String qualPrefix, - List values) { - if(propNodeList.isEmpty()) { - if(values==null) - values = new ArrayList(); - return values; - } - return getPropertyValuesByName(propNodeList.get(0).getItem(), - propName, qualPrefix, values); - } - - /** - * @param propNodeList the Item list to search for the named property - * @param propName the name of the property of interest - * @param qualPrefix a namespace qualifier prefix (with ':') to prepend, or null - * @return a List of string values found for the named property - */ - public static List getPropertyValuesByName( - List propItems, String propName, String qualPrefix) { - return getPropertyValuesByName(propItems, propName, qualPrefix, null); - } - - /** - * @param propNodeList the Item list to search for the named property - * @param propName the name of the property of interest - * @param qualPrefix a namespace qualifier prefix (with ':') to prepend, or null - * @param values and existing list to append values to. If null, a new one will be created. - * @return values, or that is null, a new List of string values found for the named property - */ - public static List getPropertyValuesByName( - List propItems, String propName, String qualPrefix, - List values ) { - if(values==null) - values = new ArrayList(); - for(PropertyItemType propItem:propItems) { - if(propName.equals(propItem.getKey())) { - // TODO - the trim() belongs here, not down a few lines. - String value = propItem.getValue(); - if(value!=null) { - values.add((qualPrefix!=null)?(qualPrefix+value):value.trim()); - } - } - } - return values; - } - - /** - * @param propNodeList the wrapping list node from JAXB - * @param propName the property to set - * @param value the new value to set - * @param onlyIfNotSet if true, will not override an existing value - * @return true if set, false if an existing value was left as is. - */ - public static boolean setPropertyValueInNodeList(List propNodeList, - String propName, String value, - boolean onlyIfNotSet) { - if(propNodeList.isEmpty()) { - propNodeList.add(new PropertyType()); - } - List propList = propNodeList.get(0).getItem(); - return setPropertyValue(propList, propName, value, onlyIfNotSet); - } - - /** - * @param propName the property to set - * @param value the new value to set - * @param onlyIfNotSet if true, will not override an existing value - * @return true if set, false if an existing value was left as is. - */ - public static boolean setPropertyValue(List propList, - String propName, String value, - boolean onlyIfNotSet) { - boolean valueFound = false; - boolean valueSet = false; - if(propName==null) { - throw new IllegalArgumentException("ServiceBindingUtils.setPropertyValue: null property name!"); - } - for(PropertyItemType propItem:propList) { - if(propName.equals(propItem.getKey())) { - if(!onlyIfNotSet) { - propItem.setValue(value); - valueSet = true; - } - // whether we set it or not, we found it, so break; - valueFound = true; - break; - } - } - if(!valueFound) { - PropertyItemType propItem = new PropertyItemType(); - propItem.setKey(propName); - propItem.setValue(value); - propList.add(propItem); - valueSet = true; - } - return valueSet; - } - -} +package org.collectionspace.services.common.config; + +import java.util.ArrayList; +import java.util.List; + +import org.collectionspace.services.config.types.PropertyItemType; +import org.collectionspace.services.config.types.PropertyType; + +public class PropertyItemUtils { + + /** + * @param propNodeList the wrapping list node from JAXB + * @param propName the property to fetch + * @return the String value of the named property + */ + public static String getPropertyValueByNameFromNodeList(List propNodeList, + String propName) { + if(propNodeList.isEmpty()) { + return null; + } + return getPropertyValueByName(propNodeList.get(0).getItem(), propName); + } + + + /** + * @param propList the list of properties. + * @param propName the property to fetch + * @return the String value of the named property + */ + public static String getPropertyValueByName(List propList, + String propName) { + if(propName==null) { + throw new IllegalArgumentException("PropertyItemUtils.getPropertyValues: null property name!"); + } + for(PropertyItemType propItem:propList) { + if(propName.equals(propItem.getKey())) { + return propItem.getValue(); + } + } + return null; + } + + /** + * @param propNodeList the JAXB wrapping node of for the list to search for the named property + * @param propName the name of the property of interest + * @param qualPrefix a namespace qualifier prefix (with ':') to prepend, or null + * @return a List of string values found for the named property + */ + public static List getPropertyValuesByNameInNodeList( + List propNodeList, String propName, String qualPrefix) { + return getPropertyValuesByNameInNodeList(propNodeList, propName, qualPrefix, null); + } + + /** + * @param propNodeList the JAXB wrapping node of for the list to search for the named property + * @param propName the name of the property of interest + * @param qualPrefix a namespace qualifier prefix (with ':') to prepend, or null + * @param values and existing list to append values to. If null, a new one will be created. + * @return values, or that is null, a new List of string values found for the named property + */ + public static List getPropertyValuesByNameInNodeList( + List propNodeList, String propName, String qualPrefix, + List values) { + if(propNodeList.isEmpty()) { + if(values==null) + values = new ArrayList(); + return values; + } + return getPropertyValuesByName(propNodeList.get(0).getItem(), + propName, qualPrefix, values); + } + + /** + * @param propNodeList the Item list to search for the named property + * @param propName the name of the property of interest + * @param qualPrefix a namespace qualifier prefix (with ':') to prepend, or null + * @return a List of string values found for the named property + */ + public static List getPropertyValuesByName( + List propItems, String propName, String qualPrefix) { + return getPropertyValuesByName(propItems, propName, qualPrefix, null); + } + + /** + * @param propNodeList the Item list to search for the named property + * @param propName the name of the property of interest + * @param qualPrefix a namespace qualifier prefix (with ':') to prepend, or null + * @param values and existing list to append values to. If null, a new one will be created. + * @return values, or that is null, a new List of string values found for the named property + */ + public static List getPropertyValuesByName( + List propItems, String propName, String qualPrefix, + List values ) { + if(values==null) + values = new ArrayList(); + for(PropertyItemType propItem:propItems) { + if(propName.equals(propItem.getKey())) { + // TODO - the trim() belongs here, not down a few lines. + String value = propItem.getValue(); + if(value!=null) { + values.add((qualPrefix!=null)?(qualPrefix+value):value.trim()); + } + } + } + return values; + } + + /** + * @param propNodeList the wrapping list node from JAXB + * @param propName the property to set + * @param value the new value to set + * @param onlyIfNotSet if true, will not override an existing value + * @return true if set, false if an existing value was left as is. + */ + public static boolean setPropertyValueInNodeList(List propNodeList, + String propName, String value, + boolean onlyIfNotSet) { + if(propNodeList.isEmpty()) { + propNodeList.add(new PropertyType()); + } + List propList = propNodeList.get(0).getItem(); + return setPropertyValue(propList, propName, value, onlyIfNotSet); + } + + /** + * @param propName the property to set + * @param value the new value to set + * @param onlyIfNotSet if true, will not override an existing value + * @return true if set, false if an existing value was left as is. + */ + public static boolean setPropertyValue(List propList, + String propName, String value, + boolean onlyIfNotSet) { + boolean valueFound = false; + boolean valueSet = false; + if(propName==null) { + throw new IllegalArgumentException("ServiceBindingUtils.setPropertyValue: null property name!"); + } + for(PropertyItemType propItem:propList) { + if(propName.equals(propItem.getKey())) { + if(!onlyIfNotSet) { + propItem.setValue(value); + valueSet = true; + } + // whether we set it or not, we found it, so break; + valueFound = true; + break; + } + } + if(!valueFound) { + PropertyItemType propItem = new PropertyItemType(); + propItem.setKey(propName); + propItem.setValue(value); + propList.add(propItem); + valueSet = true; + } + return valueSet; + } + +} diff --git a/services/contact/.classpath b/services/contact/.classpath index d18316afc..2068e34f3 100644 --- a/services/contact/.classpath +++ b/services/contact/.classpath @@ -1,5 +1,5 @@ - - - - - + + + + + diff --git a/services/contact/.project b/services/contact/.project index 114bacd90..ea892d40b 100644 --- a/services/contact/.project +++ b/services/contact/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.contact - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.contact + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/contact/3rdparty/.classpath b/services/contact/3rdparty/.classpath index d18316afc..2068e34f3 100644 --- a/services/contact/3rdparty/.classpath +++ b/services/contact/3rdparty/.classpath @@ -1,5 +1,5 @@ - - - - - + + + + + diff --git a/services/contact/3rdparty/.project b/services/contact/3rdparty/.project index 9a453ba2d..4b8b48d5b 100644 --- a/services/contact/3rdparty/.project +++ b/services/contact/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.contact.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.contact.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/contact/client/src/main/java/org/collectionspace/services/client/AuthorityWithContactsClient.java b/services/contact/client/src/main/java/org/collectionspace/services/client/AuthorityWithContactsClient.java index d5ffa928f..c927d5dba 100644 --- a/services/contact/client/src/main/java/org/collectionspace/services/client/AuthorityWithContactsClient.java +++ b/services/contact/client/src/main/java/org/collectionspace/services/client/AuthorityWithContactsClient.java @@ -1,266 +1,266 @@ -package org.collectionspace.services.client; - -import javax.ws.rs.core.Response; - -import org.collectionspace.services.jaxb.AbstractCommonList; -import org.jboss.resteasy.client.ClientResponse; - -/* - * LT - List type - * ILT - Authority item list type - * P - Proxy type - */ -public interface AuthorityWithContactsClient - extends AuthorityClient { - /** - * Creates the contact. - * - * @param parentcsid the parentcsid - * @param itemcsid the itemcsid - * @param multipart the multipart - * @return the client response - */ - public ClientResponse createContact(String parentcsid, - String itemcsid, PoxPayloadOut xmlPayload); - - /** - * Creates the contact. - * - * @param parentcsid - * @param itemspecifier (shortIdentifier) - * @param multipart - * @return the client response - */ - public ClientResponse createContactForNamedItem( - String parentcsid, - String itemspecifier, - PoxPayloadOut xmlPayload); - - /** - * Creates the contact. - * - * @param parentspecifier (shortIdentifier) - * @param itemcsid - * @param multipart - * @return the client response - */ - public ClientResponse createContactForItemInNamedAuthority( - String parentspecifier, - String itemcsid, - PoxPayloadOut xmlPayload); - - /** - * Creates the contact. - * - * @param parentspecifier (shortIdentifier) - * @param itemspecifier (shortIdentifier) - * @param multipart - * @return the client response - */ - public ClientResponse createContactForNamedItemInNamedAuthority( - String parentspecifier, - String itemspecifier, - PoxPayloadOut xmlPayload); - - /** - * Read contact. - * - * @param parentcsid the parentcsid - * @param itemcsid the itemcsid - * @param csid the csid - * @return the client response - */ - public ClientResponse readContact(String parentcsid, - String itemcsid, String csid); - - /** - * Read contact. - * - * @param parentcsid - * @param itemspecifier (shortIdentifier) - * @param csid - * @return the client response - */ - public ClientResponse readContactForNamedItem( - String parentcsid, - String itemspecifier, - String csid); - - /** - * Read contact. - * - * @param parentspecifier (shortIdentifier) - * @param itemcsid - * @param csid - * @return the client response - */ - public ClientResponse readContactInNamedAuthority( - String parentspecifier, - String itemcsid, - String csid); - - /** - * Read contact. - * - * @param parentspecifier (shortIdentifier) - * @param itemspecifier (shortIdentifier) - * @param csid - * @return the client response - */ - public ClientResponse readContactForNamedItemInNamedAuthority( - String parentspecifier, - String itemspecifier, - String csid); - - - /** - * Read contact list. - * - * @param parentcsid the parentcsid - * @param itemcsid the itemcsid - * @return the client response - */ - public ClientResponse readContactList(String parentcsid, - String itemcsid); - - /** - * Read contact list. - * - * @param parentcsid - * @param itemspecifier (shortIdentifier) - * @return the client response - */ - public ClientResponse readContactListForNamedItem( - String parentcsid, - String itemspecifier); - - /** - * Read contact list. - * - * @param parentspecifier (shortIdentifier) - * @param itemcsid - * @return the client response - */ - public ClientResponse readContactListForItemInNamedAuthority( - String parentspecifier, - String itemcsid); - - /** - * Read contact list. - * - * @param parentspecifier (shortIdentifier) - * @param itemspecifier (shortIdentifier) - * @return the client response - */ - public ClientResponse readContactListForNamedItemInNamedAuthority( - String parentspecifier, - String itemspecifier); - - /** - * Update contact. - * - * @param parentcsid the parentcsid - * @param itemcsid the itemcsid - * @param csid the csid - * @param multipart the multipart - * @return the client response - */ - public ClientResponse updateContact(String parentcsid, - String itemcsid, String csid, PoxPayloadOut xmlPayload); - - /** - * Update contact. - * - * @param parentcsid the parentcsid - * @param itemspecifier (shortIdentifier) - * @param csid the csid - * @param multipart the multipart - * @return the client response - */ - public ClientResponse updateContactForNamedItem( - String parentcsid, - String itemspecifier, - String csid, - PoxPayloadOut xmlPayload); - - /** - * Update contact. - * - * @param parentspecifier (shortIdentifier) - * @param itemcsid the itemcsid - * @param csid the csid - * @param multipart the multipart - * @return the client response - */ - public ClientResponse updateContactInNamedAuthority( - String parentspecifier, - String itemcsid, - String csid, - PoxPayloadOut xmlPayload); - - /** - * Update contact. - * - * @param parentspecifier (shortIdentifier) - * @param itemspecifier (shortIdentifier) - * @param csid the csid - * @param multipart the multipart - * @return the client response - */ - public ClientResponse updateContactForNamedItemInNamedAuthority( - String parentspecifier, - String itemspecifier, - String csid, - PoxPayloadOut xmlPayload); - - /** - * Delete contact. - * - * @param parentcsid the parentcsid - * @param itemcsid the itemcsid - * @param csid the csid - * @return the client response - */ - public ClientResponse deleteContact(String parentcsid, - String itemcsid, String csid); - - /** - * Delete contact. - * - * @param parentcsid the parentcsid - * @param itemspecifier (shortIdentifier) - * @param csid the csid - * @return the client response - */ - public ClientResponse deleteContactForNamedItem( - String parentcsid, - String itemspecifier, - String csid); - - /** - * Delete contact. - * - * @param parentspecifier (shortIdentifier) - * @param itemcsid the itemcsid - * @param csid the csid - * @return the client response - */ - public ClientResponse deleteContactInNamedAuthority( - String parentspecifier, - String itemcsid, - String csid); - - /** - * Delete contact. - * - * @param parentspecifier (shortIdentifier) - * @param itemspecifier (shortIdentifier) - * @param csid the csid - * @return the client response - */ - public ClientResponse deleteContactForNamedItemInNamedAuthority( - String parentspecifier, - String itemspecifier, - String csid); - -} +package org.collectionspace.services.client; + +import javax.ws.rs.core.Response; + +import org.collectionspace.services.jaxb.AbstractCommonList; +import org.jboss.resteasy.client.ClientResponse; + +/* + * LT - List type + * ILT - Authority item list type + * P - Proxy type + */ +public interface AuthorityWithContactsClient + extends AuthorityClient { + /** + * Creates the contact. + * + * @param parentcsid the parentcsid + * @param itemcsid the itemcsid + * @param multipart the multipart + * @return the client response + */ + public ClientResponse createContact(String parentcsid, + String itemcsid, PoxPayloadOut xmlPayload); + + /** + * Creates the contact. + * + * @param parentcsid + * @param itemspecifier (shortIdentifier) + * @param multipart + * @return the client response + */ + public ClientResponse createContactForNamedItem( + String parentcsid, + String itemspecifier, + PoxPayloadOut xmlPayload); + + /** + * Creates the contact. + * + * @param parentspecifier (shortIdentifier) + * @param itemcsid + * @param multipart + * @return the client response + */ + public ClientResponse createContactForItemInNamedAuthority( + String parentspecifier, + String itemcsid, + PoxPayloadOut xmlPayload); + + /** + * Creates the contact. + * + * @param parentspecifier (shortIdentifier) + * @param itemspecifier (shortIdentifier) + * @param multipart + * @return the client response + */ + public ClientResponse createContactForNamedItemInNamedAuthority( + String parentspecifier, + String itemspecifier, + PoxPayloadOut xmlPayload); + + /** + * Read contact. + * + * @param parentcsid the parentcsid + * @param itemcsid the itemcsid + * @param csid the csid + * @return the client response + */ + public ClientResponse readContact(String parentcsid, + String itemcsid, String csid); + + /** + * Read contact. + * + * @param parentcsid + * @param itemspecifier (shortIdentifier) + * @param csid + * @return the client response + */ + public ClientResponse readContactForNamedItem( + String parentcsid, + String itemspecifier, + String csid); + + /** + * Read contact. + * + * @param parentspecifier (shortIdentifier) + * @param itemcsid + * @param csid + * @return the client response + */ + public ClientResponse readContactInNamedAuthority( + String parentspecifier, + String itemcsid, + String csid); + + /** + * Read contact. + * + * @param parentspecifier (shortIdentifier) + * @param itemspecifier (shortIdentifier) + * @param csid + * @return the client response + */ + public ClientResponse readContactForNamedItemInNamedAuthority( + String parentspecifier, + String itemspecifier, + String csid); + + + /** + * Read contact list. + * + * @param parentcsid the parentcsid + * @param itemcsid the itemcsid + * @return the client response + */ + public ClientResponse readContactList(String parentcsid, + String itemcsid); + + /** + * Read contact list. + * + * @param parentcsid + * @param itemspecifier (shortIdentifier) + * @return the client response + */ + public ClientResponse readContactListForNamedItem( + String parentcsid, + String itemspecifier); + + /** + * Read contact list. + * + * @param parentspecifier (shortIdentifier) + * @param itemcsid + * @return the client response + */ + public ClientResponse readContactListForItemInNamedAuthority( + String parentspecifier, + String itemcsid); + + /** + * Read contact list. + * + * @param parentspecifier (shortIdentifier) + * @param itemspecifier (shortIdentifier) + * @return the client response + */ + public ClientResponse readContactListForNamedItemInNamedAuthority( + String parentspecifier, + String itemspecifier); + + /** + * Update contact. + * + * @param parentcsid the parentcsid + * @param itemcsid the itemcsid + * @param csid the csid + * @param multipart the multipart + * @return the client response + */ + public ClientResponse updateContact(String parentcsid, + String itemcsid, String csid, PoxPayloadOut xmlPayload); + + /** + * Update contact. + * + * @param parentcsid the parentcsid + * @param itemspecifier (shortIdentifier) + * @param csid the csid + * @param multipart the multipart + * @return the client response + */ + public ClientResponse updateContactForNamedItem( + String parentcsid, + String itemspecifier, + String csid, + PoxPayloadOut xmlPayload); + + /** + * Update contact. + * + * @param parentspecifier (shortIdentifier) + * @param itemcsid the itemcsid + * @param csid the csid + * @param multipart the multipart + * @return the client response + */ + public ClientResponse updateContactInNamedAuthority( + String parentspecifier, + String itemcsid, + String csid, + PoxPayloadOut xmlPayload); + + /** + * Update contact. + * + * @param parentspecifier (shortIdentifier) + * @param itemspecifier (shortIdentifier) + * @param csid the csid + * @param multipart the multipart + * @return the client response + */ + public ClientResponse updateContactForNamedItemInNamedAuthority( + String parentspecifier, + String itemspecifier, + String csid, + PoxPayloadOut xmlPayload); + + /** + * Delete contact. + * + * @param parentcsid the parentcsid + * @param itemcsid the itemcsid + * @param csid the csid + * @return the client response + */ + public ClientResponse deleteContact(String parentcsid, + String itemcsid, String csid); + + /** + * Delete contact. + * + * @param parentcsid the parentcsid + * @param itemspecifier (shortIdentifier) + * @param csid the csid + * @return the client response + */ + public ClientResponse deleteContactForNamedItem( + String parentcsid, + String itemspecifier, + String csid); + + /** + * Delete contact. + * + * @param parentspecifier (shortIdentifier) + * @param itemcsid the itemcsid + * @param csid the csid + * @return the client response + */ + public ClientResponse deleteContactInNamedAuthority( + String parentspecifier, + String itemcsid, + String csid); + + /** + * Delete contact. + * + * @param parentspecifier (shortIdentifier) + * @param itemspecifier (shortIdentifier) + * @param csid the csid + * @return the client response + */ + public ClientResponse deleteContactForNamedItemInNamedAuthority( + String parentspecifier, + String itemspecifier, + String csid); + +} diff --git a/services/contact/client/src/main/java/org/collectionspace/services/client/AuthorityWithContactsClientImpl.java b/services/contact/client/src/main/java/org/collectionspace/services/client/AuthorityWithContactsClientImpl.java index 9f55df44b..c90004b99 100644 --- a/services/contact/client/src/main/java/org/collectionspace/services/client/AuthorityWithContactsClientImpl.java +++ b/services/contact/client/src/main/java/org/collectionspace/services/client/AuthorityWithContactsClientImpl.java @@ -1,325 +1,325 @@ -package org.collectionspace.services.client; - -import javax.ws.rs.core.Response; -import org.jboss.resteasy.client.ClientResponse; - -import org.collectionspace.services.jaxb.AbstractCommonList; - -/* - * LT - List type - * ILT - Authority item list type - * P - Proxy type - */ -public abstract class AuthorityWithContactsClientImpl - extends AuthorityClientImpl - implements AuthorityWithContactsClient { - - @Override - public ClientResponse createContact(String parentcsid, - String itemcsid, PoxPayloadOut xmlPayload) { - return getProxy().createContact(parentcsid, itemcsid, xmlPayload.getBytes()); - } - - /** - * Creates the contact. - * - * @param parentcsid - * @param itemspecifier (shortIdentifier) - * @param multipart - * @return the client response - */ - @Override - public ClientResponse createContactForNamedItem( - String parentcsid, - String itemspecifier, - PoxPayloadOut xmlPayload) { - return getProxy().createContactForNamedItem(parentcsid, itemspecifier, xmlPayload.getBytes()); - } - /** - * Creates the contact. - * - * @param parentspecifier (shortIdentifier) - * @param itemcsid - * @param multipart - * @return the client response - */ - @Override - public ClientResponse createContactForItemInNamedAuthority( - String parentspecifier, - String itemcsid, - PoxPayloadOut xmlPayload) { - return getProxy().createContactForItemInNamedAuthority(parentspecifier, - itemcsid, xmlPayload.getBytes()); - } - /** - * Creates the contact. - * - * @param parentspecifier (shortIdentifier) - * @param itemspecifier (shortIdentifier) - * @param multipart - * @return the client response - */ - @Override - public ClientResponse createContactForNamedItemInNamedAuthority( - String parentspecifier, - String itemspecifier, - PoxPayloadOut xmlPayload) { - return getProxy().createContactForNamedItemInNamedAuthority(parentspecifier, itemspecifier, - xmlPayload.getBytes()); - } - - /** - * Read contact. - * - * @param parentcsid the parentcsid - * @param itemcsid the itemcsid - * @param csid the csid - * @return the client response - */ - @Override - public ClientResponse readContact(String parentcsid, - String itemcsid, String csid) { - return getProxy().readContact(parentcsid, itemcsid, csid); - } - - /** - * Read contact. - * - * @param parentcsid - * @param itemspecifier (shortIdentifier) - * @param csid - * @return the client response - */ - @Override - public ClientResponse readContactForNamedItem( - String parentcsid, - String itemspecifier, - String csid){ - return getProxy().readContactForNamedItem(parentcsid, itemspecifier, csid); - } - - /** - * Read contact. - * - * @param parentspecifier (shortIdentifier) - * @param itemcsid - * @param csid - * @return the client response - */ - @Override - public ClientResponse readContactInNamedAuthority( - String parentspecifier, - String itemcsid, - String csid){ - return getProxy().readContactInNamedAuthority(parentspecifier, itemcsid, csid); - } - - /** - * Read contact. - * - * @param parentspecifier (shortIdentifier) - * @param itemspecifier (shortIdentifier) - * @param csid - * @return the client response - */ - @Override - public ClientResponse readContactForNamedItemInNamedAuthority( - String parentspecifier, - String itemspecifier, - String csid){ - return getProxy().readContactForNamedItemInNamedAuthority(parentspecifier, itemspecifier, csid); - } - - - /** - * Read contact list. - * - * @param parentcsid the parentcsid - * @param itemcsid the itemcsid - * @return the client response - */ - @Override - public ClientResponse readContactList(String parentcsid, - String itemcsid) { - return getProxy().readContactList(parentcsid, itemcsid); - } - - /** - * Read contact list. - * - * @param parentcsid - * @param itemspecifier (shortIdentifier) - * @return the client response - */ - @Override - public ClientResponse readContactListForNamedItem( - String parentcsid, - String itemspecifier){ - return getProxy().readContactList(parentcsid, itemspecifier); - } - - /** - * Read contact list. - * - * @param parentspecifier (shortIdentifier) - * @param itemcsid - * @return the client response - */ - @Override - public ClientResponse readContactListForItemInNamedAuthority( - String parentspecifier, - String itemcsid){ - return getProxy().readContactList(parentspecifier, itemcsid); - } - - /** - * Read contact list. - * - * @param parentspecifier (shortIdentifier) - * @param itemspecifier (shortIdentifier) - * @return the client response - */ - @Override - public ClientResponse readContactListForNamedItemInNamedAuthority( - String parentspecifier, - String itemspecifier){ - return getProxy().readContactList(parentspecifier, itemspecifier); - } - - /** - * Update contact. - * - * @param parentcsid the parentcsid - * @param itemcsid the itemcsid - * @param csid the csid - * @param multipart the multipart - * @return the client response - */ - @Override - public ClientResponse updateContact(String parentcsid, - String itemcsid, String csid, PoxPayloadOut xmlPayload) { - return getProxy().updateContact(parentcsid, itemcsid, csid, xmlPayload.getBytes()); - } - - /** - * Update contact. - * - * @param parentcsid the parentcsid - * @param itemspecifier (shortIdentifier) - * @param csid the csid - * @param multipart the multipart - * @return the client response - */ - @Override - public ClientResponse updateContactForNamedItem( - String parentcsid, - String itemspecifier, - String csid, - PoxPayloadOut xmlPayload) { - return getProxy().updateContactForNamedItem(parentcsid, itemspecifier, csid, xmlPayload.getBytes()); - } - - /** - * Update contact. - * - * @param parentspecifier (shortIdentifier) - * @param itemcsid the itemcsid - * @param csid the csid - * @param multipart the multipart - * @return the client response - */ - @Override - public ClientResponse updateContactInNamedAuthority( - String parentspecifier, - String itemcsid, - String csid, - PoxPayloadOut xmlPayload) { - return getProxy().updateContactInNamedAuthority(parentspecifier, itemcsid, csid, xmlPayload.getBytes()); - } - - /** - * Update contact. - * - * @param parentspecifier (shortIdentifier) - * @param itemspecifier (shortIdentifier) - * @param csid the csid - * @param multipart the multipart - * @return the client response - */ - @Override - public ClientResponse updateContactForNamedItemInNamedAuthority( - String parentspecifier, - String itemspecifier, - String csid, - PoxPayloadOut xmlPayload) { - return getProxy().updateContactForNamedItemInNamedAuthority(parentspecifier, itemspecifier, csid, - xmlPayload.getBytes()); - } - - /** - * Delete contact. - * - * @param parentcsid the parentcsid - * @param itemcsid the itemcsid - * @param csid the csid - * @return the client response - */ - @Override - public ClientResponse deleteContact(String parentcsid, - String itemcsid, String csid) { - return getProxy().deleteContact(parentcsid, - itemcsid, csid); - } - - /** - * Delete contact. - * - * @param parentcsid the parentcsid - * @param itemspecifier (shortIdentifier) - * @param csid the csid - * @return the client response - */ - @Override - public ClientResponse deleteContactForNamedItem( - String parentcsid, - String itemspecifier, - String csid) { - return getProxy().deleteContactForNamedItem(parentcsid, - itemspecifier, csid); - } - - /** - * Delete contact. - * - * @param parentspecifier (shortIdentifier) - * @param itemcsid the itemcsid - * @param csid the csid - * @return the client response - */ - @Override - public ClientResponse deleteContactInNamedAuthority( - String parentspecifier, - String itemcsid, - String csid) { - return getProxy().deleteContactInNamedAuthority(parentspecifier, - itemcsid, csid); - } - - /** - * Delete contact. - * - * @param parentspecifier (shortIdentifier) - * @param itemspecifier (shortIdentifier) - * @param csid the csid - * @return the client response - */ - @Override - public ClientResponse deleteContactForNamedItemInNamedAuthority( - String parentspecifier, - String itemspecifier, - String csid) { - return getProxy().deleteContactForNamedItemInNamedAuthority(parentspecifier, - itemspecifier, csid); - } - -} +package org.collectionspace.services.client; + +import javax.ws.rs.core.Response; +import org.jboss.resteasy.client.ClientResponse; + +import org.collectionspace.services.jaxb.AbstractCommonList; + +/* + * LT - List type + * ILT - Authority item list type + * P - Proxy type + */ +public abstract class AuthorityWithContactsClientImpl + extends AuthorityClientImpl + implements AuthorityWithContactsClient { + + @Override + public ClientResponse createContact(String parentcsid, + String itemcsid, PoxPayloadOut xmlPayload) { + return getProxy().createContact(parentcsid, itemcsid, xmlPayload.getBytes()); + } + + /** + * Creates the contact. + * + * @param parentcsid + * @param itemspecifier (shortIdentifier) + * @param multipart + * @return the client response + */ + @Override + public ClientResponse createContactForNamedItem( + String parentcsid, + String itemspecifier, + PoxPayloadOut xmlPayload) { + return getProxy().createContactForNamedItem(parentcsid, itemspecifier, xmlPayload.getBytes()); + } + /** + * Creates the contact. + * + * @param parentspecifier (shortIdentifier) + * @param itemcsid + * @param multipart + * @return the client response + */ + @Override + public ClientResponse createContactForItemInNamedAuthority( + String parentspecifier, + String itemcsid, + PoxPayloadOut xmlPayload) { + return getProxy().createContactForItemInNamedAuthority(parentspecifier, + itemcsid, xmlPayload.getBytes()); + } + /** + * Creates the contact. + * + * @param parentspecifier (shortIdentifier) + * @param itemspecifier (shortIdentifier) + * @param multipart + * @return the client response + */ + @Override + public ClientResponse createContactForNamedItemInNamedAuthority( + String parentspecifier, + String itemspecifier, + PoxPayloadOut xmlPayload) { + return getProxy().createContactForNamedItemInNamedAuthority(parentspecifier, itemspecifier, + xmlPayload.getBytes()); + } + + /** + * Read contact. + * + * @param parentcsid the parentcsid + * @param itemcsid the itemcsid + * @param csid the csid + * @return the client response + */ + @Override + public ClientResponse readContact(String parentcsid, + String itemcsid, String csid) { + return getProxy().readContact(parentcsid, itemcsid, csid); + } + + /** + * Read contact. + * + * @param parentcsid + * @param itemspecifier (shortIdentifier) + * @param csid + * @return the client response + */ + @Override + public ClientResponse readContactForNamedItem( + String parentcsid, + String itemspecifier, + String csid){ + return getProxy().readContactForNamedItem(parentcsid, itemspecifier, csid); + } + + /** + * Read contact. + * + * @param parentspecifier (shortIdentifier) + * @param itemcsid + * @param csid + * @return the client response + */ + @Override + public ClientResponse readContactInNamedAuthority( + String parentspecifier, + String itemcsid, + String csid){ + return getProxy().readContactInNamedAuthority(parentspecifier, itemcsid, csid); + } + + /** + * Read contact. + * + * @param parentspecifier (shortIdentifier) + * @param itemspecifier (shortIdentifier) + * @param csid + * @return the client response + */ + @Override + public ClientResponse readContactForNamedItemInNamedAuthority( + String parentspecifier, + String itemspecifier, + String csid){ + return getProxy().readContactForNamedItemInNamedAuthority(parentspecifier, itemspecifier, csid); + } + + + /** + * Read contact list. + * + * @param parentcsid the parentcsid + * @param itemcsid the itemcsid + * @return the client response + */ + @Override + public ClientResponse readContactList(String parentcsid, + String itemcsid) { + return getProxy().readContactList(parentcsid, itemcsid); + } + + /** + * Read contact list. + * + * @param parentcsid + * @param itemspecifier (shortIdentifier) + * @return the client response + */ + @Override + public ClientResponse readContactListForNamedItem( + String parentcsid, + String itemspecifier){ + return getProxy().readContactList(parentcsid, itemspecifier); + } + + /** + * Read contact list. + * + * @param parentspecifier (shortIdentifier) + * @param itemcsid + * @return the client response + */ + @Override + public ClientResponse readContactListForItemInNamedAuthority( + String parentspecifier, + String itemcsid){ + return getProxy().readContactList(parentspecifier, itemcsid); + } + + /** + * Read contact list. + * + * @param parentspecifier (shortIdentifier) + * @param itemspecifier (shortIdentifier) + * @return the client response + */ + @Override + public ClientResponse readContactListForNamedItemInNamedAuthority( + String parentspecifier, + String itemspecifier){ + return getProxy().readContactList(parentspecifier, itemspecifier); + } + + /** + * Update contact. + * + * @param parentcsid the parentcsid + * @param itemcsid the itemcsid + * @param csid the csid + * @param multipart the multipart + * @return the client response + */ + @Override + public ClientResponse updateContact(String parentcsid, + String itemcsid, String csid, PoxPayloadOut xmlPayload) { + return getProxy().updateContact(parentcsid, itemcsid, csid, xmlPayload.getBytes()); + } + + /** + * Update contact. + * + * @param parentcsid the parentcsid + * @param itemspecifier (shortIdentifier) + * @param csid the csid + * @param multipart the multipart + * @return the client response + */ + @Override + public ClientResponse updateContactForNamedItem( + String parentcsid, + String itemspecifier, + String csid, + PoxPayloadOut xmlPayload) { + return getProxy().updateContactForNamedItem(parentcsid, itemspecifier, csid, xmlPayload.getBytes()); + } + + /** + * Update contact. + * + * @param parentspecifier (shortIdentifier) + * @param itemcsid the itemcsid + * @param csid the csid + * @param multipart the multipart + * @return the client response + */ + @Override + public ClientResponse updateContactInNamedAuthority( + String parentspecifier, + String itemcsid, + String csid, + PoxPayloadOut xmlPayload) { + return getProxy().updateContactInNamedAuthority(parentspecifier, itemcsid, csid, xmlPayload.getBytes()); + } + + /** + * Update contact. + * + * @param parentspecifier (shortIdentifier) + * @param itemspecifier (shortIdentifier) + * @param csid the csid + * @param multipart the multipart + * @return the client response + */ + @Override + public ClientResponse updateContactForNamedItemInNamedAuthority( + String parentspecifier, + String itemspecifier, + String csid, + PoxPayloadOut xmlPayload) { + return getProxy().updateContactForNamedItemInNamedAuthority(parentspecifier, itemspecifier, csid, + xmlPayload.getBytes()); + } + + /** + * Delete contact. + * + * @param parentcsid the parentcsid + * @param itemcsid the itemcsid + * @param csid the csid + * @return the client response + */ + @Override + public ClientResponse deleteContact(String parentcsid, + String itemcsid, String csid) { + return getProxy().deleteContact(parentcsid, + itemcsid, csid); + } + + /** + * Delete contact. + * + * @param parentcsid the parentcsid + * @param itemspecifier (shortIdentifier) + * @param csid the csid + * @return the client response + */ + @Override + public ClientResponse deleteContactForNamedItem( + String parentcsid, + String itemspecifier, + String csid) { + return getProxy().deleteContactForNamedItem(parentcsid, + itemspecifier, csid); + } + + /** + * Delete contact. + * + * @param parentspecifier (shortIdentifier) + * @param itemcsid the itemcsid + * @param csid the csid + * @return the client response + */ + @Override + public ClientResponse deleteContactInNamedAuthority( + String parentspecifier, + String itemcsid, + String csid) { + return getProxy().deleteContactInNamedAuthority(parentspecifier, + itemcsid, csid); + } + + /** + * Delete contact. + * + * @param parentspecifier (shortIdentifier) + * @param itemspecifier (shortIdentifier) + * @param csid the csid + * @return the client response + */ + @Override + public ClientResponse deleteContactForNamedItemInNamedAuthority( + String parentspecifier, + String itemspecifier, + String csid) { + return getProxy().deleteContactForNamedItemInNamedAuthority(parentspecifier, + itemspecifier, csid); + } + +} diff --git a/services/contact/client/src/main/java/org/collectionspace/services/client/AuthorityWithContactsProxy.java b/services/contact/client/src/main/java/org/collectionspace/services/client/AuthorityWithContactsProxy.java index c31f4bb18..98e8eec05 100644 --- a/services/contact/client/src/main/java/org/collectionspace/services/client/AuthorityWithContactsProxy.java +++ b/services/contact/client/src/main/java/org/collectionspace/services/client/AuthorityWithContactsProxy.java @@ -1,156 +1,156 @@ -package org.collectionspace.services.client; - -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Response; - -import org.collectionspace.services.jaxb.AbstractCommonList; -import org.jboss.resteasy.client.ClientResponse; - -/* - * ILT = Item list type - * LT = List type - */ -public interface AuthorityWithContactsProxy extends AuthorityProxy { - @GET - @Produces({"application/xml"}) - @Path("/{parentcsid}/items/{itemcsid}/contacts/") - public ClientResponse readContactList( - @PathParam("parentcsid") String parentcsid, - @PathParam("itemcsid") String itemcsid); - - @GET - @Produces({"application/xml"}) - @Path("/{parentcsid}/items/urn:cspace:name({itemspecifier})/contacts/") - ClientResponse readContactListForNamedItem( - @PathParam("parentcsid") String parentcsid, - @PathParam("itemspecifier") String itemspecifier); - - @GET - @Produces({"application/xml"}) - @Path("/urn:cspace:name({parentspecifier})/items/{itemcsid}/contacts/") - ClientResponse readContactListForItemInNamedAuthority( - @PathParam("parentspecifier") String parentspecifier, - @PathParam("itemcsid") String itemcsid); - @GET - @Produces({"application/xml"}) - @Path("/urn:cspace:name({parentspecifier})/items/urn:cspace:name({itemspecifier})/contacts/") - ClientResponse readContactListForNamedItemInNamedAuthority( - @PathParam("parentspecifier") String parentspecifier, - @PathParam("itemspecifier") String itemspecifier); - - //(C)reate Contact - @POST - @Path("/{parentcsid}/items/{itemcsid}/contacts/") - ClientResponse createContact( - @PathParam("parentcsid") String parentcsid, - @PathParam("itemcsid") String itemcsid, - byte[] xmlPayload); - @POST - @Path("/{parentcsid}/items/urn:cspace:name({itemspecifier})/contacts/") - ClientResponse createContactForNamedItem( - @PathParam("parentcsid") String parentcsid, - @PathParam("itemspecifier") String itemspecifier, - byte[] xmlPayload); - @POST - @Path("/urn:cspace:name({parentspecifier})/items/{itemcsid}/contacts/") - ClientResponse createContactForItemInNamedAuthority( - @PathParam("parentspecifier") String parentspecifier, - @PathParam("itemcsid") String itemcsid, - byte[] xmlPayload); - @POST - @Path("/urn:cspace:name({parentspecifier})/items/urn:cspace:name({itemspecifier})/contacts/") - ClientResponse createContactForNamedItemInNamedAuthority( - @PathParam("parentspecifier") String parentspecifier, - @PathParam("itemspecifier") String itemspecifier, - byte[] xmlPayload); - - //(R)ead Contact - @GET - @Path("/{parentcsid}/items/{itemcsid}/contacts/{csid}") - ClientResponse readContact( - @PathParam("parentcsid") String parentcsid, - @PathParam("itemcsid") String itemcsid, - @PathParam("csid") String csid); - @GET - @Path("/{parentcsid}/items/urn:cspace:name({itemspecifier})/contacts/{csid}") - ClientResponse readContactForNamedItem( - @PathParam("parentcsid") String parentcsid, - @PathParam("itemspecifier") String itemspecifier, - @PathParam("csid") String csid); - @GET - @Path("/urn:cspace:name({parentspecifier})/items/{itemcsid}/contacts/{csid}") - ClientResponse readContactInNamedAuthority( - @PathParam("parentspecifier") String parentspecifier, - @PathParam("itemcsid") String itemcsid, - @PathParam("csid") String csid); - @GET - @Path("/urn:cspace:name({parentspecifier})/items/urn:cspace:name({itemspecifier})/contacts/{csid}") - ClientResponse readContactForNamedItemInNamedAuthority( - @PathParam("parentspecifier") String parentspecifier, - @PathParam("itemspecifier") String itemspecifier, - @PathParam("csid") String csid); - - //(U)pdate Contact - @PUT - @Path("/{parentcsid}/items/{itemcsid}/contacts/{csid}") - ClientResponse updateContact( - @PathParam("parentcsid") String parentcsid, - @PathParam("itemcsid") String itemcsid, - @PathParam("csid") String csid, - byte[] xmlPayload); - @PUT - @Path("/{parentcsid}/items/urn:cspace:name({itemspecifier})/contacts/{csid}") - ClientResponse updateContactForNamedItem( - @PathParam("parentcsid") String parentcsid, - @PathParam("itemspecifier") String itemspecifier, - @PathParam("csid") String csid, - byte[] xmlPayload); - @PUT - @Path("/urn:cspace:name({parentspecifier})/items/{itemcsid}/contacts/{csid}") - ClientResponse updateContactInNamedAuthority( - @PathParam("parentspecifier") String parentspecifier, - @PathParam("itemcsid") String itemcsid, - @PathParam("csid") String csid, - byte[] xmlPayload); - @PUT - @Path("/urn:cspace:name({parentspecifier})/items/urn:cspace:name({itemspecifier})/contacts/{csid}") - ClientResponse updateContactForNamedItemInNamedAuthority( - @PathParam("parentspecifier") String parentspecifier, - @PathParam("itemspecifier") String itemspecifier, - @PathParam("csid") String csid, - byte[] xmlPayload); - - //(D)elete Contact - @DELETE - @Path("/{parentcsid}/items/{itemcsid}/contacts/{csid}") - ClientResponse deleteContact( - @PathParam("parentcsid") String parentcsid, - @PathParam("itemcsid") String itemcsid, - @PathParam("csid") String csid); - - @DELETE - @Path("/{parentcsid}/items/urn:cspace:name({itemspecifier})/contacts/{csid}") - ClientResponse deleteContactForNamedItem( - @PathParam("parentcsid") String parentcsid, - @PathParam("itemspecifier") String itemspecifier, - @PathParam("csid") String csid); - @DELETE - @Path("/urn:cspace:name({parentspecifier})/items/{itemcsid}/contacts/{csid}") - ClientResponse deleteContactInNamedAuthority( - @PathParam("parentspecifier") String parentspecifier, - @PathParam("itemcsid") String itemcsid, - @PathParam("csid") String csid); - - @DELETE - @Path("/urn:cspace:name({parentspecifier})/items/urn:cspace:name({itemspecifier})/contacts/{csid}") - ClientResponse deleteContactForNamedItemInNamedAuthority( - @PathParam("parentspecifier") String parentspecifier, - @PathParam("itemspecifier") String itemspecifier, - @PathParam("csid") String csid); -} +package org.collectionspace.services.client; + +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Response; + +import org.collectionspace.services.jaxb.AbstractCommonList; +import org.jboss.resteasy.client.ClientResponse; + +/* + * ILT = Item list type + * LT = List type + */ +public interface AuthorityWithContactsProxy extends AuthorityProxy { + @GET + @Produces({"application/xml"}) + @Path("/{parentcsid}/items/{itemcsid}/contacts/") + public ClientResponse readContactList( + @PathParam("parentcsid") String parentcsid, + @PathParam("itemcsid") String itemcsid); + + @GET + @Produces({"application/xml"}) + @Path("/{parentcsid}/items/urn:cspace:name({itemspecifier})/contacts/") + ClientResponse readContactListForNamedItem( + @PathParam("parentcsid") String parentcsid, + @PathParam("itemspecifier") String itemspecifier); + + @GET + @Produces({"application/xml"}) + @Path("/urn:cspace:name({parentspecifier})/items/{itemcsid}/contacts/") + ClientResponse readContactListForItemInNamedAuthority( + @PathParam("parentspecifier") String parentspecifier, + @PathParam("itemcsid") String itemcsid); + @GET + @Produces({"application/xml"}) + @Path("/urn:cspace:name({parentspecifier})/items/urn:cspace:name({itemspecifier})/contacts/") + ClientResponse readContactListForNamedItemInNamedAuthority( + @PathParam("parentspecifier") String parentspecifier, + @PathParam("itemspecifier") String itemspecifier); + + //(C)reate Contact + @POST + @Path("/{parentcsid}/items/{itemcsid}/contacts/") + ClientResponse createContact( + @PathParam("parentcsid") String parentcsid, + @PathParam("itemcsid") String itemcsid, + byte[] xmlPayload); + @POST + @Path("/{parentcsid}/items/urn:cspace:name({itemspecifier})/contacts/") + ClientResponse createContactForNamedItem( + @PathParam("parentcsid") String parentcsid, + @PathParam("itemspecifier") String itemspecifier, + byte[] xmlPayload); + @POST + @Path("/urn:cspace:name({parentspecifier})/items/{itemcsid}/contacts/") + ClientResponse createContactForItemInNamedAuthority( + @PathParam("parentspecifier") String parentspecifier, + @PathParam("itemcsid") String itemcsid, + byte[] xmlPayload); + @POST + @Path("/urn:cspace:name({parentspecifier})/items/urn:cspace:name({itemspecifier})/contacts/") + ClientResponse createContactForNamedItemInNamedAuthority( + @PathParam("parentspecifier") String parentspecifier, + @PathParam("itemspecifier") String itemspecifier, + byte[] xmlPayload); + + //(R)ead Contact + @GET + @Path("/{parentcsid}/items/{itemcsid}/contacts/{csid}") + ClientResponse readContact( + @PathParam("parentcsid") String parentcsid, + @PathParam("itemcsid") String itemcsid, + @PathParam("csid") String csid); + @GET + @Path("/{parentcsid}/items/urn:cspace:name({itemspecifier})/contacts/{csid}") + ClientResponse readContactForNamedItem( + @PathParam("parentcsid") String parentcsid, + @PathParam("itemspecifier") String itemspecifier, + @PathParam("csid") String csid); + @GET + @Path("/urn:cspace:name({parentspecifier})/items/{itemcsid}/contacts/{csid}") + ClientResponse readContactInNamedAuthority( + @PathParam("parentspecifier") String parentspecifier, + @PathParam("itemcsid") String itemcsid, + @PathParam("csid") String csid); + @GET + @Path("/urn:cspace:name({parentspecifier})/items/urn:cspace:name({itemspecifier})/contacts/{csid}") + ClientResponse readContactForNamedItemInNamedAuthority( + @PathParam("parentspecifier") String parentspecifier, + @PathParam("itemspecifier") String itemspecifier, + @PathParam("csid") String csid); + + //(U)pdate Contact + @PUT + @Path("/{parentcsid}/items/{itemcsid}/contacts/{csid}") + ClientResponse updateContact( + @PathParam("parentcsid") String parentcsid, + @PathParam("itemcsid") String itemcsid, + @PathParam("csid") String csid, + byte[] xmlPayload); + @PUT + @Path("/{parentcsid}/items/urn:cspace:name({itemspecifier})/contacts/{csid}") + ClientResponse updateContactForNamedItem( + @PathParam("parentcsid") String parentcsid, + @PathParam("itemspecifier") String itemspecifier, + @PathParam("csid") String csid, + byte[] xmlPayload); + @PUT + @Path("/urn:cspace:name({parentspecifier})/items/{itemcsid}/contacts/{csid}") + ClientResponse updateContactInNamedAuthority( + @PathParam("parentspecifier") String parentspecifier, + @PathParam("itemcsid") String itemcsid, + @PathParam("csid") String csid, + byte[] xmlPayload); + @PUT + @Path("/urn:cspace:name({parentspecifier})/items/urn:cspace:name({itemspecifier})/contacts/{csid}") + ClientResponse updateContactForNamedItemInNamedAuthority( + @PathParam("parentspecifier") String parentspecifier, + @PathParam("itemspecifier") String itemspecifier, + @PathParam("csid") String csid, + byte[] xmlPayload); + + //(D)elete Contact + @DELETE + @Path("/{parentcsid}/items/{itemcsid}/contacts/{csid}") + ClientResponse deleteContact( + @PathParam("parentcsid") String parentcsid, + @PathParam("itemcsid") String itemcsid, + @PathParam("csid") String csid); + + @DELETE + @Path("/{parentcsid}/items/urn:cspace:name({itemspecifier})/contacts/{csid}") + ClientResponse deleteContactForNamedItem( + @PathParam("parentcsid") String parentcsid, + @PathParam("itemspecifier") String itemspecifier, + @PathParam("csid") String csid); + @DELETE + @Path("/urn:cspace:name({parentspecifier})/items/{itemcsid}/contacts/{csid}") + ClientResponse deleteContactInNamedAuthority( + @PathParam("parentspecifier") String parentspecifier, + @PathParam("itemcsid") String itemcsid, + @PathParam("csid") String csid); + + @DELETE + @Path("/urn:cspace:name({parentspecifier})/items/urn:cspace:name({itemspecifier})/contacts/{csid}") + ClientResponse deleteContactForNamedItemInNamedAuthority( + @PathParam("parentspecifier") String parentspecifier, + @PathParam("itemspecifier") String itemspecifier, + @PathParam("csid") String csid); +} diff --git a/services/dimension/.classpath b/services/dimension/.classpath index 046988541..25df93560 100644 --- a/services/dimension/.classpath +++ b/services/dimension/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/dimension/.project b/services/dimension/.project index c602d4fb8..cb42c3caf 100644 --- a/services/dimension/.project +++ b/services/dimension/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.dimension - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.dimension + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/dimension/3rdparty/.classpath b/services/dimension/3rdparty/.classpath index 046988541..25df93560 100644 --- a/services/dimension/3rdparty/.classpath +++ b/services/dimension/3rdparty/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/dimension/3rdparty/.project b/services/dimension/3rdparty/.project index c7eb0bb79..ebd0b5f50 100644 --- a/services/dimension/3rdparty/.project +++ b/services/dimension/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.dimension.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.dimension.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/dimension/3rdparty/build.xml b/services/dimension/3rdparty/build.xml index f546b4867..c1a8f84a4 100644 --- a/services/dimension/3rdparty/build.xml +++ b/services/dimension/3rdparty/build.xml @@ -1,125 +1,125 @@ - - - - dimension service 3rdparty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + dimension service 3rdparty + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/dimension/3rdparty/nuxeo-platform-cs-dimension/src/main/resources/schemas/dimensions_common.xsd b/services/dimension/3rdparty/nuxeo-platform-cs-dimension/src/main/resources/schemas/dimensions_common.xsd index c60c0e498..67e247613 100644 --- a/services/dimension/3rdparty/nuxeo-platform-cs-dimension/src/main/resources/schemas/dimensions_common.xsd +++ b/services/dimension/3rdparty/nuxeo-platform-cs-dimension/src/main/resources/schemas/dimensions_common.xsd @@ -1,33 +1,33 @@ - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + diff --git a/services/dimension/3rdparty/pom.xml b/services/dimension/3rdparty/pom.xml index 62e2d9d21..3926d94a9 100644 --- a/services/dimension/3rdparty/pom.xml +++ b/services/dimension/3rdparty/pom.xml @@ -1,23 +1,23 @@ - - - - org.collectionspace.services - org.collectionspace.services.dimension - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.dimension.3rdparty - services.dimension.3rdparty - pom - - 3rd party build for dimension service - - - - nuxeo-platform-cs-dimension - - + + + + org.collectionspace.services + org.collectionspace.services.dimension + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.dimension.3rdparty + services.dimension.3rdparty + pom + + 3rd party build for dimension service + + + + nuxeo-platform-cs-dimension + + diff --git a/services/dimension/build.xml b/services/dimension/build.xml index 731846a8e..4cae2b747 100644 --- a/services/dimension/build.xml +++ b/services/dimension/build.xml @@ -1,122 +1,122 @@ - - - - Dimension service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + Dimension service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/dimension/client/pom.xml b/services/dimension/client/pom.xml index eafd148c2..c044f36e5 100644 --- a/services/dimension/client/pom.xml +++ b/services/dimension/client/pom.xml @@ -1,86 +1,86 @@ - - - - - org.collectionspace.services - org.collectionspace.services.dimension - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.dimension.client - services.dimension.client - - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - - org.collectionspace.services - org.collectionspace.services.dimension.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - - - - org.testng - testng - test - - - org.jboss.resteasy - resteasy-jaxrs - - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - commons-httpclient - commons-httpclient - 3.1 - - - - - collectionspace-services-dimension-client - - - + + + + + org.collectionspace.services + org.collectionspace.services.dimension + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.dimension.client + services.dimension.client + + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + + org.collectionspace.services + org.collectionspace.services.dimension.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + + + + org.testng + testng + test + + + org.jboss.resteasy + resteasy-jaxrs + + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + commons-httpclient + commons-httpclient + 3.1 + + + + + collectionspace-services-dimension-client + + + diff --git a/services/dimension/client/src/test/java/org/collectionspace/services/client/test/DimensionXmlReplayTest.java b/services/dimension/client/src/test/java/org/collectionspace/services/client/test/DimensionXmlReplayTest.java index 3b9aefd98..17f121291 100644 --- a/services/dimension/client/src/test/java/org/collectionspace/services/client/test/DimensionXmlReplayTest.java +++ b/services/dimension/client/src/test/java/org/collectionspace/services/client/test/DimensionXmlReplayTest.java @@ -1,42 +1,42 @@ -package org.collectionspace.services.client.test; - -/* - * XMLReplay test classes shoud ***NOT*** be part of the IntegrationTests module. Move them out into the org.collectionspace.services.client (src/main.test) module ASAP! - */ - -/* -import org.collectionspace.services.IntegrationTests.xmlreplay.ServiceResult; -import org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplay; -import org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplayTest; -import org.testng.annotations.Test; - -import java.util.List; -*/ - -/** - * User: laramie - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ -public class DimensionXmlReplayTest /*extends XmlReplayTest*/ { - - /* - //@Test - public void runMaster() throws Exception { - XmlReplay replay = createXmlReplayUsingIntegrationTestsModule("../../"); - List> list = replay.runMaster("dimension-master.xml"); - logTestForGroup(list, "runMaster"); - } - - //@Test - public void runOneTest() throws Exception { - XmlReplay replay = createXmlReplayForModule(); - replay.readOptionsFromMasterConfigFile("dimension-master.xml"); - replay.setControlFileName("dimension.xml"); - - ServiceResult res = replay.runTest("dimensionTestGroup", "dimension1"); - logTest(res, "runOneTest"); - } - */ - -} +package org.collectionspace.services.client.test; + +/* + * XMLReplay test classes shoud ***NOT*** be part of the IntegrationTests module. Move them out into the org.collectionspace.services.client (src/main.test) module ASAP! + */ + +/* +import org.collectionspace.services.IntegrationTests.xmlreplay.ServiceResult; +import org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplay; +import org.collectionspace.services.IntegrationTests.xmlreplay.XmlReplayTest; +import org.testng.annotations.Test; + +import java.util.List; +*/ + +/** + * User: laramie + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ +public class DimensionXmlReplayTest /*extends XmlReplayTest*/ { + + /* + //@Test + public void runMaster() throws Exception { + XmlReplay replay = createXmlReplayUsingIntegrationTestsModule("../../"); + List> list = replay.runMaster("dimension-master.xml"); + logTestForGroup(list, "runMaster"); + } + + //@Test + public void runOneTest() throws Exception { + XmlReplay replay = createXmlReplayForModule(); + replay.readOptionsFromMasterConfigFile("dimension-master.xml"); + replay.setControlFileName("dimension.xml"); + + ServiceResult res = replay.runTest("dimensionTestGroup", "dimension1"); + logTest(res, "runOneTest"); + } + */ + +} diff --git a/services/dimension/client/src/test/resources/log4j.properties b/services/dimension/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/dimension/client/src/test/resources/log4j.properties +++ b/services/dimension/client/src/test/resources/log4j.properties @@ -1,23 +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 +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/dimension/client/src/test/resources/test-data/xmlreplay/dimension-master.xml b/services/dimension/client/src/test/resources/test-data/xmlreplay/dimension-master.xml index fcca1b534..a6f160f7f 100644 --- a/services/dimension/client/src/test/resources/test-data/xmlreplay/dimension-master.xml +++ b/services/dimension/client/src/test/resources/test-data/xmlreplay/dimension-master.xml @@ -1,16 +1,16 @@ - - - http://localhost:8280 - - - - - - dGVzdDp0ZXN0 - - - - - - - + + + http://localhost:8280 + + + + + + dGVzdDp0ZXN0 + + + + + + + diff --git a/services/dimension/client/src/test/resources/test-data/xmlreplay/dimension.xml b/services/dimension/client/src/test/resources/test-data/xmlreplay/dimension.xml index 26064e96b..62f53bd31 100644 --- a/services/dimension/client/src/test/resources/test-data/xmlreplay/dimension.xml +++ b/services/dimension/client/src/test/resources/test-data/xmlreplay/dimension.xml @@ -1,37 +1,37 @@ - - - - - dGVzdDp0ZXN0 - YmlnYmlyZDIwMTA6YmlnYmlyZDIwMTA= - - - - - - - - 401,403 - POST - /cspace-services/dimensions/ - - - dimension/1.xml - - - - - - POST - /cspace-services/dimensions/ - - - dimension/1.xml - - - - - - - + + + + + dGVzdDp0ZXN0 + YmlnYmlyZDIwMTA6YmlnYmlyZDIwMTA= + + + + + + + + 401,403 + POST + /cspace-services/dimensions/ + + + dimension/1.xml + + + + + + POST + /cspace-services/dimensions/ + + + dimension/1.xml + + + + + + + \ No newline at end of file diff --git a/services/dimension/client/src/test/resources/test-data/xmlreplay/dimension/1.xml b/services/dimension/client/src/test/resources/test-data/xmlreplay/dimension/1.xml index 6867ddfaf..205f35b10 100644 --- a/services/dimension/client/src/test/resources/test-data/xmlreplay/dimension/1.xml +++ b/services/dimension/client/src/test/resources/test-data/xmlreplay/dimension/1.xml @@ -1,9 +1,9 @@ - - - dimensionType-1288727556164 - entryNumber-1288727556164 - entryDate-1288727556164 - - + + + dimensionType-1288727556164 + entryNumber-1288727556164 + entryDate-1288727556164 + + diff --git a/services/dimension/jaxb/src/main/java/org/collectionspace/services/dimension/DimensionJAXBSchema.java b/services/dimension/jaxb/src/main/java/org/collectionspace/services/dimension/DimensionJAXBSchema.java index 5007b71d1..60b2d8bc2 100644 --- a/services/dimension/jaxb/src/main/java/org/collectionspace/services/dimension/DimensionJAXBSchema.java +++ b/services/dimension/jaxb/src/main/java/org/collectionspace/services/dimension/DimensionJAXBSchema.java @@ -1,19 +1,19 @@ -/** - * - */ -package org.collectionspace.services.dimension; - -/** - * @author remillet - * - */ -public interface DimensionJAXBSchema { - final static String DIMENSION = "dimension"; - final static String MEASURED_PART = "measuredPart"; - final static String MEASUREMENT_UNIT = "measurementUnit"; - final static String VALUE = "value"; - final static String VALUE_DATE = "valueDate"; - final static String VALUE_QUALIFIER = "valueQualifier"; -} - - +/** + * + */ +package org.collectionspace.services.dimension; + +/** + * @author remillet + * + */ +public interface DimensionJAXBSchema { + final static String DIMENSION = "dimension"; + final static String MEASURED_PART = "measuredPart"; + final static String MEASUREMENT_UNIT = "measurementUnit"; + final static String VALUE = "value"; + final static String VALUE_DATE = "valueDate"; + final static String VALUE_QUALIFIER = "valueQualifier"; +} + + diff --git a/services/dimension/jaxb/src/main/java/org/collectionspace/services/dimension/DimensionListItemJAXBSchema.java b/services/dimension/jaxb/src/main/java/org/collectionspace/services/dimension/DimensionListItemJAXBSchema.java index c159899c8..79aad1616 100644 --- a/services/dimension/jaxb/src/main/java/org/collectionspace/services/dimension/DimensionListItemJAXBSchema.java +++ b/services/dimension/jaxb/src/main/java/org/collectionspace/services/dimension/DimensionListItemJAXBSchema.java @@ -1,7 +1,7 @@ -package org.collectionspace.services.dimension; - -public interface DimensionListItemJAXBSchema { - final static String DIMENSION = "dimension"; - final static String CSID = "csid"; - final static String URI = "url"; -} +package org.collectionspace.services.dimension; + +public interface DimensionListItemJAXBSchema { + final static String DIMENSION = "dimension"; + final static String CSID = "csid"; + final static String URI = "url"; +} diff --git a/services/dimension/pom.xml b/services/dimension/pom.xml index b40bd2e13..b61fa38cd 100644 --- a/services/dimension/pom.xml +++ b/services/dimension/pom.xml @@ -1,36 +1,36 @@ - - - - - - org.collectionspace.services.main - org.collectionspace.services - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.dimension - services.dimension - pom - - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - - - jaxb - service - 3rdparty - client - - - - + + + + + + org.collectionspace.services.main + org.collectionspace.services + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.dimension + services.dimension + pom + + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + + + jaxb + service + 3rdparty + client + + + + diff --git a/services/dimension/service/pom.xml b/services/dimension/service/pom.xml index 8a878cb31..fb23d933f 100644 --- a/services/dimension/service/pom.xml +++ b/services/dimension/service/pom.xml @@ -1,106 +1,106 @@ - - - - - org.collectionspace.services - org.collectionspace.services.dimension - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.dimension.service - services.dimension.service - jar - - - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.dimension.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.dimension.client - ${project.version} - - - - junit - junit - 4.1 - test - - - org.testng - testng - - - - - - javax.security - jaas - 1.0.01 - provided - - - dom4j - dom4j - 1.6.1 - provided - - - - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - - - org.nuxeo.ecm.core - nuxeo-core-api - ${nuxeo.core.version} - - - jboss-remoting - jboss - - - - - - - - collectionspace-services-dimension - - - + + + + + org.collectionspace.services + org.collectionspace.services.dimension + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.dimension.service + services.dimension.service + jar + + + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.dimension.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.dimension.client + ${project.version} + + + + junit + junit + 4.1 + test + + + org.testng + testng + + + + + + javax.security + jaas + 1.0.01 + provided + + + dom4j + dom4j + 1.6.1 + provided + + + + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + + + org.nuxeo.ecm.core + nuxeo-core-api + ${nuxeo.core.version} + + + jboss-remoting + jboss + + + + + + + + collectionspace-services-dimension + + + diff --git a/services/group/.classpath b/services/group/.classpath index 046988541..25df93560 100644 --- a/services/group/.classpath +++ b/services/group/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/group/.project b/services/group/.project index dbf1fa394..b95b1b5db 100644 --- a/services/group/.project +++ b/services/group/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.group - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.group + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/group/3rdparty/.classpath b/services/group/3rdparty/.classpath index 046988541..25df93560 100644 --- a/services/group/3rdparty/.classpath +++ b/services/group/3rdparty/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/group/3rdparty/.project b/services/group/3rdparty/.project index fd5779382..8bf2ac7b9 100644 --- a/services/group/3rdparty/.project +++ b/services/group/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.group.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.group.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/group/client/src/test/resources/log4j.properties b/services/group/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/group/client/src/test/resources/log4j.properties +++ b/services/group/client/src/test/resources/log4j.properties @@ -1,23 +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 +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/hyperjaxb/pom.xml b/services/hyperjaxb/pom.xml index 3465e8712..55059d4bf 100644 --- a/services/hyperjaxb/pom.xml +++ b/services/hyperjaxb/pom.xml @@ -1,79 +1,79 @@ - - - - - - - - org.collectionspace.services - org.collectionspace.services.main - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.hyperjaxb - services.hyperjaxb - - - - - - javax.persistence - persistence-api - - - org.hibernate - hibernate-entitymanager - - - org.jvnet.hyperjaxb3 - hyperjaxb3-ejb-runtime - - - - - collectionspace-services-hyperjaxb - install - - - - org.jvnet.hyperjaxb3 - maven-hyperjaxb3-plugin - - - - - - + + + + + + + + org.collectionspace.services + org.collectionspace.services.main + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.hyperjaxb + services.hyperjaxb + + + + + + javax.persistence + persistence-api + + + org.hibernate + hibernate-entitymanager + + + org.jvnet.hyperjaxb3 + hyperjaxb3-ejb-runtime + + + + + collectionspace-services-hyperjaxb + install + + + + org.jvnet.hyperjaxb3 + maven-hyperjaxb3-plugin + + + + + + diff --git a/services/id/.classpath b/services/id/.classpath index 046988541..25df93560 100644 --- a/services/id/.classpath +++ b/services/id/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/id/.project b/services/id/.project index b8cd682ea..bff7eeff7 100644 --- a/services/id/.project +++ b/services/id/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.id - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.id + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/id/3rdparty/.classpath b/services/id/3rdparty/.classpath index 046988541..25df93560 100644 --- a/services/id/3rdparty/.classpath +++ b/services/id/3rdparty/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/id/3rdparty/nuxeo-platform-cs-id/.classpath b/services/id/3rdparty/nuxeo-platform-cs-id/.classpath index 2b6bb65c8..4d6dcbf50 100644 --- a/services/id/3rdparty/nuxeo-platform-cs-id/.classpath +++ b/services/id/3rdparty/nuxeo-platform-cs-id/.classpath @@ -1,8 +1,8 @@ - - - - - - - - + + + + + + + + diff --git a/services/id/build.xml b/services/id/build.xml index 1837be17f..dae8cf04f 100644 --- a/services/id/build.xml +++ b/services/id/build.xml @@ -1,137 +1,137 @@ - - - - id service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + id service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/id/jaxb/.classpath b/services/id/jaxb/.classpath index 557f8a4e0..4c4656ce5 100644 --- a/services/id/jaxb/.classpath +++ b/services/id/jaxb/.classpath @@ -1,10 +1,10 @@ - - - - - - - - - - + + + + + + + + + + diff --git a/services/id/service/src/test/resources/log4j.properties b/services/id/service/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/id/service/src/test/resources/log4j.properties +++ b/services/id/service/src/test/resources/log4j.properties @@ -1,23 +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 +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/imports/.project b/services/imports/.project index 0ffebd6f0..7804fcf9b 100644 --- a/services/imports/.project +++ b/services/imports/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.imports - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.imports + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/imports/3rdparty/.project b/services/imports/3rdparty/.project index 7e106358f..a2f5cb49f 100644 --- a/services/imports/3rdparty/.project +++ b/services/imports/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.imports.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.imports.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/imports/3rdparty/nuxeo-platform-cs-imports/src/main/resources/META-INF/MANIFEST.MF b/services/imports/3rdparty/nuxeo-platform-cs-imports/src/main/resources/META-INF/MANIFEST.MF index 3185c7c03..524a8f744 100644 --- a/services/imports/3rdparty/nuxeo-platform-cs-imports/src/main/resources/META-INF/MANIFEST.MF +++ b/services/imports/3rdparty/nuxeo-platform-cs-imports/src/main/resources/META-INF/MANIFEST.MF @@ -1,22 +1,22 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 1 -Bundle-Name: NuxeoCS -Bundle-SymbolicName: org.collectionspace.imports;singleton:=true -Bundle-Version: 1.0.0 -Bundle-Localization: plugin -Bundle-Vendor: Nuxeo -Require-Bundle: org.nuxeo.runtime, - org.nuxeo.ecm.core.api, - org.nuxeo.ecm.core, - org.nuxeo.ecm.core.api, - org.nuxeo.ecm.platform.types.api, - org.nuxeo.ecm.platform.versioning.api, - org.nuxeo.ecm.platform.ui, - org.nuxeo.ecm.platform.forms.layout.client, - org.nuxeo.ecm.platform.ws, - org.collectionspace.collectionspace_core -Provide-Package: org.collectionspace.imports -Nuxeo-Component: OSGI-INF/core-types-contrib.xml, - OSGI-INF/ecm-types-contrib.xml, - OSGI-INF/layouts-contrib.xml - +Manifest-Version: 1.0 +Bundle-ManifestVersion: 1 +Bundle-Name: NuxeoCS +Bundle-SymbolicName: org.collectionspace.imports;singleton:=true +Bundle-Version: 1.0.0 +Bundle-Localization: plugin +Bundle-Vendor: Nuxeo +Require-Bundle: org.nuxeo.runtime, + org.nuxeo.ecm.core.api, + org.nuxeo.ecm.core, + org.nuxeo.ecm.core.api, + org.nuxeo.ecm.platform.types.api, + org.nuxeo.ecm.platform.versioning.api, + org.nuxeo.ecm.platform.ui, + org.nuxeo.ecm.platform.forms.layout.client, + org.nuxeo.ecm.platform.ws, + org.collectionspace.collectionspace_core +Provide-Package: org.collectionspace.imports +Nuxeo-Component: OSGI-INF/core-types-contrib.xml, + OSGI-INF/ecm-types-contrib.xml, + OSGI-INF/layouts-contrib.xml + diff --git a/services/imports/3rdparty/nuxeo-platform-cs-imports/src/main/resources/schemas/imports_common.xsd b/services/imports/3rdparty/nuxeo-platform-cs-imports/src/main/resources/schemas/imports_common.xsd index c6299df02..7ff0f5ae3 100644 --- a/services/imports/3rdparty/nuxeo-platform-cs-imports/src/main/resources/schemas/imports_common.xsd +++ b/services/imports/3rdparty/nuxeo-platform-cs-imports/src/main/resources/schemas/imports_common.xsd @@ -1,18 +1,18 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + diff --git a/services/imports/service/src/main/java/org/collectionspace/services/imports/nuxeo/ImportCommand.java b/services/imports/service/src/main/java/org/collectionspace/services/imports/nuxeo/ImportCommand.java index 32d6dc5c3..2d943836d 100644 --- a/services/imports/service/src/main/java/org/collectionspace/services/imports/nuxeo/ImportCommand.java +++ b/services/imports/service/src/main/java/org/collectionspace/services/imports/nuxeo/ImportCommand.java @@ -1,131 +1,131 @@ -package org.collectionspace.services.imports.nuxeo; - -import java.io.File; -import java.util.Calendar; -import java.util.HashMap; -import java.util.Map; -import java.util.TreeSet; - -import org.collectionspace.services.common.api.Tools; -import org.collectionspace.services.nuxeo.client.java.NuxeoClientEmbedded; -import org.collectionspace.services.nuxeo.client.java.NuxeoConnectorEmbedded; -import org.collectionspace.services.nuxeo.client.java.RepositoryInstanceInterface; -import org.nuxeo.ecm.core.api.DocumentModel; -import org.nuxeo.ecm.core.api.DocumentRef; -import org.nuxeo.ecm.core.api.repository.RepositoryInstance; -import org.nuxeo.ecm.core.io.DocumentPipe; -import org.nuxeo.ecm.core.io.DocumentReader; -import org.nuxeo.ecm.core.io.DocumentTranslationMap; -import org.nuxeo.ecm.core.io.DocumentWriter; -import org.nuxeo.ecm.core.io.impl.DocumentPipeImpl; -import org.nuxeo.ecm.core.io.impl.plugins.DocumentModelWriter; -// we use our own override of this: import org.nuxeo.ecm.core.io.impl.plugins.XMLDirectoryReader; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -// based loosely on package org.nuxeo.ecm.shell.commands.io.ImportCommand; -public class ImportCommand { - - private final Logger logger = LoggerFactory.getLogger(ImportCommand.class); - - public String run(String src, String repoName, String workspacesPath, int timeOut) throws Exception { - File file = new File(src); - ///cspace way of configuring client and auth: - NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient(); - RepositoryInstanceInterface repoSession = null; - try { - repoSession = client.openRepository(repoName, timeOut); - if (logger.isDebugEnabled()) { - String msg = String.format("Start of import is Local time: %tT", Calendar.getInstance()); - logger.debug(msg); - } - return importTree(repoSession, file, workspacesPath); - } catch (Exception e) { - throw e; - } finally { - if (logger.isDebugEnabled()) { - String msg = String.format("End of import is Local time: %tT", Calendar.getInstance()); - logger.debug(msg); - } - client.releaseRepository(repoSession); - } - } - - String importTree(RepositoryInstanceInterface repoSession, File file, String toPath) throws Exception { - Exception failed = null; - DocumentReader reader = null; - DocumentWriter writer = null; - DocumentModel docModel = null; - DocumentRef keyDocRef, valueDocRef; - String docType; - StringBuffer dump = new StringBuffer(); - Map recordsImportedForDocType = new HashMap(); - Integer numRecordsImportedForDocType = new Integer(0); - int totalRecordsImported = 0; - try { - if (logger.isInfoEnabled()) { - logger.info("importTree reading file: " + file + (file != null ? " exists? " + file.exists() : " file param is null")); - } - reader = new LoggedXMLDirectoryReader(file); //our overload of XMLDirectoryReader. - writer = new DocumentModelWriter(repoSession.getRepositoryInstance(), toPath, 10); - DocumentPipe pipe = new DocumentPipeImpl(10); - // pipe.addTransformer(transformer); - pipe.setReader(reader); - pipe.setWriter(writer); - DocumentTranslationMap dtm = pipe.run(); - Map documentRefs = dtm.getDocRefMap(); // FIXME: Should be checking for null here! - dump.append(""); - for (Map.Entry entry : documentRefs.entrySet()) { - keyDocRef = (DocumentRef) entry.getKey(); - valueDocRef = (DocumentRef) entry.getValue(); - if (keyDocRef == null || valueDocRef == null) { - continue; - } - dump.append(""); - docModel = repoSession.getDocument(valueDocRef); - docType = docModel.getDocumentType().getName(); - dump.append("" + docType + ""); - dump.append("" + keyDocRef.toString() + ""); - dump.append(""); - if (recordsImportedForDocType.containsKey(docType)) { - numRecordsImportedForDocType = (Integer) recordsImportedForDocType.get(docType); - numRecordsImportedForDocType = Integer.valueOf(numRecordsImportedForDocType.intValue() + 1); - recordsImportedForDocType.put(docType, numRecordsImportedForDocType); - } else { - recordsImportedForDocType.put(docType, 1); - } - totalRecordsImported++; - } - dump.append(""); - } catch (Exception e) { - failed = e; - throw failed; - } finally { - String status = failed == null ? "Success" : "Failed"; - dump.append("" + status + ""); - dump.append("" + totalRecordsImported + ""); - dump.append(""); - TreeSet keys = new TreeSet(recordsImportedForDocType.keySet()); - for (String key : keys) { - dump.append(""); - dump.append("" + key + ""); - dump.append("" + recordsImportedForDocType.get(key).intValue() + ""); - dump.append(""); - } - dump.append(""); - if (reader != null) { - dump.append("" + (((LoggedXMLDirectoryReader) reader).report()) + ""); - reader.close(); - } - if (writer != null) { - writer.close(); - } - - if (failed != null) { - String msg = "The Import service encountered an exception: " + failed.getLocalizedMessage(); - logger.error(msg, failed); - } - } - return dump.toString(); - } +package org.collectionspace.services.imports.nuxeo; + +import java.io.File; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeSet; + +import org.collectionspace.services.common.api.Tools; +import org.collectionspace.services.nuxeo.client.java.NuxeoClientEmbedded; +import org.collectionspace.services.nuxeo.client.java.NuxeoConnectorEmbedded; +import org.collectionspace.services.nuxeo.client.java.RepositoryInstanceInterface; +import org.nuxeo.ecm.core.api.DocumentModel; +import org.nuxeo.ecm.core.api.DocumentRef; +import org.nuxeo.ecm.core.api.repository.RepositoryInstance; +import org.nuxeo.ecm.core.io.DocumentPipe; +import org.nuxeo.ecm.core.io.DocumentReader; +import org.nuxeo.ecm.core.io.DocumentTranslationMap; +import org.nuxeo.ecm.core.io.DocumentWriter; +import org.nuxeo.ecm.core.io.impl.DocumentPipeImpl; +import org.nuxeo.ecm.core.io.impl.plugins.DocumentModelWriter; +// we use our own override of this: import org.nuxeo.ecm.core.io.impl.plugins.XMLDirectoryReader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +// based loosely on package org.nuxeo.ecm.shell.commands.io.ImportCommand; +public class ImportCommand { + + private final Logger logger = LoggerFactory.getLogger(ImportCommand.class); + + public String run(String src, String repoName, String workspacesPath, int timeOut) throws Exception { + File file = new File(src); + ///cspace way of configuring client and auth: + NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient(); + RepositoryInstanceInterface repoSession = null; + try { + repoSession = client.openRepository(repoName, timeOut); + if (logger.isDebugEnabled()) { + String msg = String.format("Start of import is Local time: %tT", Calendar.getInstance()); + logger.debug(msg); + } + return importTree(repoSession, file, workspacesPath); + } catch (Exception e) { + throw e; + } finally { + if (logger.isDebugEnabled()) { + String msg = String.format("End of import is Local time: %tT", Calendar.getInstance()); + logger.debug(msg); + } + client.releaseRepository(repoSession); + } + } + + String importTree(RepositoryInstanceInterface repoSession, File file, String toPath) throws Exception { + Exception failed = null; + DocumentReader reader = null; + DocumentWriter writer = null; + DocumentModel docModel = null; + DocumentRef keyDocRef, valueDocRef; + String docType; + StringBuffer dump = new StringBuffer(); + Map recordsImportedForDocType = new HashMap(); + Integer numRecordsImportedForDocType = new Integer(0); + int totalRecordsImported = 0; + try { + if (logger.isInfoEnabled()) { + logger.info("importTree reading file: " + file + (file != null ? " exists? " + file.exists() : " file param is null")); + } + reader = new LoggedXMLDirectoryReader(file); //our overload of XMLDirectoryReader. + writer = new DocumentModelWriter(repoSession.getRepositoryInstance(), toPath, 10); + DocumentPipe pipe = new DocumentPipeImpl(10); + // pipe.addTransformer(transformer); + pipe.setReader(reader); + pipe.setWriter(writer); + DocumentTranslationMap dtm = pipe.run(); + Map documentRefs = dtm.getDocRefMap(); // FIXME: Should be checking for null here! + dump.append(""); + for (Map.Entry entry : documentRefs.entrySet()) { + keyDocRef = (DocumentRef) entry.getKey(); + valueDocRef = (DocumentRef) entry.getValue(); + if (keyDocRef == null || valueDocRef == null) { + continue; + } + dump.append(""); + docModel = repoSession.getDocument(valueDocRef); + docType = docModel.getDocumentType().getName(); + dump.append("" + docType + ""); + dump.append("" + keyDocRef.toString() + ""); + dump.append(""); + if (recordsImportedForDocType.containsKey(docType)) { + numRecordsImportedForDocType = (Integer) recordsImportedForDocType.get(docType); + numRecordsImportedForDocType = Integer.valueOf(numRecordsImportedForDocType.intValue() + 1); + recordsImportedForDocType.put(docType, numRecordsImportedForDocType); + } else { + recordsImportedForDocType.put(docType, 1); + } + totalRecordsImported++; + } + dump.append(""); + } catch (Exception e) { + failed = e; + throw failed; + } finally { + String status = failed == null ? "Success" : "Failed"; + dump.append("" + status + ""); + dump.append("" + totalRecordsImported + ""); + dump.append(""); + TreeSet keys = new TreeSet(recordsImportedForDocType.keySet()); + for (String key : keys) { + dump.append(""); + dump.append("" + key + ""); + dump.append("" + recordsImportedForDocType.get(key).intValue() + ""); + dump.append(""); + } + dump.append(""); + if (reader != null) { + dump.append("" + (((LoggedXMLDirectoryReader) reader).report()) + ""); + reader.close(); + } + if (writer != null) { + writer.close(); + } + + if (failed != null) { + String msg = "The Import service encountered an exception: " + failed.getLocalizedMessage(); + logger.error(msg, failed); + } + } + return dump.toString(); + } } \ No newline at end of file diff --git a/services/imports/service/src/main/resources/templates/service-document.xml b/services/imports/service/src/main/resources/templates/service-document.xml index 5c6419681..6aeb26224 100644 --- a/services/imports/service/src/main/resources/templates/service-document.xml +++ b/services/imports/service/src/main/resources/templates/service-document.xml @@ -1,49 +1,49 @@ - - - ${ServiceType} - ${ServiceName}/${docID} - project - default - - - - - - - - - Administrator - - Administrator - - - 2011-03-05T00:06:17Z - - - - - - - 2011-03-05T00:06:17Z - - - - - - - - - - - - ${createdAt} - ${createdBy} - ${updatedAt} - ${updatedBy} - ${tenantID} - ${uri} - ${refName} - - ${Schema} - - + + + ${ServiceType} + ${ServiceName}/${docID} + project + default + + + + + + + + + Administrator + + Administrator + + + 2011-03-05T00:06:17Z + + + + + + + 2011-03-05T00:06:17Z + + + + + + + + + + + + ${createdAt} + ${createdBy} + ${updatedAt} + ${updatedBy} + ${tenantID} + ${uri} + ${refName} + + ${Schema} + + diff --git a/services/imports/service/src/test/resources/requests/authority-request.xml b/services/imports/service/src/test/resources/requests/authority-request.xml index 800e073e8..c15587e92 100644 --- a/services/imports/service/src/test/resources/requests/authority-request.xml +++ b/services/imports/service/src/test/resources/requests/authority-request.xml @@ -1,19 +1,19 @@ - - - - - Perf Test Person Auth ${docID} - perfTestPersons-${docID} - PersonAuthority - urn:cspace:collectionspace.org:Personauthorities(perfTestPersons)'Perf Test Person Auth' - - - - - Perf Test Person Auth ${docID} - perfTestPersons-${docID} - PersonAuthority - urn:cspace:collectionspace.org:Personauthorities(perfTestPersons)'Perf Test Person Auth' - - + + + + + Perf Test Person Auth ${docID} + perfTestPersons-${docID} + PersonAuthority + urn:cspace:collectionspace.org:Personauthorities(perfTestPersons)'Perf Test Person Auth' + + + + + Perf Test Person Auth ${docID} + perfTestPersons-${docID} + PersonAuthority + urn:cspace:collectionspace.org:Personauthorities(perfTestPersons)'Perf Test Person Auth' + + \ No newline at end of file diff --git a/services/imports/service/src/test/resources/requests/collectionobject-request.xml b/services/imports/service/src/test/resources/requests/collectionobject-request.xml index f336e91ac..1d229a32d 100644 --- a/services/imports/service/src/test/resources/requests/collectionobject-request.xml +++ b/services/imports/service/src/test/resources/requests/collectionobject-request.xml @@ -1,276 +1,276 @@ - - - - - - - - - public - - - - gothic-script - urn:cspace:org.collectionspace.demo:orgauthority:name(organization):organization:name(screenmagicinc.)'Screen+Magic+Inc.' - No, it's true, I'm not a baguette - label - I'm a vegetarian - - Non, c'est vrai! Je ne suis pas une baguette - It could mean a lot of things, but oddly no connection to ogres - arabic - base - - - - - - - decoration - bottom - urn:cspace:org.collectionspace.demo:personauthority:name(person):person:name(reginabadet)'Regina+Badet' - - No Idea - Big symbol at the base - - - - - - - The Ogres hand - - - - urn:cspace:org.collectionspace.demo:personauthority:name(person):person:name(maryannecasseta)'Mary+Anne+Cassata' - - - - - 78 - record-speed - rpm - - - - - - - - - urn:cspace:org.collectionspace.demo:orgauthority:name(organization):organization:name(boardwalkrecords)'Boardwalk+Records' - - - - - - sleeve - - - - - - - - - - - - - - - - 1 - poundsterling - - - - - - - 123-bg-192 - - - - - - A petrified Ogre found in the woods of Neverland - Or it could be a petrified tree looking slightly like an ogre - Or just a rock, looking a lot like a petrified tree - - - - - - - - These object records are tedious to fill out - Content of a piece of rock?! .. well there might be diamonds and petrified fish in it - - - - - - - - - - - - - - - It's pretty big - the size of an ogre.. Three arms and a hump-back - - - years - - - - - - - - - pst., it's not a real ogre - -
-
- - - none - - - urn:cspace:org.collectionspace.demo:orgauthority:name(organization):organization:name(7-eleven)'7-Eleven' - - CompleteObject001 - - - - - - - - urn:cspace:org.collectionspace.demo:orgauthority:name(organization):organization:name(wolperorganization)'Wolper+Organization' - - exchange - - - .. But it wasn't - 10223 - study-collection - Made out of rock, pretty big - - fieldCollectionEventName - - - urn:cspace:org.collectionspace.demo:personauthority:name(person):person:name(gingerrogers)'Ginger+Rogers' - - - - - urn:cspace:org.collectionspace.demo:personauthority:name(person):person:name(virginiaboardman)'Virginia+Boardman' - - - Haven't really contributed with much - Should have gone with an automagic solution - Someone found it, then gave it to a museum, duh! - 1 - - - Petrified Ogre - klingon - waka waka - generic - swahili - - - - - Probably a horrible one, considering how uninteresting this object is - - Seriously guys, it's just a piece of rock - - - adult - - - current - french - - nomenclature - simple - Je ne suis pas une baguette - subgroup - - - - - - - - You got the basic details down - it was horrible, what else can I say - - - - - - - - - - - - - - - associated act. note - - - - - \"yeah, that was pretty horrible\", viewer, 1982 - - - - - Dont know what viewers role is - in-process - Document - - - - - - - - - - - open - - 189 - - - - - - - female - - - - rocky balboa rocks - It is not gold - - - - - - antiquities - decorative-arts - ethnography - -
-
-
+ + + + + + + + + public + + + + gothic-script + urn:cspace:org.collectionspace.demo:orgauthority:name(organization):organization:name(screenmagicinc.)'Screen+Magic+Inc.' + No, it's true, I'm not a baguette + label + I'm a vegetarian + + Non, c'est vrai! Je ne suis pas une baguette + It could mean a lot of things, but oddly no connection to ogres + arabic + base + + + + + + + decoration + bottom + urn:cspace:org.collectionspace.demo:personauthority:name(person):person:name(reginabadet)'Regina+Badet' + + No Idea + Big symbol at the base + + + + + + + The Ogres hand + + + + urn:cspace:org.collectionspace.demo:personauthority:name(person):person:name(maryannecasseta)'Mary+Anne+Cassata' + + + + + 78 + record-speed + rpm + + + + + + + + + urn:cspace:org.collectionspace.demo:orgauthority:name(organization):organization:name(boardwalkrecords)'Boardwalk+Records' + + + + + + sleeve + + + + + + + + + + + + + + + + 1 + poundsterling + + + + + + + 123-bg-192 + + + + + + A petrified Ogre found in the woods of Neverland + Or it could be a petrified tree looking slightly like an ogre + Or just a rock, looking a lot like a petrified tree + + + + + + + + These object records are tedious to fill out + Content of a piece of rock?! .. well there might be diamonds and petrified fish in it + + + + + + + + + + + + + + + It's pretty big - the size of an ogre.. Three arms and a hump-back + + + years + + + + + + + + + pst., it's not a real ogre + +
+
+ + + none + + + urn:cspace:org.collectionspace.demo:orgauthority:name(organization):organization:name(7-eleven)'7-Eleven' + + CompleteObject001 + + + + + + + + urn:cspace:org.collectionspace.demo:orgauthority:name(organization):organization:name(wolperorganization)'Wolper+Organization' + + exchange + + + .. But it wasn't + 10223 + study-collection + Made out of rock, pretty big + + fieldCollectionEventName + + + urn:cspace:org.collectionspace.demo:personauthority:name(person):person:name(gingerrogers)'Ginger+Rogers' + + + + + urn:cspace:org.collectionspace.demo:personauthority:name(person):person:name(virginiaboardman)'Virginia+Boardman' + + + Haven't really contributed with much + Should have gone with an automagic solution + Someone found it, then gave it to a museum, duh! + 1 + + + Petrified Ogre + klingon + waka waka + generic + swahili + + + + + Probably a horrible one, considering how uninteresting this object is + + Seriously guys, it's just a piece of rock + + + adult + + + current + french + + nomenclature + simple + Je ne suis pas une baguette + subgroup + + + + + + + + You got the basic details down - it was horrible, what else can I say + + + + + + + + + + + + + + + associated act. note + + + + + \"yeah, that was pretty horrible\", viewer, 1982 + + + + + Dont know what viewers role is + in-process + Document + + + + + + + + + + + open + + 189 + + + + + + + female + + + + rocky balboa rocks + It is not gold + + + + + + antiquities + decorative-arts + ethnography + +
+
+
diff --git a/services/installer/build.xml b/services/installer/build.xml index ad9a4d19a..97db7952d 100644 --- a/services/installer/build.xml +++ b/services/installer/build.xml @@ -1,79 +1,79 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/intake/.classpath b/services/intake/.classpath index 046988541..25df93560 100644 --- a/services/intake/.classpath +++ b/services/intake/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/intake/.project b/services/intake/.project index 7f4c7ed69..00de592f3 100644 --- a/services/intake/.project +++ b/services/intake/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.intake - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.intake + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/intake/3rdparty/.classpath b/services/intake/3rdparty/.classpath index 046988541..25df93560 100644 --- a/services/intake/3rdparty/.classpath +++ b/services/intake/3rdparty/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/intake/3rdparty/.project b/services/intake/3rdparty/.project index 3b8c16a8a..1d1c7467b 100644 --- a/services/intake/3rdparty/.project +++ b/services/intake/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.intake.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.intake.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/intake/3rdparty/build.xml b/services/intake/3rdparty/build.xml index 5c30ec729..3e7a517d6 100644 --- a/services/intake/3rdparty/build.xml +++ b/services/intake/3rdparty/build.xml @@ -1,129 +1,129 @@ - - - - intake service 3rdparty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + intake service 3rdparty + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/intake/3rdparty/pom.xml b/services/intake/3rdparty/pom.xml index 246cb4a17..260484239 100644 --- a/services/intake/3rdparty/pom.xml +++ b/services/intake/3rdparty/pom.xml @@ -1,25 +1,25 @@ - - - - org.collectionspace.services.intake - org.collectionspace.services - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.intake.3rdparty - services.intake.3rdparty - pom - - - 3rd party build for intake service - - - - - - + + + + org.collectionspace.services.intake + org.collectionspace.services + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.intake.3rdparty + services.intake.3rdparty + pom + + + 3rd party build for intake service + + + + + + diff --git a/services/intake/build.xml b/services/intake/build.xml index fa973a6f0..ba68283e1 100644 --- a/services/intake/build.xml +++ b/services/intake/build.xml @@ -1,124 +1,124 @@ - - - - intake service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + intake service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/intake/client/pom.xml b/services/intake/client/pom.xml index 5f231b296..04ce160e7 100644 --- a/services/intake/client/pom.xml +++ b/services/intake/client/pom.xml @@ -1,101 +1,101 @@ - - - - org.collectionspace.services - org.collectionspace.services.intake - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.intake.client - services.intake.client - - - - - org.slf4j - slf4j-api - test - - - org.slf4j - slf4j-log4j12 - test - - - - org.collectionspace.services - org.collectionspace.services.authority.jaxb - true - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.common - true - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.intake.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.person.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.organization.client - ${project.version} - - - - org.testng - testng - - - org.jboss.resteasy - resteasy-jaxrs - - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - commons-httpclient - commons-httpclient - 3.1 - - - - - collectionspace-services-intake-client - - - + + + + org.collectionspace.services + org.collectionspace.services.intake + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.intake.client + services.intake.client + + + + + org.slf4j + slf4j-api + test + + + org.slf4j + slf4j-log4j12 + test + + + + org.collectionspace.services + org.collectionspace.services.authority.jaxb + true + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.common + true + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.intake.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.person.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.organization.client + ${project.version} + + + + org.testng + testng + + + org.jboss.resteasy + resteasy-jaxrs + + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + commons-httpclient + commons-httpclient + 3.1 + + + + + collectionspace-services-intake-client + + + diff --git a/services/intake/client/src/test/java/org/collectionspace/services/client/test/OrganizationAuthRefDocsTest.java b/services/intake/client/src/test/java/org/collectionspace/services/client/test/OrganizationAuthRefDocsTest.java index 95f4d9056..be59cc252 100644 --- a/services/intake/client/src/test/java/org/collectionspace/services/client/test/OrganizationAuthRefDocsTest.java +++ b/services/intake/client/src/test/java/org/collectionspace/services/client/test/OrganizationAuthRefDocsTest.java @@ -1,370 +1,370 @@ -/** - * 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 Regents of the University of California - * - * 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.client.test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.collectionspace.services.OrganizationJAXBSchema; -import org.collectionspace.services.client.CollectionSpaceClient; -import org.collectionspace.services.client.IntakeClient; -import org.collectionspace.services.client.OrgAuthorityClient; -import org.collectionspace.services.client.OrgAuthorityClientUtils; -import org.collectionspace.services.client.PayloadOutputPart; -import org.collectionspace.services.client.PoxPayloadOut; -import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils; -import org.collectionspace.services.common.authorityref.AuthorityRefDocList; -import org.collectionspace.services.intake.ConditionCheckerOrAssessorList; -import org.collectionspace.services.intake.IntakesCommon; -import org.collectionspace.services.intake.InsurerList; -import org.collectionspace.services.jaxb.AbstractCommonList; -import org.collectionspace.services.organization.OrgTermGroup; - -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.AfterClass; -import org.testng.annotations.Test; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * OrganizationAuthRefDocsTest, carries out tests against a - * deployed and running Organization Service. - * - * $LastChangedRevision: 1327 $ - * $LastChangedDate: 2010-02-12 10:35:11 -0800 (Fri, 12 Feb 2010) $ - */ -public class OrganizationAuthRefDocsTest extends BaseServiceTest { - - private final String CLASS_NAME = OrganizationAuthRefDocsTest.class.getName(); - private final Logger logger = LoggerFactory.getLogger(CLASS_NAME); - - // Instance variables specific to this test. - final String SERVICE_PATH_COMPONENT = "intakes"; - final String ORGANIZATION_AUTHORITY_NAME = "TestOrganizationAuth"; - private String knownIntakeId = null; - private List intakeIdsCreated = new ArrayList(); - private List orgIdsCreated = new ArrayList(); - private String orgAuthCSID = null; - //private String orgAuthRefName = null; - private String currentOwnerOrgCSID = null; - private String currentOwnerRefName = null; - private String depositorRefName = null; - private String conditionCheckerAssessorRefName = null; - private String insurerRefName = null; - private String valuerRefName = null; - private final int NUM_AUTH_REF_DOCS_EXPECTED = 1; - private final static String CURRENT_DATE_UTC = - GregorianCalendarDateTimeUtils.currentDateUTC(); - - @Override - protected String getServiceName() { - throw new UnsupportedOperationException(); //FIXME: REM - See http://issues.collectionspace.org/browse/CSPACE-3498 - } - - /* (non-Javadoc) - * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance() - */ - @Override - protected CollectionSpaceClient getClientInstance() { - throw new UnsupportedOperationException(); //method not supported (or needed) in this test class - } - - /* (non-Javadoc) - * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse) - */ - @Override - protected AbstractCommonList getCommonList( - ClientResponse response) { - throw new UnsupportedOperationException(); //method not supported (or needed) in this test class - } - - // --------------------------------------------------------------- - // CRUD tests : CREATE tests - // --------------------------------------------------------------- - // Success outcomes - @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class) - public void createIntakeWithAuthRefs(String testName) throws Exception { - testSetup(STATUS_CREATED, ServiceRequestType.CREATE); - - // Submit the request to the service and store the response. - String identifier = createIdentifier(); - - // Create all the organization refs and entities - createOrgRefs(); - - IntakeClient intakeClient = new IntakeClient(); - PoxPayloadOut multipart = createIntakeInstance( - "entryNumber-" + identifier, - CURRENT_DATE_UTC, - currentOwnerRefName, - // Use currentOwnerRefName twice to test fix for CSPACE-2863 - currentOwnerRefName, //depositorRefName, - conditionCheckerAssessorRefName, - insurerRefName, - valuerRefName ); - - ClientResponse res = intakeClient.create(multipart); - try { - int statusCode = res.getStatus(); - - // Check the status code of the response: does it match - // the expected response(s)? - // - // Specifically: - // Does it fall within the set of valid status codes? - // Does it exactly match the expected status code? - if(logger.isDebugEnabled()){ - logger.debug(testName + ": status = " + statusCode); - } - Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), - invalidStatusCodeMessage(testRequestType, statusCode)); - Assert.assertEquals(statusCode, testExpectedStatusCode); - } finally { - res.releaseConnection(); - } - - // Store the ID returned from the first resource created - // for additional tests below. - if (knownIntakeId == null){ - knownIntakeId = extractId(res); - if (logger.isDebugEnabled()) { - logger.debug(testName + ": knownIntakeId=" + knownIntakeId); - } - } - - // Store the IDs from every resource created by tests, - // so they can be deleted after tests have been run. - intakeIdsCreated.add(extractId(res)); - } - - /** - * Creates the organization refs. - */ - protected void createOrgRefs(){ - OrgAuthorityClient orgAuthClient = new OrgAuthorityClient(); - //orgAuthRefName = - // OrgAuthorityClientUtils.createOrgAuthRefName(ORGANIZATION_AUTHORITY_NAME, null); - PoxPayloadOut multipart = OrgAuthorityClientUtils.createOrgAuthorityInstance( - ORGANIZATION_AUTHORITY_NAME, ORGANIZATION_AUTHORITY_NAME, orgAuthClient.getCommonPartName()); - ClientResponse res = orgAuthClient.create(multipart); - int statusCode = res.getStatus(); - - Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), - invalidStatusCodeMessage(testRequestType, statusCode)); - Assert.assertEquals(statusCode, STATUS_CREATED); - orgAuthCSID = extractId(res); - - currentOwnerOrgCSID = createOrganization("olivierOwnerCompany", "Olivier Owner Company", "Olivier Owner Company"); - orgIdsCreated.add(currentOwnerOrgCSID); - currentOwnerRefName = OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, currentOwnerOrgCSID, orgAuthClient); - - String newOrgCSID = - createOrganization("debbieDepositorAssocs", "Debbie Depositor & Associates", "Debbie Depositor & Associates"); - depositorRefName = - OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, newOrgCSID, orgAuthClient); - orgIdsCreated.add(newOrgCSID); - - newOrgCSID = createOrganization("andrewCheckerAssessorLtd", "Andrew Checker-Assessor Ltd.", "Andrew Checker-Assessor Ltd."); - conditionCheckerAssessorRefName = - OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, newOrgCSID, orgAuthClient); - orgIdsCreated.add(newOrgCSID); - - newOrgCSID = createOrganization("ingridInsurerBureau", "Ingrid Insurer Bureau", "Ingrid Insurer Bureau"); - insurerRefName = - OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, newOrgCSID, orgAuthClient); - orgIdsCreated.add(newOrgCSID); - - newOrgCSID = createOrganization("vinceValuerLLC", "Vince Valuer LLC", "Vince Valuer LLC"); - valuerRefName = - OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, newOrgCSID, orgAuthClient); - orgIdsCreated.add(newOrgCSID); - } - - protected String createOrganization(String shortId, String shortName, String longName) { - OrgAuthorityClient orgAuthClient = new OrgAuthorityClient(); - Map orgInfo = new HashMap(); - orgInfo.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId); - - List orgTerms = new ArrayList(); - OrgTermGroup term = new OrgTermGroup(); - term.setTermDisplayName(shortName); - term.setTermName(shortName); - term.setMainBodyName(longName); - orgTerms.add(term); - PoxPayloadOut multipart = - OrgAuthorityClientUtils.createOrganizationInstance(null, //orgAuthRefName - orgInfo, orgTerms, orgAuthClient.getItemCommonPartName()); - - ClientResponse res = orgAuthClient.createItem(orgAuthCSID, multipart); - int statusCode = res.getStatus(); - - Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), - invalidStatusCodeMessage(testRequestType, statusCode)); - Assert.assertEquals(statusCode, STATUS_CREATED); - return extractId(res); - } - - // Success outcomes - @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, - dependsOnMethods = {"createIntakeWithAuthRefs"}) - public void readAndCheckAuthRefDocs(String testName) throws Exception { - // Perform setup. - testSetup(STATUS_OK, ServiceRequestType.READ); - - // Get the auth ref docs and check them - OrgAuthorityClient orgAuthClient = new OrgAuthorityClient(); - ClientResponse refDocListResp = - orgAuthClient.getReferencingObjects(orgAuthCSID, currentOwnerOrgCSID); - AuthorityRefDocList list = null; - try { - assertStatusCode(refDocListResp, testName); - list = refDocListResp.getEntity(); - Assert.assertNotNull(list); - } finally { - if (refDocListResp != null) { - refDocListResp.releaseConnection(); - } - } - - // Optionally output additional data about list members for debugging. - boolean iterateThroughList = true; - int nIntakesFound = 0; - if(iterateThroughList && logger.isDebugEnabled()){ - List items = - list.getAuthorityRefDocItem(); - int i = 0; - logger.debug(testName + ": Docs that use: " + currentOwnerRefName); - for(AuthorityRefDocList.AuthorityRefDocItem item : items){ - logger.debug(testName + ": list-item[" + i + "] " + - item.getDocType() + "(" + - item.getDocId() + ") Name:[" + - item.getDocName() + "] Number:[" + - item.getDocNumber() + "] in field:[" + - item.getSourceField() + "]"); - if(knownIntakeId.equalsIgnoreCase(item.getDocId())) { - nIntakesFound++; - } - i++; - } - // - Assert.assertTrue((nIntakesFound==2), "Did not find Intake (twice) with authref!"); - } - } - - - // --------------------------------------------------------------- - // Cleanup of resources created during testing - // --------------------------------------------------------------- - - /** - * Deletes all resources created by tests, after all tests have been run. - * - * This cleanup method will always be run, even if one or more tests fail. - * For this reason, it attempts to remove all resources created - * at any point during testing, even if some of those resources - * may be expected to be deleted by certain tests. - */ - @AfterClass(alwaysRun=true) - public void cleanUp() { - String noTest = System.getProperty("noTestCleanup"); - if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) { - if (logger.isDebugEnabled()) { - logger.debug("Skipping Cleanup phase ..."); - } - return; - } - if (logger.isDebugEnabled()) { - logger.debug("Cleaning up temporary resources created for testing ..."); - } - IntakeClient intakeClient = new IntakeClient(); - // Note: Any non-success responses are ignored and not reported. - for (String resourceId : intakeIdsCreated) { - ClientResponse res = intakeClient.delete(resourceId); - res.releaseConnection(); - } - // Delete persons before PersonAuth - OrgAuthorityClient personAuthClient = new OrgAuthorityClient(); - for (String resourceId : orgIdsCreated) { - ClientResponse res = personAuthClient.deleteItem(orgAuthCSID, resourceId); - res.releaseConnection(); - } - if (orgAuthCSID != null) { - personAuthClient.delete(orgAuthCSID).releaseConnection(); - } - } - - // --------------------------------------------------------------- - // Utility methods used by tests above - // --------------------------------------------------------------- - @Override - public String getServicePathComponent() { - return SERVICE_PATH_COMPONENT; - } - - private PoxPayloadOut createIntakeInstance(String entryNumber, - String entryDate, - String currentOwner, - String depositor, - String conditionCheckerAssessor, - String insurer, - String Valuer ) { - IntakesCommon intake = new IntakesCommon(); - intake.setEntryNumber(entryNumber); - intake.setEntryDate(entryDate); - intake.setCurrentOwner(currentOwner); - intake.setDepositor(depositor); - intake.setValuer(Valuer); - - ConditionCheckerOrAssessorList checkerOrAssessorList = new ConditionCheckerOrAssessorList(); - List checkersOrAssessors = checkerOrAssessorList.getConditionCheckerOrAssessor(); - checkersOrAssessors.add(conditionCheckerAssessor); - intake.setConditionCheckersOrAssessors(checkerOrAssessorList); - - InsurerList insurerList = new InsurerList(); - List insurers = insurerList.getInsurer(); - insurers.add(insurer); - intake.setInsurers(insurerList); - - PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent()); - PayloadOutputPart commonPart = - multipart.addPart(new IntakeClient().getCommonPartName(), intake); - - if(logger.isDebugEnabled()){ - logger.debug("to be created, intake common"); - logger.debug(objectAsXmlString(intake, IntakesCommon.class)); - } - - return multipart; - } -} +/** + * 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 Regents of the University of California + * + * 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.client.test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.collectionspace.services.OrganizationJAXBSchema; +import org.collectionspace.services.client.CollectionSpaceClient; +import org.collectionspace.services.client.IntakeClient; +import org.collectionspace.services.client.OrgAuthorityClient; +import org.collectionspace.services.client.OrgAuthorityClientUtils; +import org.collectionspace.services.client.PayloadOutputPart; +import org.collectionspace.services.client.PoxPayloadOut; +import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils; +import org.collectionspace.services.common.authorityref.AuthorityRefDocList; +import org.collectionspace.services.intake.ConditionCheckerOrAssessorList; +import org.collectionspace.services.intake.IntakesCommon; +import org.collectionspace.services.intake.InsurerList; +import org.collectionspace.services.jaxb.AbstractCommonList; +import org.collectionspace.services.organization.OrgTermGroup; + +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.AfterClass; +import org.testng.annotations.Test; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * OrganizationAuthRefDocsTest, carries out tests against a + * deployed and running Organization Service. + * + * $LastChangedRevision: 1327 $ + * $LastChangedDate: 2010-02-12 10:35:11 -0800 (Fri, 12 Feb 2010) $ + */ +public class OrganizationAuthRefDocsTest extends BaseServiceTest { + + private final String CLASS_NAME = OrganizationAuthRefDocsTest.class.getName(); + private final Logger logger = LoggerFactory.getLogger(CLASS_NAME); + + // Instance variables specific to this test. + final String SERVICE_PATH_COMPONENT = "intakes"; + final String ORGANIZATION_AUTHORITY_NAME = "TestOrganizationAuth"; + private String knownIntakeId = null; + private List intakeIdsCreated = new ArrayList(); + private List orgIdsCreated = new ArrayList(); + private String orgAuthCSID = null; + //private String orgAuthRefName = null; + private String currentOwnerOrgCSID = null; + private String currentOwnerRefName = null; + private String depositorRefName = null; + private String conditionCheckerAssessorRefName = null; + private String insurerRefName = null; + private String valuerRefName = null; + private final int NUM_AUTH_REF_DOCS_EXPECTED = 1; + private final static String CURRENT_DATE_UTC = + GregorianCalendarDateTimeUtils.currentDateUTC(); + + @Override + protected String getServiceName() { + throw new UnsupportedOperationException(); //FIXME: REM - See http://issues.collectionspace.org/browse/CSPACE-3498 + } + + /* (non-Javadoc) + * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance() + */ + @Override + protected CollectionSpaceClient getClientInstance() { + throw new UnsupportedOperationException(); //method not supported (or needed) in this test class + } + + /* (non-Javadoc) + * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse) + */ + @Override + protected AbstractCommonList getCommonList( + ClientResponse response) { + throw new UnsupportedOperationException(); //method not supported (or needed) in this test class + } + + // --------------------------------------------------------------- + // CRUD tests : CREATE tests + // --------------------------------------------------------------- + // Success outcomes + @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class) + public void createIntakeWithAuthRefs(String testName) throws Exception { + testSetup(STATUS_CREATED, ServiceRequestType.CREATE); + + // Submit the request to the service and store the response. + String identifier = createIdentifier(); + + // Create all the organization refs and entities + createOrgRefs(); + + IntakeClient intakeClient = new IntakeClient(); + PoxPayloadOut multipart = createIntakeInstance( + "entryNumber-" + identifier, + CURRENT_DATE_UTC, + currentOwnerRefName, + // Use currentOwnerRefName twice to test fix for CSPACE-2863 + currentOwnerRefName, //depositorRefName, + conditionCheckerAssessorRefName, + insurerRefName, + valuerRefName ); + + ClientResponse res = intakeClient.create(multipart); + try { + int statusCode = res.getStatus(); + + // Check the status code of the response: does it match + // the expected response(s)? + // + // Specifically: + // Does it fall within the set of valid status codes? + // Does it exactly match the expected status code? + if(logger.isDebugEnabled()){ + logger.debug(testName + ": status = " + statusCode); + } + Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), + invalidStatusCodeMessage(testRequestType, statusCode)); + Assert.assertEquals(statusCode, testExpectedStatusCode); + } finally { + res.releaseConnection(); + } + + // Store the ID returned from the first resource created + // for additional tests below. + if (knownIntakeId == null){ + knownIntakeId = extractId(res); + if (logger.isDebugEnabled()) { + logger.debug(testName + ": knownIntakeId=" + knownIntakeId); + } + } + + // Store the IDs from every resource created by tests, + // so they can be deleted after tests have been run. + intakeIdsCreated.add(extractId(res)); + } + + /** + * Creates the organization refs. + */ + protected void createOrgRefs(){ + OrgAuthorityClient orgAuthClient = new OrgAuthorityClient(); + //orgAuthRefName = + // OrgAuthorityClientUtils.createOrgAuthRefName(ORGANIZATION_AUTHORITY_NAME, null); + PoxPayloadOut multipart = OrgAuthorityClientUtils.createOrgAuthorityInstance( + ORGANIZATION_AUTHORITY_NAME, ORGANIZATION_AUTHORITY_NAME, orgAuthClient.getCommonPartName()); + ClientResponse res = orgAuthClient.create(multipart); + int statusCode = res.getStatus(); + + Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), + invalidStatusCodeMessage(testRequestType, statusCode)); + Assert.assertEquals(statusCode, STATUS_CREATED); + orgAuthCSID = extractId(res); + + currentOwnerOrgCSID = createOrganization("olivierOwnerCompany", "Olivier Owner Company", "Olivier Owner Company"); + orgIdsCreated.add(currentOwnerOrgCSID); + currentOwnerRefName = OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, currentOwnerOrgCSID, orgAuthClient); + + String newOrgCSID = + createOrganization("debbieDepositorAssocs", "Debbie Depositor & Associates", "Debbie Depositor & Associates"); + depositorRefName = + OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, newOrgCSID, orgAuthClient); + orgIdsCreated.add(newOrgCSID); + + newOrgCSID = createOrganization("andrewCheckerAssessorLtd", "Andrew Checker-Assessor Ltd.", "Andrew Checker-Assessor Ltd."); + conditionCheckerAssessorRefName = + OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, newOrgCSID, orgAuthClient); + orgIdsCreated.add(newOrgCSID); + + newOrgCSID = createOrganization("ingridInsurerBureau", "Ingrid Insurer Bureau", "Ingrid Insurer Bureau"); + insurerRefName = + OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, newOrgCSID, orgAuthClient); + orgIdsCreated.add(newOrgCSID); + + newOrgCSID = createOrganization("vinceValuerLLC", "Vince Valuer LLC", "Vince Valuer LLC"); + valuerRefName = + OrgAuthorityClientUtils.getOrgRefName(orgAuthCSID, newOrgCSID, orgAuthClient); + orgIdsCreated.add(newOrgCSID); + } + + protected String createOrganization(String shortId, String shortName, String longName) { + OrgAuthorityClient orgAuthClient = new OrgAuthorityClient(); + Map orgInfo = new HashMap(); + orgInfo.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortId); + + List orgTerms = new ArrayList(); + OrgTermGroup term = new OrgTermGroup(); + term.setTermDisplayName(shortName); + term.setTermName(shortName); + term.setMainBodyName(longName); + orgTerms.add(term); + PoxPayloadOut multipart = + OrgAuthorityClientUtils.createOrganizationInstance(null, //orgAuthRefName + orgInfo, orgTerms, orgAuthClient.getItemCommonPartName()); + + ClientResponse res = orgAuthClient.createItem(orgAuthCSID, multipart); + int statusCode = res.getStatus(); + + Assert.assertTrue(testRequestType.isValidStatusCode(statusCode), + invalidStatusCodeMessage(testRequestType, statusCode)); + Assert.assertEquals(statusCode, STATUS_CREATED); + return extractId(res); + } + + // Success outcomes + @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, + dependsOnMethods = {"createIntakeWithAuthRefs"}) + public void readAndCheckAuthRefDocs(String testName) throws Exception { + // Perform setup. + testSetup(STATUS_OK, ServiceRequestType.READ); + + // Get the auth ref docs and check them + OrgAuthorityClient orgAuthClient = new OrgAuthorityClient(); + ClientResponse refDocListResp = + orgAuthClient.getReferencingObjects(orgAuthCSID, currentOwnerOrgCSID); + AuthorityRefDocList list = null; + try { + assertStatusCode(refDocListResp, testName); + list = refDocListResp.getEntity(); + Assert.assertNotNull(list); + } finally { + if (refDocListResp != null) { + refDocListResp.releaseConnection(); + } + } + + // Optionally output additional data about list members for debugging. + boolean iterateThroughList = true; + int nIntakesFound = 0; + if(iterateThroughList && logger.isDebugEnabled()){ + List items = + list.getAuthorityRefDocItem(); + int i = 0; + logger.debug(testName + ": Docs that use: " + currentOwnerRefName); + for(AuthorityRefDocList.AuthorityRefDocItem item : items){ + logger.debug(testName + ": list-item[" + i + "] " + + item.getDocType() + "(" + + item.getDocId() + ") Name:[" + + item.getDocName() + "] Number:[" + + item.getDocNumber() + "] in field:[" + + item.getSourceField() + "]"); + if(knownIntakeId.equalsIgnoreCase(item.getDocId())) { + nIntakesFound++; + } + i++; + } + // + Assert.assertTrue((nIntakesFound==2), "Did not find Intake (twice) with authref!"); + } + } + + + // --------------------------------------------------------------- + // Cleanup of resources created during testing + // --------------------------------------------------------------- + + /** + * Deletes all resources created by tests, after all tests have been run. + * + * This cleanup method will always be run, even if one or more tests fail. + * For this reason, it attempts to remove all resources created + * at any point during testing, even if some of those resources + * may be expected to be deleted by certain tests. + */ + @AfterClass(alwaysRun=true) + public void cleanUp() { + String noTest = System.getProperty("noTestCleanup"); + if(Boolean.TRUE.toString().equalsIgnoreCase(noTest)) { + if (logger.isDebugEnabled()) { + logger.debug("Skipping Cleanup phase ..."); + } + return; + } + if (logger.isDebugEnabled()) { + logger.debug("Cleaning up temporary resources created for testing ..."); + } + IntakeClient intakeClient = new IntakeClient(); + // Note: Any non-success responses are ignored and not reported. + for (String resourceId : intakeIdsCreated) { + ClientResponse res = intakeClient.delete(resourceId); + res.releaseConnection(); + } + // Delete persons before PersonAuth + OrgAuthorityClient personAuthClient = new OrgAuthorityClient(); + for (String resourceId : orgIdsCreated) { + ClientResponse res = personAuthClient.deleteItem(orgAuthCSID, resourceId); + res.releaseConnection(); + } + if (orgAuthCSID != null) { + personAuthClient.delete(orgAuthCSID).releaseConnection(); + } + } + + // --------------------------------------------------------------- + // Utility methods used by tests above + // --------------------------------------------------------------- + @Override + public String getServicePathComponent() { + return SERVICE_PATH_COMPONENT; + } + + private PoxPayloadOut createIntakeInstance(String entryNumber, + String entryDate, + String currentOwner, + String depositor, + String conditionCheckerAssessor, + String insurer, + String Valuer ) { + IntakesCommon intake = new IntakesCommon(); + intake.setEntryNumber(entryNumber); + intake.setEntryDate(entryDate); + intake.setCurrentOwner(currentOwner); + intake.setDepositor(depositor); + intake.setValuer(Valuer); + + ConditionCheckerOrAssessorList checkerOrAssessorList = new ConditionCheckerOrAssessorList(); + List checkersOrAssessors = checkerOrAssessorList.getConditionCheckerOrAssessor(); + checkersOrAssessors.add(conditionCheckerAssessor); + intake.setConditionCheckersOrAssessors(checkerOrAssessorList); + + InsurerList insurerList = new InsurerList(); + List insurers = insurerList.getInsurer(); + insurers.add(insurer); + intake.setInsurers(insurerList); + + PoxPayloadOut multipart = new PoxPayloadOut(this.getServicePathComponent()); + PayloadOutputPart commonPart = + multipart.addPart(new IntakeClient().getCommonPartName(), intake); + + if(logger.isDebugEnabled()){ + logger.debug("to be created, intake common"); + logger.debug(objectAsXmlString(intake, IntakesCommon.class)); + } + + return multipart; + } +} diff --git a/services/intake/client/src/test/resources/log4j.properties b/services/intake/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/intake/client/src/test/resources/log4j.properties +++ b/services/intake/client/src/test/resources/log4j.properties @@ -1,23 +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 +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/intake/jaxb/src/main/java/org/collectionspace/services/IntakeJAXBSchema.java b/services/intake/jaxb/src/main/java/org/collectionspace/services/IntakeJAXBSchema.java index def5f25ed..45583ae49 100644 --- a/services/intake/jaxb/src/main/java/org/collectionspace/services/IntakeJAXBSchema.java +++ b/services/intake/jaxb/src/main/java/org/collectionspace/services/IntakeJAXBSchema.java @@ -1,23 +1,23 @@ -/** - * - */ -package org.collectionspace.services; - -/** - * @author remillet - * - */ -public interface IntakeJAXBSchema { - final static String CURRENT_OWNER = "currentOwner"; - final static String DEPOSITOR = "depositor"; - final static String DEPOSITORS_REQUIREMENTS = "depositorsRequirements"; - final static String ENTRY_DATE = "entryDate"; - final static String ENTRY_METHOD = "entryMethod"; - final static String ENTRY_NOTE = "entryNote"; - final static String ENTRY_NUMBER = "entryNumber"; - final static String ENTRY_REASON = "entryReason"; - final static String PACKING_NOTE = "packingNote"; - final static String RETURN_DATE = "returnDate"; -} - - +/** + * + */ +package org.collectionspace.services; + +/** + * @author remillet + * + */ +public interface IntakeJAXBSchema { + final static String CURRENT_OWNER = "currentOwner"; + final static String DEPOSITOR = "depositor"; + final static String DEPOSITORS_REQUIREMENTS = "depositorsRequirements"; + final static String ENTRY_DATE = "entryDate"; + final static String ENTRY_METHOD = "entryMethod"; + final static String ENTRY_NOTE = "entryNote"; + final static String ENTRY_NUMBER = "entryNumber"; + final static String ENTRY_REASON = "entryReason"; + final static String PACKING_NOTE = "packingNote"; + final static String RETURN_DATE = "returnDate"; +} + + diff --git a/services/intake/jaxb/src/main/java/org/collectionspace/services/IntakeListItemJAXBSchema.java b/services/intake/jaxb/src/main/java/org/collectionspace/services/IntakeListItemJAXBSchema.java index 5d2250976..fa6254430 100644 --- a/services/intake/jaxb/src/main/java/org/collectionspace/services/IntakeListItemJAXBSchema.java +++ b/services/intake/jaxb/src/main/java/org/collectionspace/services/IntakeListItemJAXBSchema.java @@ -1,8 +1,8 @@ -package org.collectionspace.services; - -public interface IntakeListItemJAXBSchema { - final static String ENTRY_NUMBER = "entryNumber"; - final static String DEPOSITOR="depositor"; - final static String CSID = "csid"; - final static String URI = "url"; -} +package org.collectionspace.services; + +public interface IntakeListItemJAXBSchema { + final static String ENTRY_NUMBER = "entryNumber"; + final static String DEPOSITOR="depositor"; + final static String CSID = "csid"; + final static String URI = "url"; +} diff --git a/services/intake/pom.xml b/services/intake/pom.xml index 5a7bff2e8..b98e309e5 100644 --- a/services/intake/pom.xml +++ b/services/intake/pom.xml @@ -1,24 +1,24 @@ - - - - - org.collectionspace.services - org.collectionspace.services.main - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.intake - services.intake - pom - - - jaxb - service - 3rdparty - client - - - - + + + + + org.collectionspace.services + org.collectionspace.services.main + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.intake + services.intake + pom + + + jaxb + service + 3rdparty + client + + + + diff --git a/services/intake/service/pom.xml b/services/intake/service/pom.xml index d8a06909b..9ad87dab6 100644 --- a/services/intake/service/pom.xml +++ b/services/intake/service/pom.xml @@ -1,111 +1,111 @@ - - - - - org.collectionspace.services - org.collectionspace.services.intake - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.intake.service - services.intake.service - jar - - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.intake.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.intake.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.collectionobject.jaxb - ${project.version} - - - - junit - junit - 4.1 - test - - - org.testng - testng - - - - - - javax.security - jaas - 1.0.01 - provided - - - - dom4j - dom4j - 1.6.1 - provided - - - - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - - - org.nuxeo.ecm.core - nuxeo-core-api - ${nuxeo.core.version} - - - jboss-remoting - jboss - - - - - - - - collectionspace-services-intake - - - + + + + + org.collectionspace.services + org.collectionspace.services.intake + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.intake.service + services.intake.service + jar + + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.intake.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.intake.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.collectionobject.jaxb + ${project.version} + + + + junit + junit + 4.1 + test + + + org.testng + testng + + + + + + javax.security + jaas + 1.0.01 + provided + + + + dom4j + dom4j + 1.6.1 + provided + + + + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + + + org.nuxeo.ecm.core + nuxeo-core-api + ${nuxeo.core.version} + + + jboss-remoting + jboss + + + + + + + + collectionspace-services-intake + + + diff --git a/services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeValidatorHandler.java b/services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeValidatorHandler.java index fffe25e93..7e4123d66 100644 --- a/services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeValidatorHandler.java +++ b/services/intake/service/src/main/java/org/collectionspace/services/intake/nuxeo/IntakeValidatorHandler.java @@ -1,66 +1,66 @@ -package org.collectionspace.services.intake.nuxeo; - -import org.collectionspace.services.client.PoxPayloadIn; -import org.collectionspace.services.client.PoxPayloadOut; -import org.collectionspace.services.common.document.InvalidDocumentException; -import org.collectionspace.services.common.document.ValidatorHandlerImpl; -import org.collectionspace.services.intake.IntakesCommon; - -import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; -import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class IntakeValidatorHandler extends ValidatorHandlerImpl { - - /** The logger. */ - private final Logger logger = LoggerFactory.getLogger(IntakeValidatorHandler.class); - - /** Error Messages **/ - private static final String VALIDATION_ERROR = "The intake record payload was invalid. See log file for more details."; - - - @Override - protected Class getCommonPartClass() { - return IntakesCommon.class; - } - - @Override - protected void handleCreate() throws InvalidDocumentException { - try { - IntakesCommon intakesCommon = (IntakesCommon)getCommonPart(); - assert(intakesCommon != null); - } catch (AssertionError e) { - if (logger.isErrorEnabled() == true) { - logger.error(e.getMessage(), e); - } - throw new InvalidDocumentException(VALIDATION_ERROR, e); - } - } - - @Override - protected void handleGet() throws InvalidDocumentException { - // TODO Auto-generated method stub - - } - - @Override - protected void handleGetAll() throws InvalidDocumentException { - // TODO Auto-generated method stub - - } - - @Override - protected void handleUpdate() throws InvalidDocumentException { - // TODO Auto-generated method stub - - } - - @Override - protected void handleDelete() throws InvalidDocumentException { - // TODO Auto-generated method stub - - } - -} +package org.collectionspace.services.intake.nuxeo; + +import org.collectionspace.services.client.PoxPayloadIn; +import org.collectionspace.services.client.PoxPayloadOut; +import org.collectionspace.services.common.document.InvalidDocumentException; +import org.collectionspace.services.common.document.ValidatorHandlerImpl; +import org.collectionspace.services.intake.IntakesCommon; + +import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; +import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class IntakeValidatorHandler extends ValidatorHandlerImpl { + + /** The logger. */ + private final Logger logger = LoggerFactory.getLogger(IntakeValidatorHandler.class); + + /** Error Messages **/ + private static final String VALIDATION_ERROR = "The intake record payload was invalid. See log file for more details."; + + + @Override + protected Class getCommonPartClass() { + return IntakesCommon.class; + } + + @Override + protected void handleCreate() throws InvalidDocumentException { + try { + IntakesCommon intakesCommon = (IntakesCommon)getCommonPart(); + assert(intakesCommon != null); + } catch (AssertionError e) { + if (logger.isErrorEnabled() == true) { + logger.error(e.getMessage(), e); + } + throw new InvalidDocumentException(VALIDATION_ERROR, e); + } + } + + @Override + protected void handleGet() throws InvalidDocumentException { + // TODO Auto-generated method stub + + } + + @Override + protected void handleGetAll() throws InvalidDocumentException { + // TODO Auto-generated method stub + + } + + @Override + protected void handleUpdate() throws InvalidDocumentException { + // TODO Auto-generated method stub + + } + + @Override + protected void handleDelete() throws InvalidDocumentException { + // TODO Auto-generated method stub + + } + +} diff --git a/services/jaxb/pom.xml b/services/jaxb/pom.xml index eeda2c4ba..02f91247b 100644 --- a/services/jaxb/pom.xml +++ b/services/jaxb/pom.xml @@ -1,49 +1,49 @@ - - - - - - - - org.collectionspace.services - org.collectionspace.services.main - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.jaxb - services.jaxb - - - - com.sun.xml.bind - jaxb-impl - - - org.jvnet.jaxb2_commons - jaxb2-basics - ${jaxb2-basics.version} - - - - - collectionspace-services-jaxb - install - - - org.jvnet.jaxb2.maven2 - maven-jaxb2-plugin - - - - - - + + + + + + + + org.collectionspace.services + org.collectionspace.services.main + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.jaxb + services.jaxb + + + + com.sun.xml.bind + jaxb-impl + + + org.jvnet.jaxb2_commons + jaxb2-basics + ${jaxb2-basics.version} + + + + + collectionspace-services-jaxb + install + + + org.jvnet.jaxb2.maven2 + maven-jaxb2-plugin + + + + + + diff --git a/services/jaxb/src/main/resources/relations_common.xsd b/services/jaxb/src/main/resources/relations_common.xsd index bc6aef7c9..959818872 100644 --- a/services/jaxb/src/main/resources/relations_common.xsd +++ b/services/jaxb/src/main/resources/relations_common.xsd @@ -1,127 +1,127 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/loanin/.classpath b/services/loanin/.classpath index 046988541..25df93560 100644 --- a/services/loanin/.classpath +++ b/services/loanin/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/loanin/.project b/services/loanin/.project index 62877a5f9..6e2025c07 100644 --- a/services/loanin/.project +++ b/services/loanin/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.loanin - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.loanin + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/loanin/3rdparty/.classpath b/services/loanin/3rdparty/.classpath index 046988541..25df93560 100644 --- a/services/loanin/3rdparty/.classpath +++ b/services/loanin/3rdparty/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/loanin/3rdparty/.project b/services/loanin/3rdparty/.project index 059aa3976..9b51d5ec5 100644 --- a/services/loanin/3rdparty/.project +++ b/services/loanin/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.loanin.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.loanin.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/loanin/client/src/test/resources/log4j.properties b/services/loanin/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/loanin/client/src/test/resources/log4j.properties +++ b/services/loanin/client/src/test/resources/log4j.properties @@ -1,23 +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 +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/loanout/.project b/services/loanout/.project index 5d279352a..fb5f09dd9 100644 --- a/services/loanout/.project +++ b/services/loanout/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.loanout - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.loanout + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/loanout/3rdparty/.project b/services/loanout/3rdparty/.project index e1dd95864..c0993a5fa 100644 --- a/services/loanout/3rdparty/.project +++ b/services/loanout/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.loanout.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.loanout.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/loanout/client/src/test/resources/log4j.properties b/services/loanout/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/loanout/client/src/test/resources/log4j.properties +++ b/services/loanout/client/src/test/resources/log4j.properties @@ -1,23 +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 +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/location/.classpath b/services/location/.classpath index 046988541..25df93560 100644 --- a/services/location/.classpath +++ b/services/location/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/location/.project b/services/location/.project index 7e663eb30..ec3294822 100644 --- a/services/location/.project +++ b/services/location/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.location - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.location + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/location/3rdparty/.classpath b/services/location/3rdparty/.classpath index 046988541..25df93560 100644 --- a/services/location/3rdparty/.classpath +++ b/services/location/3rdparty/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/location/3rdparty/.project b/services/location/3rdparty/.project index a2270c68b..2950ff81f 100644 --- a/services/location/3rdparty/.project +++ b/services/location/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.location.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.location.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/location/3rdparty/build.xml b/services/location/3rdparty/build.xml index d795bfef5..3436086ba 100644 --- a/services/location/3rdparty/build.xml +++ b/services/location/3rdparty/build.xml @@ -1,135 +1,135 @@ - - - - location service 3rdparty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + location service 3rdparty + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/location/3rdparty/pom.xml b/services/location/3rdparty/pom.xml index 9de3555f8..20ed9e5b7 100644 --- a/services/location/3rdparty/pom.xml +++ b/services/location/3rdparty/pom.xml @@ -1,23 +1,23 @@ - - - org.collectionspace.services - org.collectionspace.services.location - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.location.3rdparty - services.location.3rdparty - pom - - 3rd party build for location service - - - - - - + + + org.collectionspace.services + org.collectionspace.services.location + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.location.3rdparty + services.location.3rdparty + pom + + 3rd party build for location service + + + + + + diff --git a/services/location/build.xml b/services/location/build.xml index 943a8a0c8..a1840238d 100644 --- a/services/location/build.xml +++ b/services/location/build.xml @@ -1,132 +1,132 @@ - - - - Location Authority service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + Location Authority service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/location/client/pom.xml b/services/location/client/pom.xml index b3e358bd2..0f2fd2dd3 100644 --- a/services/location/client/pom.xml +++ b/services/location/client/pom.xml @@ -1,93 +1,93 @@ - - - - org.collectionspace.services - org.collectionspace.services.location - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.location.client - services.location.client - - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - - org.collectionspace.services - org.collectionspace.services.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.common - true - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.location.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authority.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.contact.client - ${project.version} - - - - org.testng - testng - - - org.jboss.resteasy - resteasy-jaxrs - - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - commons-httpclient - commons-httpclient - - - - - collectionspace-services-location-client - - - - - + + + + org.collectionspace.services + org.collectionspace.services.location + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.location.client + services.location.client + + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + + org.collectionspace.services + org.collectionspace.services.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.common + true + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.location.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authority.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.contact.client + ${project.version} + + + + org.testng + testng + + + org.jboss.resteasy + resteasy-jaxrs + + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + commons-httpclient + commons-httpclient + + + + + collectionspace-services-location-client + + + + + diff --git a/services/location/client/src/main/java/org/collectionspace/services/client/LocationAuthorityClientUtils.java b/services/location/client/src/main/java/org/collectionspace/services/client/LocationAuthorityClientUtils.java index e8ae69ad0..d13558888 100644 --- a/services/location/client/src/main/java/org/collectionspace/services/client/LocationAuthorityClientUtils.java +++ b/services/location/client/src/main/java/org/collectionspace/services/client/LocationAuthorityClientUtils.java @@ -1,319 +1,319 @@ -package org.collectionspace.services.client; - -import java.io.File; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import org.apache.commons.io.FileUtils; -import org.collectionspace.services.LocationJAXBSchema; -import org.collectionspace.services.client.test.ServiceRequestType; -import org.collectionspace.services.common.api.Tools; -import org.collectionspace.services.location.*; -import org.dom4j.DocumentException; -import org.jboss.resteasy.client.ClientResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class LocationAuthorityClientUtils { - private static final Logger logger = - LoggerFactory.getLogger(LocationAuthorityClientUtils.class); - - /** - * Creates a new Location Authority - * @param displayName The displayName used in UI, etc. - * @param refName The proper refName for this authority - * @param headerLabel The common part label - * @return The PoxPayloadOut payload for the create call - */ - public static PoxPayloadOut createLocationAuthorityInstance( - String displayName, String shortIdentifier, String headerLabel ) { - - LocationauthoritiesCommon locationAuthority = new LocationauthoritiesCommon(); - locationAuthority.setDisplayName(displayName); - locationAuthority.setShortIdentifier(shortIdentifier); - // String refName = createLocationAuthRefName(shortIdentifier, displayName); - // locationAuthority.setRefName(refName); - locationAuthority.setVocabType("LocationAuthority"); //FIXME: REM - Should this really be hard-coded? - - PoxPayloadOut multipart = new PoxPayloadOut(LocationAuthorityClient.SERVICE_PAYLOAD_NAME); - PayloadOutputPart commonPart = multipart.addPart(headerLabel, locationAuthority); - - if(logger.isDebugEnabled()){ - logger.debug("to be created, locationAuthority common ", - locationAuthority, LocationauthoritiesCommon.class); - } - - return multipart; - } - - /** - * @param locationRefName The proper refName for this authority - * @param locationInfo the properties for the new Location. Can pass in one condition - * note and date string. - * @param headerLabel The common part label - * @return The PoxPayloadOut payload for the create call - */ - public static PoxPayloadOut createLocationInstance( - String locationAuthRefName, Map locationInfo, - List terms, String headerLabel){ - LocationsCommon location = new LocationsCommon(); - String shortId = locationInfo.get(LocationJAXBSchema.SHORT_IDENTIFIER); - String displayName = locationInfo.get(LocationJAXBSchema.DISPLAY_NAME); - location.setShortIdentifier(shortId); - // String locationRefName = createLocationRefName(locationAuthRefName, shortId, displayName); - // location.setRefName(locationRefName); - String value = null; - value = locationInfo.get(LocationJAXBSchema.DISPLAY_NAME_COMPUTED); - boolean displayNameComputed = (value==null) || value.equalsIgnoreCase("true"); - - // Set values in the Term Information Group - LocTermGroupList termList = new LocTermGroupList(); - if (terms == null || terms.isEmpty()) { - terms = getTermGroupInstance(getGeneratedIdentifier()); - } - termList.getLocTermGroup().addAll(terms); - location.setLocTermGroupList(termList); - - if((value = (String)locationInfo.get(LocationJAXBSchema.CONDITION_NOTE))!=null) { - ConditionGroupList conditionGroupList = new ConditionGroupList(); - List conditionGroups = conditionGroupList.getConditionGroup(); - ConditionGroup conditionGroup = new ConditionGroup(); - conditionGroup.setConditionNote(value); - if((value = (String)locationInfo.get(LocationJAXBSchema.CONDITION_NOTE_DATE))!=null) - conditionGroup.setConditionNoteDate(value); - conditionGroups.add(conditionGroup); - location.setConditionGroupList(conditionGroupList); - } - if((value = (String)locationInfo.get(LocationJAXBSchema.SECURITY_NOTE))!=null) - location.setSecurityNote(value); - if((value = (String)locationInfo.get(LocationJAXBSchema.ACCESS_NOTE))!=null) - location.setAccessNote(value); - if((value = (String)locationInfo.get(LocationJAXBSchema.LOCATION_TYPE))!=null) - location.setLocationType(value); - if((value = (String)locationInfo.get(LocationJAXBSchema.ADDRESS))!=null) - location.setAddress(value); - - PoxPayloadOut multipart = new PoxPayloadOut(LocationAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME); - PayloadOutputPart commonPart = multipart.addPart(location, - MediaType.APPLICATION_XML_TYPE); - commonPart.setLabel(headerLabel); - - if(logger.isDebugEnabled()){ - logger.debug("to be created, location common ", location, LocationsCommon.class); - } - - return multipart; - } - - /** - * @param vcsid CSID of the authority to create a new location in - * @param locationAuthorityRefName The refName for the authority - * @param locationMap the properties for the new Location - * @param client the service client - * @return the CSID of the new item - */ - public static String createItemInAuthority(String vcsid, - String locationAuthorityRefName, Map locationMap, - List terms, LocationAuthorityClient client ) { - // Expected status code: 201 Created - int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; - - String displayName = ""; - if ((terms !=null) && (! terms.isEmpty())) { - displayName = terms.get(0).getTermDisplayName(); - } - - if(logger.isDebugEnabled()){ - logger.debug("Creating item with display name: \"" + displayName - +"\" in locationAuthority: \"" + vcsid +"\""); - } - - PoxPayloadOut multipart = - createLocationInstance( locationAuthorityRefName, - locationMap, terms, client.getItemCommonPartName() ); - String newID = null; - ClientResponse res = client.createItem(vcsid, multipart); - try { - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not create Item: \"" - +locationMap.get(LocationJAXBSchema.SHORT_IDENTIFIER) - +"\" in locationAuthority: \"" + locationAuthorityRefName - +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when creating Item: \"" - +locationMap.get(LocationJAXBSchema.SHORT_IDENTIFIER) - +"\" in locationAuthority: \"" + locationAuthorityRefName +"\", Status:"+ statusCode); - } - newID = extractId(res); - } finally { - res.releaseConnection(); - } - - return newID; - } - - public static PoxPayloadOut createLocationInstance( - String commonPartXML, String headerLabel) throws DocumentException { - PoxPayloadOut multipart = new PoxPayloadOut(LocationAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME); - PayloadOutputPart commonPart = multipart.addPart(commonPartXML, - MediaType.APPLICATION_XML_TYPE); - commonPart.setLabel(headerLabel); - - if(logger.isDebugEnabled()){ - logger.debug("to be created, location common ", commonPartXML); - } - - return multipart; - } - - public static String createItemInAuthority(String vcsid, - String commonPartXML, - LocationAuthorityClient client ) throws DocumentException { - // Expected status code: 201 Created - int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; - - PoxPayloadOut multipart = - createLocationInstance(commonPartXML, client.getItemCommonPartName()); - String newID = null; - ClientResponse res = client.createItem(vcsid, multipart); - try { - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not create Item: \""+commonPartXML - +"\" in locationAuthority: \"" + vcsid - +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when creating Item: \""+commonPartXML - +"\" in locationAuthority: \"" + vcsid +"\", Status:"+ statusCode); - } - newID = extractId(res); - } finally { - res.releaseConnection(); - } - - return newID; - } - - /** - * Creates the from xml file. - * - * @param fileName the file name - * @return new CSID as string - * @throws Exception the exception - */ - private String createItemInAuthorityFromXmlFile(String vcsid, String commonPartFileName, - LocationAuthorityClient client) throws Exception { - byte[] b = FileUtils.readFileToByteArray(new File(commonPartFileName)); - String commonPartXML = new String(b); - return createItemInAuthority(vcsid, commonPartXML, client ); - } - - /** - * Creates the locationAuthority ref name. - * - * @param shortId the locationAuthority shortIdentifier - * @param displaySuffix displayName to be appended, if non-null - * @return the string - */ - public static String createLocationAuthRefName(String shortId, String displaySuffix) { - String refName = "urn:cspace:org.collectionspace.demo:locationauthority:name(" - +shortId+")"; - if(displaySuffix!=null&&!displaySuffix.isEmpty()) - refName += "'"+displaySuffix+"'"; - return refName; - } - - /** - * Creates the location ref name. - * - * @param locationAuthRefName the locationAuthority ref name - * @param shortId the location shortIdentifier - * @param displaySuffix displayName to be appended, if non-null - * @return the string - */ - public static String createLocationRefName( - String locationAuthRefName, String shortId, String displaySuffix) { - String refName = locationAuthRefName+":location:name("+shortId+")"; - if(displaySuffix!=null&&!displaySuffix.isEmpty()) - refName += "'"+displaySuffix+"'"; - return refName; - } - - public static String extractId(ClientResponse res) { - MultivaluedMap mvm = res.getMetadata(); - String uri = (String) ((ArrayList) mvm.get("Location")).get(0); - if(logger.isDebugEnabled()){ - logger.debug("extractId:uri=" + uri); - } - String[] segments = uri.split("/"); - String id = segments[segments.length - 1]; - if(logger.isDebugEnabled()){ - logger.debug("id=" + id); - } - return id; - } - - /** - * Returns an error message indicating that the status code returned by a - * specific call to a service does not fall within a set of valid status - * codes for that service. - * - * @param serviceRequestType A type of service request (e.g. CREATE, DELETE). - * - * @param statusCode The invalid status code that was returned in the response, - * from submitting that type of request to the service. - * - * @return An error message. - */ - public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) { - return "Status code '" + statusCode + "' in response is NOT within the expected set: " + - requestType.validStatusCodesAsString(); - } - - - - /** - * Produces a default displayName from the basic name and dates fields. - * @see LocationDocumentModelHandler.prepareDefaultDisplayName() which - * duplicates this logic, until we define a service-general utils package - * that is neither client nor service specific. - * @param name - * @return - */ - public static String prepareDefaultDisplayName( - String name ) { - StringBuilder newStr = new StringBuilder(); - newStr.append(name); - return newStr.toString(); - } - - public static List getTermGroupInstance(String identifier) { - if (Tools.isBlank(identifier)) { - identifier = getGeneratedIdentifier(); - } - List terms = new ArrayList(); - LocTermGroup term = new LocTermGroup(); - term.setTermDisplayName(identifier); - term.setTermName(identifier); - terms.add(term); - return terms; - } - - private static String getGeneratedIdentifier() { - return "id" + new Date().getTime(); - } - -} +package org.collectionspace.services.client; + +import java.io.File; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import org.apache.commons.io.FileUtils; +import org.collectionspace.services.LocationJAXBSchema; +import org.collectionspace.services.client.test.ServiceRequestType; +import org.collectionspace.services.common.api.Tools; +import org.collectionspace.services.location.*; +import org.dom4j.DocumentException; +import org.jboss.resteasy.client.ClientResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LocationAuthorityClientUtils { + private static final Logger logger = + LoggerFactory.getLogger(LocationAuthorityClientUtils.class); + + /** + * Creates a new Location Authority + * @param displayName The displayName used in UI, etc. + * @param refName The proper refName for this authority + * @param headerLabel The common part label + * @return The PoxPayloadOut payload for the create call + */ + public static PoxPayloadOut createLocationAuthorityInstance( + String displayName, String shortIdentifier, String headerLabel ) { + + LocationauthoritiesCommon locationAuthority = new LocationauthoritiesCommon(); + locationAuthority.setDisplayName(displayName); + locationAuthority.setShortIdentifier(shortIdentifier); + // String refName = createLocationAuthRefName(shortIdentifier, displayName); + // locationAuthority.setRefName(refName); + locationAuthority.setVocabType("LocationAuthority"); //FIXME: REM - Should this really be hard-coded? + + PoxPayloadOut multipart = new PoxPayloadOut(LocationAuthorityClient.SERVICE_PAYLOAD_NAME); + PayloadOutputPart commonPart = multipart.addPart(headerLabel, locationAuthority); + + if(logger.isDebugEnabled()){ + logger.debug("to be created, locationAuthority common ", + locationAuthority, LocationauthoritiesCommon.class); + } + + return multipart; + } + + /** + * @param locationRefName The proper refName for this authority + * @param locationInfo the properties for the new Location. Can pass in one condition + * note and date string. + * @param headerLabel The common part label + * @return The PoxPayloadOut payload for the create call + */ + public static PoxPayloadOut createLocationInstance( + String locationAuthRefName, Map locationInfo, + List terms, String headerLabel){ + LocationsCommon location = new LocationsCommon(); + String shortId = locationInfo.get(LocationJAXBSchema.SHORT_IDENTIFIER); + String displayName = locationInfo.get(LocationJAXBSchema.DISPLAY_NAME); + location.setShortIdentifier(shortId); + // String locationRefName = createLocationRefName(locationAuthRefName, shortId, displayName); + // location.setRefName(locationRefName); + String value = null; + value = locationInfo.get(LocationJAXBSchema.DISPLAY_NAME_COMPUTED); + boolean displayNameComputed = (value==null) || value.equalsIgnoreCase("true"); + + // Set values in the Term Information Group + LocTermGroupList termList = new LocTermGroupList(); + if (terms == null || terms.isEmpty()) { + terms = getTermGroupInstance(getGeneratedIdentifier()); + } + termList.getLocTermGroup().addAll(terms); + location.setLocTermGroupList(termList); + + if((value = (String)locationInfo.get(LocationJAXBSchema.CONDITION_NOTE))!=null) { + ConditionGroupList conditionGroupList = new ConditionGroupList(); + List conditionGroups = conditionGroupList.getConditionGroup(); + ConditionGroup conditionGroup = new ConditionGroup(); + conditionGroup.setConditionNote(value); + if((value = (String)locationInfo.get(LocationJAXBSchema.CONDITION_NOTE_DATE))!=null) + conditionGroup.setConditionNoteDate(value); + conditionGroups.add(conditionGroup); + location.setConditionGroupList(conditionGroupList); + } + if((value = (String)locationInfo.get(LocationJAXBSchema.SECURITY_NOTE))!=null) + location.setSecurityNote(value); + if((value = (String)locationInfo.get(LocationJAXBSchema.ACCESS_NOTE))!=null) + location.setAccessNote(value); + if((value = (String)locationInfo.get(LocationJAXBSchema.LOCATION_TYPE))!=null) + location.setLocationType(value); + if((value = (String)locationInfo.get(LocationJAXBSchema.ADDRESS))!=null) + location.setAddress(value); + + PoxPayloadOut multipart = new PoxPayloadOut(LocationAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME); + PayloadOutputPart commonPart = multipart.addPart(location, + MediaType.APPLICATION_XML_TYPE); + commonPart.setLabel(headerLabel); + + if(logger.isDebugEnabled()){ + logger.debug("to be created, location common ", location, LocationsCommon.class); + } + + return multipart; + } + + /** + * @param vcsid CSID of the authority to create a new location in + * @param locationAuthorityRefName The refName for the authority + * @param locationMap the properties for the new Location + * @param client the service client + * @return the CSID of the new item + */ + public static String createItemInAuthority(String vcsid, + String locationAuthorityRefName, Map locationMap, + List terms, LocationAuthorityClient client ) { + // Expected status code: 201 Created + int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; + + String displayName = ""; + if ((terms !=null) && (! terms.isEmpty())) { + displayName = terms.get(0).getTermDisplayName(); + } + + if(logger.isDebugEnabled()){ + logger.debug("Creating item with display name: \"" + displayName + +"\" in locationAuthority: \"" + vcsid +"\""); + } + + PoxPayloadOut multipart = + createLocationInstance( locationAuthorityRefName, + locationMap, terms, client.getItemCommonPartName() ); + String newID = null; + ClientResponse res = client.createItem(vcsid, multipart); + try { + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not create Item: \"" + +locationMap.get(LocationJAXBSchema.SHORT_IDENTIFIER) + +"\" in locationAuthority: \"" + locationAuthorityRefName + +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when creating Item: \"" + +locationMap.get(LocationJAXBSchema.SHORT_IDENTIFIER) + +"\" in locationAuthority: \"" + locationAuthorityRefName +"\", Status:"+ statusCode); + } + newID = extractId(res); + } finally { + res.releaseConnection(); + } + + return newID; + } + + public static PoxPayloadOut createLocationInstance( + String commonPartXML, String headerLabel) throws DocumentException { + PoxPayloadOut multipart = new PoxPayloadOut(LocationAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME); + PayloadOutputPart commonPart = multipart.addPart(commonPartXML, + MediaType.APPLICATION_XML_TYPE); + commonPart.setLabel(headerLabel); + + if(logger.isDebugEnabled()){ + logger.debug("to be created, location common ", commonPartXML); + } + + return multipart; + } + + public static String createItemInAuthority(String vcsid, + String commonPartXML, + LocationAuthorityClient client ) throws DocumentException { + // Expected status code: 201 Created + int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; + + PoxPayloadOut multipart = + createLocationInstance(commonPartXML, client.getItemCommonPartName()); + String newID = null; + ClientResponse res = client.createItem(vcsid, multipart); + try { + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not create Item: \""+commonPartXML + +"\" in locationAuthority: \"" + vcsid + +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when creating Item: \""+commonPartXML + +"\" in locationAuthority: \"" + vcsid +"\", Status:"+ statusCode); + } + newID = extractId(res); + } finally { + res.releaseConnection(); + } + + return newID; + } + + /** + * Creates the from xml file. + * + * @param fileName the file name + * @return new CSID as string + * @throws Exception the exception + */ + private String createItemInAuthorityFromXmlFile(String vcsid, String commonPartFileName, + LocationAuthorityClient client) throws Exception { + byte[] b = FileUtils.readFileToByteArray(new File(commonPartFileName)); + String commonPartXML = new String(b); + return createItemInAuthority(vcsid, commonPartXML, client ); + } + + /** + * Creates the locationAuthority ref name. + * + * @param shortId the locationAuthority shortIdentifier + * @param displaySuffix displayName to be appended, if non-null + * @return the string + */ + public static String createLocationAuthRefName(String shortId, String displaySuffix) { + String refName = "urn:cspace:org.collectionspace.demo:locationauthority:name(" + +shortId+")"; + if(displaySuffix!=null&&!displaySuffix.isEmpty()) + refName += "'"+displaySuffix+"'"; + return refName; + } + + /** + * Creates the location ref name. + * + * @param locationAuthRefName the locationAuthority ref name + * @param shortId the location shortIdentifier + * @param displaySuffix displayName to be appended, if non-null + * @return the string + */ + public static String createLocationRefName( + String locationAuthRefName, String shortId, String displaySuffix) { + String refName = locationAuthRefName+":location:name("+shortId+")"; + if(displaySuffix!=null&&!displaySuffix.isEmpty()) + refName += "'"+displaySuffix+"'"; + return refName; + } + + public static String extractId(ClientResponse res) { + MultivaluedMap mvm = res.getMetadata(); + String uri = (String) ((ArrayList) mvm.get("Location")).get(0); + if(logger.isDebugEnabled()){ + logger.debug("extractId:uri=" + uri); + } + String[] segments = uri.split("/"); + String id = segments[segments.length - 1]; + if(logger.isDebugEnabled()){ + logger.debug("id=" + id); + } + return id; + } + + /** + * Returns an error message indicating that the status code returned by a + * specific call to a service does not fall within a set of valid status + * codes for that service. + * + * @param serviceRequestType A type of service request (e.g. CREATE, DELETE). + * + * @param statusCode The invalid status code that was returned in the response, + * from submitting that type of request to the service. + * + * @return An error message. + */ + public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) { + return "Status code '" + statusCode + "' in response is NOT within the expected set: " + + requestType.validStatusCodesAsString(); + } + + + + /** + * Produces a default displayName from the basic name and dates fields. + * @see LocationDocumentModelHandler.prepareDefaultDisplayName() which + * duplicates this logic, until we define a service-general utils package + * that is neither client nor service specific. + * @param name + * @return + */ + public static String prepareDefaultDisplayName( + String name ) { + StringBuilder newStr = new StringBuilder(); + newStr.append(name); + return newStr.toString(); + } + + public static List getTermGroupInstance(String identifier) { + if (Tools.isBlank(identifier)) { + identifier = getGeneratedIdentifier(); + } + List terms = new ArrayList(); + LocTermGroup term = new LocTermGroup(); + term.setTermDisplayName(identifier); + term.setTermName(identifier); + terms.add(term); + return terms; + } + + private static String getGeneratedIdentifier() { + return "id" + new Date().getTime(); + } + +} diff --git a/services/location/client/src/test/resources/log4j.properties b/services/location/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/location/client/src/test/resources/log4j.properties +++ b/services/location/client/src/test/resources/log4j.properties @@ -1,23 +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 +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/location/installer/build.xml b/services/location/installer/build.xml index 9c62d3eab..eafb2dfc2 100644 --- a/services/location/installer/build.xml +++ b/services/location/installer/build.xml @@ -1,61 +1,61 @@ - - - - location service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + location service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/location/jaxb/src/main/java/org/collectionspace/services/LocationJAXBSchema.java b/services/location/jaxb/src/main/java/org/collectionspace/services/LocationJAXBSchema.java index 65ad36ae9..92097fc2d 100644 --- a/services/location/jaxb/src/main/java/org/collectionspace/services/LocationJAXBSchema.java +++ b/services/location/jaxb/src/main/java/org/collectionspace/services/LocationJAXBSchema.java @@ -1,23 +1,23 @@ -/** - * - */ -package org.collectionspace.services; -import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema; - -/** - * @author pschmitz - * - */ -public interface LocationJAXBSchema extends AuthorityItemJAXBSchema { - final static String LOCATIONS_COMMON = "locations_common"; - final static String NAME = "name"; - final static String CONDITION_GROUP_LIST = "conditionGroupList"; - final static String CONDITION_GROUP = "conditionGroup"; - final static String CONDITION_NOTE = "conditionNote"; - final static String CONDITION_NOTE_DATE = "conditionNoteDate"; - final static String SECURITY_NOTE = "securityNote"; - final static String ACCESS_NOTE = "accessNote"; - final static String ADDRESS = "address"; - final static String LOCATION_TYPE = "locationType"; -} - +/** + * + */ +package org.collectionspace.services; +import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema; + +/** + * @author pschmitz + * + */ +public interface LocationJAXBSchema extends AuthorityItemJAXBSchema { + final static String LOCATIONS_COMMON = "locations_common"; + final static String NAME = "name"; + final static String CONDITION_GROUP_LIST = "conditionGroupList"; + final static String CONDITION_GROUP = "conditionGroup"; + final static String CONDITION_NOTE = "conditionNote"; + final static String CONDITION_NOTE_DATE = "conditionNoteDate"; + final static String SECURITY_NOTE = "securityNote"; + final static String ACCESS_NOTE = "accessNote"; + final static String ADDRESS = "address"; + final static String LOCATION_TYPE = "locationType"; +} + diff --git a/services/location/pom.xml b/services/location/pom.xml index 94f75b90b..2f512df12 100644 --- a/services/location/pom.xml +++ b/services/location/pom.xml @@ -1,35 +1,35 @@ - - - - org.collectionspace.services - org.collectionspace.services.main - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.location - services.location - pom - - - - - - jaxb - service - 3rdparty - client - - - - - samples - - - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.main + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.location + services.location + pom + + + + + + jaxb + service + 3rdparty + client + + + + + samples + + + + + + + + diff --git a/services/location/service/pom.xml b/services/location/service/pom.xml index ae57eec58..9c9419a19 100644 --- a/services/location/service/pom.xml +++ b/services/location/service/pom.xml @@ -1,133 +1,133 @@ - - - - org.collectionspace.services - org.collectionspace.services.location - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.location.service - services.location.service - jar - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.location.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.location.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authority.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.contact.service - ${project.version} - - - - junit - junit - 4.1 - test - - - org.testng - testng - - - - - commons-beanutils - commons-beanutils - 1.6.1 - - - - commons-logging - commons-logging - 1.1 - - - - - - javax.security - jaas - 1.0.01 - provided - - - - dom4j - dom4j - 1.6.1 - provided - - - - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - - - org.nuxeo.ecm.core - nuxeo-core-api - - - jboss-remoting - jboss - - - - - - - - collectionspace-services-location - - - - - + + + + org.collectionspace.services + org.collectionspace.services.location + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.location.service + services.location.service + jar + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.location.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.location.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authority.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.contact.service + ${project.version} + + + + junit + junit + 4.1 + test + + + org.testng + testng + + + + + commons-beanutils + commons-beanutils + 1.6.1 + + + + commons-logging + commons-logging + 1.1 + + + + + + javax.security + jaas + 1.0.01 + provided + + + + dom4j + dom4j + 1.6.1 + provided + + + + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + + + org.nuxeo.ecm.core + nuxeo-core-api + + + jboss-remoting + jboss + + + + + + + + collectionspace-services-location + + + + + diff --git a/services/media/.project b/services/media/.project index 222db5666..024ee2a31 100644 --- a/services/media/.project +++ b/services/media/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.media - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.media + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/media/3rdparty/.project b/services/media/3rdparty/.project index 4b250fa94..9df5c138c 100644 --- a/services/media/3rdparty/.project +++ b/services/media/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.media.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.media.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/media/client/src/test/resources/log4j.properties b/services/media/client/src/test/resources/log4j.properties index 66bef70e6..2a4e1058a 100644 --- a/services/media/client/src/test/resources/log4j.properties +++ b/services/media/client/src/test/resources/log4j.properties @@ -1,26 +1,26 @@ -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.services.client.PoxPayloadIn=DEBUG -log4j.logger.org.collectionspace.services.client.PoxPayloadOut=DEBUG - -log4j.logger.org.collectionspace=DEBUG -log4j.logger.org.apache=INFO -log4j.logger.httpclient=INFO -log4j.logger.org.jboss.resteasy=INFO +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.services.client.PoxPayloadIn=DEBUG +log4j.logger.org.collectionspace.services.client.PoxPayloadOut=DEBUG + +log4j.logger.org.collectionspace=DEBUG +log4j.logger.org.apache=INFO +log4j.logger.httpclient=INFO +log4j.logger.org.jboss.resteasy=INFO diff --git a/services/media/service/src/main/java/org/collectionspace/services/media/MediaBlobInput.java b/services/media/service/src/main/java/org/collectionspace/services/media/MediaBlobInput.java index 62a0e9800..64ee714bc 100644 --- a/services/media/service/src/main/java/org/collectionspace/services/media/MediaBlobInput.java +++ b/services/media/service/src/main/java/org/collectionspace/services/media/MediaBlobInput.java @@ -1,27 +1,27 @@ -package org.collectionspace.services.media; - -import java.io.File; - -public class MediaBlobInput { - private String mediaCsid; - private File blobFile; - private String blobUri; - - MediaBlobInput(String mediaCsid, File blobFile, String blobUri) { - this.mediaCsid = mediaCsid; - this.blobFile = blobFile; - this.blobUri = blobUri; - } - - String getMediaCsid() { - return mediaCsid; - } - - File getBlobFile() { - return blobFile; - } - - String getBlobUri() { - return blobUri; - } -} +package org.collectionspace.services.media; + +import java.io.File; + +public class MediaBlobInput { + private String mediaCsid; + private File blobFile; + private String blobUri; + + MediaBlobInput(String mediaCsid, File blobFile, String blobUri) { + this.mediaCsid = mediaCsid; + this.blobFile = blobFile; + this.blobUri = blobUri; + } + + String getMediaCsid() { + return mediaCsid; + } + + File getBlobFile() { + return blobFile; + } + + String getBlobUri() { + return blobUri; + } +} diff --git a/services/movement/.project b/services/movement/.project index 43c50797b..be03195c2 100644 --- a/services/movement/.project +++ b/services/movement/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.movement - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.movement + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/movement/3rdparty/.project b/services/movement/3rdparty/.project index 9e1e11858..7d048e95b 100644 --- a/services/movement/3rdparty/.project +++ b/services/movement/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.movement.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.movement.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/movement/client/src/test/resources/log4j.properties b/services/movement/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/movement/client/src/test/resources/log4j.properties +++ b/services/movement/client/src/test/resources/log4j.properties @@ -1,23 +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 +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/note/.classpath b/services/note/.classpath index 046988541..25df93560 100644 --- a/services/note/.classpath +++ b/services/note/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/note/.project b/services/note/.project index eff807f25..e32d89ede 100644 --- a/services/note/.project +++ b/services/note/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.note - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.note + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/note/3rdparty/.classpath b/services/note/3rdparty/.classpath index 046988541..25df93560 100644 --- a/services/note/3rdparty/.classpath +++ b/services/note/3rdparty/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/note/3rdparty/.project b/services/note/3rdparty/.project index b592d9d94..0dadf5659 100644 --- a/services/note/3rdparty/.project +++ b/services/note/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.note.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.note.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/note/3rdparty/build.xml b/services/note/3rdparty/build.xml index 1662eadcd..c9ace8efa 100644 --- a/services/note/3rdparty/build.xml +++ b/services/note/3rdparty/build.xml @@ -1,129 +1,129 @@ - - - - note service 3rdparty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + note service 3rdparty + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/note/3rdparty/nuxeo-platform-cs-note/build.xml b/services/note/3rdparty/nuxeo-platform-cs-note/build.xml index 543ceb225..756bccf25 100644 --- a/services/note/3rdparty/nuxeo-platform-cs-note/build.xml +++ b/services/note/3rdparty/nuxeo-platform-cs-note/build.xml @@ -1,140 +1,140 @@ - - - - note nuxeo document type - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + note nuxeo document type + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/note/3rdparty/nuxeo-platform-cs-note/pom.xml b/services/note/3rdparty/nuxeo-platform-cs-note/pom.xml index bc11def34..daab513d2 100644 --- a/services/note/3rdparty/nuxeo-platform-cs-note/pom.xml +++ b/services/note/3rdparty/nuxeo-platform-cs-note/pom.xml @@ -1,43 +1,43 @@ - - - org.collectionspace.services - org.collectionspace.services.note.3rdparty - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.note.3rdparty.nuxeo - services.note.3rdparty.nuxeo - jar - - note Nuxeo Document Type - - - - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-jar-plugin - - - src/main/resources/META-INF/MANIFEST.MF - - ${eclipseVersion} - 2 - - - - - - - - + + + org.collectionspace.services + org.collectionspace.services.note.3rdparty + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.note.3rdparty.nuxeo + services.note.3rdparty.nuxeo + jar + + note Nuxeo Document Type + + + + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-jar-plugin + + + src/main/resources/META-INF/MANIFEST.MF + + ${eclipseVersion} + 2 + + + + + + + + diff --git a/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/META-INF/MANIFEST.MF b/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/META-INF/MANIFEST.MF index 3ce672f4b..7766b29f0 100644 --- a/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/META-INF/MANIFEST.MF +++ b/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/META-INF/MANIFEST.MF @@ -1,23 +1,23 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 1 -Bundle-Name: NuxeoCS -Bundle-SymbolicName: org.collectionspace.note;singleton:=true -Bundle-Version: 1.0.0 -Bundle-Localization: plugin -Bundle-Vendor: Nuxeo -Require-Bundle: org.nuxeo.runtime, - org.nuxeo.ecm.core.api, - org.nuxeo.ecm.core, - org.nuxeo.ecm.core.api, - org.nuxeo.ecm.platform.types.api, - org.nuxeo.ecm.platform.versioning.api, - org.nuxeo.ecm.platform.ui, - org.nuxeo.ecm.platform.forms.layout.client, - org.nuxeo.ecm.platform.ws, - org.collectionspace.collectionspace_core -Provide-Package: org.collectionspace.note -Nuxeo-Component: OSGI-INF/core-types-contrib.xml, - OSGI-INF/life-cycle-contrib.xml, - OSGI-INF/ecm-types-contrib.xml, - OSGI-INF/layouts-contrib.xml - +Manifest-Version: 1.0 +Bundle-ManifestVersion: 1 +Bundle-Name: NuxeoCS +Bundle-SymbolicName: org.collectionspace.note;singleton:=true +Bundle-Version: 1.0.0 +Bundle-Localization: plugin +Bundle-Vendor: Nuxeo +Require-Bundle: org.nuxeo.runtime, + org.nuxeo.ecm.core.api, + org.nuxeo.ecm.core, + org.nuxeo.ecm.core.api, + org.nuxeo.ecm.platform.types.api, + org.nuxeo.ecm.platform.versioning.api, + org.nuxeo.ecm.platform.ui, + org.nuxeo.ecm.platform.forms.layout.client, + org.nuxeo.ecm.platform.ws, + org.collectionspace.collectionspace_core +Provide-Package: org.collectionspace.note +Nuxeo-Component: OSGI-INF/core-types-contrib.xml, + OSGI-INF/life-cycle-contrib.xml, + OSGI-INF/ecm-types-contrib.xml, + OSGI-INF/layouts-contrib.xml + diff --git a/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/OSGI-INF/core-types-contrib.xml b/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/OSGI-INF/core-types-contrib.xml index e82f5f6c4..f2b21c1f4 100644 --- a/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/OSGI-INF/core-types-contrib.xml +++ b/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/OSGI-INF/core-types-contrib.xml @@ -1,15 +1,15 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + diff --git a/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/OSGI-INF/deployment-fragment.xml b/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/OSGI-INF/deployment-fragment.xml index 226075b98..270abbd5f 100644 --- a/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/OSGI-INF/deployment-fragment.xml +++ b/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/OSGI-INF/deployment-fragment.xml @@ -1,10 +1,10 @@ - - - - - - ${bundle.fileName} - - - - + + + + + + ${bundle.fileName} + + + + diff --git a/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/OSGI-INF/ecm-types-contrib.xml b/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/OSGI-INF/ecm-types-contrib.xml index c175ecc30..1f67636e8 100644 --- a/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/OSGI-INF/ecm-types-contrib.xml +++ b/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/OSGI-INF/ecm-types-contrib.xml @@ -1,30 +1,30 @@ - - - - - - - view_documents - - - heading - collectionspace_core - subitem - cs_note - - - - - - Note - - - - - - Note - - - - - + + + + + + + view_documents + + + heading + collectionspace_core + subitem + cs_note + + + + + + Note + + + + + + Note + + + + + diff --git a/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/OSGI-INF/layouts-contrib.xml b/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/OSGI-INF/layouts-contrib.xml index fba057674..8882243e5 100644 --- a/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/OSGI-INF/layouts-contrib.xml +++ b/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/OSGI-INF/layouts-contrib.xml @@ -1,61 +1,61 @@ - - - - - - - - - - - - - content - author - date - - - - - - - true - - content - - - dataInputText - - - - - - - - true - - author - - - dataInputText - - - - - - - - true - - date - - - dataInputText - - - - - - - + + + + + + + + + + + + + content + author + date + + + + + + + true + + content + + + dataInputText + + + + + + + + true + + author + + + dataInputText + + + + + + + + true + + date + + + dataInputText + + + + + + + diff --git a/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/schemas/notes_common.xsd b/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/schemas/notes_common.xsd index f12eed3eb..6ee4515ae 100644 --- a/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/schemas/notes_common.xsd +++ b/services/note/3rdparty/nuxeo-platform-cs-note/src/main/resources/schemas/notes_common.xsd @@ -1,26 +1,26 @@ - - - - - - - - - - - - + + + + + + + + + + + + diff --git a/services/note/3rdparty/pom.xml b/services/note/3rdparty/pom.xml index e77ce625c..767527e4b 100644 --- a/services/note/3rdparty/pom.xml +++ b/services/note/3rdparty/pom.xml @@ -1,24 +1,24 @@ - - - - org.collectionspace.services - org.collectionspace.services.note - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.note.3rdparty - services.note.3rdparty - pom - - 3rd party build for note service - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.note + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.note.3rdparty + services.note.3rdparty + pom + + 3rd party build for note service + + + + + + diff --git a/services/note/build.xml b/services/note/build.xml index b1d725104..382b1c7fa 100644 --- a/services/note/build.xml +++ b/services/note/build.xml @@ -1,122 +1,122 @@ - - - - note service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + note service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/note/client/pom.xml b/services/note/client/pom.xml index a8b8cb400..58073f203 100644 --- a/services/note/client/pom.xml +++ b/services/note/client/pom.xml @@ -1,87 +1,87 @@ - - - - org.collectionspace.services.note - org.collectionspace.services - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.note.client - services.note.client - - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - - org.collectionspace.services - org.collectionspace.services.note.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.common - true - ${project.version} - - - - - - - org.testng - testng - - - org.jboss.resteasy - resteasy-jaxrs - - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - commons-httpclient - commons-httpclient - 3.1 - - - - - collectionspace-services-note-client - - - + + + + org.collectionspace.services.note + org.collectionspace.services + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.note.client + services.note.client + + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + + org.collectionspace.services + org.collectionspace.services.note.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.common + true + ${project.version} + + + + + + + org.testng + testng + + + org.jboss.resteasy + resteasy-jaxrs + + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + commons-httpclient + commons-httpclient + 3.1 + + + + + collectionspace-services-note-client + + + diff --git a/services/note/client/src/main/java/org/collectionspace/services/client/NoteClient.java b/services/note/client/src/main/java/org/collectionspace/services/client/NoteClient.java index f38dae4ef..c361264af 100644 --- a/services/note/client/src/main/java/org/collectionspace/services/client/NoteClient.java +++ b/services/note/client/src/main/java/org/collectionspace/services/client/NoteClient.java @@ -1,68 +1,68 @@ -/** - * 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 (c) 2009 Regents of the University of California - * - * 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.client; - -import javax.ws.rs.core.Response; - -import org.collectionspace.services.note.NotesCommonList; - -import org.jboss.resteasy.client.ProxyFactory; -import org.jboss.resteasy.plugins.providers.RegisterBuiltin; -import org.jboss.resteasy.client.ClientResponse; -import org.jboss.resteasy.client.core.executors.ApacheHttpClientExecutor; -import org.jboss.resteasy.spi.ResteasyProviderFactory; - -/** - * NoteClient.java - * - * $LastChangedRevision: $ - * $LastChangedDate: $ - */ - -public class NoteClient extends AbstractPoxServiceClientImpl { - - public static final String SERVICE_NAME = "notes"; - public static final String SERVICE_PATH_COMPONENT = SERVICE_NAME; - public static final String SERVICE_PATH = "/" + SERVICE_PATH_COMPONENT; - - @Override - public String getServiceName() { - return SERVICE_NAME; - } - - @Override - public String getServicePathComponent() { - return SERVICE_PATH_COMPONENT; - } - - @Override - public Class getProxyClass() { - return NoteProxy.class; - } - - /* - * Proxied service calls - */ - - /** - * @return - * @see org.collectionspace.services.client.Note#getNote() - */ - public ClientResponse readList() { - return getProxy().readList(); - } -} +/** + * 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 (c) 2009 Regents of the University of California + * + * 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.client; + +import javax.ws.rs.core.Response; + +import org.collectionspace.services.note.NotesCommonList; + +import org.jboss.resteasy.client.ProxyFactory; +import org.jboss.resteasy.plugins.providers.RegisterBuiltin; +import org.jboss.resteasy.client.ClientResponse; +import org.jboss.resteasy.client.core.executors.ApacheHttpClientExecutor; +import org.jboss.resteasy.spi.ResteasyProviderFactory; + +/** + * NoteClient.java + * + * $LastChangedRevision: $ + * $LastChangedDate: $ + */ + +public class NoteClient extends AbstractPoxServiceClientImpl { + + public static final String SERVICE_NAME = "notes"; + public static final String SERVICE_PATH_COMPONENT = SERVICE_NAME; + public static final String SERVICE_PATH = "/" + SERVICE_PATH_COMPONENT; + + @Override + public String getServiceName() { + return SERVICE_NAME; + } + + @Override + public String getServicePathComponent() { + return SERVICE_PATH_COMPONENT; + } + + @Override + public Class getProxyClass() { + return NoteProxy.class; + } + + /* + * Proxied service calls + */ + + /** + * @return + * @see org.collectionspace.services.client.Note#getNote() + */ + public ClientResponse readList() { + return getProxy().readList(); + } +} diff --git a/services/note/client/src/main/java/org/collectionspace/services/client/NoteClientUtils.java b/services/note/client/src/main/java/org/collectionspace/services/client/NoteClientUtils.java index 8d08dd452..18c946788 100644 --- a/services/note/client/src/main/java/org/collectionspace/services/client/NoteClientUtils.java +++ b/services/note/client/src/main/java/org/collectionspace/services/client/NoteClientUtils.java @@ -1,56 +1,56 @@ -package org.collectionspace.services.client; - -import javax.ws.rs.core.MediaType; - -import org.collectionspace.services.note.NotesCommon; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class NoteClientUtils { - - private static final Logger logger = - LoggerFactory.getLogger(NoteClientUtils.class); - - private static final String SERVICE_PATH_COMPONENT = "notes"; - - public static PoxPayloadOut createNoteInstance ( - String owner, String identifier, String headerLabel) { - return createNoteInstance( - owner, - false, 0, - "content-" + identifier, - "author-" + identifier, - "date-" + identifier, - headerLabel); - } - - public static PoxPayloadOut createNoteInstance( - String owner, boolean isPrimary, int order, - String content, String author, String date, String headerLabel) { - NotesCommon noteCommon = new NotesCommon(); - noteCommon.setOwner(owner); - noteCommon.setIsPrimary(isPrimary); - noteCommon.setOrder(order); - noteCommon.setContent(content); - noteCommon.setAuthor(author); - noteCommon.setDate(date); - - PoxPayloadOut multipart = new PoxPayloadOut(getServicePathComponent()); - PayloadOutputPart commonPart = - multipart.addPart(noteCommon, MediaType.APPLICATION_XML_TYPE); - commonPart.setLabel(new NoteClient().getCommonPartName()); - - if(logger.isDebugEnabled()){ - logger.debug("to be created, note common"); - // logger.debug(objectAsXmlString(note, NotesCommon.class)); - } - - return multipart; - } - - public static String getServicePathComponent() { - return SERVICE_PATH_COMPONENT; - } - -} +package org.collectionspace.services.client; + +import javax.ws.rs.core.MediaType; + +import org.collectionspace.services.note.NotesCommon; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NoteClientUtils { + + private static final Logger logger = + LoggerFactory.getLogger(NoteClientUtils.class); + + private static final String SERVICE_PATH_COMPONENT = "notes"; + + public static PoxPayloadOut createNoteInstance ( + String owner, String identifier, String headerLabel) { + return createNoteInstance( + owner, + false, 0, + "content-" + identifier, + "author-" + identifier, + "date-" + identifier, + headerLabel); + } + + public static PoxPayloadOut createNoteInstance( + String owner, boolean isPrimary, int order, + String content, String author, String date, String headerLabel) { + NotesCommon noteCommon = new NotesCommon(); + noteCommon.setOwner(owner); + noteCommon.setIsPrimary(isPrimary); + noteCommon.setOrder(order); + noteCommon.setContent(content); + noteCommon.setAuthor(author); + noteCommon.setDate(date); + + PoxPayloadOut multipart = new PoxPayloadOut(getServicePathComponent()); + PayloadOutputPart commonPart = + multipart.addPart(noteCommon, MediaType.APPLICATION_XML_TYPE); + commonPart.setLabel(new NoteClient().getCommonPartName()); + + if(logger.isDebugEnabled()){ + logger.debug("to be created, note common"); + // logger.debug(objectAsXmlString(note, NotesCommon.class)); + } + + return multipart; + } + + public static String getServicePathComponent() { + return SERVICE_PATH_COMPONENT; + } + +} diff --git a/services/note/client/src/main/java/org/collectionspace/services/client/NoteProxy.java b/services/note/client/src/main/java/org/collectionspace/services/client/NoteProxy.java index d0669f1e8..3544b882c 100644 --- a/services/note/client/src/main/java/org/collectionspace/services/client/NoteProxy.java +++ b/services/note/client/src/main/java/org/collectionspace/services/client/NoteProxy.java @@ -1,63 +1,63 @@ -package org.collectionspace.services.client; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; - -import org.collectionspace.services.note.NotesCommonList; -import org.collectionspace.services.client.workflow.WorkflowClient; - -import org.jboss.resteasy.client.ClientResponse; - -/** - * @version $Revision:$ - */ -@Path("/notes/") -@Produces({"application/xml;charset=UTF-8"}) -@Consumes({"application/xml"}) -public interface NoteProxy extends CollectionSpacePoxProxy { - @GET - @Produces({"application/xml"}) - ClientResponse readList(); - - @Override - @GET - @Produces({"application/xml"}) - ClientResponse readIncludeDeleted( - @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); - - @Override - @GET - @Produces({"application/xml"}) - ClientResponse keywordSearchIncludeDeleted( - @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_KW) String keywords, - @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); - - /* - //(C)reate - @POST - ClientResponse create(String payload); - - //(R)ead - @GET - @Path("/{csid}") - ClientResponse read(@PathParam("csid") String csid); - - //(U)pdate - @PUT - @Path("/{csid}") - ClientResponse update(@PathParam("csid") String csid, String payload); - - //(D)elete - @DELETE - @Path("/{csid}") - ClientResponse delete(@PathParam("csid") String csid); - */ -} +package org.collectionspace.services.client; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; + +import org.collectionspace.services.note.NotesCommonList; +import org.collectionspace.services.client.workflow.WorkflowClient; + +import org.jboss.resteasy.client.ClientResponse; + +/** + * @version $Revision:$ + */ +@Path("/notes/") +@Produces({"application/xml;charset=UTF-8"}) +@Consumes({"application/xml"}) +public interface NoteProxy extends CollectionSpacePoxProxy { + @GET + @Produces({"application/xml"}) + ClientResponse readList(); + + @Override + @GET + @Produces({"application/xml"}) + ClientResponse readIncludeDeleted( + @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); + + @Override + @GET + @Produces({"application/xml"}) + ClientResponse keywordSearchIncludeDeleted( + @QueryParam(IQueryManager.SEARCH_TYPE_KEYWORDS_KW) String keywords, + @QueryParam(WorkflowClient.WORKFLOWSTATE_QUERY) String workflowState); + + /* + //(C)reate + @POST + ClientResponse create(String payload); + + //(R)ead + @GET + @Path("/{csid}") + ClientResponse read(@PathParam("csid") String csid); + + //(U)pdate + @PUT + @Path("/{csid}") + ClientResponse update(@PathParam("csid") String csid, String payload); + + //(D)elete + @DELETE + @Path("/{csid}") + ClientResponse delete(@PathParam("csid") String csid); + */ +} diff --git a/services/note/client/src/test/java/org/collectionspace/services/client/test/NoteServiceTest.java b/services/note/client/src/test/java/org/collectionspace/services/client/test/NoteServiceTest.java index d2e2a232d..fb8e9539d 100644 --- a/services/note/client/src/test/java/org/collectionspace/services/client/test/NoteServiceTest.java +++ b/services/note/client/src/test/java/org/collectionspace/services/client/test/NoteServiceTest.java @@ -1,116 +1,116 @@ -/** - * 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 Regents of the University of California - * - * 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.client.test; - -import org.collectionspace.services.client.CollectionSpaceClient; -import org.collectionspace.services.client.NoteClient; -import org.collectionspace.services.client.NoteClientUtils; -import org.collectionspace.services.client.PoxPayloadOut; -import org.collectionspace.services.note.NotesCommon; -import org.collectionspace.services.note.NotesCommonList; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; - -/** - * NoteServiceTest, carries out tests against a - * deployed and running Note Service. - * - * $LastChangedRevision: 917 $ - * $LastChangedDate: 2009-11-06 12:20:28 -0800 (Fri, 06 Nov 2009) $ - */ -public class NoteServiceTest extends AbstractPoxServiceTestImpl { - - private final String CLASS_NAME = NoteServiceTest.class.getName(); - private final Logger logger = LoggerFactory.getLogger(CLASS_NAME); - - private final String SERVICE_PATH_COMPONENT = "notes"; - private final String SERVICE_NAME = "notes"; - - /* (non-Javadoc) - * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance() - */ - @Override - protected CollectionSpaceClient getClientInstance() { - return new NoteClient(); - } - - @Override - protected PoxPayloadOut createInstance(String commonPartName, - String identifier) { - PoxPayloadOut result = - NoteClientUtils.createNoteInstance("owner"+identifier, identifier, - commonPartName); - return result; - } - - // --------------------------------------------------------------- - // Utility tests : tests of code used in tests above - // --------------------------------------------------------------- - - @Override - public String getServiceName() { - return SERVICE_NAME; - } - - // --------------------------------------------------------------- - // Utility methods used by tests above - // --------------------------------------------------------------- - @Override - public String getServicePathComponent() { - return SERVICE_PATH_COMPONENT; - } - - @Override - protected Class getCommonListType() { - return NotesCommonList.class; - } - - @Override - protected NotesCommon updateInstance(NotesCommon notesCommon) { - NotesCommon result = new NotesCommon(); - - // Update the common part, both the subitem, and the content - result.setContent("updated-" + notesCommon.getContent()); - result.setOrder(notesCommon.getOrder() + 10); - - return result; - } - - @Override - protected void compareUpdatedInstances(NotesCommon original, - NotesCommon updated) throws Exception { - // Check selected fields in the updated common part. - Assert.assertEquals(updated.getContent(), original.getContent(), - "Content in updated object did not match submitted data."); - Assert.assertEquals(updated.getOrder(), original.getOrder(), - "Order in updated object (subitem) did not match submitted data."); - } - - @Override - public void CRUDTests(String testName) { - // TODO Auto-generated method stub - - } -} +/** + * 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 Regents of the University of California + * + * 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.client.test; + +import org.collectionspace.services.client.CollectionSpaceClient; +import org.collectionspace.services.client.NoteClient; +import org.collectionspace.services.client.NoteClientUtils; +import org.collectionspace.services.client.PoxPayloadOut; +import org.collectionspace.services.note.NotesCommon; +import org.collectionspace.services.note.NotesCommonList; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; + +/** + * NoteServiceTest, carries out tests against a + * deployed and running Note Service. + * + * $LastChangedRevision: 917 $ + * $LastChangedDate: 2009-11-06 12:20:28 -0800 (Fri, 06 Nov 2009) $ + */ +public class NoteServiceTest extends AbstractPoxServiceTestImpl { + + private final String CLASS_NAME = NoteServiceTest.class.getName(); + private final Logger logger = LoggerFactory.getLogger(CLASS_NAME); + + private final String SERVICE_PATH_COMPONENT = "notes"; + private final String SERVICE_NAME = "notes"; + + /* (non-Javadoc) + * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance() + */ + @Override + protected CollectionSpaceClient getClientInstance() { + return new NoteClient(); + } + + @Override + protected PoxPayloadOut createInstance(String commonPartName, + String identifier) { + PoxPayloadOut result = + NoteClientUtils.createNoteInstance("owner"+identifier, identifier, + commonPartName); + return result; + } + + // --------------------------------------------------------------- + // Utility tests : tests of code used in tests above + // --------------------------------------------------------------- + + @Override + public String getServiceName() { + return SERVICE_NAME; + } + + // --------------------------------------------------------------- + // Utility methods used by tests above + // --------------------------------------------------------------- + @Override + public String getServicePathComponent() { + return SERVICE_PATH_COMPONENT; + } + + @Override + protected Class getCommonListType() { + return NotesCommonList.class; + } + + @Override + protected NotesCommon updateInstance(NotesCommon notesCommon) { + NotesCommon result = new NotesCommon(); + + // Update the common part, both the subitem, and the content + result.setContent("updated-" + notesCommon.getContent()); + result.setOrder(notesCommon.getOrder() + 10); + + return result; + } + + @Override + protected void compareUpdatedInstances(NotesCommon original, + NotesCommon updated) throws Exception { + // Check selected fields in the updated common part. + Assert.assertEquals(updated.getContent(), original.getContent(), + "Content in updated object did not match submitted data."); + Assert.assertEquals(updated.getOrder(), original.getOrder(), + "Order in updated object (subitem) did not match submitted data."); + } + + @Override + public void CRUDTests(String testName) { + // TODO Auto-generated method stub + + } +} diff --git a/services/note/client/src/test/resources/log4j.properties b/services/note/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/note/client/src/test/resources/log4j.properties +++ b/services/note/client/src/test/resources/log4j.properties @@ -1,23 +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 +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/note/jaxb/pom.xml b/services/note/jaxb/pom.xml index 9db1081ae..03636cfdc 100644 --- a/services/note/jaxb/pom.xml +++ b/services/note/jaxb/pom.xml @@ -1,39 +1,39 @@ - - - - org.collectionspace.services - org.collectionspace.services.note - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.note.jaxb - services.note.jaxb - - - - org.collectionspace.services - org.collectionspace.services.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.hyperjaxb - ${project.version} - - - - - collectionspace-services-note-jaxb - install - - - org.jvnet.jaxb2.maven2 - maven-jaxb2-plugin - - - - - + + + + org.collectionspace.services + org.collectionspace.services.note + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.note.jaxb + services.note.jaxb + + + + org.collectionspace.services + org.collectionspace.services.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.hyperjaxb + ${project.version} + + + + + collectionspace-services-note-jaxb + install + + + org.jvnet.jaxb2.maven2 + maven-jaxb2-plugin + + + + + diff --git a/services/note/jaxb/src/main/java/org/collectionspace/services/note/NoteJAXBSchema.java b/services/note/jaxb/src/main/java/org/collectionspace/services/note/NoteJAXBSchema.java index 5d0d6d7a4..6576fe3bf 100644 --- a/services/note/jaxb/src/main/java/org/collectionspace/services/note/NoteJAXBSchema.java +++ b/services/note/jaxb/src/main/java/org/collectionspace/services/note/NoteJAXBSchema.java @@ -1,20 +1,20 @@ -/** - * - */ -package org.collectionspace.services.note; - -/** - * - */ -public interface NoteJAXBSchema { - final static String NOTES_COMMON = "notes_common"; - final static String CSID = "csid"; - final static String OWNER = "owner"; - final static String IS_PRIMARY ="isPrimary"; - final static String ORDER = "order"; - final static String CONTENT = "content"; - final static String AUTHOR = "author"; - final static String DATE = "date"; -} - - +/** + * + */ +package org.collectionspace.services.note; + +/** + * + */ +public interface NoteJAXBSchema { + final static String NOTES_COMMON = "notes_common"; + final static String CSID = "csid"; + final static String OWNER = "owner"; + final static String IS_PRIMARY ="isPrimary"; + final static String ORDER = "order"; + final static String CONTENT = "content"; + final static String AUTHOR = "author"; + final static String DATE = "date"; +} + + diff --git a/services/note/jaxb/src/main/java/org/collectionspace/services/note/NoteListItemJAXBSchema.java b/services/note/jaxb/src/main/java/org/collectionspace/services/note/NoteListItemJAXBSchema.java index 58b82133d..ac929f0fd 100644 --- a/services/note/jaxb/src/main/java/org/collectionspace/services/note/NoteListItemJAXBSchema.java +++ b/services/note/jaxb/src/main/java/org/collectionspace/services/note/NoteListItemJAXBSchema.java @@ -1,7 +1,7 @@ -package org.collectionspace.services.note; - -public interface NoteListItemJAXBSchema { - final static String CONTENT = "content"; - final static String CSID = "csid"; - final static String URI = "url"; -} +package org.collectionspace.services.note; + +public interface NoteListItemJAXBSchema { + final static String CONTENT = "content"; + final static String CSID = "csid"; + final static String URI = "url"; +} diff --git a/services/note/jaxb/src/main/resources/notes-common.xsd b/services/note/jaxb/src/main/resources/notes-common.xsd index aa01369f2..5a0f38a46 100644 --- a/services/note/jaxb/src/main/resources/notes-common.xsd +++ b/services/note/jaxb/src/main/resources/notes-common.xsd @@ -1,74 +1,74 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/note/pom.xml b/services/note/pom.xml index 8618bae82..379e02e03 100644 --- a/services/note/pom.xml +++ b/services/note/pom.xml @@ -1,24 +1,24 @@ - - - - - org.collectionspace.services.main - org.collectionspace.services - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.note - services.note - pom - - - jaxb - service - 3rdparty - client - - - - + + + + + org.collectionspace.services.main + org.collectionspace.services + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.note + services.note + pom + + + jaxb + service + 3rdparty + client + + + + diff --git a/services/note/service/pom.xml b/services/note/service/pom.xml index ceb4bcb36..87147fb00 100644 --- a/services/note/service/pom.xml +++ b/services/note/service/pom.xml @@ -1,93 +1,93 @@ - - - - org.collectionspace.services.note - org.collectionspace.services - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.note.service - services.note.service - jar - - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.note.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.note.client - ${project.version} - - - - org.testng - testng - - - - - - javax.security - jaas - 1.0.01 - provided - - - - dom4j - dom4j - 1.6.1 - provided - - - - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - - - org.nuxeo.ecm.core - nuxeo-core-api - - - jboss-remoting - jboss - - - - - - - - collectionspace-services-note - - - + + + + org.collectionspace.services.note + org.collectionspace.services + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.note.service + services.note.service + jar + + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.note.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.note.client + ${project.version} + + + + org.testng + testng + + + + + + javax.security + jaas + 1.0.01 + provided + + + + dom4j + dom4j + 1.6.1 + provided + + + + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + + + org.nuxeo.ecm.core + nuxeo-core-api + + + jboss-remoting + jboss + + + + + + + + collectionspace-services-note + + + diff --git a/services/note/service/profiles.xml b/services/note/service/profiles.xml index 12051b851..347b9df22 100644 --- a/services/note/service/profiles.xml +++ b/services/note/service/profiles.xml @@ -1,4 +1,4 @@ - - + + \ No newline at end of file diff --git a/services/note/service/src/main/java/org/collectionspace/services/note/NoteResource.java b/services/note/service/src/main/java/org/collectionspace/services/note/NoteResource.java index 368b7663f..f1081cc3b 100644 --- a/services/note/service/src/main/java/org/collectionspace/services/note/NoteResource.java +++ b/services/note/service/src/main/java/org/collectionspace/services/note/NoteResource.java @@ -1,58 +1,58 @@ -/** - * 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 Regents of the University of California - - * 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.note; - -import org.collectionspace.services.client.NoteClient; -import org.collectionspace.services.common.ResourceBase; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.ws.rs.Consumes; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; - -@Path(NoteClient.SERVICE_PATH) -@Consumes("application/xml") -@Produces("application/xml") -//@Produces("application/xml;charset=UTF-8") -public class NoteResource extends ResourceBase { - final Logger logger = LoggerFactory.getLogger(NoteResource.class); - - @Override - protected String getVersionString() { - final String lastChangeRevision = "$LastChangedRevision: 1982 $"; - return lastChangeRevision; - } - - @Override - public String getServiceName() { - return NoteClient.SERVICE_PATH_COMPONENT; - } - - @Override - public Class getCommonPartClass() { - return NotesCommon.class; - } - -} +/** + * 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 Regents of the University of California + + * 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.note; + +import org.collectionspace.services.client.NoteClient; +import org.collectionspace.services.common.ResourceBase; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.Consumes; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; + +@Path(NoteClient.SERVICE_PATH) +@Consumes("application/xml") +@Produces("application/xml") +//@Produces("application/xml;charset=UTF-8") +public class NoteResource extends ResourceBase { + final Logger logger = LoggerFactory.getLogger(NoteResource.class); + + @Override + protected String getVersionString() { + final String lastChangeRevision = "$LastChangedRevision: 1982 $"; + return lastChangeRevision; + } + + @Override + public String getServiceName() { + return NoteClient.SERVICE_PATH_COMPONENT; + } + + @Override + public Class getCommonPartClass() { + return NotesCommon.class; + } + +} diff --git a/services/note/service/src/main/java/org/collectionspace/services/note/nuxeo/NoteConstants.java b/services/note/service/src/main/java/org/collectionspace/services/note/nuxeo/NoteConstants.java index d1bf29ed2..917d61705 100644 --- a/services/note/service/src/main/java/org/collectionspace/services/note/nuxeo/NoteConstants.java +++ b/services/note/service/src/main/java/org/collectionspace/services/note/nuxeo/NoteConstants.java @@ -1,35 +1,35 @@ -/** - * 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.note.nuxeo; - -/** - * NoteConstants, stores constants related to Note documents - * - */ -public class NoteConstants { - - public final static String NUXEO_DOCTYPE = "Note"; - public final static String NUXEO_SCHEMA_NAME = "note"; - public final static String NUXEO_DC_TITLE = "CollectionSpace-Note"; -} +/** + * 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.note.nuxeo; + +/** + * NoteConstants, stores constants related to Note documents + * + */ +public class NoteConstants { + + public final static String NUXEO_DOCTYPE = "Note"; + public final static String NUXEO_SCHEMA_NAME = "note"; + public final static String NUXEO_DC_TITLE = "CollectionSpace-Note"; +} diff --git a/services/note/service/src/main/java/org/collectionspace/services/note/nuxeo/NoteDocumentModelHandler.java b/services/note/service/src/main/java/org/collectionspace/services/note/nuxeo/NoteDocumentModelHandler.java index df5dd994e..f2321cd3e 100644 --- a/services/note/service/src/main/java/org/collectionspace/services/note/nuxeo/NoteDocumentModelHandler.java +++ b/services/note/service/src/main/java/org/collectionspace/services/note/nuxeo/NoteDocumentModelHandler.java @@ -1,166 +1,166 @@ -/** - * 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 Regents of the University of California - - * 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.note.nuxeo; - -import java.util.Iterator; -import java.util.List; - -import org.collectionspace.services.note.NoteJAXBSchema; -import org.collectionspace.services.common.document.DocumentHandler.Action; -import org.collectionspace.services.common.document.DocumentWrapper; -import org.collectionspace.services.note.NotesCommon; -import org.collectionspace.services.note.NotesCommonList; -import org.collectionspace.services.note.NotesCommonList.NoteListItem; - -import org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl; -import org.collectionspace.services.nuxeo.client.java.RemoteSubItemDocumentModelHandlerImpl; -import org.collectionspace.services.nuxeo.util.NuxeoUtils; -import org.nuxeo.ecm.core.api.DocumentModel; -import org.nuxeo.ecm.core.api.DocumentModelList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The Class NoteDocumentModelHandler. - */ -public class NoteDocumentModelHandler - extends RemoteSubItemDocumentModelHandlerImpl { - - /** The logger. */ - private final Logger logger = LoggerFactory.getLogger(NoteDocumentModelHandler.class); - - /** The note. */ - private NotesCommon note; - - /** The note list. */ - private NotesCommonList noteList; - - /** The owner. */ - private String owner; - - private final String commonSchemaName = "notes_common"; - - public boolean schemaHasSubItem(String schema) { - return commonSchemaName.equals(schema); - } - - - /** - * Gets the owner. - * - * @return the owner - */ - public String getOwner() { - return owner; - } - - /** - * Sets the owner. - * - * @param owner the new owner - */ - public void setInAuthority(String owner) { - this.owner = owner; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getCommonPart() - */ - @Override - public NotesCommon getCommonPart() { - return note; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#setCommonPart(java.lang.Object) - */ - @Override - public void setCommonPart(NotesCommon note) { - this.note = note; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getCommonPartList() - */ - @Override - public NotesCommonList getCommonPartList() { - return noteList; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#setCommonPartList(java.lang.Object) - */ - @Override - public void setCommonPartList(NotesCommonList noteList) { - this.noteList = noteList; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#extractCommonPart(org.collectionspace.services.common.document.DocumentWrapper) - */ - @Override - public NotesCommon extractCommonPart(DocumentWrapper wrapDoc) - throws Exception { - throw new UnsupportedOperationException(); - } - - /* (non-Javadoc) - * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#fillCommonPart(java.lang.Object, org.collectionspace.services.common.document.DocumentWrapper) - */ - @Override - public void fillCommonPart(NotesCommon noteObject, DocumentWrapper wrapDoc) throws Exception { - throw new UnsupportedOperationException(); - } - - /* (non-Javadoc) - * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#extractCommonPartList(org.collectionspace.services.common.document.DocumentWrapper) - */ - @Override - public NotesCommonList extractCommonPartList(DocumentWrapper wrapDoc) throws Exception { - NotesCommonList coList = extractPagingInfo(new NotesCommonList(), wrapDoc); - List list = coList.getNoteListItem(); - Iterator iter = wrapDoc.getWrappedObject().iterator(); - while(iter.hasNext()){ - DocumentModel docModel = iter.next(); - NoteListItem clistItem = new NoteListItem(); - clistItem.setContent((String) docModel.getProperty(getServiceContext().getCommonPartLabel(), - NoteJAXBSchema.CONTENT)); - String id = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString()); - clistItem.setUri(getServiceContextPath() + id); - clistItem.setCsid(id); - list.add(clistItem); - } - - return coList; - } - - /* (non-Javadoc) - * @see org.collectionspace.services.common.document.AbstractMultipartDocumentHandlerImpl#getQProperty(java.lang.String) - */ - @Override - public String getQProperty(String prop) { - return NoteConstants.NUXEO_SCHEMA_NAME + ":" + prop; - } -} - +/** + * 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 Regents of the University of California + + * 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.note.nuxeo; + +import java.util.Iterator; +import java.util.List; + +import org.collectionspace.services.note.NoteJAXBSchema; +import org.collectionspace.services.common.document.DocumentHandler.Action; +import org.collectionspace.services.common.document.DocumentWrapper; +import org.collectionspace.services.note.NotesCommon; +import org.collectionspace.services.note.NotesCommonList; +import org.collectionspace.services.note.NotesCommonList.NoteListItem; + +import org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl; +import org.collectionspace.services.nuxeo.client.java.RemoteSubItemDocumentModelHandlerImpl; +import org.collectionspace.services.nuxeo.util.NuxeoUtils; +import org.nuxeo.ecm.core.api.DocumentModel; +import org.nuxeo.ecm.core.api.DocumentModelList; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The Class NoteDocumentModelHandler. + */ +public class NoteDocumentModelHandler + extends RemoteSubItemDocumentModelHandlerImpl { + + /** The logger. */ + private final Logger logger = LoggerFactory.getLogger(NoteDocumentModelHandler.class); + + /** The note. */ + private NotesCommon note; + + /** The note list. */ + private NotesCommonList noteList; + + /** The owner. */ + private String owner; + + private final String commonSchemaName = "notes_common"; + + public boolean schemaHasSubItem(String schema) { + return commonSchemaName.equals(schema); + } + + + /** + * Gets the owner. + * + * @return the owner + */ + public String getOwner() { + return owner; + } + + /** + * Sets the owner. + * + * @param owner the new owner + */ + public void setInAuthority(String owner) { + this.owner = owner; + } + + /* (non-Javadoc) + * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getCommonPart() + */ + @Override + public NotesCommon getCommonPart() { + return note; + } + + /* (non-Javadoc) + * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#setCommonPart(java.lang.Object) + */ + @Override + public void setCommonPart(NotesCommon note) { + this.note = note; + } + + /* (non-Javadoc) + * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getCommonPartList() + */ + @Override + public NotesCommonList getCommonPartList() { + return noteList; + } + + /* (non-Javadoc) + * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#setCommonPartList(java.lang.Object) + */ + @Override + public void setCommonPartList(NotesCommonList noteList) { + this.noteList = noteList; + } + + /* (non-Javadoc) + * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#extractCommonPart(org.collectionspace.services.common.document.DocumentWrapper) + */ + @Override + public NotesCommon extractCommonPart(DocumentWrapper wrapDoc) + throws Exception { + throw new UnsupportedOperationException(); + } + + /* (non-Javadoc) + * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#fillCommonPart(java.lang.Object, org.collectionspace.services.common.document.DocumentWrapper) + */ + @Override + public void fillCommonPart(NotesCommon noteObject, DocumentWrapper wrapDoc) throws Exception { + throw new UnsupportedOperationException(); + } + + /* (non-Javadoc) + * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#extractCommonPartList(org.collectionspace.services.common.document.DocumentWrapper) + */ + @Override + public NotesCommonList extractCommonPartList(DocumentWrapper wrapDoc) throws Exception { + NotesCommonList coList = extractPagingInfo(new NotesCommonList(), wrapDoc); + List list = coList.getNoteListItem(); + Iterator iter = wrapDoc.getWrappedObject().iterator(); + while(iter.hasNext()){ + DocumentModel docModel = iter.next(); + NoteListItem clistItem = new NoteListItem(); + clistItem.setContent((String) docModel.getProperty(getServiceContext().getCommonPartLabel(), + NoteJAXBSchema.CONTENT)); + String id = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString()); + clistItem.setUri(getServiceContextPath() + id); + clistItem.setCsid(id); + list.add(clistItem); + } + + return coList; + } + + /* (non-Javadoc) + * @see org.collectionspace.services.common.document.AbstractMultipartDocumentHandlerImpl#getQProperty(java.lang.String) + */ + @Override + public String getQProperty(String prop) { + return NoteConstants.NUXEO_SCHEMA_NAME + ":" + prop; + } +} + diff --git a/services/note/service/src/test/java/org/collectionspace/services/test/NoteServiceTest.java b/services/note/service/src/test/java/org/collectionspace/services/test/NoteServiceTest.java index a8393860e..f841a19c6 100644 --- a/services/note/service/src/test/java/org/collectionspace/services/test/NoteServiceTest.java +++ b/services/note/service/src/test/java/org/collectionspace/services/test/NoteServiceTest.java @@ -1,11 +1,11 @@ -package org.collectionspace.services.test; - - -/** - * NoteServiceTest - * - * @version $Revision:$ - */ -public class NoteServiceTest { - //empty -} +package org.collectionspace.services.test; + + +/** + * NoteServiceTest + * + * @version $Revision:$ + */ +public class NoteServiceTest { + //empty +} diff --git a/services/note/service/src/test/resources/log4j.xml b/services/note/service/src/test/resources/log4j.xml index 6881ae6dd..52121cb83 100644 --- a/services/note/service/src/test/resources/log4j.xml +++ b/services/note/service/src/test/resources/log4j.xml @@ -1,45 +1,45 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/objectexit/.project b/services/objectexit/.project index 221909388..70d12f959 100644 --- a/services/objectexit/.project +++ b/services/objectexit/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.objectexit - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.objectexit + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/objectexit/3rdparty/.project b/services/objectexit/3rdparty/.project index 9ffbbb0bc..ca5b178fb 100644 --- a/services/objectexit/3rdparty/.project +++ b/services/objectexit/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.objectexit.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.objectexit.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/objectexit/client/src/test/resources/log4j.properties b/services/objectexit/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/objectexit/client/src/test/resources/log4j.properties +++ b/services/objectexit/client/src/test/resources/log4j.properties @@ -1,23 +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 +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/organization/.classpath b/services/organization/.classpath index d18316afc..2068e34f3 100644 --- a/services/organization/.classpath +++ b/services/organization/.classpath @@ -1,5 +1,5 @@ - - - - - + + + + + diff --git a/services/organization/.project b/services/organization/.project index 5985f1b66..d3d10aaa1 100644 --- a/services/organization/.project +++ b/services/organization/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.organization - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.organization + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/organization/3rdparty/.classpath b/services/organization/3rdparty/.classpath index d18316afc..2068e34f3 100644 --- a/services/organization/3rdparty/.classpath +++ b/services/organization/3rdparty/.classpath @@ -1,5 +1,5 @@ - - - - - + + + + + diff --git a/services/organization/3rdparty/.project b/services/organization/3rdparty/.project index ac15649ed..831bc1666 100644 --- a/services/organization/3rdparty/.project +++ b/services/organization/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.organization.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.organization.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/organization/3rdparty/build.xml b/services/organization/3rdparty/build.xml index c1727ddce..e4b252023 100644 --- a/services/organization/3rdparty/build.xml +++ b/services/organization/3rdparty/build.xml @@ -1,135 +1,135 @@ - - - - organization service 3rdparty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + organization service 3rdparty + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/organization/3rdparty/pom.xml b/services/organization/3rdparty/pom.xml index 8aec1961f..e99aedf0d 100644 --- a/services/organization/3rdparty/pom.xml +++ b/services/organization/3rdparty/pom.xml @@ -1,23 +1,23 @@ - - - org.collectionspace.services - org.collectionspace.services.organization - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.organization.3rdparty - services.organization.3rdparty - pom - - 3rd party build for organization service - - - - - - + + + org.collectionspace.services + org.collectionspace.services.organization + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.organization.3rdparty + services.organization.3rdparty + pom + + 3rd party build for organization service + + + + + + diff --git a/services/organization/build.xml b/services/organization/build.xml index 85c3189a0..332535624 100644 --- a/services/organization/build.xml +++ b/services/organization/build.xml @@ -1,132 +1,132 @@ - - - - organization service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + organization service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/organization/client/pom.xml b/services/organization/client/pom.xml index b07cfadd7..5b3c2e32b 100644 --- a/services/organization/client/pom.xml +++ b/services/organization/client/pom.xml @@ -1,90 +1,90 @@ - - - - org.collectionspace.services - org.collectionspace.services.organization - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.organization.client - services.organization.client - - - - - org.slf4j - slf4j-api - provided - - - org.slf4j - slf4j-log4j12 - provided - - - - org.collectionspace.services - org.collectionspace.services.organization.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.common - true - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.contact.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.person.client - ${project.version} - - - - org.testng - testng - - - org.jboss.resteasy - resteasy-jaxrs - - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - commons-httpclient - commons-httpclient - 3.1 - - - - - collectionspace-services-organization-client - - - + + + + org.collectionspace.services + org.collectionspace.services.organization + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.organization.client + services.organization.client + + + + + org.slf4j + slf4j-api + provided + + + org.slf4j + slf4j-log4j12 + provided + + + + org.collectionspace.services + org.collectionspace.services.organization.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.common + true + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.contact.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.person.client + ${project.version} + + + + org.testng + testng + + + org.jboss.resteasy + resteasy-jaxrs + + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + commons-httpclient + commons-httpclient + 3.1 + + + + + collectionspace-services-organization-client + + + diff --git a/services/organization/client/src/main/java/org/collectionspace/services/client/OrgAuthorityClientUtils.java b/services/organization/client/src/main/java/org/collectionspace/services/client/OrgAuthorityClientUtils.java index 4d6b203e4..e07bbed73 100644 --- a/services/organization/client/src/main/java/org/collectionspace/services/client/OrgAuthorityClientUtils.java +++ b/services/organization/client/src/main/java/org/collectionspace/services/client/OrgAuthorityClientUtils.java @@ -1,416 +1,416 @@ -/** - * 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, 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 - */ -package org.collectionspace.services.client; - -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import org.collectionspace.services.OrganizationJAXBSchema; -import org.collectionspace.services.client.test.ServiceRequestType; -import org.collectionspace.services.common.api.Tools; -import org.collectionspace.services.organization.ContactNameList; -import org.collectionspace.services.organization.FunctionList; -import org.collectionspace.services.organization.GroupList; -import org.collectionspace.services.organization.HistoryNoteList; -import org.collectionspace.services.organization.OrganizationsCommon; -import org.collectionspace.services.organization.OrgauthoritiesCommon; -import org.collectionspace.services.organization.OrgTermGroup; -import org.collectionspace.services.organization.OrgTermGroupList; -import org.jboss.resteasy.client.ClientResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.collectionspace.services.organization.StructuredDateGroup; - -/** - * OrgAuthorityClientUtils. - */ -public class OrgAuthorityClientUtils { - - /** The Constant logger. */ - private static final Logger logger = - LoggerFactory.getLogger(OrgAuthorityClientUtils.class); - private static final ServiceRequestType READ_REQ = ServiceRequestType.READ; - - /** - * @param csid the id of the OrgAuthority - * @param client if null, creates a new client - * @return - */ - public static String getAuthorityRefName(String csid, OrgAuthorityClient client){ - if(client==null) - client = new OrgAuthorityClient(); - ClientResponse res = client.read(csid); - try { - int statusCode = res.getStatus(); - if(!READ_REQ.isValidStatusCode(statusCode) - ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) { - throw new RuntimeException("Invalid status code returned: "+statusCode); - } - //FIXME: remove the following try catch once Aron fixes signatures - try { - PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); - OrgauthoritiesCommon orgAuthority = - (OrgauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input, - client.getCommonPartName(), OrgauthoritiesCommon.class); - if(orgAuthority==null) { - throw new RuntimeException("Null orgAuthority returned from service."); - } - return orgAuthority.getRefName(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } finally { - res.releaseConnection(); - } - } - - /** - * @param inAuthority the ID of the parent OrgAuthority - * @param csid the ID of the Organization - * @param client if null, creates a new client - * @return - */ - public static String getOrgRefName(String inAuthority, String csid, OrgAuthorityClient client){ - if(client==null) - client = new OrgAuthorityClient(); - ClientResponse res = client.readItem(inAuthority, csid); - try { - int statusCode = res.getStatus(); - if(!READ_REQ.isValidStatusCode(statusCode) - ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) { - throw new RuntimeException("Invalid status code returned: "+statusCode); - } - //FIXME: remove the following try catch once Aron fixes signatures - try { - PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); - OrganizationsCommon org = - (OrganizationsCommon) CollectionSpaceClientUtils.extractPart(input, - client.getItemCommonPartName(), OrganizationsCommon.class); - if(org==null) { - throw new RuntimeException("Null Organization returned from service."); - } - return org.getRefName(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } finally { - res.releaseConnection(); - } - } - - /** - * Creates the org authority instance. - * - * @param displayName the display name - * @param shortIdentifier the short Id - * @param headerLabel the header label - * @return the multipart output - */ - public static PoxPayloadOut createOrgAuthorityInstance( - String displayName, String shortIdentifier, String headerLabel ) { - OrgauthoritiesCommon orgAuthority = new OrgauthoritiesCommon(); - orgAuthority.setDisplayName(displayName); - orgAuthority.setShortIdentifier(shortIdentifier); - //String refName = createOrgAuthRefName(shortIdentifier, displayName); - //orgAuthority.setRefName(refName); - orgAuthority.setVocabType("OrgAuthority"); - PoxPayloadOut multipart = new PoxPayloadOut(OrgAuthorityClient.SERVICE_PAYLOAD_NAME); - PayloadOutputPart commonPart = multipart.addPart(orgAuthority, MediaType.APPLICATION_XML_TYPE); - commonPart.setLabel(headerLabel); - - if(logger.isDebugEnabled()){ - logger.debug("to be created, orgAuthority common ", - orgAuthority, OrgauthoritiesCommon.class); - } - - return multipart; - } - - /** - * Creates the item in authority. - * - * @param inAuthority the owning authority - * @param orgAuthorityRefName the owning Authority ref name - * @param orgInfo the org info. OrganizationJAXBSchema.SHORT_IDENTIFIER is REQUIRED. - * @param client the client - * @return the string - */ - public static String createItemInAuthority( String inAuthority, - String orgAuthorityRefName, Map orgInfo, List terms, - Map> orgRepeatablesInfo, OrgAuthorityClient client) { - // Expected status code: 201 Created - int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; - - String displayName = ""; - if ((terms !=null) && (! terms.isEmpty())) { - displayName = terms.get(0).getTermDisplayName(); - } - - if(logger.isDebugEnabled()){ - logger.debug("Import: Create Item: \""+displayName - +"\" in orgAuthority: \"" + orgAuthorityRefName +"\""); - } - PoxPayloadOut multipart = - createOrganizationInstance(orgAuthorityRefName, - orgInfo, terms, orgRepeatablesInfo, client.getItemCommonPartName()); - - ClientResponse res = client.createItem(inAuthority, multipart); - String result; - try { - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not create Item: \""+orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER) - +"\" in orgAuthority: \"" + orgAuthorityRefName - +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when creating Item: \""+ orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER) - +"\" in orgAuthority: \"" + orgAuthorityRefName +"\", Status:"+ statusCode); - } - - result = extractId(res); - } finally { - res.releaseConnection(); - } - - return result; - } - - /** - * Creates the organization instance. - * - * @param orgAuthRefName the owning Authority ref name - * @param orgInfo the org info - * @param headerLabel the header label - * @return the multipart output - */ - public static PoxPayloadOut createOrganizationInstance( - String orgAuthRefName, - Map orgInfo, - List terms, - String headerLabel) { - final Map> EMPTY_ORG_REPEATABLES_INFO = new HashMap>(); - return createOrganizationInstance(orgAuthRefName, orgInfo, terms, - EMPTY_ORG_REPEATABLES_INFO, headerLabel); - } - - /** - * Creates the organization instance. - * - * @param orgAuthRefName the owning Authority ref name - * @param orgInfo the org info - * @param orgRepeatablesInfo names and values of repeatable scalar - * fields in the Organization record - * @param headerLabel the header label - * @return the multipart output - */ - public static PoxPayloadOut createOrganizationInstance( - String orgAuthRefName, Map orgInfo, List terms, - Map> orgRepeatablesInfo, String headerLabel){ - OrganizationsCommon organization = new OrganizationsCommon(); - String shortId = orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER); - if (shortId == null || shortId.isEmpty()) { - throw new IllegalArgumentException("shortIdentifier cannot be null or empty"); - } - organization.setShortIdentifier(shortId); - String value = null; - List values = null; - - // Set values in the Term Information Group - OrgTermGroupList termList = new OrgTermGroupList(); - if (terms == null || terms.isEmpty()) { - terms = getTermGroupInstance(getGeneratedIdentifier()); - } - termList.getOrgTermGroup().addAll(terms); - organization.setOrgTermGroupList(termList); - - if((values = (List)orgRepeatablesInfo.get(OrganizationJAXBSchema.CONTACT_NAMES))!=null) { - ContactNameList contactsList = new ContactNameList(); - List contactNames = contactsList.getContactName(); - contactNames.addAll(values); - organization.setContactNames(contactsList); - } - if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_DATE))!=null) { - StructuredDateGroup foundingDate = new StructuredDateGroup(); - foundingDate.setDateDisplayDate(value); - organization.setFoundingDateGroup(foundingDate); - } - if((value = (String)orgInfo.get(OrganizationJAXBSchema.DISSOLUTION_DATE))!=null) { - StructuredDateGroup dissolutionDate = new StructuredDateGroup(); - dissolutionDate.setDateDisplayDate(value); - organization.setDissolutionDateGroup(dissolutionDate); - } - if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_PLACE))!=null) - organization.setFoundingPlace(value); - if((values = (List)orgRepeatablesInfo.get(OrganizationJAXBSchema.GROUPS))!=null) { - GroupList groupsList = new GroupList(); - List groups = groupsList.getGroup(); - groups.addAll(values); - organization.setGroups(groupsList); - } - if((values = (List)orgRepeatablesInfo.get(OrganizationJAXBSchema.FUNCTIONS))!=null) { - FunctionList functionsList = new FunctionList(); - List functions = functionsList.getFunction(); - functions.addAll(values); - organization.setFunctions(functionsList); - } - if((values = (List)orgRepeatablesInfo.get(OrganizationJAXBSchema.HISTORY_NOTES))!=null) { - HistoryNoteList historyNotesList = new HistoryNoteList(); - List historyNotes = historyNotesList.getHistoryNote(); - historyNotes.addAll(values); - organization.setHistoryNotes(historyNotesList); - } - - PoxPayloadOut multipart = new PoxPayloadOut(OrgAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME); - PayloadOutputPart commonPart = multipart.addPart(organization, - MediaType.APPLICATION_XML_TYPE); - commonPart.setLabel(headerLabel); - - if(logger.isDebugEnabled()){ - logger.debug("to be created, organization common ", organization, OrganizationsCommon.class); - } - - return multipart; - } - - /** - * Returns an error message indicating that the status code returned by a - * specific call to a service does not fall within a set of valid status - * codes for that service. - * - * @param serviceRequestType A type of service request (e.g. CREATE, DELETE). - * - * @param statusCode The invalid status code that was returned in the response, - * from submitting that type of request to the service. - * - * @return An error message. - */ - public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) { - return "Status code '" + statusCode + "' in response is NOT within the expected set: " + - requestType.validStatusCodesAsString(); - } - - /** - * Extract id. - * - * @param res the res - * @return the string - */ - public static String extractId(ClientResponse res) { - MultivaluedMap mvm = res.getMetadata(); - String uri = (String) ((ArrayList) mvm.get("Location")).get(0); - if(logger.isDebugEnabled()){ - logger.info("extractId:uri=" + uri); - } - String[] segments = uri.split("/"); - String id = segments[segments.length - 1]; - if(logger.isDebugEnabled()){ - logger.debug("id=" + id); - } - return id; - } - - /** - * Creates the org auth ref name. - * - * @param shortId the orgAuthority shortIdentifier - * @param displaySuffix displayName to be appended, if non-null - * @return the string - */ - /* - public static String createOrgAuthRefName(String shortId, String displaySuffix) { - String refName = "urn:cspace:org.collectionspace.demo:orgauthority:name(" - +shortId+")"; - if(displaySuffix!=null&&!displaySuffix.isEmpty()) - refName += "'"+displaySuffix+"'"; - return refName; - } - */ - - /** - * Creates the organization ref name. - * - * @param orgAuthRefName the org auth ref name - * @param shortId the person shortIdentifier - * @param displaySuffix displayName to be appended, if non-null - * @return the string - */ - /* - public static String createOrganizationRefName( - String orgAuthRefName, String shortId, String displaySuffix) { - String refName = orgAuthRefName+":organization:name("+shortId+")"; - if(displaySuffix!=null&&!displaySuffix.isEmpty()) - refName += "'"+displaySuffix+"'"; - return refName; - } - */ - - /** - * Produces a default displayName from the basic name and foundingPlace fields. - * @see OrgAuthorityDocumentModelHandler.prepareDefaultDisplayName() which - * duplicates this logic, until we define a service-general utils package - * that is neither client nor service specific. - * @param shortName - * @param foundingPlace - * @return - * @throws Exception - */ - public static String prepareDefaultDisplayName( - String shortName, String foundingPlace ) { - StringBuilder newStr = new StringBuilder(); - final String sep = " "; - boolean firstAdded = false; - if(null != shortName ) { - newStr.append(shortName); - firstAdded = true; - } - // Now we add the place - if(null != foundingPlace ) { - if(firstAdded) { - newStr.append(sep); - } - newStr.append(foundingPlace); - } - return newStr.toString(); - } - - public static List getTermGroupInstance(String identifier) { - if (Tools.isBlank(identifier)) { - identifier = getGeneratedIdentifier(); - } - List terms = new ArrayList(); - OrgTermGroup term = new OrgTermGroup(); - term.setTermDisplayName(identifier); - term.setTermName(identifier); - terms.add(term); - return terms; - } - - private static String getGeneratedIdentifier() { - return "id" + new Date().getTime(); - } - -} +/** + * 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, 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 + */ +package org.collectionspace.services.client; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import org.collectionspace.services.OrganizationJAXBSchema; +import org.collectionspace.services.client.test.ServiceRequestType; +import org.collectionspace.services.common.api.Tools; +import org.collectionspace.services.organization.ContactNameList; +import org.collectionspace.services.organization.FunctionList; +import org.collectionspace.services.organization.GroupList; +import org.collectionspace.services.organization.HistoryNoteList; +import org.collectionspace.services.organization.OrganizationsCommon; +import org.collectionspace.services.organization.OrgauthoritiesCommon; +import org.collectionspace.services.organization.OrgTermGroup; +import org.collectionspace.services.organization.OrgTermGroupList; +import org.jboss.resteasy.client.ClientResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.collectionspace.services.organization.StructuredDateGroup; + +/** + * OrgAuthorityClientUtils. + */ +public class OrgAuthorityClientUtils { + + /** The Constant logger. */ + private static final Logger logger = + LoggerFactory.getLogger(OrgAuthorityClientUtils.class); + private static final ServiceRequestType READ_REQ = ServiceRequestType.READ; + + /** + * @param csid the id of the OrgAuthority + * @param client if null, creates a new client + * @return + */ + public static String getAuthorityRefName(String csid, OrgAuthorityClient client){ + if(client==null) + client = new OrgAuthorityClient(); + ClientResponse res = client.read(csid); + try { + int statusCode = res.getStatus(); + if(!READ_REQ.isValidStatusCode(statusCode) + ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) { + throw new RuntimeException("Invalid status code returned: "+statusCode); + } + //FIXME: remove the following try catch once Aron fixes signatures + try { + PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); + OrgauthoritiesCommon orgAuthority = + (OrgauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input, + client.getCommonPartName(), OrgauthoritiesCommon.class); + if(orgAuthority==null) { + throw new RuntimeException("Null orgAuthority returned from service."); + } + return orgAuthority.getRefName(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } finally { + res.releaseConnection(); + } + } + + /** + * @param inAuthority the ID of the parent OrgAuthority + * @param csid the ID of the Organization + * @param client if null, creates a new client + * @return + */ + public static String getOrgRefName(String inAuthority, String csid, OrgAuthorityClient client){ + if(client==null) + client = new OrgAuthorityClient(); + ClientResponse res = client.readItem(inAuthority, csid); + try { + int statusCode = res.getStatus(); + if(!READ_REQ.isValidStatusCode(statusCode) + ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) { + throw new RuntimeException("Invalid status code returned: "+statusCode); + } + //FIXME: remove the following try catch once Aron fixes signatures + try { + PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); + OrganizationsCommon org = + (OrganizationsCommon) CollectionSpaceClientUtils.extractPart(input, + client.getItemCommonPartName(), OrganizationsCommon.class); + if(org==null) { + throw new RuntimeException("Null Organization returned from service."); + } + return org.getRefName(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } finally { + res.releaseConnection(); + } + } + + /** + * Creates the org authority instance. + * + * @param displayName the display name + * @param shortIdentifier the short Id + * @param headerLabel the header label + * @return the multipart output + */ + public static PoxPayloadOut createOrgAuthorityInstance( + String displayName, String shortIdentifier, String headerLabel ) { + OrgauthoritiesCommon orgAuthority = new OrgauthoritiesCommon(); + orgAuthority.setDisplayName(displayName); + orgAuthority.setShortIdentifier(shortIdentifier); + //String refName = createOrgAuthRefName(shortIdentifier, displayName); + //orgAuthority.setRefName(refName); + orgAuthority.setVocabType("OrgAuthority"); + PoxPayloadOut multipart = new PoxPayloadOut(OrgAuthorityClient.SERVICE_PAYLOAD_NAME); + PayloadOutputPart commonPart = multipart.addPart(orgAuthority, MediaType.APPLICATION_XML_TYPE); + commonPart.setLabel(headerLabel); + + if(logger.isDebugEnabled()){ + logger.debug("to be created, orgAuthority common ", + orgAuthority, OrgauthoritiesCommon.class); + } + + return multipart; + } + + /** + * Creates the item in authority. + * + * @param inAuthority the owning authority + * @param orgAuthorityRefName the owning Authority ref name + * @param orgInfo the org info. OrganizationJAXBSchema.SHORT_IDENTIFIER is REQUIRED. + * @param client the client + * @return the string + */ + public static String createItemInAuthority( String inAuthority, + String orgAuthorityRefName, Map orgInfo, List terms, + Map> orgRepeatablesInfo, OrgAuthorityClient client) { + // Expected status code: 201 Created + int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; + + String displayName = ""; + if ((terms !=null) && (! terms.isEmpty())) { + displayName = terms.get(0).getTermDisplayName(); + } + + if(logger.isDebugEnabled()){ + logger.debug("Import: Create Item: \""+displayName + +"\" in orgAuthority: \"" + orgAuthorityRefName +"\""); + } + PoxPayloadOut multipart = + createOrganizationInstance(orgAuthorityRefName, + orgInfo, terms, orgRepeatablesInfo, client.getItemCommonPartName()); + + ClientResponse res = client.createItem(inAuthority, multipart); + String result; + try { + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not create Item: \""+orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER) + +"\" in orgAuthority: \"" + orgAuthorityRefName + +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when creating Item: \""+ orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER) + +"\" in orgAuthority: \"" + orgAuthorityRefName +"\", Status:"+ statusCode); + } + + result = extractId(res); + } finally { + res.releaseConnection(); + } + + return result; + } + + /** + * Creates the organization instance. + * + * @param orgAuthRefName the owning Authority ref name + * @param orgInfo the org info + * @param headerLabel the header label + * @return the multipart output + */ + public static PoxPayloadOut createOrganizationInstance( + String orgAuthRefName, + Map orgInfo, + List terms, + String headerLabel) { + final Map> EMPTY_ORG_REPEATABLES_INFO = new HashMap>(); + return createOrganizationInstance(orgAuthRefName, orgInfo, terms, + EMPTY_ORG_REPEATABLES_INFO, headerLabel); + } + + /** + * Creates the organization instance. + * + * @param orgAuthRefName the owning Authority ref name + * @param orgInfo the org info + * @param orgRepeatablesInfo names and values of repeatable scalar + * fields in the Organization record + * @param headerLabel the header label + * @return the multipart output + */ + public static PoxPayloadOut createOrganizationInstance( + String orgAuthRefName, Map orgInfo, List terms, + Map> orgRepeatablesInfo, String headerLabel){ + OrganizationsCommon organization = new OrganizationsCommon(); + String shortId = orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER); + if (shortId == null || shortId.isEmpty()) { + throw new IllegalArgumentException("shortIdentifier cannot be null or empty"); + } + organization.setShortIdentifier(shortId); + String value = null; + List values = null; + + // Set values in the Term Information Group + OrgTermGroupList termList = new OrgTermGroupList(); + if (terms == null || terms.isEmpty()) { + terms = getTermGroupInstance(getGeneratedIdentifier()); + } + termList.getOrgTermGroup().addAll(terms); + organization.setOrgTermGroupList(termList); + + if((values = (List)orgRepeatablesInfo.get(OrganizationJAXBSchema.CONTACT_NAMES))!=null) { + ContactNameList contactsList = new ContactNameList(); + List contactNames = contactsList.getContactName(); + contactNames.addAll(values); + organization.setContactNames(contactsList); + } + if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_DATE))!=null) { + StructuredDateGroup foundingDate = new StructuredDateGroup(); + foundingDate.setDateDisplayDate(value); + organization.setFoundingDateGroup(foundingDate); + } + if((value = (String)orgInfo.get(OrganizationJAXBSchema.DISSOLUTION_DATE))!=null) { + StructuredDateGroup dissolutionDate = new StructuredDateGroup(); + dissolutionDate.setDateDisplayDate(value); + organization.setDissolutionDateGroup(dissolutionDate); + } + if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_PLACE))!=null) + organization.setFoundingPlace(value); + if((values = (List)orgRepeatablesInfo.get(OrganizationJAXBSchema.GROUPS))!=null) { + GroupList groupsList = new GroupList(); + List groups = groupsList.getGroup(); + groups.addAll(values); + organization.setGroups(groupsList); + } + if((values = (List)orgRepeatablesInfo.get(OrganizationJAXBSchema.FUNCTIONS))!=null) { + FunctionList functionsList = new FunctionList(); + List functions = functionsList.getFunction(); + functions.addAll(values); + organization.setFunctions(functionsList); + } + if((values = (List)orgRepeatablesInfo.get(OrganizationJAXBSchema.HISTORY_NOTES))!=null) { + HistoryNoteList historyNotesList = new HistoryNoteList(); + List historyNotes = historyNotesList.getHistoryNote(); + historyNotes.addAll(values); + organization.setHistoryNotes(historyNotesList); + } + + PoxPayloadOut multipart = new PoxPayloadOut(OrgAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME); + PayloadOutputPart commonPart = multipart.addPart(organization, + MediaType.APPLICATION_XML_TYPE); + commonPart.setLabel(headerLabel); + + if(logger.isDebugEnabled()){ + logger.debug("to be created, organization common ", organization, OrganizationsCommon.class); + } + + return multipart; + } + + /** + * Returns an error message indicating that the status code returned by a + * specific call to a service does not fall within a set of valid status + * codes for that service. + * + * @param serviceRequestType A type of service request (e.g. CREATE, DELETE). + * + * @param statusCode The invalid status code that was returned in the response, + * from submitting that type of request to the service. + * + * @return An error message. + */ + public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) { + return "Status code '" + statusCode + "' in response is NOT within the expected set: " + + requestType.validStatusCodesAsString(); + } + + /** + * Extract id. + * + * @param res the res + * @return the string + */ + public static String extractId(ClientResponse res) { + MultivaluedMap mvm = res.getMetadata(); + String uri = (String) ((ArrayList) mvm.get("Location")).get(0); + if(logger.isDebugEnabled()){ + logger.info("extractId:uri=" + uri); + } + String[] segments = uri.split("/"); + String id = segments[segments.length - 1]; + if(logger.isDebugEnabled()){ + logger.debug("id=" + id); + } + return id; + } + + /** + * Creates the org auth ref name. + * + * @param shortId the orgAuthority shortIdentifier + * @param displaySuffix displayName to be appended, if non-null + * @return the string + */ + /* + public static String createOrgAuthRefName(String shortId, String displaySuffix) { + String refName = "urn:cspace:org.collectionspace.demo:orgauthority:name(" + +shortId+")"; + if(displaySuffix!=null&&!displaySuffix.isEmpty()) + refName += "'"+displaySuffix+"'"; + return refName; + } + */ + + /** + * Creates the organization ref name. + * + * @param orgAuthRefName the org auth ref name + * @param shortId the person shortIdentifier + * @param displaySuffix displayName to be appended, if non-null + * @return the string + */ + /* + public static String createOrganizationRefName( + String orgAuthRefName, String shortId, String displaySuffix) { + String refName = orgAuthRefName+":organization:name("+shortId+")"; + if(displaySuffix!=null&&!displaySuffix.isEmpty()) + refName += "'"+displaySuffix+"'"; + return refName; + } + */ + + /** + * Produces a default displayName from the basic name and foundingPlace fields. + * @see OrgAuthorityDocumentModelHandler.prepareDefaultDisplayName() which + * duplicates this logic, until we define a service-general utils package + * that is neither client nor service specific. + * @param shortName + * @param foundingPlace + * @return + * @throws Exception + */ + public static String prepareDefaultDisplayName( + String shortName, String foundingPlace ) { + StringBuilder newStr = new StringBuilder(); + final String sep = " "; + boolean firstAdded = false; + if(null != shortName ) { + newStr.append(shortName); + firstAdded = true; + } + // Now we add the place + if(null != foundingPlace ) { + if(firstAdded) { + newStr.append(sep); + } + newStr.append(foundingPlace); + } + return newStr.toString(); + } + + public static List getTermGroupInstance(String identifier) { + if (Tools.isBlank(identifier)) { + identifier = getGeneratedIdentifier(); + } + List terms = new ArrayList(); + OrgTermGroup term = new OrgTermGroup(); + term.setTermDisplayName(identifier); + term.setTermName(identifier); + terms.add(term); + return terms; + } + + private static String getGeneratedIdentifier() { + return "id" + new Date().getTime(); + } + +} diff --git a/services/organization/client/src/test/resources/log4j.properties b/services/organization/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/organization/client/src/test/resources/log4j.properties +++ b/services/organization/client/src/test/resources/log4j.properties @@ -1,23 +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 +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/organization/installer/build.xml b/services/organization/installer/build.xml index fbd862e93..ee115a6b0 100644 --- a/services/organization/installer/build.xml +++ b/services/organization/installer/build.xml @@ -1,61 +1,61 @@ - - - - organization service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + organization service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/organization/jaxb/src/main/java/org/collectionspace/services/OrganizationJAXBSchema.java b/services/organization/jaxb/src/main/java/org/collectionspace/services/OrganizationJAXBSchema.java index 80e070aa6..2607d9d30 100644 --- a/services/organization/jaxb/src/main/java/org/collectionspace/services/OrganizationJAXBSchema.java +++ b/services/organization/jaxb/src/main/java/org/collectionspace/services/OrganizationJAXBSchema.java @@ -1,26 +1,26 @@ -/** - * - */ -package org.collectionspace.services; - -import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema; - -/** - * @author pschmitz - * - */ -public interface OrganizationJAXBSchema extends AuthorityItemJAXBSchema { - - final static String ORGANIZATIONS_COMMON = "organizations_common"; - final static String TERM_NAME = "shortName"; - final static String NAME_ADDITIONS = "nameAdditions"; - final static String CONTACT_NAMES = "contactNames"; - final static String FOUNDING_DATE = "foundingDate"; - final static String DISSOLUTION_DATE = "dissolutionDate"; - final static String FOUNDING_PLACE = "foundingPlace"; - final static String GROUPS = "groups"; - final static String FUNCTIONS = "functions"; - final static String HISTORY_NOTES = "historyNotes"; -} - - +/** + * + */ +package org.collectionspace.services; + +import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema; + +/** + * @author pschmitz + * + */ +public interface OrganizationJAXBSchema extends AuthorityItemJAXBSchema { + + final static String ORGANIZATIONS_COMMON = "organizations_common"; + final static String TERM_NAME = "shortName"; + final static String NAME_ADDITIONS = "nameAdditions"; + final static String CONTACT_NAMES = "contactNames"; + final static String FOUNDING_DATE = "foundingDate"; + final static String DISSOLUTION_DATE = "dissolutionDate"; + final static String FOUNDING_PLACE = "foundingPlace"; + final static String GROUPS = "groups"; + final static String FUNCTIONS = "functions"; + final static String HISTORY_NOTES = "historyNotes"; +} + + diff --git a/services/organization/pom.xml b/services/organization/pom.xml index 3c47e6126..46e47c306 100644 --- a/services/organization/pom.xml +++ b/services/organization/pom.xml @@ -1,43 +1,43 @@ - - - - org.collectionspace.services - org.collectionspace.services.main - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.organization - services.organization - pom - - - - - - - jaxb - service - 3rdparty - client - - - - - samples - - sample - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.main + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.organization + services.organization + pom + + + + + + + jaxb + service + 3rdparty + client + + + + + samples + + sample + + + + + + diff --git a/services/organization/sample/.classpath b/services/organization/sample/.classpath index ad5c57cd5..e526a4712 100644 --- a/services/organization/sample/.classpath +++ b/services/organization/sample/.classpath @@ -1,5 +1,5 @@ - - - - - + + + + + diff --git a/services/organization/sample/.project b/services/organization/sample/.project index a04f35d0c..cc557058c 100644 --- a/services/organization/sample/.project +++ b/services/organization/sample/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.organization.client.samples - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.organization.client.samples + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/organization/sample/pom.xml b/services/organization/sample/pom.xml index de701bc09..1f0c71fd0 100644 --- a/services/organization/sample/pom.xml +++ b/services/organization/sample/pom.xml @@ -1,14 +1,14 @@ - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.organization.client.samples - pom - 4.2-SNAPSHOT - organization.client.samples - - - sample - - - + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.organization.client.samples + pom + 4.2-SNAPSHOT + organization.client.samples + + + sample + + + diff --git a/services/organization/sample/sample/.project b/services/organization/sample/sample/.project index d6d4cf76e..b7fd28fa8 100644 --- a/services/organization/sample/sample/.project +++ b/services/organization/sample/sample/.project @@ -1,23 +1,23 @@ - - - org.collectionspace.services.organization.client.sample - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.organization.client.sample + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/organization/sample/sample/pom.xml b/services/organization/sample/sample/pom.xml index 8d378f3f1..7e0553ca5 100644 --- a/services/organization/sample/sample/pom.xml +++ b/services/organization/sample/sample/pom.xml @@ -1,112 +1,112 @@ - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.organization.client.sample - jar - 4.2-SNAPSHOT - organization.client.sample - - - - org.collectionspace.services - org.collectionspace.services.organization.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.organization.client - ${project.version} - - - - - - libs-releases-local - libs-releases-local - http://nightly.collectionspace.org:8081/artifactory/libs-release-local - - true - - - false - - - - - libs-snapshots-local - libs-snapshots-local - http://nightly.collectionspace.org:8081/artifactory/libs-snapshot-local - - false - - - true - - - - collectionspace-releases - collectionspace-releases - http://nightly.collectionspace.org:8081/artifactory/nuxeo-public - - true - - - false - - - - nuxeo-public-snapshot - nuxeo-public-snapshot - http://nightly.collectionspace.org:8081/artifactory/nuxeo-public-snapshot - - false - - - true - - - - - - organization-client-sample - - - org.apache.maven.plugins - maven-assembly-plugin - - - - attached - - package - - - jar-with-dependencies - - - - org.collectionspace.services.organization.client.sample.Sample - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.7 - 1.7 - - - - - - + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.organization.client.sample + jar + 4.2-SNAPSHOT + organization.client.sample + + + + org.collectionspace.services + org.collectionspace.services.organization.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.organization.client + ${project.version} + + + + + + libs-releases-local + libs-releases-local + http://nightly.collectionspace.org:8081/artifactory/libs-release-local + + true + + + false + + + + + libs-snapshots-local + libs-snapshots-local + http://nightly.collectionspace.org:8081/artifactory/libs-snapshot-local + + false + + + true + + + + collectionspace-releases + collectionspace-releases + http://nightly.collectionspace.org:8081/artifactory/nuxeo-public + + true + + + false + + + + nuxeo-public-snapshot + nuxeo-public-snapshot + http://nightly.collectionspace.org:8081/artifactory/nuxeo-public-snapshot + + false + + + true + + + + + + organization-client-sample + + + org.apache.maven.plugins + maven-assembly-plugin + + + + attached + + package + + + jar-with-dependencies + + + + org.collectionspace.services.organization.client.sample.Sample + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.7 + 1.7 + + + + + + diff --git a/services/organization/sample/sample/src/main/java/org/collectionspace/services/organization/client/sample/Sample.java b/services/organization/sample/sample/src/main/java/org/collectionspace/services/organization/client/sample/Sample.java index 8667b5b53..5e52df1d9 100644 --- a/services/organization/sample/sample/src/main/java/org/collectionspace/services/organization/client/sample/Sample.java +++ b/services/organization/sample/sample/src/main/java/org/collectionspace/services/organization/client/sample/Sample.java @@ -1,510 +1,510 @@ -/** - * 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 (c)) 2009 Regents of the University of California - * - * 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.organization.client.sample; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; - -import org.apache.log4j.BasicConfigurator; -import org.collectionspace.services.OrganizationJAXBSchema; -import org.collectionspace.services.client.OrgAuthorityClient; -import org.collectionspace.services.client.OrgAuthorityClientUtils; -import org.collectionspace.services.client.PayloadInputPart; -import org.collectionspace.services.client.PoxPayloadIn; -import org.collectionspace.services.client.PoxPayloadOut; -import org.collectionspace.services.client.test.ServiceRequestType; -import org.collectionspace.services.organization.OrgauthoritiesCommon; -import org.collectionspace.services.organization.OrgauthoritiesCommonList; -import org.collectionspace.services.organization.OrganizationsCommon; -import org.collectionspace.services.organization.OrganizationsCommonList; -import org.jboss.resteasy.client.ClientResponse; -import org.jboss.resteasy.plugins.providers.multipart.InputPart; -import org.jboss.resteasy.plugins.providers.multipart.OutputPart; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * OrgAuthority Sample, carries out tests against a - * deployed and running OrgAuthority Service. - * - * $LastChangedRevision: 1055 $ - * $LastChangedDate: 2009-12-09 12:25:15 -0800 (Wed, 09 Dec 2009) $ - */ -public class Sample { - private static final Logger logger = - LoggerFactory.getLogger(Sample.class); - - // Instance variables specific to this test. - private OrgAuthorityClient client = new OrgAuthorityClient(); - final String SERVICE_PATH_COMPONENT = "organizations"; - final String ITEM_SERVICE_PATH_COMPONENT = "items"; - - - // --------------------------------------------------------------- - // Create - // --------------------------------------------------------------- - protected String createOrgAuthRefName(String orgAuthorityName) { - return "urn:cspace:org.collectionspace.demo:orgauthority:name(" - +orgAuthorityName+")"; - } - - protected String createOrganizationRefName( - String orgAuthRefName, String orgName) { - return orgAuthRefName+":organization:name("+orgName+")"; - } - - - - public void createOrgAuthority(String orgAuthName, List> orgInfos ) { - - // Expected status code: 201 Created - int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; - - logger.info("Import: Create orgAuthority: \"" + orgAuthName +"\""); - String baseOrgAuthRefName = createOrgAuthRefName(orgAuthName); - String fullOrgAuthRefName = baseOrgAuthRefName+"'"+orgAuthName+"'"; - PoxPayloadOut multipart = - OrgAuthorityClientUtils.createOrgAuthorityInstance( - orgAuthName, fullOrgAuthRefName, - client.getCommonPartName()); - ClientResponse res = client.create(multipart); - - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not create enumeration: \""+orgAuthName - +"\" "+ OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when creating enumeration: \"" - +orgAuthName +"\", Status:"+ statusCode); - } - - // Store the ID returned from this create operation - // for additional tests below. - String newOrgAuthId = OrgAuthorityClientUtils.extractId(res); - logger.info("Import: Created orgAuthority: \"" + orgAuthName +"\" ID:" - +newOrgAuthId ); - - // Add items to the orgAuthority - for(Map orgInfo : orgInfos){ - createItemInOrgAuth(newOrgAuthId, baseOrgAuthRefName, orgInfo); - } - - } - - private String createItemInOrgAuth(String vcsid, - String orgAuthorityRefName, Map orgInfo) { - // Expected status code: 201 Created - int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; - String shortName = orgInfo.get(OrganizationJAXBSchema.SHORT_NAME); - String refName = createOrganizationRefName( - orgAuthorityRefName, shortName)+"'"+shortName+"'"; - - - logger.info("Import: Create Item: \""+shortName+ - "\" in orgAuthority: \"" + orgAuthorityRefName +"\""); - PoxPayloadOut multipart = - OrgAuthorityClientUtils.createOrganizationInstance(refName, orgInfo, client.getItemCommonPartName() ); - - ClientResponse res = client.createItem(vcsid, multipart); - - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not create Item: \""+shortName - +"\" in orgAuthority: \"" + orgAuthorityRefName - +"\" "+ OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when creating Item: \""+shortName - +"\" in orgAuthority: \"" + orgAuthorityRefName + - "\", Status:"+ statusCode); - } - - return OrgAuthorityClientUtils.extractId(res); - } - - - // --------------------------------------------------------------- - // Read - // --------------------------------------------------------------- - - private OrgauthoritiesCommonList readOrgAuthorities() { - - // Expected status code: 200 OK - int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; - - // Submit the request to the service and store the response. - ClientResponse res = client.readList(); - OrgauthoritiesCommonList list = res.getEntity(); - - int statusCode = res.getStatus(); - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not read list of orgAuthorities: " - + OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when reading " + - "list of orgAuthorities, Status:"+ statusCode); - } - - return list; - } - - private List readOrgAuthorityIds(OrgauthoritiesCommonList list) { - - List ids = new ArrayList(); - List orgAuthorities = - list.getOrgauthorityListItem(); - for (OrgauthoritiesCommonList.OrgauthorityListItem orgAuthority : orgAuthorities) { - ids.add(orgAuthority.getCsid()); - } - return ids; - } - - private OrgauthoritiesCommon readOrgAuthority(String orgAuthId) { - - // Expected status code: 200 OK - int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; - - // Submit the request to the service and store the response. - OrgauthoritiesCommon orgAuthority = null; - try { - ClientResponse res = client.read(orgAuthId); - int statusCode = res.getStatus(); - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not read orgAuthority" - + OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when reading " + - "orgAuthority, Status:"+ statusCode); - } - PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); - PayloadInputPart orgAuthorityPart = input.getPart(client.getCommonPartName()); - orgAuthority = (OrgauthoritiesCommon) orgAuthorityPart.getBody(); - } catch (Exception e) { - throw new RuntimeException("Could not read orgAuthority: ", e); - } - - return orgAuthority; - } - - private OrganizationsCommonList readItemsInOrgAuth(String orgAuthId) { - - // Expected status code: 200 OK - int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; - - // Submit the request to the service and store the response. - - //was: ClientResponse res = client.readItemList(orgAuthId); - //new API: readItemList(String inAuthority, String partialTerm, String keywords) - ClientResponse res = client.readItemList(orgAuthId, "", "");//TODO: .New call, most certainly wrong. Just trying to get this to compile. Laramie20100728 - - OrganizationsCommonList list = res.getEntity(); - - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not read items in orgAuthority: " - + OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when reading " + - "items in orgAuthority, Status:"+ statusCode); - } - - return list; - } - - private List readOrganizationIds(OrganizationsCommonList list) { - - List ids = new ArrayList(); - List items = - list.getOrganizationListItem(); - for (OrganizationsCommonList.OrganizationListItem item : items) { - ids.add(item.getCsid()); - } - return ids; - } - - // --------------------------------------------------------------- - // Delete - // --------------------------------------------------------------- - - private void deleteOrgAuthority(String vcsid) { - // Expected status code: 200 OK - int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE; - - ClientResponse res = client.delete(vcsid); - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not delete orgAuthority: " - + OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when deleting " + - "orgAuthority, Status:"+ statusCode); - } - } - - private void deleteAllOrgAuthorities() { - List ids = readOrgAuthorityIds(readOrgAuthorities()); - for (String id : ids) { - deleteOrgAuthority(id); - } - } - - private void deleteOrganization(String vcsid, String itemcsid) { - // Expected status code: 200 OK - int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE; - - ClientResponse res = client.deleteItem(vcsid, itemcsid); - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not delete orgAuthority item: " - + OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when deleting " + - "orgAuthority item, Status:"+ statusCode); - } - } - - private void deleteAllItemsForOrgAuth(String orgAuthId) { - List itemIds = readOrganizationIds(readItemsInOrgAuth(orgAuthId)); - for (String itemId : itemIds) { - deleteOrganization(orgAuthId, itemId); - } - } - - // --------------------------------------------------------------- - // Utility methods used by tests above - // --------------------------------------------------------------- - - - // Retrieve individual fields of orgAuthority records. - - private String displayAllOrgAuthorities(OrgauthoritiesCommonList list) { - StringBuffer sb = new StringBuffer(); - List orgAuthorities = - list.getOrgauthorityListItem(); - int i = 0; - for (OrgauthoritiesCommonList.OrgauthorityListItem orgAuthority : orgAuthorities) { - sb.append("orgAuthority [" + i + "]" + "\n"); - sb.append(displayOrgAuthorityDetails(orgAuthority)); - i++; - } - return sb.toString(); - } - - private String displayOrgAuthorityDetails( - OrgauthoritiesCommonList.OrgauthorityListItem orgAuthority) { - StringBuffer sb = new StringBuffer(); - sb.append("displayName=" + orgAuthority.getDisplayName() + "\n"); - sb.append("vocabType=" + orgAuthority.getVocabType() + "\n"); - // sb.append("csid=" + orgAuthority.getCsid() + "\n"); - sb.append("URI=" + orgAuthority.getUri() + "\n"); - return sb.toString(); - } - - // Retrieve individual fields of organization records. - - private String displayAllOrganizations(OrganizationsCommonList list) { - StringBuffer sb = new StringBuffer(); - List items = - list.getOrganizationListItem(); - int i = 0; - for (OrganizationsCommonList.OrganizationListItem item : items) { - sb.append("organization [" + i + "]" + "\n"); - sb.append(displayOrganizationDetails(item)); - i++; - } - return sb.toString(); - } - - private String displayOrganizationDetails( - OrganizationsCommonList.OrganizationListItem item) { - StringBuffer sb = new StringBuffer(); - sb.append("csid=" + item.getCsid() + "\n"); - sb.append("displayName=" + item.getDisplayName() + "\n"); - // sb.append("URI=" + item.getUri() + "\n"); - return sb.toString(); - } - -// private Object extractPart(PoxPayloadIn input, String label, -// Class clazz) throws Exception { -// Object obj = null; -// for(PayloadInputPart part : input.getParts()){ -// String partLabel = part.getHeaders().getFirst("label"); -// if(label.equalsIgnoreCase(partLabel)){ -// String partStr = part.getBodyAsString(); -// if(logger.isDebugEnabled()){ -// logger.debug("extracted part str=\n" + partStr); -// } -// obj = part.getBody(clazz, null); -// if(logger.isDebugEnabled()){ -// logger.debug("extracted part obj=\n", obj, clazz); -// } -// break; -// } -// } -// return obj; -// } - - public static void main(String[] args) { - - // Configure logging. - BasicConfigurator.configure(); - - logger.info("OrgAuthority Sample starting..."); - - Sample sample = new Sample(); - OrgauthoritiesCommonList orgAuthorities; - List orgAuthIds; - String details = ""; - - // Optionally delete all orgAuthorities and organizations. - - boolean ENABLE_DELETE_ALL = false; - if (ENABLE_DELETE_ALL) { - - logger.info("Deleting all organizations and orgAuthorities ..."); - - // For each orgAuthority ... - orgAuthorities = sample.readOrgAuthorities(); - orgAuthIds = sample.readOrgAuthorityIds(orgAuthorities); - for (String orgAuthId : orgAuthIds) { - logger.info("Deleting all organizations for orgAuthority ..."); - sample.deleteAllItemsForOrgAuth(orgAuthId); - logger.info("Deleting orgAuthority ..."); - sample.deleteOrgAuthority(orgAuthId); - } - - logger.info("Reading orgAuthorities after deletion ..."); - orgAuthorities = sample.readOrgAuthorities(); - details = sample.displayAllOrgAuthorities(orgAuthorities); - logger.info(details); - - logger.info("Reading items in each orgAuthority after deletion ..."); - orgAuthIds = sample.readOrgAuthorityIds(orgAuthorities); - for (String orgAuthId : orgAuthIds) { - OrganizationsCommonList items = sample.readItemsInOrgAuth(orgAuthId); - details = sample.displayAllOrganizations(items); - logger.info(details); - } - - } - - // Create new authorities, each populated with organizations. - Map mmiOrgMap = new HashMap(); - mmiOrgMap.put(OrganizationJAXBSchema.SHORT_NAME, "MMI"); - mmiOrgMap.put(OrganizationJAXBSchema.LONG_NAME, "Museum of the Moving Image"); - //mmiOrgMap.put(OrganizationJAXBSchema.CONTACT_NAME, "Megan Forbes"); - mmiOrgMap.put(OrganizationJAXBSchema.FOUNDING_DATE, "1984"); - mmiOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Astoria, NY"); - Map pahmaOrgMap = new HashMap(); - pahmaOrgMap.put(OrganizationJAXBSchema.SHORT_NAME, "PAHMA"); - pahmaOrgMap.put(OrganizationJAXBSchema.LONG_NAME, "Phoebe A. Hearst Museum of Anthropology"); - pahmaOrgMap.put(OrganizationJAXBSchema.NAME_ADDITIONS, "University of California, Berkeley"); - //pahmaOrgMap.put(OrganizationJAXBSchema.CONTACT_NAME, "Michael Black"); - pahmaOrgMap.put(OrganizationJAXBSchema.FOUNDING_DATE, "1901"); - pahmaOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Berkeley, CA"); - Map savoyOrgMap = new HashMap(); - savoyOrgMap.put(OrganizationJAXBSchema.SHORT_NAME, "Savoy Theatre"); - savoyOrgMap.put(OrganizationJAXBSchema.FOUNDING_DATE, "1900"); - savoyOrgMap.put(OrganizationJAXBSchema.DISSOLUTION_DATE, "1952"); - savoyOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "New York, NY"); - List> orgMaps = - Arrays.asList(mmiOrgMap, pahmaOrgMap, savoyOrgMap ); - - sample.createOrgAuthority("Sample Org Authority", orgMaps); - - logger.info("OrgAuthority Sample complete."); - - logger.info("Reading orgAuthorities and items ..."); - // Get a list of orgAuthorities. - orgAuthorities = sample.readOrgAuthorities(); - // For each orgAuthority ... - for (OrgauthoritiesCommonList.OrgauthorityListItem - orgAuthority : orgAuthorities.getOrgauthorityListItem()) { - // Get its display name. - logger.info(orgAuthority.getDisplayName()); - // Get a list of the organizations in this orgAuthority. - OrganizationsCommonList items = - sample.readItemsInOrgAuth(orgAuthority.getCsid()); - // For each organization ... - for (OrganizationsCommonList.OrganizationListItem - item : items.getOrganizationListItem()) { - // Get its display name. - logger.info(" " + item.getDisplayName()); - } - } - - // Sample alternate methods of reading all orgAuthorities and - // organizations separately. - boolean RUN_ADDITIONAL_SAMPLES = false; - if (RUN_ADDITIONAL_SAMPLES) { - - logger.info("Reading all orgAuthorities ..."); - details = sample.displayAllOrgAuthorities(orgAuthorities); - logger.info(details); - - logger.info("Reading all organizations ..."); - orgAuthIds = sample.readOrgAuthorityIds(orgAuthorities); - for (String orgAuthId : orgAuthIds) { - OrganizationsCommonList items = sample.readItemsInOrgAuth(orgAuthId); - details = sample.displayAllOrganizations(items); - logger.info(details); - } - - } - - } - -} +/** + * 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 (c)) 2009 Regents of the University of California + * + * 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.organization.client.sample; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; + +import org.apache.log4j.BasicConfigurator; +import org.collectionspace.services.OrganizationJAXBSchema; +import org.collectionspace.services.client.OrgAuthorityClient; +import org.collectionspace.services.client.OrgAuthorityClientUtils; +import org.collectionspace.services.client.PayloadInputPart; +import org.collectionspace.services.client.PoxPayloadIn; +import org.collectionspace.services.client.PoxPayloadOut; +import org.collectionspace.services.client.test.ServiceRequestType; +import org.collectionspace.services.organization.OrgauthoritiesCommon; +import org.collectionspace.services.organization.OrgauthoritiesCommonList; +import org.collectionspace.services.organization.OrganizationsCommon; +import org.collectionspace.services.organization.OrganizationsCommonList; +import org.jboss.resteasy.client.ClientResponse; +import org.jboss.resteasy.plugins.providers.multipart.InputPart; +import org.jboss.resteasy.plugins.providers.multipart.OutputPart; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * OrgAuthority Sample, carries out tests against a + * deployed and running OrgAuthority Service. + * + * $LastChangedRevision: 1055 $ + * $LastChangedDate: 2009-12-09 12:25:15 -0800 (Wed, 09 Dec 2009) $ + */ +public class Sample { + private static final Logger logger = + LoggerFactory.getLogger(Sample.class); + + // Instance variables specific to this test. + private OrgAuthorityClient client = new OrgAuthorityClient(); + final String SERVICE_PATH_COMPONENT = "organizations"; + final String ITEM_SERVICE_PATH_COMPONENT = "items"; + + + // --------------------------------------------------------------- + // Create + // --------------------------------------------------------------- + protected String createOrgAuthRefName(String orgAuthorityName) { + return "urn:cspace:org.collectionspace.demo:orgauthority:name(" + +orgAuthorityName+")"; + } + + protected String createOrganizationRefName( + String orgAuthRefName, String orgName) { + return orgAuthRefName+":organization:name("+orgName+")"; + } + + + + public void createOrgAuthority(String orgAuthName, List> orgInfos ) { + + // Expected status code: 201 Created + int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; + + logger.info("Import: Create orgAuthority: \"" + orgAuthName +"\""); + String baseOrgAuthRefName = createOrgAuthRefName(orgAuthName); + String fullOrgAuthRefName = baseOrgAuthRefName+"'"+orgAuthName+"'"; + PoxPayloadOut multipart = + OrgAuthorityClientUtils.createOrgAuthorityInstance( + orgAuthName, fullOrgAuthRefName, + client.getCommonPartName()); + ClientResponse res = client.create(multipart); + + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not create enumeration: \""+orgAuthName + +"\" "+ OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when creating enumeration: \"" + +orgAuthName +"\", Status:"+ statusCode); + } + + // Store the ID returned from this create operation + // for additional tests below. + String newOrgAuthId = OrgAuthorityClientUtils.extractId(res); + logger.info("Import: Created orgAuthority: \"" + orgAuthName +"\" ID:" + +newOrgAuthId ); + + // Add items to the orgAuthority + for(Map orgInfo : orgInfos){ + createItemInOrgAuth(newOrgAuthId, baseOrgAuthRefName, orgInfo); + } + + } + + private String createItemInOrgAuth(String vcsid, + String orgAuthorityRefName, Map orgInfo) { + // Expected status code: 201 Created + int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; + String shortName = orgInfo.get(OrganizationJAXBSchema.SHORT_NAME); + String refName = createOrganizationRefName( + orgAuthorityRefName, shortName)+"'"+shortName+"'"; + + + logger.info("Import: Create Item: \""+shortName+ + "\" in orgAuthority: \"" + orgAuthorityRefName +"\""); + PoxPayloadOut multipart = + OrgAuthorityClientUtils.createOrganizationInstance(refName, orgInfo, client.getItemCommonPartName() ); + + ClientResponse res = client.createItem(vcsid, multipart); + + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not create Item: \""+shortName + +"\" in orgAuthority: \"" + orgAuthorityRefName + +"\" "+ OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when creating Item: \""+shortName + +"\" in orgAuthority: \"" + orgAuthorityRefName + + "\", Status:"+ statusCode); + } + + return OrgAuthorityClientUtils.extractId(res); + } + + + // --------------------------------------------------------------- + // Read + // --------------------------------------------------------------- + + private OrgauthoritiesCommonList readOrgAuthorities() { + + // Expected status code: 200 OK + int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; + + // Submit the request to the service and store the response. + ClientResponse res = client.readList(); + OrgauthoritiesCommonList list = res.getEntity(); + + int statusCode = res.getStatus(); + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not read list of orgAuthorities: " + + OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when reading " + + "list of orgAuthorities, Status:"+ statusCode); + } + + return list; + } + + private List readOrgAuthorityIds(OrgauthoritiesCommonList list) { + + List ids = new ArrayList(); + List orgAuthorities = + list.getOrgauthorityListItem(); + for (OrgauthoritiesCommonList.OrgauthorityListItem orgAuthority : orgAuthorities) { + ids.add(orgAuthority.getCsid()); + } + return ids; + } + + private OrgauthoritiesCommon readOrgAuthority(String orgAuthId) { + + // Expected status code: 200 OK + int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; + + // Submit the request to the service and store the response. + OrgauthoritiesCommon orgAuthority = null; + try { + ClientResponse res = client.read(orgAuthId); + int statusCode = res.getStatus(); + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not read orgAuthority" + + OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when reading " + + "orgAuthority, Status:"+ statusCode); + } + PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); + PayloadInputPart orgAuthorityPart = input.getPart(client.getCommonPartName()); + orgAuthority = (OrgauthoritiesCommon) orgAuthorityPart.getBody(); + } catch (Exception e) { + throw new RuntimeException("Could not read orgAuthority: ", e); + } + + return orgAuthority; + } + + private OrganizationsCommonList readItemsInOrgAuth(String orgAuthId) { + + // Expected status code: 200 OK + int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; + + // Submit the request to the service and store the response. + + //was: ClientResponse res = client.readItemList(orgAuthId); + //new API: readItemList(String inAuthority, String partialTerm, String keywords) + ClientResponse res = client.readItemList(orgAuthId, "", "");//TODO: .New call, most certainly wrong. Just trying to get this to compile. Laramie20100728 + + OrganizationsCommonList list = res.getEntity(); + + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not read items in orgAuthority: " + + OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when reading " + + "items in orgAuthority, Status:"+ statusCode); + } + + return list; + } + + private List readOrganizationIds(OrganizationsCommonList list) { + + List ids = new ArrayList(); + List items = + list.getOrganizationListItem(); + for (OrganizationsCommonList.OrganizationListItem item : items) { + ids.add(item.getCsid()); + } + return ids; + } + + // --------------------------------------------------------------- + // Delete + // --------------------------------------------------------------- + + private void deleteOrgAuthority(String vcsid) { + // Expected status code: 200 OK + int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE; + + ClientResponse res = client.delete(vcsid); + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not delete orgAuthority: " + + OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when deleting " + + "orgAuthority, Status:"+ statusCode); + } + } + + private void deleteAllOrgAuthorities() { + List ids = readOrgAuthorityIds(readOrgAuthorities()); + for (String id : ids) { + deleteOrgAuthority(id); + } + } + + private void deleteOrganization(String vcsid, String itemcsid) { + // Expected status code: 200 OK + int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE; + + ClientResponse res = client.deleteItem(vcsid, itemcsid); + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not delete orgAuthority item: " + + OrgAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when deleting " + + "orgAuthority item, Status:"+ statusCode); + } + } + + private void deleteAllItemsForOrgAuth(String orgAuthId) { + List itemIds = readOrganizationIds(readItemsInOrgAuth(orgAuthId)); + for (String itemId : itemIds) { + deleteOrganization(orgAuthId, itemId); + } + } + + // --------------------------------------------------------------- + // Utility methods used by tests above + // --------------------------------------------------------------- + + + // Retrieve individual fields of orgAuthority records. + + private String displayAllOrgAuthorities(OrgauthoritiesCommonList list) { + StringBuffer sb = new StringBuffer(); + List orgAuthorities = + list.getOrgauthorityListItem(); + int i = 0; + for (OrgauthoritiesCommonList.OrgauthorityListItem orgAuthority : orgAuthorities) { + sb.append("orgAuthority [" + i + "]" + "\n"); + sb.append(displayOrgAuthorityDetails(orgAuthority)); + i++; + } + return sb.toString(); + } + + private String displayOrgAuthorityDetails( + OrgauthoritiesCommonList.OrgauthorityListItem orgAuthority) { + StringBuffer sb = new StringBuffer(); + sb.append("displayName=" + orgAuthority.getDisplayName() + "\n"); + sb.append("vocabType=" + orgAuthority.getVocabType() + "\n"); + // sb.append("csid=" + orgAuthority.getCsid() + "\n"); + sb.append("URI=" + orgAuthority.getUri() + "\n"); + return sb.toString(); + } + + // Retrieve individual fields of organization records. + + private String displayAllOrganizations(OrganizationsCommonList list) { + StringBuffer sb = new StringBuffer(); + List items = + list.getOrganizationListItem(); + int i = 0; + for (OrganizationsCommonList.OrganizationListItem item : items) { + sb.append("organization [" + i + "]" + "\n"); + sb.append(displayOrganizationDetails(item)); + i++; + } + return sb.toString(); + } + + private String displayOrganizationDetails( + OrganizationsCommonList.OrganizationListItem item) { + StringBuffer sb = new StringBuffer(); + sb.append("csid=" + item.getCsid() + "\n"); + sb.append("displayName=" + item.getDisplayName() + "\n"); + // sb.append("URI=" + item.getUri() + "\n"); + return sb.toString(); + } + +// private Object extractPart(PoxPayloadIn input, String label, +// Class clazz) throws Exception { +// Object obj = null; +// for(PayloadInputPart part : input.getParts()){ +// String partLabel = part.getHeaders().getFirst("label"); +// if(label.equalsIgnoreCase(partLabel)){ +// String partStr = part.getBodyAsString(); +// if(logger.isDebugEnabled()){ +// logger.debug("extracted part str=\n" + partStr); +// } +// obj = part.getBody(clazz, null); +// if(logger.isDebugEnabled()){ +// logger.debug("extracted part obj=\n", obj, clazz); +// } +// break; +// } +// } +// return obj; +// } + + public static void main(String[] args) { + + // Configure logging. + BasicConfigurator.configure(); + + logger.info("OrgAuthority Sample starting..."); + + Sample sample = new Sample(); + OrgauthoritiesCommonList orgAuthorities; + List orgAuthIds; + String details = ""; + + // Optionally delete all orgAuthorities and organizations. + + boolean ENABLE_DELETE_ALL = false; + if (ENABLE_DELETE_ALL) { + + logger.info("Deleting all organizations and orgAuthorities ..."); + + // For each orgAuthority ... + orgAuthorities = sample.readOrgAuthorities(); + orgAuthIds = sample.readOrgAuthorityIds(orgAuthorities); + for (String orgAuthId : orgAuthIds) { + logger.info("Deleting all organizations for orgAuthority ..."); + sample.deleteAllItemsForOrgAuth(orgAuthId); + logger.info("Deleting orgAuthority ..."); + sample.deleteOrgAuthority(orgAuthId); + } + + logger.info("Reading orgAuthorities after deletion ..."); + orgAuthorities = sample.readOrgAuthorities(); + details = sample.displayAllOrgAuthorities(orgAuthorities); + logger.info(details); + + logger.info("Reading items in each orgAuthority after deletion ..."); + orgAuthIds = sample.readOrgAuthorityIds(orgAuthorities); + for (String orgAuthId : orgAuthIds) { + OrganizationsCommonList items = sample.readItemsInOrgAuth(orgAuthId); + details = sample.displayAllOrganizations(items); + logger.info(details); + } + + } + + // Create new authorities, each populated with organizations. + Map mmiOrgMap = new HashMap(); + mmiOrgMap.put(OrganizationJAXBSchema.SHORT_NAME, "MMI"); + mmiOrgMap.put(OrganizationJAXBSchema.LONG_NAME, "Museum of the Moving Image"); + //mmiOrgMap.put(OrganizationJAXBSchema.CONTACT_NAME, "Megan Forbes"); + mmiOrgMap.put(OrganizationJAXBSchema.FOUNDING_DATE, "1984"); + mmiOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Astoria, NY"); + Map pahmaOrgMap = new HashMap(); + pahmaOrgMap.put(OrganizationJAXBSchema.SHORT_NAME, "PAHMA"); + pahmaOrgMap.put(OrganizationJAXBSchema.LONG_NAME, "Phoebe A. Hearst Museum of Anthropology"); + pahmaOrgMap.put(OrganizationJAXBSchema.NAME_ADDITIONS, "University of California, Berkeley"); + //pahmaOrgMap.put(OrganizationJAXBSchema.CONTACT_NAME, "Michael Black"); + pahmaOrgMap.put(OrganizationJAXBSchema.FOUNDING_DATE, "1901"); + pahmaOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "Berkeley, CA"); + Map savoyOrgMap = new HashMap(); + savoyOrgMap.put(OrganizationJAXBSchema.SHORT_NAME, "Savoy Theatre"); + savoyOrgMap.put(OrganizationJAXBSchema.FOUNDING_DATE, "1900"); + savoyOrgMap.put(OrganizationJAXBSchema.DISSOLUTION_DATE, "1952"); + savoyOrgMap.put(OrganizationJAXBSchema.FOUNDING_PLACE, "New York, NY"); + List> orgMaps = + Arrays.asList(mmiOrgMap, pahmaOrgMap, savoyOrgMap ); + + sample.createOrgAuthority("Sample Org Authority", orgMaps); + + logger.info("OrgAuthority Sample complete."); + + logger.info("Reading orgAuthorities and items ..."); + // Get a list of orgAuthorities. + orgAuthorities = sample.readOrgAuthorities(); + // For each orgAuthority ... + for (OrgauthoritiesCommonList.OrgauthorityListItem + orgAuthority : orgAuthorities.getOrgauthorityListItem()) { + // Get its display name. + logger.info(orgAuthority.getDisplayName()); + // Get a list of the organizations in this orgAuthority. + OrganizationsCommonList items = + sample.readItemsInOrgAuth(orgAuthority.getCsid()); + // For each organization ... + for (OrganizationsCommonList.OrganizationListItem + item : items.getOrganizationListItem()) { + // Get its display name. + logger.info(" " + item.getDisplayName()); + } + } + + // Sample alternate methods of reading all orgAuthorities and + // organizations separately. + boolean RUN_ADDITIONAL_SAMPLES = false; + if (RUN_ADDITIONAL_SAMPLES) { + + logger.info("Reading all orgAuthorities ..."); + details = sample.displayAllOrgAuthorities(orgAuthorities); + logger.info(details); + + logger.info("Reading all organizations ..."); + orgAuthIds = sample.readOrgAuthorityIds(orgAuthorities); + for (String orgAuthId : orgAuthIds) { + OrganizationsCommonList items = sample.readItemsInOrgAuth(orgAuthId); + details = sample.displayAllOrganizations(items); + logger.info(details); + } + + } + + } + +} diff --git a/services/organization/sample/sample/src/main/resources/collectionspace-client.properties b/services/organization/sample/sample/src/main/resources/collectionspace-client.properties index 429b9f6fe..927081034 100644 --- a/services/organization/sample/sample/src/main/resources/collectionspace-client.properties +++ b/services/organization/sample/sample/src/main/resources/collectionspace-client.properties @@ -1,6 +1,6 @@ -#url of the collectionspace server -cspace.url=http://localhost:8180/cspace-services/ -cspace.ssl=false -cspace.auth=false -cspace.user=test +#url of the collectionspace server +cspace.url=http://localhost:8180/cspace-services/ +cspace.ssl=false +cspace.auth=false +cspace.user=test cspace.password=test \ No newline at end of file diff --git a/services/organization/sample/sample/src/main/resources/log4j.xml b/services/organization/sample/sample/src/main/resources/log4j.xml index 2e9dd00c1..af20cb489 100644 --- a/services/organization/sample/sample/src/main/resources/log4j.xml +++ b/services/organization/sample/sample/src/main/resources/log4j.xml @@ -1,38 +1,38 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/organization/service/pom.xml b/services/organization/service/pom.xml index 98f05533e..6594fdfca 100644 --- a/services/organization/service/pom.xml +++ b/services/organization/service/pom.xml @@ -1,132 +1,132 @@ - - - - org.collectionspace.services - org.collectionspace.services.organization - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.organization.service - services.organization.service - jar - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - - org.collectionspace.services - org.collectionspace.services.authority.service - true - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.organization.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.organization.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.contact.service - ${project.version} - - - - junit - junit - 4.1 - test - - - org.testng - testng - - - - - commons-beanutils - commons-beanutils - 1.6.1 - - - - commons-logging - commons-logging - 1.1 - - - - - - javax.security - jaas - 1.0.01 - provided - - - - dom4j - dom4j - 1.6.1 - provided - - - - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - - - org.nuxeo.ecm.core - nuxeo-core-api - - - jboss-remoting - jboss - - - - - - - - collectionspace-services-organization - - - + + + + org.collectionspace.services + org.collectionspace.services.organization + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.organization.service + services.organization.service + jar + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + + org.collectionspace.services + org.collectionspace.services.authority.service + true + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.organization.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.organization.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.contact.service + ${project.version} + + + + junit + junit + 4.1 + test + + + org.testng + testng + + + + + commons-beanutils + commons-beanutils + 1.6.1 + + + + commons-logging + commons-logging + 1.1 + + + + + + javax.security + jaas + 1.0.01 + provided + + + + dom4j + dom4j + 1.6.1 + provided + + + + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + + + org.nuxeo.ecm.core + nuxeo-core-api + + + jboss-remoting + jboss + + + + + + + + collectionspace-services-organization + + + diff --git a/services/person/.classpath b/services/person/.classpath index d18316afc..2068e34f3 100644 --- a/services/person/.classpath +++ b/services/person/.classpath @@ -1,5 +1,5 @@ - - - - - + + + + + diff --git a/services/person/.project b/services/person/.project index bcf39ab34..5ab91c75d 100644 --- a/services/person/.project +++ b/services/person/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.person - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.person + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/person/3rdparty/.classpath b/services/person/3rdparty/.classpath index d18316afc..2068e34f3 100644 --- a/services/person/3rdparty/.classpath +++ b/services/person/3rdparty/.classpath @@ -1,5 +1,5 @@ - - - - - + + + + + diff --git a/services/person/3rdparty/.project b/services/person/3rdparty/.project index 6eca3a3f9..9be735986 100644 --- a/services/person/3rdparty/.project +++ b/services/person/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.person.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.person.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/person/3rdparty/build.xml b/services/person/3rdparty/build.xml index 0affac9d8..f54ea8aab 100644 --- a/services/person/3rdparty/build.xml +++ b/services/person/3rdparty/build.xml @@ -1,139 +1,139 @@ - - - - person service 3rdparty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + person service 3rdparty + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/person/3rdparty/pom.xml b/services/person/3rdparty/pom.xml index b0efcd3e0..3c052ad17 100644 --- a/services/person/3rdparty/pom.xml +++ b/services/person/3rdparty/pom.xml @@ -1,25 +1,25 @@ - - - - org.collectionspace.services - org.collectionspace.services.person - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.person.3rdparty - services.person.3rdparty - pom - - 3rd party build for person service - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.person + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.person.3rdparty + services.person.3rdparty + pom + + 3rd party build for person service + + + + + + diff --git a/services/person/build.xml b/services/person/build.xml index 7d14120f2..2efc35282 100644 --- a/services/person/build.xml +++ b/services/person/build.xml @@ -1,132 +1,132 @@ - - - - person service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + person service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/person/client/pom.xml b/services/person/client/pom.xml index d4b5765d1..1a5fabb87 100644 --- a/services/person/client/pom.xml +++ b/services/person/client/pom.xml @@ -1,91 +1,91 @@ - - - - org.collectionspace.services - org.collectionspace.services.person - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.person.client - services.person.client - - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - - org.collectionspace.services - org.collectionspace.services.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authority.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.person.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.contact.client - ${project.version} - - - - org.testng - testng - - - - org.jboss.resteasy - resteasy-jaxrs - - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - commons-httpclient - commons-httpclient - 3.1 - - - - - collectionspace-services-person-client - - - - - + + + + org.collectionspace.services + org.collectionspace.services.person + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.person.client + services.person.client + + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + + org.collectionspace.services + org.collectionspace.services.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authority.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.person.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.contact.client + ${project.version} + + + + org.testng + testng + + + + org.jboss.resteasy + resteasy-jaxrs + + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + commons-httpclient + commons-httpclient + 3.1 + + + + + collectionspace-services-person-client + + + + + diff --git a/services/person/client/src/main/java/org/collectionspace/services/client/PersonAuthorityClientUtils.java b/services/person/client/src/main/java/org/collectionspace/services/client/PersonAuthorityClientUtils.java index 7e1584766..bfe8ff3bf 100644 --- a/services/person/client/src/main/java/org/collectionspace/services/client/PersonAuthorityClientUtils.java +++ b/services/person/client/src/main/java/org/collectionspace/services/client/PersonAuthorityClientUtils.java @@ -1,474 +1,474 @@ -/** - * PersonAuthorityClientUtils.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.client; - -import java.util.*; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; - -import org.collectionspace.services.PersonJAXBSchema; -import org.collectionspace.services.client.test.ServiceRequestType; -import org.collectionspace.services.common.api.Tools; -import org.collectionspace.services.person.GroupList; -import org.collectionspace.services.person.NationalityList; -import org.collectionspace.services.person.OccupationList; -import org.collectionspace.services.person.PersonTermGroup; -import org.collectionspace.services.person.PersonTermGroupList; -import org.collectionspace.services.person.PersonsCommon; -import org.collectionspace.services.person.PersonauthoritiesCommon; -import org.collectionspace.services.person.SchoolOrStyleList; -import org.jboss.resteasy.client.ClientResponse; -//import org.jboss.resteasy.plugins.providers.multipart.OutputPart; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.collectionspace.services.person.StructuredDateGroup; - -/** - * The Class PersonAuthorityClientUtils. - */ -public class PersonAuthorityClientUtils { - - /** The Constant logger. */ - private static final Logger logger = - LoggerFactory.getLogger(PersonAuthorityClientUtils.class); - private static final ServiceRequestType READ_REQ = ServiceRequestType.READ; - - /** - * @param csid the id of the PersonAuthority - * @param client if null, creates a new client - * @return - */ - public static String getAuthorityRefName(String csid, PersonAuthorityClient client){ - if (client == null) { - client = new PersonAuthorityClient(); - } - ClientResponse res = client.read(csid); - try { - int statusCode = res.getStatus(); - if(!READ_REQ.isValidStatusCode(statusCode) - ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) { - throw new RuntimeException("Invalid status code returned: "+statusCode); - } - //FIXME: remove the following try catch once Aron fixes signatures - try { - PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); - PersonauthoritiesCommon personAuthority = - (PersonauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input, - client.getCommonPartName(), PersonauthoritiesCommon.class); - if(personAuthority == null) { - throw new RuntimeException("Null personAuthority returned from service."); - } - return personAuthority.getRefName(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } finally { - res.releaseConnection(); - } - } - - /** - * @param csid the id of the PersonAuthority - * @param client if null, creates a new client - * @return - */ - public static String getPersonRefName(String inAuthority, String csid, PersonAuthorityClient client){ - if ( client == null) { - client = new PersonAuthorityClient(); - } - ClientResponse res = client.readItem(inAuthority, csid); - try { - int statusCode = res.getStatus(); - if(!READ_REQ.isValidStatusCode(statusCode) - ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) { - throw new RuntimeException("Invalid status code returned: "+statusCode); - } - //FIXME: remove the following try catch once Aron fixes signatures - try { - PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); - PersonsCommon person = - (PersonsCommon) CollectionSpaceClientUtils.extractPart(input, - client.getItemCommonPartName(), PersonsCommon.class); - if (person == null) { - throw new RuntimeException("Null person returned from service."); - } - return person.getRefName(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } finally { - res.releaseConnection(); - } - } - - /** - * Creates the person authority instance. - * - * @param displayName the display name - * @param shortIdentifier the short Id - * @param headerLabel the header label - * @return the multipart output - */ - public static PoxPayloadOut createPersonAuthorityInstance( - String displayName, String shortIdentifier, String headerLabel ) { - PersonauthoritiesCommon personAuthority = new PersonauthoritiesCommon(); - personAuthority.setDisplayName(displayName); - personAuthority.setShortIdentifier(shortIdentifier); - //String refName = createPersonAuthRefName(shortIdentifier, displayName); - //personAuthority.setRefName(refName); - personAuthority.setVocabType("PersonAuthority"); - PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_PAYLOAD_NAME); - PayloadOutputPart commonPart = multipart.addPart(personAuthority, MediaType.APPLICATION_XML_TYPE); - commonPart.setLabel(headerLabel); - - if(logger.isDebugEnabled()){ - logger.debug("to be created, personAuthority common ", - personAuthority, PersonauthoritiesCommon.class); - } - - return multipart; - } - - /** - * Creates a person instance. - * - * @param inAuthority the owning authority - * @param personAuthRefName the owning Authority ref name - * @param personInfo the person info - * @param headerLabel the header label - * @return the multipart output - */ - public static PoxPayloadOut createPersonInstance(String inAuthority, - String personAuthRefName, - Map personInfo, - List terms, - String headerLabel){ - if (terms == null || terms.isEmpty()) { - terms = getTermGroupInstance(getGeneratedIdentifier()); - } - final Map> EMPTY_PERSON_REPEATABLES_INFO = - new HashMap>(); - return createPersonInstance(inAuthority, null /*personAuthRefName*/, - personInfo, terms, EMPTY_PERSON_REPEATABLES_INFO, headerLabel); - } - - /** - * Creates a person instance. - * - * @param inAuthority the owning authority - * @param personAuthRefName the owning Authority ref name - * @param personInfo the person info - * @param terms a list of Person terms - * @param personRepeatablesInfo names and values of repeatable scalar fields in the Person record - * @param headerLabel the header label - * @return the multipart output - */ - public static PoxPayloadOut createPersonInstance(String inAuthority, - String personAuthRefName, Map personInfo, - List terms, - Map> personRepeatablesInfo, String headerLabel){ - PersonsCommon person = new PersonsCommon(); - person.setInAuthority(inAuthority); - String shortId = personInfo.get(PersonJAXBSchema.SHORT_IDENTIFIER); - if (shortId == null || shortId.isEmpty()) { - throw new IllegalArgumentException("shortIdentifier cannot be null or empty"); - } - person.setShortIdentifier(shortId); - - String value; - List values = null; - - if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null) { - StructuredDateGroup birthDate = new StructuredDateGroup(); - birthDate.setDateDisplayDate(value); - person.setBirthDateGroup(birthDate); - } - if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null) { - StructuredDateGroup deathDate = new StructuredDateGroup(); - deathDate.setDateDisplayDate(value); - person.setDeathDateGroup(deathDate); - } - if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null) - person.setBirthPlace(value); - if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null) - person.setDeathPlace(value); - if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null) - person.setGender(value); - if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null) - person.setBioNote(value); - if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null) - person.setNameNote(value); - - // Set values in the Term Information Group - PersonTermGroupList termList = new PersonTermGroupList(); - if (terms == null || terms.isEmpty()) { - terms = getTermGroupInstance(getGeneratedIdentifier()); - } - termList.getPersonTermGroup().addAll(terms); - person.setPersonTermGroupList(termList); - - if (personRepeatablesInfo != null) { - if((values = (List)personRepeatablesInfo.get(PersonJAXBSchema.GROUPS))!=null) { - GroupList groupsList = new GroupList(); - List groups = groupsList.getGroup(); - groups.addAll(values); - person.setGroups(groupsList); - } - if((values = (List)personRepeatablesInfo.get(PersonJAXBSchema.NATIONALITIES))!=null) { - NationalityList nationalitiesList = new NationalityList(); - List nationalities = nationalitiesList.getNationality(); - nationalities.addAll(values); - person.setNationalities(nationalitiesList); - } - - if((values = (List)personRepeatablesInfo.get(PersonJAXBSchema.OCCUPATIONS))!=null) { - OccupationList occupationsList = new OccupationList(); - List occupations = occupationsList.getOccupation(); - occupations.addAll(values); - person.setOccupations(occupationsList); - } - if((values = (List)personRepeatablesInfo.get(PersonJAXBSchema.SCHOOLS_OR_STYLES))!=null) { - SchoolOrStyleList schoolOrStyleList = new SchoolOrStyleList(); - List schoolsOrStyles = schoolOrStyleList.getSchoolOrStyle(); - schoolsOrStyles.addAll(values); - person.setSchoolsOrStyles(schoolOrStyleList); - } - } - - - PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME); - PayloadOutputPart commonPart = multipart.addPart(person, - MediaType.APPLICATION_XML_TYPE); - commonPart.setLabel(headerLabel); - - if(logger.isDebugEnabled()){ - logger.debug("to be created, person common ", person, PersonsCommon.class); - } - - return multipart; - } - - /** - * Creates the item in authority. - * - * @param vcsid the vcsid - * @param personAuthorityRefName the person authority ref name - * @param personMap the person map. PersonJAXBSchema.SHORT_IDENTIFIER is REQUIRED. - * @param client the client - * @return the string - */ - public static String createItemInAuthority(String vcsid, - String personAuthorityRefName, Map personMap, - List terms, Map> personRepeatablesMap, - PersonAuthorityClient client ) { - // Expected status code: 201 Created - int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; - - String displayName = ""; - if (terms !=null && terms.size() > 0) { - displayName = terms.get(0).getTermDisplayName(); - } - - if(logger.isDebugEnabled()){ - logger.debug("Creating item with display name: \"" + displayName - +"\" in personAuthority: \"" + vcsid +"\""); - } - PoxPayloadOut multipart = - createPersonInstance(vcsid, null /*personAuthorityRefName*/, - personMap, terms, personRepeatablesMap, client.getItemCommonPartName()); - - String result = null; - ClientResponse res = client.createItem(vcsid, multipart); - try { - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not create Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER) - +"\" in personAuthority: \"" + vcsid //personAuthorityRefName - +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when creating Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER) - +"\" in personAuthority: \"" + vcsid /*personAuthorityRefName*/ +"\", Status:"+ statusCode); - } - - result = extractId(res); - } finally { - res.releaseConnection(); - } - - return result; - } - - /** - * Creates the personAuthority ref name. - * - * @param shortId the personAuthority shortIdentifier - * @param displaySuffix displayName to be appended, if non-null - * @return the string - */ - /* - public static String createPersonAuthRefName(String shortId, String displaySuffix) { - String refName = "urn:cspace:org.collectionspace.demo:personauthority:name(" - +shortId+")"; - if(displaySuffix!=null&&!displaySuffix.isEmpty()) - refName += "'"+displaySuffix+"'"; - return refName; - } - */ - - /** - * Creates the person ref name. - * - * @param personAuthRefName the person auth ref name - * @param shortId the person shortIdentifier - * @param displaySuffix displayName to be appended, if non-null - * @return the string - */ - /* - public static String createPersonRefName( - String personAuthRefName, String shortId, String displaySuffix) { - String refName = personAuthRefName+":person:name("+shortId+")"; - if(displaySuffix!=null&&!displaySuffix.isEmpty()) - refName += "'"+displaySuffix+"'"; - return refName; - } - */ - - /** - * Extract id. - * - * @param res the res - * @return the string - */ - public static String extractId(ClientResponse res) { - MultivaluedMap mvm = res.getMetadata(); - // FIXME: This may throw an NPE if the Location: header isn't present - String uri = (String) ((ArrayList) mvm.get("Location")).get(0); - if(logger.isDebugEnabled()){ - logger.debug("extractId:uri=" + uri); - } - String[] segments = uri.split("/"); - String id = segments[segments.length - 1]; - if(logger.isDebugEnabled()){ - logger.debug("id=" + id); - } - return id; - } - - /** - * Returns an error message indicating that the status code returned by a - * specific call to a service does not fall within a set of valid status - * codes for that service. - * - * @param serviceRequestType A type of service request (e.g. CREATE, DELETE). - * - * @param statusCode The invalid status code that was returned in the response, - * from submitting that type of request to the service. - * - * @return An error message. - */ - public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) { - return "Status code '" + statusCode + "' in response is NOT within the expected set: " + - requestType.validStatusCodesAsString(); - } - - - - /** - * Produces a default displayName from the basic name and dates fields. - * @see PersonDocumentModelHandler.prepareDefaultDisplayName() which - * duplicates this logic, until we define a service-general utils package - * that is neither client nor service specific. - * @param foreName - * @param middleName - * @param surName - * @param birthDate - * @param deathDate - * @return display name - */ - public static String prepareDefaultDisplayName( - String foreName, String middleName, String surName, - String birthDate, String deathDate) { - StringBuilder newStr = new StringBuilder(); - final String sep = " "; - final String dateSep = "-"; - List nameStrings = - Arrays.asList(foreName, middleName, surName); - boolean firstAdded = false; - for(String partStr : nameStrings ){ - if(null != partStr ) { - if(firstAdded) { - newStr.append(sep); - } - newStr.append(partStr); - firstAdded = true; - } - } - // Now we add the dates. In theory could have dates with no name, but that is their problem. - boolean foundBirth = false; - if(null != birthDate) { - if(firstAdded) { - newStr.append(sep); - } - newStr.append(birthDate); - newStr.append(dateSep); // Put this in whether there is a death date or not - foundBirth = true; - } - if(null != deathDate) { - if(!foundBirth) { - if(firstAdded) { - newStr.append(sep); - } - newStr.append(dateSep); - } - newStr.append(deathDate); - } - return newStr.toString(); - } - - public static List getTermGroupInstance(String identifier) { - if (Tools.isBlank(identifier)) { - identifier = getGeneratedIdentifier(); - } - List terms = new ArrayList(); - PersonTermGroup term = new PersonTermGroup(); - term.setTermDisplayName(identifier); - term.setTermName(identifier); - terms.add(term); - return terms; - } - - private static String getGeneratedIdentifier() { - return "id" + new Date().getTime(); - } - -} +/** + * PersonAuthorityClientUtils.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.client; + +import java.util.*; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; + +import org.collectionspace.services.PersonJAXBSchema; +import org.collectionspace.services.client.test.ServiceRequestType; +import org.collectionspace.services.common.api.Tools; +import org.collectionspace.services.person.GroupList; +import org.collectionspace.services.person.NationalityList; +import org.collectionspace.services.person.OccupationList; +import org.collectionspace.services.person.PersonTermGroup; +import org.collectionspace.services.person.PersonTermGroupList; +import org.collectionspace.services.person.PersonsCommon; +import org.collectionspace.services.person.PersonauthoritiesCommon; +import org.collectionspace.services.person.SchoolOrStyleList; +import org.jboss.resteasy.client.ClientResponse; +//import org.jboss.resteasy.plugins.providers.multipart.OutputPart; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.collectionspace.services.person.StructuredDateGroup; + +/** + * The Class PersonAuthorityClientUtils. + */ +public class PersonAuthorityClientUtils { + + /** The Constant logger. */ + private static final Logger logger = + LoggerFactory.getLogger(PersonAuthorityClientUtils.class); + private static final ServiceRequestType READ_REQ = ServiceRequestType.READ; + + /** + * @param csid the id of the PersonAuthority + * @param client if null, creates a new client + * @return + */ + public static String getAuthorityRefName(String csid, PersonAuthorityClient client){ + if (client == null) { + client = new PersonAuthorityClient(); + } + ClientResponse res = client.read(csid); + try { + int statusCode = res.getStatus(); + if(!READ_REQ.isValidStatusCode(statusCode) + ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) { + throw new RuntimeException("Invalid status code returned: "+statusCode); + } + //FIXME: remove the following try catch once Aron fixes signatures + try { + PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); + PersonauthoritiesCommon personAuthority = + (PersonauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input, + client.getCommonPartName(), PersonauthoritiesCommon.class); + if(personAuthority == null) { + throw new RuntimeException("Null personAuthority returned from service."); + } + return personAuthority.getRefName(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } finally { + res.releaseConnection(); + } + } + + /** + * @param csid the id of the PersonAuthority + * @param client if null, creates a new client + * @return + */ + public static String getPersonRefName(String inAuthority, String csid, PersonAuthorityClient client){ + if ( client == null) { + client = new PersonAuthorityClient(); + } + ClientResponse res = client.readItem(inAuthority, csid); + try { + int statusCode = res.getStatus(); + if(!READ_REQ.isValidStatusCode(statusCode) + ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) { + throw new RuntimeException("Invalid status code returned: "+statusCode); + } + //FIXME: remove the following try catch once Aron fixes signatures + try { + PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); + PersonsCommon person = + (PersonsCommon) CollectionSpaceClientUtils.extractPart(input, + client.getItemCommonPartName(), PersonsCommon.class); + if (person == null) { + throw new RuntimeException("Null person returned from service."); + } + return person.getRefName(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } finally { + res.releaseConnection(); + } + } + + /** + * Creates the person authority instance. + * + * @param displayName the display name + * @param shortIdentifier the short Id + * @param headerLabel the header label + * @return the multipart output + */ + public static PoxPayloadOut createPersonAuthorityInstance( + String displayName, String shortIdentifier, String headerLabel ) { + PersonauthoritiesCommon personAuthority = new PersonauthoritiesCommon(); + personAuthority.setDisplayName(displayName); + personAuthority.setShortIdentifier(shortIdentifier); + //String refName = createPersonAuthRefName(shortIdentifier, displayName); + //personAuthority.setRefName(refName); + personAuthority.setVocabType("PersonAuthority"); + PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_PAYLOAD_NAME); + PayloadOutputPart commonPart = multipart.addPart(personAuthority, MediaType.APPLICATION_XML_TYPE); + commonPart.setLabel(headerLabel); + + if(logger.isDebugEnabled()){ + logger.debug("to be created, personAuthority common ", + personAuthority, PersonauthoritiesCommon.class); + } + + return multipart; + } + + /** + * Creates a person instance. + * + * @param inAuthority the owning authority + * @param personAuthRefName the owning Authority ref name + * @param personInfo the person info + * @param headerLabel the header label + * @return the multipart output + */ + public static PoxPayloadOut createPersonInstance(String inAuthority, + String personAuthRefName, + Map personInfo, + List terms, + String headerLabel){ + if (terms == null || terms.isEmpty()) { + terms = getTermGroupInstance(getGeneratedIdentifier()); + } + final Map> EMPTY_PERSON_REPEATABLES_INFO = + new HashMap>(); + return createPersonInstance(inAuthority, null /*personAuthRefName*/, + personInfo, terms, EMPTY_PERSON_REPEATABLES_INFO, headerLabel); + } + + /** + * Creates a person instance. + * + * @param inAuthority the owning authority + * @param personAuthRefName the owning Authority ref name + * @param personInfo the person info + * @param terms a list of Person terms + * @param personRepeatablesInfo names and values of repeatable scalar fields in the Person record + * @param headerLabel the header label + * @return the multipart output + */ + public static PoxPayloadOut createPersonInstance(String inAuthority, + String personAuthRefName, Map personInfo, + List terms, + Map> personRepeatablesInfo, String headerLabel){ + PersonsCommon person = new PersonsCommon(); + person.setInAuthority(inAuthority); + String shortId = personInfo.get(PersonJAXBSchema.SHORT_IDENTIFIER); + if (shortId == null || shortId.isEmpty()) { + throw new IllegalArgumentException("shortIdentifier cannot be null or empty"); + } + person.setShortIdentifier(shortId); + + String value; + List values = null; + + if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null) { + StructuredDateGroup birthDate = new StructuredDateGroup(); + birthDate.setDateDisplayDate(value); + person.setBirthDateGroup(birthDate); + } + if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null) { + StructuredDateGroup deathDate = new StructuredDateGroup(); + deathDate.setDateDisplayDate(value); + person.setDeathDateGroup(deathDate); + } + if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null) + person.setBirthPlace(value); + if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null) + person.setDeathPlace(value); + if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null) + person.setGender(value); + if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null) + person.setBioNote(value); + if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null) + person.setNameNote(value); + + // Set values in the Term Information Group + PersonTermGroupList termList = new PersonTermGroupList(); + if (terms == null || terms.isEmpty()) { + terms = getTermGroupInstance(getGeneratedIdentifier()); + } + termList.getPersonTermGroup().addAll(terms); + person.setPersonTermGroupList(termList); + + if (personRepeatablesInfo != null) { + if((values = (List)personRepeatablesInfo.get(PersonJAXBSchema.GROUPS))!=null) { + GroupList groupsList = new GroupList(); + List groups = groupsList.getGroup(); + groups.addAll(values); + person.setGroups(groupsList); + } + if((values = (List)personRepeatablesInfo.get(PersonJAXBSchema.NATIONALITIES))!=null) { + NationalityList nationalitiesList = new NationalityList(); + List nationalities = nationalitiesList.getNationality(); + nationalities.addAll(values); + person.setNationalities(nationalitiesList); + } + + if((values = (List)personRepeatablesInfo.get(PersonJAXBSchema.OCCUPATIONS))!=null) { + OccupationList occupationsList = new OccupationList(); + List occupations = occupationsList.getOccupation(); + occupations.addAll(values); + person.setOccupations(occupationsList); + } + if((values = (List)personRepeatablesInfo.get(PersonJAXBSchema.SCHOOLS_OR_STYLES))!=null) { + SchoolOrStyleList schoolOrStyleList = new SchoolOrStyleList(); + List schoolsOrStyles = schoolOrStyleList.getSchoolOrStyle(); + schoolsOrStyles.addAll(values); + person.setSchoolsOrStyles(schoolOrStyleList); + } + } + + + PoxPayloadOut multipart = new PoxPayloadOut(PersonAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME); + PayloadOutputPart commonPart = multipart.addPart(person, + MediaType.APPLICATION_XML_TYPE); + commonPart.setLabel(headerLabel); + + if(logger.isDebugEnabled()){ + logger.debug("to be created, person common ", person, PersonsCommon.class); + } + + return multipart; + } + + /** + * Creates the item in authority. + * + * @param vcsid the vcsid + * @param personAuthorityRefName the person authority ref name + * @param personMap the person map. PersonJAXBSchema.SHORT_IDENTIFIER is REQUIRED. + * @param client the client + * @return the string + */ + public static String createItemInAuthority(String vcsid, + String personAuthorityRefName, Map personMap, + List terms, Map> personRepeatablesMap, + PersonAuthorityClient client ) { + // Expected status code: 201 Created + int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; + + String displayName = ""; + if (terms !=null && terms.size() > 0) { + displayName = terms.get(0).getTermDisplayName(); + } + + if(logger.isDebugEnabled()){ + logger.debug("Creating item with display name: \"" + displayName + +"\" in personAuthority: \"" + vcsid +"\""); + } + PoxPayloadOut multipart = + createPersonInstance(vcsid, null /*personAuthorityRefName*/, + personMap, terms, personRepeatablesMap, client.getItemCommonPartName()); + + String result = null; + ClientResponse res = client.createItem(vcsid, multipart); + try { + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not create Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER) + +"\" in personAuthority: \"" + vcsid //personAuthorityRefName + +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when creating Item: \""+personMap.get(PersonJAXBSchema.SHORT_IDENTIFIER) + +"\" in personAuthority: \"" + vcsid /*personAuthorityRefName*/ +"\", Status:"+ statusCode); + } + + result = extractId(res); + } finally { + res.releaseConnection(); + } + + return result; + } + + /** + * Creates the personAuthority ref name. + * + * @param shortId the personAuthority shortIdentifier + * @param displaySuffix displayName to be appended, if non-null + * @return the string + */ + /* + public static String createPersonAuthRefName(String shortId, String displaySuffix) { + String refName = "urn:cspace:org.collectionspace.demo:personauthority:name(" + +shortId+")"; + if(displaySuffix!=null&&!displaySuffix.isEmpty()) + refName += "'"+displaySuffix+"'"; + return refName; + } + */ + + /** + * Creates the person ref name. + * + * @param personAuthRefName the person auth ref name + * @param shortId the person shortIdentifier + * @param displaySuffix displayName to be appended, if non-null + * @return the string + */ + /* + public static String createPersonRefName( + String personAuthRefName, String shortId, String displaySuffix) { + String refName = personAuthRefName+":person:name("+shortId+")"; + if(displaySuffix!=null&&!displaySuffix.isEmpty()) + refName += "'"+displaySuffix+"'"; + return refName; + } + */ + + /** + * Extract id. + * + * @param res the res + * @return the string + */ + public static String extractId(ClientResponse res) { + MultivaluedMap mvm = res.getMetadata(); + // FIXME: This may throw an NPE if the Location: header isn't present + String uri = (String) ((ArrayList) mvm.get("Location")).get(0); + if(logger.isDebugEnabled()){ + logger.debug("extractId:uri=" + uri); + } + String[] segments = uri.split("/"); + String id = segments[segments.length - 1]; + if(logger.isDebugEnabled()){ + logger.debug("id=" + id); + } + return id; + } + + /** + * Returns an error message indicating that the status code returned by a + * specific call to a service does not fall within a set of valid status + * codes for that service. + * + * @param serviceRequestType A type of service request (e.g. CREATE, DELETE). + * + * @param statusCode The invalid status code that was returned in the response, + * from submitting that type of request to the service. + * + * @return An error message. + */ + public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) { + return "Status code '" + statusCode + "' in response is NOT within the expected set: " + + requestType.validStatusCodesAsString(); + } + + + + /** + * Produces a default displayName from the basic name and dates fields. + * @see PersonDocumentModelHandler.prepareDefaultDisplayName() which + * duplicates this logic, until we define a service-general utils package + * that is neither client nor service specific. + * @param foreName + * @param middleName + * @param surName + * @param birthDate + * @param deathDate + * @return display name + */ + public static String prepareDefaultDisplayName( + String foreName, String middleName, String surName, + String birthDate, String deathDate) { + StringBuilder newStr = new StringBuilder(); + final String sep = " "; + final String dateSep = "-"; + List nameStrings = + Arrays.asList(foreName, middleName, surName); + boolean firstAdded = false; + for(String partStr : nameStrings ){ + if(null != partStr ) { + if(firstAdded) { + newStr.append(sep); + } + newStr.append(partStr); + firstAdded = true; + } + } + // Now we add the dates. In theory could have dates with no name, but that is their problem. + boolean foundBirth = false; + if(null != birthDate) { + if(firstAdded) { + newStr.append(sep); + } + newStr.append(birthDate); + newStr.append(dateSep); // Put this in whether there is a death date or not + foundBirth = true; + } + if(null != deathDate) { + if(!foundBirth) { + if(firstAdded) { + newStr.append(sep); + } + newStr.append(dateSep); + } + newStr.append(deathDate); + } + return newStr.toString(); + } + + public static List getTermGroupInstance(String identifier) { + if (Tools.isBlank(identifier)) { + identifier = getGeneratedIdentifier(); + } + List terms = new ArrayList(); + PersonTermGroup term = new PersonTermGroup(); + term.setTermDisplayName(identifier); + term.setTermName(identifier); + terms.add(term); + return terms; + } + + private static String getGeneratedIdentifier() { + return "id" + new Date().getTime(); + } + +} diff --git a/services/person/client/src/test/resources/log4j.properties b/services/person/client/src/test/resources/log4j.properties index 4519e9992..dbbca89e7 100644 --- a/services/person/client/src/test/resources/log4j.properties +++ b/services/person/client/src/test/resources/log4j.properties @@ -1,25 +1,25 @@ -log4j.rootLogger=debug, stdout, R - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.encoding=UTF-8 - -# 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.encoding=UTF-8 - -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 +log4j.rootLogger=debug, stdout, R + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.encoding=UTF-8 + +# 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.encoding=UTF-8 + +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/person/installer/build.xml b/services/person/installer/build.xml index c0fc960c8..c9e926f27 100644 --- a/services/person/installer/build.xml +++ b/services/person/installer/build.xml @@ -1,61 +1,61 @@ - - - - person service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + person service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/person/jaxb/src/main/java/org/collectionspace/services/PersonJAXBSchema.java b/services/person/jaxb/src/main/java/org/collectionspace/services/PersonJAXBSchema.java index a9b8ce981..445fa30e7 100644 --- a/services/person/jaxb/src/main/java/org/collectionspace/services/PersonJAXBSchema.java +++ b/services/person/jaxb/src/main/java/org/collectionspace/services/PersonJAXBSchema.java @@ -1,32 +1,32 @@ -/** - * - */ -package org.collectionspace.services; -import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema; - -/** - * @author pschmitz - * - */ -public interface PersonJAXBSchema extends AuthorityItemJAXBSchema { - final static String PERSONS_COMMON = "persons_common"; - final static String FORE_NAME = "foreName"; - final static String MIDDLE_NAME = "middleName"; - final static String SUR_NAME = "surName"; - final static String INITIALS = "initials"; - final static String SALUTATIONS = "salutations"; - final static String TITLE = "title"; - final static String NAME_ADDITIONS = "nameAdditions"; - final static String BIRTH_DATE = "birthDate"; - final static String DEATH_DATE = "deathDate"; - final static String BIRTH_PLACE = "birthPlace"; - final static String DEATH_PLACE = "deathPlace"; - final static String GROUPS = "groups"; - final static String NATIONALITIES = "nationalities"; - final static String GENDER = "gender"; - final static String OCCUPATIONS = "occupations"; - final static String SCHOOLS_OR_STYLES = "schoolsOrStyles"; - final static String BIO_NOTE = "bioNote"; - final static String NAME_NOTE = "nameNote"; -} - +/** + * + */ +package org.collectionspace.services; +import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema; + +/** + * @author pschmitz + * + */ +public interface PersonJAXBSchema extends AuthorityItemJAXBSchema { + final static String PERSONS_COMMON = "persons_common"; + final static String FORE_NAME = "foreName"; + final static String MIDDLE_NAME = "middleName"; + final static String SUR_NAME = "surName"; + final static String INITIALS = "initials"; + final static String SALUTATIONS = "salutations"; + final static String TITLE = "title"; + final static String NAME_ADDITIONS = "nameAdditions"; + final static String BIRTH_DATE = "birthDate"; + final static String DEATH_DATE = "deathDate"; + final static String BIRTH_PLACE = "birthPlace"; + final static String DEATH_PLACE = "deathPlace"; + final static String GROUPS = "groups"; + final static String NATIONALITIES = "nationalities"; + final static String GENDER = "gender"; + final static String OCCUPATIONS = "occupations"; + final static String SCHOOLS_OR_STYLES = "schoolsOrStyles"; + final static String BIO_NOTE = "bioNote"; + final static String NAME_NOTE = "nameNote"; +} + diff --git a/services/person/pom.xml b/services/person/pom.xml index dc2d18112..f25845481 100644 --- a/services/person/pom.xml +++ b/services/person/pom.xml @@ -1,43 +1,43 @@ - - - - org.collectionspace.services - org.collectionspace.services.main - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.person - services.person - pom - - - - - - - jaxb - service - 3rdparty - client - - - - - samples - - sample - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.main + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.person + services.person + pom + + + + + + + jaxb + service + 3rdparty + client + + + + + samples + + sample + + + + + + diff --git a/services/person/sample/.classpath b/services/person/sample/.classpath index ad5c57cd5..e526a4712 100644 --- a/services/person/sample/.classpath +++ b/services/person/sample/.classpath @@ -1,5 +1,5 @@ - - - - - + + + + + diff --git a/services/person/sample/.project b/services/person/sample/.project index bce7b990c..0e446eafd 100644 --- a/services/person/sample/.project +++ b/services/person/sample/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.person.client.samples - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.person.client.samples + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/person/sample/pom.xml b/services/person/sample/pom.xml index 722a68d84..b7357045b 100644 --- a/services/person/sample/pom.xml +++ b/services/person/sample/pom.xml @@ -1,14 +1,14 @@ - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.person.client.samples - pom - 1.0 - person.client.samples - - - sample - - - + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.person.client.samples + pom + 1.0 + person.client.samples + + + sample + + + diff --git a/services/person/sample/sample/.classpath b/services/person/sample/sample/.classpath index 4905d3908..72d2ee925 100644 --- a/services/person/sample/sample/.classpath +++ b/services/person/sample/sample/.classpath @@ -1,32 +1,32 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/person/sample/sample/.project b/services/person/sample/sample/.project index 578b4c5de..ca6768087 100644 --- a/services/person/sample/sample/.project +++ b/services/person/sample/sample/.project @@ -1,23 +1,23 @@ - - - org.collectionspace.services.person.client.sample - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.person.client.sample + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/person/sample/sample/pom.xml b/services/person/sample/sample/pom.xml index c8119ab1d..deedd7d81 100644 --- a/services/person/sample/sample/pom.xml +++ b/services/person/sample/sample/pom.xml @@ -1,111 +1,111 @@ - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.person.client.sample - jar - 1.0 - person.client.sample - - - - - - - - libs-releases-local - libs-releases-local - http://nightly.collectionspace.org:8081/artifactory/libs-release-local - - true - - - false - - - - - libs-snapshots-local - libs-snapshots-local - http://nightly.collectionspace.org:8081/artifactory/libs-snapshot-local - - false - - - true - - - - nuxeo-public - nuxeo-public - http://nightly.collectionspace.org:8081/artifactory/nuxeo-public - - true - - - false - - - - nuxeo-public-snapshot - nuxeo-public-snapshot - http://nightly.collectionspace.org:8081/artifactory/nuxeo-public-snapshot - - false - - - true - - - - - - person-client-sample - - - org.apache.maven.plugins - maven-assembly-plugin - - - - attached - - package - - - jar-with-dependencies - - - - org.collectionspace.services.person.client.sample.Sample - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.7 - 1.7 - - - - - - + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.person.client.sample + jar + 1.0 + person.client.sample + + + + + + + + libs-releases-local + libs-releases-local + http://nightly.collectionspace.org:8081/artifactory/libs-release-local + + true + + + false + + + + + libs-snapshots-local + libs-snapshots-local + http://nightly.collectionspace.org:8081/artifactory/libs-snapshot-local + + false + + + true + + + + nuxeo-public + nuxeo-public + http://nightly.collectionspace.org:8081/artifactory/nuxeo-public + + true + + + false + + + + nuxeo-public-snapshot + nuxeo-public-snapshot + http://nightly.collectionspace.org:8081/artifactory/nuxeo-public-snapshot + + false + + + true + + + + + + person-client-sample + + + org.apache.maven.plugins + maven-assembly-plugin + + + + attached + + package + + + jar-with-dependencies + + + + org.collectionspace.services.person.client.sample.Sample + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.7 + 1.7 + + + + + + diff --git a/services/person/sample/sample/src/main/java/org/collectionspace/services/person/client/sample/Sample.java b/services/person/sample/sample/src/main/java/org/collectionspace/services/person/client/sample/Sample.java index 1e09bc184..10aa55db2 100644 --- a/services/person/sample/sample/src/main/java/org/collectionspace/services/person/client/sample/Sample.java +++ b/services/person/sample/sample/src/main/java/org/collectionspace/services/person/client/sample/Sample.java @@ -1,593 +1,593 @@ -/** - * 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 (c)) 2009 Regents of the University of California - * - * 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.person.client.sample; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; - -import org.apache.log4j.BasicConfigurator; -import org.collectionspace.services.PersonJAXBSchema; -import org.collectionspace.services.client.PersonAuthorityClient; -import org.collectionspace.services.client.PersonAuthorityClientUtils; -import org.collectionspace.services.client.PoxPayloadIn; -import org.collectionspace.services.client.PoxPayloadOut; -import org.collectionspace.services.client.test.ServiceRequestType; -import org.collectionspace.services.person.PersonauthoritiesCommon; -import org.collectionspace.services.person.PersonauthoritiesCommonList; -import org.collectionspace.services.person.PersonsCommon; -import org.collectionspace.services.person.PersonsCommonList; -import org.jboss.resteasy.client.ClientResponse; -import org.jboss.resteasy.plugins.providers.multipart.InputPart; -import org.jboss.resteasy.plugins.providers.multipart.OutputPart; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * PersonAuthority Sample, carries out tests against a - * deployed and running PersonAuthority Service. - * - * $LastChangedRevision: 1055 $ - * $LastChangedDate: 2009-12-09 12:25:15 -0800 (Wed, 09 Dec 2009) $ - */ -public class Sample { - private static final Logger logger = - LoggerFactory.getLogger(Sample.class); - - // Instance variables specific to this test. - private PersonAuthorityClient client = new PersonAuthorityClient(); - final String SERVICE_PATH_COMPONENT = "persons"; - final String ITEM_SERVICE_PATH_COMPONENT = "items"; - - - // --------------------------------------------------------------- - // Create - // --------------------------------------------------------------- - - public void createPersonAuthority(String personAuthorityName, - List> personMaps ) { - - // Expected status code: 201 Created - int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; - - logger.info("Import: Create personAuthority: \"" + personAuthorityName +"\""); - - - String displaySuffix = "displayName-" + System.currentTimeMillis(); //TODO: Laramie20100728 temp fix, made-up displaySuffix. - String basePersonRefName = PersonAuthorityClientUtils.createPersonAuthRefName(personAuthorityName, displaySuffix);//TODO: Laramie20100728 temp fix was personAuthorityName, false - String fullPersonRefName = PersonAuthorityClientUtils.createPersonAuthRefName(personAuthorityName, displaySuffix); //TODO: Laramie20100728 temp fix was personAuthorityName, true - PoxPayloadOut multipart = - PersonAuthorityClientUtils.createPersonAuthorityInstance( - personAuthorityName, fullPersonRefName, client.getCommonPartName() ); - ClientResponse res = client.create(multipart); - - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not create enumeration: \""+personAuthorityName - +"\" "+ PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when creating enumeration: \"" - +personAuthorityName +"\", Status:"+ statusCode); - } - - // Store the ID returned from this create operation - // for additional tests below. - String newPersonAuthId = PersonAuthorityClientUtils.extractId(res); - logger.info("Import: Created personAuthority: \"" + personAuthorityName +"\" ID:" - +newPersonAuthId ); - - // Add items to the personAuthority - for(Map personMap : personMaps){ - createItemInAuthority(newPersonAuthId, basePersonRefName, personMap); - } - - } - - private String createItemInAuthority(String vcsid, - String personAuthorityRefName, Map personMap) { - // Expected status code: 201 Created - int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; - String foreName = personMap.get(PersonJAXBSchema.FORE_NAME); - String middleName = personMap.get(PersonJAXBSchema.MIDDLE_NAME); - String surName = personMap.get(PersonJAXBSchema.SUR_NAME); - String birthDate = personMap.get(PersonJAXBSchema.BIRTH_DATE); - String deathDate = personMap.get(PersonJAXBSchema.DEATH_DATE); - StringBuilder builtName = new StringBuilder(); - if(foreName!=null) - builtName.append(foreName); - if(middleName!=null) - builtName.append(middleName); - if(surName!=null) - builtName.append(surName); - if(birthDate!=null) - builtName.append(birthDate); - builtName.append("-"); - if(deathDate!=null) - builtName.append(deathDate); - - String displaySuffix = "displayName-" + System.currentTimeMillis(); //TODO: Laramie20100728 temp fix, made-up displaySuffix. - - String refName = PersonAuthorityClientUtils.createPersonRefName(personAuthorityRefName, builtName.toString(), displaySuffix); //TODO was ...,true); - logger.info("Import: Create Item: \""+refName+"\" in personAuthority: \"" + personAuthorityRefName +"\""); - - if(logger.isDebugEnabled()){ - logger.debug("Import: Create Item: \""+builtName.toString() - +"\" in personAuthorityulary: \"" + personAuthorityRefName +"\""); - } - PoxPayloadOut multipart = createPersonInstance( vcsid, refName, - personMap ); - ClientResponse res = client.createItem(vcsid, multipart); - - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not create Item: \""+refName - +"\" in personAuthority: \"" + personAuthorityRefName - +"\" "+ PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when creating Item: \""+refName - +"\" in personAuthority: \"" + personAuthorityRefName +"\", Status:"+ statusCode); - } - - return PersonAuthorityClientUtils.extractId(res); - } - - - // --------------------------------------------------------------- - // Read - // --------------------------------------------------------------- - - private PersonauthoritiesCommonList readPersonAuthorities() { - - // Expected status code: 200 OK - int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; - - // Submit the request to the service and store the response. - ClientResponse res = client.readList(); - PersonauthoritiesCommonList list = res.getEntity(); - - int statusCode = res.getStatus(); - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not read list of personAuthorities: " - + PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when reading " + - "list of personAuthorities, Status:"+ statusCode); - } - - return list; - } - - private List readPersonAuthorityIds(PersonauthoritiesCommonList list) { - - List ids = new ArrayList(); - List personAuthorities = - list.getPersonauthorityListItem(); - for (PersonauthoritiesCommonList.PersonauthorityListItem personAuthority : personAuthorities) { - ids.add(personAuthority.getCsid()); - } - return ids; - } - - private PersonauthoritiesCommon readPersonAuthority(String personAuthId) { - - // Expected status code: 200 OK - int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; - - // Submit the request to the service and store the response. - PersonauthoritiesCommon personAuthority = null; - try { - ClientResponse res = client.read(personAuthId); - int statusCode = res.getStatus(); - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not read personAuthority" - + PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when reading " + - "personAuthority, Status:"+ statusCode); - } - PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); - personAuthority = (PersonauthoritiesCommon) extractPart(input, - client.getCommonPartName(), PersonauthoritiesCommon.class); - } catch (Exception e) { - throw new RuntimeException("Could not read personAuthority: ", e); - } - - return personAuthority; - } - - private PersonsCommonList readItemsInPersonAuth(String personAuthId) { - - // Expected status code: 200 OK - int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; - - // Submit the request to the service and store the response. - ClientResponse res = client.readItemList(personAuthId, "", ""); //TODO: Laramie201007289 added empty strings to satisfy api - PersonsCommonList list = res.getEntity(); - - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not read items in personAuthority: " - + PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when reading " + - "items in personAuthority, Status:"+ statusCode); - } - - return list; - } - - private List readPersonIds(PersonsCommonList list) { - - List ids = new ArrayList(); - List items = - list.getPersonListItem(); - for (PersonsCommonList.PersonListItem item : items) { - ids.add(item.getCsid()); - } - return ids; - } - - // --------------------------------------------------------------- - // Delete - // --------------------------------------------------------------- - - private void deletePersonAuthority(String vcsid) { - // Expected status code: 200 OK - int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE; - - ClientResponse res = client.delete(vcsid); - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not delete personAuthority: " - + PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when deleting " + - "personAuthority, Status:"+ statusCode); - } - } - - private void deleteAllPersonAuthorities() { - List ids = readPersonAuthorityIds(readPersonAuthorities()); - for (String id : ids) { - deletePersonAuthority(id); - } - } - - private void deletePerson(String vcsid, String itemcsid) { - // Expected status code: 200 OK - int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE; - - ClientResponse res = client.deleteItem(vcsid, itemcsid); - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not delete personAuthority item: " - + PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when deleting " + - "personAuthority item, Status:"+ statusCode); - } - } - - private void deleteAllItemsForPersonAuth(String personAuthId) { - List itemIds = readPersonIds(readItemsInPersonAuth(personAuthId)); - for (String itemId : itemIds) { - deletePerson(personAuthId, itemId); - } - } - - // --------------------------------------------------------------- - // Utility methods used by tests above - // --------------------------------------------------------------- - - /* - private PoxPayloadOut createPersonAuthorityInstance( - String displayName, String refName ) { - PersonauthoritiesCommon personAuthority = new PersonauthoritiesCommon(); - personAuthority.setDisplayName(displayName); - personAuthority.setRefName(refName); - personAuthority.setVocabType("PersonAuthority"); - PoxPayloadOut multipart = new PoxPayloadOut(); - OutputPart commonPart = multipart.addPart(personAuthority, MediaType.APPLICATION_XML_TYPE); - commonPart.getHeaders().add("label", client.getCommonPartName()); - - if(logger.isDebugEnabled()){ - logger.debug("to be created, personAuthority common ", - personAuthority, PersonauthoritiesCommon.class); - } - - return multipart; - } - */ - - private PoxPayloadOut createPersonInstance(String inAuthority, - String refName, Map personInfo ) { - PersonsCommon person = new PersonsCommon(); - person.setInAuthority(inAuthority); - person.setRefName(refName); - String value = null; - if((value = (String)personInfo.get(PersonJAXBSchema.FORE_NAME))!=null) - person.setForeName(value); - if((value = (String)personInfo.get(PersonJAXBSchema.MIDDLE_NAME))!=null) - person.setMiddleName(value); - if((value = (String)personInfo.get(PersonJAXBSchema.SUR_NAME))!=null) - person.setSurName(value); - if((value = (String)personInfo.get(PersonJAXBSchema.INITIALS))!=null) - person.setInitials(value); - if((value = (String)personInfo.get(PersonJAXBSchema.SALUTATIONS))!=null) - person.setSalutation(value); - if((value = (String)personInfo.get(PersonJAXBSchema.TITLE))!=null) - person.setTitle(value); - if((value = (String)personInfo.get(PersonJAXBSchema.NAME_ADDITIONS))!=null) - person.setNameAdditions(value); - if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null) { - StructuredDateGroup birthDate = new StructuredDateGroup(); - birthDate.setDateDisplayDate(value); - person.setBirthDateGroup(birthDate); - } - if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null) { - StructuredDateGroup deathDate = new StructuredDateGroup(); - deathDate.setDateDisplayDate(value); - person.setDeathDateGroup(deathDate); - } - if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null) - person.setBirthPlace(value); - if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null) - person.setDeathPlace(value); - - /* TODO: Laramie20100728 removed missing member calls - if((value = (String)personInfo.get(PersonJAXBSchema.GROUP))!=null) - person.setGroup(value); - if((value = (String)personInfo.get(PersonJAXBSchema.NATIONALITY))!=null) - person.setNationality(value); - if((value = (String)personInfo.get(PersonJAXBSchema.OCCUPATION))!=null) - person.setOccupation(value); - if((value = (String)personInfo.get(PersonJAXBSchema.SCHOOL_OR_STYLE))!=null) - person.setSchoolOrStyle(value); - */ - - if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null) - person.setGender(value); - if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null) - person.setBioNote(value); - if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null) - person.setNameNote(value); - PoxPayloadOut multipart = new PoxPayloadOut(); - OutputPart commonPart = multipart.addPart(person, - MediaType.APPLICATION_XML_TYPE); - commonPart.getHeaders().add("label", client.getItemCommonPartName()); - - if(logger.isDebugEnabled()){ - logger.debug("to be created, person common"+person); - } - - return multipart; - } - - // Retrieve individual fields of personAuthority records. - - private String displayAllPersonAuthorities(PersonauthoritiesCommonList list) { - StringBuffer sb = new StringBuffer(); - List personAuthorities = - list.getPersonauthorityListItem(); - int i = 0; - for (PersonauthoritiesCommonList.PersonauthorityListItem personAuthority : personAuthorities) { - sb.append("personAuthority [" + i + "]" + "\n"); - sb.append(displayPersonAuthorityDetails(personAuthority)); - i++; - } - return sb.toString(); - } - - private String displayPersonAuthorityDetails( - PersonauthoritiesCommonList.PersonauthorityListItem personAuthority) { - StringBuffer sb = new StringBuffer(); - sb.append("displayName=" + personAuthority.getDisplayName() + "\n"); - sb.append("vocabType=" + personAuthority.getVocabType() + "\n"); - // sb.append("csid=" + personAuthority.getCsid() + "\n"); - sb.append("URI=" + personAuthority.getUri() + "\n"); - return sb.toString(); - } - - // Retrieve individual fields of person records. - - private String displayAllPersons(PersonsCommonList list) { - StringBuffer sb = new StringBuffer(); - List items = - list.getPersonListItem(); - int i = 0; - for (PersonsCommonList.PersonListItem item : items) { - sb.append("person [" + i + "]" + "\n"); - sb.append(displayPersonDetails(item)); - i++; - } - return sb.toString(); - } - - private String displayPersonDetails( - PersonsCommonList.PersonListItem item) { - StringBuffer sb = new StringBuffer(); - sb.append("csid=" + item.getCsid() + "\n"); - sb.append("displayName=" + item.getDisplayName() + "\n"); - // sb.append("URI=" + item.getUri() + "\n"); - return sb.toString(); - } - - private Object extractPart(PoxPayloadIn input, String label, - Class clazz) throws Exception { - Object obj = null; - for(InputPart part : input.getParts()){ - String partLabel = part.getHeaders().getFirst("label"); - if(label.equalsIgnoreCase(partLabel)){ - String partStr = part.getBodyAsString(); - if(logger.isDebugEnabled()){ - logger.debug("extracted part str=\n" + partStr); - } - obj = part.getBody(clazz, null); - if(logger.isDebugEnabled()){ - logger.debug("extracted part obj=\n", obj, clazz); - } - break; - } - } - return obj; - } - - public static void main(String[] args) { - - // Configure logging. - BasicConfigurator.configure(); - - logger.info("PersonAuthority Sample starting..."); - - Sample sample = new Sample(); - PersonauthoritiesCommonList personAuthorities; - List personAuthIds; - String details = ""; - - // Optionally delete all personAuthorities and persons. - - boolean ENABLE_DELETE_ALL = false; - if (ENABLE_DELETE_ALL) { - - logger.info("Deleting all persons and personAuthorities ..."); - - // For each personAuthority ... - personAuthorities = sample.readPersonAuthorities(); - personAuthIds = sample.readPersonAuthorityIds(personAuthorities); - for (String personAuthId : personAuthIds) { - logger.info("Deleting all persons for personAuthority ..."); - sample.deleteAllItemsForPersonAuth(personAuthId); - logger.info("Deleting personAuthority ..."); - sample.deletePersonAuthority(personAuthId); - } - - logger.info("Reading personAuthorities after deletion ..."); - personAuthorities = sample.readPersonAuthorities(); - details = sample.displayAllPersonAuthorities(personAuthorities); - logger.info(details); - - logger.info("Reading items in each personAuthority after deletion ..."); - personAuthIds = sample.readPersonAuthorityIds(personAuthorities); - for (String personAuthId : personAuthIds) { - PersonsCommonList items = sample.readItemsInPersonAuth(personAuthId); - details = sample.displayAllPersons(items); - logger.info(details); - } - - } - - // Create new authorities, each populated with persons. - - Map johnWayneMap = new HashMap(); - johnWayneMap.put(PersonJAXBSchema.FORE_NAME, "John"); - johnWayneMap.put(PersonJAXBSchema.SUR_NAME, "Wayne"); - johnWayneMap.put(PersonJAXBSchema.GENDER, "male"); - Map patrickSchmitzMap = new HashMap(); - patrickSchmitzMap.put(PersonJAXBSchema.FORE_NAME, "Patrick"); - patrickSchmitzMap.put(PersonJAXBSchema.SUR_NAME, "Schmitz"); - patrickSchmitzMap.put(PersonJAXBSchema.GENDER, "male"); - Map janeDoeMap = new HashMap(); - janeDoeMap.put(PersonJAXBSchema.FORE_NAME, "Jane"); - janeDoeMap.put(PersonJAXBSchema.SUR_NAME, "Doe"); - janeDoeMap.put(PersonJAXBSchema.GENDER, "female"); - List> personsMaps = - Arrays.asList(johnWayneMap, patrickSchmitzMap, janeDoeMap ); - - sample.createPersonAuthority("Sample Person Auth", personsMaps); - - logger.info("PersonAuthority Sample complete."); - - logger.info("Reading personAuthorities and items ..."); - // Get a list of personAuthorities. - personAuthorities = sample.readPersonAuthorities(); - // For each personAuthority ... - for (PersonauthoritiesCommonList.PersonauthorityListItem - personAuthority : personAuthorities.getPersonauthorityListItem()) { - // Get its display name. - logger.info(personAuthority.getDisplayName()); - // Get a list of the persons in this personAuthority. - PersonsCommonList items = - sample.readItemsInPersonAuth(personAuthority.getCsid()); - // For each person ... - for (PersonsCommonList.PersonListItem - item : items.getPersonListItem()) { - // Get its short name. - logger.info(" " + item.getDisplayName()); - } - } - - // Sample alternate methods of reading all personAuthorities and - // persons separately. - boolean RUN_ADDITIONAL_SAMPLES = false; - if (RUN_ADDITIONAL_SAMPLES) { - - logger.info("Reading all personAuthorities ..."); - details = sample.displayAllPersonAuthorities(personAuthorities); - logger.info(details); - - logger.info("Reading all persons ..."); - personAuthIds = sample.readPersonAuthorityIds(personAuthorities); - for (String personAuthId : personAuthIds) { - PersonsCommonList items = sample.readItemsInPersonAuth(personAuthId); - details = sample.displayAllPersons(items); - logger.info(details); - } - - } - - } - -} +/** + * 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 (c)) 2009 Regents of the University of California + * + * 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.person.client.sample; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; + +import org.apache.log4j.BasicConfigurator; +import org.collectionspace.services.PersonJAXBSchema; +import org.collectionspace.services.client.PersonAuthorityClient; +import org.collectionspace.services.client.PersonAuthorityClientUtils; +import org.collectionspace.services.client.PoxPayloadIn; +import org.collectionspace.services.client.PoxPayloadOut; +import org.collectionspace.services.client.test.ServiceRequestType; +import org.collectionspace.services.person.PersonauthoritiesCommon; +import org.collectionspace.services.person.PersonauthoritiesCommonList; +import org.collectionspace.services.person.PersonsCommon; +import org.collectionspace.services.person.PersonsCommonList; +import org.jboss.resteasy.client.ClientResponse; +import org.jboss.resteasy.plugins.providers.multipart.InputPart; +import org.jboss.resteasy.plugins.providers.multipart.OutputPart; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * PersonAuthority Sample, carries out tests against a + * deployed and running PersonAuthority Service. + * + * $LastChangedRevision: 1055 $ + * $LastChangedDate: 2009-12-09 12:25:15 -0800 (Wed, 09 Dec 2009) $ + */ +public class Sample { + private static final Logger logger = + LoggerFactory.getLogger(Sample.class); + + // Instance variables specific to this test. + private PersonAuthorityClient client = new PersonAuthorityClient(); + final String SERVICE_PATH_COMPONENT = "persons"; + final String ITEM_SERVICE_PATH_COMPONENT = "items"; + + + // --------------------------------------------------------------- + // Create + // --------------------------------------------------------------- + + public void createPersonAuthority(String personAuthorityName, + List> personMaps ) { + + // Expected status code: 201 Created + int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; + + logger.info("Import: Create personAuthority: \"" + personAuthorityName +"\""); + + + String displaySuffix = "displayName-" + System.currentTimeMillis(); //TODO: Laramie20100728 temp fix, made-up displaySuffix. + String basePersonRefName = PersonAuthorityClientUtils.createPersonAuthRefName(personAuthorityName, displaySuffix);//TODO: Laramie20100728 temp fix was personAuthorityName, false + String fullPersonRefName = PersonAuthorityClientUtils.createPersonAuthRefName(personAuthorityName, displaySuffix); //TODO: Laramie20100728 temp fix was personAuthorityName, true + PoxPayloadOut multipart = + PersonAuthorityClientUtils.createPersonAuthorityInstance( + personAuthorityName, fullPersonRefName, client.getCommonPartName() ); + ClientResponse res = client.create(multipart); + + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not create enumeration: \""+personAuthorityName + +"\" "+ PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when creating enumeration: \"" + +personAuthorityName +"\", Status:"+ statusCode); + } + + // Store the ID returned from this create operation + // for additional tests below. + String newPersonAuthId = PersonAuthorityClientUtils.extractId(res); + logger.info("Import: Created personAuthority: \"" + personAuthorityName +"\" ID:" + +newPersonAuthId ); + + // Add items to the personAuthority + for(Map personMap : personMaps){ + createItemInAuthority(newPersonAuthId, basePersonRefName, personMap); + } + + } + + private String createItemInAuthority(String vcsid, + String personAuthorityRefName, Map personMap) { + // Expected status code: 201 Created + int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; + String foreName = personMap.get(PersonJAXBSchema.FORE_NAME); + String middleName = personMap.get(PersonJAXBSchema.MIDDLE_NAME); + String surName = personMap.get(PersonJAXBSchema.SUR_NAME); + String birthDate = personMap.get(PersonJAXBSchema.BIRTH_DATE); + String deathDate = personMap.get(PersonJAXBSchema.DEATH_DATE); + StringBuilder builtName = new StringBuilder(); + if(foreName!=null) + builtName.append(foreName); + if(middleName!=null) + builtName.append(middleName); + if(surName!=null) + builtName.append(surName); + if(birthDate!=null) + builtName.append(birthDate); + builtName.append("-"); + if(deathDate!=null) + builtName.append(deathDate); + + String displaySuffix = "displayName-" + System.currentTimeMillis(); //TODO: Laramie20100728 temp fix, made-up displaySuffix. + + String refName = PersonAuthorityClientUtils.createPersonRefName(personAuthorityRefName, builtName.toString(), displaySuffix); //TODO was ...,true); + logger.info("Import: Create Item: \""+refName+"\" in personAuthority: \"" + personAuthorityRefName +"\""); + + if(logger.isDebugEnabled()){ + logger.debug("Import: Create Item: \""+builtName.toString() + +"\" in personAuthorityulary: \"" + personAuthorityRefName +"\""); + } + PoxPayloadOut multipart = createPersonInstance( vcsid, refName, + personMap ); + ClientResponse res = client.createItem(vcsid, multipart); + + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not create Item: \""+refName + +"\" in personAuthority: \"" + personAuthorityRefName + +"\" "+ PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when creating Item: \""+refName + +"\" in personAuthority: \"" + personAuthorityRefName +"\", Status:"+ statusCode); + } + + return PersonAuthorityClientUtils.extractId(res); + } + + + // --------------------------------------------------------------- + // Read + // --------------------------------------------------------------- + + private PersonauthoritiesCommonList readPersonAuthorities() { + + // Expected status code: 200 OK + int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; + + // Submit the request to the service and store the response. + ClientResponse res = client.readList(); + PersonauthoritiesCommonList list = res.getEntity(); + + int statusCode = res.getStatus(); + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not read list of personAuthorities: " + + PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when reading " + + "list of personAuthorities, Status:"+ statusCode); + } + + return list; + } + + private List readPersonAuthorityIds(PersonauthoritiesCommonList list) { + + List ids = new ArrayList(); + List personAuthorities = + list.getPersonauthorityListItem(); + for (PersonauthoritiesCommonList.PersonauthorityListItem personAuthority : personAuthorities) { + ids.add(personAuthority.getCsid()); + } + return ids; + } + + private PersonauthoritiesCommon readPersonAuthority(String personAuthId) { + + // Expected status code: 200 OK + int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; + + // Submit the request to the service and store the response. + PersonauthoritiesCommon personAuthority = null; + try { + ClientResponse res = client.read(personAuthId); + int statusCode = res.getStatus(); + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not read personAuthority" + + PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when reading " + + "personAuthority, Status:"+ statusCode); + } + PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); + personAuthority = (PersonauthoritiesCommon) extractPart(input, + client.getCommonPartName(), PersonauthoritiesCommon.class); + } catch (Exception e) { + throw new RuntimeException("Could not read personAuthority: ", e); + } + + return personAuthority; + } + + private PersonsCommonList readItemsInPersonAuth(String personAuthId) { + + // Expected status code: 200 OK + int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; + + // Submit the request to the service and store the response. + ClientResponse res = client.readItemList(personAuthId, "", ""); //TODO: Laramie201007289 added empty strings to satisfy api + PersonsCommonList list = res.getEntity(); + + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not read items in personAuthority: " + + PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when reading " + + "items in personAuthority, Status:"+ statusCode); + } + + return list; + } + + private List readPersonIds(PersonsCommonList list) { + + List ids = new ArrayList(); + List items = + list.getPersonListItem(); + for (PersonsCommonList.PersonListItem item : items) { + ids.add(item.getCsid()); + } + return ids; + } + + // --------------------------------------------------------------- + // Delete + // --------------------------------------------------------------- + + private void deletePersonAuthority(String vcsid) { + // Expected status code: 200 OK + int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE; + + ClientResponse res = client.delete(vcsid); + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not delete personAuthority: " + + PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when deleting " + + "personAuthority, Status:"+ statusCode); + } + } + + private void deleteAllPersonAuthorities() { + List ids = readPersonAuthorityIds(readPersonAuthorities()); + for (String id : ids) { + deletePersonAuthority(id); + } + } + + private void deletePerson(String vcsid, String itemcsid) { + // Expected status code: 200 OK + int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE; + + ClientResponse res = client.deleteItem(vcsid, itemcsid); + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not delete personAuthority item: " + + PersonAuthorityClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when deleting " + + "personAuthority item, Status:"+ statusCode); + } + } + + private void deleteAllItemsForPersonAuth(String personAuthId) { + List itemIds = readPersonIds(readItemsInPersonAuth(personAuthId)); + for (String itemId : itemIds) { + deletePerson(personAuthId, itemId); + } + } + + // --------------------------------------------------------------- + // Utility methods used by tests above + // --------------------------------------------------------------- + + /* + private PoxPayloadOut createPersonAuthorityInstance( + String displayName, String refName ) { + PersonauthoritiesCommon personAuthority = new PersonauthoritiesCommon(); + personAuthority.setDisplayName(displayName); + personAuthority.setRefName(refName); + personAuthority.setVocabType("PersonAuthority"); + PoxPayloadOut multipart = new PoxPayloadOut(); + OutputPart commonPart = multipart.addPart(personAuthority, MediaType.APPLICATION_XML_TYPE); + commonPart.getHeaders().add("label", client.getCommonPartName()); + + if(logger.isDebugEnabled()){ + logger.debug("to be created, personAuthority common ", + personAuthority, PersonauthoritiesCommon.class); + } + + return multipart; + } + */ + + private PoxPayloadOut createPersonInstance(String inAuthority, + String refName, Map personInfo ) { + PersonsCommon person = new PersonsCommon(); + person.setInAuthority(inAuthority); + person.setRefName(refName); + String value = null; + if((value = (String)personInfo.get(PersonJAXBSchema.FORE_NAME))!=null) + person.setForeName(value); + if((value = (String)personInfo.get(PersonJAXBSchema.MIDDLE_NAME))!=null) + person.setMiddleName(value); + if((value = (String)personInfo.get(PersonJAXBSchema.SUR_NAME))!=null) + person.setSurName(value); + if((value = (String)personInfo.get(PersonJAXBSchema.INITIALS))!=null) + person.setInitials(value); + if((value = (String)personInfo.get(PersonJAXBSchema.SALUTATIONS))!=null) + person.setSalutation(value); + if((value = (String)personInfo.get(PersonJAXBSchema.TITLE))!=null) + person.setTitle(value); + if((value = (String)personInfo.get(PersonJAXBSchema.NAME_ADDITIONS))!=null) + person.setNameAdditions(value); + if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_DATE))!=null) { + StructuredDateGroup birthDate = new StructuredDateGroup(); + birthDate.setDateDisplayDate(value); + person.setBirthDateGroup(birthDate); + } + if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_DATE))!=null) { + StructuredDateGroup deathDate = new StructuredDateGroup(); + deathDate.setDateDisplayDate(value); + person.setDeathDateGroup(deathDate); + } + if((value = (String)personInfo.get(PersonJAXBSchema.BIRTH_PLACE))!=null) + person.setBirthPlace(value); + if((value = (String)personInfo.get(PersonJAXBSchema.DEATH_PLACE))!=null) + person.setDeathPlace(value); + + /* TODO: Laramie20100728 removed missing member calls + if((value = (String)personInfo.get(PersonJAXBSchema.GROUP))!=null) + person.setGroup(value); + if((value = (String)personInfo.get(PersonJAXBSchema.NATIONALITY))!=null) + person.setNationality(value); + if((value = (String)personInfo.get(PersonJAXBSchema.OCCUPATION))!=null) + person.setOccupation(value); + if((value = (String)personInfo.get(PersonJAXBSchema.SCHOOL_OR_STYLE))!=null) + person.setSchoolOrStyle(value); + */ + + if((value = (String)personInfo.get(PersonJAXBSchema.GENDER))!=null) + person.setGender(value); + if((value = (String)personInfo.get(PersonJAXBSchema.BIO_NOTE))!=null) + person.setBioNote(value); + if((value = (String)personInfo.get(PersonJAXBSchema.NAME_NOTE))!=null) + person.setNameNote(value); + PoxPayloadOut multipart = new PoxPayloadOut(); + OutputPart commonPart = multipart.addPart(person, + MediaType.APPLICATION_XML_TYPE); + commonPart.getHeaders().add("label", client.getItemCommonPartName()); + + if(logger.isDebugEnabled()){ + logger.debug("to be created, person common"+person); + } + + return multipart; + } + + // Retrieve individual fields of personAuthority records. + + private String displayAllPersonAuthorities(PersonauthoritiesCommonList list) { + StringBuffer sb = new StringBuffer(); + List personAuthorities = + list.getPersonauthorityListItem(); + int i = 0; + for (PersonauthoritiesCommonList.PersonauthorityListItem personAuthority : personAuthorities) { + sb.append("personAuthority [" + i + "]" + "\n"); + sb.append(displayPersonAuthorityDetails(personAuthority)); + i++; + } + return sb.toString(); + } + + private String displayPersonAuthorityDetails( + PersonauthoritiesCommonList.PersonauthorityListItem personAuthority) { + StringBuffer sb = new StringBuffer(); + sb.append("displayName=" + personAuthority.getDisplayName() + "\n"); + sb.append("vocabType=" + personAuthority.getVocabType() + "\n"); + // sb.append("csid=" + personAuthority.getCsid() + "\n"); + sb.append("URI=" + personAuthority.getUri() + "\n"); + return sb.toString(); + } + + // Retrieve individual fields of person records. + + private String displayAllPersons(PersonsCommonList list) { + StringBuffer sb = new StringBuffer(); + List items = + list.getPersonListItem(); + int i = 0; + for (PersonsCommonList.PersonListItem item : items) { + sb.append("person [" + i + "]" + "\n"); + sb.append(displayPersonDetails(item)); + i++; + } + return sb.toString(); + } + + private String displayPersonDetails( + PersonsCommonList.PersonListItem item) { + StringBuffer sb = new StringBuffer(); + sb.append("csid=" + item.getCsid() + "\n"); + sb.append("displayName=" + item.getDisplayName() + "\n"); + // sb.append("URI=" + item.getUri() + "\n"); + return sb.toString(); + } + + private Object extractPart(PoxPayloadIn input, String label, + Class clazz) throws Exception { + Object obj = null; + for(InputPart part : input.getParts()){ + String partLabel = part.getHeaders().getFirst("label"); + if(label.equalsIgnoreCase(partLabel)){ + String partStr = part.getBodyAsString(); + if(logger.isDebugEnabled()){ + logger.debug("extracted part str=\n" + partStr); + } + obj = part.getBody(clazz, null); + if(logger.isDebugEnabled()){ + logger.debug("extracted part obj=\n", obj, clazz); + } + break; + } + } + return obj; + } + + public static void main(String[] args) { + + // Configure logging. + BasicConfigurator.configure(); + + logger.info("PersonAuthority Sample starting..."); + + Sample sample = new Sample(); + PersonauthoritiesCommonList personAuthorities; + List personAuthIds; + String details = ""; + + // Optionally delete all personAuthorities and persons. + + boolean ENABLE_DELETE_ALL = false; + if (ENABLE_DELETE_ALL) { + + logger.info("Deleting all persons and personAuthorities ..."); + + // For each personAuthority ... + personAuthorities = sample.readPersonAuthorities(); + personAuthIds = sample.readPersonAuthorityIds(personAuthorities); + for (String personAuthId : personAuthIds) { + logger.info("Deleting all persons for personAuthority ..."); + sample.deleteAllItemsForPersonAuth(personAuthId); + logger.info("Deleting personAuthority ..."); + sample.deletePersonAuthority(personAuthId); + } + + logger.info("Reading personAuthorities after deletion ..."); + personAuthorities = sample.readPersonAuthorities(); + details = sample.displayAllPersonAuthorities(personAuthorities); + logger.info(details); + + logger.info("Reading items in each personAuthority after deletion ..."); + personAuthIds = sample.readPersonAuthorityIds(personAuthorities); + for (String personAuthId : personAuthIds) { + PersonsCommonList items = sample.readItemsInPersonAuth(personAuthId); + details = sample.displayAllPersons(items); + logger.info(details); + } + + } + + // Create new authorities, each populated with persons. + + Map johnWayneMap = new HashMap(); + johnWayneMap.put(PersonJAXBSchema.FORE_NAME, "John"); + johnWayneMap.put(PersonJAXBSchema.SUR_NAME, "Wayne"); + johnWayneMap.put(PersonJAXBSchema.GENDER, "male"); + Map patrickSchmitzMap = new HashMap(); + patrickSchmitzMap.put(PersonJAXBSchema.FORE_NAME, "Patrick"); + patrickSchmitzMap.put(PersonJAXBSchema.SUR_NAME, "Schmitz"); + patrickSchmitzMap.put(PersonJAXBSchema.GENDER, "male"); + Map janeDoeMap = new HashMap(); + janeDoeMap.put(PersonJAXBSchema.FORE_NAME, "Jane"); + janeDoeMap.put(PersonJAXBSchema.SUR_NAME, "Doe"); + janeDoeMap.put(PersonJAXBSchema.GENDER, "female"); + List> personsMaps = + Arrays.asList(johnWayneMap, patrickSchmitzMap, janeDoeMap ); + + sample.createPersonAuthority("Sample Person Auth", personsMaps); + + logger.info("PersonAuthority Sample complete."); + + logger.info("Reading personAuthorities and items ..."); + // Get a list of personAuthorities. + personAuthorities = sample.readPersonAuthorities(); + // For each personAuthority ... + for (PersonauthoritiesCommonList.PersonauthorityListItem + personAuthority : personAuthorities.getPersonauthorityListItem()) { + // Get its display name. + logger.info(personAuthority.getDisplayName()); + // Get a list of the persons in this personAuthority. + PersonsCommonList items = + sample.readItemsInPersonAuth(personAuthority.getCsid()); + // For each person ... + for (PersonsCommonList.PersonListItem + item : items.getPersonListItem()) { + // Get its short name. + logger.info(" " + item.getDisplayName()); + } + } + + // Sample alternate methods of reading all personAuthorities and + // persons separately. + boolean RUN_ADDITIONAL_SAMPLES = false; + if (RUN_ADDITIONAL_SAMPLES) { + + logger.info("Reading all personAuthorities ..."); + details = sample.displayAllPersonAuthorities(personAuthorities); + logger.info(details); + + logger.info("Reading all persons ..."); + personAuthIds = sample.readPersonAuthorityIds(personAuthorities); + for (String personAuthId : personAuthIds) { + PersonsCommonList items = sample.readItemsInPersonAuth(personAuthId); + details = sample.displayAllPersons(items); + logger.info(details); + } + + } + + } + +} diff --git a/services/person/sample/sample/src/main/resources/collectionspace-client.properties b/services/person/sample/sample/src/main/resources/collectionspace-client.properties index 429b9f6fe..927081034 100644 --- a/services/person/sample/sample/src/main/resources/collectionspace-client.properties +++ b/services/person/sample/sample/src/main/resources/collectionspace-client.properties @@ -1,6 +1,6 @@ -#url of the collectionspace server -cspace.url=http://localhost:8180/cspace-services/ -cspace.ssl=false -cspace.auth=false -cspace.user=test +#url of the collectionspace server +cspace.url=http://localhost:8180/cspace-services/ +cspace.ssl=false +cspace.auth=false +cspace.user=test cspace.password=test \ No newline at end of file diff --git a/services/person/sample/sample/src/main/resources/log4j.xml b/services/person/sample/sample/src/main/resources/log4j.xml index f3969c91a..708c1601b 100644 --- a/services/person/sample/sample/src/main/resources/log4j.xml +++ b/services/person/sample/sample/src/main/resources/log4j.xml @@ -1,38 +1,38 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/person/service/pom.xml b/services/person/service/pom.xml index 7682b55cc..c9d879cf8 100644 --- a/services/person/service/pom.xml +++ b/services/person/service/pom.xml @@ -1,133 +1,133 @@ - - - - org.collectionspace.services - org.collectionspace.services.person - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.person.service - services.person.service - jar - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authority.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.person.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.person.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.contact.service - ${project.version} - - - - junit - junit - 4.1 - test - - - org.testng - testng - - - - - commons-beanutils - commons-beanutils - 1.6.1 - - - - commons-logging - commons-logging - 1.1 - - - - - - javax.security - jaas - 1.0.01 - provided - - - - dom4j - dom4j - 1.6.1 - provided - - - - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - - - org.nuxeo.ecm.core - nuxeo-core-api - - - jboss-remoting - jboss - - - - - - - - collectionspace-services-person - - - - - + + + + org.collectionspace.services + org.collectionspace.services.person + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.person.service + services.person.service + jar + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authority.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.person.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.person.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.contact.service + ${project.version} + + + + junit + junit + 4.1 + test + + + org.testng + testng + + + + + commons-beanutils + commons-beanutils + 1.6.1 + + + + commons-logging + commons-logging + 1.1 + + + + + + javax.security + jaas + 1.0.01 + provided + + + + dom4j + dom4j + 1.6.1 + provided + + + + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + + + org.nuxeo.ecm.core + nuxeo-core-api + + + jboss-remoting + jboss + + + + + + + + collectionspace-services-person + + + + + diff --git a/services/query/.classpath b/services/query/.classpath index d8f291998..a225f00db 100644 --- a/services/query/.classpath +++ b/services/query/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/query/.project b/services/query/.project index 03ef415b1..e5cc78d37 100644 --- a/services/query/.project +++ b/services/query/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.query - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.query + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/query/pom.xml b/services/query/pom.xml index d2eb8b0c1..dd72f1a2d 100644 --- a/services/query/pom.xml +++ b/services/query/pom.xml @@ -1,28 +1,28 @@ - - - - org.collectionspace.services.main - org.collectionspace.services - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.query - services.query - pom - - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - - - service - - - - + + + + org.collectionspace.services.main + org.collectionspace.services + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.query + services.query + pom + + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + + + service + + + + diff --git a/services/query/service/pom.xml b/services/query/service/pom.xml index 51a66b30a..c1dbcf5cc 100644 --- a/services/query/service/pom.xml +++ b/services/query/service/pom.xml @@ -1,91 +1,91 @@ - - - - org.collectionspace.services - org.collectionspace.services.query - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.query.service - services.query.service - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - org.testng - testng - - - - - commons-beanutils - commons-beanutils - 1.6.1 - - - - commons-logging - commons-logging - 1.1 - - - - - - - - - - org.jboss.resteasy - jaxrs-api - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - - collectionspace-services-query - - - + + + + org.collectionspace.services + org.collectionspace.services.query + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.query.service + services.query.service + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + org.testng + testng + + + + + commons-beanutils + commons-beanutils + 1.6.1 + + + + commons-logging + commons-logging + 1.1 + + + + + + + + + + org.jboss.resteasy + jaxrs-api + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + + collectionspace-services-query + + + diff --git a/services/relation/.classpath b/services/relation/.classpath index 046988541..25df93560 100644 --- a/services/relation/.classpath +++ b/services/relation/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/relation/.project b/services/relation/.project index 666fb035b..09f14dc9c 100644 --- a/services/relation/.project +++ b/services/relation/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.relation - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.relation + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/relation/3rdparty/.classpath b/services/relation/3rdparty/.classpath index d7501e2c4..b8a2888f8 100644 --- a/services/relation/3rdparty/.classpath +++ b/services/relation/3rdparty/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/relation/3rdparty/.project b/services/relation/3rdparty/.project index 21a9fcf9e..51f850bc9 100644 --- a/services/relation/3rdparty/.project +++ b/services/relation/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.relation.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.relation.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/relation/3rdparty/build.xml b/services/relation/3rdparty/build.xml index a377252d3..0b72b72d5 100644 --- a/services/relation/3rdparty/build.xml +++ b/services/relation/3rdparty/build.xml @@ -1,128 +1,128 @@ - - - - relation service 3rdparty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + relation service 3rdparty + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/relation/3rdparty/nuxeo-platform-cs-relation/build.xml b/services/relation/3rdparty/nuxeo-platform-cs-relation/build.xml index d2906b474..275650b20 100644 --- a/services/relation/3rdparty/nuxeo-platform-cs-relation/build.xml +++ b/services/relation/3rdparty/nuxeo-platform-cs-relation/build.xml @@ -1,137 +1,137 @@ - - - - relation nuxeo document type - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + relation nuxeo document type + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/relation/3rdparty/nuxeo-platform-cs-relation/pom.xml b/services/relation/3rdparty/nuxeo-platform-cs-relation/pom.xml index e41188208..8db284a39 100644 --- a/services/relation/3rdparty/nuxeo-platform-cs-relation/pom.xml +++ b/services/relation/3rdparty/nuxeo-platform-cs-relation/pom.xml @@ -1,42 +1,42 @@ - - - org.collectionspace.services - org.collectionspace.services.relation.3rdparty - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.relation.3rdparty.nuxeo - services.relation.3rdparty.nuxeo - jar - - CollectionSpace relation Nuxeo document type. - - - - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-jar-plugin - - - src/main/resources/META-INF/MANIFEST.MF - - ${eclipseVersion} - 2 - - - - - - - + + + org.collectionspace.services + org.collectionspace.services.relation.3rdparty + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.relation.3rdparty.nuxeo + services.relation.3rdparty.nuxeo + jar + + CollectionSpace relation Nuxeo document type. + + + + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-jar-plugin + + + src/main/resources/META-INF/MANIFEST.MF + + ${eclipseVersion} + 2 + + + + + + + diff --git a/services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/META-INF/MANIFEST.MF b/services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/META-INF/MANIFEST.MF index 180b0bd15..0ad9895f8 100644 --- a/services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/META-INF/MANIFEST.MF +++ b/services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/META-INF/MANIFEST.MF @@ -1,23 +1,23 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 1 -Bundle-Name: nuxeo-platform-cs-relation -Bundle-SymbolicName: org.collectionspace.relation;singleton:=true -Bundle-Version: 1.0.0 -Bundle-Localization: plugin -Bundle-Vendor: Nuxeo -Require-Bundle: org.nuxeo.runtime, - org.nuxeo.ecm.core.api, - org.nuxeo.ecm.core, - org.nuxeo.ecm.core.api, - org.nuxeo.ecm.platform.types.api, - org.nuxeo.ecm.platform.versioning.api, - org.nuxeo.ecm.platform.ui, - org.nuxeo.ecm.platform.forms.layout.client, - org.nuxeo.ecm.platform.ws, - org.collectionspace.collectionspace_core -Provide-Package: org.collectionspace.relation -Nuxeo-Component: OSGI-INF/core-types-contrib.xml, - OSGI-INF/life-cycle-contrib.xml, - OSGI-INF/ecm-types-contrib.xml, - OSGI-INF/layouts-contrib.xml - +Manifest-Version: 1.0 +Bundle-ManifestVersion: 1 +Bundle-Name: nuxeo-platform-cs-relation +Bundle-SymbolicName: org.collectionspace.relation;singleton:=true +Bundle-Version: 1.0.0 +Bundle-Localization: plugin +Bundle-Vendor: Nuxeo +Require-Bundle: org.nuxeo.runtime, + org.nuxeo.ecm.core.api, + org.nuxeo.ecm.core, + org.nuxeo.ecm.core.api, + org.nuxeo.ecm.platform.types.api, + org.nuxeo.ecm.platform.versioning.api, + org.nuxeo.ecm.platform.ui, + org.nuxeo.ecm.platform.forms.layout.client, + org.nuxeo.ecm.platform.ws, + org.collectionspace.collectionspace_core +Provide-Package: org.collectionspace.relation +Nuxeo-Component: OSGI-INF/core-types-contrib.xml, + OSGI-INF/life-cycle-contrib.xml, + OSGI-INF/ecm-types-contrib.xml, + OSGI-INF/layouts-contrib.xml + diff --git a/services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/schemas/relations_common.xsd b/services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/schemas/relations_common.xsd index 359946fc1..4840c01df 100644 --- a/services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/schemas/relations_common.xsd +++ b/services/relation/3rdparty/nuxeo-platform-cs-relation/src/main/resources/schemas/relations_common.xsd @@ -1,71 +1,71 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/relation/build.xml b/services/relation/build.xml index 21c483029..e01a1353f 100644 --- a/services/relation/build.xml +++ b/services/relation/build.xml @@ -1,125 +1,125 @@ - - - - relationship service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + relationship service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/relation/client/pom.xml b/services/relation/client/pom.xml index f0d47d297..8f0f0d72f 100644 --- a/services/relation/client/pom.xml +++ b/services/relation/client/pom.xml @@ -1,88 +1,88 @@ - - - - org.collectionspace.services - org.collectionspace.services.relation - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.relation.client - services.relation.client - - - - - org.slf4j - slf4j-api - provided - - - org.slf4j - slf4j-log4j12 - provided - - - - org.collectionspace.services - org.collectionspace.services.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.person.client - ${project.version} - test - - - org.collectionspace.services - org.collectionspace.services.authority.jaxb - true - ${project.version} - - - - - - org.testng - testng - test - - - org.jboss.resteasy - resteasy-jaxrs - - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - commons-httpclient - commons-httpclient - 3.1 - - - - - cspace-services-relation-client - - + + + + org.collectionspace.services + org.collectionspace.services.relation + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.relation.client + services.relation.client + + + + + org.slf4j + slf4j-api + provided + + + org.slf4j + slf4j-log4j12 + provided + + + + org.collectionspace.services + org.collectionspace.services.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.person.client + ${project.version} + test + + + org.collectionspace.services + org.collectionspace.services.authority.jaxb + true + ${project.version} + + + + + + org.testng + testng + test + + + org.jboss.resteasy + resteasy-jaxrs + + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + commons-httpclient + commons-httpclient + 3.1 + + + + + cspace-services-relation-client + + diff --git a/services/relation/client/src/test/resources/log4j.properties b/services/relation/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/relation/client/src/test/resources/log4j.properties +++ b/services/relation/client/src/test/resources/log4j.properties @@ -1,23 +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 +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/pom.xml b/services/relation/pom.xml index 6471ecfb4..ff21fa673 100644 --- a/services/relation/pom.xml +++ b/services/relation/pom.xml @@ -1,22 +1,22 @@ - - - - org.collectionspace.services - org.collectionspace.services.main - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.relation - services.relation - pom - - - service - 3rdparty - client - - - - + + + + org.collectionspace.services + org.collectionspace.services.main + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.relation + services.relation + pom + + + service + 3rdparty + client + + + + diff --git a/services/relation/service/pom.xml b/services/relation/service/pom.xml index 4498491fd..f11162d69 100644 --- a/services/relation/service/pom.xml +++ b/services/relation/service/pom.xml @@ -1,49 +1,49 @@ - - - - org.collectionspace.services - org.collectionspace.services.relation - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.relation.service - services.relation.service - jar - - - - org.collectionspace.services - org.collectionspace.services.config - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - - - junit - junit - 4.1 - test - - - org.testng - testng - - - - org.collectionspace.services - org.collectionspace.services.person.client - ${project.version} - + + + + org.collectionspace.services + org.collectionspace.services.relation + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.relation.service + services.relation.service + jar + + + + org.collectionspace.services + org.collectionspace.services.config + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + + + junit + junit + 4.1 + test + + + org.testng + testng + + + + org.collectionspace.services + org.collectionspace.services.person.client + ${project.version} + org.collectionspace.services @@ -51,91 +51,91 @@ ${project.version} - - org.collectionspace.services - org.collectionspace.services.organization.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.location.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.place.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.work.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.taxonomy.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.concept.client - ${project.version} - - - - - - - javax.security - jaas - 1.0.01 - provided - - - - dom4j - dom4j - 1.6.1 - provided - - - - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - - - org.nuxeo.ecm.core - nuxeo-core-api - - - jboss-remoting - jboss - - - - - - - - collectionspace-services-relation - - + + org.collectionspace.services + org.collectionspace.services.organization.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.location.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.place.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.work.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.taxonomy.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.concept.client + ${project.version} + + + + + + + javax.security + jaas + 1.0.01 + provided + + + + dom4j + dom4j + 1.6.1 + provided + + + + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + + + org.nuxeo.ecm.core + nuxeo-core-api + + + jboss-remoting + jboss + + + + + + + + collectionspace-services-relation + + diff --git a/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationValidatorHandler.java b/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationValidatorHandler.java index c93a8bc1e..dff09ae20 100644 --- a/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationValidatorHandler.java +++ b/services/relation/service/src/main/java/org/collectionspace/services/relation/nuxeo/RelationValidatorHandler.java @@ -1,119 +1,119 @@ -package org.collectionspace.services.relation.nuxeo; - -//import junit.framework.Assert; -import org.collectionspace.services.client.PoxPayloadIn; -import org.collectionspace.services.client.PoxPayloadOut; -import org.collectionspace.services.common.document.InvalidDocumentException; -import org.collectionspace.services.common.document.ValidatorHandlerImpl; -import org.collectionspace.services.common.api.RefName.Authority; -import org.collectionspace.services.common.api.RefName.AuthorityItem; -import org.collectionspace.services.common.api.Tools; -import org.collectionspace.services.relation.RelationsCommon; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -//import org.testng.Assert; - -public class RelationValidatorHandler extends ValidatorHandlerImpl { - - /** The logger. */ - private final Logger logger = LoggerFactory.getLogger(RelationValidatorHandler.class); - /* Error messages - */ - private static final String VALIDATION_ERROR = "The relation record payload was invalid. See log file for more details."; - private static final String SUBJECT_EQUALS_OBJECT_ERROR = "The subject ID and object ID cannot be the same."; - - @Override - protected Class getCommonPartClass() { - return RelationsCommon.class; - } - - @Override - protected void handleCreate() - throws InvalidDocumentException{ - try { - RelationsCommon relationsCommon = (RelationsCommon)getCommonPart(); - CS_ASSERT(relationsCommon != null); - if (logger.isTraceEnabled() == true) { - logger.trace(relationsCommon.toString()); - } - - String subjectCsid = relationsCommon.getSubjectCsid(); - String objectCsid = relationsCommon.getObjectCsid(); - - // If no CSID for a subject or object is included in the create payload, - // a refName must be provided for that subject or object as an alternate identifier. - CS_ASSERT(hasCsid(subjectCsid) || hasSubjectRefname(relationsCommon)); - CS_ASSERT(hasCsid(objectCsid) || hasObjectRefname(relationsCommon)); - - // The Subject identifier and Object ID must not be identical: - // that is, a resource cannot be related to itself. - if (hasCsid(subjectCsid) && hasCsid(objectCsid)) { - CS_ASSERT (subjectCsid.trim().equalsIgnoreCase(objectCsid.trim()) == false, - SUBJECT_EQUALS_OBJECT_ERROR); - } - - // A relationship type must be provided. - CS_ASSERT(relationsCommon.getRelationshipType() != null); - - } catch (AssertionError e) { - if (logger.isErrorEnabled() == true) { - logger.error(e.getMessage(), e); - } - throw new InvalidDocumentException(VALIDATION_ERROR, e); - } - } - - @Override - protected void handleGet() { - // TODO Auto-generated method stub - } - - @Override - protected void handleGetAll() { - // TODO Auto-generated method stub - } - - @Override - protected void handleUpdate() { - // TODO Auto-generated method stub - } - - @Override - protected void handleDelete() { - // TODO Auto-generated method stub - } - - private boolean hasCsid(String csid) { - boolean hasCsid = false; - if (Tools.notBlank(csid)) { - hasCsid = true; - } - return hasCsid; - } - - private boolean hasSubjectRefname(RelationsCommon relationsCommon) { - String subjectRefName = relationsCommon.getSubjectRefName(); - return hasRefName(subjectRefName); - } - - private boolean hasObjectRefname(RelationsCommon relationsCommon) { - String objectRefName = relationsCommon.getObjectRefName(); - return hasRefName(objectRefName); - } - - private boolean hasRefName(String refName) { - boolean hasRefname = false; - if (Tools.isBlank(refName)) { - return hasRefname; - } else { - Authority authority = Authority.parse(refName); - AuthorityItem authItem = AuthorityItem.parse(refName); - if (authority != null || authItem != null) { - hasRefname = true; - } - return hasRefname; - } - - } -} +package org.collectionspace.services.relation.nuxeo; + +//import junit.framework.Assert; +import org.collectionspace.services.client.PoxPayloadIn; +import org.collectionspace.services.client.PoxPayloadOut; +import org.collectionspace.services.common.document.InvalidDocumentException; +import org.collectionspace.services.common.document.ValidatorHandlerImpl; +import org.collectionspace.services.common.api.RefName.Authority; +import org.collectionspace.services.common.api.RefName.AuthorityItem; +import org.collectionspace.services.common.api.Tools; +import org.collectionspace.services.relation.RelationsCommon; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +//import org.testng.Assert; + +public class RelationValidatorHandler extends ValidatorHandlerImpl { + + /** The logger. */ + private final Logger logger = LoggerFactory.getLogger(RelationValidatorHandler.class); + /* Error messages + */ + private static final String VALIDATION_ERROR = "The relation record payload was invalid. See log file for more details."; + private static final String SUBJECT_EQUALS_OBJECT_ERROR = "The subject ID and object ID cannot be the same."; + + @Override + protected Class getCommonPartClass() { + return RelationsCommon.class; + } + + @Override + protected void handleCreate() + throws InvalidDocumentException{ + try { + RelationsCommon relationsCommon = (RelationsCommon)getCommonPart(); + CS_ASSERT(relationsCommon != null); + if (logger.isTraceEnabled() == true) { + logger.trace(relationsCommon.toString()); + } + + String subjectCsid = relationsCommon.getSubjectCsid(); + String objectCsid = relationsCommon.getObjectCsid(); + + // If no CSID for a subject or object is included in the create payload, + // a refName must be provided for that subject or object as an alternate identifier. + CS_ASSERT(hasCsid(subjectCsid) || hasSubjectRefname(relationsCommon)); + CS_ASSERT(hasCsid(objectCsid) || hasObjectRefname(relationsCommon)); + + // The Subject identifier and Object ID must not be identical: + // that is, a resource cannot be related to itself. + if (hasCsid(subjectCsid) && hasCsid(objectCsid)) { + CS_ASSERT (subjectCsid.trim().equalsIgnoreCase(objectCsid.trim()) == false, + SUBJECT_EQUALS_OBJECT_ERROR); + } + + // A relationship type must be provided. + CS_ASSERT(relationsCommon.getRelationshipType() != null); + + } catch (AssertionError e) { + if (logger.isErrorEnabled() == true) { + logger.error(e.getMessage(), e); + } + throw new InvalidDocumentException(VALIDATION_ERROR, e); + } + } + + @Override + protected void handleGet() { + // TODO Auto-generated method stub + } + + @Override + protected void handleGetAll() { + // TODO Auto-generated method stub + } + + @Override + protected void handleUpdate() { + // TODO Auto-generated method stub + } + + @Override + protected void handleDelete() { + // TODO Auto-generated method stub + } + + private boolean hasCsid(String csid) { + boolean hasCsid = false; + if (Tools.notBlank(csid)) { + hasCsid = true; + } + return hasCsid; + } + + private boolean hasSubjectRefname(RelationsCommon relationsCommon) { + String subjectRefName = relationsCommon.getSubjectRefName(); + return hasRefName(subjectRefName); + } + + private boolean hasObjectRefname(RelationsCommon relationsCommon) { + String objectRefName = relationsCommon.getObjectRefName(); + return hasRefName(objectRefName); + } + + private boolean hasRefName(String refName) { + boolean hasRefname = false; + if (Tools.isBlank(refName)) { + return hasRefname; + } else { + Authority authority = Authority.parse(refName); + AuthorityItem authItem = AuthorityItem.parse(refName); + if (authority != null || authItem != null) { + hasRefname = true; + } + return hasRefname; + } + + } +} diff --git a/services/report/.classpath b/services/report/.classpath index 046988541..25df93560 100644 --- a/services/report/.classpath +++ b/services/report/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/report/.project b/services/report/.project index a970c72fb..7e4e4f732 100644 --- a/services/report/.project +++ b/services/report/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.report - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.report + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/report/3rdparty/.classpath b/services/report/3rdparty/.classpath index 046988541..25df93560 100644 --- a/services/report/3rdparty/.classpath +++ b/services/report/3rdparty/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/report/3rdparty/.project b/services/report/3rdparty/.project index 887c666a0..a665ec42d 100644 --- a/services/report/3rdparty/.project +++ b/services/report/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.report.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.report.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/report/3rdparty/build.xml b/services/report/3rdparty/build.xml index 4051538af..83c710cce 100644 --- a/services/report/3rdparty/build.xml +++ b/services/report/3rdparty/build.xml @@ -1,142 +1,142 @@ - - - report service 3rdparty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + report service 3rdparty + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/report/3rdparty/nuxeo-platform-cs-report/src/main/resources/META-INF/MANIFEST.MF b/services/report/3rdparty/nuxeo-platform-cs-report/src/main/resources/META-INF/MANIFEST.MF index 1cca8161d..3035f14fd 100644 --- a/services/report/3rdparty/nuxeo-platform-cs-report/src/main/resources/META-INF/MANIFEST.MF +++ b/services/report/3rdparty/nuxeo-platform-cs-report/src/main/resources/META-INF/MANIFEST.MF @@ -1,23 +1,23 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 1 -Bundle-Name: NuxeoCS -Bundle-SymbolicName: org.collectionspace.report;singleton:=true -Bundle-Version: 1.0.0 -Bundle-Localization: plugin -Bundle-Vendor: Nuxeo -Require-Bundle: org.nuxeo.runtime, - org.nuxeo.ecm.core.api, - org.nuxeo.ecm.core, - org.nuxeo.ecm.core.api, - org.nuxeo.ecm.platform.types.api, - org.nuxeo.ecm.platform.versioning.api, - org.nuxeo.ecm.platform.ui, - org.nuxeo.ecm.platform.forms.layout.client, - org.nuxeo.ecm.platform.ws, - org.collectionspace.collectionspace_core -Provide-Package: org.collectionspace.report -Nuxeo-Component: OSGI-INF/core-types-contrib.xml, - OSGI-INF/life-cycle-contrib.xml, - OSGI-INF/ecm-types-contrib.xml, - OSGI-INF/layouts-contrib.xml - +Manifest-Version: 1.0 +Bundle-ManifestVersion: 1 +Bundle-Name: NuxeoCS +Bundle-SymbolicName: org.collectionspace.report;singleton:=true +Bundle-Version: 1.0.0 +Bundle-Localization: plugin +Bundle-Vendor: Nuxeo +Require-Bundle: org.nuxeo.runtime, + org.nuxeo.ecm.core.api, + org.nuxeo.ecm.core, + org.nuxeo.ecm.core.api, + org.nuxeo.ecm.platform.types.api, + org.nuxeo.ecm.platform.versioning.api, + org.nuxeo.ecm.platform.ui, + org.nuxeo.ecm.platform.forms.layout.client, + org.nuxeo.ecm.platform.ws, + org.collectionspace.collectionspace_core +Provide-Package: org.collectionspace.report +Nuxeo-Component: OSGI-INF/core-types-contrib.xml, + OSGI-INF/life-cycle-contrib.xml, + OSGI-INF/ecm-types-contrib.xml, + OSGI-INF/layouts-contrib.xml + diff --git a/services/report/3rdparty/nuxeo-platform-cs-report/src/main/resources/schemas/reports_common.xsd b/services/report/3rdparty/nuxeo-platform-cs-report/src/main/resources/schemas/reports_common.xsd index 3c2b75960..2c19db83f 100644 --- a/services/report/3rdparty/nuxeo-platform-cs-report/src/main/resources/schemas/reports_common.xsd +++ b/services/report/3rdparty/nuxeo-platform-cs-report/src/main/resources/schemas/reports_common.xsd @@ -1,40 +1,40 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/report/3rdparty/pom.xml b/services/report/3rdparty/pom.xml index 10fd62096..27aef3b38 100644 --- a/services/report/3rdparty/pom.xml +++ b/services/report/3rdparty/pom.xml @@ -1,24 +1,24 @@ - - - org.collectionspace.services.report - org.collectionspace.services - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.report.3rdparty - services.report.3rdparty - pom - - - 3rd party build for report service - - - - - - + + + org.collectionspace.services.report + org.collectionspace.services + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.report.3rdparty + services.report.3rdparty + pom + + + 3rd party build for report service + + + + + + diff --git a/services/report/build.xml b/services/report/build.xml index 74aaed852..4ee783710 100644 --- a/services/report/build.xml +++ b/services/report/build.xml @@ -1,124 +1,124 @@ - - - - report service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + report service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/report/client/pom.xml b/services/report/client/pom.xml index 281f041f6..82816f881 100644 --- a/services/report/client/pom.xml +++ b/services/report/client/pom.xml @@ -1,103 +1,103 @@ - - - - org.collectionspace.services - org.collectionspace.services.report - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.report.client - services.report.client - - - - - org.slf4j - slf4j-api - test - - - org.slf4j - slf4j-log4j12 - test - - - - org.collectionspace.services - org.collectionspace.services.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.common - true - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.report.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.person.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.acquisition.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.acquisition.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.organization.client - ${project.version} - - - - org.testng - testng - - - org.jboss.resteasy - resteasy-jaxrs - - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - commons-httpclient - commons-httpclient - - - - - collectionspace-services-report-client - - - + + + + org.collectionspace.services + org.collectionspace.services.report + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.report.client + services.report.client + + + + + org.slf4j + slf4j-api + test + + + org.slf4j + slf4j-log4j12 + test + + + + org.collectionspace.services + org.collectionspace.services.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.common + true + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.report.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.person.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.acquisition.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.acquisition.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.organization.client + ${project.version} + + + + org.testng + testng + + + org.jboss.resteasy + resteasy-jaxrs + + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + commons-httpclient + commons-httpclient + + + + + collectionspace-services-report-client + + + diff --git a/services/report/client/src/test/resources/log4j.properties b/services/report/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/report/client/src/test/resources/log4j.properties +++ b/services/report/client/src/test/resources/log4j.properties @@ -1,23 +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 +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/report/jaxb/src/main/java/org/collectionspace/services/ReportJAXBSchema.java b/services/report/jaxb/src/main/java/org/collectionspace/services/ReportJAXBSchema.java index d5a461fea..6a47fc84d 100644 --- a/services/report/jaxb/src/main/java/org/collectionspace/services/ReportJAXBSchema.java +++ b/services/report/jaxb/src/main/java/org/collectionspace/services/ReportJAXBSchema.java @@ -1,19 +1,19 @@ -/** - * - */ -package org.collectionspace.services; - -import org.collectionspace.services.jaxb.InvocableJAXBSchema; - -/** - * @author pschmitz - * - */ -public interface ReportJAXBSchema extends InvocableJAXBSchema { - final static String NAME = "name"; - final static String NOTES = "notes"; - final static String FILENAME = "filename"; - final static String OUTPUT_MIME = "outputMIME"; -} - - +/** + * + */ +package org.collectionspace.services; + +import org.collectionspace.services.jaxb.InvocableJAXBSchema; + +/** + * @author pschmitz + * + */ +public interface ReportJAXBSchema extends InvocableJAXBSchema { + final static String NAME = "name"; + final static String NOTES = "notes"; + final static String FILENAME = "filename"; + final static String OUTPUT_MIME = "outputMIME"; +} + + diff --git a/services/report/pom.xml b/services/report/pom.xml index 801d3961f..bb6b88936 100644 --- a/services/report/pom.xml +++ b/services/report/pom.xml @@ -1,63 +1,63 @@ - - - - - org.collectionspace.services - org.collectionspace.services.main - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.report - services.report - pom - - - - net.sf.jasperreports - jasperreports - 5.0.1 - - - itext - com.lowagie - - - - - - - net.sf.jasperreports - jasperreports-fonts - 4.0.0 - - - - com.lowagie - itext - 2.1.7 - - - - org.codehaus.groovy - groovy-all - 2.0.1 - - - - - - jaxb - service - 3rdparty - client - - - - + + + + + org.collectionspace.services + org.collectionspace.services.main + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.report + services.report + pom + + + + net.sf.jasperreports + jasperreports + 5.0.1 + + + itext + com.lowagie + + + + + + + net.sf.jasperreports + jasperreports-fonts + 4.0.0 + + + + com.lowagie + itext + 2.1.7 + + + + org.codehaus.groovy + groovy-all + 2.0.1 + + + + + + jaxb + service + 3rdparty + client + + + + diff --git a/services/report/service/pom.xml b/services/report/service/pom.xml index c5fdcc47b..5493c379f 100644 --- a/services/report/service/pom.xml +++ b/services/report/service/pom.xml @@ -1,116 +1,116 @@ - - - - - org.collectionspace.services - org.collectionspace.services.report - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.report.service - services.report.service - jar - - - - org.collectionspace.services - org.collectionspace.services.config - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authority.jaxb - true - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.report.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.report.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.collectionobject.jaxb - ${project.version} - - - - junit - junit - 4.1 - test - - - org.testng - testng - - - - - - javax.security - jaas - 1.0.01 - provided - - - - dom4j - dom4j - 1.6.1 - provided - - - - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - - - org.nuxeo.ecm.core - nuxeo-core-api - ${nuxeo.core.version} - - - jboss-remoting - jboss - - - - - - - - collectionspace-services-report - - - + + + + + org.collectionspace.services + org.collectionspace.services.report + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.report.service + services.report.service + jar + + + + org.collectionspace.services + org.collectionspace.services.config + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authority.jaxb + true + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.report.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.report.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.collectionobject.jaxb + ${project.version} + + + + junit + junit + 4.1 + test + + + org.testng + testng + + + + + + javax.security + jaas + 1.0.01 + provided + + + + dom4j + dom4j + 1.6.1 + provided + + + + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + + + org.nuxeo.ecm.core + nuxeo-core-api + ${nuxeo.core.version} + + + jboss-remoting + jboss + + + + + + + + collectionspace-services-report + + + diff --git a/services/report/service/src/main/java/org/collectionspace/services/report/nuxeo/ReportPostInitHandler.java b/services/report/service/src/main/java/org/collectionspace/services/report/nuxeo/ReportPostInitHandler.java index 2baf505b3..0f45f2fd1 100644 --- a/services/report/service/src/main/java/org/collectionspace/services/report/nuxeo/ReportPostInitHandler.java +++ b/services/report/service/src/main/java/org/collectionspace/services/report/nuxeo/ReportPostInitHandler.java @@ -1,82 +1,82 @@ -/** - * 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 - */ -package org.collectionspace.services.report.nuxeo; - -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -import org.collectionspace.services.common.ServiceMain; -import org.collectionspace.services.common.api.Tools; -import org.collectionspace.services.common.init.IInitHandler; -import org.collectionspace.services.common.init.InitHandler; -import org.collectionspace.services.common.storage.DatabaseProductType; -import org.collectionspace.services.common.storage.JDBCTools; - -import org.collectionspace.services.config.service.InitHandler.Params.Field; -import org.collectionspace.services.config.service.InitHandler.Params.Property; -import org.collectionspace.services.config.service.ServiceBindingType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * ReportPostInitHandler, post-init action to add grant reader access to DB - * - * In the configuration file, looks for a single Field declaration - * with a param value that has the name of the reader account/role. - * If not specified, it will assume 'reader'; - * - * $LastChangedRevision: 5103 $ - * $LastChangedDate: 2011-06-23 16:50:06 -0700 (Thu, 23 Jun 2011) $ - */ -public class ReportPostInitHandler extends InitHandler implements IInitHandler { - - final Logger logger = LoggerFactory.getLogger(ReportPostInitHandler.class); - - public static final String READER_ROLE_NAME_KEY = "readerRoleName"; - public static final String DEFAULT_READER_ROLE_NAME = "reader" + ServiceMain.getInstance().getCspaceInstanceId(); - private String readerRoleName = DEFAULT_READER_ROLE_NAME; - - /** See the class javadoc for this class: it shows the syntax supported in the configuration params. - */ - @Override - public void onRepositoryInitialized(String dataSourceName, - String repositoryName, - String cspaceInstanceId, - ServiceBindingType sbt, - List fields, - List propertyList) throws Exception { - //Check for existing privileges, and if not there, grant them - for(Property prop : propertyList) { - if(READER_ROLE_NAME_KEY.equals(prop.getKey())) { - String value = prop.getValue(); - if(Tools.notEmpty(value) && !DEFAULT_READER_ROLE_NAME.equals(value)){ - readerRoleName = value + ServiceMain.getInstance().getCspaceInstanceId(); - logger.debug("ReportPostInitHandler: overriding readerRoleName default value to use: " - + value); - } - } - } - String privilegeName = JDBCTools.DATABASE_SELECT_PRIVILEGE_NAME; - JDBCTools.grantPrivilegeToDatabaseUser(dataSourceName, repositoryName, cspaceInstanceId, privilegeName, readerRoleName); - } - - -} +/** + * 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 + */ +package org.collectionspace.services.report.nuxeo; + +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import org.collectionspace.services.common.ServiceMain; +import org.collectionspace.services.common.api.Tools; +import org.collectionspace.services.common.init.IInitHandler; +import org.collectionspace.services.common.init.InitHandler; +import org.collectionspace.services.common.storage.DatabaseProductType; +import org.collectionspace.services.common.storage.JDBCTools; + +import org.collectionspace.services.config.service.InitHandler.Params.Field; +import org.collectionspace.services.config.service.InitHandler.Params.Property; +import org.collectionspace.services.config.service.ServiceBindingType; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * ReportPostInitHandler, post-init action to add grant reader access to DB + * + * In the configuration file, looks for a single Field declaration + * with a param value that has the name of the reader account/role. + * If not specified, it will assume 'reader'; + * + * $LastChangedRevision: 5103 $ + * $LastChangedDate: 2011-06-23 16:50:06 -0700 (Thu, 23 Jun 2011) $ + */ +public class ReportPostInitHandler extends InitHandler implements IInitHandler { + + final Logger logger = LoggerFactory.getLogger(ReportPostInitHandler.class); + + public static final String READER_ROLE_NAME_KEY = "readerRoleName"; + public static final String DEFAULT_READER_ROLE_NAME = "reader" + ServiceMain.getInstance().getCspaceInstanceId(); + private String readerRoleName = DEFAULT_READER_ROLE_NAME; + + /** See the class javadoc for this class: it shows the syntax supported in the configuration params. + */ + @Override + public void onRepositoryInitialized(String dataSourceName, + String repositoryName, + String cspaceInstanceId, + ServiceBindingType sbt, + List fields, + List propertyList) throws Exception { + //Check for existing privileges, and if not there, grant them + for(Property prop : propertyList) { + if(READER_ROLE_NAME_KEY.equals(prop.getKey())) { + String value = prop.getValue(); + if(Tools.notEmpty(value) && !DEFAULT_READER_ROLE_NAME.equals(value)){ + readerRoleName = value + ServiceMain.getInstance().getCspaceInstanceId(); + logger.debug("ReportPostInitHandler: overriding readerRoleName default value to use: " + + value); + } + } + } + String privilegeName = JDBCTools.DATABASE_SELECT_PRIVILEGE_NAME; + JDBCTools.grantPrivilegeToDatabaseUser(dataSourceName, repositoryName, cspaceInstanceId, privilegeName, readerRoleName); + } + + +} diff --git a/services/report/service/src/main/java/org/collectionspace/services/report/nuxeo/ReportValidatorHandler.java b/services/report/service/src/main/java/org/collectionspace/services/report/nuxeo/ReportValidatorHandler.java index 9e4045ef8..f66fc5071 100644 --- a/services/report/service/src/main/java/org/collectionspace/services/report/nuxeo/ReportValidatorHandler.java +++ b/services/report/service/src/main/java/org/collectionspace/services/report/nuxeo/ReportValidatorHandler.java @@ -1,18 +1,18 @@ -package org.collectionspace.services.report.nuxeo; - -import org.collectionspace.services.common.context.ServiceContext; -import org.collectionspace.services.common.document.InvalidDocumentException; -import org.collectionspace.services.common.document.ValidatorHandler; -import org.collectionspace.services.common.document.DocumentHandler.Action; - -public class ReportValidatorHandler implements ValidatorHandler { - - @Override - public void validate(Action action, ServiceContext ctx) - throws InvalidDocumentException { - // TODO Auto-generated method stub - System.out.println("ReportValidatorHandler executed."); - - } - -} +package org.collectionspace.services.report.nuxeo; + +import org.collectionspace.services.common.context.ServiceContext; +import org.collectionspace.services.common.document.InvalidDocumentException; +import org.collectionspace.services.common.document.ValidatorHandler; +import org.collectionspace.services.common.document.DocumentHandler.Action; + +public class ReportValidatorHandler implements ValidatorHandler { + + @Override + public void validate(Action action, ServiceContext ctx) + throws InvalidDocumentException { + // TODO Auto-generated method stub + System.out.println("ReportValidatorHandler executed."); + + } + +} diff --git a/services/sdk/.classpath b/services/sdk/.classpath index d8f291998..a225f00db 100644 --- a/services/sdk/.classpath +++ b/services/sdk/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/sdk/pom.xml b/services/sdk/pom.xml index 9177229bf..389ecef9f 100644 --- a/services/sdk/pom.xml +++ b/services/sdk/pom.xml @@ -1,33 +1,33 @@ - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.sdk - pom - services.sdk - 4.2-SNAPSHOT - - - - libs-releases-local - libs-releases-local - http://nightly.collectionspace.org:8081/artifactory/libs-release-local - - - libs-snapshots-local - libs-snapshots-local - http://nightly.collectionspace.org:8081/artifactory/libs-snapshot-local - - - - - - samples - - sample - - - - - - + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.sdk + pom + services.sdk + 4.2-SNAPSHOT + + + + libs-releases-local + libs-releases-local + http://nightly.collectionspace.org:8081/artifactory/libs-release-local + + + libs-snapshots-local + libs-snapshots-local + http://nightly.collectionspace.org:8081/artifactory/libs-snapshot-local + + + + + + samples + + sample + + + + + + diff --git a/services/sdk/sample/.classpath b/services/sdk/sample/.classpath index 425cd1620..7c3d14f89 100644 --- a/services/sdk/sample/.classpath +++ b/services/sdk/sample/.classpath @@ -1,10 +1,10 @@ - - - - - - - - - - + + + + + + + + + + diff --git a/services/sdk/sample/pom.xml b/services/sdk/sample/pom.xml index 3653faae8..332e1a946 100644 --- a/services/sdk/sample/pom.xml +++ b/services/sdk/sample/pom.xml @@ -1,60 +1,60 @@ - - - 4.0.0 - org.collectionspace.services.client - org.collectionspace.services.client.sample - jar - client.sample - - - - org.collectionspace.services - org.collectionspace.services.collectionobject.client - - - org.slf4j - slf4j-simple - 1.5.2 - - - - - - libs-releases-local - libs-releases-local - http://nightly.collectionspace.org:8081/artifactory/libs-release-local - - true - - - false - - - - libs-snapshots-local - libs-snapshots-local - http://nightly.collectionspace.org:8081/artifactory/libs-snapshot-local - - false - - - true - - - - - - client-sample - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.7 - 1.7 - - - - - - + + + 4.0.0 + org.collectionspace.services.client + org.collectionspace.services.client.sample + jar + client.sample + + + + org.collectionspace.services + org.collectionspace.services.collectionobject.client + + + org.slf4j + slf4j-simple + 1.5.2 + + + + + + libs-releases-local + libs-releases-local + http://nightly.collectionspace.org:8081/artifactory/libs-release-local + + true + + + false + + + + libs-snapshots-local + libs-snapshots-local + http://nightly.collectionspace.org:8081/artifactory/libs-snapshot-local + + false + + + true + + + + + + client-sample + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.7 + 1.7 + + + + + + diff --git a/services/sdk/sample/src/main/java/org/collectionspace/services/sdk/sample/Sample.java b/services/sdk/sample/src/main/java/org/collectionspace/services/sdk/sample/Sample.java index 7a29f137c..28b800e39 100644 --- a/services/sdk/sample/src/main/java/org/collectionspace/services/sdk/sample/Sample.java +++ b/services/sdk/sample/src/main/java/org/collectionspace/services/sdk/sample/Sample.java @@ -1,229 +1,229 @@ -/** - * Sample.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.sdk.sample; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; - -import org.collectionspace.services.collectionobject.ObjectNameGroup; -import org.collectionspace.services.collectionobject.ObjectNameList; -import org.testng.Assert; - -import org.jboss.resteasy.client.ClientResponse; -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.collectionspace.services.client.CollectionObjectClient; -import org.collectionspace.services.collectionobject.CollectionobjectsCommon; -import org.collectionspace.services.collectionobject.CollectionobjectsCommonList; - -/** - * The Class Sample. - */ -public class Sample { - - /** The collection object client. */ - private static CollectionObjectClient collectionObjectClient = new CollectionObjectClient(); - - /** - * @param args - */ - public static void main(String[] args) { - - System.out.println("Base URL is: " - + collectionObjectClient.getBaseURL()); - - String csid = createCollectionObject(); - System.out.println("Created a new collection object with CSID=" + csid); - - CollectionobjectsCommon co = readCollectionObject(csid); - System.out.println("Got a collection object with CSID=" + csid); - - int status = updateCollectionObject(csid); - System.out.println("Updated the collection object with CSID=" + csid); - } - - /** - * Creates the collection object. - * - * @return the string - */ - static String createCollectionObject() { - String result = null; - - CollectionobjectsCommon co = new CollectionobjectsCommon(); - ObjectNameList onl = co.getObjectNameList(); - ObjectNameGroup ong = new ObjectNameGroup(); - ong.setObjectName("Keiko CollectionobjectsCommon"); - onl.getObjectNameGroup().add(ong); - - MultipartOutput multipart = new MultipartOutput(); - OutputPart commonPart = multipart.addPart(co, - MediaType.APPLICATION_XML_TYPE); - commonPart.getHeaders().add("label", - collectionObjectClient.getCommonPartName()); - - ClientResponse response = collectionObjectClient - .create(multipart); - Assert.assertEquals(response.getStatus(), Response.Status.CREATED - .getStatusCode()); - result = extractId(response); - - return result; - } - - /** - * Read collection object. - * - * @param csid - * the csid - * - * @return the collectionobjects common - */ - static CollectionobjectsCommon readCollectionObject(String csid) { - CollectionobjectsCommon result = null; - - ClientResponse response = collectionObjectClient - .read(csid); - Assert.assertEquals(response.getStatus(), Response.Status.OK - .getStatusCode()); - try { - MultipartInput input = (MultipartInput) response.getEntity(); - result = (CollectionobjectsCommon) extractPart(input, - collectionObjectClient.getCommonPartName(), - CollectionobjectsCommon.class); - } catch (Exception e) { - throw new RuntimeException(e); - } - - return result; - } - - /** - * Update collection object. - */ - static int updateCollectionObject(String csid) { - ClientResponse response = collectionObjectClient - .read(csid); - Assert.assertEquals(response.getStatus(), Response.Status.OK - .getStatusCode()); - - MultipartInput input = (MultipartInput) response.getEntity(); - CollectionobjectsCommon collectionObject = (CollectionobjectsCommon) extractPart( - input, collectionObjectClient.getCommonPartName(), - CollectionobjectsCommon.class); - Assert.assertNotNull(collectionObject); - - // Update the content of this resource. - collectionObject.setObjectNumber("updated-" - + collectionObject.getObjectNumber()); - String name = collectionObject.getObjectNameList().getObjectNameGroup().get(0).getObjectName(); - collectionObject.getObjectNameList().getObjectNameGroup().get(0).setObjectName("updated-"+ name); - - // Submit the request to the service and store the response. - MultipartOutput output = new MultipartOutput(); - OutputPart commonPart = output.addPart(collectionObject, - MediaType.APPLICATION_XML_TYPE); - commonPart.getHeaders().add("label", - collectionObjectClient.getCommonPartName()); - - response = collectionObjectClient.update(csid, output); - int statusCode = response.getStatus(); - - return statusCode; - } - - // - // Utility methods that belong somewhere in the SDK and NOT the sample. - // - - /** - * Extract id. - * - * @param res - * the res - * - * @return the string - */ - static String extractId(ClientResponse res) { - String result = null; - - try { - MultivaluedMap mvm = res.getMetadata(); - String uri = (String) ((ArrayList) mvm.get("Location")).get(0); - String[] segments = uri.split("/"); - result = segments[segments.length - 1]; - } catch (Exception e) { - e.printStackTrace(); - } - - return result; - } - - /** - * Extract part. - * - * @param input - * the input - * @param label - * the label - * @param clazz - * the clazz - * - * @return the object - * - * @throws Exception - * the exception - */ - static Object extractPart(MultipartInput input, String label, Class clazz) { - Object obj = null; - - try { - for (InputPart part : input.getParts()) { - String partLabel = part.getHeaders().getFirst("label"); - if (label.equalsIgnoreCase(partLabel)) { - String partStr = part.getBodyAsString(); - obj = part.getBody(clazz, null); - break; - } - } - } catch (Exception e) { - e.printStackTrace(); - } - - return obj; - } - -} +/** + * Sample.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.sdk.sample; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; + +import org.collectionspace.services.collectionobject.ObjectNameGroup; +import org.collectionspace.services.collectionobject.ObjectNameList; +import org.testng.Assert; + +import org.jboss.resteasy.client.ClientResponse; +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.collectionspace.services.client.CollectionObjectClient; +import org.collectionspace.services.collectionobject.CollectionobjectsCommon; +import org.collectionspace.services.collectionobject.CollectionobjectsCommonList; + +/** + * The Class Sample. + */ +public class Sample { + + /** The collection object client. */ + private static CollectionObjectClient collectionObjectClient = new CollectionObjectClient(); + + /** + * @param args + */ + public static void main(String[] args) { + + System.out.println("Base URL is: " + + collectionObjectClient.getBaseURL()); + + String csid = createCollectionObject(); + System.out.println("Created a new collection object with CSID=" + csid); + + CollectionobjectsCommon co = readCollectionObject(csid); + System.out.println("Got a collection object with CSID=" + csid); + + int status = updateCollectionObject(csid); + System.out.println("Updated the collection object with CSID=" + csid); + } + + /** + * Creates the collection object. + * + * @return the string + */ + static String createCollectionObject() { + String result = null; + + CollectionobjectsCommon co = new CollectionobjectsCommon(); + ObjectNameList onl = co.getObjectNameList(); + ObjectNameGroup ong = new ObjectNameGroup(); + ong.setObjectName("Keiko CollectionobjectsCommon"); + onl.getObjectNameGroup().add(ong); + + MultipartOutput multipart = new MultipartOutput(); + OutputPart commonPart = multipart.addPart(co, + MediaType.APPLICATION_XML_TYPE); + commonPart.getHeaders().add("label", + collectionObjectClient.getCommonPartName()); + + ClientResponse response = collectionObjectClient + .create(multipart); + Assert.assertEquals(response.getStatus(), Response.Status.CREATED + .getStatusCode()); + result = extractId(response); + + return result; + } + + /** + * Read collection object. + * + * @param csid + * the csid + * + * @return the collectionobjects common + */ + static CollectionobjectsCommon readCollectionObject(String csid) { + CollectionobjectsCommon result = null; + + ClientResponse response = collectionObjectClient + .read(csid); + Assert.assertEquals(response.getStatus(), Response.Status.OK + .getStatusCode()); + try { + MultipartInput input = (MultipartInput) response.getEntity(); + result = (CollectionobjectsCommon) extractPart(input, + collectionObjectClient.getCommonPartName(), + CollectionobjectsCommon.class); + } catch (Exception e) { + throw new RuntimeException(e); + } + + return result; + } + + /** + * Update collection object. + */ + static int updateCollectionObject(String csid) { + ClientResponse response = collectionObjectClient + .read(csid); + Assert.assertEquals(response.getStatus(), Response.Status.OK + .getStatusCode()); + + MultipartInput input = (MultipartInput) response.getEntity(); + CollectionobjectsCommon collectionObject = (CollectionobjectsCommon) extractPart( + input, collectionObjectClient.getCommonPartName(), + CollectionobjectsCommon.class); + Assert.assertNotNull(collectionObject); + + // Update the content of this resource. + collectionObject.setObjectNumber("updated-" + + collectionObject.getObjectNumber()); + String name = collectionObject.getObjectNameList().getObjectNameGroup().get(0).getObjectName(); + collectionObject.getObjectNameList().getObjectNameGroup().get(0).setObjectName("updated-"+ name); + + // Submit the request to the service and store the response. + MultipartOutput output = new MultipartOutput(); + OutputPart commonPart = output.addPart(collectionObject, + MediaType.APPLICATION_XML_TYPE); + commonPart.getHeaders().add("label", + collectionObjectClient.getCommonPartName()); + + response = collectionObjectClient.update(csid, output); + int statusCode = response.getStatus(); + + return statusCode; + } + + // + // Utility methods that belong somewhere in the SDK and NOT the sample. + // + + /** + * Extract id. + * + * @param res + * the res + * + * @return the string + */ + static String extractId(ClientResponse res) { + String result = null; + + try { + MultivaluedMap mvm = res.getMetadata(); + String uri = (String) ((ArrayList) mvm.get("Location")).get(0); + String[] segments = uri.split("/"); + result = segments[segments.length - 1]; + } catch (Exception e) { + e.printStackTrace(); + } + + return result; + } + + /** + * Extract part. + * + * @param input + * the input + * @param label + * the label + * @param clazz + * the clazz + * + * @return the object + * + * @throws Exception + * the exception + */ + static Object extractPart(MultipartInput input, String label, Class clazz) { + Object obj = null; + + try { + for (InputPart part : input.getParts()) { + String partLabel = part.getHeaders().getFirst("label"); + if (label.equalsIgnoreCase(partLabel)) { + String partStr = part.getBodyAsString(); + obj = part.getBody(clazz, null); + break; + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + return obj; + } + +} diff --git a/services/sdk/sample/src/main/resources/collectionspace-client.properties b/services/sdk/sample/src/main/resources/collectionspace-client.properties index 429b9f6fe..927081034 100644 --- a/services/sdk/sample/src/main/resources/collectionspace-client.properties +++ b/services/sdk/sample/src/main/resources/collectionspace-client.properties @@ -1,6 +1,6 @@ -#url of the collectionspace server -cspace.url=http://localhost:8180/cspace-services/ -cspace.ssl=false -cspace.auth=false -cspace.user=test +#url of the collectionspace server +cspace.url=http://localhost:8180/cspace-services/ +cspace.ssl=false +cspace.auth=false +cspace.user=test cspace.password=test \ No newline at end of file diff --git a/services/security/.classpath b/services/security/.classpath index 046988541..25df93560 100644 --- a/services/security/.classpath +++ b/services/security/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/security/.project b/services/security/.project index ddf9eb9fa..0d93f6ebf 100644 --- a/services/security/.project +++ b/services/security/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.security - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.security + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/security/build.xml b/services/security/build.xml index 88412c6ef..8a0d733bf 100644 --- a/services/security/build.xml +++ b/services/security/build.xml @@ -1,127 +1,127 @@ - - - - security service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - < - - - - - - - + + + + security service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + < + + + + + + + diff --git a/services/security/client/build.xml b/services/security/client/build.xml index 45a73990d..3f51a1f5b 100644 --- a/services/security/client/build.xml +++ b/services/security/client/build.xml @@ -1,141 +1,141 @@ - - - collectionspace security service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + collectionspace security service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/security/client/pom.xml b/services/security/client/pom.xml index 387ccd556..a462c8ef4 100644 --- a/services/security/client/pom.xml +++ b/services/security/client/pom.xml @@ -1,115 +1,115 @@ - - - - org.collectionspace.services.security - org.collectionspace.services - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.security.client - services.security.client - - - - - org.slf4j - slf4j-api - test - - - org.slf4j - slf4j-log4j12 - test - - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - - org.collectionspace.services - org.collectionspace.services.account.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authorization-mgt.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.collectionobject.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.dimension.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.intake.client - ${project.version} - - - - org.testng - testng - - - org.jboss.resteasy - resteasy-jaxrs - - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - commons-httpclient - commons-httpclient - 3.1 - - - - - cspace-services-security-client - - - maven-antrun-plugin - - - subs-hibernate-config - generate-test-resources - - run - - - - - - - - - - - - - - + + + + org.collectionspace.services.security + org.collectionspace.services + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.security.client + services.security.client + + + + + org.slf4j + slf4j-api + test + + + org.slf4j + slf4j-log4j12 + test + + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + + org.collectionspace.services + org.collectionspace.services.account.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authorization-mgt.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.collectionobject.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.dimension.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.intake.client + ${project.version} + + + + org.testng + testng + + + org.jboss.resteasy + resteasy-jaxrs + + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + commons-httpclient + commons-httpclient + 3.1 + + + + + cspace-services-security-client + + + maven-antrun-plugin + + + subs-hibernate-config + generate-test-resources + + run + + + + + + + + + + + + + + diff --git a/services/security/client/src/test/resources/log4j.properties b/services/security/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/security/client/src/test/resources/log4j.properties +++ b/services/security/client/src/test/resources/log4j.properties @@ -1,23 +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 +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/security/pom.xml b/services/security/pom.xml index 078bfbeaf..b432428cb 100644 --- a/services/security/pom.xml +++ b/services/security/pom.xml @@ -1,23 +1,23 @@ - - - - org.collectionspace.services.main - org.collectionspace.services - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.security - services.security - pom - - - - - - client - - - - + + + + org.collectionspace.services.main + org.collectionspace.services + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.security + services.security + pom + + + + + + client + + + + diff --git a/services/vocabulary/.classpath b/services/vocabulary/.classpath index 046988541..25df93560 100644 --- a/services/vocabulary/.classpath +++ b/services/vocabulary/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/vocabulary/.project b/services/vocabulary/.project index dbf94a589..e47deb16f 100644 --- a/services/vocabulary/.project +++ b/services/vocabulary/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.vocabulary - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.vocabulary + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/vocabulary/3rdparty/.classpath b/services/vocabulary/3rdparty/.classpath index 046988541..25df93560 100644 --- a/services/vocabulary/3rdparty/.classpath +++ b/services/vocabulary/3rdparty/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/vocabulary/3rdparty/.project b/services/vocabulary/3rdparty/.project index c8187641e..6bf47fbc8 100644 --- a/services/vocabulary/3rdparty/.project +++ b/services/vocabulary/3rdparty/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.vocabulary.3rdparty - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.vocabulary.3rdparty + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/vocabulary/3rdparty/build.xml b/services/vocabulary/3rdparty/build.xml index 743b53d81..1f77423cf 100644 --- a/services/vocabulary/3rdparty/build.xml +++ b/services/vocabulary/3rdparty/build.xml @@ -1,135 +1,135 @@ - - - - vocabulary service 3rdparty - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + vocabulary service 3rdparty + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/vocabulary/3rdparty/nuxeo-platform-cs-vocabulary/src/main/resources/schemas/README.txt b/services/vocabulary/3rdparty/nuxeo-platform-cs-vocabulary/src/main/resources/schemas/README.txt index fbefc97b1..5f8c5a6d0 100644 --- a/services/vocabulary/3rdparty/nuxeo-platform-cs-vocabulary/src/main/resources/schemas/README.txt +++ b/services/vocabulary/3rdparty/nuxeo-platform-cs-vocabulary/src/main/resources/schemas/README.txt @@ -1,16 +1,16 @@ -Files formerly located in this directory are no longer needed -------------------------------------------------------------- - -In CollectionSpace versions 4.0 and higher, changes were introduced -which streamline and simplify the process through which you configure -fields in CollectionSpace's main record types. - -In most cases now, you will typically change the behavior of existing fields, -or create extension schemas to add new fields specific to your museum and/or -community of practice, merely by editing simpler XML-based configuration -files within CollectionSpace's Application layer. - -Services layer files that were formerly located in this directory and -other, similar directories - which you previously needed to manually -create or edit - are now generated automatically from your configuration +Files formerly located in this directory are no longer needed +------------------------------------------------------------- + +In CollectionSpace versions 4.0 and higher, changes were introduced +which streamline and simplify the process through which you configure +fields in CollectionSpace's main record types. + +In most cases now, you will typically change the behavior of existing fields, +or create extension schemas to add new fields specific to your museum and/or +community of practice, merely by editing simpler XML-based configuration +files within CollectionSpace's Application layer. + +Services layer files that were formerly located in this directory and +other, similar directories - which you previously needed to manually +create or edit - are now generated automatically from your configuration in the Application layer. \ No newline at end of file diff --git a/services/vocabulary/3rdparty/pom.xml b/services/vocabulary/3rdparty/pom.xml index 055a0483a..6dc9972e9 100644 --- a/services/vocabulary/3rdparty/pom.xml +++ b/services/vocabulary/3rdparty/pom.xml @@ -1,24 +1,24 @@ - - - - org.collectionspace.services - org.collectionspace.services.vocabulary - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.vocabulary.3rdparty - services.vocabulary.3rdparty - pom - - 3rd party build for vocabulary service - - - - - - + + + + org.collectionspace.services + org.collectionspace.services.vocabulary + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.vocabulary.3rdparty + services.vocabulary.3rdparty + pom + + 3rd party build for vocabulary service + + + + + + diff --git a/services/vocabulary/build.xml b/services/vocabulary/build.xml index e6396b27e..8c78722f2 100644 --- a/services/vocabulary/build.xml +++ b/services/vocabulary/build.xml @@ -1,132 +1,132 @@ - - - - vocabulary service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + vocabulary service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/vocabulary/client/pom.xml b/services/vocabulary/client/pom.xml index e72438e8a..538bde2bd 100644 --- a/services/vocabulary/client/pom.xml +++ b/services/vocabulary/client/pom.xml @@ -1,78 +1,78 @@ - - - - - org.collectionspace.services - org.collectionspace.services.vocabulary - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.vocabulary.client - services.vocabulary.client - - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - - org.collectionspace.services - org.collectionspace.services.vocabulary.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authority.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - - org.testng - testng - - - org.jboss.resteasy - resteasy-jaxrs - - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - commons-httpclient - commons-httpclient - 3.1 - - - - - collectionspace-services-vocabulary-client - - - + + + + + org.collectionspace.services + org.collectionspace.services.vocabulary + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.vocabulary.client + services.vocabulary.client + + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + + org.collectionspace.services + org.collectionspace.services.vocabulary.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authority.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + + org.testng + testng + + + org.jboss.resteasy + resteasy-jaxrs + + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + commons-httpclient + commons-httpclient + 3.1 + + + + + collectionspace-services-vocabulary-client + + + diff --git a/services/vocabulary/client/src/main/java/org/collectionspace/services/client/VocabularyClientUtils.java b/services/vocabulary/client/src/main/java/org/collectionspace/services/client/VocabularyClientUtils.java index 5c4930645..5b39a29a4 100644 --- a/services/vocabulary/client/src/main/java/org/collectionspace/services/client/VocabularyClientUtils.java +++ b/services/vocabulary/client/src/main/java/org/collectionspace/services/client/VocabularyClientUtils.java @@ -1,147 +1,147 @@ -package org.collectionspace.services.client; - -import java.util.ArrayList; -import java.util.Map; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; - -import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema; -import org.collectionspace.services.client.test.ServiceRequestType; -import org.collectionspace.services.vocabulary.VocabularyitemsCommon; -import org.collectionspace.services.vocabulary.VocabulariesCommon; -import org.jboss.resteasy.client.ClientResponse; -//import org.jboss.resteasy.plugins.providers.multipart.PoxPayloadOut; -//import org.jboss.resteasy.plugins.providers.multipart.OutputPart; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class VocabularyClientUtils { - private static final Logger logger = - LoggerFactory.getLogger(VocabularyClientUtils.class); - - public static PoxPayloadOut createEnumerationInstance( - String displayName, String shortIdentifier, String headerLabel ) { - VocabulariesCommon vocabulary = new VocabulariesCommon(); - vocabulary.setDisplayName(displayName); - vocabulary.setShortIdentifier(shortIdentifier); - //String refName = createVocabularyRefName(shortIdentifier, displayName); - //vocabulary.setRefName(refName); - vocabulary.setVocabType("enum"); - PoxPayloadOut multipart = new PoxPayloadOut(VocabularyClient.SERVICE_PAYLOAD_NAME); - PayloadOutputPart commonPart = multipart.addPart(vocabulary, MediaType.APPLICATION_XML_TYPE); - commonPart.setLabel(headerLabel); - - if(logger.isDebugEnabled()){ - logger.debug("to be created, vocabulary common for enumeration ", - vocabulary, VocabulariesCommon.class); - } - - return multipart; - } - - // Note that we do not use the map, but we will once we add more info to the - // items - public static PoxPayloadOut createVocabularyItemInstance( - String vocabularyRefName, Map vocabItemInfo, String headerLabel){ - VocabularyitemsCommon vocabularyItem = new VocabularyitemsCommon(); - String shortId = vocabItemInfo.get(AuthorityItemJAXBSchema.SHORT_IDENTIFIER); - String displayName = vocabItemInfo.get(AuthorityItemJAXBSchema.DISPLAY_NAME); - vocabularyItem.setShortIdentifier(shortId); - vocabularyItem.setDisplayName(displayName); - //String refName = createVocabularyItemRefName(vocabularyRefName, shortId, displayName); - //vocabularyItem.setRefName(refName); - PoxPayloadOut multipart = new PoxPayloadOut(VocabularyClient.SERVICE_ITEM_PAYLOAD_NAME); - PayloadOutputPart commonPart = multipart.addPart(vocabularyItem, - MediaType.APPLICATION_XML_TYPE); - commonPart.setLabel(headerLabel); - - if(logger.isDebugEnabled()){ - logger.debug("to be created, vocabularyItem common ", vocabularyItem, VocabularyitemsCommon.class); - } - - return multipart; - } - - public static String createItemInVocabulary(String vcsid, - String vocabularyRefName, Map itemMap, - VocabularyClient client ) { - // Expected status code: 201 Created - int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; - - if(logger.isDebugEnabled()){ - logger.debug("Import: Create Item: \""+itemMap.get(AuthorityItemJAXBSchema.SHORT_IDENTIFIER) - +"\" in vocabularyAuthority: \"" + vcsid +"\""); - } - PoxPayloadOut multipart = createVocabularyItemInstance(null, //vocabularyRefName, - itemMap, client.getItemCommonPartName()); - ClientResponse res = client.createItem(vcsid, multipart); - - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not create Item: \"" + itemMap.get(AuthorityItemJAXBSchema.DISPLAY_NAME) - + "\" in personAuthority: \"" + vcsid //vocabularyRefName - + "\" " + invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when creating Item: \""+itemMap.get(AuthorityItemJAXBSchema.DISPLAY_NAME) - + "\" in vocabularyAuthority: \"" + vcsid /*vocabularyRefName*/ + "\", Status:" + statusCode); - } - - return extractId(res); - } - - /** - * Returns an error message indicating that the status code returned by a - * specific call to a service does not fall within a set of valid status - * codes for that service. - * - * @param serviceRequestType A type of service request (e.g. CREATE, DELETE). - * - * @param statusCode The invalid status code that was returned in the response, - * from submitting that type of request to the service. - * - * @return An error message. - */ - public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) { - return "Status code '" + statusCode + "' in response is NOT within the expected set: " + - requestType.validStatusCodesAsString(); - } - - public static String extractId(ClientResponse res) { - MultivaluedMap mvm = res.getMetadata(); - String uri = (String) ((ArrayList) mvm.get("Location")).get(0); - if(logger.isDebugEnabled()){ - logger.info("extractId:uri=" + uri); - } - String[] segments = uri.split("/"); - String id = segments[segments.length - 1]; - if(logger.isDebugEnabled()){ - logger.debug("id=" + id); - } - return id; - } - - /* - public static String createVocabularyRefName(String shortIdentifier, String displaySuffix) { - String refName = "urn:cspace:org.collectionspace.demo:vocabulary:name(" - + shortIdentifier + ")"; - if(displaySuffix != null && !displaySuffix.isEmpty()) - refName += "'" + displaySuffix + "'"; - return refName; - } - - public static String createVocabularyItemRefName( - String vocabularyRefName, String shortIdentifier, String displaySuffix) { - String refName = vocabularyRefName+":item:name("+shortIdentifier+")"; - if(displaySuffix != null && !displaySuffix.isEmpty()) - refName += "'" + displaySuffix + "'"; - return refName; - } - */ - -} +package org.collectionspace.services.client; + +import java.util.ArrayList; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; + +import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema; +import org.collectionspace.services.client.test.ServiceRequestType; +import org.collectionspace.services.vocabulary.VocabularyitemsCommon; +import org.collectionspace.services.vocabulary.VocabulariesCommon; +import org.jboss.resteasy.client.ClientResponse; +//import org.jboss.resteasy.plugins.providers.multipart.PoxPayloadOut; +//import org.jboss.resteasy.plugins.providers.multipart.OutputPart; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class VocabularyClientUtils { + private static final Logger logger = + LoggerFactory.getLogger(VocabularyClientUtils.class); + + public static PoxPayloadOut createEnumerationInstance( + String displayName, String shortIdentifier, String headerLabel ) { + VocabulariesCommon vocabulary = new VocabulariesCommon(); + vocabulary.setDisplayName(displayName); + vocabulary.setShortIdentifier(shortIdentifier); + //String refName = createVocabularyRefName(shortIdentifier, displayName); + //vocabulary.setRefName(refName); + vocabulary.setVocabType("enum"); + PoxPayloadOut multipart = new PoxPayloadOut(VocabularyClient.SERVICE_PAYLOAD_NAME); + PayloadOutputPart commonPart = multipart.addPart(vocabulary, MediaType.APPLICATION_XML_TYPE); + commonPart.setLabel(headerLabel); + + if(logger.isDebugEnabled()){ + logger.debug("to be created, vocabulary common for enumeration ", + vocabulary, VocabulariesCommon.class); + } + + return multipart; + } + + // Note that we do not use the map, but we will once we add more info to the + // items + public static PoxPayloadOut createVocabularyItemInstance( + String vocabularyRefName, Map vocabItemInfo, String headerLabel){ + VocabularyitemsCommon vocabularyItem = new VocabularyitemsCommon(); + String shortId = vocabItemInfo.get(AuthorityItemJAXBSchema.SHORT_IDENTIFIER); + String displayName = vocabItemInfo.get(AuthorityItemJAXBSchema.DISPLAY_NAME); + vocabularyItem.setShortIdentifier(shortId); + vocabularyItem.setDisplayName(displayName); + //String refName = createVocabularyItemRefName(vocabularyRefName, shortId, displayName); + //vocabularyItem.setRefName(refName); + PoxPayloadOut multipart = new PoxPayloadOut(VocabularyClient.SERVICE_ITEM_PAYLOAD_NAME); + PayloadOutputPart commonPart = multipart.addPart(vocabularyItem, + MediaType.APPLICATION_XML_TYPE); + commonPart.setLabel(headerLabel); + + if(logger.isDebugEnabled()){ + logger.debug("to be created, vocabularyItem common ", vocabularyItem, VocabularyitemsCommon.class); + } + + return multipart; + } + + public static String createItemInVocabulary(String vcsid, + String vocabularyRefName, Map itemMap, + VocabularyClient client ) { + // Expected status code: 201 Created + int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; + + if(logger.isDebugEnabled()){ + logger.debug("Import: Create Item: \""+itemMap.get(AuthorityItemJAXBSchema.SHORT_IDENTIFIER) + +"\" in vocabularyAuthority: \"" + vcsid +"\""); + } + PoxPayloadOut multipart = createVocabularyItemInstance(null, //vocabularyRefName, + itemMap, client.getItemCommonPartName()); + ClientResponse res = client.createItem(vcsid, multipart); + + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not create Item: \"" + itemMap.get(AuthorityItemJAXBSchema.DISPLAY_NAME) + + "\" in personAuthority: \"" + vcsid //vocabularyRefName + + "\" " + invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when creating Item: \""+itemMap.get(AuthorityItemJAXBSchema.DISPLAY_NAME) + + "\" in vocabularyAuthority: \"" + vcsid /*vocabularyRefName*/ + "\", Status:" + statusCode); + } + + return extractId(res); + } + + /** + * Returns an error message indicating that the status code returned by a + * specific call to a service does not fall within a set of valid status + * codes for that service. + * + * @param serviceRequestType A type of service request (e.g. CREATE, DELETE). + * + * @param statusCode The invalid status code that was returned in the response, + * from submitting that type of request to the service. + * + * @return An error message. + */ + public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) { + return "Status code '" + statusCode + "' in response is NOT within the expected set: " + + requestType.validStatusCodesAsString(); + } + + public static String extractId(ClientResponse res) { + MultivaluedMap mvm = res.getMetadata(); + String uri = (String) ((ArrayList) mvm.get("Location")).get(0); + if(logger.isDebugEnabled()){ + logger.info("extractId:uri=" + uri); + } + String[] segments = uri.split("/"); + String id = segments[segments.length - 1]; + if(logger.isDebugEnabled()){ + logger.debug("id=" + id); + } + return id; + } + + /* + public static String createVocabularyRefName(String shortIdentifier, String displaySuffix) { + String refName = "urn:cspace:org.collectionspace.demo:vocabulary:name(" + + shortIdentifier + ")"; + if(displaySuffix != null && !displaySuffix.isEmpty()) + refName += "'" + displaySuffix + "'"; + return refName; + } + + public static String createVocabularyItemRefName( + String vocabularyRefName, String shortIdentifier, String displaySuffix) { + String refName = vocabularyRefName+":item:name("+shortIdentifier+")"; + if(displaySuffix != null && !displaySuffix.isEmpty()) + refName += "'" + displaySuffix + "'"; + return refName; + } + */ + +} diff --git a/services/vocabulary/client/src/test/resources/log4j.properties b/services/vocabulary/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/vocabulary/client/src/test/resources/log4j.properties +++ b/services/vocabulary/client/src/test/resources/log4j.properties @@ -1,23 +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 +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/vocabulary/installer/build.xml b/services/vocabulary/installer/build.xml index 156a1135f..a87c4b652 100644 --- a/services/vocabulary/installer/build.xml +++ b/services/vocabulary/installer/build.xml @@ -1,61 +1,61 @@ - - - - vocabulary service - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + vocabulary service + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/services/vocabulary/pom.xml b/services/vocabulary/pom.xml index d409970a9..7cdf6d82a 100644 --- a/services/vocabulary/pom.xml +++ b/services/vocabulary/pom.xml @@ -1,45 +1,45 @@ - - - - org.collectionspace.services.main - org.collectionspace.services - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.vocabulary - services.vocabulary - pom - - - - - - - jaxb - service - 3rdparty - client - - - - - samples - - sample - - - - - - + + + + org.collectionspace.services.main + org.collectionspace.services + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.vocabulary + services.vocabulary + pom + + + + + + + jaxb + service + 3rdparty + client + + + + + samples + + sample + + + + + + diff --git a/services/vocabulary/sample/.classpath b/services/vocabulary/sample/.classpath index d8f291998..a225f00db 100644 --- a/services/vocabulary/sample/.classpath +++ b/services/vocabulary/sample/.classpath @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/services/vocabulary/sample/.project b/services/vocabulary/sample/.project index 89c52d527..2366e4ffa 100644 --- a/services/vocabulary/sample/.project +++ b/services/vocabulary/sample/.project @@ -1,17 +1,17 @@ - - - org.collectionspace.services.vocabulary.client.samples - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.vocabulary.client.samples + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/vocabulary/sample/pom.xml b/services/vocabulary/sample/pom.xml index e5aec84a3..574b8fe6c 100644 --- a/services/vocabulary/sample/pom.xml +++ b/services/vocabulary/sample/pom.xml @@ -1,14 +1,14 @@ - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.vocabulary.client.samples - pom - 1.0 - vocabulary.client.samples - - - sample - - - + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.vocabulary.client.samples + pom + 1.0 + vocabulary.client.samples + + + sample + + + diff --git a/services/vocabulary/sample/sample/.project b/services/vocabulary/sample/sample/.project index e08b6fd1a..524e532e8 100644 --- a/services/vocabulary/sample/sample/.project +++ b/services/vocabulary/sample/sample/.project @@ -1,23 +1,23 @@ - - - org.collectionspace.services.vocabulary.client.sample - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - + + + org.collectionspace.services.vocabulary.client.sample + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/services/vocabulary/sample/sample/pom.xml b/services/vocabulary/sample/sample/pom.xml index ffa0516ae..4988b2285 100644 --- a/services/vocabulary/sample/sample/pom.xml +++ b/services/vocabulary/sample/sample/pom.xml @@ -1,134 +1,134 @@ - - - 4.0.0 - org.collectionspace.services - org.collectionspace.services.vocabulary.client.sample - jar - 4.2-SNAPSHOT - vocabulary.client.sample - - - - org.collectionspace.services - org.collectionspace.services.vocabulary.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.client - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.vocabulary.client - ${project.version} - - - - - - libs-releases-local - libs-releases-local - http://nightly.collectionspace.org:8081/artifactory/libs-release-local - - true - - - false - - - - libs-snapshots-local - libs-snapshots-local - http://nightly.collectionspace.org:8081/artifactory/libs-snapshot-local - - false - - - true - - - - - collectionspace-releases - collectionspace-releases - http://nightly.collectionspace.org:8081/artifactory/nuxeo-public - - true - - - false - - - - nuxeo-public-snapshot - nuxeo-public-snapshot - http://nightly.collectionspace.org:8081/artifactory/nuxeo-public-snapshot - - false - - - true - - - - - - - vocabulary-client-sample - - - org.apache.maven.plugins - maven-assembly-plugin - - - - attached - - package - - - jar-with-dependencies - - - - org.collectionspace.services.vocabulary.client.sample.Sample - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.7 - 1.7 - - - - - - + + + 4.0.0 + org.collectionspace.services + org.collectionspace.services.vocabulary.client.sample + jar + 4.2-SNAPSHOT + vocabulary.client.sample + + + + org.collectionspace.services + org.collectionspace.services.vocabulary.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.client + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.vocabulary.client + ${project.version} + + + + + + libs-releases-local + libs-releases-local + http://nightly.collectionspace.org:8081/artifactory/libs-release-local + + true + + + false + + + + libs-snapshots-local + libs-snapshots-local + http://nightly.collectionspace.org:8081/artifactory/libs-snapshot-local + + false + + + true + + + + + collectionspace-releases + collectionspace-releases + http://nightly.collectionspace.org:8081/artifactory/nuxeo-public + + true + + + false + + + + nuxeo-public-snapshot + nuxeo-public-snapshot + http://nightly.collectionspace.org:8081/artifactory/nuxeo-public-snapshot + + false + + + true + + + + + + + vocabulary-client-sample + + + org.apache.maven.plugins + maven-assembly-plugin + + + + attached + + package + + + jar-with-dependencies + + + + org.collectionspace.services.vocabulary.client.sample.Sample + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.7 + 1.7 + + + + + + diff --git a/services/vocabulary/sample/sample/src/main/java/org/collectionspace/services/vocabulary/client/sample/Sample.java b/services/vocabulary/sample/sample/src/main/java/org/collectionspace/services/vocabulary/client/sample/Sample.java index ee006622b..897604a45 100644 --- a/services/vocabulary/sample/sample/src/main/java/org/collectionspace/services/vocabulary/client/sample/Sample.java +++ b/services/vocabulary/sample/sample/src/main/java/org/collectionspace/services/vocabulary/client/sample/Sample.java @@ -1,469 +1,469 @@ -/** - * 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 (c)) 2009 Regents of the University of California - * - * 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.vocabulary.client.sample; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; - -import org.apache.log4j.BasicConfigurator; -//import org.collectionspace.services.VocabularyItemJAXBSchema; -import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema; - -import org.collectionspace.services.client.PayloadInputPart; -import org.collectionspace.services.client.PoxPayloadIn; -import org.collectionspace.services.client.PoxPayloadOut; -import org.collectionspace.services.client.VocabularyClient; -import org.collectionspace.services.client.VocabularyClientUtils; -import org.collectionspace.services.client.test.ServiceRequestType; -import org.collectionspace.services.vocabulary.VocabulariesCommon; -import org.collectionspace.services.vocabulary.VocabulariesCommonList; -import org.collectionspace.services.vocabulary.VocabularyitemsCommon; -import org.collectionspace.services.vocabulary.VocabularyitemsCommonList; -import org.jboss.resteasy.client.ClientResponse; -import org.jboss.resteasy.plugins.providers.multipart.InputPart; -import org.jboss.resteasy.plugins.providers.multipart.OutputPart; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * VocabularyServiceTest, carries out tests against a - * deployed and running Vocabulary Service. - * - * $LastChangedRevision$ - * $LastChangedDate$ - */ -public class Sample { - private static final Logger logger = - LoggerFactory.getLogger(Sample.class); - - // Instance variables specific to this test. - private VocabularyClient client = new VocabularyClient(); - final String SERVICE_PATH_COMPONENT = "vocabularies"; - final String ITEM_SERVICE_PATH_COMPONENT = "items"; - - - // --------------------------------------------------------------- - // Create - // --------------------------------------------------------------- - - public void createEnumeration(String vocabName, List enumValues ) { - - // Expected status code: 201 Created - int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; - - if(logger.isDebugEnabled()){ - logger.debug("Import: Create vocabulary: \"" + vocabName +"\""); - } - - String displaySuffix = "displayName-" + System.currentTimeMillis(); //TODO: Laramie20100728 temp fix, made-up displaySuffix. - String baseVocabRefName = VocabularyClientUtils.createVocabularyRefName(vocabName, displaySuffix); //TODO: Laramie20100728 temp fix was vocabName, false - String fullVocabRefName = VocabularyClientUtils.createVocabularyRefName(vocabName, displaySuffix); //TODO: Laramie20100728 temp fix was vocabName, true - PoxPayloadOut multipart = VocabularyClientUtils.createEnumerationInstance( - vocabName, fullVocabRefName, client.getCommonPartName()); - ClientResponse res = client.create(multipart); - - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not create enumeration: \""+vocabName - +"\" "+ VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when creating enumeration: \"" - +vocabName +"\", Status:"+ statusCode); - } - - // Store the ID returned from this create operation - // for additional tests below. - String newVocabId = VocabularyClientUtils.extractId(res); - if(logger.isDebugEnabled()){ - logger.debug("Import: Created vocabulary: \"" + vocabName +"\" ID:" - +newVocabId ); - } - for(String itemName : enumValues){ - HashMap itemInfo = new HashMap(); - itemInfo.put(AuthorityItemJAXBSchema.DISPLAY_NAME, itemName); - VocabularyClientUtils.createItemInVocabulary(newVocabId, - baseVocabRefName, itemInfo, client); - } - } - - // --------------------------------------------------------------- - // Read - // --------------------------------------------------------------- - - private VocabulariesCommonList readVocabularies() { - - // Expected status code: 200 OK - int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; - - // Submit the request to the service and store the response. - ClientResponse res = client.readList(); - VocabulariesCommonList list = res.getEntity(); - - int statusCode = res.getStatus(); - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not read list of vocabularies: " - + VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when reading " + - "list of vocabularies, Status:"+ statusCode); - } - - return list; - } - - private List readVocabularyIds(VocabulariesCommonList list) { - - List ids = new ArrayList(); - List vocabularies = - list.getVocabularyListItem(); - for (VocabulariesCommonList.VocabularyListItem vocabulary : vocabularies) { - ids.add(vocabulary.getCsid()); - } - return ids; - } - - private VocabulariesCommon readVocabulary(String vocabId) { - - // Expected status code: 200 OK - int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; - - // Submit the request to the service and store the response. - VocabulariesCommon vocabulary = null; - try { - ClientResponse res = client.read(vocabId); - int statusCode = res.getStatus(); - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not read vocabulary" - + VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when reading " + - "vocabulary, Status:"+ statusCode); - } - PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); - vocabulary = (VocabulariesCommon) extractPart(input, - client.getCommonPartName(), VocabulariesCommon.class); - } catch (Exception e) { - throw new RuntimeException("Could not read vocabulary: ", e); - } - - return vocabulary; - } - - private VocabularyitemsCommonList readItemsInVocab(String vocabId) { - - // Expected status code: 200 OK - int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; - - // Submit the request to the service and store the response. - // readItemList(String inAuthority, String partialTerm, String keywords) - ClientResponse res = client.readItemList(vocabId, "", ""); //TODO: figure out these params. I just put in empty string to make it recompile after refactoring. Laramie20100728 - VocabularyitemsCommonList list = res.getEntity(); - - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not read items in vocabulary: " - + VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when reading " + - "items in vocabulary, Status:"+ statusCode); - } - - return list; - } - - private List readVocabularyItemIds(VocabularyitemsCommonList list) { - - List ids = new ArrayList(); - List items = - list.getVocabularyitemListItem(); - for (VocabularyitemsCommonList.VocabularyitemListItem item : items) { - ids.add(item.getCsid()); - } - return ids; - } - - // --------------------------------------------------------------- - // Delete - // --------------------------------------------------------------- - - private void deleteVocabulary(String vcsid) { - // Expected status code: 200 OK - int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE; - - ClientResponse res = client.delete(vcsid); - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not delete vocabulary: " - + VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when deleting " + - "vocabulary, Status:"+ statusCode); - } - } - - private void deleteAllVocabularies() { - List ids = readVocabularyIds(readVocabularies()); - for (String id : ids) { - deleteVocabulary(id); - } - } - - private void deleteVocabularyItem(String vcsid, String itemcsid) { - // Expected status code: 200 OK - int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); - // Type of service request being tested - ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE; - - ClientResponse res = client.deleteItem(vcsid, itemcsid); - int statusCode = res.getStatus(); - - if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { - throw new RuntimeException("Could not delete vocabulary item: " - + VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); - } - if(statusCode != EXPECTED_STATUS_CODE) { - throw new RuntimeException("Unexpected Status when deleting " + - "vocabulary item, Status:"+ statusCode); - } - } - - private void deleteAllItemsForVocab(String vocabId) { - List itemIds = readVocabularyItemIds(readItemsInVocab(vocabId)); - for (String itemId : itemIds) { - deleteVocabularyItem(vocabId, itemId); - } - } - - // --------------------------------------------------------------- - // Utility methods used by tests above - // --------------------------------------------------------------- - - // Retrieve individual fields of vocabulary records. - - private String displayAllVocabularies(VocabulariesCommonList list) { - StringBuffer sb = new StringBuffer(); - List vocabularies = - list.getVocabularyListItem(); - int i = 0; - for (VocabulariesCommonList.VocabularyListItem vocabulary : vocabularies) { - sb.append("vocabulary [" + i + "]" + "\n"); - sb.append(displayVocabularyDetails(vocabulary)); - i++; - } - return sb.toString(); - } - - private String displayVocabularyDetails( - VocabulariesCommonList.VocabularyListItem vocabulary) { - StringBuffer sb = new StringBuffer(); - sb.append("displayName=" + vocabulary.getDisplayName() + "\n"); - sb.append("vocabType=" + vocabulary.getVocabType() + "\n"); - // sb.append("csid=" + vocabulary.getCsid() + "\n"); - sb.append("URI=" + vocabulary.getUri() + "\n"); - return sb.toString(); - } - - // Retrieve individual fields of vocabulary item records. - - private String displayAllVocabularyItems(VocabularyitemsCommonList list) { - StringBuffer sb = new StringBuffer(); - List items = - list.getVocabularyitemListItem(); - int i = 0; - for (VocabularyitemsCommonList.VocabularyitemListItem item : items) { - sb.append("vocabulary item [" + i + "]" + "\n"); - sb.append(displayVocabularyItemDetails(item)); - i++; - } - return sb.toString(); - } - - private String displayVocabularyItemDetails( - VocabularyitemsCommonList.VocabularyitemListItem item) { - StringBuffer sb = new StringBuffer(); - sb.append("csid=" + item.getCsid() + "\n"); - sb.append("displayName=" + item.getDisplayName() + "\n"); - // sb.append("URI=" + item.getUri() + "\n"); - return sb.toString(); - } - - // TODO this should be moved to a common utils class - private Object extractPart(PoxPayloadIn input, String label, - Class clazz) throws Exception { - Object obj = null; - obj = input.getPart(label); - /* - for(PayloadInputPart part : input.getParts()){ - String partLabel = part.getHeaders().getFirst("label"); - if(label.equalsIgnoreCase(partLabel)){ - String partStr = part.getBodyAsString(); - if(logger.isDebugEnabled()){ - logger.debug("extracted part str=\n" + partStr); - } - obj = part.getBody(clazz, null); - if(logger.isDebugEnabled()){ - logger.debug("extracted part obj=\n", obj, clazz); - } - break; - } - } - */ - return obj; - } - - public static void main(String[] args) { - - // Configure logging. - BasicConfigurator.configure(); - - logger.info("VocabularyBaseImport starting..."); - - Sample vbi = new Sample(); - VocabulariesCommonList vocabularies; - List vocabIds; - String details = ""; - - // Optionally delete all vocabularies and vocabulary items. - - boolean ENABLE_DELETE_ALL = false; - if (ENABLE_DELETE_ALL) { - - logger.info("Deleting all vocabulary items and vocabularies ..."); - - // For each vocabulary ... - vocabularies = vbi.readVocabularies(); - vocabIds = vbi.readVocabularyIds(vocabularies); - for (String vocabId : vocabIds) { - logger.info("Deleting all vocabulary items for vocabulary ..."); - vbi.deleteAllItemsForVocab(vocabId); - logger.info("Deleting vocabulary ..."); - vbi.deleteVocabulary(vocabId); - } - - logger.info("Reading vocabularies after deletion ..."); - vocabularies = vbi.readVocabularies(); - details = vbi.displayAllVocabularies(vocabularies); - logger.info(details); - - logger.info("Reading items in each vocabulary after deletion ..."); - vocabIds = vbi.readVocabularyIds(vocabularies); - for (String vocabId : vocabIds) { - VocabularyitemsCommonList items = vbi.readItemsInVocab(vocabId); - details = vbi.displayAllVocabularyItems(items); - logger.info(details); - } - - } - - // Create new vocabularies, each populated with vocabulary items. - - final String acquisitionMethodsVocabName = "Acquisition Methods"; - final String entryMethodsVocabName = "Entry Methods"; - final String entryReasonsVocabName = "Entry Reasons"; - final String responsibleDeptsVocabName = "Responsible Departments"; - - List acquisitionMethodsEnumValues = - Arrays.asList("Gift","Purchase","Exchange","Transfer","Treasure"); - List entryMethodsEnumValues = - Arrays.asList("In person","Post","Found on doorstep"); - List entryReasonsEnumValues = - Arrays.asList("Enquiry","Commission","Loan"); - List respDeptNamesEnumValues = - Arrays.asList("Antiquities","Architecture and Design","Decorative Arts", - "Ethnography","Herpetology","Media and Performance Art", - "Paintings and Sculpture","Paleobotany","Photographs", - "Prints and Drawings"); - - vbi.createEnumeration(acquisitionMethodsVocabName, acquisitionMethodsEnumValues); - vbi.createEnumeration(entryMethodsVocabName, entryMethodsEnumValues); - vbi.createEnumeration(entryReasonsVocabName, entryReasonsEnumValues); - vbi.createEnumeration(responsibleDeptsVocabName, respDeptNamesEnumValues); - - logger.info("VocabularyBaseImport complete."); - - logger.info("Reading vocabularies and items ..."); - // Get a list of vocabularies. - vocabularies = vbi.readVocabularies(); - // For each vocabulary ... - for (VocabulariesCommonList.VocabularyListItem - vocabulary : vocabularies.getVocabularyListItem()) { - // Get its display name. - logger.info(vocabulary.getDisplayName()); - // Get a list of the vocabulary items in this vocabulary. - VocabularyitemsCommonList items = - vbi.readItemsInVocab(vocabulary.getCsid()); - // For each vocabulary item ... - for (VocabularyitemsCommonList.VocabularyitemListItem - item : items.getVocabularyitemListItem()) { - // Get its display name. - logger.info(" " + item.getDisplayName()); - } - } - - // Sample alternate methods of reading all vocabularies and - // vocabulary items separately. - boolean RUN_ADDITIONAL_SAMPLES = false; - if (RUN_ADDITIONAL_SAMPLES) { - - logger.info("Reading all vocabularies ..."); - details = vbi.displayAllVocabularies(vocabularies); - logger.info(details); - - logger.info("Reading all vocabulary items ..."); - vocabIds = vbi.readVocabularyIds(vocabularies); - for (String vocabId : vocabIds) { - VocabularyitemsCommonList items = vbi.readItemsInVocab(vocabId); - details = vbi.displayAllVocabularyItems(items); - logger.info(details); - } - - } - - } - -} +/** + * 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 (c)) 2009 Regents of the University of California + * + * 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.vocabulary.client.sample; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; + +import org.apache.log4j.BasicConfigurator; +//import org.collectionspace.services.VocabularyItemJAXBSchema; +import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema; + +import org.collectionspace.services.client.PayloadInputPart; +import org.collectionspace.services.client.PoxPayloadIn; +import org.collectionspace.services.client.PoxPayloadOut; +import org.collectionspace.services.client.VocabularyClient; +import org.collectionspace.services.client.VocabularyClientUtils; +import org.collectionspace.services.client.test.ServiceRequestType; +import org.collectionspace.services.vocabulary.VocabulariesCommon; +import org.collectionspace.services.vocabulary.VocabulariesCommonList; +import org.collectionspace.services.vocabulary.VocabularyitemsCommon; +import org.collectionspace.services.vocabulary.VocabularyitemsCommonList; +import org.jboss.resteasy.client.ClientResponse; +import org.jboss.resteasy.plugins.providers.multipart.InputPart; +import org.jboss.resteasy.plugins.providers.multipart.OutputPart; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * VocabularyServiceTest, carries out tests against a + * deployed and running Vocabulary Service. + * + * $LastChangedRevision$ + * $LastChangedDate$ + */ +public class Sample { + private static final Logger logger = + LoggerFactory.getLogger(Sample.class); + + // Instance variables specific to this test. + private VocabularyClient client = new VocabularyClient(); + final String SERVICE_PATH_COMPONENT = "vocabularies"; + final String ITEM_SERVICE_PATH_COMPONENT = "items"; + + + // --------------------------------------------------------------- + // Create + // --------------------------------------------------------------- + + public void createEnumeration(String vocabName, List enumValues ) { + + // Expected status code: 201 Created + int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE; + + if(logger.isDebugEnabled()){ + logger.debug("Import: Create vocabulary: \"" + vocabName +"\""); + } + + String displaySuffix = "displayName-" + System.currentTimeMillis(); //TODO: Laramie20100728 temp fix, made-up displaySuffix. + String baseVocabRefName = VocabularyClientUtils.createVocabularyRefName(vocabName, displaySuffix); //TODO: Laramie20100728 temp fix was vocabName, false + String fullVocabRefName = VocabularyClientUtils.createVocabularyRefName(vocabName, displaySuffix); //TODO: Laramie20100728 temp fix was vocabName, true + PoxPayloadOut multipart = VocabularyClientUtils.createEnumerationInstance( + vocabName, fullVocabRefName, client.getCommonPartName()); + ClientResponse res = client.create(multipart); + + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not create enumeration: \""+vocabName + +"\" "+ VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when creating enumeration: \"" + +vocabName +"\", Status:"+ statusCode); + } + + // Store the ID returned from this create operation + // for additional tests below. + String newVocabId = VocabularyClientUtils.extractId(res); + if(logger.isDebugEnabled()){ + logger.debug("Import: Created vocabulary: \"" + vocabName +"\" ID:" + +newVocabId ); + } + for(String itemName : enumValues){ + HashMap itemInfo = new HashMap(); + itemInfo.put(AuthorityItemJAXBSchema.DISPLAY_NAME, itemName); + VocabularyClientUtils.createItemInVocabulary(newVocabId, + baseVocabRefName, itemInfo, client); + } + } + + // --------------------------------------------------------------- + // Read + // --------------------------------------------------------------- + + private VocabulariesCommonList readVocabularies() { + + // Expected status code: 200 OK + int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; + + // Submit the request to the service and store the response. + ClientResponse res = client.readList(); + VocabulariesCommonList list = res.getEntity(); + + int statusCode = res.getStatus(); + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not read list of vocabularies: " + + VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when reading " + + "list of vocabularies, Status:"+ statusCode); + } + + return list; + } + + private List readVocabularyIds(VocabulariesCommonList list) { + + List ids = new ArrayList(); + List vocabularies = + list.getVocabularyListItem(); + for (VocabulariesCommonList.VocabularyListItem vocabulary : vocabularies) { + ids.add(vocabulary.getCsid()); + } + return ids; + } + + private VocabulariesCommon readVocabulary(String vocabId) { + + // Expected status code: 200 OK + int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; + + // Submit the request to the service and store the response. + VocabulariesCommon vocabulary = null; + try { + ClientResponse res = client.read(vocabId); + int statusCode = res.getStatus(); + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not read vocabulary" + + VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when reading " + + "vocabulary, Status:"+ statusCode); + } + PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); + vocabulary = (VocabulariesCommon) extractPart(input, + client.getCommonPartName(), VocabulariesCommon.class); + } catch (Exception e) { + throw new RuntimeException("Could not read vocabulary: ", e); + } + + return vocabulary; + } + + private VocabularyitemsCommonList readItemsInVocab(String vocabId) { + + // Expected status code: 200 OK + int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.READ; + + // Submit the request to the service and store the response. + // readItemList(String inAuthority, String partialTerm, String keywords) + ClientResponse res = client.readItemList(vocabId, "", ""); //TODO: figure out these params. I just put in empty string to make it recompile after refactoring. Laramie20100728 + VocabularyitemsCommonList list = res.getEntity(); + + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not read items in vocabulary: " + + VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when reading " + + "items in vocabulary, Status:"+ statusCode); + } + + return list; + } + + private List readVocabularyItemIds(VocabularyitemsCommonList list) { + + List ids = new ArrayList(); + List items = + list.getVocabularyitemListItem(); + for (VocabularyitemsCommonList.VocabularyitemListItem item : items) { + ids.add(item.getCsid()); + } + return ids; + } + + // --------------------------------------------------------------- + // Delete + // --------------------------------------------------------------- + + private void deleteVocabulary(String vcsid) { + // Expected status code: 200 OK + int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE; + + ClientResponse res = client.delete(vcsid); + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not delete vocabulary: " + + VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when deleting " + + "vocabulary, Status:"+ statusCode); + } + } + + private void deleteAllVocabularies() { + List ids = readVocabularyIds(readVocabularies()); + for (String id : ids) { + deleteVocabulary(id); + } + } + + private void deleteVocabularyItem(String vcsid, String itemcsid) { + // Expected status code: 200 OK + int EXPECTED_STATUS_CODE = Response.Status.OK.getStatusCode(); + // Type of service request being tested + ServiceRequestType REQUEST_TYPE = ServiceRequestType.DELETE; + + ClientResponse res = client.deleteItem(vcsid, itemcsid); + int statusCode = res.getStatus(); + + if(!REQUEST_TYPE.isValidStatusCode(statusCode)) { + throw new RuntimeException("Could not delete vocabulary item: " + + VocabularyClientUtils.invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); + } + if(statusCode != EXPECTED_STATUS_CODE) { + throw new RuntimeException("Unexpected Status when deleting " + + "vocabulary item, Status:"+ statusCode); + } + } + + private void deleteAllItemsForVocab(String vocabId) { + List itemIds = readVocabularyItemIds(readItemsInVocab(vocabId)); + for (String itemId : itemIds) { + deleteVocabularyItem(vocabId, itemId); + } + } + + // --------------------------------------------------------------- + // Utility methods used by tests above + // --------------------------------------------------------------- + + // Retrieve individual fields of vocabulary records. + + private String displayAllVocabularies(VocabulariesCommonList list) { + StringBuffer sb = new StringBuffer(); + List vocabularies = + list.getVocabularyListItem(); + int i = 0; + for (VocabulariesCommonList.VocabularyListItem vocabulary : vocabularies) { + sb.append("vocabulary [" + i + "]" + "\n"); + sb.append(displayVocabularyDetails(vocabulary)); + i++; + } + return sb.toString(); + } + + private String displayVocabularyDetails( + VocabulariesCommonList.VocabularyListItem vocabulary) { + StringBuffer sb = new StringBuffer(); + sb.append("displayName=" + vocabulary.getDisplayName() + "\n"); + sb.append("vocabType=" + vocabulary.getVocabType() + "\n"); + // sb.append("csid=" + vocabulary.getCsid() + "\n"); + sb.append("URI=" + vocabulary.getUri() + "\n"); + return sb.toString(); + } + + // Retrieve individual fields of vocabulary item records. + + private String displayAllVocabularyItems(VocabularyitemsCommonList list) { + StringBuffer sb = new StringBuffer(); + List items = + list.getVocabularyitemListItem(); + int i = 0; + for (VocabularyitemsCommonList.VocabularyitemListItem item : items) { + sb.append("vocabulary item [" + i + "]" + "\n"); + sb.append(displayVocabularyItemDetails(item)); + i++; + } + return sb.toString(); + } + + private String displayVocabularyItemDetails( + VocabularyitemsCommonList.VocabularyitemListItem item) { + StringBuffer sb = new StringBuffer(); + sb.append("csid=" + item.getCsid() + "\n"); + sb.append("displayName=" + item.getDisplayName() + "\n"); + // sb.append("URI=" + item.getUri() + "\n"); + return sb.toString(); + } + + // TODO this should be moved to a common utils class + private Object extractPart(PoxPayloadIn input, String label, + Class clazz) throws Exception { + Object obj = null; + obj = input.getPart(label); + /* + for(PayloadInputPart part : input.getParts()){ + String partLabel = part.getHeaders().getFirst("label"); + if(label.equalsIgnoreCase(partLabel)){ + String partStr = part.getBodyAsString(); + if(logger.isDebugEnabled()){ + logger.debug("extracted part str=\n" + partStr); + } + obj = part.getBody(clazz, null); + if(logger.isDebugEnabled()){ + logger.debug("extracted part obj=\n", obj, clazz); + } + break; + } + } + */ + return obj; + } + + public static void main(String[] args) { + + // Configure logging. + BasicConfigurator.configure(); + + logger.info("VocabularyBaseImport starting..."); + + Sample vbi = new Sample(); + VocabulariesCommonList vocabularies; + List vocabIds; + String details = ""; + + // Optionally delete all vocabularies and vocabulary items. + + boolean ENABLE_DELETE_ALL = false; + if (ENABLE_DELETE_ALL) { + + logger.info("Deleting all vocabulary items and vocabularies ..."); + + // For each vocabulary ... + vocabularies = vbi.readVocabularies(); + vocabIds = vbi.readVocabularyIds(vocabularies); + for (String vocabId : vocabIds) { + logger.info("Deleting all vocabulary items for vocabulary ..."); + vbi.deleteAllItemsForVocab(vocabId); + logger.info("Deleting vocabulary ..."); + vbi.deleteVocabulary(vocabId); + } + + logger.info("Reading vocabularies after deletion ..."); + vocabularies = vbi.readVocabularies(); + details = vbi.displayAllVocabularies(vocabularies); + logger.info(details); + + logger.info("Reading items in each vocabulary after deletion ..."); + vocabIds = vbi.readVocabularyIds(vocabularies); + for (String vocabId : vocabIds) { + VocabularyitemsCommonList items = vbi.readItemsInVocab(vocabId); + details = vbi.displayAllVocabularyItems(items); + logger.info(details); + } + + } + + // Create new vocabularies, each populated with vocabulary items. + + final String acquisitionMethodsVocabName = "Acquisition Methods"; + final String entryMethodsVocabName = "Entry Methods"; + final String entryReasonsVocabName = "Entry Reasons"; + final String responsibleDeptsVocabName = "Responsible Departments"; + + List acquisitionMethodsEnumValues = + Arrays.asList("Gift","Purchase","Exchange","Transfer","Treasure"); + List entryMethodsEnumValues = + Arrays.asList("In person","Post","Found on doorstep"); + List entryReasonsEnumValues = + Arrays.asList("Enquiry","Commission","Loan"); + List respDeptNamesEnumValues = + Arrays.asList("Antiquities","Architecture and Design","Decorative Arts", + "Ethnography","Herpetology","Media and Performance Art", + "Paintings and Sculpture","Paleobotany","Photographs", + "Prints and Drawings"); + + vbi.createEnumeration(acquisitionMethodsVocabName, acquisitionMethodsEnumValues); + vbi.createEnumeration(entryMethodsVocabName, entryMethodsEnumValues); + vbi.createEnumeration(entryReasonsVocabName, entryReasonsEnumValues); + vbi.createEnumeration(responsibleDeptsVocabName, respDeptNamesEnumValues); + + logger.info("VocabularyBaseImport complete."); + + logger.info("Reading vocabularies and items ..."); + // Get a list of vocabularies. + vocabularies = vbi.readVocabularies(); + // For each vocabulary ... + for (VocabulariesCommonList.VocabularyListItem + vocabulary : vocabularies.getVocabularyListItem()) { + // Get its display name. + logger.info(vocabulary.getDisplayName()); + // Get a list of the vocabulary items in this vocabulary. + VocabularyitemsCommonList items = + vbi.readItemsInVocab(vocabulary.getCsid()); + // For each vocabulary item ... + for (VocabularyitemsCommonList.VocabularyitemListItem + item : items.getVocabularyitemListItem()) { + // Get its display name. + logger.info(" " + item.getDisplayName()); + } + } + + // Sample alternate methods of reading all vocabularies and + // vocabulary items separately. + boolean RUN_ADDITIONAL_SAMPLES = false; + if (RUN_ADDITIONAL_SAMPLES) { + + logger.info("Reading all vocabularies ..."); + details = vbi.displayAllVocabularies(vocabularies); + logger.info(details); + + logger.info("Reading all vocabulary items ..."); + vocabIds = vbi.readVocabularyIds(vocabularies); + for (String vocabId : vocabIds) { + VocabularyitemsCommonList items = vbi.readItemsInVocab(vocabId); + details = vbi.displayAllVocabularyItems(items); + logger.info(details); + } + + } + + } + +} diff --git a/services/vocabulary/sample/sample/src/main/resources/collectionspace-client.properties b/services/vocabulary/sample/sample/src/main/resources/collectionspace-client.properties index 429b9f6fe..927081034 100644 --- a/services/vocabulary/sample/sample/src/main/resources/collectionspace-client.properties +++ b/services/vocabulary/sample/sample/src/main/resources/collectionspace-client.properties @@ -1,6 +1,6 @@ -#url of the collectionspace server -cspace.url=http://localhost:8180/cspace-services/ -cspace.ssl=false -cspace.auth=false -cspace.user=test +#url of the collectionspace server +cspace.url=http://localhost:8180/cspace-services/ +cspace.ssl=false +cspace.auth=false +cspace.user=test cspace.password=test \ No newline at end of file diff --git a/services/vocabulary/service/pom.xml b/services/vocabulary/service/pom.xml index cceb8d139..48b393e15 100644 --- a/services/vocabulary/service/pom.xml +++ b/services/vocabulary/service/pom.xml @@ -1,131 +1,131 @@ - - - - org.collectionspace.services - org.collectionspace.services.vocabulary - 4.2-SNAPSHOT - - - 4.0.0 - org.collectionspace.services.vocabulary.service - services.vocabulary.service - jar - - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - - org.collectionspace.services - org.collectionspace.services.common - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.config - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.authority.service - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.vocabulary.jaxb - ${project.version} - - - org.collectionspace.services - org.collectionspace.services.vocabulary.client - ${project.version} - - - - - junit - junit - 4.1 - test - - - org.testng - testng - - - - - commons-beanutils - commons-beanutils - 1.6.1 - - - - commons-logging - commons-logging - 1.1 - - - - - - javax.security - jaas - 1.0.01 - provided - - - - dom4j - dom4j - 1.6.1 - provided - - - - - - org.jboss.resteasy - resteasy-jaxrs - - - tjws - webserver - - - - - org.jboss.resteasy - resteasy-jaxb-provider - - - org.jboss.resteasy - resteasy-multipart-provider - - - - - - org.nuxeo.ecm.core - nuxeo-core-api - - - jboss-remoting - jboss - - - - - - - - collectionspace-services-vocabulary - - - + + + + org.collectionspace.services + org.collectionspace.services.vocabulary + 4.2-SNAPSHOT + + + 4.0.0 + org.collectionspace.services.vocabulary.service + services.vocabulary.service + jar + + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + + org.collectionspace.services + org.collectionspace.services.common + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.config + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.authority.service + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.vocabulary.jaxb + ${project.version} + + + org.collectionspace.services + org.collectionspace.services.vocabulary.client + ${project.version} + + + + + junit + junit + 4.1 + test + + + org.testng + testng + + + + + commons-beanutils + commons-beanutils + 1.6.1 + + + + commons-logging + commons-logging + 1.1 + + + + + + javax.security + jaas + 1.0.01 + provided + + + + dom4j + dom4j + 1.6.1 + provided + + + + + + org.jboss.resteasy + resteasy-jaxrs + + + tjws + webserver + + + + + org.jboss.resteasy + resteasy-jaxb-provider + + + org.jboss.resteasy + resteasy-multipart-provider + + + + + + org.nuxeo.ecm.core + nuxeo-core-api + + + jboss-remoting + jboss + + + + + + + + collectionspace-services-vocabulary + + + diff --git a/services/workflow/3rdparty/nuxeo-platform-cs-workflow/src/main/resources/META-INF/MANIFEST.MF b/services/workflow/3rdparty/nuxeo-platform-cs-workflow/src/main/resources/META-INF/MANIFEST.MF index fb5cad529..409d564e5 100644 --- a/services/workflow/3rdparty/nuxeo-platform-cs-workflow/src/main/resources/META-INF/MANIFEST.MF +++ b/services/workflow/3rdparty/nuxeo-platform-cs-workflow/src/main/resources/META-INF/MANIFEST.MF @@ -1,20 +1,20 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 1 -Bundle-Name: NuxeoCS -Bundle-SymbolicName: org.collectionspace.workflow;singleton:=true -Bundle-Version: 1.0.0 -Bundle-Localization: plugin -Bundle-Vendor: Nuxeo -Require-Bundle: org.nuxeo.runtime, - org.nuxeo.ecm.core.api, - org.nuxeo.ecm.core, - org.nuxeo.ecm.core.api, - org.nuxeo.ecm.platform.types.api, - org.nuxeo.ecm.platform.versioning.api, - org.nuxeo.ecm.platform.ui, - org.nuxeo.ecm.platform.forms.layout.client, - org.nuxeo.ecm.platform.ws, - org.collectionspace.collectionspace_core -Provide-Package: org.collectionspace.workflow -Nuxeo-Component: OSGI-INF/core-types-contrib.xml - +Manifest-Version: 1.0 +Bundle-ManifestVersion: 1 +Bundle-Name: NuxeoCS +Bundle-SymbolicName: org.collectionspace.workflow;singleton:=true +Bundle-Version: 1.0.0 +Bundle-Localization: plugin +Bundle-Vendor: Nuxeo +Require-Bundle: org.nuxeo.runtime, + org.nuxeo.ecm.core.api, + org.nuxeo.ecm.core, + org.nuxeo.ecm.core.api, + org.nuxeo.ecm.platform.types.api, + org.nuxeo.ecm.platform.versioning.api, + org.nuxeo.ecm.platform.ui, + org.nuxeo.ecm.platform.forms.layout.client, + org.nuxeo.ecm.platform.ws, + org.collectionspace.collectionspace_core +Provide-Package: org.collectionspace.workflow +Nuxeo-Component: OSGI-INF/core-types-contrib.xml + diff --git a/services/workflow/3rdparty/nuxeo-platform-cs-workflow/src/main/resources/schemas/workflow_common.xsd b/services/workflow/3rdparty/nuxeo-platform-cs-workflow/src/main/resources/schemas/workflow_common.xsd index c93c1b938..215c9d0ed 100644 --- a/services/workflow/3rdparty/nuxeo-platform-cs-workflow/src/main/resources/schemas/workflow_common.xsd +++ b/services/workflow/3rdparty/nuxeo-platform-cs-workflow/src/main/resources/schemas/workflow_common.xsd @@ -1,30 +1,30 @@ - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + diff --git a/services/workflow/client/src/test/resources/log4j.properties b/services/workflow/client/src/test/resources/log4j.properties index 18c510350..148a3e865 100644 --- a/services/workflow/client/src/test/resources/log4j.properties +++ b/services/workflow/client/src/test/resources/log4j.properties @@ -1,23 +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 +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 -- 2.47.3