/* (non-Javadoc)
  * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleCreate(org.collectionspace.services.common.document.DocumentWrapper)
  */
 @Override
 public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
   // first fill all the parts of the document, refname and short ID get set as well
   super.handleCreate(wrapDoc);
   // Ensure we have required fields set properly
   handleInAuthority(wrapDoc.getWrappedObject());
 }
  public AuthorityRefDocList getReferencingObjects(
      ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
      UriTemplateRegistry uriTemplateRegistry,
      List<String> serviceTypes,
      String propertyName,
      String itemcsid)
      throws Exception {
    AuthorityRefDocList authRefDocList = null;
    RepositoryInstanceInterface repoSession = null;
    boolean releaseRepoSession = false;

    try {
      RepositoryJavaClientImpl repoClient =
          (RepositoryJavaClientImpl) this.getRepositoryClient(ctx);
      repoSession = this.getRepositorySession();
      if (repoSession == null) {
        repoSession = repoClient.getRepositorySession(ctx);
        releaseRepoSession = true;
      }
      DocumentFilter myFilter = getDocumentFilter();

      try {
        DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
        DocumentModel docModel = wrapper.getWrappedObject();
        String refName = (String) docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
        authRefDocList =
            RefNameServiceUtils.getAuthorityRefDocs(
                repoSession,
                ctx,
                uriTemplateRegistry,
                repoClient,
                serviceTypes,
                refName,
                propertyName,
                myFilter,
                true /*computeTotal*/);
      } catch (PropertyException pe) {
        throw pe;
      } catch (DocumentException de) {
        throw de;
      } catch (Exception e) {
        if (logger.isDebugEnabled()) {
          logger.debug("Caught exception ", e);
        }
        throw new DocumentException(e);
      } finally {
        // If we got/aquired a new seesion then we're responsible for releasing it.
        if (releaseRepoSession && repoSession != null) {
          repoClient.releaseRepositorySession(ctx, repoSession);
        }
      }
    } catch (Exception e) {
      if (logger.isDebugEnabled()) {
        logger.debug("Caught exception ", e);
      }
      throw new DocumentException(e);
    }

    return authRefDocList;
  }
 @Override
 public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
   super.handleCreate(wrapDoc);
   // CSPACE-3178:
   // Uncomment once debugged and App layer is read to integrate
   // Experimenting with this uncommented now ...
   handleDisplayNameAsShortIdentifier(wrapDoc.getWrappedObject(), authorityCommonSchemaName);
   updateRefnameForAuthority(wrapDoc, authorityCommonSchemaName); // CSPACE-3178
 }
  @Override
  protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
    String result = null;

    DocumentModel docModel = docWrapper.getWrappedObject();
    ServiceContext ctx = this.getServiceContext();
    RefName.AuthorityItem refname = (RefName.AuthorityItem) getRefName(ctx, docModel);
    result = refname.getDisplayName();

    return result;
  }
 @Override
 public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
   DocumentModel docModel = wrapDoc.getWrappedObject();
   String[] schemas = {WorkflowClient.SERVICE_COMMONPART_NAME};
   Map<String, ObjectPartType> partsMetaMap = getServiceContext().getPartsMetadata();
   for (String schema : schemas) {
     ObjectPartType partMeta = partsMetaMap.get(schema);
     if (partMeta == null) {
       continue; // unknown part, ignore
     }
     Map<String, Object> unQObjectProperties = extractPart(docModel, schema, partMeta);
     addOutputPart(unQObjectProperties, schema, partMeta);
   }
 }
 /**
  * Generate a refName for the authority from the short identifier and display name.
  *
  * <p>All refNames for authorities are generated. If a client supplies a refName, it will be
  * overwritten during create (per this method) or discarded during update (per
  * filterReadOnlyPropertiesForPart).
  *
  * @see #filterReadOnlyPropertiesForPart(Map<String, Object>,
  *     org.collectionspace.services.common.service.ObjectPartType)
  */
 protected void updateRefnameForAuthority(
     DocumentWrapper<DocumentModel> 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);
 }
 /* (non-Javadoc)
  * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleUpdate(org.collectionspace.services.common.document.DocumentWrapper)
  */
 @Override
 // FIXME: Once we remove the refName field from the authority item schemas, we can remove this
 // override method since our super does everthing for us now.
 @Deprecated
 public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
   // Must call our super's version first, this updates the core schema and the relationship
   // records to deal with possible refName changes/update
   super.handleUpdate(wrapDoc);
   if (this.hasRefNameUpdate() == true) {
     DocumentModel docModel = wrapDoc.getWrappedObject();
     docModel.setProperty(
         authorityItemCommonSchemaName,
         AuthorityItemJAXBSchema.REF_NAME,
         this
             .newRefNameOnUpdate); // This field is deprecated since it is now a duplicate of what
                                   // is in the collectionspace_core:refName field
   }
 }
  @Override
  public RelationsCommonList extractCommonPartList(DocumentWrapper<DocumentModelList> wrapDoc)
      throws Exception {
    RelationsCommonList relList = this.extractPagingInfo(new RelationsCommonList(), wrapDoc);
    relList.setFieldsReturned(
        "subjectCsid|relationshipType|predicateDisplayName|objectCsid|uri|csid|subject|object");
    ServiceContext ctx = getServiceContext();
    String serviceContextPath = getServiceContextPath();

    TenantBindingConfigReaderImpl tReader =
        ServiceMain.getInstance().getTenantBindingConfigReader();
    String serviceName = getServiceContext().getServiceName().toLowerCase();
    ServiceBindingType sbt = tReader.getServiceBinding(ctx.getTenantId(), serviceName);

    Iterator<DocumentModel> iter = wrapDoc.getWrappedObject().iterator();
    while (iter.hasNext()) {
      DocumentModel docModel = iter.next();
      RelationListItem relListItem =
          getRelationListItem(ctx, sbt, tReader, docModel, serviceContextPath);
      relList.getRelationListItem().add(relListItem);
    }
    return relList;
  }
  public String getShortIdentifier(String authCSID, String schemaName) throws Exception {
    String shortIdentifier = null;
    RepositoryInstance repoSession = null;

    ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
    RepositoryJavaClientImpl nuxeoRepoClient =
        (RepositoryJavaClientImpl) this.getRepositoryClient(ctx);
    try {
      repoSession = nuxeoRepoClient.getRepositorySession();
      DocumentWrapper<DocumentModel> wrapDoc =
          nuxeoRepoClient.getDocFromCsid(ctx, repoSession, authCSID);
      DocumentModel docModel = wrapDoc.getWrappedObject();
      shortIdentifier =
          (String) docModel.getProperty(schemaName, AuthorityJAXBSchema.SHORT_IDENTIFIER);
    } catch (ClientException ce) {
      throw new RuntimeException("AuthorityDocHandler Internal Error: cannot get shortId!", ce);
    } finally {
      if (repoSession != null) {
        nuxeoRepoClient.releaseRepositorySession(repoSession);
      }
    }

    return shortIdentifier;
  }