return authRefDocList;
}
+ public AuthorityRefDocList getReferencingObjects(
+ ServiceContext<PoxPayloadIn, PoxPayloadOut> existingContext,
+ String parentspecifier,
+ String itemspecifier,
+ UriInfo uriInfo) throws Exception {
+ return getReferencingObjects(existingContext, parentspecifier, itemspecifier, uriInfo, PAGE_NUM_FROM_QUERYPARAMS, PAGE_SIZE_FROM_QUERYPARAMS, true, true);
+ }
+
public AuthorityRefDocList getReferencingObjects(
ServiceContext<PoxPayloadIn, PoxPayloadOut> existingContext,
String parentspecifier,
<artifactId>org.collectionspace.services.taxonomy.service</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.collectionspace.services</groupId>
+ <artifactId>org.collectionspace.services.vocabulary.service</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.collectionspace.services</groupId>
+ <artifactId>org.collectionspace.services.group.service</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
<!-- External dependencies -->
+
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
public CoreSessionInterface getRepoSession();
public String getTenantId();
+
+ public void run(BatchCommon batchCommon);
}
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
+import org.collectionspace.services.batch.BatchCommon;
import org.collectionspace.services.batch.AbstractBatchInvocable;
import org.collectionspace.services.client.CollectionObjectClient;
import org.collectionspace.services.client.CollectionSpaceClient;
private Map<String, String> authorityServiceNamesByDocType;
+ @SuppressWarnings("unchecked")
+ protected static <T> Set<T> convertListToSet(List<T> list)
+ {
+ // create a set from the List
+ return (Set<T>) list.stream().collect(Collectors.toSet());
+ }
+
+ @Override
+ public void run(BatchCommon batchCommon) {
+ String errMsg = String.format("%s class does not support run(BatchCommon batchCommon) method.", getClass().getName());
+ throw new java.lang.UnsupportedOperationException(errMsg);
+ }
+
protected String getFieldXml(Map<String, String> fields, String fieldName) {
return getFieldXml(fieldName, fields.get(fieldName));
}
"</document>";
NuxeoBasedResource resource = (NuxeoBasedResource) getResourceMap().get(RelationClient.SERVICE_NAME);
- Response response = resource.create(getResourceMap(), null, createRelationPayload);
+ Response response = resource.create(getServiceContext(), getResourceMap(), null, createRelationPayload);
if (response.getStatus() == CREATED_STATUS) {
relationCsid = CollectionSpaceClientUtils.extractId(response);
*/
protected List<RelationListItem> findRelated(String subjectCsid, String subjectDocType, String predicate, String objectCsid, String objectDocType) throws URISyntaxException {
RelationResource relationResource = (RelationResource) getResourceMap().get(RelationClient.SERVICE_NAME);
- RelationsCommonList relationList = relationResource.getList(createRelationSearchUriInfo(subjectCsid, subjectDocType, predicate, objectCsid, objectDocType));
+ RelationsCommonList relationList = relationResource.getList(getServiceContext(), createRelationSearchUriInfo(subjectCsid, subjectDocType, predicate, objectCsid, objectDocType));
return relationList.getRelationListItem();
}
String csid = uriParts[4];
if (items.equals("items")) {
- payload = findAuthorityItemByCsid(serviceName, vocabularyCsid, csid);
+ try {
+ payload = findAuthorityItemByCsid(serviceName, vocabularyCsid, csid);
+ } catch (Exception e) {
+ payload = null;
+ }
}
}
protected PoxPayloadOut findByCsid(String serviceName, String csid) throws URISyntaxException, DocumentException {
NuxeoBasedResource resource = (NuxeoBasedResource) getResourceMap().get(serviceName);
- byte[] outputBytes = (byte[]) resource.get(null, null, createUriInfo(), csid).getEntity();
-
- PoxPayloadOut payload = new PoxPayloadOut(outputBytes);
-
+ PoxPayloadOut payload = resource.getWithParentCtx(getServiceContext(), csid);
return payload;
}
protected List<String> findAll(String serviceName, int pageSize, int pageNum, String sortBy) throws URISyntaxException, DocumentException {
NuxeoBasedResource resource = (NuxeoBasedResource) getResourceMap().get(serviceName);
- return findAll(resource, pageSize, pageNum, null);
+ return findAll(resource, pageSize, pageNum, sortBy);
}
protected List<String> findAll(NuxeoBasedResource resource, int pageSize, int pageNum, String sortBy) throws URISyntaxException, DocumentException {
- AbstractCommonList list = resource.getList(createPagedListUriInfo(resource.getServiceName(), pageNum, pageSize, sortBy));
+ AbstractCommonList list = resource.getList(getServiceContext(), createPagedListUriInfo(resource.getServiceName(), pageNum, pageSize, sortBy));
List<String> csids = new ArrayList<String>();
if (list instanceof RelationsCommonList) {
}
protected List<String> getVocabularyCsids(AuthorityResource<?, ?> resource) throws URISyntaxException {
- AbstractCommonList vocabularyList = resource.getAuthorityList(createDeleteFilterUriInfo());
+ AbstractCommonList vocabularyList = resource.getAuthorityList(getServiceContext(), createDeleteFilterUriInfo());
List<String> csids = new ArrayList<String>();
for (AbstractCommonList.ListItem item : vocabularyList.getListItem()) {
return csids;
}
- protected List<String> findAllAuthorityItems(String serviceName, String vocabularyCsid, int pageSize, int pageNum) throws URISyntaxException, DocumentException {
+ protected List<String> findAllAuthorityItems(String serviceName, String vocabularyCsid, int pageSize, int pageNum) throws Exception {
return findAllAuthorityItems(serviceName, vocabularyCsid, pageSize, pageNum, null);
}
- protected List<String> findAllAuthorityItems(String serviceName, String vocabularyCsid, int pageSize, int pageNum, String sortBy) throws URISyntaxException, DocumentException {
+ protected List<String> findAllAuthorityItems(String serviceName, String vocabularyCsid, int pageSize, int pageNum, String sortBy) throws Exception {
AuthorityResource<?, ?> resource = (AuthorityResource<?, ?>) getResourceMap().get(serviceName);
return findAllAuthorityItems(resource, vocabularyCsid, pageSize, pageNum, sortBy);
}
- protected List<String> findAllAuthorityItems(AuthorityResource<?, ?> resource, String vocabularyCsid, int pageSize, int pageNum, String sortBy) throws URISyntaxException, DocumentException {
- AbstractCommonList list = resource.getAuthorityItemList(vocabularyCsid, createPagedListUriInfo(resource.getServiceName(), pageNum, pageSize, sortBy));
+ protected List<String> findAllAuthorityItems(AuthorityResource<?, ?> resource, String vocabularyCsid, int pageSize, int pageNum, String sortBy) throws Exception {
+ AbstractCommonList list = resource.getAuthorityItemList(getServiceContext(), vocabularyCsid, createPagedListUriInfo(resource.getServiceName(), pageNum, pageSize, sortBy));
List<String> csids = new ArrayList<String>();
for (AbstractCommonList.ListItem item : list.getListItem()) {
try {
itemPayload = findAuthorityItemByCsid(serviceName, vocabularyCsid, csid);
- } catch (CSWebApplicationException e) {
+ } catch (Exception e) {
itemPayload = null;
}
return itemPayload;
}
- protected PoxPayloadOut findAuthorityItemByCsid(String serviceName, String vocabularyCsid, String csid) throws URISyntaxException, DocumentException {
+ protected PoxPayloadOut findAuthorityItemByCsid(String serviceName, String vocabularyCsid, String csid) throws URISyntaxException, DocumentException, Exception {
AuthorityResource<?, ?> resource = (AuthorityResource<?, ?>) getResourceMap().get(serviceName);
- byte[] response = resource.getAuthorityItem(null, createDeleteFilterUriInfo(), getResourceMap(), vocabularyCsid, csid);
-
- PoxPayloadOut payload = new PoxPayloadOut(response);
+ PoxPayloadOut payload = resource.getAuthorityItemWithExistingContext(getServiceContext(), createDeleteFilterUriInfo(), getResourceMap(), vocabularyCsid, csid);
return payload;
}
return authorityServiceNamesByDocType.get(authorityDocType);
}
+ protected PoxPayloadOut findTaxonByCsid(String csid, String vocabularyCsid) throws URISyntaxException, DocumentException, Exception {
+ return findAuthorityItemByCsid(TaxonomyAuthorityClient.SERVICE_NAME, vocabularyCsid, csid);
+ }
+
protected PoxPayloadOut findTaxonByCsid(String csid) throws URISyntaxException, DocumentException {
return findAuthorityItemByCsid(TaxonomyAuthorityClient.SERVICE_NAME, csid);
}
-
- protected PoxPayloadOut findAuthorityItemByShortId(String serviceName, String vocabularyShortId, String itemShortId) throws URISyntaxException, DocumentException {
+
+ protected PoxPayloadOut findAuthorityItemByShortId(String serviceName, String vocabularyShortId, String itemShortId) throws URISyntaxException, DocumentException, Exception {
AuthorityResource<?, ?> resource = (AuthorityResource<?, ?>) getResourceMap().get(serviceName);
- byte[] response = resource.getAuthorityItem(null, createDeleteFilterUriInfo(), getResourceMap(), "urn:cspace:name(" + vocabularyShortId + ")", "urn:cspace:name(" + itemShortId + ")");
-
- PoxPayloadOut payload = new PoxPayloadOut(response);
+ PoxPayloadOut payload = resource.getAuthorityItemWithExistingContext(getServiceContext(), createDeleteFilterUriInfo(), getResourceMap(),
+ "urn:cspace:name(" + vocabularyShortId + ")", "urn:cspace:name(" + itemShortId + ")");
return payload;
}
- protected PoxPayloadOut findAuthorityItemByRefName(String serviceName, String refName) throws URISyntaxException, DocumentException {
+ protected PoxPayloadOut findAuthorityItemByRefName(String serviceName, String refName) throws URISyntaxException, DocumentException, Exception {
RefName.AuthorityItem item = RefName.AuthorityItem.parse(refName);
-
+ if (item == null) {
+ return null;
+ }
String vocabularyShortId = item.getParentShortIdentifier();
String itemShortId = item.getShortIdentifier();
return findAuthorityItemByShortId(serviceName, vocabularyShortId, itemShortId);
}
- protected PoxPayloadOut findPlaceByRefName(String refName) throws URISyntaxException, DocumentException {
+ protected PoxPayloadOut findPlaceByRefName(String refName) throws URISyntaxException, DocumentException, Exception {
return findAuthorityItemByRefName(PlaceAuthorityClient.SERVICE_NAME, refName);
}
- protected PoxPayloadOut findTaxonByRefName(String refName) throws URISyntaxException, DocumentException {
+ protected PoxPayloadOut findTaxonByRefName(String refName) throws URISyntaxException, DocumentException, Exception {
return findAuthorityItemByRefName(TaxonomyAuthorityClient.SERVICE_NAME, refName);
}
- protected List<AuthorityRefDocList.AuthorityRefDocItem> findReferencingFields(String serviceName, String parentCsid, String csid, String type, int pageNum, int pageSize) throws URISyntaxException {
+ protected List<AuthorityRefDocList.AuthorityRefDocItem> findReferencingFields(String serviceName, String parentCsid, String csid, String type, int pageNum, int pageSize) throws Exception {
AuthorityResource<?, ?> resource = (AuthorityResource<?, ?>) getResourceMap().get(serviceName);
// The pageNum and pageSize params don't work right for the refobj request.
// contain repeats of items already returned on the previous page. Any
// code that uses this function should be aware of this.
- AuthorityRefDocList refDocList = resource.getReferencingObjects(parentCsid, csid, createRefSearchFilterUriInfo(type, pageNum, pageSize));
+ AuthorityRefDocList refDocList = resource.getReferencingObjects(getServiceContext(), parentCsid, csid, createRefSearchFilterUriInfo(type, pageNum, pageSize));
return refDocList.getAuthorityRefDocItem();
}
* Only records that reference the given item in the specified field are returned.
* If null, returns records that reference the item in any field.
* @return A List containing the csids of referencing records.
- * @throws URISyntaxException
+ * @throws Exception
*/
- protected List<String> findReferencingObjects(String serviceName, String parentCsid, String csid, String type, String sourceField) throws URISyntaxException {
+ protected List<String> findReferencingObjects(String serviceName, String parentCsid, String csid, String type, String sourceField) throws Exception {
logger.debug("findReferencingObjects serviceName=" + serviceName + " parentCsid=" + parentCsid + " csid=" + csid + " type=" + type + " sourceField=" + sourceField);
List<AuthorityRefDocList.AuthorityRefDocItem> items = findReferencingFields(serviceName, parentCsid, csid, type, 0, 0);
return csids;
}
- protected List<String> findReferencingObjects(String serviceName, String csid, String type, String sourceField) throws URISyntaxException, DocumentException {
+ protected List<String> findReferencingObjects(String serviceName, String csid, String type, String sourceField) throws Exception {
logger.debug("findReferencingObjects serviceName=" + serviceName + " csid=" + csid + " type=" + type + " sourceField=" + sourceField);
List<String> vocabularyCsids = getVocabularyCsids(serviceName);
return findReferencingObjects(serviceName, parentCsid, csid, type, sourceField);
}
- protected List<String> findReferencingCollectionObjects(String serviceName, String csid, String sourceField) throws URISyntaxException, DocumentException {
+ protected List<String> findReferencingCollectionObjects(String serviceName, String csid, String sourceField) throws Exception {
return findReferencingObjects(serviceName, csid, ServiceBindingUtils.SERVICE_TYPE_OBJECT, sourceField);
}
- protected List<String> findReferencingCollectionObjects(String serviceName, String vocabularyShortId, String csid, String sourceField) throws URISyntaxException, DocumentException {
+ protected List<String> findReferencingCollectionObjects(String serviceName, String vocabularyShortId, String csid, String sourceField) throws Exception {
return findReferencingObjects(serviceName, "urn:cspace:name(" + vocabularyShortId + ")", csid, ServiceBindingUtils.SERVICE_TYPE_OBJECT, sourceField);
}
}
}
- batchInstance.run();
+ batchInstance.run(batchCommon);
int status = batchInstance.getCompletionStatus();
if (status == Invocable.STATUS_ERROR) {
InvocationError error = batchInstance.getErrorInfo();
import javax.ws.rs.core.UriInfo;
import org.collectionspace.services.client.MovementClient;
+import org.collectionspace.services.client.PoxPayloadOut;
+import org.collectionspace.services.client.VocabularyClient;
import org.collectionspace.services.common.NuxeoBasedResource;
import org.collectionspace.services.common.invocable.InvocationResults;
import org.collectionspace.services.jaxb.AbstractCommonList;
import org.collectionspace.services.movement.MovementResource;
import org.collectionspace.services.movement.nuxeo.MovementBotGardenConstants;
+import org.collectionspace.services.vocabulary.nuxeo.VocabularyConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public ClearLocationLabelRequestBatchJob() {
setSupportedInvocationModes(Arrays.asList(INVOCATION_MODE_SINGLE, INVOCATION_MODE_LIST, INVOCATION_MODE_NO_CONTEXT));
}
-
+
@Override
public void run() {
setCompletionStatus(STATUS_MIN_PROGRESS);
-
+
try {
/*
* For now, treat any mode as if it were no context.
*/
-
+
setResults(clearLabelRequests());
setCompletionStatus(STATUS_COMPLETE);
}
}
}
- public InvocationResults clearLabelRequests() throws URISyntaxException {
+ public InvocationResults clearLabelRequests() throws Exception {
List<String> movementCsids = findLabelRequests();
InvocationResults results = null;
-
+
if (movementCsids.size() > 0) {
results = clearLabelRequests(movementCsids);
}
results = new InvocationResults();
results.setUserNote("No label requests found");
}
-
+
return results;
}
-
- public InvocationResults clearLabelRequests(String movementCsid) throws URISyntaxException {
+
+ public InvocationResults clearLabelRequests(String movementCsid) throws Exception {
return clearLabelRequests(Arrays.asList(movementCsid));
}
-
- public InvocationResults clearLabelRequests(List<String> movementCsids) throws URISyntaxException {
+
+ public InvocationResults clearLabelRequests(List<String> movementCsids) throws Exception {
InvocationResults results = new InvocationResults();
long numAffected = 0;
-
+
for (String movementCsid : movementCsids) {
clearLabelRequest(movementCsid);
numAffected = numAffected + 1;
}
-
+
results.setNumAffected(numAffected);
results.setUserNote("Removed " + numAffected + " label " + (numAffected == 1 ? "request" : "requests"));
return results;
}
-
- private void clearLabelRequest(String movementCsid) throws URISyntaxException {
+
+ private void clearLabelRequest(String movementCsid) throws Exception {
logger.debug("clear label request: movementCsid=" + movementCsid);
+
+ PoxPayloadOut payloadout = findAuthorityItemByRefName(VocabularyClient.SERVICE_NAME, MovementBotGardenConstants.OTHER_ACTION_CODE);
+ String termDisplayName = getFieldValue(payloadout, VocabularyConstants.DISPLAY_NAME_SCHEMA_NAME, VocabularyConstants.DISPLAY_NAME_FIELD_NAME);
- final String updatePayload =
+ final String updatePayload =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<document name=\"movements\">" +
"<ns2:movements_common xmlns:ns2=\"http://collectionspace.org/services/movement\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
- getFieldXml("reasonForMove", MovementBotGardenConstants.OTHER_ACTION_CODE) +
+ getFieldXml("reasonForMove", MovementBotGardenConstants.OTHER_ACTION_CODE + String.format("'%s'", termDisplayName)) +
"</ns2:movements_common>" +
"<ns2:movements_botgarden xmlns:ns2=\"http://collectionspace.org/services/movement/local/botgarden\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
getFieldXml("labelRequested", MovementBotGardenConstants.LABEL_REQUESTED_NO_VALUE) +
getFieldXml("labelCount", "") +
"</ns2:movements_botgarden>" +
"</document>";
-
+
NuxeoBasedResource resource = (NuxeoBasedResource) getResourceMap().get(MovementClient.SERVICE_NAME);
- resource.update(getResourceMap(), createUriInfo(), movementCsid, updatePayload);
+ resource.update(getServiceContext(), getResourceMap(), createUriInfo(), movementCsid, updatePayload);
}
-
+
private List<String> findLabelRequests() throws URISyntaxException {
List<String> csids = new ArrayList<String>();
MovementResource movementResource = (MovementResource) getResourceMap().get(MovementClient.SERVICE_NAME);
- AbstractCommonList movementList = movementResource.getList(createLabelRequestSearchUriInfo());
+ AbstractCommonList movementList = movementResource.getList(getServiceContext(), createLabelRequestSearchUriInfo());
for (AbstractCommonList.ListItem item : movementList.getListItem()) {
for (org.w3c.dom.Element element : item.getAny()) {
private UriInfo createLabelRequestSearchUriInfo() throws URISyntaxException {
return createKeywordSearchUriInfo(MovementBotGardenConstants.LABEL_REQUESTED_SCHEMA_NAME, MovementBotGardenConstants.LABEL_REQUESTED_FIELD_NAME,
- MovementBotGardenConstants.LABEL_REQUESTED_YES_VALUE);
+ MovementBotGardenConstants.LABEL_REQUESTED_YES_VALUE);
}
-}
\ No newline at end of file
+}
"</document>";
NuxeoBasedResource resource = (NuxeoBasedResource) getResourceMap().get(PottagClient.SERVICE_NAME);
- resource.update(getResourceMap(), createUriInfo(), potTagCsid, updatePayload);
+ resource.update(getServiceContext(), getResourceMap(), createUriInfo(), potTagCsid, updatePayload);
}
private List<String> findLabelRequests() throws URISyntaxException {
List<String> csids = new ArrayList<String>();
PottagResource potTagResource = (PottagResource) getResourceMap().get(PottagClient.SERVICE_NAME);
- AbstractCommonList potTagList = potTagResource.getList(createLabelRequestSearchUriInfo());
+ AbstractCommonList potTagList = potTagResource.getList(getServiceContext(), createLabelRequestSearchUriInfo());
for (AbstractCommonList.ListItem item : potTagList.getListItem()) {
for (org.w3c.dom.Element element : item.getAny()) {
"</document>";
NuxeoBasedResource resource = (NuxeoBasedResource) getResourceMap().get(LoanoutClient.SERVICE_NAME);
- resource.update(getResourceMap(), createUriInfo(), loanoutCsid, updatePayload);
+ resource.update(getServiceContext(), getResourceMap(), createUriInfo(), loanoutCsid, updatePayload);
}
private List<String> findLabelRequests() throws URISyntaxException {
List<String> csids = new ArrayList<String>();
LoanoutResource loanoutResource = (LoanoutResource) getResourceMap().get(LoanoutClient.SERVICE_NAME);
- AbstractCommonList loanoutList = loanoutResource.getList(createLabelRequestSearchUriInfo());
+ AbstractCommonList loanoutList = loanoutResource.getList(getServiceContext(), createLabelRequestSearchUriInfo());
for (AbstractCommonList.ListItem item : loanoutList.getListItem()) {
for (org.w3c.dom.Element element : item.getAny()) {
import javax.ws.rs.core.Response;
import org.collectionspace.services.batch.AbstractBatchInvocable;
+import org.collectionspace.services.batch.BatchCommon;
import org.collectionspace.services.client.CollectionSpaceClientUtils;
import org.collectionspace.services.common.NuxeoBasedResource;
import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils;
setSupportedInvocationModes(Arrays.asList(INVOCATION_MODE_SINGLE, INVOCATION_MODE_LIST));
}
+ @Override
+ public void run(BatchCommon batchCommon) {
+ run(); // Ignore batchCommon since it's not needed
+ }
+
/**
* The main work logic of the batch job. Will be called after setContext.
*/
}
}
- public InvocationResults createVoucherFromCataloging(String collectionObjectCsid) throws ResourceException, URISyntaxException, DocumentException {
+ public InvocationResults createVoucherFromCataloging(String collectionObjectCsid) throws Exception {
return createVoucherFromCataloging(collectionObjectCsid, null);
}
- public InvocationResults createVoucherFromCataloging(String collectionObjectCsid, String movementCsid) throws ResourceException, URISyntaxException, DocumentException {
+ public InvocationResults createVoucherFromCataloging(String collectionObjectCsid, String movementCsid) throws Exception {
InvocationResults results = new InvocationResults();
PoxPayloadOut collectionObjectPayload = findCollectionObjectByCsid(collectionObjectCsid);
logger.debug("relations created: forwardRelationCsid=" + forwardRelationCsid + " backwardRelationCsid=" + backwardRelationCsid);
results.setNumAffected(1);
- results.setPrimaryURICreated("loanout.html?csid=" + voucherCsid);
+ results.setPrimaryURICreated("/loansout/" + voucherCsid);
results.setUserNote("Voucher created");
}
return results;
}
- private String getFieldCollectionNote(PoxPayloadOut collectionObjectPayload) throws URISyntaxException, DocumentException {
+ private String getFieldCollectionNote(PoxPayloadOut collectionObjectPayload) throws Exception {
String placeNote = "";
String reverseFieldCollectionPlace = getReverseFieldCollectionPlace(collectionObjectPayload);
return collectionNote;
}
- private String getReverseFieldCollectionPlace(PoxPayloadOut collectionObjectPayload) throws URISyntaxException, DocumentException {
+ private String getReverseFieldCollectionPlace(PoxPayloadOut collectionObjectPayload) throws Exception {
String reverseDisplayName = null;
String fieldCollectionPlaceRefName = getFieldValue(collectionObjectPayload, CollectionObjectBotGardenConstants.FIELD_COLLECTION_PLACE_SCHEMA_NAME,
CollectionObjectBotGardenConstants.FIELD_COLLECTION_PLACE_FIELD_NAME);
return annotation;
}
- public InvocationResults createVoucherFromCurrentLocation(String movementCsid) throws ResourceException, URISyntaxException, DocumentException {
+ public InvocationResults createVoucherFromCurrentLocation(String movementCsid) throws Exception {
long numAffected = 0;
String primaryUriCreated = null;
"</document>";
NuxeoBasedResource resource = (NuxeoBasedResource) getResourceMap().get(LoanoutClient.SERVICE_NAME);
- Response response = resource.create(getResourceMap(), null, createVoucherPayload);
+ Response response = resource.create(getServiceContext(), getResourceMap(), null, createVoucherPayload);
if (response.getStatus() == CREATED_STATUS) {
voucherCsid = CollectionSpaceClientUtils.extractId(response);
private List<String> findLabelRequests() throws URISyntaxException {
List<String> csids = new ArrayList<String>();
LoanoutResource loanoutResource = (LoanoutResource) getResourceMap().get(LoanoutClient.SERVICE_NAME);
- AbstractCommonList loanoutList = loanoutResource.getList(createLabelRequestSearchUriInfo());
+ AbstractCommonList loanoutList = loanoutResource.getList(getServiceContext(), createLabelRequestSearchUriInfo());
for (AbstractCommonList.ListItem item : loanoutList.getListItem()) {
for (org.w3c.dom.Element element : item.getAny()) {
"</document>";
NuxeoBasedResource resource = (NuxeoBasedResource) getResourceMap().get(LoanoutClient.SERVICE_NAME);
- resource.update(getResourceMap(), createUriInfo(), loanoutCsid, updatePayload);
+ resource.update(getServiceContext(), getResourceMap(), createUriInfo(), loanoutCsid, updatePayload);
}
private UriInfo createLabelRequestSearchUriInfo() throws URISyntaxException {
}
}
- public InvocationResults merge(String docType, String target, String sourceCsid) throws URISyntaxException, DocumentException {
+ public InvocationResults merge(String docType, String target, String sourceCsid) throws Exception {
return merge(docType, target, new LinkedHashSet<String>(Arrays.asList(sourceCsid)));
}
- public InvocationResults merge(String docType, String target, Set<String> sourceCsids) throws URISyntaxException, DocumentException {
+ public InvocationResults merge(String docType, String target, Set<String> sourceCsids) throws Exception {
logger.debug("Merging docType=" + docType + " target=" + target + " sourceCsids=" + StringUtils.join(sourceCsids, ","));
String serviceName = getAuthorityServiceNameForDocType(docType);
return merge(docType, targetItemPayload, sourceItemPayloads);
}
- private InvocationResults merge(String docType, PoxPayloadOut targetItemPayload, List<PoxPayloadOut> sourceItemPayloads) throws URISyntaxException, DocumentException {
+ private InvocationResults merge(String docType, PoxPayloadOut targetItemPayload, List<PoxPayloadOut> sourceItemPayloads) throws Exception {
int numAffected = 0;
List<String> userNotes = new ArrayList<String>();
return results;
}
- private InvocationResults updateReferences(String serviceName, String inAuthority, String sourceCsid, String sourceRefName, String targetRefName) throws URISyntaxException, DocumentException {
+ private InvocationResults updateReferences(String serviceName, String inAuthority, String sourceCsid, String sourceRefName, String targetRefName) throws Exception {
logger.debug("Updating references: serviceName=" + serviceName + " inAuthority=" + inAuthority + " sourceCsid=" + sourceCsid + " sourceRefName=" + sourceRefName + " targetRefName=" + targetRefName);
String sourceDisplayName = RefNameUtils.getDisplayName(sourceRefName);
import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Field;
-import java.security.Principal;
+import java.net.URISyntaxException;
+
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
+import org.collectionspace.services.batch.BatchCommon;
import org.collectionspace.services.common.CollectionSpaceResource;
import org.collectionspace.services.common.NuxeoBasedResource;
import org.collectionspace.services.common.StoredValuesUriTemplate;
import org.collectionspace.services.common.invocable.InvocationContext.Params.Param;
import org.collectionspace.services.common.invocable.InvocationResults;
import org.collectionspace.services.common.vocabulary.AuthorityResource;
+
+import org.dom4j.DocumentException;
import org.nuxeo.ecm.core.api.AbstractSession;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.IterableQueryResult;
import org.nuxeo.ecm.core.api.NuxeoException;
-import org.nuxeo.ecm.core.api.NuxeoPrincipal;
import org.nuxeo.ecm.core.event.EventService;
import org.nuxeo.ecm.core.query.QueryFilter;
import org.nuxeo.ecm.core.query.sql.NXQL;
log.debug("stop file directory is " + stopFileDirectory);
}
+
+ //
+ // Since the ReindexFullTextBatchJob class deals with transactions differently than other batch jobs, we need to
+ // override this method to ensure there is an active transaction.
+ //
+ @Override
+ protected List<String> getVocabularyCsids(AuthorityResource<?, ?> resource) throws URISyntaxException {
+ boolean tx = false;
+ if (TransactionHelper.isTransactionActive() == false) {
+ tx = TransactionHelper.startTransaction();
+ }
+
+ try {
+ return super.getVocabularyCsids(resource);
+ } finally {
+ if (tx) {
+ TransactionHelper.commitOrRollbackTransaction();
+ }
+ }
+ }
+
+ //
+ // Since the ReindexFullTextBatchJob class deals with transactions differently than other batch jobs, we need to
+ // override this method to ensure there is an active transaction.
+ //
+ @Override
+ protected List<String> findAll(NuxeoBasedResource resource, int pageSize, int pageNum, String sortBy)
+ throws URISyntaxException, DocumentException {
+ boolean tx = false;
+ if (TransactionHelper.isTransactionActive() == false) {
+ tx = TransactionHelper.startTransaction();
+ }
+
+ try {
+ return super.findAll(resource, pageSize, pageNum, sortBy);
+ } finally {
+ if (tx) {
+ TransactionHelper.commitOrRollbackTransaction();
+ }
+ }
+ }
+
+ //
+ // Since the ReindexFullTextBatchJob class deals with transactions differently than other batch jobs, we need to
+ // override this method to ensure there is an active transaction.
+ //
+ @Override
+ protected List<String> findAllAuthorityItems(AuthorityResource<?, ?> resource, String vocabularyCsid, int pageSize, int pageNum, String sortBy)
+ throws URISyntaxException, Exception {
+ boolean tx = false;
+ if (TransactionHelper.isTransactionActive() == false) {
+ tx = TransactionHelper.startTransaction();
+ }
+
+ try {
+ return super.findAllAuthorityItems(resource, vocabularyCsid, pageSize, pageNum, sortBy);
+ } finally {
+ if (tx) {
+ TransactionHelper.commitOrRollbackTransaction();
+ }
+ }
+ }
+
@Override
public void run() {
+ run(null);
+ }
+
+ @Override
+ public void run(BatchCommon batchCommon) {
setCompletionStatus(STATUS_MIN_PROGRESS);
numAffected = 0;
}
}
+ //
+ // If docTypes is empty, we should use the <forDocTypes> list from the resource/payload
+ //
+ if (docTypes.isEmpty() == true && batchCommon != null) {
+ List<String> payloadDocTypes = batchCommon.getForDocTypes().getForDocType();
+ if (payloadDocTypes != null && !payloadDocTypes.isEmpty()) {
+ docTypes = convertListToSet(payloadDocTypes);
+ }
+ }
+
initResourceMap();
reindexDocuments(docTypes);
}
import java.util.Arrays;
import org.collectionspace.services.batch.AbstractBatchInvocable;
+import org.collectionspace.services.batch.BatchCommon;
public class TestBatchJob extends AbstractBatchInvocable {
public void run() {
// An empty batch job used just for testing.
}
-
+
+ @Override
+ public void run(BatchCommon batchCommon) {
+ // An empty batch job used just for testing.
+ }
}
"</document>";
NuxeoBasedResource resource = (NuxeoBasedResource) getResourceMap().get(CollectionObjectClient.SERVICE_NAME);
- resource.update(getResourceMap(), createUriInfo(), collectionObjectCsid, updatePayload);
+ resource.update(getServiceContext(), getResourceMap(), createUriInfo(), collectionObjectCsid, updatePayload);
}
}
import javax.ws.rs.core.UriInfo;
import org.collectionspace.services.batch.AbstractBatchInvocable;
+import org.collectionspace.services.batch.BatchCommon;
import org.collectionspace.services.client.AbstractCommonListUtils;
import org.collectionspace.services.client.CollectionObjectClient;
import org.collectionspace.services.client.IClientQueryParams;
INVOCATION_MODE_GROUP, INVOCATION_MODE_NO_CONTEXT));
}
+ @Override
+ public void run(BatchCommon batchCommon) {
+ String errMsg = String.format("%s class does not support run(BatchCommon batchCommon) method.", getClass().getName());
+ throw new java.lang.UnsupportedOperationException(errMsg);
+ }
+
/**
* The main work logic of the batch job. Will be called after setContext.
*/
logger.trace("Update payload: " + "\n" + collectionObjectUpdatePayload);
}
+ //
+ // Update the record and save the response for debugging message
+ //
UriInfo uriInfo = this.setupQueryParamForUpdateRecords(); // Determines if we'll updated the updateAt and updatedBy core values
+ byte[] responseBytes = collectionObjectResource.update(getServiceContext(), resourcemap, uriInfo, collectionObjectCsid,
+ collectionObjectUpdatePayload);
+ numUpdated++;
+
if (logger.isDebugEnabled()) {
- byte[] responseBytes = collectionObjectResource.update(resourcemap, uriInfo, collectionObjectCsid,
- collectionObjectUpdatePayload);
logger.debug(String.format("Batch resource: Resonse from collectionobject (cataloging record) update: %s", new String(responseBytes)));
}
- numUpdated++;
if (logger.isTraceEnabled()) {
logger.trace("Computed current location value for CollectionObject " + collectionObjectCsid
+ " was set to " + computedCurrentLocation);
-
}
+
return numUpdated;
}
PoxPayloadOut result = null;
try {
- result = resource.getResourceFromCsid(null, createUriInfo(), csid);
+ result = resource.getWithParentCtx(getServiceContext(), csid);
} catch (Exception e) {
String msg = String.format("UpdateObjectLocation batch job could find/get resource CSID='%s' of type '%s'",
csid, resource.getServiceName());
throws URISyntaxException, DocumentException {
boolean isDeleted = false;
- byte[] workflowResponse = resource.getWorkflow(createUriInfo(), collectionObjectCsid);
+ byte[] workflowResponse = resource.getWorkflowWithExistingContext(getServiceContext(), createUriInfo(), collectionObjectCsid);
if (workflowResponse != null) {
PoxPayloadOut payloadOut = new PoxPayloadOut(workflowResponse);
String workflowState =
}
// The 'resource' type used here identifies the record type of the
// related records to be retrieved
- AbstractCommonList relatedRecords = resource.getList(uriInfo);
+ AbstractCommonList relatedRecords = resource.getList(getServiceContext(), uriInfo);
if (logger.isTraceEnabled()) {
logger.trace("Identified " + relatedRecords.getTotalItems()
+ " record(s) related to the object record via direction " + relationshipDirection + " with CSID " + csid);
while (morePages == true) {
uriInfo = addFilterForPageSize(uriInfo, currentPage, pageSize);
- AbstractCommonList collectionObjects = collectionObjectResource.getList(uriInfo);
+ AbstractCommonList collectionObjects = collectionObjectResource.getList(getServiceContext(), uriInfo);
appendItemsToCsidsList(noContextCsids, collectionObjects);
if (collectionObjects.getItemsInPage() == pageSize) { // We know we're at the last page when the number of items returned in the last request is less than the page size.
*
* @param taxonCsid The csid of the taxon record
* @return
- * @throws URISyntaxException
- * @throws DocumentException
+ * @throws Exception
*/
- public InvocationResults updateReferencingRareFlags(String taxonCsid, String vocabularyCsid) throws URISyntaxException, DocumentException {
- PoxPayloadOut taxonPayload = findTaxonByCsid(taxonCsid);
+ public InvocationResults updateReferencingRareFlags(String taxonCsid, String vocabularyCsid) throws Exception {
+ PoxPayloadOut taxonPayload = vocabularyCsid == null
+ ? findTaxonByCsid(taxonCsid)
+ : findTaxonByCsid(taxonCsid, vocabularyCsid);
String taxonRefName = getFieldValue(taxonPayload, TaxonConstants.REFNAME_SCHEMA_NAME, TaxonConstants.REFNAME_FIELD_NAME);
RefName.AuthorityItem item = RefName.AuthorityItem.parse(taxonRefName);
*
* @param collectionObjectCsid The csid of the collectionobject
* @return
- * @throws URISyntaxException
- * @throws DocumentException
+ * @throws Exception
*/
- public InvocationResults updateRareFlag(String collectionObjectCsid) throws URISyntaxException, DocumentException {
+ public InvocationResults updateRareFlag(String collectionObjectCsid) throws Exception {
PoxPayloadOut collectionObjectPayload = findCollectionObjectByCsid(collectionObjectCsid);
return updateRareFlag(collectionObjectPayload);
*
* @param collectionObjectPayload The payload representing the collectionobject
* @return
- * @throws URISyntaxException
- * @throws DocumentException
+ * @throws Exception
*/
- public InvocationResults updateRareFlag(PoxPayloadOut collectionObjectPayload) throws URISyntaxException, DocumentException {
+ public InvocationResults updateRareFlag(PoxPayloadOut collectionObjectPayload) throws Exception {
InvocationResults results = new InvocationResults();
String uri = this.getFieldValue(collectionObjectPayload, CollectionObjectBotGardenConstants.URI_SCHEMA_NAME,
*
* @param collectionObjectCsids The csids of the collectionobjects
* @return
- * @throws URISyntaxException
- * @throws DocumentException
+ * @throws Exception
*/
- public InvocationResults updateRareFlags(List<String> collectionObjectCsids) throws URISyntaxException, DocumentException {
+ public InvocationResults updateRareFlags(List<String> collectionObjectCsids) throws Exception {
int numSubmitted = collectionObjectCsids.size();
long numAffected = 0;
* Updates the rare flags of all collectionobjects.
*
* @return
- * @throws URISyntaxException
- * @throws DocumentException
+ * @throws Exception
*/
- public InvocationResults updateAllRareFlags() throws URISyntaxException, DocumentException {
+ public InvocationResults updateAllRareFlags() throws Exception {
long numFound = 0;
long numAffected = 0;
"</document>";
NuxeoBasedResource resource = (NuxeoBasedResource) getResourceMap().get(CollectionObjectClient.SERVICE_NAME);
- resource.update(getResourceMap(), createUriInfo(), collectionObjectCsid, updatePayload);
+ resource.update(getServiceContext(), getResourceMap(), createUriInfo(), collectionObjectCsid, updatePayload);
}
}
private final Logger logger = LoggerFactory.getLogger(RefNameUtils.class);
- public static final String URN_PREFIX = "urn:cspace:";
- public static final int URN_PREFIX_LEN = 11;
+ public static final String SEPARATOR = ":";
+ public static final String URN_PREFIX = "urn";
+ public static final String URN_CSPACE = "cspace";
+ public static final String URN_CSPACE_PREFIX = URN_PREFIX + SEPARATOR + URN_CSPACE + SEPARATOR; // "urn:cspace:"
+ public static final int URN_PREFIX_LEN = URN_CSPACE_PREFIX.length();
public static final String URN_NAME_PREFIX = "urn:cspace:name(";
- public static final int URN_NAME_PREFIX_LEN = 16;
+ public static final int URN_NAME_PREFIX_LEN = URN_NAME_PREFIX.length();
public static final String NAME_SPECIFIER = "name";
public static final String ID_SPECIFIER = "id";
private static final int INSTANCE_DISPLAYNAME_TOKEN = 2;// optional displayName suffix
private static final int INSTANCE_TOKENS_MIN = 2;
private static final int INSTANCE_TOKENS_MAX = 3;
- public static final String SEPARATOR = ":";
- public static class AuthorityInfo {
+ public static String domainToPhrase(String domain) {
+ String result = "";
+
+ String[] split = domain.split("\\.", 0);
+ for (String token : split) {
+ result = result + token + ' ';
+ }
+
+ return result.trim();
+ }
+
+ public static class AuthorityInfo {
private final Logger logger = LoggerFactory.getLogger(AuthorityInfo.class);
private static int MIN_TOKENS = 3;
public String domain;
public static AuthorityInfo parseAuthorityInfo(String refName)
throws IllegalArgumentException {
- if(refName==null || !refName.startsWith(URN_PREFIX))
+ if(refName==null || !refName.startsWith(URN_CSPACE_PREFIX))
throw new IllegalArgumentException( "Null or invalid refName syntax");
String[] refNameTokens = refName.substring(URN_PREFIX_LEN).split(SEPARATOR, AUTH_REFNAME_TOKENS);
return new AuthorityInfo(refNameTokens);
}
public static AuthorityTermInfo parseAuthorityTermInfo(String refName) throws IllegalArgumentException {
- if (refName == null || !refName.startsWith(URN_PREFIX)) {
+ if (refName == null || !refName.startsWith(URN_CSPACE_PREFIX)) {
throw new IllegalArgumentException("Null or invalid refName syntax");
}
String[] refNameTokens = refName.substring(URN_PREFIX_LEN).split(SEPARATOR, AUTH_ITEM_REFNAME_TOKENS);
public static String stripAuthorityTermDisplayName(String refName)
throws IllegalArgumentException {
- if(refName==null || !refName.startsWith(URN_PREFIX))
+ if(refName==null || !refName.startsWith(URN_CSPACE_PREFIX))
throw new IllegalArgumentException( "Null or invalid refName syntax");
String[] refNameTokens = refName.substring(URN_PREFIX_LEN).split(SEPARATOR, AUTH_ITEM_REFNAME_TOKENS);
int rightParen = refNameTokens[ITEM_INSTANCE_TOKEN].indexOf(')');
refNameTokens[ITEM_INSTANCE_TOKEN] = refNameTokens[ITEM_INSTANCE_TOKEN].substring(0, rightParen+1);
- return URN_PREFIX + implodeStringArray(refNameTokens, SEPARATOR);
+ return URN_CSPACE_PREFIX + implodeStringArray(refNameTokens, SEPARATOR);
}
public static String implodeStringArray(String tokens[], String separator) {
public byte[] getWorkflow(
@Context UriInfo uriInfo,
@PathParam("csid") String csid) {
+ return getWorkflowWithExistingContext(null, uriInfo, csid);
+ }
+
+ public byte[] getWorkflowWithExistingContext(
+ ServiceContext<PoxPayloadIn, PoxPayloadOut> existingContext,
+ UriInfo uriInfo,
+ String csid) {
PoxPayloadOut result = null;
try {
String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, uriInfo);
+ if (existingContext != null && existingContext.getCurrentRepositorySession() != null) {
+ ctx.setCurrentRepositorySession(existingContext.getCurrentRepositorySession()); // Reuse the current repo session if one exists
+ }
WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
getRepositoryClient(ctx).get(ctx, csid, handler);
ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(uriInfo);
if (parentCtx != null && parentCtx.getCurrentRepositorySession() != null) {
ctx.setCurrentRepositorySession(parentCtx.getCurrentRepositorySession()); // Reuse the current repo session if one exists
- } DocumentHandler handler = createDocumentHandler(ctx);
+ }
+ DocumentHandler handler = createDocumentHandler(ctx);
getRepositoryClient(ctx).getFiltered(ctx, handler);
AbstractCommonList list = (AbstractCommonList) handler.getCommonPartList();
return list;
// If anonymous access is being attempted, then a tenant ID needs to be set as a query param
//
if (uriInfo == null) {
- String errMsg = "Anonymous access attempted with null UriInfo.";
+ String errMsg = "Anonymous access attempted with missing or invalid tenant ID query or path paramter. A null 'UriInfo' instance was passed into the service context constructor.";
logger.warn(errMsg);
throw new UnauthorizedException(errMsg);
}
import org.collectionspace.services.client.PoxPayloadIn;
import org.collectionspace.services.client.PoxPayloadOut;
+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.DocumentNotFoundException;
import org.nuxeo.ecm.core.api.DocumentModelList;
import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import com.google.common.collect.AbstractIterator;
/**
*
*/
public class LazyAuthorityRefDocList extends DocumentModelListImpl {
+ private static final Logger logger = LoggerFactory.getLogger(LazyAuthorityRefDocList.class);
private static final long serialVersionUID = 1L;
private ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx;
try {
nextPageDocList = fetchPage(nextPageNum, false, true);
+ } catch(DocumentException e) {
+ logger.error(e.getMessage());
}
- catch(DocumentException e) {}
if (nextPageDocList == null || nextPageDocList.size() == 0) {
// There are no more pages.
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.UUID;
import javax.ws.rs.core.Response;
import org.collectionspace.services.client.IRelationsManager;
import org.collectionspace.services.client.PoxPayloadIn;
import org.collectionspace.services.client.PoxPayloadOut;
+import org.collectionspace.services.client.Profiler;
import org.collectionspace.services.common.CSWebApplicationException;
import org.collectionspace.services.common.ServiceMain;
+import org.collectionspace.services.common.ServletTools;
import org.collectionspace.services.common.StoredValuesUriTemplate;
import org.collectionspace.services.common.UriTemplateFactory;
import org.collectionspace.services.common.UriTemplateRegistry;
authRefFieldsByService,
filter.getWhereClause(),
null, // orderByClause
- 2*pageSize,
+ 2, // pageScale
+ pageSize,
useDefaultOrderByClause,
computeTotal);
String strippedRefName = RefNameUtils.stripAuthorityTermDisplayName(refName);
// *** Need to pass in pagination info here.
- int nRefsFound = processRefObjsDocListForList(docList, ctx.getTenantId(), strippedRefName,
+ long nRefsFound = processRefObjsDocListForList(docList, ctx.getTenantId(), strippedRefName,
queriedServiceBindings, authRefFieldsByService, // the actual list size needs to be updated to the size of "list"
list, pageSize, pageNum);
// 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(ctx, docList, ctx.getTenantId(), oldRefName,
+ long nRefsFoundThisPage = processRefObjsDocListForUpdate(ctx, docList, ctx.getTenantId(), oldRefName,
queriedServiceBindings, authRefFieldsByService, // Perform the refName updates on the list of document models
newRefName);
if (nRefsFoundThisPage > 0) {
Map<String, List<AuthRefConfigInfo>> authRefFieldsByService,
String whereClauseAdditions,
String orderByClause,
+ int pageScale,
int pageSize,
boolean useDefaultOrderByClause,
boolean computeTotal) throws DocumentException, DocumentNotFoundException {
authRefFieldsByService,
whereClauseAdditions,
orderByClause,
- pageSize,
+ pageSize*pageScale,
useDefaultOrderByClause,
computeTotal);
}
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
- NuxeoRepositoryClientImpl nuxeoRepoClient = (NuxeoRepositoryClientImpl) repoClient;
- DocumentWrapper<DocumentModelList> docListWrapper = nuxeoRepoClient.findDocs(
+ DocumentModelList docList = findDocs(
+ repoClient,
ctx,
repoSession,
docTypes,
query,
- orderByClause,
- pageNum,
- pageSize,
+ orderByClause,
+ pageNum,
+ pageSize,
useDefaultOrderByClause,
computeTotal);
- // Now we gather the info for each document into the list and return
- DocumentModelList docList = docListWrapper.getWrappedObject();
+
+ return docList;
+ }
+
+ private static final DocumentModelList findDocs(
+ RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient,
+ ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
+ CoreSessionInterface repoSession,
+ List<String> docTypes,
+ String query,
+ String orderByClause,
+ int pageNum,
+ int pageSize,
+ boolean useDefaultOrderByClause,
+ boolean computeTotal)
+ throws DocumentNotFoundException, DocumentException {
+ Profiler profiler = new Profiler(query, 0);
+
+ // Start timing.
+ profiler.start();
+ UUID uuid = UUID.randomUUID();
+
+ // 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()
+ + "," + uuid.toString()
+ + "," + query
+ + "," + pageNum
+ + "," + pageSize
+ + "," + Thread.currentThread().getName();
+ final boolean FORMAT_LOG_MESSAGE = false;
+ profiler.log(csvMsg, FORMAT_LOG_MESSAGE);
+
+ // Now we have to issue the search
+ NuxeoRepositoryClientImpl nuxeoRepoClient = (NuxeoRepositoryClientImpl) repoClient;
+ DocumentWrapper<DocumentModelList> docListWrapper = nuxeoRepoClient.findDocs(
+ ctx,
+ repoSession,
+ docTypes,
+ query,
+ orderByClause,
+ pageNum,
+ pageSize,
+ useDefaultOrderByClause,
+ computeTotal);
+ // Now we gather the info for each document into the list and return
+ DocumentModelList docList = docListWrapper.getWrappedObject();
+
+ // Stop timing and log performance-related metrics.
+ profiler.stop();
+
+ csvMsg =
+ profiler.getStopTime()
+ + "," + uuid.toString()
+ + "," + query
+ + "," + pageNum
+ + "," + pageSize
+ + "," + Thread.currentThread().getName();
+ profiler.log(csvMsg, FORMAT_LOG_MESSAGE);
+
+ profiler.reset();
+
return docList;
}
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
+
+ // Note that this will also match the term item itself, but that will get filtered out when
// we compute actual matches.
AuthorityTermInfo authTermInfo = RefNameUtils.parseAuthorityTermInfo(refName);
+
+ // Example refname: urn:cspace:pahma.cspace.berkeley.edu:personauthorities:name(person):item:name(ReneRichie1586477168934)
+ // Corresponding phrase: "urn cspace pahma cspace berkeley edu personauthorities name person item name ReneRichie1586477168934
+
+ String refnamePhrase = String.format("urn cspace %s %s name %s item name %s",
+ RefNameUtils.domainToPhrase(authTermInfo.inAuthority.domain),
+ authTermInfo.inAuthority.resource,
+ authTermInfo.inAuthority.name,
+ authTermInfo.name
+ );
+ refnamePhrase = String.format("\"%s\"", refnamePhrase); // surround the phase in double quotes to indicate this is a NXQL phrase search
- String keywords = RefNameUtils.URN_PREFIX
- + " AND " + (authTermInfo.inAuthority.name != null
- ? authTermInfo.inAuthority.name : authTermInfo.inAuthority.csid)
- + " AND " + (authTermInfo.name != null
- ? authTermInfo.name : authTermInfo.csid); // REM - This seems likely to cause trouble? We should consider searching for the full refname -excluding the display name suffix?
-
- String whereClauseStr = QueryManager.createWhereClauseFromKeywords(keywords);
+ String whereClauseStr = QueryManager.createWhereClauseFromKeywords(refnamePhrase);
if (logger.isTraceEnabled()) {
- logger.trace("The 'where' clause to find refObjs is: ", whereClauseStr);
+ logger.trace("The 'where' clause to find refObjs is: ", refnamePhrase);
}
return whereClauseStr;
return result;
}
- private static int processRefObjsDocListForUpdate(
+ private static long processRefObjsDocListForUpdate(
ServiceContext ctx,
DocumentModelList docList,
String tenantId,
authRefFieldsByService, null, 0, 0, newAuthorityRefName);
}
- private static int processRefObjsDocListForList(
+ private static long processRefObjsDocListForList(
DocumentModelList docList,
String tenantId,
String refName,
* an open session, and caller must release Session after calling this.
*
*/
- private static int processRefObjsDocList(
+ private static long processRefObjsDocList(
DocumentModelList docList,
String tenantId,
String refName,
String newAuthorityRefName) {
UriTemplateRegistry registry = ServiceMain.getInstance().getUriTemplateRegistry();
Iterator<DocumentModel> iter = docList.iterator();
- int nRefsFoundTotal = 0;
+ long nRefsFoundTotal = 0;
+ long nRefsFalsePositives = 0;
boolean foundSelf = false;
+ boolean warningLogged = 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;
+ long nDocsReturnedInQuery = (int)docList.totalSize();
+ long nDocsProcessed = 0;
+ long firstItemInPage = pageNum*pageSize;
while (iter.hasNext()) {
+ if (!warningLogged && (float)nRefsFalsePositives / nDocsReturnedInQuery > 0.5) {
+ warningLogged = true;
+ String msg = String.format("When searching for documents referencing the term '%s', more than 1/2 of the results were false-positives.",
+ refName);
+ logger.warn(msg);
+ }
DocumentModel docModel = iter.next();
AuthorityRefDocList.AuthorityRefDocItem ilistItem;
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);
+ if (firstItemInPage > 100) {
+ String msg = String.format("Processing a large offset for records referencing (term:%s, size:%d, num:%d) - will be expensive!!!",
+ refName, pageSize, pageNum);
+ logger.warn(msg);
}
// Note that we have to go through check all the fields to determine the actual page start
ilistItem = new AuthorityRefDocList.AuthorityRefDocItem();
throw new RuntimeException(
"getAuthorityRefDocs: internal logic error: can't fetch authRefFields for DocType.");
}
- //String authRefAncestorField = "";
- //String authRefDescendantField = "";
- //String sourceField = "";
ArrayList<RefNameServiceUtils.AuthRefInfo> foundProps = new ArrayList<RefNameServiceUtils.AuthRefInfo>();
try {
:refName.equals(docRefName)) {
// We found the self for an item
foundSelf = true;
- logger.debug("getAuthorityRefDocs: Result: "
+ logger.trace("getAuthorityRefDocs: Result: "
+ docType + " [" + NuxeoUtils.getCsid(docModel)
+ "] appears to be self for: ["
+ refName + "]");
} else {
- logger.debug("getAuthorityRefDocs: Result: "
+ nRefsFalsePositives++;
+ logger.trace("getAuthorityRefDocs: Result: "
+ docType + " [" + NuxeoUtils.getCsid(docModel)
+ "] does not reference ["
+ refName + "]");
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)) {
+ 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) {
+ long 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)
+ if (!foundSelf)
unprocessedDocs--;
nRefsFoundTotal += unprocessedDocs;
}
break;
}
} // close while(iterator)
+
+ // Log a final warning if we find too many false-positives.
+ if ((float)nRefsFalsePositives / nDocsReturnedInQuery > 0.33) {
+ String msg = String.format("Found %d false-positives and %d only true references the refname:%s",
+ nRefsFalsePositives, nRefsFoundTotal, refName);
+ logger.warn(msg);
+ }
+
return nRefsFoundTotal;
}
try {
result = docModel.getPropertyValue(propertyName);
} catch (NullPointerException npe) {
- result = null;
+ logger.warn(String.format("Could not get a value for the property '%s' in Nuxeo document with CSID '%s'.",
+ propertyName, docModel != null ? docModel.getName() : "<null>"));
}
return result;
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ This config is used by the maven surefire plugin (for tests), as configured in services/pom.xml.
+ For runtime logging config, see services/JaxRsServiceProvider/src/main/resources/log4j2.xml.
+-->
+<Configuration status="WARN">
+ <Properties>
+ <Property name="logPattern">%d %-5p [%t] [%c:%L] %m%n</Property>
+ </Properties>
+
+ <Appenders>
+ <Console name="ConsoleAppender" target="SYSTEM_OUT">
+ <PatternLayout pattern="${logPattern}" />
+ </Console>
+
+ <File name="LogFileAppender" append="false" fileName="target/test.log">
+ <PatternLayout pattern="${logPattern}" />
+ </File>
+ </Appenders>
+
+ <Loggers>
+ <Root level="DEBUG">
+ <AppenderRef ref="ConsoleAppender"/>
+ <AppenderRef ref="LogFileAppender" />
+ </Root>
+
+ <Logger name="httpclient" level="INFO" />
+ <Logger name="org.apache" level="INFO" />
+ <Logger name="org.collectionspace.services.client.PoxPayloadIn" level="DEBUG" />
+ <Logger name="org.collectionspace.services.client.PoxPayloadOut" level="DEBUG" />
+ <Logger name="org.collectionspace" level="DEBUG" />
+ <Logger name="org.jboss.resteasy" level="INFO" />
+ </Loggers>
+</Configuration>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ This config is used by the maven surefire plugin (for tests), as configured in services/pom.xml.
+ For runtime logging config, see services/JaxRsServiceProvider/src/main/resources/log4j2.xml.
+-->
+<Configuration status="WARN">
+ <Properties>
+ <Property name="logPattern">%d %-5p [%t] [%c:%L] %m%n</Property>
+ </Properties>
+
+ <Appenders>
+ <Console name="ConsoleAppender" target="SYSTEM_OUT">
+ <PatternLayout pattern="${logPattern}" />
+ </Console>
+
+ <File name="LogFileAppender" append="false" fileName="target/test.log">
+ <PatternLayout pattern="${logPattern}" />
+ </File>
+ </Appenders>
+
+ <Loggers>
+ <Root level="DEBUG">
+ <AppenderRef ref="ConsoleAppender"/>
+ <AppenderRef ref="LogFileAppender" />
+ </Root>
+
+ <Logger name="httpclient" level="INFO" />
+ <Logger name="org.apache" level="INFO" />
+ <Logger name="org.collectionspace.services.client.PoxPayloadIn" level="DEBUG" />
+ <Logger name="org.collectionspace.services.client.PoxPayloadOut" level="DEBUG" />
+ <Logger name="org.collectionspace" level="DEBUG" />
+ <Logger name="org.jboss.resteasy" level="INFO" />
+ </Loggers>
+</Configuration>
//
if (!Tools.isEmpty(invContext.getOutputMIME())) {
outMimeType.append(invContext.getOutputMIME());
- }
- if (outMimeType == null || Tools.isEmpty(outMimeType.toString())) {
- String reportOutputMime = (String) NuxeoUtils.getProperyValue(docModel, ReportJAXBSchema.OUTPUT_MIME); //docModel.getPropertyValue(ReportJAXBSchema.OUTPUT_MIME);
- if (!Tools.isEmpty(reportOutputMime)) {
- outMimeType.append(reportOutputMime);
- } else {
- outMimeType.append(ReportClient.DEFAULT_REPORT_OUTPUT_MIME);
- }
+ } else if (Tools.isEmpty(outMimeType.toString()) && params.containsKey("OutputMIME")) {
+ // See UCB - https://github.com/cspace-deployment/services/pull/140/files
+ outMimeType.append(params.get("OutputMIME"));
+ } else {
+ // Use the default
+ String reportOutputMime = (String) NuxeoUtils.getProperyValue(docModel, ReportJAXBSchema.OUTPUT_MIME); //docModel.getPropertyValue(ReportJAXBSchema.OUTPUT_MIME);
+ if (!Tools.isEmpty(reportOutputMime)) {
+ outMimeType.append(reportOutputMime);
+ } else {
+ outMimeType.append(ReportClient.DEFAULT_REPORT_OUTPUT_MIME);
+ }
}
} catch (PropertyException pe) {
if (logger.isDebugEnabled()) {
*/
package org.collectionspace.services.vocabulary.nuxeo;
+import org.collectionspace.services.client.VocabularyClient;
+
/**
* VocabularyConstants processes CollectionObject document
*
public final static String NUXEO_DOCTYPE = "Vocabulary";
public final static String NUXEO_SCHEMA_NAME = "vocabulary";
public final static String NUXEO_DC_TITLE = "CollectionSpace-Vocabulary";
+
+ public static final String COMMON_SCHEMA_NAME = VocabularyClient.SERVICE_COMMON_PART_NAME;
+ public final static String COMMON_ITEM_SCHEMA_NAME = VocabularyClient.SERVICE_ITEM_COMMON_PART_NAME;
+
+ public final static String DISPLAY_NAME_SCHEMA_NAME = COMMON_ITEM_SCHEMA_NAME;
+ public final static String DISPLAY_NAME_FIELD_NAME = "displayName";
}