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;
  }
示例#2
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);
  }
 protected String blobsToText(List<Blob> blobs, String docId) {
   List<String> strings = new LinkedList<String>();
   for (Blob blob : blobs) {
     try {
       SimpleBlobHolder bh = new SimpleBlobHolder(blob);
       BlobHolder result = convert(bh);
       if (result == null) {
         continue;
       }
       blob = result.getBlob();
       if (blob == null) {
         continue;
       }
       String string = new String(blob.getByteArray(), "UTF-8");
       // strip '\0 chars from text
       if (string.indexOf('\0') >= 0) {
         string = string.replace("\0", " ");
       }
       strings.add(string);
     } catch (Exception e) {
       String msg =
           "Could not extract fulltext of file '"
               + blob.getFilename()
               + "' for document: "
               + docId
               + ": "
               + e;
       log.warn(msg);
       log.debug(msg, e);
       continue;
     }
   }
   return StringUtils.join(strings, " ");
 }
示例#4
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;
 }
  @Test
  public void testSignPDFDocumentArchive() throws Exception {
    Blob pdfBlob = Blobs.createBlob(origPdfFile, "application/pdf", null, "foo.pdf");
    DocumentModel doc = session.createDocumentModel("File");
    doc.setPropertyValue("file:content", (Serializable) pdfBlob);

    Blob signedBlob =
        signatureService.signDocument(
            doc,
            user,
            USER_KEY_PASSWORD,
            "test",
            false,
            SigningDisposition.ARCHIVE,
            "foo archive.pdf");

    assertEquals("foo.pdf", signedBlob.getFilename());
    assertEquals(Arrays.asList("Signature1"), getSignatureNames(signedBlob));
    assertEquals(signedBlob, doc.getPropertyValue("file:content"));
    @SuppressWarnings("unchecked")
    List<Map<String, Serializable>> files =
        (List<Map<String, Serializable>>) doc.getPropertyValue("files:files");
    assertEquals(1, files.size());
    Blob archivedBlob = (Blob) files.get(0).get("file");
    assertEquals("application/pdf", archivedBlob.getMimeType());
    assertEquals("foo archive.pdf", archivedBlob.getFilename());
    assertEquals("foo archive.pdf", files.get(0).get("filename"));
  }
示例#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);
  }
 protected String getContentDispositionHeader(Blob blob, HttpServletRequest servletRequest) {
   if (servletRequest == null) {
     return RFC2231.encodeContentDisposition(blob.getFilename(), false, null);
   } else {
     return DownloadHelper.getRFC2231ContentDisposition(servletRequest, blob.getFilename());
   }
 }
 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;
 }
  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;
  }
示例#10
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);
 }
  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);
  }
  @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();
  }
示例#13
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);
 }
示例#14
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");
  }
示例#15
0
 public boolean isVideoPlayerReady() throws PropertyException, ClientException {
   String FILE_CONTENT = "file:content";
   Blob mainBlob = (Blob) doc.getPropertyValue(FILE_CONTENT);
   if (mainBlob != null
       && ("video/mp4".equals(mainBlob.getMimeType())
           || "video/webm".equals(mainBlob.getMimeType()))) {
     return true;
   }
   return webmTranscodedVideo != null || mp4TranscodedVideo != null;
 }
  protected static String guessEncoding(Blob blob) throws IOException {
    // encoding already known?
    if (blob.getEncoding() != null) {
      return null;
    }

    // bad mime type?
    String mimeType = blob.getMimeType();
    if (mimeType == null) {
      return null;
    }
    if (!mimeType.startsWith("text/") && !mimeType.startsWith("application/xhtml")) {
      // not a text file, we shouldn't be in the Note importer
      return null;
    }

    byte[] bytes = blob.getByteArray();

    List<String> charsets = Arrays.asList("utf-8", "iso-8859-1");

    // charset specified in MIME type?
    String CSEQ = "charset=";
    int i = mimeType.indexOf(CSEQ);
    if (i > 0) {
      String onlyMimeType = mimeType.substring(0, i).replace(";", "").trim();
      blob.setMimeType(onlyMimeType);
      String charset = mimeType.substring(i + CSEQ.length());
      i = charset.indexOf(";");
      if (i > 0) {
        charset = charset.substring(0, i);
      }
      charset = charset.trim().replace("\"", "");
      charsets = new ArrayList<String>(charsets);
      charsets.add(0, charset);
    }

    // resort to auto-detection
    for (String charset : charsets) {
      try {
        Charset cs = Charset.forName(charset);
        CharsetDecoder d =
            cs.newDecoder()
                .onMalformedInput(CodingErrorAction.REPORT)
                .onUnmappableCharacter(CodingErrorAction.REPORT);
        CharBuffer cb = d.decode(ByteBuffer.wrap(bytes));
        return cb.toString();
      } catch (IllegalArgumentException e) {
        // illegal charset
      } catch (CharacterCodingException e) {
        // could not decode
      }
    }
    // nothing worked, use platform
    return null;
  }
  @Test
  public void ensureDigestDecode() throws IOException, StorageException {
    Blob blob = Blobs.createBlob(CONTENT2);
    String contentMd5;
    try (InputStream is = blob.getStream()) {
      StreamMd5AndLength md5 =
          Utility.analyzeStream(is, blob.getLength(), 2 * Constants.MB, true, true);
      contentMd5 = md5.getMd5();
    }

    assertTrue(AzureFileStorage.isBlobDigestCorrect(CONTENT2_MD5, contentMd5));
  }
示例#18
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());
 }
 protected String getContentTypeHeader(Blob blob) {
   String contentType = blob.getMimeType();
   String encoding = blob.getEncoding();
   if (contentType != null && !StringUtils.isBlank(encoding)) {
     int i = contentType.indexOf(';');
     if (i >= 0) {
       contentType = contentType.substring(0, i);
     }
     contentType += "; charset=" + encoding;
   }
   return contentType;
 }
示例#20
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());
 }
  @Override
  public DocumentModel create(
      CoreSession documentManager,
      Blob content,
      String path,
      boolean overwrite,
      String fullname,
      TypeManager typeService)
      throws ClientException, IOException {
    path = getNearestContainerPath(documentManager, path);
    doSecurityCheck(documentManager, path, getNoteTypeName(), typeService);

    String filename = FileManagerUtils.fetchFileName(fullname);

    String title = FileManagerUtils.fetchTitle(filename);

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

    if (overwrite && docModel != null) {

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

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

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

    log.debug(
        "Created the Note: "
            + docModel.getName()
            + " with icon: "
            + docModel.getProperty(COMMON_SCHEMA, ICON_FIELD));
    return docModel;
  }
示例#22
0
 protected String getVideoLink(String mimetype, TranscodedVideo transcodedVideo)
     throws PropertyException, ClientException {
   String FILE_CONTENT = "file:content";
   Blob mainBlob = (Blob) doc.getPropertyValue(FILE_CONTENT);
   if (mainBlob != null && mimetype.equals(mainBlob.getMimeType())) {
     return bigFileUrl(FILE_CONTENT, mainBlob.getFilename());
   } else if (transcodedVideo != null) {
     String blobPropertyName = transcodedVideo.getBlobPropertyName();
     return bigFileUrl(blobPropertyName, transcodedVideo.getBlob().getFilename());
   } else {
     return null;
   }
 }
示例#23
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());
 }
 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;
 }
  @Test
  public void testResignDocument() throws Exception {
    Blob pdfBlob = Blobs.createBlob(signedPdfFile, "application/pdf", null, "foo.pdf");
    assertEquals(Arrays.asList("Signature1"), getSignatureNames(pdfBlob));

    DocumentModel doc = session.createDocumentModel("File");
    doc.setPropertyValue("file:content", (Serializable) pdfBlob);

    Blob signedBlob =
        signatureService.signDocument(
            doc, user, USER_KEY_PASSWORD, "test", false, SigningDisposition.REPLACE, null);

    assertEquals("foo.pdf", signedBlob.getFilename());
    assertEquals(Arrays.asList("Signature2", "Signature1"), getSignatureNames(signedBlob));
  }
  @Test
  public void testSignDocumentReplace() throws Exception {
    Blob txtBlob = Blobs.createBlob(helloTxtFile, "text/plain", null, "foo.txt");
    DocumentModel doc = session.createDocumentModel("File");
    doc.setPropertyValue("file:content", (Serializable) txtBlob);

    Blob signedBlob =
        signatureService.signDocument(
            doc, user, USER_KEY_PASSWORD, "test", false, SigningDisposition.REPLACE, null);

    assertEquals("foo.pdf", signedBlob.getFilename());
    assertEquals(Arrays.asList("Signature1"), getSignatureNames(signedBlob));
    assertEquals(signedBlob, doc.getPropertyValue("file:content"));
    assertEquals(Collections.emptyList(), doc.getPropertyValue("files:files"));
  }
 protected String getString(Blob blob) throws IOException {
   String s = guessEncoding(blob);
   if (s == null) {
     s = blob.getString(); // uses default charset
   }
   return s;
 }
  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;
  }
示例#29
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;
  }