예제 #1
0
  @Test
  public void testTilingSpead() throws Exception {
    PictureTilingService pts = Framework.getLocalService(PictureTilingService.class);
    assertNotNull(pts);

    File file = FileUtils.getResourceFileFromContext("test.jpg");
    Blob image = Blobs.createBlob(file);

    GimpExecutor.setUseQuickExec(false);
    image.setFilename("slow.jpg");
    PictureTiles tiles = pts.getTilesFromBlob(image, 255, 255, 20, 0, 0, false);
    assertNotNull(tiles);
    assertFalse(tiles.getZoomfactor() == 0);
    // System.out.println("ExecTime="
    // + tiles.getInfo().get("JavaProcessExecTime"));

    GimpExecutor.setUseQuickExec(true);
    image.setFilename("quick.jpg");
    PictureTiles tiles2 = pts.getTilesFromBlob(image, 255, 255, 20, 0, 0, false);
    assertNotNull(tiles2);
    assertFalse(tiles2.getZoomfactor() == 0);
    // System.out.println("ExecTime="
    // + tiles2.getInfo().get("JavaProcessExecTime"));

    GimpExecutor.setUseQuickExec(false);
  }
  @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();
  }
  protected Blob resolveBlob(Element el, AttributeConfigDescriptor conf) {
    @SuppressWarnings("unchecked")
    Map<String, Object> propValues = (Map<String, Object>) resolveComplex(el, conf);

    if (propValues.containsKey("content")) {
      try {
        Blob blob = null;
        String content = (String) propValues.get("content");
        if (content != null && workingDirectory != null) {
          File file = new File(workingDirectory, content.trim());
          if (file.exists()) {
            blob = Blobs.createBlob(file);
          }
        }
        if (blob == null) {
          blob = Blobs.createBlob((String) propValues.get("content"));
        }
        if (propValues.containsKey("mimetype")) {
          blob.setMimeType((String) propValues.get("mimetype"));
        }
        if (propValues.containsKey("filename")) {
          blob.setFilename((String) propValues.get("filename"));
        }
        return blob;
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
    return null;
  }
예제 #4
0
 protected Blob convert(Blob blob) throws IOException {
   String mimetype = blob.getMimeType();
   if (mimetype == null || !mimetype.startsWith("text/")) {
     return blob;
   }
   String encoding = blob.getEncoding();
   if (encoding != null && "UTF-8".equals(encoding)) {
     return blob;
   }
   InputStream in = new BufferedInputStream(blob.getStream());
   String filename = blob.getFilename();
   if (encoding == null || encoding.length() == 0) {
     encoding = detectEncoding(in);
   }
   Blob newBlob;
   if ("UTF-8".equals(encoding)) {
     newBlob = new InputStreamBlob(in);
   } else {
     String content = IOUtils.toString(in, encoding);
     newBlob = new StringBlob(content);
   }
   newBlob.setMimeType(mimetype);
   newBlob.setEncoding("UTF-8");
   newBlob.setFilename(filename);
   return newBlob;
 }
예제 #5
0
 /**
  * Creates a serializable blob from a stream, with filename and mimetype detection.
  *
  * <p>Creates an in-memory blob if data is under 64K, otherwise constructs a serializable FileBlob
  * which stores data in a temporary file on the hard disk.
  *
  * @param file the input stream holding data
  * @param filename the file name. Will be set on the blob and will used for mimetype detection.
  * @param mimeType the detected mimetype at upload. Can be null. Will be verified by the mimetype
  *     service.
  */
 public static Blob createSerializableBlob(InputStream file, String filename, String mimeType) {
   Blob blob = null;
   try {
     // persisting the blob makes it possible to read the binary content
     // of the request stream several times (mimetype sniffing, digest
     // computation, core binary storage)
     blob = StreamingBlob.createFromStream(file, mimeType).persist();
     // filename
     if (filename != null) {
       filename = getCleanFileName(filename);
     }
     blob.setFilename(filename);
     // mimetype detection
     MimetypeRegistry mimeService = Framework.getService(MimetypeRegistry.class);
     String detectedMimeType =
         mimeService.getMimetypeFromFilenameAndBlobWithDefault(filename, blob, null);
     if (detectedMimeType == null) {
       if (mimeType != null) {
         detectedMimeType = mimeType;
       } else {
         // default
         detectedMimeType = "application/octet-stream";
       }
     }
     blob.setMimeType(detectedMimeType);
   } catch (MimetypeDetectionException e) {
     log.error(String.format("could not fetch mimetype for file %s", filename), e);
   } catch (IOException e) {
     log.error(e);
   } catch (Exception e) {
     log.error(e);
   }
   return blob;
 }
예제 #6
0
  @Test
  public void testLazy() throws Exception {
    PictureTilingService pts = Framework.getLocalService(PictureTilingService.class);
    assertNotNull(pts);

    String wdirPath = System.getProperty("java.io.tmpdir") + "/testMe";
    new File(wdirPath).mkdir();
    pts.setWorkingDirPath(wdirPath);

    File file = FileUtils.getResourceFileFromContext("test.jpg");
    Blob image = Blobs.createBlob(file);

    image.setFilename("test.jpg");
    PictureTiles tiles = pts.getTilesFromBlob(image, 255, 255, 20, 0, 0, false);

    assertNotNull(tiles);

    Blob tile00 = tiles.getTile(0, 0);
    assertNotNull(tile00);

    Blob tile01 = tiles.getTile(0, 1);
    assertNotNull(tile01);

    Blob tile02 = tiles.getTile(0, 2);
    assertNotNull(tile02);
  }
 private Blob getTestBlob() {
   String filename = "pomodoro_cheat_sheet.pdf";
   File testFile = new File(FileUtils.getResourcePathFromContext("testFiles/" + filename));
   Blob blob = new FileBlob(testFile);
   blob.setFilename(filename);
   blob.setMimeType("application/pdf");
   return blob;
 }
예제 #8
0
 protected String checkFileBlob(String filename, boolean usefilename, String targetExt)
     throws Exception {
   File file = FileUtils.getResourceFileFromContext(filename);
   Blob blob = Blobs.createBlob(file);
   if (usefilename) {
     blob.setFilename(filename);
   }
   return check(blob, targetExt);
 }
예제 #9
0
 protected String checkStringBlob(String filename, boolean usefilename, String targetExt)
     throws Exception {
   File file = FileUtils.getResourceFileFromContext(filename);
   byte[] bytes = org.apache.commons.io.FileUtils.readFileToByteArray(file);
   Blob blob = Blobs.createBlob(bytes);
   if (usefilename) {
     blob.setFilename(filename);
   }
   return check(blob, targetExt);
 }
예제 #10
0
  public List<Blob> getPreview(Blob blob, DocumentModel dm) throws PreviewException {
    if (useTiling(blob, dm)) {
      List<Blob> blobResults = new ArrayList<Blob>();
      String htmlFile = getString().replace("$repoId$", dm.getRepositoryName());
      htmlFile = htmlFile.replace("$docId$", dm.getId());
      htmlFile = htmlFile.replace("$tileWidth$", "" + 200);
      htmlFile = htmlFile.replace("$tileHeight$", "" + 200);
      htmlFile = htmlFile.replace("$maxTiles$", "" + 2);
      Blob mainBlob = new StringBlob(htmlFile);
      mainBlob.setFilename("index.html");
      mainBlob.setMimeType("text/html");
      blob.setFilename("image");

      blobResults.add(mainBlob);
      blobResults.add(blob);

      return blobResults;
    }

    return new ImagePreviewer().getPreview(blob, dm);
  }
예제 #11
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());
 }
예제 #12
0
 @Test
 public void testCreateBlobWithBlobMimetypeFallback() throws Exception {
   // don't use a binary file, we store it in a text field and PostgreSQL doesn't accept 0x00 bytes
   File file = getTestFile("test-data/hello.xml");
   Blob blob = Blobs.createBlob(file);
   blob.setFilename("hello.plouf");
   blob.setMimeType("text/plain");
   DocumentModel doc =
       service.createDocumentFromBlob(
           coreSession, blob, workspace.getPathAsString(), true, "test-data/hello.plouf");
   assertNotNull(doc);
   assertEquals("text/plain", blob.getMimeType());
   assertEquals("Note", doc.getType());
 }
예제 #13
0
  @Test
  public void test() throws Exception {
    DocumentModel doc = new DocumentModelImpl("/", "doc", "ComplexDoc");

    List<Map<String, Object>> vignettes = new ArrayList<Map<String, Object>>();
    Map<String, Object> vignette = new HashMap<String, Object>();
    vignette.put("width", Long.valueOf(0));
    vignette.put("height", Long.valueOf(0));
    Blob blob1 = Blobs.createBlob("foo1 bar1");
    blob1.setFilename("file1.txt");
    vignette.put("content", blob1);
    vignettes.add(vignette);

    vignette = new HashMap<String, Object>();
    vignette.put("width", Long.valueOf(0));
    vignette.put("height", Long.valueOf(0));
    Blob blob2 = Blobs.createBlob("foo2 bar2");
    blob2.setFilename("file2.txt");
    vignette.put("content", blob2);
    vignettes.add(vignette);

    Map<String, Object> attachedFile = new HashMap<String, Object>();
    attachedFile.put("name", "some name");
    attachedFile.put("vignettes", vignettes);
    doc.setPropertyValue("cmpf:attachedFile", (Serializable) attachedFile);

    Blob blob3 = Blobs.createBlob("foo3 bar3");
    doc.setProperty("file", "content", blob3);

    BlobsExtractor extractor = new BlobsExtractor();
    List<Blob> blobs = extractor.getBlobs(doc);
    assertEquals(3, blobs.size());
    assertTrue(blobs.contains(blob1));
    assertTrue(blobs.contains(blob2));
    assertTrue(blobs.contains(blob3));
  }
  protected DocumentModel createFile(
      CoreSession session, String path, String name, String type, String fileName, String content)
      throws InterruptedException {

    DocumentModel file = session.createDocumentModel(path, name, type);
    org.nuxeo.ecm.core.api.Blob blob = new org.nuxeo.ecm.core.api.impl.blob.StringBlob(content);
    blob.setFilename(fileName);
    file.setPropertyValue("file:content", (Serializable) blob);
    file = session.createDocument(file);
    // If the test is run against MySQL or SQL Server, because of its
    // milliseconds limitation, we need to wait for 1 second between each
    // document creation to ensure correct ordering when fetching a folder's
    // children, the default page provider query being ordered by ascendant
    // creation date.
    waitIfMySQLOrSQLServer();
    return file;
  }
예제 #15
0
  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 Blob renderTemplate(TemplateBasedDocument templateBasedDocument, String templateName)
      throws Exception {

    Blob sourceTemplateBlob = getSourceTemplateBlob(templateBasedDocument, templateName);
    List<TemplateInput> params = templateBasedDocument.getParams(templateName);

    DocumentModel doc = templateBasedDocument.getAdaptedDoc();
    Map<String, Object> ctx = FMContextBuilder.build(doc, false);

    JXLSBindingResolver resolver = new JXLSBindingResolver();

    resolver.resolve(params, ctx, templateBasedDocument);

    File workingDir = getWorkingDir();
    File generated = new File(workingDir, "JXLSresult-" + System.currentTimeMillis());
    generated.createNewFile();

    File input = new File(workingDir, "JXLSInput-" + System.currentTimeMillis());
    input.createNewFile();

    sourceTemplateBlob.transferTo(input);

    XLSTransformer transformer = new XLSTransformer();

    transformer.transformXLS(input.getAbsolutePath(), ctx, generated.getAbsolutePath());

    input.delete();

    Blob newBlob = new FileBlob(generated);

    String templateFileName = sourceTemplateBlob.getFilename();

    // set the output file name
    String targetFileExt = FileUtils.getFileExtension(templateFileName);
    String targetFileName =
        FileUtils.getFileNameNoExt(templateBasedDocument.getAdaptedDoc().getTitle());
    targetFileName = targetFileName + "." + targetFileExt;
    newBlob.setFilename(targetFileName);

    // mark the file for automatic deletion on GC
    Framework.trackFile(generated, newBlob);
    return newBlob;
  }
예제 #17
0
  public List<Blob> getPreview(Blob blob, DocumentModel dm) throws PreviewException {
    final String USER_TEMP = System.getProperty("java.io.tmpdir");

    Message msg = null;
    try {
      blob.transferTo(new File(USER_TEMP + "\\previewnuxeo.tmp"));
      MsgParser msgp = new MsgParser();
      msg = msgp.parseMsg(USER_TEMP + "\\previewnuxeo.tmp");

    } catch (IOException e1) {
      log.error(e1.toString());
    }

    List<Blob> blobResults = new ArrayList<Blob>();
    StringBuilder htmlPage = new StringBuilder();

    htmlPage.append("<html>");
    String tempheader =
        msg.toString()
            .replace("&", "&amp;")
            .replace("<", "&lt;")
            .replace(">", "&gt;")
            .replace("\'", "&apos;")
            .replace("\"", "&quot;");
    String tempbody =
        msg.getBodyText()
            .replace("&", "&amp;")
            .replace("<", "&lt;")
            .replace(">", "&gt;")
            .replace("\'", "&apos;")
            .replace("\"", "&quot;");
    htmlPage.append("<pre>").append(tempheader.replace("\n", "<br/>")).append("</pre>");
    htmlPage.append("<pre>").append(tempbody.replace("\n", "")).append("</pre>");
    htmlPage.append("</html>");

    Blob mainBlob = new StringBlob(htmlPage.toString());
    mainBlob.setFilename("index.html");
    mainBlob.setMimeType("text/html");

    blobResults.add(mainBlob);
    return blobResults;
  }
  @Override
  public Blob renderTemplate(TemplateBasedDocument templateBasedDocument, String templateName)
      throws IOException {

    Blob sourceTemplateBlob = getSourceTemplateBlob(templateBasedDocument, templateName);

    // load the template
    IXDocReport report;
    try {
      report =
          XDocReportRegistry.getRegistry()
              .loadReport(sourceTemplateBlob.getStream(), TemplateEngineKind.Freemarker, false);
    } catch (XDocReportException e) {
      throw new IOException(e);
    }

    // manage parameters
    List<TemplateInput> params = templateBasedDocument.getParams(templateName);
    FieldsMetadata metadata = new FieldsMetadata();
    for (TemplateInput param : params) {
      if (param.getType() == InputType.PictureProperty) {
        metadata.addFieldAsImage(param.getName());
      }
    }
    report.setFieldsMetadata(metadata);

    // fill Freemarker context
    DocumentModel doc = templateBasedDocument.getAdaptedDoc();
    Map<String, Object> ctx = fmContextBuilder.build(doc, templateName);

    XDocReportBindingResolver resolver = new XDocReportBindingResolver(metadata);
    resolver.resolve(params, ctx, templateBasedDocument);

    // add default context vars
    IContext context;
    try {
      context = report.createContext();
    } catch (XDocReportException e) {
      throw new IOException(e);
    }
    for (String key : ctx.keySet()) {
      context.put(key, ctx.get(key));
    }
    // add automatic loop on audit entries
    metadata.addFieldAsList("auditEntries.principalName");
    metadata.addFieldAsList("auditEntries.eventId");
    metadata.addFieldAsList("auditEntries.eventDate");
    metadata.addFieldAsList("auditEntries.docUUID");
    metadata.addFieldAsList("auditEntries.docPath");
    metadata.addFieldAsList("auditEntries.docType");
    metadata.addFieldAsList("auditEntries.category");
    metadata.addFieldAsList("auditEntries.comment");
    metadata.addFieldAsList("auditEntries.docLifeCycle");
    metadata.addFieldAsList("auditEntries.repositoryId");

    File workingDir = getWorkingDir();
    File generated = new File(workingDir, "XDOCReportresult-" + System.currentTimeMillis());
    generated.createNewFile();

    OutputStream out = new FileOutputStream(generated);

    try {
      report.process(context, out);
    } catch (XDocReportException e) {
      throw new IOException(e);
    }

    Blob newBlob = Blobs.createBlob(generated);

    String templateFileName = sourceTemplateBlob.getFilename();

    // set the output file name
    String targetFileExt = FileUtils.getFileExtension(templateFileName);
    String targetFileName =
        FileUtils.getFileNameNoExt(templateBasedDocument.getAdaptedDoc().getTitle());
    targetFileName = targetFileName + "." + targetFileExt;
    newBlob.setFilename(targetFileName);

    // mark the file for automatic deletion on GC
    Framework.trackFile(generated, newBlob);
    return newBlob;
  }
예제 #19
0
  @Test
  public void testWithRepositoryConfiguration() throws Exception {
    DocumentModel doc = new DocumentModelImpl("/", "doc", "ComplexDoc");

    List<Map<String, Object>> vignettes = new ArrayList<Map<String, Object>>();
    Map<String, Object> vignette = new HashMap<String, Object>();
    vignette.put("width", Long.valueOf(0));
    vignette.put("height", Long.valueOf(0));
    Blob blob1 = Blobs.createBlob("foo1 bar1");
    blob1.setFilename("file1.txt");
    vignette.put("content", blob1);
    vignettes.add(vignette);

    vignette = new HashMap<String, Object>();
    vignette.put("width", Long.valueOf(0));
    vignette.put("height", Long.valueOf(0));
    Blob blob2 = Blobs.createBlob("foo2 bar2");
    blob2.setFilename("file2.txt");
    vignette.put("content", blob2);
    vignettes.add(vignette);

    Map<String, Object> attachedFile = new HashMap<String, Object>();
    attachedFile.put("name", "some name");
    attachedFile.put("vignettes", vignettes);
    doc.setPropertyValue("cmpf:attachedFile", (Serializable) attachedFile);

    Blob blob3 = Blobs.createBlob("foo3 bar3");
    doc.setProperty("file", "content", blob3);

    BlobsExtractor extractor = new BlobsExtractor();
    List<Blob> blobs;

    /*
     * First configuration : only a simple property <index> <field>dc:title</field> </index>
     */
    extractor.setExtractorProperties(null, null, false);
    blobs = extractor.getBlobs(doc);
    assertEquals(0, blobs.size());

    /*
     * Second configuration : only blobs property <index> <fieldType>blob</fieldType> </index>
     */
    extractor.setExtractorProperties(null, null, true);
    blobs = extractor.getBlobs(doc);
    assertEquals(3, blobs.size());
    assertTrue(blobs.contains(blob1));
    assertTrue(blobs.contains(blob2));
    assertTrue(blobs.contains(blob3));

    /*
     * Third configuration : only a blob property whose schema has a prefix <index>
     * <field>cmpf:attachedFile/vignettes//content/data</field> </index>
     */
    Set<String> pathProps = new HashSet<String>();
    pathProps.add("cmpf:attachedFile/vignettes/*/content/data");
    extractor.setExtractorProperties(pathProps, null, false);
    blobs = extractor.getBlobs(doc);
    assertEquals(2, blobs.size());
    assertTrue(blobs.contains(blob1));
    assertTrue(blobs.contains(blob2));

    /*
     * Fourth configuration : only the blob of file whose schema doesn't have a prefix <index>
     * <field>content/data</field> </index>
     */
    pathProps = new HashSet<String>();
    pathProps.add("content/data");
    extractor.setExtractorProperties(pathProps, null, false);
    blobs = extractor.getBlobs(doc);
    assertEquals(1, blobs.size());
    assertTrue(blobs.contains(blob3));

    /*
     * Fifth configuration : all blobs minus some blobs <index> <fieldType>blob</fieldType>
     * <excludeField>content/data</excludeField> </index>
     */
    pathProps = new HashSet<String>();
    pathProps.add("content/data");
    extractor.setExtractorProperties(null, pathProps, true);
    blobs = extractor.getBlobs(doc);
    assertEquals(2, blobs.size());
    assertTrue(blobs.contains(blob2));
  }
  @Test
  public void testWriteOperations() throws Exception {

    // ------------------------------------------------------
    // Check #createFolder
    // ------------------------------------------------------
    // Not allowed to create a folder in a non FolderItem
    try {
      fileSystemItemManagerService.createFolder(
          DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(), "A new folder", principal);
      fail("Folder creation in a non folder item should fail.");
    } catch (NuxeoException e) {
      assertEquals(
          String.format(
              "Cannot create a folder in file system item with id %s because it is not a folder but is: "
                  + "DocumentBackedFileItem(id=\"%s\", name=\"Joe.odt\")",
              DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(),
              DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId()),
          e.getMessage());
    }

    // Folder creation
    FolderItem newFolderItem =
        fileSystemItemManagerService.createFolder(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), "A new folder", principal);
    assertNotNull(newFolderItem);
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), newFolderItem.getParentId());
    assertEquals("A new folder", newFolderItem.getName());
    DocumentModelList folderChildren =
        session.query(
            String.format(
                "select * from Document where ecm:parentId = '%s' and ecm:primaryType = 'Folder' order by dc:title asc",
                folder.getId()));
    DocumentModel newFolder = folderChildren.get(0);
    assertTrue(newFolder.isFolder());
    assertEquals("A new folder", newFolder.getTitle());

    // Parent folder children check
    assertEquals(
        6,
        fileSystemItemManagerService
            .getChildren(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), principal)
            .size());

    // ------------------------------------------------------
    // Check #createFile
    // ------------------------------------------------------
    // File creation
    Blob blob = new StringBlob("Content of a new file.");
    blob.setFilename("New file.odt");
    blob.setMimeType("application/vnd.oasis.opendocument.text");
    FileItem fileItem =
        fileSystemItemManagerService.createFile(newFolderItem.getId(), blob, principal);
    assertNotNull(fileItem);
    assertEquals(newFolderItem.getId(), fileItem.getParentId());
    assertEquals("New file.odt", fileItem.getName());
    folderChildren =
        session.query(
            String.format("select * from Document where ecm:parentId = '%s'", newFolder.getId()));
    assertEquals(1, folderChildren.size());
    DocumentModel newFile = folderChildren.get(0);
    assertEquals("File", newFile.getType());
    assertEquals("New file.odt", newFile.getTitle());
    assertEquals("/syncRoot1/aFolder/A new folder/New file.odt", newFile.getPathAsString());
    Blob newFileBlob = (Blob) newFile.getPropertyValue("file:content");
    assertEquals("New file.odt", newFileBlob.getFilename());
    assertEquals("Content of a new file.", newFileBlob.getString());
    assertEquals(
        "nxfile/test/" + newFile.getId() + "/blobholder:0/New%20file.odt",
        fileItem.getDownloadURL());
    assertEquals("MD5", fileItem.getDigestAlgorithm());
    assertEquals(newFileBlob.getDigest(), fileItem.getDigest());

    // Parent folder children check
    assertEquals(
        1, fileSystemItemManagerService.getChildren(newFolderItem.getId(), principal).size());

    // ------------------------------------------------------
    // Check #updateFile
    // ------------------------------------------------------
    String fileItemId = fileItem.getId();
    String fileItemParentId = fileItem.getParentId();
    blob = new StringBlob("Modified content of an existing file.");
    fileItem = fileSystemItemManagerService.updateFile(fileItemId, blob, principal);
    assertNotNull(fileItem);
    assertEquals(fileItemId, fileItem.getId());
    assertEquals(fileItemParentId, fileItem.getParentId());
    assertEquals("New file.odt", fileItem.getName());
    folderChildren =
        session.query(
            String.format("select * from Document where ecm:parentId = '%s'", newFolder.getId()));
    assertEquals(1, folderChildren.size());
    DocumentModel updatedFile = folderChildren.get(0);
    assertEquals("File", updatedFile.getType());
    assertEquals("New file.odt", updatedFile.getTitle());
    assertEquals("/syncRoot1/aFolder/A new folder/New file.odt", updatedFile.getPathAsString());
    Blob updatedFileBlob = (Blob) updatedFile.getPropertyValue("file:content");
    assertEquals("New file.odt", updatedFileBlob.getFilename());
    assertEquals("Modified content of an existing file.", updatedFileBlob.getString());
    assertEquals(
        "nxfile/test/" + updatedFile.getId() + "/blobholder:0/New%20file.odt",
        fileItem.getDownloadURL());
    assertEquals("MD5", fileItem.getDigestAlgorithm());
    assertEquals(updatedFileBlob.getDigest(), fileItem.getDigest());

    // ------------------------------------------------------
    // Check #delete
    // ------------------------------------------------------
    // File deletion
    fileSystemItemManagerService.delete(
        DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + updatedFile.getId(), principal);
    updatedFile = session.getDocument(new IdRef(updatedFile.getId()));
    assertEquals("deleted", updatedFile.getCurrentLifeCycleState());

    // Parent folder children check
    assertTrue(
        fileSystemItemManagerService.getChildren(newFolderItem.getId(), principal).isEmpty());

    // ------------------------------------------------------
    // Check #rename
    // ------------------------------------------------------
    // Folder rename
    String fsItemId = DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId();
    FileSystemItem fsItem =
        fileSystemItemManagerService.rename(fsItemId, "Jack's folder has a new name", principal);
    assertEquals(fsItemId, fsItem.getId());
    String expectedSyncRoot1Id = DEFAULT_SYNC_ROOT_ITEM_ID_PREFIX + syncRoot1.getId();
    assertEquals(expectedSyncRoot1Id, fsItem.getParentId());
    assertEquals("Jack's folder has a new name", fsItem.getName());
    folder = session.getDocument(folder.getRef());
    assertEquals("Jack's folder has a new name", folder.getTitle());

    // File rename with title != filename
    // => should rename filename but not title
    assertEquals("aFile", file.getTitle());
    assertEquals("Joe.odt", ((Blob) file.getPropertyValue("file:content")).getFilename());
    fsItemId = DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId();
    fsItem = fileSystemItemManagerService.rename(fsItemId, "File new name.odt", principal);
    assertEquals(fsItemId, fsItem.getId());
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), fsItem.getParentId());
    assertEquals("File new name.odt", fsItem.getName());
    file = session.getDocument(file.getRef());
    assertEquals("aFile", file.getTitle());
    Blob fileBlob = (Blob) file.getPropertyValue("file:content");
    assertEquals("File new name.odt", fileBlob.getFilename());
    fileItem = (FileItem) fsItem;
    assertEquals(
        "nxfile/test/" + file.getId() + "/blobholder:0/File%20new%20name.odt",
        fileItem.getDownloadURL());
    assertEquals("MD5", fileItem.getDigestAlgorithm());
    assertEquals(fileBlob.getDigest(), fileItem.getDigest());

    // File rename with title == filename
    // => should rename filename and title
    blob = new StringBlob("File for a doc with title == filename.");
    blob.setFilename("Title-filename equality.odt");
    blob.setMimeType("application/vnd.oasis.opendocument.text");
    fileItem = fileSystemItemManagerService.createFile(newFolderItem.getId(), blob, principal);
    // Note that the PathSegmentService truncates doc title at 24 characters
    newFile =
        session.getDocument(
            new PathRef("/syncRoot1/aFolder/A new folder/Title-filename equality."));
    assertEquals("Title-filename equality.odt", newFile.getTitle());
    assertEquals(
        "Title-filename equality.odt",
        ((Blob) newFile.getPropertyValue("file:content")).getFilename());
    fileItem =
        (FileItem)
            fileSystemItemManagerService.rename(
                DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + newFile.getId(),
                "Renamed title-filename equality.odt",
                principal);
    assertEquals("Renamed title-filename equality.odt", fileItem.getName());
    newFile = session.getDocument(newFile.getRef());
    assertEquals("Renamed title-filename equality.odt", newFile.getTitle());
    newFileBlob = (Blob) newFile.getPropertyValue("file:content");
    assertEquals("Renamed title-filename equality.odt", newFileBlob.getFilename());
    assertEquals(
        "nxfile/test/" + newFile.getId() + "/blobholder:0/Renamed%20title-filename%20equality.odt",
        fileItem.getDownloadURL());
    assertEquals("MD5", fileItem.getDigestAlgorithm());
    assertEquals(newFileBlob.getDigest(), fileItem.getDigest());

    // ------------------------------------------------------
    // Check #move
    // ------------------------------------------------------
    // 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();
    try {
      fileSystemItemManagerService.move(srcFsItemId, destFsItemId, principal);
      fail("Move to a non folder item should fail.");
    } catch (NuxeoException e) {
      assertEquals(
          String.format(
              "Cannot move a file system item to file system item with id %s because it is not a folder.",
              DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId()),
          e.getMessage());
    }

    // Move to a FolderItem
    destFsItemId = DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + subFolder.getId();
    FileSystemItem movedFsItem =
        fileSystemItemManagerService.move(srcFsItemId, destFsItemId, principal);
    assertEquals(srcFsItemId, movedFsItem.getId());
    assertEquals(destFsItemId, movedFsItem.getParentId());
    assertEquals("aNote.txt", movedFsItem.getName());
    note = session.getDocument(note.getRef());
    assertEquals("/syncRoot1/aFolder/aSubFolder/aNote", note.getPathAsString());
    assertEquals("aNote", note.getTitle());
  }
예제 #21
0
  @Override
  public BlobHolder convert(BlobHolder blobHolder, Map<String, Serializable> parameters)
      throws ConversionException {
    blobHolder = new UTF8CharsetConverter().convert(blobHolder, parameters);
    Blob inputBlob = blobHolder.getBlob();
    String blobPath = blobHolder.getFilePath();
    if (inputBlob == null) {
      return null;
    }

    OfficeDocumentConverter documentConverter = newDocumentConverter();
    // This plugin do deal only with one input source.
    String sourceMimetype = inputBlob.getMimeType();

    boolean pdfa1 = parameters != null && Boolean.TRUE.equals(parameters.get(PDFA1_PARAM));

    File sourceFile = null;
    File outFile = null;
    File[] files = null;
    try {

      // If the input blob has the HTML mime type, make sure the
      // charset meta is present, add it if not
      if ("text/html".equals(sourceMimetype)) {
        inputBlob = checkCharsetMeta(inputBlob);
      }

      // Get original file extension
      String ext = inputBlob.getFilename();
      int dotPosition = ext.lastIndexOf('.');
      if (dotPosition == -1) {
        ext = ".bin";
      } else {
        ext = ext.substring(dotPosition);
      }
      // Copy in a file to be able to read it several time
      sourceFile = Framework.createTempFile("NXJOOoConverterDocumentIn", ext);
      InputStream stream = inputBlob.getStream();
      FileUtils.copyToFile(stream, sourceFile);
      stream.close();

      DocumentFormat sourceFormat = null;
      if (sourceMimetype != null) {
        // Try to fetch it from the registry.
        sourceFormat = getSourceFormat(documentConverter, sourceMimetype);
      }
      // If not found in the registry or not given as a parameter.
      // Try to sniff ! What does that smell ? :)
      if (sourceFormat == null) {
        sourceFormat = getSourceFormat(documentConverter, sourceFile);
      }

      // From plugin settings because we know the destination
      // mimetype.
      DocumentFormat destinationFormat =
          getDestinationFormat(documentConverter, sourceFormat, pdfa1);

      // allow HTML2PDF filtering

      List<Blob> blobs = new ArrayList<>();

      if (descriptor.getDestinationMimeType().equals("text/html")) {
        String tmpDirPath = getTmpDirectory();
        File myTmpDir = new File(tmpDirPath + "/JODConv_" + System.currentTimeMillis());
        boolean created = myTmpDir.mkdir();
        if (!created) {
          throw new IOException("Unable to create temp dir");
        }

        outFile =
            new File(
                myTmpDir.getAbsolutePath()
                    + "/"
                    + "NXJOOoConverterDocumentOut."
                    + destinationFormat.getExtension());

        created = outFile.createNewFile();
        if (!created) {
          throw new IOException("Unable to create temp file");
        }

        log.debug("Input File = " + outFile.getAbsolutePath());
        // Perform the actual conversion.
        documentConverter.convert(sourceFile, outFile, destinationFormat);

        files = myTmpDir.listFiles();
        for (File file : files) {
          // copy the files to a new tmp location, as we'll delete them
          Blob blob;
          try (FileInputStream in = new FileInputStream(file)) {
            blob = Blobs.createBlob(in);
          }
          blob.setFilename(file.getName());
          blobs.add(blob);
          // add a blob for the index
          if (file.getName().equals(outFile.getName())) {
            Blob indexBlob;
            try (FileInputStream in = new FileInputStream(file)) {
              indexBlob = Blobs.createBlob(in);
            }
            indexBlob.setFilename("index.html");
            blobs.add(0, indexBlob);
          }
        }

      } else {
        outFile =
            Framework.createTempFile(
                "NXJOOoConverterDocumentOut", '.' + destinationFormat.getExtension());

        // Perform the actual conversion.
        documentConverter.convert(sourceFile, outFile, destinationFormat, parameters);

        Blob blob;
        try (FileInputStream in = new FileInputStream(outFile)) {
          blob = Blobs.createBlob(in, getDestinationMimeType());
        }
        blobs.add(blob);
      }
      return new SimpleCachableBlobHolder(blobs);
    } catch (IOException e) {
      String msg =
          String.format(
              "An error occurred trying to convert file %s to from %s to %s",
              blobPath, sourceMimetype, getDestinationMimeType());
      throw new ConversionException(msg, e);
    } finally {
      if (sourceFile != null) {
        sourceFile.delete();
      }
      if (outFile != null) {
        outFile.delete();
      }

      if (files != null) {
        for (File file : files) {
          if (file.exists()) {
            file.delete();
          }
        }
      }
    }
  }