From: Aron Roberts Date: Wed, 28 Sep 2011 01:53:10 +0000 (+0000) Subject: CSPACE-3178,CSPACE-2215: First iteration of automatic creation of refNames from short... X-Git-Url: https://git.aero2k.de/?a=commitdiff_plain;h=7383b5ca699b48792737a886bdb6a8c7174e212d;p=tmp%2Fjakarta-migration.git CSPACE-3178,CSPACE-2215: First iteration of automatic creation of refNames from short identifiers, and of short identifiers from display names, in authority and vocabulary services. Currently, client-supplied refNames are still accepted, rather than being dropped; this will change soon. --- diff --git a/services/authority/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityResource.java b/services/authority/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityResource.java index 328067fe0..029fef8a4 100644 --- a/services/authority/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityResource.java +++ b/services/authority/src/main/java/org/collectionspace/services/common/vocabulary/AuthorityResource.java @@ -91,134 +91,136 @@ import java.util.List; public abstract class AuthorityResource extends ResourceBase { - protected Class authCommonClass; - protected Class resourceClass; - protected String authorityCommonSchemaName; - protected String authorityItemCommonSchemaName; - - final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType(); - - final static String URN_PREFIX = "urn:cspace:"; - final static int URN_PREFIX_LEN = URN_PREFIX.length(); - final static String URN_PREFIX_NAME = "name("; - final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length(); - final static String URN_PREFIX_ID = "id("; - final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length(); - final static String FETCH_SHORT_ID = "_fetch_"; - + protected Class authCommonClass; + protected Class resourceClass; + protected String authorityCommonSchemaName; + protected String authorityItemCommonSchemaName; + final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType(); + final static String URN_PREFIX = "urn:cspace:"; + final static int URN_PREFIX_LEN = URN_PREFIX.length(); + final static String URN_PREFIX_NAME = "name("; + final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length(); + final static String URN_PREFIX_ID = "id("; + final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length(); + final static String FETCH_SHORT_ID = "_fetch_"; final Logger logger = LoggerFactory.getLogger(AuthorityResource.class); - - public enum SpecifierForm { CSID, URN_NAME }; - + + public enum SpecifierForm { + + CSID, URN_NAME + }; + public class Specifier { - public SpecifierForm form; - public String value; - Specifier(SpecifierForm form, String value) { - this.form = form; - this.value = value; - } + + public SpecifierForm form; + public String value; + + Specifier(SpecifierForm form, String value) { + this.form = form; + this.value = value; + } } - + protected Specifier getSpecifier(String specifierIn, String method, String op) throws WebApplicationException { - if (logger.isDebugEnabled()) { - logger.debug("getSpecifier called by: "+method+" with specifier: "+specifierIn); - } - if (specifierIn != null) { - if(!specifierIn.startsWith(URN_PREFIX)) { - // We'll assume it is a CSID and complain if it does not match - return new Specifier(SpecifierForm.CSID, specifierIn); - } else { - if(specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) { - int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN); - if(closeParen>=0) { - return new Specifier(SpecifierForm.URN_NAME, - specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen)); - } - } else if(specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) { - int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN); - if(closeParen>=0) { - return new Specifier(SpecifierForm.CSID, - specifierIn.substring(URN_ID_PREFIX_LEN, closeParen)); - } - } - } - } - logger.error(method+": bad or missing specifier!"); - Response response = Response.status(Response.Status.BAD_REQUEST).entity( - op+" failed on bad or missing Authority specifier").type( - "text/plain").build(); - throw new WebApplicationException(response); + if (logger.isDebugEnabled()) { + logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn); + } + if (specifierIn != null) { + if (!specifierIn.startsWith(URN_PREFIX)) { + // We'll assume it is a CSID and complain if it does not match + return new Specifier(SpecifierForm.CSID, specifierIn); + } else { + if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) { + int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN); + if (closeParen >= 0) { + return new Specifier(SpecifierForm.URN_NAME, + specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen)); + } + } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) { + int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN); + if (closeParen >= 0) { + return new Specifier(SpecifierForm.CSID, + specifierIn.substring(URN_ID_PREFIX_LEN, closeParen)); + } + } + } + } + logger.error(method + ": bad or missing specifier!"); + Response response = Response.status(Response.Status.BAD_REQUEST).entity( + op + " failed on bad or missing Authority specifier").type( + "text/plain").build(); + throw new WebApplicationException(response); } /** - * Instantiates a new Authority resource. - */ - public AuthorityResource(Class authCommonClass, Class resourceClass, - String authorityCommonSchemaName, String authorityItemCommonSchemaName) { - this.authCommonClass = authCommonClass; - this.resourceClass = resourceClass; - this.authorityCommonSchemaName = authorityCommonSchemaName; - this.authorityItemCommonSchemaName = authorityItemCommonSchemaName; - } - - public abstract String getItemServiceName(); - - @Override - protected String getVersionString() { - return "$LastChangedRevision: 2617 $"; - } - - @Override - public Class getCommonPartClass() { - return authCommonClass; - } - - /** - * Creates the item document handler. - * - * @param ctx the ctx - * @param inAuthority the in vocabulary - * - * @return the document handler - * - * @throws Exception the exception - */ - protected DocumentHandler createItemDocumentHandler( - ServiceContext ctx, - String inAuthority, String parentShortIdentifier) - throws Exception { - String authorityRefNameBase; - AuthorityItemDocumentModelHandler docHandler; - - if(parentShortIdentifier==null) { - authorityRefNameBase = null; - } else { - ServiceContext parentCtx = - createServiceContext(getServiceName()); - if(parentShortIdentifier.equals(FETCH_SHORT_ID)) { - // Get from parent document - parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority); - } - authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier); - } - - docHandler = (AuthorityItemDocumentModelHandler)createDocumentHandler(ctx, - ctx.getCommonPartLabel(getItemServiceName()), - authCommonClass); - docHandler.setInAuthority(inAuthority); - docHandler.setAuthorityRefNameBase(authorityRefNameBase); - - return docHandler; - } - + * Instantiates a new Authority resource. + */ + public AuthorityResource(Class authCommonClass, Class resourceClass, + String authorityCommonSchemaName, String authorityItemCommonSchemaName) { + this.authCommonClass = authCommonClass; + this.resourceClass = resourceClass; + this.authorityCommonSchemaName = authorityCommonSchemaName; + this.authorityItemCommonSchemaName = authorityItemCommonSchemaName; + } + + public abstract String getItemServiceName(); + + @Override + protected String getVersionString() { + return "$LastChangedRevision: 2617 $"; + } + + @Override + public Class getCommonPartClass() { + return authCommonClass; + } + + /** + * Creates the item document handler. + * + * @param ctx the ctx + * @param inAuthority the in vocabulary + * + * @return the document handler + * + * @throws Exception the exception + */ + protected DocumentHandler createItemDocumentHandler( + ServiceContext ctx, + String inAuthority, String parentShortIdentifier) + throws Exception { + String authorityRefNameBase; + AuthorityItemDocumentModelHandler docHandler; + + if (parentShortIdentifier == null) { + authorityRefNameBase = null; + } else { + ServiceContext parentCtx = + createServiceContext(getServiceName()); + if (parentShortIdentifier.equals(FETCH_SHORT_ID)) { + // Get from parent document + parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority); + } + authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier); + } + + docHandler = (AuthorityItemDocumentModelHandler) createDocumentHandler(ctx, + ctx.getCommonPartLabel(getItemServiceName()), + authCommonClass); + docHandler.setInAuthority(inAuthority); + docHandler.setAuthorityRefNameBase(authorityRefNameBase); + + return docHandler; + } + public String getAuthShortIdentifier( ServiceContext ctx, String authCSID) throws DocumentNotFoundException, DocumentException { String shortIdentifier = null; try { DocumentWrapper wrapDoc = getRepositoryClient(ctx).getDocFromCsid(ctx, authCSID); - AuthorityDocumentModelHandler handler = - (AuthorityDocumentModelHandler)createDocumentHandler(ctx); + AuthorityDocumentModelHandler handler = + (AuthorityDocumentModelHandler) createDocumentHandler(ctx); shortIdentifier = handler.getShortIdentifier(wrapDoc, authorityCommonSchemaName); } catch (Exception e) { if (logger.isDebugEnabled()) { @@ -229,37 +231,38 @@ public abstract class AuthorityResource return shortIdentifier; } - - protected String buildAuthorityRefNameBase( - ServiceContext ctx, String shortIdentifier) { + protected String buildAuthorityRefNameBase( + ServiceContext ctx, String shortIdentifier) { RefName.Authority authority = RefName.buildAuthority(ctx.getTenantName(), ctx.getServiceName(), shortIdentifier, null); return authority.toString(); - } + } public static class CsidAndShortIdentifier { + String CSID; String shortIdentifier; } - public String lookupParentCSID (String parentspecifier, String method, String op, MultivaluedMap queryParams) - throws Exception { - CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(parentspecifier, method, op, queryParams); + public String lookupParentCSID(String parentspecifier, String method, String op, MultivaluedMap queryParams) + throws Exception { + CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(parentspecifier, method, op, queryParams); return tempResult.CSID; } - public CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer (String parentspecifier, String method, String op, MultivaluedMap queryParams) - throws Exception { + public CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(String parentspecifier, String method, String op, MultivaluedMap queryParams) + throws Exception { CsidAndShortIdentifier result = new CsidAndShortIdentifier(); Specifier parentSpec = getSpecifier(parentspecifier, method, op); // Note that we have to create the service context for the Items, not the main service String parentcsid; String parentShortIdentifier; - if(parentSpec.form==SpecifierForm.CSID) { + if (parentSpec.form == SpecifierForm.CSID) { parentShortIdentifier = null; parentcsid = parentSpec.value; // Uncomment when app layer is ready to integrate - // parentShortIdentifier = FETCH_SHORT_ID; + // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178 + parentShortIdentifier = FETCH_SHORT_ID; } else { parentShortIdentifier = parentSpec.value; String whereClause = buildWhereForAuthByName(parentSpec.value); @@ -267,14 +270,15 @@ public abstract class AuthorityResource parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item? } result.CSID = parentcsid; + result.shortIdentifier = parentShortIdentifier; return result; } - public String lookupItemCSID (String itemspecifier, String parentcsid, String method, String op, ServiceContext ctx) - throws DocumentException { + public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext ctx) + throws DocumentException { String itemcsid; Specifier itemSpec = getSpecifier(itemspecifier, method, op); - if(itemSpec.form==SpecifierForm.CSID) { + if (itemSpec.form == SpecifierForm.CSID) { itemcsid = itemSpec.value; } else { String itemWhereClause = buildWhereForAuthItemByName(itemSpec.value, parentcsid); @@ -283,192 +287,191 @@ public abstract class AuthorityResource return itemcsid; } - @POST - public Response createAuthority(String xmlPayload) { - try { - PoxPayloadIn input = new PoxPayloadIn(xmlPayload); - ServiceContext ctx = createServiceContext(input); - DocumentHandler handler = createDocumentHandler(ctx); - String csid = getRepositoryClient(ctx).create(ctx, handler); - UriBuilder path = UriBuilder.fromResource(resourceClass); - path.path("" + csid); - Response response = Response.created(path.build()).build(); - return response; - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.CREATE_FAILED); - } - } - - protected String buildWhereForAuthByName(String name) { - return authorityCommonSchemaName+ - ":"+AuthorityJAXBSchema.SHORT_IDENTIFIER+ - "='"+name+"'"; - } - - protected String buildWhereForAuthItemByName(String name, String parentcsid) { - return - authorityItemCommonSchemaName+ - ":"+AuthorityItemJAXBSchema.SHORT_IDENTIFIER+ - "='"+name+"' AND " - + authorityItemCommonSchemaName + ":" - + AuthorityItemJAXBSchema.IN_AUTHORITY + "=" - + "'" + parentcsid + "'"; - } - - /** - * Gets the authority. - * - * @param specifier either a CSID or one of the urn forms - * - * @return the authority - */ - @GET - @Path("{csid}") - @Override - public byte[] get( // getAuthority( - @Context UriInfo ui, - @PathParam("csid") String specifier) { - PoxPayloadOut result = null; - try { - ServiceContext ctx = createServiceContext(ui); + @POST + public Response createAuthority(String xmlPayload) { + try { + PoxPayloadIn input = new PoxPayloadIn(xmlPayload); + ServiceContext ctx = createServiceContext(input); + DocumentHandler handler = createDocumentHandler(ctx); + String csid = getRepositoryClient(ctx).create(ctx, handler); + UriBuilder path = UriBuilder.fromResource(resourceClass); + path.path("" + csid); + Response response = Response.created(path.build()).build(); + return response; + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.CREATE_FAILED); + } + } + + protected String buildWhereForAuthByName(String name) { + return authorityCommonSchemaName + + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER + + "='" + name + "'"; + } + + protected String buildWhereForAuthItemByName(String name, String parentcsid) { + return authorityItemCommonSchemaName + + ":" + AuthorityItemJAXBSchema.SHORT_IDENTIFIER + + "='" + name + "' AND " + + authorityItemCommonSchemaName + ":" + + AuthorityItemJAXBSchema.IN_AUTHORITY + "=" + + "'" + parentcsid + "'"; + } + + /** + * Gets the authority. + * + * @param specifier either a CSID or one of the urn forms + * + * @return the authority + */ + @GET + @Path("{csid}") + @Override + public byte[] get( // getAuthority( + @Context UriInfo ui, + @PathParam("csid") String specifier) { + PoxPayloadOut result = null; + try { + ServiceContext ctx = createServiceContext(ui); DocumentHandler handler = createDocumentHandler(ctx); Specifier spec = getSpecifier(specifier, "getAuthority", "GET"); - if(spec.form == SpecifierForm.CSID) { - if (logger.isDebugEnabled()) { - logger.debug("getAuthority with csid=" + spec.value); - } - getRepositoryClient(ctx).get(ctx, spec.value, handler); - } else { - String whereClause = buildWhereForAuthByName(spec.value); - DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1); - handler.setDocumentFilter(myFilter); - getRepositoryClient(ctx).get(ctx, handler); - } - result = ctx.getOutput(); - - } catch (Exception e) { + if (spec.form == SpecifierForm.CSID) { + if (logger.isDebugEnabled()) { + logger.debug("getAuthority with csid=" + spec.value); + } + getRepositoryClient(ctx).get(ctx, spec.value, handler); + } else { + String whereClause = buildWhereForAuthByName(spec.value); + DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1); + handler.setDocumentFilter(myFilter); + getRepositoryClient(ctx).get(ctx, handler); + } + result = ctx.getOutput(); + + } catch (Exception e) { throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier); - } - - if (result == null) { - Response response = Response.status(Response.Status.NOT_FOUND).entity( - "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type( - "text/plain").build(); - throw new WebApplicationException(response); - } - - return result.getBytes(); - } - - /** - * Finds and populates the authority list. - * - * @param ui the ui - * - * @return the authority list - */ + } + + if (result == null) { + Response response = Response.status(Response.Status.NOT_FOUND).entity( + "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type( + "text/plain").build(); + throw new WebApplicationException(response); + } + + return result.getBytes(); + } + + /** + * Finds and populates the authority list. + * + * @param ui the ui + * + * @return the authority list + */ @GET @Produces("application/xml") public AbstractCommonList getAuthorityList(@Context UriInfo ui) { - try { - MultivaluedMap queryParams = ui.getQueryParameters(); - ServiceContext ctx = createServiceContext(queryParams); - DocumentHandler handler = createDocumentHandler(ctx); - DocumentFilter myFilter = handler.getDocumentFilter(); - String nameQ = queryParams.getFirst("refName"); - if (nameQ != null) { - myFilter.setWhereClause(authorityCommonSchemaName+":refName='" + nameQ + "'"); - } - getRepositoryClient(ctx).getFiltered(ctx, handler); - return (AbstractCommonList) handler.getCommonPartList(); + try { + MultivaluedMap queryParams = ui.getQueryParameters(); + ServiceContext ctx = createServiceContext(queryParams); + DocumentHandler handler = createDocumentHandler(ctx); + DocumentFilter myFilter = handler.getDocumentFilter(); + String nameQ = queryParams.getFirst("refName"); + if (nameQ != null) { + myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'"); + } + getRepositoryClient(ctx).getFiltered(ctx, handler); + return (AbstractCommonList) handler.getCommonPartList(); } catch (Exception e) { throw bigReThrow(e, ServiceMessages.GET_FAILED); - } - } - - /** - * Update authority. - * - * @param specifier the csid or id - * - * @return the multipart output - */ - @PUT - @Path("{csid}") - public byte[] updateAuthority( - @PathParam("csid") String specifier, - String xmlPayload) { - PoxPayloadOut result = null; - try { - PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload); - Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE"); - ServiceContext ctx = createServiceContext(theUpdate); - DocumentHandler handler = createDocumentHandler(ctx); - String csid; - if(spec.form==SpecifierForm.CSID) { - csid = spec.value; - } else { - String whereClause = buildWhereForAuthByName(spec.value); - csid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause); - } - getRepositoryClient(ctx).update(ctx, csid, handler); - result = ctx.getOutput(); - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.UPDATE_FAILED); - } - return result.getBytes(); - } - - /** - * Delete authority. - * - * @param csid the csid - * - * @return the response - */ - @DELETE - @Path("{csid}") - public Response deleteAuthority(@PathParam("csid") String csid) { - if (logger.isDebugEnabled()) { - logger.debug("deleteAuthority with csid=" + csid); - } - try { + } + } + + /** + * Update authority. + * + * @param specifier the csid or id + * + * @return the multipart output + */ + @PUT + @Path("{csid}") + public byte[] updateAuthority( + @PathParam("csid") String specifier, + String xmlPayload) { + PoxPayloadOut result = null; + try { + PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload); + Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE"); + ServiceContext ctx = createServiceContext(theUpdate); + DocumentHandler handler = createDocumentHandler(ctx); + String csid; + if (spec.form == SpecifierForm.CSID) { + csid = spec.value; + } else { + String whereClause = buildWhereForAuthByName(spec.value); + csid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause); + } + getRepositoryClient(ctx).update(ctx, csid, handler); + result = ctx.getOutput(); + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.UPDATE_FAILED); + } + return result.getBytes(); + } + + /** + * Delete authority. + * + * @param csid the csid + * + * @return the response + */ + @DELETE + @Path("{csid}") + public Response deleteAuthority(@PathParam("csid") String csid) { + if (logger.isDebugEnabled()) { + logger.debug("deleteAuthority with csid=" + csid); + } + try { ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid"); ServiceContext ctx = createServiceContext(); - getRepositoryClient(ctx).delete(ctx, csid); - return Response.status(HttpResponseCodes.SC_OK).build(); - } catch (Exception e) { + getRepositoryClient(ctx).delete(ctx, csid); + return Response.status(HttpResponseCodes.SC_OK).build(); + } catch (Exception e) { throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid); - } - } - - /************************************************************************* - * Create an AuthorityItem - this is a sub-resource of Authority - * @param specifier either a CSID or one of the urn forms - * @return Authority item response - *************************************************************************/ - @POST - @Path("{csid}/items") - public Response createAuthorityItem(@Context UriInfo ui, @PathParam("csid") String specifier, String xmlPayload) { - try { - PoxPayloadIn input = new PoxPayloadIn(xmlPayload); + } + } + + /************************************************************************* + * Create an AuthorityItem - this is a sub-resource of Authority + * @param specifier either a CSID or one of the urn forms + * @return Authority item response + *************************************************************************/ + @POST + @Path("{csid}/items") + public Response createAuthorityItem(@Context UriInfo ui, @PathParam("csid") String specifier, String xmlPayload) { + try { + PoxPayloadIn input = new PoxPayloadIn(xmlPayload); ServiceContext ctx = createServiceContext(getItemServiceName(), input); ctx.setUriInfo(ui); //Laramie // Note: must have the parentShortId, to do the create. - CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(specifier,"createAuthorityItem", "CREATE_ITEM", null); + CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(specifier, "createAuthorityItem", "CREATE_ITEM", null); DocumentHandler handler = createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier); - String itemcsid = getRepositoryClient(ctx).create(ctx, handler); - UriBuilder path = UriBuilder.fromResource(resourceClass); - path.path(parent.CSID + "/items/" + itemcsid); - Response response = Response.created(path.build()).build(); - return response; - } catch (Exception e) { + String itemcsid = getRepositoryClient(ctx).create(ctx, handler); + UriBuilder path = UriBuilder.fromResource(resourceClass); + path.path(parent.CSID + "/items/" + itemcsid); + Response response = Response.created(path.build()).build(); + return response; + } catch (Exception e) { throw bigReThrow(e, ServiceMessages.CREATE_FAILED); - } - } - + } + } + @GET @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH) public byte[] getItemWorkflow( @@ -476,13 +479,13 @@ public abstract class AuthorityResource @PathParam("itemcsid") String itemcsid) { PoxPayloadOut result = null; - try { + try { ServiceContext parentCtx = createServiceContext(getItemServiceName()); String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName(); - - MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME); - WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx); - ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace + + MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME); + WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx); + ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace getRepositoryClient(ctx).get(ctx, itemcsid, handler); result = ctx.getOutput(); } catch (Exception e) { @@ -496,148 +499,147 @@ public abstract class AuthorityResource public byte[] updateWorkflow( @PathParam("csid") String csid, @PathParam("itemcsid") String itemcsid, - String xmlPayload) { + String xmlPayload) { PoxPayloadOut result = null; - try { - ServiceContext parentCtx = createServiceContext(getItemServiceName()); - String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName(); + try { + ServiceContext parentCtx = createServiceContext(getItemServiceName()); + String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName(); - PoxPayloadIn workflowUpdate = new PoxPayloadIn(xmlPayload); - MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, workflowUpdate); + PoxPayloadIn workflowUpdate = new PoxPayloadIn(xmlPayload); + MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, workflowUpdate); WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx); - ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace - getRepositoryClient(ctx).update(ctx, itemcsid, handler); - result = ctx.getOutput(); + ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace + getRepositoryClient(ctx).update(ctx, itemcsid, handler); + result = ctx.getOutput(); } catch (Exception e) { throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid); } return result.getBytes(); } - - /** - * Gets the authority item. - * - * @param parentspecifier either a CSID or one of the urn forms - * @param itemspecifier either a CSID or one of the urn forms - * - * @return the authority item - */ - @GET - @Path("{csid}/items/{itemcsid}") - public byte[] getAuthorityItem( - @Context Request request, + /** + * Gets the authority item. + * + * @param parentspecifier either a CSID or one of the urn forms + * @param itemspecifier either a CSID or one of the urn forms + * + * @return the authority item + */ + @GET + @Path("{csid}/items/{itemcsid}") + public byte[] getAuthorityItem( + @Context Request request, @Context UriInfo ui, - @PathParam("csid") String parentspecifier, - @PathParam("itemcsid") String itemspecifier) { - PoxPayloadOut result = null; - try { - JaxRsContext jaxRsContext = new JaxRsContext(request, ui); + @PathParam("csid") String parentspecifier, + @PathParam("itemcsid") String itemspecifier) { + PoxPayloadOut result = null; + try { + JaxRsContext jaxRsContext = new JaxRsContext(request, ui); MultivaluedMap queryParams = ui.getQueryParameters(); String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", queryParams); RemoteServiceContext ctx = null; - ctx = (RemoteServiceContext)createServiceContext(getItemServiceName(), queryParams); - ctx.setJaxRsContext(jaxRsContext); + ctx = (RemoteServiceContext) createServiceContext(getItemServiceName(), queryParams); + ctx.setJaxRsContext(jaxRsContext); - ctx.setUriInfo(ui); //ARG! must pass this or subsequent calls will not have a ui. + ctx.setUriInfo(ui); //ARG! must pass this or subsequent calls will not have a ui. - // We omit the parentShortId, only needed when doing a create... - DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null); + // We omit the parentShortId, only needed when doing a create... + DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null); Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM"); - if(itemSpec.form==SpecifierForm.CSID) { - getRepositoryClient(ctx).get(ctx, itemSpec.value, handler); - } else { - String itemWhereClause = - buildWhereForAuthItemByName(itemSpec.value, parentcsid); - DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1); - handler.setDocumentFilter(myFilter); - getRepositoryClient(ctx).get(ctx, handler); - } - // TODO should we assert that the item is in the passed vocab? - result = ctx.getOutput(); - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.GET_FAILED); - } - if (result == null) { - Response response = Response.status(Response.Status.NOT_FOUND).entity( - "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type( - "text/plain").build(); - throw new WebApplicationException(response); - } - return result.getBytes(); - } - - /** - * Gets the authorityItem list for the specified authority - * If partialPerm is specified, keywords will be ignored. - * - * @param specifier either a CSID or one of the urn forms - * @param partialTerm if non-null, matches partial terms - * @param keywords if non-null, matches terms in the keyword index for items - * @param ui passed to include additional parameters, like pagination controls - * - * @return the authorityItem list - */ - @GET - @Path("{csid}/items") - @Produces("application/xml") - public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier, - @Context UriInfo ui) { - try { - MultivaluedMap queryParams = ui.getQueryParameters(); - String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM); - String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW); - String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS); - - String qualifiedDisplayNameField = authorityItemCommonSchemaName + ":" - + AuthorityItemJAXBSchema.DISPLAY_NAME; - + if (itemSpec.form == SpecifierForm.CSID) { + getRepositoryClient(ctx).get(ctx, itemSpec.value, handler); + } else { + String itemWhereClause = + buildWhereForAuthItemByName(itemSpec.value, parentcsid); + DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1); + handler.setDocumentFilter(myFilter); + getRepositoryClient(ctx).get(ctx, handler); + } + // TODO should we assert that the item is in the passed vocab? + result = ctx.getOutput(); + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.GET_FAILED); + } + if (result == null) { + Response response = Response.status(Response.Status.NOT_FOUND).entity( + "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type( + "text/plain").build(); + throw new WebApplicationException(response); + } + return result.getBytes(); + } + + /** + * Gets the authorityItem list for the specified authority + * If partialPerm is specified, keywords will be ignored. + * + * @param specifier either a CSID or one of the urn forms + * @param partialTerm if non-null, matches partial terms + * @param keywords if non-null, matches terms in the keyword index for items + * @param ui passed to include additional parameters, like pagination controls + * + * @return the authorityItem list + */ + @GET + @Path("{csid}/items") + @Produces("application/xml") + public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier, + @Context UriInfo ui) { + try { + MultivaluedMap queryParams = ui.getQueryParameters(); + String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM); + String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW); + String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS); + + String qualifiedDisplayNameField = authorityItemCommonSchemaName + ":" + + AuthorityItemJAXBSchema.DISPLAY_NAME; + // Note that docType defaults to the ServiceName, so we're fine with that. ServiceContext ctx = null; String parentcsid = lookupParentCSID(specifier, "getAuthorityItemList", "LIST", queryParams); - ctx = createServiceContext(getItemServiceName(), queryParams); - // We omit the parentShortId, only needed when doing a create... - DocumentHandler handler = createItemDocumentHandler(ctx, - parentcsid, null); - DocumentFilter myFilter = handler.getDocumentFilter(); - // Need to make the default sort order for authority items - // be on the displayName field - String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM); - if(sortBy==null || sortBy.isEmpty()) { - myFilter.setOrderByClause(qualifiedDisplayNameField); - } - - myFilter.appendWhereClause(authorityItemCommonSchemaName + ":" + - AuthorityItemJAXBSchema.IN_AUTHORITY + "=" + - "'" + parentcsid + "'", - IQueryManager.SEARCH_QUALIFIER_AND); - - // AND vocabularyitems_common:displayName LIKE '%partialTerm%' - // NOTE: Partial terms searches are mutually exclusive to keyword and advanced-search, but - // the PT query param trumps the KW and AS query params. - if (partialTerm != null && !partialTerm.isEmpty()) { - String ptClause = QueryManager.createWhereClauseForPartialMatch( - qualifiedDisplayNameField, partialTerm ); - myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND); - } else if (keywords != null || advancedSearch != null) { + ctx = createServiceContext(getItemServiceName(), queryParams); + // We omit the parentShortId, only needed when doing a create... + DocumentHandler handler = createItemDocumentHandler(ctx, + parentcsid, null); + DocumentFilter myFilter = handler.getDocumentFilter(); + // Need to make the default sort order for authority items + // be on the displayName field + String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM); + if (sortBy == null || sortBy.isEmpty()) { + myFilter.setOrderByClause(qualifiedDisplayNameField); + } + + myFilter.appendWhereClause(authorityItemCommonSchemaName + ":" + + AuthorityItemJAXBSchema.IN_AUTHORITY + "=" + + "'" + parentcsid + "'", + IQueryManager.SEARCH_QUALIFIER_AND); + + // AND vocabularyitems_common:displayName LIKE '%partialTerm%' + // NOTE: Partial terms searches are mutually exclusive to keyword and advanced-search, but + // the PT query param trumps the KW and AS query params. + if (partialTerm != null && !partialTerm.isEmpty()) { + String ptClause = QueryManager.createWhereClauseForPartialMatch( + qualifiedDisplayNameField, partialTerm); + myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND); + } else if (keywords != null || advancedSearch != null) { // String kwdClause = QueryManager.createWhereClauseFromKeywords(keywords); // myFilter.appendWhereClause(kwdClause, IQueryManager.SEARCH_QUALIFIER_AND); - return search(ctx, handler, queryParams, keywords, advancedSearch); - } - if (logger.isDebugEnabled()) { - logger.debug("getAuthorityItemList filtered WHERE clause: " - + myFilter.getWhereClause()); - } - getRepositoryClient(ctx).getFiltered(ctx, handler); - return (AbstractCommonList) handler.getCommonPartList(); - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.LIST_FAILED); - } - } + return search(ctx, handler, queryParams, keywords, advancedSearch); + } + if (logger.isDebugEnabled()) { + logger.debug("getAuthorityItemList filtered WHERE clause: " + + myFilter.getWhereClause()); + } + getRepositoryClient(ctx).getFiltered(ctx, handler); + return (AbstractCommonList) handler.getCommonPartList(); + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.LIST_FAILED); + } + } /** * Gets the entities referencing this Authority item instance. The service type @@ -645,8 +647,8 @@ public abstract class AuthorityResource * for the service bindings. If not set, the type defaults to * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE. * - * @param parentspecifier either a CSID or one of the urn forms - * @param itemspecifier either a CSID or one of the urn forms + * @param parentspecifier either a CSID or one of the urn forms + * @param itemspecifier either a CSID or one of the urn forms * @param ui the ui * * @return the info for the referencing objects @@ -655,55 +657,55 @@ public abstract class AuthorityResource @Path("{csid}/items/{itemcsid}/refObjs") @Produces("application/xml") public AuthorityRefDocList getReferencingObjects( - @PathParam("csid") String parentspecifier, - @PathParam("itemcsid") String itemspecifier, - @Context UriInfo ui) { - AuthorityRefDocList authRefDocList = null; - try { - MultivaluedMap queryParams = ui.getQueryParameters(); + @PathParam("csid") String parentspecifier, + @PathParam("itemcsid") String itemspecifier, + @Context UriInfo ui) { + AuthorityRefDocList authRefDocList = null; + try { + MultivaluedMap queryParams = ui.getQueryParameters(); String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", queryParams); ServiceContext ctx = createServiceContext(getItemServiceName(), queryParams); - String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx); + String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx); // Note that we have to create the service context for the Items, not the main service - // We omit the parentShortId, only needed when doing a create... - DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null); - RepositoryClient repoClient = getRepositoryClient(ctx); - DocumentFilter myFilter = handler.getDocumentFilter(); - String serviceType = ServiceBindingUtils.SERVICE_TYPE_PROCEDURE; - List list = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP); - if (list != null) { - serviceType = list.get(0); - } - DocumentWrapper docWrapper = repoClient.getDoc(ctx, itemcsid); - DocumentModel docModel = docWrapper.getWrappedObject(); - String refName = (String)docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME); - - authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(ctx, - repoClient, - serviceType, - refName, - myFilter.getPageSize(), myFilter.getStartPage(), true /*computeTotal*/ ); - } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.GET_FAILED); - } - if (authRefDocList == null) { - Response response = Response.status(Response.Status.NOT_FOUND).entity( - "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type( - "text/plain").build(); - throw new WebApplicationException(response); - } - return authRefDocList; + // We omit the parentShortId, only needed when doing a create... + DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null); + RepositoryClient repoClient = getRepositoryClient(ctx); + DocumentFilter myFilter = handler.getDocumentFilter(); + String serviceType = ServiceBindingUtils.SERVICE_TYPE_PROCEDURE; + List list = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP); + if (list != null) { + serviceType = list.get(0); + } + DocumentWrapper docWrapper = repoClient.getDoc(ctx, itemcsid); + DocumentModel docModel = docWrapper.getWrappedObject(); + String refName = (String) docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME); + + authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(ctx, + repoClient, + serviceType, + refName, + myFilter.getPageSize(), myFilter.getStartPage(), true /*computeTotal*/); + } catch (Exception e) { + throw bigReThrow(e, ServiceMessages.GET_FAILED); + } + if (authRefDocList == null) { + Response response = Response.status(Response.Status.NOT_FOUND).entity( + "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type( + "text/plain").build(); + throw new WebApplicationException(response); + } + return authRefDocList; } /** * Gets the authority terms used in the indicated Authority item. * - * @param parentspecifier either a CSID or one of the urn forms - * @param itemspecifier either a CSID or one of the urn forms - * @param ui passed to include additional parameters, like pagination controls + * @param parentspecifier either a CSID or one of the urn forms + * @param itemspecifier either a CSID or one of the urn forms + * @param ui passed to include additional parameters, like pagination controls * * @return the authority refs for the Authority item. */ @@ -711,12 +713,12 @@ public abstract class AuthorityResource @Path("{csid}/items/{itemcsid}/authorityrefs") @Produces("application/xml") public AuthorityRefList getAuthorityItemAuthorityRefs( - @PathParam("csid") String parentspecifier, - @PathParam("itemcsid") String itemspecifier, - @Context UriInfo ui) { - AuthorityRefList authRefList = null; + @PathParam("csid") String parentspecifier, + @PathParam("itemcsid") String itemspecifier, + @Context UriInfo ui) { + AuthorityRefList authRefList = null; try { - // Note that we have to create the service context for the Items, not the main service + // Note that we have to create the service context for the Items, not the main service MultivaluedMap queryParams = ui.getQueryParameters(); ServiceContext ctx = null; @@ -725,115 +727,113 @@ public abstract class AuthorityResource ctx = createServiceContext(getItemServiceName(), queryParams); // We omit the parentShortId, only needed when doing a create... RemoteDocumentModelHandlerImpl handler = - (RemoteDocumentModelHandlerImpl) createItemDocumentHandler(ctx, parentcsid, null); + (RemoteDocumentModelHandlerImpl) createItemDocumentHandler(ctx, parentcsid, null); - String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx); + String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx); DocumentWrapper docWrapper = getRepositoryClient(ctx).getDoc(ctx, itemcsid); List authRefFields = - ((MultipartServiceContextImpl)ctx).getCommonPartPropertyValues( - ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES); + ((MultipartServiceContextImpl) ctx).getCommonPartPropertyValues( + ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES); authRefList = handler.getAuthorityRefs(docWrapper, authRefFields); } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: "+parentspecifier + " itemspecifier:" +itemspecifier); - }return authRefList; + throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier); + } + return authRefList; } - /** - * Update authorityItem. - * - * @param parentspecifier either a CSID or one of the urn forms - * @param itemspecifier either a CSID or one of the urn forms - * - * @return the multipart output - */ - @PUT - @Path("{csid}/items/{itemcsid}") - public byte[] updateAuthorityItem( + /** + * Update authorityItem. + * + * @param parentspecifier either a CSID or one of the urn forms + * @param itemspecifier either a CSID or one of the urn forms + * + * @return the multipart output + */ + @PUT + @Path("{csid}/items/{itemcsid}") + public byte[] updateAuthorityItem( @Context UriInfo ui, - @PathParam("csid") String parentspecifier, - @PathParam("itemcsid") String itemspecifier, - String xmlPayload) { - PoxPayloadOut result = null; - try { - PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload); + @PathParam("csid") String parentspecifier, + @PathParam("itemcsid") String itemspecifier, + String xmlPayload) { + PoxPayloadOut result = null; + try { + PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload); // Note that we have to create the service context for the Items, not the main service //Laramie CSPACE-3175. passing null for queryParams, because prior to this refactor, the code moved to lookupParentCSID in this instance called the version of getServiceContext() that passes null String parentcsid = lookupParentCSID(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null); ServiceContext ctx = createServiceContext(getItemServiceName(), theUpdate); - String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx); + String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx); - // We omit the parentShortId, only needed when doing a create... - DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null); + // We omit the parentShortId, only needed when doing a create... + DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null); ctx.setUriInfo(ui); - getRepositoryClient(ctx).update(ctx, itemcsid, handler); - result = ctx.getOutput(); + getRepositoryClient(ctx).update(ctx, itemcsid, handler); + result = ctx.getOutput(); - } catch (Exception e) { + } catch (Exception e) { throw bigReThrow(e, ServiceMessages.UPDATE_FAILED); - } - return result.getBytes(); - } - - /** - * Delete authorityItem. - * - * @param parentcsid the parentcsid - * @param itemcsid the itemcsid - * - * @return the response - */ - @DELETE - @Path("{csid}/items/{itemcsid}") - public Response deleteAuthorityItem( - @PathParam("csid") String parentcsid, - @PathParam("itemcsid") String itemcsid) { - //try{ + } + return result.getBytes(); + } + + /** + * Delete authorityItem. + * + * @param parentcsid the parentcsid + * @param itemcsid the itemcsid + * + * @return the response + */ + @DELETE + @Path("{csid}/items/{itemcsid}") + public Response deleteAuthorityItem( + @PathParam("csid") String parentcsid, + @PathParam("itemcsid") String itemcsid) { + //try{ if (logger.isDebugEnabled()) { logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid); } try { - ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid"); + ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid"); ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid"); - //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null. - // }catch (Throwable t){ - // System.out.println("ERROR in setting up DELETE: "+t); - // } - // try { - // Note that we have to create the service context for the Items, not the main service - ServiceContext ctx = createServiceContext(getItemServiceName()); - getRepositoryClient(ctx).delete(ctx, itemcsid); - return Response.status(HttpResponseCodes.SC_OK).build(); + //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null. + // }catch (Throwable t){ + // System.out.println("ERROR in setting up DELETE: "+t); + // } + // try { + // Note that we have to create the service context for the Items, not the main service + ServiceContext ctx = createServiceContext(getItemServiceName()); + getRepositoryClient(ctx).delete(ctx, itemcsid); + return Response.status(HttpResponseCodes.SC_OK).build(); } catch (Exception e) { - throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid+ " parentcsid:" + parentcsid); - } - } - + throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid + " parentcsid:" + parentcsid); + } + } public final static String hierarchy = "hierarchy"; + @GET - @Path("{csid}/items/{itemcsid}/"+hierarchy) + @Path("{csid}/items/{itemcsid}/" + hierarchy) @Produces("application/xml") public String getHierarchy(@PathParam("csid") String csid, - @PathParam("itemcsid") String itemcsid, - @Context UriInfo ui) throws Exception { + @PathParam("itemcsid") String itemcsid, + @Context UriInfo ui) throws Exception { try { // All items in dive can look at their child uri's to get uri. So we calculate the very first one. We could also do a GET and look at the common part uri field, but why...? String calledUri = ui.getPath(); - String uri = "/"+calledUri.substring(0, (calledUri.length()-("/"+hierarchy).length())); + String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length())); ServiceContext ctx = createServiceContext(getItemServiceName()); ctx.setUriInfo(ui); String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP); - if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)){ + if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) { return Hierarchy.surface(ctx, itemcsid, uri); } else { return Hierarchy.dive(ctx, itemcsid, uri); } - } catch (Exception e){ + } catch (Exception e) { throw bigReThrow(e, "Error showing hierarchy", itemcsid); } } - - - } diff --git a/services/authority/src/main/java/org/collectionspace/services/common/vocabulary/nuxeo/AuthorityDocumentModelHandler.java b/services/authority/src/main/java/org/collectionspace/services/common/vocabulary/nuxeo/AuthorityDocumentModelHandler.java index f4b609d8c..eb2ee39bc 100644 --- a/services/authority/src/main/java/org/collectionspace/services/common/vocabulary/nuxeo/AuthorityDocumentModelHandler.java +++ b/services/authority/src/main/java/org/collectionspace/services/common/vocabulary/nuxeo/AuthorityDocumentModelHandler.java @@ -44,10 +44,10 @@ import org.nuxeo.ecm.core.api.DocumentModel; public abstract class AuthorityDocumentModelHandler extends DocHandlerBase { - private String authorityCommonSchemaName; - + private String authorityCommonSchemaName; + public AuthorityDocumentModelHandler(String authorityCommonSchemaName) { - this.authorityCommonSchemaName = authorityCommonSchemaName; + this.authorityCommonSchemaName = authorityCommonSchemaName; } /* @@ -58,48 +58,71 @@ public abstract class AuthorityDocumentModelHandler @Override protected Map extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta) throws Exception { - Map unQObjectProperties = super.extractPart(docModel, schema, partMeta); - - // Add the CSID to the common part - if (partMeta.getLabel().equalsIgnoreCase(authorityCommonSchemaName)) { - String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString()); - unQObjectProperties.put("csid", csid); - } - - return unQObjectProperties; + Map unQObjectProperties = super.extractPart(docModel, schema, partMeta); + + // Add the CSID to the common part + if (partMeta.getLabel().equalsIgnoreCase(authorityCommonSchemaName)) { + String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString()); + unQObjectProperties.put("csid", csid); + } + + return unQObjectProperties; } - + @Override public void handleCreate(DocumentWrapper wrapDoc) throws Exception { - super.handleCreate(wrapDoc); + super.handleCreate(wrapDoc); + // CSPACE-3178: // Uncomment once debugged and App layer is read to integrate - //updateRefnameForAuthority(wrapDoc, authorityCommonSchemaName);//CSPACE-3178 + // Experimenting with this uncommented now ... + updateRefnameForAuthority(wrapDoc, authorityCommonSchemaName);//CSPACE-3178 } protected void updateRefnameForAuthority(DocumentWrapper wrapDoc, String schemaName) throws Exception { DocumentModel docModel = wrapDoc.getWrappedObject(); - String shortIdentifier = (String)docModel.getProperty(schemaName, AuthorityJAXBSchema.SHORT_IDENTIFIER); - String displayName = (String)docModel.getProperty(schemaName, AuthorityJAXBSchema.DISPLAY_NAME); - MultipartServiceContext ctx = (MultipartServiceContext)getServiceContext(); - RefName.Authority authority = RefName.buildAuthority(ctx.getTenantName(), - ctx.getServiceName(), - shortIdentifier, - displayName); - String refName = authority.toString(); - docModel.setProperty(schemaName , AuthorityJAXBSchema.REF_NAME, refName); + String suppliedRefName = (String) docModel.getProperty(schemaName, AuthorityJAXBSchema.REF_NAME); + // CSPACE-3178: + // Temporarily accept client-supplied refName values, rather than always generating such values, + // Remove the surrounding 'if' statement when clients should no longer supply refName values. + if (suppliedRefName == null || suppliedRefName.isEmpty()) { + String shortIdentifier = (String) docModel.getProperty(schemaName, AuthorityJAXBSchema.SHORT_IDENTIFIER); + String displayName = (String) docModel.getProperty(schemaName, AuthorityJAXBSchema.DISPLAY_NAME); + MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext(); + RefName.Authority authority = RefName.buildAuthority(ctx.getTenantName(), + ctx.getServiceName(), + shortIdentifier, + displayName); + String refName = authority.toString(); + docModel.setProperty(schemaName, AuthorityJAXBSchema.REF_NAME, refName); + } } - public String getShortIdentifier(DocumentWrapper wrapDoc, String schemaName) { DocumentModel docModel = wrapDoc.getWrappedObject(); String shortIdentifier = null; try { - shortIdentifier = (String)docModel.getProperty(schemaName, AuthorityJAXBSchema.SHORT_IDENTIFIER); + shortIdentifier = (String) docModel.getProperty(schemaName, AuthorityJAXBSchema.SHORT_IDENTIFIER); } catch (ClientException ce) { - throw new RuntimeException("AuthorityDocHandler Internal Error: cannot get shortId!", ce); + throw new RuntimeException("AuthorityDocHandler Internal Error: cannot get shortId!", ce); } return shortIdentifier; } -} + /** + * Filters out values supplied in the request + * @param objectProps the properties parsed from the update payload + * @param partMeta metadata for the object to fill + */ + @Override + public void filterReadOnlyPropertiesForPart( + Map objectProps, ObjectPartType partMeta) { + super.filterReadOnlyPropertiesForPart(objectProps, partMeta); + String commonPartLabel = getServiceContext().getCommonPartLabel(); + if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) { + objectProps.remove(AuthorityJAXBSchema.CSID); + // Enable when clients should no longer supply refName values + // objectProps.remove(AuthorityItemJAXBSchema.REF_NAME); // CSPACE-3178 + } + } +} diff --git a/services/authority/src/main/java/org/collectionspace/services/common/vocabulary/nuxeo/AuthorityItemDocumentModelHandler.java b/services/authority/src/main/java/org/collectionspace/services/common/vocabulary/nuxeo/AuthorityItemDocumentModelHandler.java index eed07a053..865d7c62e 100644 --- a/services/authority/src/main/java/org/collectionspace/services/common/vocabulary/nuxeo/AuthorityItemDocumentModelHandler.java +++ b/services/authority/src/main/java/org/collectionspace/services/common/vocabulary/nuxeo/AuthorityItemDocumentModelHandler.java @@ -40,9 +40,10 @@ import org.collectionspace.services.common.relation.IRelationsManager; import org.collectionspace.services.common.repository.RepositoryClient; import org.collectionspace.services.common.repository.RepositoryClientFactory; import org.collectionspace.services.common.service.ObjectPartType; +import org.collectionspace.services.common.vocabulary.AuthorityJAXBSchema; import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema; +import org.collectionspace.services.common.vocabulary.AuthorityResource; import org.collectionspace.services.nuxeo.client.java.DocHandlerBase; -import org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl; import org.collectionspace.services.nuxeo.util.NuxeoUtils; import org.collectionspace.services.relation.RelationResource; import org.collectionspace.services.relation.RelationsCommon; @@ -50,6 +51,7 @@ import org.collectionspace.services.relation.RelationsCommonList; import org.collectionspace.services.relation.RelationsDocListItem; import org.collectionspace.services.relation.RelationshipType; import org.nuxeo.ecm.core.api.DocumentModel; +import org.nuxeo.ecm.core.api.model.PropertyNotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -62,7 +64,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; //import org.collectionspace.services.common.authority.AuthorityItemRelations; - /** * AuthorityItemDocumentModelHandler * @@ -73,29 +74,27 @@ public abstract class AuthorityItemDocumentModelHandler extends DocHandlerBase { private final Logger logger = LoggerFactory.getLogger(AuthorityItemDocumentModelHandler.class); - - private String authorityItemCommonSchemaName; - + private String authorityItemCommonSchemaName; /** * inVocabulary is the parent Authority for this context */ protected String inAuthority; protected String authorityRefNameBase; - + public AuthorityItemDocumentModelHandler(String authorityItemCommonSchemaName) { - this.authorityItemCommonSchemaName = authorityItemCommonSchemaName; + this.authorityItemCommonSchemaName = authorityItemCommonSchemaName; } public String getInAuthority() { - return inAuthority; - } + return inAuthority; + } - public void setInAuthority(String inAuthority) { - this.inAuthority = inAuthority; - } + public void setInAuthority(String inAuthority) { + this.inAuthority = inAuthority; + } /** Subclasses may override this to customize the URI segment. */ - public String getAuthorityServicePath(){ + public String getAuthorityServicePath() { return getServiceContext().getServiceName().toLowerCase(); // Laramie20110510 CSPACE-3932 } @@ -103,14 +102,14 @@ public abstract class AuthorityItemDocumentModelHandler public String getUri(DocumentModel docModel) { // Laramie20110510 CSPACE-3932 String authorityServicePath = getAuthorityServicePath(); - return "/"+authorityServicePath+'/'+inAuthority+'/'+ AuthorityClient.ITEMS+'/'+getCsid(docModel); + return "/" + authorityServicePath + '/' + inAuthority + '/' + AuthorityClient.ITEMS + '/' + getCsid(docModel); } - public String getAuthorityRefNameBase(){ + public String getAuthorityRefNameBase() { return this.authorityRefNameBase; } - public void setAuthorityRefNameBase(String value){ + public void setAuthorityRefNameBase(String value) { this.authorityRefNameBase = value; } @@ -119,35 +118,73 @@ public abstract class AuthorityItemDocumentModelHandler */ @Override public void handleCreate(DocumentWrapper wrapDoc) throws Exception { - // first fill all the parts of the document - super.handleCreate(wrapDoc); - handleInAuthority(wrapDoc.getWrappedObject()); + // first fill all the parts of the document + super.handleCreate(wrapDoc); + handleInAuthority(wrapDoc.getWrappedObject()); + // CSPACE-3178: // Uncomment once debugged and App layer is read to integrate - //handleDisplayNameAsShortIdentifier(wrapDoc.getWrappedObject(), authorityItemCommonSchemaName); - //updateRefnameForAuthorityItem(wrapDoc, authorityItemCommonSchemaName, getAuthorityRefNameBase()); //CSPACE-3178 + // Experimenting with these uncommented now ... + handleDisplayNameAsShortIdentifier(wrapDoc.getWrappedObject(), authorityItemCommonSchemaName); + updateRefnameForAuthorityItem(wrapDoc, authorityItemCommonSchemaName, getAuthorityRefNameBase()); } - + private void handleDisplayNameAsShortIdentifier(DocumentModel docModel, String schemaName) throws Exception { - String shortIdentifier = (String)docModel.getProperty(schemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER); - String displayName = (String)docModel.getProperty(schemaName, AuthorityItemJAXBSchema.DISPLAY_NAME); - if (Tools.isEmpty(shortIdentifier) && Tools.notEmpty(displayName)){ - String cookedShortIdentifier = Tools.squeeze(displayName)+'-'+Tools.now().toString(); - docModel.setProperty(schemaName , AuthorityItemJAXBSchema.SHORT_IDENTIFIER, cookedShortIdentifier); + String shortIdentifier = (String) docModel.getProperty(schemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER); + String displayName = (String) docModel.getProperty(schemaName, AuthorityItemJAXBSchema.DISPLAY_NAME); + String shortDisplayName = ""; + try { + shortDisplayName = (String) docModel.getProperty(schemaName, AuthorityItemJAXBSchema.SHORT_DISPLAY_NAME); + } catch (PropertyNotFoundException pnfe) { + // Do nothing on exception. Some vocabulary schemas may not include a short display name. + } + if (Tools.isEmpty(shortIdentifier)) { + String generatedShortIdentifier = generateShortIdentifierFromDisplayName(displayName, shortDisplayName); + docModel.setProperty(schemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER, generatedShortIdentifier); } } + // CSPACE-2215 + // FIXME: Consider replacing this with a different algorithm, perhaps one + // that combines stems of each word token in the displayname. + // FIXME: Verify uniqueness before returning the generated short identifier. + // FIXME: Consider using a hash of the display name, rather than a timestamp, + // when it is necessary to add a suffix for uniqueness. + private String generateShortIdentifierFromDisplayName(String displayName, String shortDisplayName) { + String generatedShortIdentifier = ""; + if (Tools.notEmpty(displayName)) { + generatedShortIdentifier = displayName + '-' + Tools.now().toString(); + } else if (Tools.notEmpty(shortDisplayName)) { + generatedShortIdentifier = shortDisplayName + '-' + Tools.now().toString(); + } + // Ensure that the short identifier consists only of word chars. + if (Tools.notEmpty(generatedShortIdentifier)) { + generatedShortIdentifier = generatedShortIdentifier.replaceAll("[^\\w]", ""); + } + // Fallback if we can't generate a short identifier from the displayname(s). + if (generatedShortIdentifier.isEmpty()) { + generatedShortIdentifier = java.util.UUID.randomUUID().toString(); + } + return generatedShortIdentifier; + } + protected void updateRefnameForAuthorityItem(DocumentWrapper wrapDoc, String schemaName, String authorityRefBaseName) throws Exception { - DocumentModel docModel = wrapDoc.getWrappedObject(); - String shortIdentifier = (String)docModel.getProperty(schemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER); - String displayName = (String)docModel.getProperty(schemaName, AuthorityItemJAXBSchema.DISPLAY_NAME); - if (Tools.isEmpty(authorityRefBaseName)){ - throw new Exception("updateRefnameForAuthorityItem requires an authorityRefBaseName, but none was supplied."); - } - RefName.Authority authority = RefName.Authority.parse(authorityRefBaseName); - String refName = RefName.buildAuthorityItem(authority, shortIdentifier, displayName).toString(); - docModel.setProperty(schemaName , AuthorityItemJAXBSchema.REF_NAME, refName); + DocumentModel docModel = wrapDoc.getWrappedObject(); + String suppliedRefName = (String) docModel.getProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME); + // CSPACE-3178: + // Temporarily accept client-supplied refName values, rather than always generating such values. + // Remove the surrounding 'if' statement when clients should no longer supply refName values. + if (suppliedRefName == null || suppliedRefName.isEmpty()) { + String shortIdentifier = (String) docModel.getProperty(schemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER); + String displayName = (String) docModel.getProperty(schemaName, AuthorityItemJAXBSchema.DISPLAY_NAME); + if (Tools.isEmpty(authorityRefBaseName)) { + throw new Exception("Could not create the refName for this authority term, because the refName for its authority parent was empty."); + } + RefName.Authority authority = RefName.Authority.parse(authorityRefBaseName); + String refName = RefName.buildAuthorityItem(authority, shortIdentifier, displayName).toString(); + docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refName); + } } /** @@ -159,8 +196,8 @@ public abstract class AuthorityItemDocumentModelHandler * @throws Exception the exception */ private void handleInAuthority(DocumentModel docModel) throws Exception { - docModel.setProperty(authorityItemCommonSchemaName, - AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority); + docModel.setProperty(authorityItemCommonSchemaName, + AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority); } @@ -170,32 +207,36 @@ public abstract class AuthorityItemDocumentModelHandler @Override protected Map extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta) throws Exception { - Map unQObjectProperties = super.extractPart(docModel, schema, partMeta); - - // Add the CSID to the common part - if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) { - String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString()); - unQObjectProperties.put("csid", csid); - } - - return unQObjectProperties; + Map unQObjectProperties = super.extractPart(docModel, schema, partMeta); + + // Add the CSID to the common part + if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) { + String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString()); + unQObjectProperties.put("csid", csid); + } + + return unQObjectProperties; } - + /** - * Filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure that + * Filters out values supplied in the request; e.g.: + * AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure that * the parent link remains untouched. * @param objectProps the properties parsed from the update payload * @param partMeta metadata for the object to fill */ @Override public void filterReadOnlyPropertiesForPart( - Map objectProps, ObjectPartType partMeta) { - super.filterReadOnlyPropertiesForPart(objectProps, partMeta); - String commonPartLabel = getServiceContext().getCommonPartLabel(); - if(partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) { - objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY); - objectProps.remove(AuthorityItemJAXBSchema.CSID); - } + Map objectProps, ObjectPartType partMeta) { + super.filterReadOnlyPropertiesForPart(objectProps, partMeta); + String commonPartLabel = getServiceContext().getCommonPartLabel(); + if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) { + objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY); + objectProps.remove(AuthorityItemJAXBSchema.CSID); + // Enable when clients should no longer supply refName values + // objectProps.remove(AuthorityItemJAXBSchema.REF_NAME); // CSPACE-3178 + + } } @Override @@ -231,7 +272,7 @@ public abstract class AuthorityItemDocumentModelHandler RelationsCommonList parentListOuter = getRelations(thisCSID, null, predicate); List parentList = parentListOuter.getRelationListItem(); if (parentList != null) { - if (parentList.size()==0){ + if (parentList.size() == 0) { return null; } RelationsCommonList.RelationListItem relationListItem = parentList.get(0); @@ -239,57 +280,57 @@ public abstract class AuthorityItemDocumentModelHandler } return parentCSID; } catch (Exception e) { - logger.error("Could not find parent for this: "+thisCSID, e); + logger.error("Could not find parent for this: " + thisCSID, e); return null; } } public void showRelations(DocumentWrapper wrapDoc, - MultipartServiceContext ctx) throws Exception { + MultipartServiceContext ctx) throws Exception { String thisCSID = NuxeoUtils.getCsid(wrapDoc.getWrappedObject()); - String predicate = RelationshipType.HAS_BROADER.value(); - RelationsCommonList parentListOuter = getRelations(thisCSID, null, predicate); - List parentList = parentListOuter.getRelationListItem(); + String predicate = RelationshipType.HAS_BROADER.value(); + RelationsCommonList parentListOuter = getRelations(thisCSID, null, predicate); + List parentList = parentListOuter.getRelationListItem(); - RelationsCommonList childrenListOuter = getRelations(null, thisCSID, predicate); - List childrenList = childrenListOuter.getRelationListItem(); + RelationsCommonList childrenListOuter = getRelations(null, thisCSID, predicate); + List childrenList = childrenListOuter.getRelationListItem(); - //Assume that there are more children than parents. Will be true for parent/child, but maybe not for other relations. - //Now add all parents to our childrenList, to be able to return just one list of consolidated results. - //Not optimal, but that's the current design spec. + //Assume that there are more children than parents. Will be true for parent/child, but maybe not for other relations. + //Now add all parents to our childrenList, to be able to return just one list of consolidated results. + //Not optimal, but that's the current design spec. long added = 0; for (RelationsCommonList.RelationListItem parent : parentList) { - childrenList.add(parent); - added++; + childrenList.add(parent); + added++; } long childrenSize = childrenList.size(); childrenListOuter.setTotalItems(childrenSize); - childrenListOuter.setItemsInPage(childrenListOuter.getItemsInPage()+added); + childrenListOuter.setItemsInPage(childrenListOuter.getItemsInPage() + added); PayloadOutputPart relationsPart = new PayloadOutputPart(RelationClient.SERVICE_COMMON_LIST_NAME, childrenListOuter); ctx.addOutputPart(relationsPart); } public void showSiblings(DocumentWrapper wrapDoc, - MultipartServiceContext ctx) throws Exception { + MultipartServiceContext ctx) throws Exception { String thisCSID = NuxeoUtils.getCsid(wrapDoc.getWrappedObject()); - String parentCSID = getParentCSID(thisCSID); - if (parentCSID == null){ - logger.warn("~~~~~\r\n~~~~ Could not find parent for this: "+thisCSID); + String parentCSID = getParentCSID(thisCSID); + if (parentCSID == null) { + logger.warn("~~~~~\r\n~~~~ Could not find parent for this: " + thisCSID); return; } - String predicate = RelationshipType.HAS_BROADER.value(); - RelationsCommonList siblingListOuter = getRelations(null, parentCSID, predicate); - List siblingList = siblingListOuter.getRelationListItem(); + String predicate = RelationshipType.HAS_BROADER.value(); + RelationsCommonList siblingListOuter = getRelations(null, parentCSID, predicate); + List siblingList = siblingListOuter.getRelationListItem(); List toRemoveList = newList(); RelationsCommonList.RelationListItem item = null; for (RelationsCommonList.RelationListItem sibling : siblingList) { - if (thisCSID.equals(sibling.getSubjectCsid())){ + if (thisCSID.equals(sibling.getSubjectCsid())) { toRemoveList.add(sibling); //IS_A copy of the main item, i.e. I have a parent that is my parent, so I'm in the list from the above query. } } @@ -302,11 +343,11 @@ public abstract class AuthorityItemDocumentModelHandler siblingListOuter.setTotalItems(siblingSize); siblingListOuter.setItemsInPage(siblingSize); - PayloadOutputPart relationsPart = new PayloadOutputPart(RelationClient.SERVICE_COMMON_LIST_NAME,siblingListOuter); + PayloadOutputPart relationsPart = new PayloadOutputPart(RelationClient.SERVICE_COMMON_LIST_NAME, siblingListOuter); ctx.addOutputPart(relationsPart); } - public void showAllRelations(DocumentWrapper wrapDoc, MultipartServiceContext ctx) throws Exception { + public void showAllRelations(DocumentWrapper wrapDoc, MultipartServiceContext ctx) throws Exception { String thisCSID = NuxeoUtils.getCsid(wrapDoc.getWrappedObject()); RelationsCommonList subjectListOuter = getRelations(thisCSID, null, null); // nulls are wildcards: predicate=*, and object=* @@ -323,14 +364,14 @@ public abstract class AuthorityItemDocumentModelHandler subjectListOuter.setTotalItems(relatedSize); subjectListOuter.setItemsInPage(relatedSize); - PayloadOutputPart relationsPart = new PayloadOutputPart(RelationClient.SERVICE_COMMON_LIST_NAME,subjectListOuter); + PayloadOutputPart relationsPart = new PayloadOutputPart(RelationClient.SERVICE_COMMON_LIST_NAME, subjectListOuter); ctx.addOutputPart(relationsPart); } public void fillAllParts(DocumentWrapper wrapDoc, Action action) throws Exception { super.fillAllParts(wrapDoc, action); ServiceContext ctx = getServiceContext(); - PoxPayloadIn input = (PoxPayloadIn)ctx.getInput(); + PoxPayloadIn input = (PoxPayloadIn) ctx.getInput(); DocumentModel documentModel = (wrapDoc.getWrappedObject()); String itemCsid = documentModel.getName(); @@ -345,28 +386,28 @@ public abstract class AuthorityItemDocumentModelHandler super.completeUpdate(wrapDoc); //now we add part for relations list ServiceContext ctx = getServiceContext(); - PayloadOutputPart foo = (PayloadOutputPart)ctx.getProperty(RelationClient.SERVICE_COMMON_LIST_NAME); - ((PoxPayloadOut)ctx.getOutput()).addPart(foo); - } - - /** updateRelations strategy: - - go through inboundList, remove anything from childList that matches from childList - go through inboundList, remove anything from parentList that matches from parentList - go through parentList, delete all remaining - go through childList, delete all remaining - go through actionList, add all remaining. - check for duplicate children - check for more than one parent. - - inboundList parentList childList actionList - ---------------- --------------- ---------------- ---------------- - child-a parent-c child-a child-b - child-b parent-d child-c - parent-a - */ + PayloadOutputPart foo = (PayloadOutputPart) ctx.getProperty(RelationClient.SERVICE_COMMON_LIST_NAME); + ((PoxPayloadOut) ctx.getOutput()).addPart(foo); + } + + /** updateRelations strategy: + + go through inboundList, remove anything from childList that matches from childList + go through inboundList, remove anything from parentList that matches from parentList + go through parentList, delete all remaining + go through childList, delete all remaining + go through actionList, add all remaining. + check for duplicate children + check for more than one parent. + + inboundList parentList childList actionList + ---------------- --------------- ---------------- ---------------- + child-a parent-c child-a child-b + child-b parent-d child-c + parent-a + */ public RelationsCommonList updateRelations(String itemCSID, PoxPayloadIn input, DocumentWrapper wrapDoc) - throws Exception { + throws Exception { PayloadInputPart part = input.getPart(RelationClient.SERVICE_COMMON_LIST_NAME); //input.getPart("relations_common"); if (part == null) { return null; //nothing to do--they didn't send a list of relations. @@ -399,8 +440,8 @@ public abstract class AuthorityItemDocumentModelHandler List childList = childListOuter.getRelationListItem(); List parentList = parentListOuter.getRelationListItem(); - if (parentList.size()>1){ - throw new Exception("Too many parents for object: "+itemCSID+" list: "+dumpList(parentList, "parentList")); + if (parentList.size() > 1) { + throw new Exception("Too many parents for object: " + itemCSID + " list: " + dumpList(parentList, "parentList")); } DocumentModel docModel = wrapDoc.getWrappedObject(); @@ -412,29 +453,29 @@ public abstract class AuthorityItemDocumentModelHandler if (inboundItem.getObject().getCsid().equals(itemCSID) && inboundItem.getPredicate().equals(HAS_BROADER)) { //then this is an item that says we have a child. That child is inboundItem RelationsCommonList.RelationListItem childItem = findInList(childList, inboundItem); - if (childItem != null){ - removeFromList(childList, childItem); //exists, just take it off delete list + if (childItem != null) { + removeFromList(childList, childItem); //exists, just take it off delete list } else { actionList.add(inboundItem); //doesn't exist as a child, but is a child. Add to additions list } ensureChildHasNoOtherParents(ctx, queryParams, inboundItem.getSubject().getCsid()); - } else if (inboundItem.getSubject().getCsid().equals(itemCSID) && inboundItem.getPredicate().equals(HAS_BROADER)) { + } else if (inboundItem.getSubject().getCsid().equals(itemCSID) && inboundItem.getPredicate().equals(HAS_BROADER)) { //then this is an item that says we have a parent. inboundItem is that parent. RelationsCommonList.RelationListItem parentItem = findInList(parentList, inboundItem); - if (parentItem != null){ - removeFromList(parentList, parentItem); //exists, just take it off delete list + if (parentItem != null) { + removeFromList(parentList, parentItem); //exists, just take it off delete list } else { actionList.add(inboundItem); //doesn't exist as a parent, but is a parent. Add to additions list } - } else { - logger.warn("Element didn't match parent or child, but may have partial fields that match. inboundItem: "+inboundItem); + } else { + logger.warn("Element didn't match parent or child, but may have partial fields that match. inboundItem: " + inboundItem); //not dealing with: hasNarrower or any other predicate. } } String dump = dumpLists(itemCSID, parentList, childList, actionList); //System.out.println("====dump====="+CR+dump); - logger.info("~~~~~~~~~~~~~~~~~~~~~~dump~~~~~~~~~~~~~~~~~~~~~~~~"+CR+ dump); + logger.info("~~~~~~~~~~~~~~~~~~~~~~dump~~~~~~~~~~~~~~~~~~~~~~~~" + CR + dump); deleteRelations(parentList, ctx, "parentList"); //todo: there are items appearing on both lists....april 20. deleteRelations(childList, ctx, "childList"); createRelations(actionList, ctx); @@ -443,47 +484,47 @@ public abstract class AuthorityItemDocumentModelHandler return relationsCommonListBody; } - private void ensureChildHasNoOtherParents(ServiceContext ctx, MultivaluedMap queryParams, String childCSID){ + private void ensureChildHasNoOtherParents(ServiceContext ctx, MultivaluedMap queryParams, String childCSID) { queryParams.putSingle(IRelationsManager.SUBJECT_QP, childCSID); queryParams.putSingle(IRelationsManager.PREDICATE_QP, RelationshipType.HAS_BROADER.value()); queryParams.putSingle(IRelationsManager.OBJECT_QP, null); //null means ANY RelationsCommonList parentListOuter = (new RelationResource()).getList(ctx.getUriInfo()); List parentList = parentListOuter.getRelationListItem(); //logger.warn("ensureChildHasNoOtherParents preparing to delete relations on "+childCSID+"\'s parent list: \r\n"+dumpList(parentList, "duplicate parent list")); - deleteRelations(parentList, ctx, "parentList-delete"); + deleteRelations(parentList, ctx, "parentList-delete"); } private String dumpLists(String itemCSID, - List parentList, - List childList, - List actionList){ + List parentList, + List childList, + List actionList) { StringBuffer sb = new StringBuffer(); - sb.append("itemCSID: "+itemCSID+CR); + sb.append("itemCSID: " + itemCSID + CR); sb.append(dumpList(parentList, "parentList")); sb.append(dumpList(childList, "childList")); sb.append(dumpList(actionList, "actionList")); return sb.toString(); } - - private final static String CR="\r\n"; + private final static String CR = "\r\n"; private final static String T = " "; - private String dumpList(List list, String label){ + private String dumpList(List list, String label) { StringBuffer sb = new StringBuffer(); String s; - if (list.size()>0) sb.append("=========== "+label+" =========="+CR); + if (list.size() > 0) { + sb.append("=========== " + label + " ==========" + CR); + } for (RelationsCommonList.RelationListItem item : list) { s = - T + item.getSubject().getCsid() //+T4 + item.getSubject().getUri() - + T + item.getPredicate() - + T + item.getObject().getCsid() //+T4 + item.getObject().getUri() - + CR - //+"subject:{"+item.getSubject()+"}\r\n object:{"+item.getObject()+"}" - //+ CR + "relation-record: {"+item+"}" - ; + T + item.getSubject().getCsid() //+T4 + item.getSubject().getUri() + + T + item.getPredicate() + + T + item.getObject().getCsid() //+T4 + item.getObject().getUri() + + CR //+"subject:{"+item.getSubject()+"}\r\n object:{"+item.getObject()+"}" + //+ CR + "relation-record: {"+item+"}" + ; sb.append(s); - } + } return sb.toString(); } @@ -492,9 +533,9 @@ public abstract class AuthorityItemDocumentModelHandler * Operates directly on the items in the list. Does not change the list ordering, does not add or remove any items. */ protected void fixupInboundListItems(ServiceContext ctx, - List inboundList, - DocumentModel docModel, - String itemCSID) throws Exception { + List inboundList, + DocumentModel docModel, + String itemCSID) throws Exception { String thisURI = this.getUri(docModel); // WARNING: the two code blocks below are almost identical and seem to ask to be put in a generic method. // beware of the little diffs in inboundItem.setObjectCsid(itemCSID); and inboundItem.setSubjectCsid(itemCSID); in the two blocks. @@ -502,26 +543,26 @@ public abstract class AuthorityItemDocumentModelHandler RelationsDocListItem inboundItemObject = inboundItem.getObject(); RelationsDocListItem inboundItemSubject = inboundItem.getSubject(); - if (inboundItemObject.getCsid().equalsIgnoreCase(CommonAPI.AuthorityItemCSID_REPLACE)){ + if (inboundItemObject.getCsid().equalsIgnoreCase(CommonAPI.AuthorityItemCSID_REPLACE)) { inboundItem.setObjectCsid(itemCSID); inboundItemObject.setCsid(itemCSID); inboundItemObject.setUri(getUri(docModel)); } else { String objectCsid = inboundItemObject.getCsid(); - DocumentModel itemDocModel = NuxeoUtils.getDocFromCsid(getRepositorySession(), ctx, objectCsid); //null if not found. + DocumentModel itemDocModel = NuxeoUtils.getDocFromCsid(getRepositorySession(), ctx, objectCsid); //null if not found. DocumentWrapper wrapper = new DocumentWrapperImpl(itemDocModel); String uri = this.getRepositoryClient(ctx).getDocURI(wrapper); inboundItemObject.setUri(uri); //CSPACE-4037 } uriPointsToSameAuthority(thisURI, inboundItemObject.getUri()); //CSPACE-4042 - if (inboundItemSubject.getCsid().equalsIgnoreCase(CommonAPI.AuthorityItemCSID_REPLACE)){ + if (inboundItemSubject.getCsid().equalsIgnoreCase(CommonAPI.AuthorityItemCSID_REPLACE)) { inboundItem.setSubjectCsid(itemCSID); inboundItemSubject.setCsid(itemCSID); inboundItemSubject.setUri(getUri(docModel)); } else { - String subjectCsid =inboundItemSubject.getCsid(); - DocumentModel itemDocModel = NuxeoUtils.getDocFromCsid(getRepositorySession(), ctx, subjectCsid); //null if not found. + String subjectCsid = inboundItemSubject.getCsid(); + DocumentModel itemDocModel = NuxeoUtils.getDocFromCsid(getRepositorySession(), ctx, subjectCsid); //null if not found. DocumentWrapper wrapper = new DocumentWrapperImpl(itemDocModel); String uri = this.getRepositoryClient(ctx).getDocURI(wrapper); inboundItemSubject.setUri(uri); //CSPACE-4037 @@ -537,31 +578,31 @@ public abstract class AuthorityItemDocumentModelHandler } // this method calls the RelationResource to have it create the relations and persist them. - private void createRelations(List inboundList, ServiceContext ctx){ - for (RelationsCommonList.RelationListItem item : inboundList) { - RelationsCommon rc = new RelationsCommon(); - //rc.setCsid(item.getCsid()); - //todo: assignTo(item, rc); - RelationsDocListItem itemSubject = item.getSubject(); - RelationsDocListItem itemObject = item.getObject(); + private void createRelations(List inboundList, ServiceContext ctx) { + for (RelationsCommonList.RelationListItem item : inboundList) { + RelationsCommon rc = new RelationsCommon(); + //rc.setCsid(item.getCsid()); + //todo: assignTo(item, rc); + RelationsDocListItem itemSubject = item.getSubject(); + RelationsDocListItem itemObject = item.getObject(); - String subjectCsid = itemSubject.getCsid(); - rc.setDocumentId1(subjectCsid); - rc.setSubjectCsid(subjectCsid); + String subjectCsid = itemSubject.getCsid(); + rc.setDocumentId1(subjectCsid); + rc.setSubjectCsid(subjectCsid); - String objCsid = item.getObject().getCsid(); - rc.setDocumentId2(objCsid); - rc.setObjectCsid(objCsid); + String objCsid = item.getObject().getCsid(); + rc.setDocumentId2(objCsid); + rc.setObjectCsid(objCsid); - rc.setRelationshipType(item.getPredicate()); - //RelationshipType foo = (RelationshipType.valueOf(item.getPredicate())) ; - //rc.setPredicate(foo); //this must be one of the type found in the enum in services/jaxb/src/main/resources/relations_common.xsd + rc.setRelationshipType(item.getPredicate()); + //RelationshipType foo = (RelationshipType.valueOf(item.getPredicate())) ; + //rc.setPredicate(foo); //this must be one of the type found in the enum in services/jaxb/src/main/resources/relations_common.xsd - rc.setDocumentType1(itemSubject.getDocumentType()); - rc.setDocumentType2(itemObject.getDocumentType()); + rc.setDocumentType1(itemSubject.getDocumentType()); + rc.setDocumentType2(itemObject.getDocumentType()); - rc.setSubjectUri(itemSubject.getUri()); - rc.setObjectUri(itemObject.getUri()); + rc.setSubjectUri(itemSubject.getUri()); + rc.setObjectUri(itemObject.getUri()); PoxPayloadOut payloadOut = new PoxPayloadOut(RelationClient.SERVICE_PAYLOAD_NAME); @@ -572,42 +613,45 @@ public abstract class AuthorityItemDocumentModelHandler Object res = relationResource.create(ctx.getUriInfo(), payloadOut.toXML()); //NOTE ui recycled from above to pass in unknown query params. } } - private void deleteRelations(List list,ServiceContext ctx, String listName){ - try { - //if (list.size()>0){ logger.info("==== deleteRelations from : "+listName); } - for (RelationsCommonList.RelationListItem item : list) { - RelationResource relationResource = new RelationResource(); - //logger.info("==== TO DELETE: " + item.getCsid() + ": " + item.getSubject().getCsid() + "--" + item.getPredicate() + "-->" + item.getObject().getCsid()); - Object res = relationResource.delete(item.getCsid()); - } - } catch (Throwable t){ - String msg = "Unable to deleteRelations: "+ Tools.errorToString(t, true); - logger.error(msg); - } - } - - private List newList(){ + + private void deleteRelations(List list, ServiceContext ctx, String listName) { + try { + //if (list.size()>0){ logger.info("==== deleteRelations from : "+listName); } + for (RelationsCommonList.RelationListItem item : list) { + RelationResource relationResource = new RelationResource(); + //logger.info("==== TO DELETE: " + item.getCsid() + ": " + item.getSubject().getCsid() + "--" + item.getPredicate() + "-->" + item.getObject().getCsid()); + Object res = relationResource.delete(item.getCsid()); + } + } catch (Throwable t) { + String msg = "Unable to deleteRelations: " + Tools.errorToString(t, true); + logger.error(msg); + } + } + + private List newList() { List result = new ArrayList(); return result; } - protected List cloneList(List inboundList){ + + protected List cloneList(List inboundList) { List result = newList(); - for (RelationsCommonList.RelationListItem item: inboundList){ + for (RelationsCommonList.RelationListItem item : inboundList) { result.add(item); } return result; } - private RelationsCommonList.RelationListItem findInList(List list, RelationsCommonList.RelationListItem item){ - for (RelationsCommonList.RelationListItem listItem : list) { - if (itemsEqual(listItem, item)){ //equals must be defined, else + + private RelationsCommonList.RelationListItem findInList(List list, RelationsCommonList.RelationListItem item) { + for (RelationsCommonList.RelationListItem listItem : list) { + if (itemsEqual(listItem, item)) { //equals must be defined, else return listItem; - } - } - return null; - } + } + } + return null; + } - private boolean itemsEqual(RelationsCommonList.RelationListItem item, RelationsCommonList.RelationListItem item2){ - if (item==null || item2==null){ + private boolean itemsEqual(RelationsCommonList.RelationListItem item, RelationsCommonList.RelationListItem item2) { + if (item == null || item2 == null) { return false; } RelationsDocListItem subj1 = item.getSubject(); @@ -615,28 +659,28 @@ public abstract class AuthorityItemDocumentModelHandler RelationsDocListItem obj1 = item.getObject(); RelationsDocListItem obj2 = item2.getObject(); - return (subj1.getCsid().equals(subj2.getCsid())) + return (subj1.getCsid().equals(subj2.getCsid())) && (obj1.getCsid().equals(obj1.getCsid())) - && ( (item.getPredicate().equals(item2.getPredicate())) - && (item.getRelationshipType().equals(item2.getRelationshipType())) ) + && ((item.getPredicate().equals(item2.getPredicate())) + && (item.getRelationshipType().equals(item2.getRelationshipType()))) && (obj1.getDocumentType().equals(obj2.getDocumentType())) - && (subj1.getDocumentType().equals(subj2.getDocumentType())) ; + && (subj1.getDocumentType().equals(subj2.getDocumentType())); } - private void removeFromList(List list, RelationsCommonList.RelationListItem item){ + private void removeFromList(List list, RelationsCommonList.RelationListItem item) { list.remove(item); } /* don't even THINK of re-using this method. * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05"; */ - private String extractInAuthorityCSID(String uri){ - String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)"; + private String extractInAuthorityCSID(String uri) { + String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)"; Pattern p = Pattern.compile(IN_AUTHORITY_REGEX); Matcher m = p.matcher(uri); - if (m.find()){ - if (m.groupCount()<3){ - logger.warn("REGEX-WRONG-GROUPCOUNT looking in "+uri); + if (m.find()) { + if (m.groupCount() < 3) { + logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri); return ""; } else { //String service = m.group(1); @@ -646,7 +690,7 @@ public abstract class AuthorityItemDocumentModelHandler //print("service:"+service+", inauth:"+inauth+", rest:"+rest); } } else { - logger.warn("REGEX-NOT-MATCHED looking in "+uri); + logger.warn("REGEX-NOT-MATCHED looking in " + uri); return ""; } } @@ -655,12 +699,11 @@ public abstract class AuthorityItemDocumentModelHandler protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception { String authorityCSID = extractInAuthorityCSID(thisURI); String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI); - if ( Tools.isBlank(authorityCSID) + if (Tools.isBlank(authorityCSID) || Tools.isBlank(authorityCSIDForInbound) - || ( ! authorityCSID.equalsIgnoreCase(authorityCSIDForInbound) ) - ) { - throw new Exception("Item URI "+thisURI+" must point to same authority as related item: "+inboundItemURI); - } + || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) { + throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI); + } } //================= TODO: move this to common, refactoring this and CollectionObjectResource.java @@ -676,6 +719,4 @@ public abstract class AuthorityItemDocumentModelHandler return relationsCommonList; } //============================= END TODO refactor ========================== - } - 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 e0a15f6e3..0b711d74d 100755 --- 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 @@ -49,13 +49,13 @@ public class RefName { public static final String REFNAME = "refName"; - public static final String AUTHORITY_REGEX = "urn:cspace:(.*):(.*)\\((.*)\\)\\'?([^\\']*)\\'?"; - public static final String AUTHORITY_ITEM_REGEX = "urn:cspace:(.*):(.*)\\((.*)\\):items\\((.*)\\)\\'?([^\\']*)\\'?"; + public static final String AUTHORITY_REGEX = "urn:cspace:(.*):(.*):name\\((.*)\\)\\'?([^\\']*)\\'?"; + public static final String AUTHORITY_ITEM_REGEX = "urn:cspace:(.*):(.*):name\\((.*)\\):item:name\\((.*)\\)\\'?([^\\']*)\\'?"; - public static final String AUTHORITY_EXAMPLE = "urn:cspace:collectionspace.org:Loansin(shortID)'displayName'"; - public static final String AUTHORITY_EXAMPLE2 = "urn:cspace:collectionspace.org:Loansin(shortID)"; + 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(shortID):items(itemShortID)'itemDisplayName'"; + public static final String AUTHORITY_ITEM_EXAMPLE ="urn:cspace:collectionspace.org:Loansin:name(shortID):item:name(itemShortID)'itemDisplayName'"; public static final String EX_tenantName = "collectionspace.org"; public static final String EX_resource = "Loansin"; @@ -80,6 +80,9 @@ public class RefName { } info.tenantName = m.group(1); info.resource = m.group(2); + if (Tools.notEmpty(info.resource)) { + info.resource.toLowerCase(); + } info.shortIdentifier = m.group(3); info.displayName = m.group(4); return info; @@ -105,7 +108,7 @@ public class RefName { } public String toString() { String displaySuffix = (displayName != null && (!displayName.isEmpty())) ? '\'' + displayName + '\'' : ""; - return URN_PREFIX + tenantName + ':' + resource + "(" + shortIdentifier + ")" + displaySuffix; + return URN_PREFIX + tenantName + ':' + resource + ":" + "name" + "(" + shortIdentifier + ")" + displaySuffix; } } @@ -158,8 +161,8 @@ public class RefName { if (ai==null){ return URN_PREFIX+"ERROR:inAuthorityNotSet: (" + shortIdentifier + ")" + displaySuffix; } else { - String base = URN_PREFIX + ai.tenantName + ':' + ai.resource + "(" + ai.shortIdentifier + ")" ; - String refname = base+":items("+shortIdentifier+")"+displaySuffix; + String base = URN_PREFIX + ai.tenantName + ':' + ai.resource + ":" + "name" + "(" + ai.shortIdentifier + ")" ; + String refname = base+":item:name("+shortIdentifier+")"+displaySuffix; return refname; } }