Пример #1
0
  @Test
  public void testUpdateReadonlyMultidir() throws Exception {
    MultiDirectory readonlyMultidir =
        (MultiDirectory) directoryService.getDirectory("readonlymulti");
    MultiDirectorySession readonlyDir = (MultiDirectorySession) readonlyMultidir.getSession();
    Session dir1 = memdir1.getSession();
    Session dir2 = memdir2.getSession();
    Session dir3 = memdir3.getSession();

    // multi-subdirs update
    DocumentModel e = readonlyDir.getEntry("1");
    assertEquals("foo1", e.getProperty("schema3", "thefoo"));
    assertEquals("bar1", e.getProperty("schema3", "thebar"));
    e.setProperty("schema3", "thefoo", "fffooo1");
    e.setProperty("schema3", "thebar", "babar1");

    readonlyDir.updateEntry(e);
    e = readonlyDir.getEntry("1");
    // the multidirectory entry was not updated
    assertEquals("foo1", e.getProperty("schema3", "thefoo"));
    assertEquals("bar1", e.getProperty("schema3", "thebar"));

    // neither the underlying directories
    assertEquals("foo1", dir1.getEntry("1").getProperty("schema1", "foo"));
    assertEquals("bar1", dir2.getEntry("1").getProperty("schema2", "bar"));
    assertNull(dir3.getEntry("1"));
  }
Пример #2
0
 @Override
 public Serializable getReference(Object entity) throws IllegalStateException {
   checkConfig();
   DocumentModel entry = null;
   if (entity != null) {
     if (entity instanceof DirectoryEntry) {
       entry = ((DirectoryEntry) entity).getDocumentModel();
     } else if (entity instanceof DocumentModel) {
       entry = (DocumentModel) entity;
     }
     if (entry != null) {
       if (!entry.hasSchema(schema)) {
         return null;
       }
       String result = (String) entry.getProperty(schema, idField);
       if (hierarchical) {
         String parent = (String) entry.getProperty(schema, parentField);
         try (Session session = directory.getSession()) {
           while (parent != null) {
             entry = session.getEntry(parent);
             if (entry == null) {
               break;
             }
             result = parent + separator + result;
             parent = (String) entry.getProperty(schema, parentField);
           }
         }
       }
       return result;
     }
   }
   return null;
 }
 /**
  * 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);
 }
Пример #4
0
  @Test
  public void testDefaultCreateFromBlob() throws Exception {
    File file = getTestFile("test-data/hello.doc");
    Blob input = Blobs.createBlob(file, "application/msword");

    DocumentModel doc =
        service.createDocumentFromBlob(
            coreSession, input, workspace.getPathAsString(), true, "test-data/hello.doc");
    assertNotNull(doc);
    assertEquals("hello.doc", doc.getProperty("dublincore", "title"));
    assertEquals("hello.doc", doc.getProperty("file", "filename"));
    assertNotNull(doc.getProperty("file", "content"));
    BinaryBlob blob = (BinaryBlob) doc.getProperty("file", "content");
    assertEquals(blob.getMimeType(), "application/msword");

    // let's make the same test but this time without mime-type checking
    // because the blob already carries a mime-type that matches the file name
    // using mime-type check on or off should yield the same result
    doc =
        service.createDocumentFromBlob(
            coreSession, input, workspace.getPathAsString(), true, "test-data/hello2.doc", true);
    assertNotNull(doc);
    assertEquals("hello2.doc", doc.getProperty("dublincore", "title"));
    assertEquals("hello2.doc", doc.getProperty("file", "filename"));
    assertNotNull(doc.getProperty("file", "content"));
    blob = (BinaryBlob) doc.getProperty("file", "content");
    assertEquals(blob.getMimeType(), "application/msword");
  }
Пример #5
0
  @Test
  public void testCreateFromBlobWithMimeTypeCheck() throws IOException {
    // if we use a mime-type that does not match the file's name,
    // we should still get a mime-type matching the file's name
    // but only if we use mime-type check
    File file = getTestFile("test-data/hello.doc");
    Blob input = Blobs.createBlob(file, "application/sometype");
    DocumentModel doc =
        service.createDocumentFromBlob(
            coreSession, input, workspace.getPathAsString(), true, "test-data/hello3.doc");
    assertNotNull(doc);
    assertEquals("hello3.doc", doc.getProperty("dublincore", "title"));
    assertEquals("hello3.doc", doc.getProperty("file", "filename"));
    assertNotNull(doc.getProperty("file", "content"));
    BinaryBlob blob = (BinaryBlob) doc.getProperty("file", "content");
    assertEquals(blob.getMimeType(), "application/msword");

    input = Blobs.createBlob(file, "application/sometype");
    doc =
        service.createDocumentFromBlob(
            coreSession, input, workspace.getPathAsString(), true, "test-data/hello3.doc", true);
    assertNotNull(doc);
    assertEquals("hello3.doc", doc.getProperty("dublincore", "title"));
    assertEquals("hello3.doc", doc.getProperty("file", "filename"));
    assertNotNull(doc.getProperty("file", "content"));
    blob = (BinaryBlob) doc.getProperty("file", "content");
    assertEquals(blob.getMimeType(), "application/sometype");
  }
 /**
  * If no short identifier was provided in the input payload, generate a short identifier from the
  * display name.
  */
 private void handleDisplayNameAsShortIdentifier(DocumentModel docModel, String schemaName)
     throws Exception {
   String shortIdentifier =
       (String) docModel.getProperty(schemaName, AuthorityJAXBSchema.SHORT_IDENTIFIER);
   String displayName =
       (String) docModel.getProperty(schemaName, AuthorityJAXBSchema.DISPLAY_NAME);
   String shortDisplayName = "";
   if (Tools.isEmpty(shortIdentifier)) {
     String generatedShortIdentifier =
         AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(
             displayName, shortDisplayName);
     docModel.setProperty(
         schemaName, AuthorityJAXBSchema.SHORT_IDENTIFIER, generatedShortIdentifier);
   }
 }
 public static Suggestion fromDocumentModel(DocumentModel doc) {
   TypeInfo typeInfo = doc.getAdapter(TypeInfo.class);
   String description = doc.getProperty("dc:description").getValue(String.class);
   String icon = null;
   if (doc.hasSchema("common")) {
     icon = (String) doc.getProperty("common", "icon");
   }
   if (StringUtils.isEmpty(icon)) {
     icon = typeInfo.getIcon();
   }
   String thumbnailURL = String.format("api/v1/id/%s/@rendition/thumbnail", doc.getId());
   return new DocumentSuggestion(doc.getId(), new DocumentLocationImpl(doc), doc.getTitle(), icon)
       .withDescription(description)
       .withThumbnailURL(thumbnailURL);
 }
 @Override
 public String getUri(DocumentModel docModel) {
   // Laramie20110510 CSPACE-3932
   String authorityServicePath = getAuthorityServicePath();
   if (inAuthority
       == null) { // Only true with the first document model received, on queries to wildcarded
                  // authorities
     wildcardedAuthorityRequest = true;
   }
   // If this search crosses multiple authorities, get the inAuthority value
   // from each record, rather than using the cached value from the first record
   if (wildcardedAuthorityRequest) {
     try {
       inAuthority =
           (String)
               docModel.getProperty(
                   authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY);
     } catch (ClientException pe) {
       throw new RuntimeException("Could not get parent specifier for item!");
     }
   }
   return "/"
       + authorityServicePath
       + '/'
       + inAuthority
       + '/'
       + AuthorityClient.ITEMS
       + '/'
       + getCsid(docModel);
 }
  /**
   * If no short identifier was provided in the input payload, generate a short identifier from the
   * preferred term display name or term name.
   */
  private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
    String result =
        (String)
            docModel.getProperty(
                authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);

    if (Tools.isEmpty(result)) {
      String termDisplayName =
          getPrimaryDisplayName(
              docModel,
              authorityItemCommonSchemaName,
              getItemTermInfoGroupXPathBase(),
              AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);

      String termName =
          getPrimaryDisplayName(
              docModel,
              authorityItemCommonSchemaName,
              getItemTermInfoGroupXPathBase(),
              AuthorityItemJAXBSchema.TERM_NAME);

      String generatedShortIdentifier =
          AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(
              termDisplayName, termName);
      docModel.setProperty(
          authorityItemCommonSchemaName,
          AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
          generatedShortIdentifier);
      result = generatedShortIdentifier;
    }

    return result;
  }
Пример #10
0
 public String getTitle() {
   String title = null;
   if (node.isLiteral()) {
     title = ((Literal) node).getValue();
   } else if (node.isQNameResource()) {
     String resourceTitle = null;
     QNameResource resource = (QNameResource) node;
     if (documentModel != null) {
       String documentTitle;
       try {
         documentTitle = (String) documentModel.getProperty("dublincore", "title");
       } catch (ClientException e) {
         throw new ClientRuntimeException(e);
       }
       if (documentTitle != null && documentTitle.length() > 0) {
         resourceTitle = documentTitle;
       }
     }
     if (resourceTitle == null) {
       title = resource.getUri();
     } else {
       title = resourceTitle;
     }
   } else if (node.isResource()) {
     title = ((Resource) node).getUri();
   }
   return title;
 }
Пример #11
0
  @Test
  public void testCreateNoteTwiceFromSameBlob() throws Exception {
    // create doc
    File file = getTestFile("test-data/hello.html");
    Blob input = Blobs.createBlob(file, "text/html");

    DocumentModel doc =
        service.createDocumentFromBlob(
            coreSession, input, workspace.getPathAsString(), true, "test-data/hello.html");
    DocumentRef docRef = doc.getRef();

    assertNotNull(doc);
    assertEquals("hello.html", doc.getProperty("dublincore", "title"));
    String expectedNoteTest = NOTE_HTML_CONTENT;
    String noteText = ((String) doc.getProperty("note", "note"));
    if (SystemUtils.IS_OS_WINDOWS) {
      expectedNoteTest = expectedNoteTest.trim();
      expectedNoteTest = expectedNoteTest.replace("\n", "");
      expectedNoteTest = expectedNoteTest.replace("\r", "");
      noteText = expectedNoteTest.trim();
      noteText = expectedNoteTest.replace("\n", "");
      noteText = expectedNoteTest.replace("\r", "");
    }
    assertEquals(expectedNoteTest, noteText);

    List<DocumentModel> versions = coreSession.getVersions(docRef);
    assertEquals(0, versions.size());

    // create again with same file
    doc =
        service.createDocumentFromBlob(
            coreSession, input, workspace.getPathAsString(), true, "test-data/hello.html");
    assertNotNull(doc);
    DocumentRef newDocRef = doc.getRef();
    assertEquals(docRef, newDocRef);
    assertEquals("hello.html", doc.getProperty("dublincore", "title"));
    noteText = ((String) doc.getProperty("note", "note"));
    if (SystemUtils.IS_OS_WINDOWS) {
      noteText = expectedNoteTest.trim();
      noteText = expectedNoteTest.replace("\n", "");
      noteText = expectedNoteTest.replace("\r", "");
    }
    assertEquals(expectedNoteTest, noteText);

    versions = coreSession.getVersions(docRef);
    assertEquals(1, versions.size());
  }
  /**
   * Gets the relation list item, looking up the subject and object documents, and getting summary
   * info via the objectName and objectNumber properties in tenant-bindings.
   *
   * @param ctx the ctx
   * @param sbt the ServiceBindingType of Relations service
   * @param tReader the tenant-bindings reader, for looking up docnumber and docname
   * @param docModel the doc model
   * @param serviceContextPath the service context path
   * @return the relation list item, with nested subject and object summary info.
   * @throws Exception the exception
   */
  private RelationListItem getRelationListItem(
      ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
      ServiceBindingType sbt,
      TenantBindingConfigReaderImpl tReader,
      DocumentModel docModel,
      String serviceContextPath)
      throws Exception {
    RelationListItem relationListItem = new RelationListItem();
    String id = getCsid(docModel);
    relationListItem.setCsid(id);

    relationListItem.setSubjectCsid(
        (String) docModel.getProperty(ctx.getCommonPartLabel(), RelationJAXBSchema.DOCUMENT_ID_1));

    String predicate =
        (String)
            docModel.getProperty(ctx.getCommonPartLabel(), RelationJAXBSchema.RELATIONSHIP_TYPE);
    relationListItem.setRelationshipType(predicate);
    relationListItem.setPredicate(predicate); // predicate is new name for relationshipType.
    relationListItem.setPredicateDisplayName(
        (String)
            docModel.getProperty(
                ctx.getCommonPartLabel(), RelationJAXBSchema.RELATIONSHIP_TYPE_DISPLAYNAME));

    relationListItem.setObjectCsid(
        (String) docModel.getProperty(ctx.getCommonPartLabel(), RelationJAXBSchema.DOCUMENT_ID_2));

    relationListItem.setUri(serviceContextPath + id);

    // Now fill in summary info for the related docs: subject and object.
    String subjectCsid = relationListItem.getSubjectCsid();
    String documentType =
        (String) docModel.getProperty(ctx.getCommonPartLabel(), RelationJAXBSchema.DOCUMENT_TYPE_1);
    RelationsDocListItem subject =
        createRelationsDocListItem(ctx, sbt, subjectCsid, tReader, documentType);

    // Object o1 =  docModel.getProperty(ctx.getCommonPartLabel(), "subject");
    // Object o2 =  docModel.getProperty(ctx.getCommonPartLabel(), "object");

    String subjectUri =
        (String) docModel.getProperty(ctx.getCommonPartLabel(), RelationJAXBSchema.subjectUri);
    subject.setUri(subjectUri);
    relationListItem.setSubject(subject);

    String objectCsid = relationListItem.getObjectCsid();
    String documentType2 =
        (String) docModel.getProperty(ctx.getCommonPartLabel(), RelationJAXBSchema.DOCUMENT_TYPE_2);
    RelationsDocListItem object =
        createRelationsDocListItem(ctx, sbt, objectCsid, tReader, documentType2);

    String objectUri =
        (String) docModel.getProperty(ctx.getCommonPartLabel(), RelationJAXBSchema.objectUri);
    object.setUri(objectUri);
    relationListItem.setObject(object);

    return relationListItem;
  }
Пример #13
0
  @Test
  public void testUpdateFileDocWithPlainTextFile() throws Exception {

    // create a File whose title is "hello.html" and content is "hello.rtf"
    File file = getTestFile("test-data/hello.rtf");
    Blob input = Blobs.createBlob(file, "text/rtf", null, "hello.html");

    DocumentModel doc =
        coreSession.createDocumentModel(workspace.getPathAsString(), "hello.html", "File");
    doc.setPropertyValue("dc:title", "hello.html");
    doc.setPropertyValue("file:content", (Serializable) input);
    doc.setPropertyValue("file:filename", "hello.html");

    // create doc
    doc = coreSession.createDocument(doc);
    coreSession.save();
    DocumentRef docRef = doc.getRef();

    assertNotNull(doc);
    assertEquals("hello.html", doc.getProperty("dublincore", "title"));
    assertEquals("hello.html", doc.getProperty("file", "filename"));
    assertNotNull(doc.getProperty("file", "content"));
    assertTrue(extractText(doc).contains("RTF"));
    assertEquals("text/rtf", getMimeType(doc));

    List<DocumentModel> versions = coreSession.getVersions(docRef);
    assertEquals(0, versions.size());

    // update the with a file that matches the same importer
    file = getTestFile("test-data/hello.html");
    input = Blobs.createBlob(file, "text/html");
    doc =
        service.createDocumentFromBlob(
            coreSession, input, workspace.getPathAsString(), true, "test-data/hello.html");
    assertNotNull(doc);

    DocumentRef newDocRef = doc.getRef();
    assertEquals(docRef, newDocRef);
    assertEquals("hello.html", doc.getProperty("file", "filename"));
    assertNotNull(doc.getProperty("file", "content"));
    assertTrue(extractText(doc).contains("HTML"));
    assertEquals("text/html", getMimeType(doc));

    versions = coreSession.getVersions(docRef);
    assertEquals(1, versions.size());
  }
Пример #14
0
  @Test
  public void testUpdatePartialReadOnlyMultidir() throws Exception {
    Session dir1 = memdir1.getSession();
    Session dir2 = memdir2.getSession();
    Session dir3 = memdir3.getSession();

    memdir2.setReadOnly(true);
    memdir3.setReadOnly(true);

    // multi-subdirs update
    DocumentModel e = dir.getEntry("1");
    assertEquals("foo1", e.getProperty("schema3", "thefoo"));
    assertEquals("bar1", e.getProperty("schema3", "thebar"));
    e.setProperty("schema3", "thefoo", "fffooo1");
    e.setProperty("schema3", "thebar", "babar1");
    dir.updateEntry(e);
    e = dir.getEntry("1");
    assertEquals("fffooo1", e.getProperty("schema3", "thefoo"));
    assertEquals("bar1", e.getProperty("schema3", "thebar"));

    // check underlying directories
    // update not done on readonly dir2
    assertEquals("fffooo1", dir1.getEntry("1").getProperty("schema1", "foo"));
    assertEquals("bar1", dir2.getEntry("1").getProperty("schema2", "bar"));
    assertNull(dir3.getEntry("1"));

    // single subdir update
    e = dir.getEntry("3");
    assertEquals("foo3", e.getProperty("schema3", "thefoo"));
    assertEquals("bar3", e.getProperty("schema3", "thebar"));
    e.setProperty("schema3", "thefoo", "fffooo3");
    e.setProperty("schema3", "thebar", "babar3");
    dir.updateEntry(e);

    e = dir.getEntry("3");
    assertEquals("foo3", e.getProperty("schema3", "thefoo"));
    assertEquals("bar3", e.getProperty("schema3", "thebar"));

    // check underlying directories
    // check update is not effective on readonly subdir
    assertNull(dir1.getEntry("3"));
    assertNull(dir2.getEntry("3"));
    assertNotNull(dir3.getEntry("3"));
    assertEquals("foo3", dir3.getEntry("3").getProperty("schema3", "thefoo"));
    assertEquals("bar3", dir3.getEntry("3").getProperty("schema3", "thebar"));
  }
  @Override
  public DocumentModel getEntry(String id, boolean fetchReferences) throws DirectoryException {
    if (!isCurrentUserAllowed(SecurityConstants.READ)) {
      return null;
    }
    init();
    String entryId = id;
    source_loop:
    for (SourceInfo sourceInfo : sourceInfos) {
      boolean isReadOnlyEntry = true;
      final Map<String, Object> map = new HashMap<String, Object>();

      for (SubDirectoryInfo dirInfo : sourceInfo.subDirectoryInfos) {
        final DocumentModel entry = dirInfo.getSession().getEntry(id, fetchReferences);
        boolean isOptional = dirInfo.isOptional;
        if (entry == null && !isOptional) {
          // not in this source
          continue source_loop;
        }
        if (entry != null && !isReadOnlyEntry(entry)) {
          // set readonly to false if at least one source is writable
          isReadOnlyEntry = false;
        }
        if (entry == null && isOptional && !dirInfo.getSession().isReadOnly()) {
          // set readonly to false if null entry is from optional and writable directory
          isReadOnlyEntry = false;
        }
        if (entry != null && entry.getId() == null) {
          entryId = entry.getId();
        }
        for (Entry<String, String> e : dirInfo.toSource.entrySet()) {
          if (entry != null) {
            try {
              map.put(e.getValue(), entry.getProperty(dirInfo.dirSchemaName, e.getKey()));
            } catch (PropertyException e1) {
              throw new DirectoryException(e1);
            }
          } else {
            // fill with default values for this directory
            if (!map.containsKey(e.getValue())) {
              map.put(e.getValue(), dirInfo.defaultEntry.get(e.getKey()));
            }
          }
        }
      }
      // force the entry in readonly if it's defined on the multidirectory
      if (isReadOnly()) {
        isReadOnlyEntry = true;
      }
      // ok we have the data
      try {
        return BaseSession.createEntryModel(null, schemaName, entryId, map, isReadOnlyEntry);
      } catch (PropertyException e) {
        throw new DirectoryException(e);
      }
    }
    return null;
  }
Пример #16
0
  @Test
  public void testRestoreToVersion() throws Exception {
    String name2 = "file#456";
    DocumentModel doc = new DocumentModelImpl("/", name2, "File");
    doc = session.createDocument(doc);
    DocumentRef docRef = doc.getRef();

    session.save();
    DocumentRef v1Ref = session.checkIn(docRef, null, null);
    assertFalse(session.isCheckedOut(docRef));
    session.checkOut(docRef);
    assertTrue(session.isCheckedOut(docRef));

    doc.setProperty("file", "filename", "second name");
    doc.setProperty("dc", "title", "f1");
    doc.setProperty("dc", "description", "desc 1");
    session.saveDocument(doc);
    session.save();

    maybeSleepToNextSecond();
    DocumentRef v2Ref = session.checkIn(docRef, null, null);
    session.checkOut(docRef);

    DocumentModel newDoc = session.getDocument(docRef);
    assertNotNull(newDoc);
    assertNotNull(newDoc.getRef());
    assertEquals("second name", newDoc.getProperty("file", "filename"));

    waitForFulltextIndexing();
    maybeSleepToNextSecond();
    DocumentModel restoredDoc = session.restoreToVersion(docRef, v1Ref);

    assertNotNull(restoredDoc);
    assertNotNull(restoredDoc.getRef());
    assertNull(restoredDoc.getProperty("file", "filename"));

    waitForFulltextIndexing();
    maybeSleepToNextSecond();
    restoredDoc = session.restoreToVersion(docRef, v2Ref);

    assertNotNull(restoredDoc);
    assertNotNull(restoredDoc.getRef());
    String pr = (String) restoredDoc.getProperty("file", "filename");
    assertEquals("second name", pr);
  }
  public String getVocabularyLabel(String voc_name, String key) {

    DirectoryService ds = Framework.getLocalService(DirectoryService.class);
    if (ds == null) {
      return key;
    }

    List<String> vocs = new ArrayList<String>();
    List<String> keys = new ArrayList<String>();
    if (voc_name.contains("/")) {
      String[] parts = voc_name.split("\\/");
      for (String part : parts) {
        vocs.add(part);
      }
      parts = key.split("\\/");
      for (String part : parts) {
        keys.add(part);
      }
    } else {
      vocs.add(voc_name);
      keys.add(key);
    }

    List<String> values = new ArrayList<String>();

    for (int i = 0; i < vocs.size(); i++) {
      String voc = vocs.get(i);
      String keyValue = keys.get(i);
      if (ds.getDirectoryNames().contains(voc)) {
        Directory dir = ds.getDirectory(voc);
        String schema = dir.getSchema();
        if ("vocabulary".equals(schema) || "xvocabulary".equals(schema)) {
          try (Session session = dir.getSession()) {
            DocumentModel entry = session.getEntry(keyValue);
            if (entry != null) {
              values.add((String) entry.getProperty(schema, "label"));
            }
          }
        }
      }
    }
    if (values.size() == 0) {
      return key;
    } else if (values.size() == 1) {
      return values.get(0);
    } else {
      String result = "";
      for (int i = 0; i < values.size(); i++) {
        if (i > 0) {
          result = result + " / ";
        }
        result = result + values.get(i);
      }
      return result;
    }
  }
 /**
  * Returns the CSID for a desired document type from a Relation record, where the relationship
  * involves two specified, different document types.
  *
  * @param relationDocModel a document model for a Relation record.
  * @param desiredDocType a desired document type.
  * @param relatedDocType a related document type.
  * @throws ClientException
  * @return the CSID from the desired document type in the relation. Returns an empty string if the
  *     Relation record does not involve both the desired and related document types, or if the
  *     desired document type is at both ends of the relation.
  */
 protected static String getCsidForDesiredDocTypeFromRelation(
     DocumentModel relationDocModel, String desiredDocType, String relatedDocType)
     throws ClientException {
   String csid = "";
   String subjectDocType =
       (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_DOCTYPE_PROPERTY);
   String objectDocType =
       (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_DOCTYPE_PROPERTY);
   if (subjectDocType.startsWith(desiredDocType) && objectDocType.startsWith(desiredDocType)) {
     return csid;
   }
   if (subjectDocType.startsWith(desiredDocType) && objectDocType.startsWith(relatedDocType)) {
     csid = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_CSID_PROPERTY);
   } else if (subjectDocType.startsWith(relatedDocType)
       && objectDocType.startsWith(desiredDocType)) {
     csid = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_CSID_PROPERTY);
   }
   return csid;
 }
Пример #19
0
 public static List<DocumentModel> getChildrenCategories(DocumentModel currentCategory)
     throws PropertyException, NullException, ClientException {
   List<DocumentModel> result = new ArrayList<DocumentModel>();
   int idCurrentCategory =
       ((Long)
               currentCategory.getProperty(
                   LabsSiteConstants.Schemas.LABS_CATEGORY.getName(), "id"))
           .intValue();
   if (idCurrentCategory != 0) {
     int parent;
     for (DocumentModel cat : getAllLabsCategory()) {
       parent =
           ((Long) cat.getProperty(LabsSiteConstants.Schemas.LABS_CATEGORY.getName(), "parent"))
               .intValue();
       if (parent == idCurrentCategory) {
         result.add(cat);
       }
     }
   }
   return result;
 }
Пример #20
0
  @Test
  public void testDefaultUpdateFromBlob() throws Exception {
    // create doc
    File file = getTestFile("test-data/hello.doc");
    Blob input = Blobs.createBlob(file, "application/msword");

    DocumentModel doc =
        service.createDocumentFromBlob(
            coreSession, input, workspace.getPathAsString(), true, "test-data/hello.doc");
    DocumentRef docRef = doc.getRef();

    assertNotNull(doc);
    assertEquals("hello.doc", doc.getProperty("dublincore", "title"));
    assertEquals("hello.doc", doc.getProperty("file", "filename"));
    assertNotNull(doc.getProperty("file", "content"));

    // update it with another file with same name
    doc =
        service.updateDocumentFromBlob(
            coreSession, input, workspace.getPathAsString(), "test-data/update/hello.doc");
    assertNotNull(doc);

    DocumentRef newDocRef = doc.getRef();
    assertEquals(docRef, newDocRef);
    assertEquals("hello.doc", doc.getProperty("dublincore", "title"));
    assertEquals("hello.doc", doc.getProperty("file", "filename"));
    assertNotNull(doc.getProperty("file", "content"));
  }
Пример #21
0
  @Test
  public void testDefaultCreateTwiceFromSameBlob() throws Exception {
    // create doc
    File file = getTestFile("test-data/hello.doc");
    Blob input = Blobs.createBlob(file, "application/msword");

    DocumentModel doc =
        service.createDocumentFromBlob(
            coreSession, input, workspace.getPathAsString(), true, "test-data/hello.doc");
    DocumentRef docRef = doc.getRef();

    assertNotNull(doc);
    assertEquals("hello.doc", doc.getProperty("dublincore", "title"));
    assertEquals("hello.doc", doc.getProperty("file", "filename"));
    assertNotNull(doc.getProperty("file", "content"));

    List<DocumentModel> versions = coreSession.getVersions(docRef);
    assertEquals(0, versions.size());

    // create again with same file
    doc =
        service.createDocumentFromBlob(
            coreSession, input, workspace.getPathAsString(), true, "test-data/hello.doc");
    assertNotNull(doc);

    DocumentRef newDocRef = doc.getRef();
    assertEquals(docRef, newDocRef);
    assertEquals("hello.doc", doc.getProperty("dublincore", "title"));
    assertEquals("hello.doc", doc.getProperty("file", "filename"));
    assertNotNull(doc.getProperty("file", "content"));

    versions = coreSession.getVersions(docRef);
    assertEquals(1, versions.size());
  }
Пример #22
0
  @Override
  public DocumentModel create(
      CoreSession documentManager,
      Blob content,
      String path,
      boolean overwrite,
      String fullname,
      TypeManager typeService)
      throws ClientException, IOException {
    path = getNearestContainerPath(documentManager, path);
    doSecurityCheck(documentManager, path, getNoteTypeName(), typeService);

    String filename = FileManagerUtils.fetchFileName(fullname);

    String title = FileManagerUtils.fetchTitle(filename);

    // Looking if an existing Document with the same filename exists.
    DocumentModel docModel = FileManagerUtils.getExistingDocByTitle(documentManager, path, title);

    if (overwrite && docModel != null) {

      docModel.setProperty(NOTE_SCHEMA, NOTE_FIELD, getString(content));
      docModel.setProperty(NOTE_SCHEMA, MT_FIELD, content.getMimeType());
      docModel = overwriteAndIncrementversion(documentManager, docModel);
    } else {
      PathSegmentService pss;
      try {
        pss = Framework.getService(PathSegmentService.class);
      } catch (Exception e) {
        throw new ClientException(e);
      }
      // Create a new empty DocumentModel of type Note in memory
      docModel = documentManager.createDocumentModel(getNoteTypeName());

      // Update known attributes (title, note)
      docModel.setProperty(DUBLINCORE_SCHEMA, TITLE_FIELD, title);
      docModel.setProperty(NOTE_SCHEMA, NOTE_FIELD, getString(content));
      docModel.setProperty(NOTE_SCHEMA, MT_FIELD, content.getMimeType());

      // Create the new document in the repository
      docModel.setPathInfo(path, pss.generatePathSegment(docModel));
      docModel = documentManager.createDocument(docModel);
    }
    documentManager.save();

    log.debug(
        "Created the Note: "
            + docModel.getName()
            + " with icon: "
            + docModel.getProperty(COMMON_SCHEMA, ICON_FIELD));
    return docModel;
  }
Пример #23
0
  @Test
  public void testCreate() throws Exception {
    Session dir1 = memdir1.getSession();
    Session dir2 = memdir2.getSession();
    Session dir3 = memdir3.getSession();

    // multi-subdir create
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("uid", "5");
    map.put("thefoo", "foo5");
    map.put("thebar", "bar5");
    DocumentModel entry = dir.createEntry(map);
    assertEquals("5", entry.getProperty("schema3", "uid"));
    assertEquals("foo5", entry.getProperty("schema3", "thefoo"));
    assertEquals("bar5", entry.getProperty("schema3", "thebar"));
    boolean exceptionThrwon = false;
    try {
      assertNull(entry.getProperty("schema3", "xyz"));
    } catch (ClientException ce) {
      exceptionThrwon = true;
    }
    assertTrue(exceptionThrwon);

    // check underlying directories
    assertNotNull(dir1.getEntry("5"));
    assertEquals("foo5", dir1.getEntry("5").getProperty("schema1", "foo"));
    assertNotNull(dir2.getEntry("5"));
    assertEquals("bar5", dir2.getEntry("5").getProperty("schema2", "bar"));
    assertNull(dir3.getEntry("5"));

    // create another with colliding id
    map = new HashMap<String, Object>();
    map.put("uid", "5");
    try {
      entry = dir.createEntry(map);
      fail("Should raise an error, entry already exists");
    } catch (DirectoryException e) {
    }
  }
Пример #24
0
  @Test
  public void testCreateNote() throws Exception {
    File file = getTestFile("test-data/hello.html");
    Blob input = Blobs.createBlob(file, "text/html");

    DocumentModel doc =
        service.createDocumentFromBlob(
            coreSession, input, workspace.getPathAsString(), true, "test-data/hello.html");
    assertNotNull(doc);
    assertEquals("hello.html", doc.getProperty("dublincore", "title"));
    String expectedNoteTest = NOTE_HTML_CONTENT;
    String noteText = ((String) doc.getProperty("note", "note"));
    if (SystemUtils.IS_OS_WINDOWS) {
      expectedNoteTest = expectedNoteTest.trim();
      expectedNoteTest = expectedNoteTest.replace("\n", "");
      expectedNoteTest = expectedNoteTest.replace("\r", "");
      noteText = expectedNoteTest.trim();
      noteText = expectedNoteTest.replace("\n", "");
      noteText = expectedNoteTest.replace("\r", "");
    }
    assertEquals(expectedNoteTest, noteText);
  }
Пример #25
0
 @Override
 public List<NuxeoGroup> getCurrentPage() {
   List<DocumentModel> groups = computeCurrentPage();
   List<NuxeoGroup> nuxeoGroups = new ArrayList<>(groups.size());
   UserManager userManager = Framework.getLocalService(UserManager.class);
   for (DocumentModel group : groups) {
     NuxeoGroup nuxeoGroup =
         userManager.getGroup(
             group.getProperty(userManager.getGroupIdField()).getValue(String.class));
     nuxeoGroups.add(nuxeoGroup);
   }
   return nuxeoGroups;
 }
Пример #26
0
  @Test
  public void testGetDocumentWithVersion() throws Exception {
    String name2 = "file#248";
    DocumentModel childFile = new DocumentModelImpl("/", name2, "File");
    childFile = session.createDocument(childFile);
    session.save();
    DocumentRef v1Ref = session.checkIn(childFile.getRef(), null, null);
    session.checkOut(childFile.getRef());

    childFile.setProperty("file", "filename", "second name");
    childFile.setProperty("dc", "title", "f1");
    childFile.setProperty("dc", "description", "desc 1");
    session.saveDocument(childFile);
    session.save();
    maybeSleepToNextSecond();
    DocumentRef v2Ref = session.checkIn(childFile.getRef(), null, null);

    DocumentModel newDoc = session.getDocument(childFile.getRef());
    assertNotNull(newDoc);
    assertNotNull(newDoc.getRef());
    assertEquals("second name", newDoc.getProperty("file", "filename"));

    // restore, no snapshot as already pristine
    waitForFulltextIndexing();
    maybeSleepToNextSecond();
    DocumentModel restoredDoc = session.restoreToVersion(childFile.getRef(), v1Ref);

    assertNotNull(restoredDoc);
    assertNotNull(restoredDoc.getRef());
    assertNull(restoredDoc.getProperty("file", "filename"));

    DocumentModel last = session.getLastDocumentVersion(childFile.getRef());
    assertNotNull(last);
    assertNotNull(last.getRef());
    assertEquals(v2Ref.reference(), last.getId());
    assertEquals("second name", last.getProperty("file", "filename"));
  }
  @Test
  public void testAddManyDocsToNewCollectionAndRemove() throws ClientException {
    DocumentModel testWorkspace =
        session.createDocumentModel("/default-domain/workspaces", "testWorkspace", "Workspace");
    testWorkspace = session.createDocument(testWorkspace);

    List<DocumentModel> files = createTestFiles(session, 3);

    collectionManager.addToNewCollection(COLLECTION_NAME, COLLECTION_DESCRIPTION, files, session);

    assertTrue(session.exists(new PathRef(COLLECTION_FOLDER_PATH)));

    final String newlyCreatedCollectionPath = COLLECTION_FOLDER_PATH + "/" + COLLECTION_NAME;

    DocumentRef newCollectionRef = new PathRef(newlyCreatedCollectionPath);
    assertTrue(session.exists(newCollectionRef));

    DocumentModel newlyCreatedCollection = session.getDocument(newCollectionRef);
    final String newlyCreatedCollectionId = newlyCreatedCollection.getId();

    assertEquals(COLLECTION_NAME, newlyCreatedCollection.getTitle());

    assertEquals(
        COLLECTION_DESCRIPTION, newlyCreatedCollection.getProperty("dc:description").getValue());

    for (DocumentModel file : files) {
      file = session.getDocument(file.getRef());

      Collection collectionAdapter = newlyCreatedCollection.getAdapter(Collection.class);

      assertTrue(collectionAdapter.getCollectedDocumentIds().contains(file.getId()));

      CollectionMember collectionMemberAdapter = file.getAdapter(CollectionMember.class);

      assertTrue(collectionMemberAdapter.getCollectionIds().contains(newlyCreatedCollectionId));
    }

    collectionManager.removeAllFromCollection(newlyCreatedCollection, files, session);

    for (DocumentModel file : files) {
      Collection collectionAdapter = newlyCreatedCollection.getAdapter(Collection.class);

      assertFalse(collectionAdapter.getCollectedDocumentIds().contains(file.getId()));

      CollectionMember collectionMemberAdapter = file.getAdapter(CollectionMember.class);

      assertFalse(collectionMemberAdapter.getCollectionIds().contains(newlyCreatedCollectionId));
    }
  }
  /*
   * After calling this method successfully, the document model will contain an updated refname and short ID
   * (non-Javadoc)
   * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getRefName(org.collectionspace.services.common.context.ServiceContext, org.nuxeo.ecm.core.api.DocumentModel)
   */
  @Override
  public RefName.RefNameInterface getRefName(ServiceContext ctx, DocumentModel docModel) {
    RefName.RefNameInterface refname = null;

    try {
      String displayName =
          getPrimaryDisplayName(
              docModel,
              authorityItemCommonSchemaName,
              getItemTermInfoGroupXPathBase(),
              AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
      if (Tools.isEmpty(displayName)) {
        throw new Exception("The displayName for this authority term was empty or not set.");
      }

      String shortIdentifier =
          (String)
              docModel.getProperty(
                  authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
      if (Tools.isEmpty(shortIdentifier)) {
        // We didn't find a short ID in the payload request, so we need to synthesize one.
        shortIdentifier =
            handleDisplayNameAsShortIdentifier(
                docModel); // updates the document model with the new short ID as a side-effect
      }

      String authorityRefBaseName = getAuthorityRefNameBase();
      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.");
      }

      // Create the items refname using the parent's as a base
      RefName.Authority parentsRefName = RefName.Authority.parse(authorityRefBaseName);
      refname = RefName.buildAuthorityItem(parentsRefName, shortIdentifier, displayName);
      // Now update the document model with the refname value
      String refNameStr = refname.toString();
      docModel.setProperty(
          authorityItemCommonSchemaName,
          AuthorityItemJAXBSchema.REF_NAME,
          refNameStr); // REM - This field is deprecated now that the refName is part of the
                       // collection_space core schema

    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }

    return refname;
  }
Пример #29
0
 @Test
 public void testGetEntries() throws Exception {
   DocumentModelList l;
   l = dir.getEntries();
   assertEquals(4, l.size());
   DocumentModel entry = null;
   for (DocumentModel e : l) {
     if (e.getId().equals("1")) {
       entry = e;
       break;
     }
   }
   assertNotNull(entry);
   assertEquals("foo1", entry.getProperty("schema3", "thefoo"));
 }
Пример #30
0
 protected String retrieveLabelFromEntry(DocumentModel docEntry) {
   if (docEntry == null) {
     return null;
   }
   String schema = docEntry.getSchemas()[0];
   // compute label
   Object labelObject = getItemLabel();
   String label = labelObject != null ? labelObject.toString() : null;
   FacesContext ctx = FacesContext.getCurrentInstance();
   Locale locale = ctx.getViewRoot().getLocale();
   if (StringUtils.isBlank(label)) {
     if (isLocalize() && isdbl10n()) {
       // lookup label property, hardcode the "label_" prefix for
       // now
       String defaultPattern = "label_en";
       String pattern = "label_" + locale.getLanguage();
       label = (String) docEntry.getProperty(schema, pattern);
       if (StringUtils.isBlank(label)) {
         label = (String) docEntry.getProperty(schema, defaultPattern);
       }
       if (StringUtils.isBlank(label)) {
         label = docEntry.getId();
         log.warn(
             "Could not find label column for entry " + label + " (falling back on entry id)");
       }
     } else {
       label = (String) docEntry.getProperties(schema).get("label");
       if (isLocalize()) {
         label = translate(ctx, locale, label);
       }
     }
   } else if (isLocalize()) {
     label = translate(ctx, locale, label);
   }
   return label;
 }