@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");
  }
  /**
   * Tests that we cannot add a document to a document which is not a document of type Collection.
   */
  @Test
  public void testCanAddCollectionNotCollection() throws ClientException {
    DocumentModel testWorkspace =
        session.createDocumentModel("/default-domain/workspaces", "testWorkspace", "Workspace");
    testWorkspace = session.createDocument(testWorkspace);
    DocumentModel testFile =
        session.createDocumentModel(testWorkspace.getPathAsString(), TEST_FILE_NAME, "File");
    testFile = session.createDocument(testFile);
    collectionManager.addToNewCollection(
        COLLECTION_NAME, COLLECTION_DESCRIPTION, testFile, session);

    DocumentModel testFile2 =
        session.createDocumentModel(testWorkspace.getPathAsString(), TEST_FILE_NAME + 2, "File");
    testFile2 = session.createDocument(testFile2);
    collectionManager.addToNewCollection(
        COLLECTION_NAME, COLLECTION_DESCRIPTION, testFile2, session);

    try {
      collectionManager.addToCollection(testFile, testFile2, session);
    } catch (IllegalArgumentException e) {
      // Expeted behaviour
      return;
    }
    fail("File is not a Collection");
  }
  @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"));
  }
  @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());
  }
 protected String resolvePath(Element el, String xpr) {
   Object ob = resolve(el, xpr);
   if (ob == null) {
     for (int i = 0; i < docsStack.size(); i++) {
       if (docsStack.get(i).isFolder()) {
         return docsStack.get(i).getPathAsString();
       }
     }
   } else {
     if (ob instanceof DocumentModel) {
       return ((DocumentModel) ob).getPathAsString();
     } else if (ob instanceof Node) {
       if (ob instanceof Element) {
         Element targetElement = (Element) ob;
         DocumentModel target = elToDoc.get(targetElement);
         if (target != null) {
           return target.getPathAsString();
         } else {
           return targetElement.getText();
         }
       } else if (ob instanceof Attribute) {
         return ((Attribute) ob).getValue();
       } else if (ob instanceof Text) {
         return ((Text) ob).getText();
       } else if (ob.getClass().isAssignableFrom(Attribute.class)) {
         return ((Attribute) ob).getValue();
       }
     } else {
       return ob.toString();
     }
   }
   return rootDoc.getPathAsString();
 }
  @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");
  }
  @Test
  public void testGetParentDocuments() {

    setPermissionToAnonymous(EVERYTHING);

    DocumentModel root = session.getRootDocument();

    String name = "Workspaces#1";
    DocumentModel workspaces = new DocumentModelImpl(root.getPathAsString(), name, "Workspace");
    session.createDocument(workspaces);
    String name2 = "repositoryWorkspace2#";
    DocumentModel repositoryWorkspace =
        new DocumentModelImpl(workspaces.getPathAsString(), name2, "Workspace");
    repositoryWorkspace = session.createDocument(repositoryWorkspace);

    String name3 = "ws#3";
    DocumentModel ws1 =
        new DocumentModelImpl(repositoryWorkspace.getPathAsString(), name3, "Workspace");
    ws1 = session.createDocument(ws1);
    String name4 = "ws#4";
    DocumentModel ws2 = new DocumentModelImpl(ws1.getPathAsString(), name4, "Workspace");
    session.createDocument(ws2);

    if (session.isNegativeAclAllowed()) { // always false for Mem
      ACP acp = new ACPImpl();
      ACE denyRead = new ACE("test", READ, false);
      ACL acl = new ACLImpl();
      acl.setACEs(new ACE[] {denyRead});
      acp.addACL(acl);
      // TODO this produces a stack trace
      repositoryWorkspace.setACP(acp, true);
      ws1.setACP(acp, true);
    }

    session.save();

    List<DocumentModel> ws2ParentsUnderAdministrator = session.getParentDocuments(ws2.getRef());
    assertTrue(
        "list parents for"
            + ws2.getName()
            + "under "
            + session.getPrincipal().getName()
            + " is not empty:",
        !ws2ParentsUnderAdministrator.isEmpty());

    CoreSession testSession = openSessionAs("test");
    List<DocumentModel> ws2ParentsUnderTest = testSession.getParentDocuments(ws2.getRef());
    assertTrue(
        "list parents for"
            + ws2.getName()
            + "under "
            + testSession.getPrincipal().getName()
            + " is empty:",
        ws2ParentsUnderTest.isEmpty());
    closeSession(testSession);
  }
Beispiel #8
0
 @Override
 public int compare(DocumentModel doc1, DocumentModel doc2) {
   String p1 = doc1.getPathAsString();
   String p2 = doc2.getPathAsString();
   if (p1 == null && p2 == null) {
     return sign * doc1.getId().compareTo(doc2.getId());
   } else if (p1 == null) {
     return sign;
   } else if (p2 == null) {
     return -1 * sign;
   }
   return sign * p1.compareTo(p2);
 }
  @Test
  public void testReadAclSecurityUpdate() {
    // check that aclOptimization update the user aclr cache
    // NXP-13109
    DocumentModel root = session.getRootDocument();
    // Create a doc and set a new ACLR on it
    DocumentModel doc = new DocumentModelImpl(root.getPathAsString(), "foo", "Folder");
    doc = session.createDocument(doc);
    ACP acp = doc.getACP();
    assertNotNull(acp);
    acp = new ACPImpl();
    ACL acl = new ACLImpl();
    acl.add(new ACE("Everyone", "Read", true));
    acp.addACL(acl);
    doc.setACP(acp, true);
    session.save();

    CoreSession joeSession = openSessionAs("joe");
    try {
      DocumentModelList list;
      list = joeSession.query("SELECT * FROM Folder");
      assertEquals(1, list.size());
      // Remove the document, so the ACLR created is not anymore assigned
      session.removeDocument(doc.getRef());
      session.save();
      list = joeSession.query("SELECT * FROM Folder");
      assertEquals(0, list.size());
    } finally {
      closeSession(joeSession);
    }

    CoreSession bobSession = openSessionAs("bob");
    try {
      DocumentModelList list;
      // Perform a query to init the ACLR cache
      list = bobSession.query("SELECT * FROM Folder");
      assertEquals(0, list.size());
      // Create a new doc with the same ACLR
      doc = new DocumentModelImpl(root.getPathAsString(), "bar", "Folder");
      doc = session.createDocument(doc);
      doc.setACP(acp, true);
      session.save();
      // Check that the ACLR has been added to the user cache
      list = bobSession.query("SELECT * FROM Folder");
      assertEquals(1, list.size());
    } finally {
      closeSession(bobSession);
    }
  }
  @Test
  public void testACLEscaping() {
    // temporary set an Everything privileges on the root for anonymous
    // so that we can create a folder
    setPermissionToAnonymous(EVERYTHING);

    DocumentModel root = session.getRootDocument();

    DocumentModel folder = new DocumentModelImpl(root.getPathAsString(), "folder1", "Folder");
    folder = session.createDocument(folder);

    ACP acp = new ACPImpl();
    ACL acl = new ACLImpl();
    acl.add(new ACE("xyz", "Read", true));
    acl.add(new ACE("abc@def<&>/ ", "Read", true));
    acl.add(new ACE("caf\u00e9", "Read", true));
    acl.add(new ACE("o'hara", "Read", true)); // name to quote
    acl.add(new ACE("A_x1234_", "Read", true)); // name to quote
    acp.addACL(acl);
    folder.setACP(acp, true);

    // check what we read
    acp = folder.getACP();
    assertNotNull(acp);
    acl = acp.getACL(ACL.LOCAL_ACL);
    assertEquals("xyz", acl.get(0).getUsername());
    assertEquals("abc@def<&>/ ", acl.get(1).getUsername());
    assertEquals("caf\u00e9", acl.get(2).getUsername());
    assertEquals("o'hara", acl.get(3).getUsername());
    assertEquals("A_x1234_", acl.get(4).getUsername());
  }
  @Test
  public void iCanGetLatestUploadsPageProvider() throws Exception {
    DocumentModel site = createSite();

    PageClasseur classeur =
        new PageClasseurAdapter.Model(
                session,
                site.getPathAsString() + "/" + LabsSiteConstants.Docs.TREE.docName(),
                "ma page classeur")
            .desc("desc page classeur")
            .create();
    assertThat(classeur.getFolders().size(), is(0));

    classeur.addFolder("My Folder", null);
    session.save();
    PageClasseurFolder folder = classeur.getFolders().get(0);
    assertThat(folder.getFiles().size(), is(0));
    folder.addFile(getTestBlob(), "Pomodoro cheat sheet", "title");
    session.save();
    assertThat(folder.getFiles().size(), is(1));
    session.save();

    Tools.getAdapter(LabsPublisher.class, classeur.getDocument(), null).publish();

    PageProvider<DocumentModel> latestUploadsPageProvider =
        LabsSiteWebAppUtils.getLatestUploadsPageProvider(site, 0, session);
    assertNotNull(latestUploadsPageProvider);
    List<DocumentModel> lastUploadedDoc = latestUploadsPageProvider.getCurrentPage();
    assertNotNull(lastUploadedDoc);
    assertEquals(1, lastUploadedDoc.size());
  }
  protected DocumentRef createDocumentModelWithSamplePermissions(String name) {
    DocumentModel root = session.getRootDocument();
    DocumentModel doc = new DocumentModelImpl(root.getPathAsString(), name, "Folder");
    doc = session.createDocument(doc);

    ACP acp = doc.getACP();
    ACL localACL = acp.getOrCreateACL();

    localACL.add(new ACE("joe_reader", READ, true));

    localACL.add(new ACE("joe_contributor", READ, true));
    localACL.add(new ACE("joe_contributor", WRITE_PROPERTIES, true));
    localACL.add(new ACE("joe_contributor", ADD_CHILDREN, true));

    localACL.add(new ACE("joe_localmanager", READ, true));
    localACL.add(new ACE("joe_localmanager", WRITE, true));
    localACL.add(new ACE("joe_localmanager", WRITE_SECURITY, true));

    acp.addACL(localACL);
    doc.setACP(acp, true);

    // add the permission to remove children on the root
    ACP rootACP = root.getACP();
    ACL rootACL = rootACP.getOrCreateACL();
    rootACL.add(new ACE("joe_localmanager", REMOVE_CHILDREN, true));
    rootACP.addACL(rootACL);
    root.setACP(rootACP, true);

    // make it visible for others
    session.save();
    return doc.getRef();
  }
  @Test
  public void testRemoveSingleDocVersion() throws Exception {
    DocumentModel folder = new DocumentModelImpl("/", "folder#1", "Folder");
    folder = session.createDocument(folder);

    DocumentModel file = new DocumentModelImpl(folder.getPathAsString(), "file#1", "File");
    file = session.createDocument(file);

    checkVersions(file);

    file.setPropertyValue("file:filename", "A");
    file.putContextData(
        ScopeType.REQUEST, VersioningDocument.CREATE_SNAPSHOT_ON_SAVE_KEY, Boolean.TRUE);
    file = session.saveDocument(file);

    checkVersions(file, "0.1");

    DocumentModel lastversion = session.getLastDocumentVersion(file.getRef());
    assertNotNull(lastversion);

    assertTrue(lastversion.isVersion());
    session.removeDocument(lastversion.getRef());

    checkVersions(file);
  }
  private String extractQueryFromRequest(final HttpServletRequest request) {
    String query = request.getParameter("query");
    if (query == null) {
      String fullText = request.getParameter("fullText");
      if (fullText == null) {
        throw new IllegalParameterException("Expecting a query or a fullText parameter");
      }
      String orderBy = request.getParameter("orderBy");
      String orderClause = "";
      if (orderBy != null) {
        orderClause = " ORDER BY " + orderBy;
      }
      String path;

      DocumentModel doc = getTarget().getAdapter(DocumentModel.class);
      if (doc.isFolder()) {
        path = doc.getPathAsString();
      } else {
        path = doc.getPath().removeLastSegments(1).toString();
      }
      query =
          "SELECT * FROM Document WHERE (ecm:fulltext = \""
              + fullText
              + "\") AND (ecm:isCheckedInVersion = 0) AND (ecm:path STARTSWITH \""
              + path
              + "\")"
              + orderClause;
    }
    return query;
  }
 protected DocumentModel createNode(DocumentModel route, String name, CoreSession session)
     throws PropertyException {
   DocumentModel node =
       session.createDocumentModel(route.getPathAsString(), name, TYPE_ROUTE_NODE);
   node.setPropertyValue(GraphNode.PROP_NODE_ID, name);
   return session.createDocument(node);
 }
Beispiel #16
0
 /**
  * Obtains a String representation of a Nuxeo property value, where the latter is an opaque Object
  * that may or may not be directly convertible to a string.
  *
  * @param obj an Object containing a property value
  * @param docModel the document model associated with this property.
  * @param propertyPath a path to the property, such as a property name, XPath, etc.
  * @return a String representation of the Nuxeo property value.
  */
 public static String propertyValueAsString(
     Object obj, DocumentModel docModel, String propertyPath) {
   if (obj == null) {
     return "";
   }
   if (String.class.isAssignableFrom(obj.getClass())) {
     return (String) obj;
   } else {
     // Handle cases where a property value returned from the repository
     // can't be directly cast to a String.
     //
     // FIXME: This method provides specific, hard-coded formatting
     // for String representations of property values. We might want
     // to add the ability to specify these formats via configuration.
     // - ADR 2013-04-26
     if (obj instanceof GregorianCalendar) {
       return GregorianCalendarDateTimeUtils.formatAsISO8601Date((GregorianCalendar) obj);
     } else if (obj instanceof Double) {
       return nuxeoDecimalValueToDecimalString(obj);
     } else {
       logger.warn(
           "Could not convert value of property "
               + propertyPath
               + " in document "
               + docModel.getPathAsString()
               + " to a String.");
       logger.warn(
           "This may be due to a new, as-yet-unhandled datatype returned from the repository");
       return "";
     }
   }
 }
Beispiel #17
0
  @GET
  @Path("@sharedElementTreeview")
  @Produces(MediaType.APPLICATION_JSON)
  public Response doSharedElementTreeview(
      @QueryParam("root") String root, @QueryParam("view") String view, @QueryParam("id") String id)
      throws ClientException {

    LabsSite site = (LabsSite) ctx.getProperty("site");
    if (site != null) {
      AbstractDocumentTree siteTree = new SharedElementTree(ctx, site.getDocument());

      String result = "";
      if (root == null || "source".equals(root)) {
        if (id != null && !"0".equals(id)) {
          DocumentModel document = getCoreSession().getDocument(new IdRef(id));
          String entryPoint =
              document.getPathAsString().replaceFirst(site.getDocument().getPathAsString(), "");
          result = siteTree.enter(ctx, entryPoint);
        } else {
          siteTree.enter(ctx, "");
          result = siteTree.getTreeAsJSONArray(ctx);
        }
      } else {
        result = siteTree.enter(ctx, root);
      }
      return Response.ok().entity(result).type(MediaType.APPLICATION_JSON).build();
    }
    return null;
  }
Beispiel #18
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());
  }
Beispiel #19
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());
  }
Beispiel #20
0
 @Test
 public void testCreateExistingBlobWithNonNFCNormalizedFilename() throws Exception {
   // Create doc from NFC normalized filename
   String fileName = "ÜÜÜ ÓÓÓ.rtf";
   String nfcNormalizedFileName = Normalizer.normalize(fileName, Normalizer.Form.NFC);
   Blob blob = Blobs.createBlob("Test content", "text/rtf", null, nfcNormalizedFileName);
   service.createDocumentFromBlob(
       coreSession, blob, workspace.getPathAsString(), true, nfcNormalizedFileName);
   assertNotNull(
       FileManagerUtils.getExistingDocByFileName(
           coreSession, workspace.getPathAsString(), nfcNormalizedFileName));
   // Check existing doc with non NFC (NFD) normalized filename
   String nfdNormalizedFileName = Normalizer.normalize(fileName, Normalizer.Form.NFD);
   assertNotNull(
       FileManagerUtils.getExistingDocByFileName(
           coreSession, workspace.getPathAsString(), nfdNormalizedFileName));
 }
  private void createDocs() throws Exception {
    rootDocument = session.getRootDocument();
    workspace = session.createDocumentModel(rootDocument.getPathAsString(), "ws1", "Workspace");
    workspace.setProperty("dublincore", "title", "test WS");
    workspace = session.createDocument(workspace);

    docToExport = session.createDocumentModel(workspace.getPathAsString(), "file", "File");
    docToExport.setProperty("dublincore", "title", "MyDoc");

    Blob blob = Blobs.createBlob("SomeDummyContent");
    blob.setFilename("dummyBlob.txt");
    docToExport.setProperty("file", "content", blob);

    docToExport = session.createDocument(docToExport);

    session.save();
  }
 @Override
 public PublicationNode wrapToPublicationNode(DocumentModel documentModel) {
   if (!isPublicationNode(documentModel)) {
     throw new NuxeoException(
         "Document " + documentModel.getPathAsString() + " is not a valid publication node.");
   }
   return new CoreFolderPublicationNode(documentModel, getConfigName(), sid, factory);
 }
  protected DocumentModel doCreateDocument() {
    DocumentModel rootDocument = session.getRootDocument();
    DocumentModel model =
        session.createDocumentModel(rootDocument.getPathAsString(), "youps", "File");
    model.setProperty("dublincore", "title", "huum");

    return session.createDocument(model);
  }
  protected DocumentModel doCreateLeafNode(DocumentModel parent, SourceNode node)
      throws IOException {
    if (!shouldImportDocument(node)) {
      return null;
    }
    Stopwatch stopwatch = SimonManager.getStopwatch("org.nuxeo.ecm.platform.importer.create_leaf");
    Split split = stopwatch.start();
    DocumentModel leaf = null;
    try {
      leaf = getFactory().createLeafNode(session, parent, node);
    } catch (IOException e) {
      String errMsg =
          "Unable to create leaf document for "
              + node.getSourcePath()
              + ":"
              + e
              + (e.getCause() != null ? e.getCause() : "");
      fslog(errMsg, true);
      log.error(errMsg);
      // Process leaf node creation error and check if the global
      // import task should continue
      boolean shouldImportTaskContinue =
          getFactory().processLeafNodeCreationError(session, parent, node);
      if (!shouldImportTaskContinue) {
        throw new NuxeoException(e);
      }
    } finally {
      split.stop();
    }
    BlobHolder bh = node.getBlobHolder();
    if (leaf != null && bh != null) {
      Blob blob = bh.getBlob();
      if (blob != null) {
        long fileSize = blob.getLength();
        String fileName = blob.getFilename();
        if (fileSize > 0) {
          long kbSize = fileSize / 1024;
          String parentPath = (parent == null) ? "null" : parent.getPathAsString();
          fslog(
              "Created doc "
                  + leaf.getName()
                  + " at "
                  + parentPath
                  + " with file "
                  + fileName
                  + " of size "
                  + kbSize
                  + "KB",
              true);
        }
        uploadedKO += fileSize;
      }

      // save session if needed
      commit();
    }
    return leaf;
  }
 public List<PublishedDocument> getExistingPublishedDocument(DocumentLocation docLoc) {
   List<PublishedDocument> publishedDocs = new ArrayList<PublishedDocument>();
   DocumentModelList proxies = getCoreSession().getProxies(docLoc.getDocRef(), null);
   for (DocumentModel proxy : proxies) {
     if (proxy.getPathAsString().startsWith(rootPath)) {
       publishedDocs.add(factory.wrapDocumentModel(proxy));
     }
   }
   return publishedDocs;
 }
  @Before
  public void createTestDocs() throws Exception {

    principal = session.getPrincipal();

    // Create and register 2 synchronization roots for Administrator
    syncRoot1 = session.createDocument(session.createDocumentModel("/", "syncRoot1", "Folder"));
    syncRoot2 = session.createDocument(session.createDocumentModel("/", "syncRoot2", "Folder"));
    Principal administrator = session.getPrincipal();
    nuxeoDriveManager.registerSynchronizationRoot(administrator, syncRoot1, session);
    nuxeoDriveManager.registerSynchronizationRoot(administrator, syncRoot2, session);

    // Folder
    folder = session.createDocumentModel(syncRoot1.getPathAsString(), "aFolder", "Folder");
    folder.setPropertyValue("dc:title", "Jack's folder");
    folder = session.createDocument(folder);

    // File
    file = session.createDocumentModel(folder.getPathAsString(), "aFile", "File");
    Blob blob = new StringBlob("Content of Joe's file.");
    blob.setFilename("Joe.odt");
    file.setPropertyValue("file:content", (Serializable) blob);
    file = session.createDocument(file);

    // Note
    note = session.createDocumentModel(folder.getPathAsString(), "aNote", "Note");
    note.setPropertyValue("note:note", "Content of Bob's note.");
    note = session.createDocument(note);

    // Custom doc type with the "file" schema
    custom = session.createDocumentModel(folder.getPathAsString(), "aCustomDoc", "Custom");
    blob = new StringBlob("Content of Bonnie's file.");
    blob.setFilename("Bonnie's file.odt");
    custom.setPropertyValue("file:content", (Serializable) blob);
    custom = session.createDocument(custom);

    // FolderishFile: doc type with the "file" schema and the "Folderish"
    // facet
    folderishFile =
        session.createDocumentModel(folder.getPathAsString(), "aFolderishFile", "FolderishFile");
    folderishFile.setPropertyValue("dc:title", "Sarah's folderish file");
    folderishFile = session.createDocument(folderishFile);

    // Doc not adaptable as a FileSystemItem (not Folderish nor a
    // BlobHolder)
    notAFileSystemItem =
        session.createDocumentModel(
            folder.getPathAsString(), "notAFileSystemItem", "NotSynchronizable");
    notAFileSystemItem = session.createDocument(notAFileSystemItem);

    // Sub folder
    subFolder = session.createDocumentModel(folder.getPathAsString(), "aSubFolder", "Folder");
    subFolder.setPropertyValue("dc:title", "Tony's sub folder");
    subFolder = session.createDocument(subFolder);

    session.save();
  }
  @Override
  public String getPathById(String uuid, CoreSession session) throws ClientException {
    DocumentModel model = session.getDocument(new IdRef(uuid));
    if (model == null) {
      return null;
    }

    String path = model.getPathAsString();
    Backend backend = getBackend(session);
    return backend.getVirtualPath(path);
  }
Beispiel #28
0
 @Test
 public void testCreateBlobWithAmbiguousMimetype() throws Exception {
   File file = getTestFile("test-data/hello.xml");
   Blob blob = Blobs.createBlob(file);
   blob.setMimeType("text/plain");
   DocumentModel doc =
       service.createDocumentFromBlob(
           coreSession, blob, workspace.getPathAsString(), true, "test-data/hello.xml");
   assertNotNull(doc);
   assertEquals("text/plain", blob.getMimeType());
   assertEquals("Note", doc.getType());
 }
Beispiel #29
0
 @Test
 public void testCreateBlobWithCalculatedBlobMimetype() throws Exception {
   File file = getTestFile("test-data/hello.doc");
   Blob blob = Blobs.createBlob(file);
   blob.setFilename("hello.plouf");
   blob.setMimeType("pif/paf");
   DocumentModel doc =
       service.createDocumentFromBlob(
           coreSession, blob, workspace.getPathAsString(), true, "test-data/hello.plouf");
   assertNotNull(doc);
   assertEquals("File", doc.getType());
 }
  /**
   * Retrieves a certain number of blog posts with information about the last <b>BlogPost</b>-s that
   * are made under an <b>BlogSite</b> that is received as parameter.
   */
  @Override
  public Model getModel() throws ModelException {
    BlogPostListModel model = new BlogPostListModel();
    if (WebEngine.getActiveContext() != null) {
      WebContext ctx = WebEngine.getActiveContext();
      CoreSession session = ctx.getCoreSession();
      DocumentModel documentModel = ctx.getTargetObject().getAdapter(DocumentModel.class);

      SimpleDateFormat simpleMonthFormat =
          new SimpleDateFormat("dd MMMM yyyy", WebEngine.getActiveContext().getLocale());
      try {
        DocumentModel blogSite = SiteUtils.getFirstWebSiteParent(session, documentModel);
        DocumentModelList blogPosts =
            SiteQueriesCollection.queryLastModifiedPages(
                session,
                blogSite.getPathAsString(),
                BLOG_POST_DOC_TYPE,
                BLOG_POST_DOC_TYPE.equals(documentModel.getType()) ? noForBlogPost : noForBlogSite);

        for (DocumentModel blogPost : blogPosts) {
          String title = SiteUtils.getString(blogPost, "dc:title");
          String path = SiteUtils.getPagePath(blogSite, blogPost);

          String description = SiteUtils.getString(blogPost, "dc:description");

          String content =
              SiteUtils.getFistNWordsFromString(
                  SiteUtils.getString(blogPost, WEBPAGE_CONTENT), Integer.MAX_VALUE);
          String author = SiteUtils.getString(blogPost, "dc:creator");

          GregorianCalendar creationDate = SiteUtils.getGregorianCalendar(blogPost, "dc:created");

          String day = getWeekDay(creationDate.get(Calendar.DAY_OF_WEEK));
          BlogSiteArchiveDayModel dayModel = getYearModel(model, day);
          if (dayModel == null) {
            dayModel =
                new BlogSiteArchiveDayModel(
                    day, simpleMonthFormat.format(creationDate.getTime()), 0);
            model.addItem(dayModel);
          }
          dayModel.increaseCount();

          BlogPostModel blogPostModel =
              new BlogPostModel(title, path, description, content, author);
          dayModel.addItem(blogPostModel);
        }
      } catch (Exception e) {
        throw new ModelException(e);
      }
    }
    return model;
  }