@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));
    }
  }
  protected boolean useTiling(Blob blob, DocumentModel dm) {
    Long width = Long.valueOf(0);
    Long height = Long.valueOf(0);

    if ("Picture".equals(dm.getType())) {
      try {
        PictureResourceAdapter adapter = dm.getAdapter(PictureResourceAdapter.class);
        String xpath = adapter.getViewXPath(ORIGINAL_JPEG_VIEW_NAME);
        if (xpath == null) {
          xpath = adapter.getViewXPath(ORIGINAL_VIEW_NAME);
          if (xpath == null) {
            xpath = adapter.getFirstViewXPath();
          }
        }

        width = (Long) dm.getPropertyValue(xpath + "width");
        height = (Long) dm.getPropertyValue(xpath + "height");
      } catch (ClientException e) {
        log.error("Failed to get picture dimensions", e);
      }
    } else {
      ImagingService imagingService = Framework.getLocalService(ImagingService.class);
      if (imagingService != null) {
        Map<String, Object> imageMetadata = imagingService.getImageMetadata(blob);
        width = ((Integer) imageMetadata.get(MetadataConstants.META_WIDTH)).longValue();
        height = ((Integer) imageMetadata.get(MetadataConstants.META_HEIGHT)).longValue();
      }
    }

    Integer widthThreshold =
        Integer.valueOf(PictureTilingComponent.getEnvValue("WidthThreshold", "1200"));
    Integer heightThreshold =
        Integer.valueOf(PictureTilingComponent.getEnvValue("HeightThreshold", "1200"));
    return width > widthThreshold || height > heightThreshold;
  }
  @Test
  public void testEndpointConsumptionRelations() throws Exception {
    // Create endpoint consumption
    SoaNodeId endpointConsumptionId = new SoaNodeId(EndpointConsumption.DOCTYPE, "MyConsumption");
    DocumentModel endpointConsumptionModel =
        documentService.create(documentManager, endpointConsumptionId);
    EndpointConsumption endpointConsumption =
        endpointConsumptionModel.getAdapter(EndpointConsumption.class);
    Assert.assertNotNull("EndpointConsumption adapter must be available", endpointConsumption);
    documentManager.save();

    // Manipulate and test it
    Assert.assertNull(
        "EndpointConsumption must not initially consume endpoints",
        endpointConsumption.getConsumedEndpoint());
    SoaNodeId consumedEndpoint = new EndpointId("myenv", "myurl");
    endpointConsumption.setConsumedEndpoint(consumedEndpoint);
    Assert.assertEquals(
        "EndpointConsumption must be set as expected",
        consumedEndpoint,
        endpointConsumption.getConsumedEndpoint());
    DocumentModel foundEndpointModel =
        documentService.findSoaNode(documentManager, consumedEndpoint);
    Assert.assertNotNull("Consumed endpoint must be created", foundEndpointModel);
    endpointConsumption.setConsumedEndpoint(null);
    Assert.assertNull(
        "EndpointConsumption must be removed", endpointConsumption.getConsumedEndpoint());
  }
  @Override
  public PublishedDocument publishDocument(
      DocumentModel doc, PublicationNode targetNode, Map<String, String> params)
      throws ClientException {

    Snapshot snapshot = null;

    if (doc.isFolder()) {
      Snapshotable snapshotable = doc.getAdapter(Snapshotable.class);
      if (snapshotable != null) {
        snapshot = snapshotable.createSnapshot(VersioningOption.MINOR);
      }
    }

    PublishedDocument result = super.publishDocument(doc, targetNode, params);

    if (snapshot != null) {

      final Snapshot tree = snapshot;
      final DocumentModel parent = ((SimpleCorePublishedDocument) result).getProxy();

      UnrestrictedSessionRunner runner =
          new UnrestrictedSessionRunner(doc.getCoreSession()) {
            @Override
            public void run() throws ClientException {
              // force cleanup of the tree !!!
              session.removeChildren(parent.getRef());
              subPublish(session, parent, tree, true);
            }
          };
      runner.runUnrestricted();
    }

    return result;
  }
  protected DocumentModel doCreateADocWithComments() throws Exception {

    DocumentModel domain = getCoreSession().createDocumentModel("Folder");
    domain.setProperty("dublincore", "title", "Domain");
    domain.setPathInfo("/", "domain");
    domain = getCoreSession().createDocument(domain);

    DocumentModel doc = getCoreSession().createDocumentModel("File");

    doc.setProperty("dublincore", "title", "MonTitre");
    doc.setPathInfo("/domain/", "TestFile");

    doc = getCoreSession().createDocument(doc);
    getCoreSession().save();
    AsyncProcessorConfig.setForceJMSUsage(false);

    // Create a first commentary
    CommentableDocument cDoc = doc.getAdapter(CommentableDocument.class);
    DocumentModel comment = getCoreSession().createDocumentModel("Comment");
    comment.setProperty("comment", "text", "This is my comment");
    comment = cDoc.addComment(comment);

    // Create a second commentary
    DocumentModel comment2 = getCoreSession().createDocumentModel("Comment");
    comment2.setProperty("comment", "text", "This is another  comment");
    comment2 = cDoc.addComment(comment);
    return doc;
  }
Beispiel #6
0
  protected BlobHolder getBlobHolderToConvert() {
    Blob blob = getTarget().getAdapter(Blob.class);
    BlobHolder bh = null;
    if (blob == null) {
      DocumentModel doc = getTarget().getAdapter(DocumentModel.class);
      if (doc != null) {
        bh = doc.getAdapter(BlobHolder.class);
        if (bh != null) {
          blob = bh.getBlob();
        }
      }
    }
    if (blob == null) {
      throw new IllegalParameterException("No Blob found");
    }

    if (getTarget().isInstanceOf("blob")) {
      bh = ((BlobObject) getTarget()).getBlobHolder();
    }

    if (bh == null) {
      bh = new SimpleBlobHolder(blob);
    }
    return bh;
  }
  @Test
  public void testServiceImplComplexProps() throws Exception {

    // Create ServiceImpl
    SoaNodeId serviceImplId = new SoaNodeId(ServiceImplementation.DOCTYPE, "MyServiceImpl");
    DocumentModel serviceImplModel = documentService.create(documentManager, serviceImplId);

    String opName = "Yo";
    String params = "Param1:java.lang.int, Param2:my.Class";
    String returnParams = "YoResponse:java.lang.String";
    String opDoc = "This does something";
    String inContentType = "text/xml";
    String outContentType =
        "application/json"; // http://stackoverflow.com/questions/477816/what-is-the-correct-json-content-type

    // Use adapter to manipulate operations
    ServiceImplementation serviceImpl = serviceImplModel.getAdapter(ServiceImplementation.class);
    List<OperationInformation> operations = serviceImpl.getOperations();
    operations.add(
        new OperationInformation(
            opName, params, returnParams, opDoc, inContentType, outContentType));
    serviceImpl.setOperations(operations);
    List<String> tests = new ArrayList<String>();
    tests.add("org.easysoa.TestClass1");
    tests.add("org.easysoa.TestClass2");
    serviceImpl.setTests(tests);

    // Save
    documentManager.saveDocument(serviceImplModel);
    documentManager.save();

    // Fetch document again, check operations update
    serviceImplModel = documentService.findSoaNode(documentManager, serviceImplId);
    serviceImpl = serviceImplModel.getAdapter(ServiceImplementation.class);
    operations = serviceImpl.getOperations();
    Assert.assertEquals(1, operations.size());
    Assert.assertEquals(opName, operations.get(0).getName());
    Assert.assertEquals(params, operations.get(0).getParameters());
    Assert.assertEquals(returnParams, operations.get(0).getReturnParameters());
    Assert.assertEquals(opDoc, operations.get(0).getDocumentation());
    Assert.assertEquals(inContentType, operations.get(0).getInContentType());
    Assert.assertEquals(outContentType, operations.get(0).getOutContentType());
    Assert.assertEquals(opDoc, operations.get(0).getDocumentation());
    Assert.assertEquals(2, serviceImpl.getTests().size());
  }
 private BusinessAdapter getAdapter(String adapterName, DocumentModel doc) {
   ObjectCodecService cs = Framework.getLocalService(ObjectCodecService.class);
   ObjectCodec<?> codec = cs.getCodec(adapterName);
   if (codec != null) {
     return (BusinessAdapter) doc.getAdapter(codec.getJavaType());
   } else {
     throw new WebException(String.format("Unable to find [%s] adapter", adapterName));
   }
 }
 @OperationMethod
 public Blob run(DocumentModel targetDocument) throws Exception {
   TemplateBasedDocument renderable = targetDocument.getAdapter(TemplateBasedDocument.class);
   if (renderable != null) {
     if (store) {
       return renderable.renderAndStoreAsAttachment(templateName, save);
     } else {
       return renderable.renderWithTemplate(templateName);
     }
   } else {
     BlobHolder bh = targetDocument.getAdapter(BlobHolder.class);
     if (bh != null) {
       return bh.getBlob();
     } else {
       return null;
     }
   }
 }
  private void emailEnglishAssertions(String filePath) throws Exception {
    // initialize mailboxes
    getPersonalMailbox("jdoe");

    injectEmail(filePath);
    DocumentRef dayRef = new PathRef(CaseConstants.CASE_ROOT_DOCUMENT_PATH + "/2009/03/17");
    assertTrue(session.exists(dayRef));
    DocumentModelList envelopes = session.getChildren(dayRef, MailConstants.MAIL_ENVELOPE_TYPE);
    assertEquals(1, envelopes.size());

    DocumentModel envelopeDoc = envelopes.get(0);
    Case envelope = envelopeDoc.getAdapter(Case.class);
    List<DocumentModel> linkedDocs = envelope.getDocuments();
    assertEquals(2, linkedDocs.size());
    DocumentModel firstDoc = linkedDocs.get(0);

    String title = (String) firstDoc.getPropertyValue(CaseConstants.TITLE_PROPERTY_NAME);
    assertEquals("[Fwd: RENOUVELLEMENT DE SUPPORT ANNUEL NUXEO]", title);
    Calendar originalReceptionDate =
        (Calendar) firstDoc.getPropertyValue(CaseConstants.DOCUMENT_IMPORT_DATE_PROPERTY_NAME);
    assertEquals(
        emailDateParser.parse("Wed, 14 Jan 2009 15:15:25 +0100").getTime(),
        originalReceptionDate.getTime().getTime());
    Calendar receptionDate =
        (Calendar) firstDoc.getPropertyValue(CaseConstants.DOCUMENT_RECEIVE_DATE_PROPERTY_NAME);
    assertEquals(
        emailDateParser.parse("Tue, 17 Mar 2009 13:39:05 +0100").getTime(),
        receptionDate.getTime().getTime());

    Contacts senders = Contacts.getContactsForDoc(firstDoc, CaseConstants.CONTACTS_SENDERS);
    assertNotNull(senders);
    assertEquals(1, senders.size());
    Contact sender = senders.get(0);
    assertEquals("Sylvie KAPCOM", sender.getName());
    assertEquals("*****@*****.**", sender.getEmail());

    Contacts recipients = Contacts.getContactsForDoc(firstDoc, CaseConstants.CONTACTS_PARTICIPANTS);
    assertNotNull(recipients);
    assertEquals(2, recipients.size());

    assertEquals("*****@*****.**", recipients.get(0).getEmail());

    assertTrue(
        (recipients.get(1).getName() == null) || ("".equals(recipients.get(1).getName().trim())));
    assertEquals("*****@*****.**", recipients.get(1).getEmail());

    // testing content
    DocumentModel secondDoc = linkedDocs.get(1);
    Blob fileBlob = (Blob) secondDoc.getPropertyValue(CaseConstants.FILE_PROPERTY_NAME);

    assertEquals("The file blob filename is", "testpdf.pdf", fileBlob.getFilename());
    assertEquals("the file blob length is", 24016, fileBlob.getLength());

    String fileNamePropertyValue =
        (String) secondDoc.getPropertyValue(CaseConstants.FILENAME_PROPERTY_NAME);
    assertEquals("The filename property value is", "testpdf.pdf", fileNamePropertyValue);
  }
  /**
   * Check that a copied document does not belong to the collections of the original documents.
   *
   * @since 7.3
   */
  @Test
  public void testCopiedCollectionMember() {
    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);
    testFile = session.getDocument(testFile.getRef());
    DocumentModel copiedTestFile =
        session.copy(testFile.getRef(), testFile.getParentRef(), TEST_FILE_NAME + "_BIS");

    assertFalse(collectionManager.isCollected(copiedTestFile));

    // Let's add to another collection and see it still does not belong to the original one.
    collectionManager.addToNewCollection(
        COLLECTION_NAME + "_BIS", COLLECTION_DESCRIPTION + "_BIS", copiedTestFile, session);

    copiedTestFile = session.getDocument(copiedTestFile.getRef());

    final String collectionPath = COLLECTION_FOLDER_PATH + "/" + COLLECTION_NAME;
    DocumentRef collectionPathRef = new PathRef(collectionPath);
    assertTrue(session.exists(collectionPathRef));
    final String collectionPathBis = COLLECTION_FOLDER_PATH + "/" + COLLECTION_NAME + "_BIS";
    DocumentRef collectionPathRefBis = new PathRef(collectionPathBis);
    assertTrue(session.exists(collectionPathRefBis));

    final DocumentModel collection = session.getDocument(collectionPathRef);
    final DocumentModel collectionBis = session.getDocument(collectionPathRefBis);

    assertFalse(
        copiedTestFile
            .getAdapter(CollectionMember.class)
            .getCollectionIds()
            .contains(collection.getId()));
    assertTrue(
        copiedTestFile
            .getAdapter(CollectionMember.class)
            .getCollectionIds()
            .contains(collectionBis.getId()));
  }
Beispiel #12
0
  public boolean isAnnotationsEnabled(DocumentModel doc) {
    BlobHolder blobHolder = doc.getAdapter(BlobHolder.class);
    Blob blob = blobHolder.getBlob();
    if (blob == null || blob.getMimeType() == null) {
      return false;
    }

    return Framework.isBooleanPropertyTrue(TEXT_ANNOTATIONS_KEY)
        || blob.getMimeType().startsWith("image");
  }
 protected CommentableDocument getCommentableDoc() {
   if (commentableDoc == null) {
     DocumentModel currentDocument = navigationContext.getCurrentDocument();
     if (currentDocument == null) {
       // what can I do?
       return null;
     }
     commentableDoc = currentDocument.getAdapter(CommentableDocument.class);
   }
   return commentableDoc;
 }
 protected DocumentRoute validate(DocumentModel routeDoc, CoreSession session)
     throws DocumentRouteNotLockedException {
   DocumentRoute route = routeDoc.getAdapter(DocumentRoute.class);
   // draft -> validated
   if (!route.isValidated()) {
     route =
         Framework.getLocalService(DocumentRoutingService.class)
             .validateRouteModel(route, session);
   }
   return route;
 }
 /**
  * Converts a {@link DocumentModelList} to a list of {@link Task}s.
  *
  * @param detach if {@code true}, detach each document before converting it to a {@code Task}.
  */
 public static List<Task> wrapDocModelInTask(DocumentModelList taskDocuments, boolean detach)
     throws ClientException {
   List<Task> tasks = new ArrayList<Task>();
   for (DocumentModel doc : taskDocuments) {
     if (detach) {
       doc.detach(true);
     }
     tasks.add(doc.getAdapter(Task.class));
   }
   return tasks;
 }
 protected List<String> getAllowedTypes(DocumentModel doc) {
   UITypesConfiguration uiTypesConfiguration = doc.getAdapter(UITypesConfiguration.class);
   if (uiTypesConfiguration == null) {
     return Collections.emptyList();
   }
   List<String> allowedTypes = new ArrayList<String>(uiTypesConfiguration.getAllowedTypes());
   if (allowedTypes.isEmpty()) {
     allowedTypes = computeAllowedTypes(doc);
   }
   return allowedTypes;
 }
  @Test
  public void testAddOneDocToNewCollectionAndRemove() throws Exception {
    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);

    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());

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

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

    testFile = session.getDocument(testFile.getRef());

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

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

    collectionManager.removeFromCollection(newlyCreatedCollection, testFile, session);

    assertFalse(collectionAdapter.getCollectedDocumentIds().contains(testFile.getId()));
    assertFalse(collectionMemberAdapter.getCollectionIds().contains(newlyCreatedCollectionId));
  }
 /**
  * update isTop to default value : false
  *
  * @param session
  */
 public static void updateIsTopOnLabsnews(CoreSession session) {
   try {
     DocumentModelList children = session.query("SELECT * FROM LabsNews");
     for (DocumentModel labsnews : children) {
       labsnews.getAdapter(LabsNews.class).setTop(false);
       session.saveDocument(labsnews);
     }
     session.save();
   } catch (ClientException e) {
     LOG.error("updateIsTopOnLabsnews : ", e);
   }
 }
 public void checkLatin1(DocumentModel doc, String name, String mtype)
     throws IOException, ClientException, MimetypeNotFoundException, MimetypeDetectionException {
   File file = new File(getClass().getResource("/" + name).getPath());
   Blob blob = new FileBlob(file);
   blob.setMimeType(mtype);
   doc.getAdapter(BlobHolder.class).setBlob(blob);
   HtmlPreviewAdapter adapter = doc.getAdapter(HtmlPreviewAdapter.class);
   Blob htmlBlob = adapter.getFilePreviewBlobs().get(0);
   String htmlContent = htmlBlob.getString().toLowerCase();
   Matcher matcher = charsetPattern.matcher(htmlContent);
   Assert.assertThat(matcher.find(), Matchers.is(true));
   String charset = matcher.group();
   if ("windows-1252".equals(charset)) {
     Assert.assertThat(
         htmlContent,
         Matchers.containsString("test de pr&Atilde;&copy;visualisation avant rattachement"));
   } else {
     Assert.assertThat(
         htmlContent, Matchers.containsString("test de prévisualisation avant rattachement"));
   }
 }
Beispiel #20
0
  public String getViewFor(Action mainTabAction) {
    if (!mainTabAction.getId().equals(WebActions.DOCUMENTS_MAIN_TAB_ID)) {
      return mainTabAction.getLink();
    }

    DocumentModel doc =
        getDocumentFor(mainTabAction.getId(), navigationContext.getCurrentDocument());
    if (doc != null) {
      TypeInfo typeInfo = doc.getAdapter(TypeInfo.class);
      return typeInfo.getDefaultView();
    }
    return DEFAULT_VIEW;
  }
  @Test
  public void testDocumentAdapters() throws ClientException {

    // Create a deliverable
    DocumentModel deliverableModel =
        documentService.create(
            documentManager,
            new SoaNodeId(Deliverable.DOCTYPE, "MyDeliverable"),
            DocumentModelHelper.getWorkspacesPath(documentManager, defaultSubprojectId));

    // Use its adapter
    Deliverable deliverable = deliverableModel.getAdapter(Deliverable.class);
    Assert.assertNotNull("Document model must be adapted as a deliverable", deliverable);
  }
 /** @deprecated this information is now held by content views */
 @Deprecated
 public List<String> getAvailableLayoutsForDocument(DocumentModel doc) {
   if (doc == null) {
     return Collections.emptyList();
   }
   TypeInfo typeInfo = doc.getAdapter(TypeInfo.class);
   String[] layoutNames = typeInfo.getLayouts(BuiltinModes.LISTING, null);
   List<String> res = new ArrayList<String>();
   if (layoutNames != null && layoutNames.length > 0) {
     res.addAll(Arrays.asList(layoutNames));
   } else {
     res.add(DEFAULT_LISTING_LAYOUT);
   }
   return res;
 }
 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);
 }
 /**
  * update the setter of comments'size on th line of pageList
  *
  * @param session
  */
 public static void updateAllCommentsOnLinesOfPageList(CoreSession session) {
   try {
     DocumentModelList children = session.query("SELECT * FROM PageListLine");
     for (DocumentModel lineDoc : children) {
       lineDoc
           .getAdapter(PageListLine.class)
           .setNbComments(
               Tools.getAdapter(CommentableDocument.class, lineDoc, null).getComments().size());
       session.saveDocument(lineDoc);
     }
     session.save();
   } catch (ClientException e) {
     LOG.error("updateNbCommentsListLine : ", e);
   }
 }
Beispiel #25
0
 public AnnotatedResult(DocumentModel doc, UriInfo info, String baseURL) {
   this.doc = doc;
   this.uriInfo = info;
   this.baseURL = baseURL;
   this.backofficeURL = URLHelper.documentUrl(doc, baseURL);
   this.translation = new SamarTranslationAdapter(doc);
   if (doc.getType().equals("Video")) {
     videoDocument = doc.getAdapter(VideoDocument.class);
     webmTranscodedVideo = videoDocument.getTranscodedVideo("WebM 480p");
     mp4TranscodedVideo = videoDocument.getTranscodedVideo("MP4 480p");
   } else {
     videoDocument = null;
     webmTranscodedVideo = null;
     mp4TranscodedVideo = null;
   }
 }
 @OperationMethod
 public Blob run(DocumentModel doc) throws OperationException {
   if (!(ctx.getPrincipal() instanceof NuxeoPrincipal)
       || !((NuxeoPrincipal) ctx.getPrincipal()).isAdministrator()) {
     throw new OperationException("Not allowed. You must be administrator to use this operation");
   }
   DocumentModel user = userManager.getUserModel(username);
   Blob originalBlob = doc.getAdapter(BlobHolder.class).getBlob();
   boolean originalIsPdf = MIME_TYPE_PDF.equals(originalBlob.getMimeType());
   // decide if we want PDF/A
   boolean pdfa = SignatureHelper.getPDFA();
   // decide disposition
   SigningDisposition disposition = SignatureHelper.getDisposition(originalIsPdf);
   // decide archive filename
   String filename = originalBlob.getFilename();
   String archiveFilename = SignatureHelper.getArchiveFilename(filename);
   return signatureService.signDocument(
       doc, user, password, reason, pdfa, disposition, archiveFilename);
 }
  @POST
  @Path("{adapterName}/{docName}")
  public Object doPutAdapter(
      @PathParam("adapterName") String adapterName,
      @PathParam("docName") String docName,
      BusinessAdapter input)
      throws Exception {
    DocumentModel document = input.getDocument();

    DocumentObject dobj = (DocumentObject) getTarget();
    DocumentModel parentDoc = dobj.getDocument();

    document.setPathInfo(parentDoc.getPathAsString(), docName);
    CoreSession session = ctx.getCoreSession();
    document = session.createDocument(document);
    session.save();
    BusinessAdapter adapter = document.getAdapter(input.getClass());
    return new DefaultJsonAdapter(adapter);
  }
 protected DocumentRoute instantiateAndRun(CoreSession session, Map<String, Serializable> map) {
   DocumentRoutingService routing = Framework.getLocalService(DocumentRoutingService.class);
   // route model
   DocumentRoute route = routeDoc.getAdapter(DocumentRoute.class);
   // draft -> validated
   if (!route.isValidated()) {
     route = routing.validateRouteModel(route, session);
   }
   session.save();
   // create instance and start
   String id =
       routing.createNewInstance(
           route.getDocument().getName(),
           Collections.singletonList(doc.getId()),
           map,
           session,
           true);
   return session.getDocument(new IdRef(id)).getAdapter(DocumentRoute.class);
 }
  @Test
  public void testReadOperations() throws Exception {

    // ------------------------------------------------------
    // Check #getTopLevelFolder
    // ------------------------------------------------------
    List<FileSystemItem> topLevelChildren =
        fileSystemItemManagerService.getTopLevelFolder(principal).getChildren();
    assertNotNull(topLevelChildren);
    assertEquals(2, topLevelChildren.size());

    FileSystemItem childFsItem = topLevelChildren.get(0);
    assertTrue(childFsItem instanceof DefaultSyncRootFolderItem);
    assertEquals("defaultSyncRootFolderItemFactory#test#" + syncRoot1.getId(), childFsItem.getId());
    assertTrue(childFsItem.getParentId().endsWith("DefaultTopLevelFolderItemFactory#"));
    assertEquals("syncRoot1", childFsItem.getName());

    childFsItem = topLevelChildren.get(1);
    assertTrue(childFsItem instanceof DefaultSyncRootFolderItem);
    assertEquals("defaultSyncRootFolderItemFactory#test#" + syncRoot2.getId(), childFsItem.getId());
    assertTrue(childFsItem.getParentId().endsWith("DefaultTopLevelFolderItemFactory#"));
    assertEquals("syncRoot2", childFsItem.getName());

    // ------------------------------------------------------
    // Check #exists
    // ------------------------------------------------------
    // Non existent doc id
    assertFalse(
        fileSystemItemManagerService.exists(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + "nonExistentId", principal));
    // File
    assertTrue(
        fileSystemItemManagerService.exists(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(), principal));
    // Not adaptable as a FileSystemItem
    assertFalse(
        fileSystemItemManagerService.exists(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + notAFileSystemItem.getId(), principal));
    // Deleted
    custom.followTransition("delete");
    assertFalse(
        fileSystemItemManagerService.exists(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + custom.getId(), principal));

    // ------------------------------------------------------------
    // Check #getFileSystemItemById(String id, Principal principal)
    // ------------------------------------------------------------
    // Folder
    FileSystemItem fsItem =
        fileSystemItemManagerService.getFileSystemItemById(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), principal);
    assertNotNull(fsItem);
    assertTrue(fsItem instanceof FolderItem);
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), fsItem.getId());
    String expectedSyncRoot1Id = DEFAULT_SYNC_ROOT_ITEM_ID_PREFIX + syncRoot1.getId();
    assertEquals(expectedSyncRoot1Id, fsItem.getParentId());
    assertEquals("Jack's folder", fsItem.getName());
    assertTrue(fsItem.isFolder());
    assertTrue(fsItem.getCanRename());
    assertTrue(fsItem.getCanDelete());
    assertTrue(((FolderItem) fsItem).getCanCreateChild());
    List<FileSystemItem> children = ((FolderItem) fsItem).getChildren();
    assertNotNull(children);
    assertEquals(4, children.size());

    // File
    fsItem =
        fileSystemItemManagerService.getFileSystemItemById(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(), principal);
    assertNotNull(fsItem);
    assertTrue(fsItem instanceof FileItem);
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(), fsItem.getId());
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), fsItem.getParentId());
    assertEquals("Joe.odt", fsItem.getName());
    assertFalse(fsItem.isFolder());
    assertTrue(fsItem.getCanRename());
    assertTrue(fsItem.getCanDelete());
    FileItem fileFsItem = (FileItem) fsItem;
    assertTrue(fileFsItem.getCanUpdate());
    assertEquals(
        "nxfile/test/" + file.getId() + "/blobholder:0/Joe.odt", fileFsItem.getDownloadURL());
    assertEquals("MD5", fileFsItem.getDigestAlgorithm());
    assertEquals(file.getAdapter(BlobHolder.class).getBlob().getDigest(), fileFsItem.getDigest());
    Blob fileItemBlob = fileFsItem.getBlob();
    assertEquals("Joe.odt", fileItemBlob.getFilename());
    assertEquals("Content of Joe's file.", fileItemBlob.getString());

    // FolderishFile
    fsItem =
        fileSystemItemManagerService.getFileSystemItemById(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folderishFile.getId(), principal);
    assertNotNull(fsItem);
    assertTrue(fsItem instanceof FolderItem);
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folderishFile.getId(), fsItem.getId());
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), fsItem.getParentId());
    assertEquals("Sarah's folderish file", fsItem.getName());
    assertTrue(fsItem.isFolder());
    assertTrue(fsItem.getCanRename());
    assertTrue(fsItem.getCanDelete());
    assertTrue(((FolderItem) fsItem).getCanCreateChild());
    assertTrue(((FolderItem) fsItem).getChildren().isEmpty());

    // Not adaptable as a FileSystemItem
    fsItem =
        fileSystemItemManagerService.getFileSystemItemById(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + notAFileSystemItem.getId(), principal);
    assertNull(fsItem);

    // Deleted
    assertNull(
        fileSystemItemManagerService.getFileSystemItemById(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + custom.getId(), principal));

    // Sub folder
    fsItem =
        fileSystemItemManagerService.getFileSystemItemById(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + subFolder.getId(), principal);
    assertNotNull(fsItem);
    assertTrue(fsItem instanceof FolderItem);
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + subFolder.getId(), fsItem.getId());
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), fsItem.getParentId());
    assertEquals("Tony's sub folder", fsItem.getName());
    assertTrue(fsItem.isFolder());
    assertTrue(fsItem.getCanRename());
    assertTrue(fsItem.getCanDelete());
    assertTrue(((FolderItem) fsItem).getCanCreateChild());
    assertTrue(((FolderItem) fsItem).getChildren().isEmpty());

    // -------------------------------------------------------------------
    // Check #getFileSystemItemById(String id, String parentId, Principal
    // principal)
    // -------------------------------------------------------------------
    fsItem =
        fileSystemItemManagerService.getFileSystemItemById(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(),
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(),
            principal);
    assertTrue(fsItem instanceof FileItem);
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(), fsItem.getId());
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), fsItem.getParentId());

    // ------------------------------------------------------
    // Check #getChildren
    // ------------------------------------------------------
    // Need to flush VCS cache for the session used in DocumentBackedFolderItem#getChildren() to be
    // aware of changes
    // in the current session
    session.save();
    children =
        fileSystemItemManagerService.getChildren(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), principal);
    assertNotNull(children);

    assertEquals(4, children.size());
    // Ordered
    checkChildren(
        children,
        folder.getId(),
        file.getId(),
        note.getId(),
        folderishFile.getId(),
        subFolder.getId(),
        true);

    children =
        fileSystemItemManagerService.getChildren(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + subFolder.getId(), principal);
    assertTrue(children.isEmpty());

    // ------------------------------------------------------
    // Check #scrollDescendants
    // ------------------------------------------------------
    // Need to flush VCS cache for the session used in DocumentBackedFolderItem#scrollDescendants to
    // be aware of
    // changes in the current session
    session.save();
    FolderItem folderItem =
        (FolderItem)
            fileSystemItemManagerService.getFileSystemItemById(
                DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), principal);
    assertTrue(folderItem.getCanScrollDescendants());

    // Scroll through all descendants in one breath
    ScrollFileSystemItemList folderDescendants =
        fileSystemItemManagerService.scrollDescendants(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), principal, null, 10, 1000);
    assertNotNull(folderDescendants);
    assertNotNull(folderDescendants.getScrollId());
    assertEquals(4, folderDescendants.size());
    // Order is not determined
    checkChildren(
        folderDescendants,
        folder.getId(),
        file.getId(),
        note.getId(),
        folderishFile.getId(),
        subFolder.getId(),
        false);

    // Scroll through descendants in several steps
    folderDescendants.clear();
    ScrollFileSystemItemList descendantsBatch;
    int batchSize = 2;
    String scrollId = null;
    while (!(descendantsBatch = folderItem.scrollDescendants(scrollId, batchSize, 1000))
        .isEmpty()) {
      assertTrue(descendantsBatch.size() > 0);
      scrollId = descendantsBatch.getScrollId();
      folderDescendants.addAll(descendantsBatch);
    }
    assertEquals(4, folderDescendants.size());
    // Order is not determined
    checkChildren(
        folderDescendants,
        folder.getId(),
        file.getId(),
        note.getId(),
        folderishFile.getId(),
        subFolder.getId(),
        false);

    folderDescendants =
        fileSystemItemManagerService.scrollDescendants(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + subFolder.getId(), principal, null, 10, 1000);
    assertTrue(folderDescendants.isEmpty());

    // ------------------------------------------------------
    // Check #canMove
    // ------------------------------------------------------
    // Not allowed to move a file system item to a non FolderItem
    String srcFsItemId = DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + note.getId();
    String destFsItemId = DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId();
    assertFalse(fileSystemItemManagerService.canMove(srcFsItemId, destFsItemId, principal));

    // Not allowed to move a file system item if no REMOVE permission on the
    // source backing doc
    Principal joePrincipal = new NuxeoPrincipalImpl("joe");
    DocumentModel rootDoc = session.getRootDocument();
    setPermission(rootDoc, "joe", SecurityConstants.READ, true);
    nuxeoDriveManager.registerSynchronizationRoot(joePrincipal, syncRoot1, session);

    // Under Oracle, the READ ACL optims are not visible from the joe
    // session while the transaction has not been committed.
    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();

    destFsItemId = DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + subFolder.getId();
    assertFalse(fileSystemItemManagerService.canMove(srcFsItemId, destFsItemId, joePrincipal));

    // Not allowed to move a file system item if no ADD_CHILDREN permission
    // on the destination backing doc
    setPermission(folder, "joe", SecurityConstants.WRITE, true);
    setPermission(subFolder, "joe", SecurityConstants.READ, true);
    setPermission(subFolder, SecurityConstants.ADMINISTRATOR, SecurityConstants.EVERYTHING, true);
    setPermission(subFolder, SecurityConstants.EVERYONE, SecurityConstants.EVERYTHING, false);
    assertFalse(fileSystemItemManagerService.canMove(srcFsItemId, destFsItemId, joePrincipal));

    // OK: REMOVE permission on the source backing doc + REMOVE_CHILDREN
    // permission on its parent + ADD_CHILDREN permission on the destination
    // backing doc
    resetPermissions(subFolder, SecurityConstants.EVERYONE);
    resetPermissions(subFolder, "joe");
    setPermission(subFolder, "joe", SecurityConstants.WRITE, true);
    assertTrue(fileSystemItemManagerService.canMove(srcFsItemId, destFsItemId, joePrincipal));

    // Reset permissions
    resetPermissions(rootDoc, "joe");
    resetPermissions(folder, "joe");
    resetPermissions(subFolder, "joe");
  }
  /**
   * copy of the previous test but with a mail forwarded using gmail
   *
   * @throws Exception
   */
  @Test
  public void testParseMailGmail() throws Exception {
    // initialize mailboxes
    Mailbox forwarderMailbox = getPersonalMailbox(nulrich);
    Mailbox origSenderMailbox = getPersonalMailbox(ldoguin);

    String filePath = "data/test_mail_gmail.eml";
    injectEmail(filePath);

    DocumentRef dayRef = new PathRef(CaseConstants.CASE_ROOT_DOCUMENT_PATH + "/2010/12/08");
    assertTrue(session.exists(dayRef));
    DocumentModelList envelopes = session.getChildren(dayRef, MailConstants.MAIL_ENVELOPE_TYPE);
    assertEquals(1, envelopes.size());

    DocumentModel envelopeDoc = envelopes.get(0);
    Case envelope = envelopeDoc.getAdapter(Case.class);
    List<DocumentModel> linkedDocs = envelope.getDocuments();
    DocumentModel firstDoc = linkedDocs.get(0);
    // initial message reception
    Calendar receptionDate =
        (Calendar) firstDoc.getPropertyValue(CaseConstants.DOCUMENT_RECEIVE_DATE_PROPERTY_NAME);
    assertEquals(
        emailDateParser.parse("Wed, 8 Dec 2010 18:25:20 +0100").getTime(),
        receptionDate.getTime().getTime());
    // date of the initial message
    Calendar importDate =
        (Calendar) firstDoc.getPropertyValue(CaseConstants.DOCUMENT_IMPORT_DATE_PROPERTY_NAME);
    assertEquals(
        new SimpleDateFormat("yyyy/M/d").parse("2010/12/8").getTime(),
        importDate.getTime().getTime());
    String reference =
        (String) firstDoc.getPropertyValue(CaseConstants.DOCUMENT_REFERENCE_PROPERTY_NAME);
    assertEquals("<[email protected]>", reference);
    String origin = (String) firstDoc.getPropertyValue(CaseConstants.DOCUMENT_ORIGIN_PROPERTY_NAME);
    assertEquals("mail", origin);
    String object = (String) firstDoc.getPropertyValue(CaseConstants.TITLE_PROPERTY_NAME);
    assertEquals("Fwd: correspondence gmail en test sample", object);

    Contacts senders = Contacts.getContactsForDoc(firstDoc, CaseConstants.CONTACTS_SENDERS);
    assertNotNull(senders);
    assertEquals(1, senders.size());
    Contact sender = senders.get(0);
    assertEquals("laurent O'doguin (nuxeo/reponseD)", sender.getName());
    assertEquals("*****@*****.**", sender.getEmail());
    assertEquals("user-ldoguin", sender.getMailboxIdd());

    Contacts recipients = Contacts.getContactsForDoc(firstDoc, CaseConstants.CONTACTS_PARTICIPANTS);
    assertNotNull(recipients);
    assertEquals(1, recipients.size());
    Contact recipient = recipients.get(0);
    assertEquals("nicolas ulrich (nuxeo/starship)", recipient.getName());
    assertEquals("*****@*****.**", recipient.getEmail());
    assertEquals("user-nulrich", recipient.getMailboxIdd());

    List<CaseLink> forwarderReceivedPosts =
        distributionService.getReceivedCaseLinks(session, forwarderMailbox, 0, 0);
    assertNotNull(forwarderReceivedPosts);
    assertEquals(1, forwarderReceivedPosts.size());

    List<CaseLink> forwarderSentPosts =
        distributionService.getSentCaseLinks(session, forwarderMailbox, 0, 0);
    assertNotNull(forwarderSentPosts);
    assertEquals(0, forwarderSentPosts.size());

    // original sender does not have any message, even if he has a
    // mailbox...
    List<CaseLink> origSenderReceivedPosts =
        distributionService.getReceivedCaseLinks(session, origSenderMailbox, 0, 0);
    assertNotNull(origSenderReceivedPosts);
    assertEquals(0, origSenderReceivedPosts.size());

    List<CaseLink> origSenderSentPosts =
        distributionService.getSentCaseLinks(session, origSenderMailbox, 0, 0);
    assertNotNull(origSenderSentPosts);
    assertEquals(0, origSenderSentPosts.size());
  }