Exemplo n.º 1
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;
 }
 protected List<String> getSignatureNames(Blob blob) throws IOException {
   PdfReader reader = new PdfReader(blob.getStream());
   try {
     @SuppressWarnings("unchecked")
     List<String> names = reader.getAcroFields().getSignatureNames();
     return names;
   } finally {
     reader.close();
   }
 }
  @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));
  }
Exemplo n.º 4
0
  public void addBlob(Blob blob) throws MessagingException, IOException {
    MimeBodyPart part = new MimeBodyPart();
    part.setDataHandler(
        new DataHandler(
            new InputStreamDataSource(blob.getStream(), blob.getMimeType(), blob.getFilename())));
    part.setDisposition("attachment");
    String filename = blob.getFilename();
    if (filename != null) {
      part.setFileName(filename);
    }
    // must set the mime type at end because setFileName is also setting a
    // wrong content type.
    String mimeType = blob.getMimeType();
    if (mimeType != null) {
      part.setHeader("Content-type", mimeType);
    }

    addBodyPart(part);
  }
  @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;
  }
  @Override
  public Map<String, Object> getImageMetadata(Blob blob) {
    Map<String, Object> metadata = new HashMap<String, Object>();

    try {
      EditableImage image =
          EditableImage.create(new ReadOp(blob.getStream(), ReadOp.Type.METADATA));
      EXIFDirectory exif = image.getEXIFDirectory();

      // CB: NXP-4348 - Return correct values for image width/height
      image = EditableImage.create(new ReadOp(blob.getStream()));
      metadata.put(META_WIDTH, image.getWidth());
      metadata.put(META_HEIGHT, image.getHeight());

      /* EXIF */
      if (exif.isImageDescriptionAvailable()) {
        String description = exif.getImageDescription().trim();
        if (description.length() > 0) {
          metadata.put(META_DESCRIPTION, description);
        }
      }

      if (exif.isMakeAvailable() || exif.isModelAvailable()) {
        String equipment = (exif.getMake() + " " + exif.getModel()).trim();
        if (equipment.length() > 0) {
          metadata.put(META_EQUIPMENT, equipment);
        }
      }

      if (exif.isDateTimeOriginalAvailable()) {
        metadata.put(META_ORIGINALDATE, exif.getDateTimeOriginalAsDate());
      }

      if (exif.isXResolutionAvailable() && exif.isYResolutionAvailable()) {
        metadata.put(META_HRESOLUTION, exif.getXResolution().intValue());
        metadata.put(META_VRESOLUTION, exif.getYResolution().intValue());
      }

      if (exif.isPixelXDimensionAvailable() && exif.isPixelYDimensionAvailable()) {
        metadata.put(META_PIXEL_XDIMENSION, exif.getPixelXDimension());
        metadata.put(META_PIXEL_YDIMENSION, exif.getPixelYDimension());
      }

      if (exif.isCopyrightAvailable()) {
        String copyright = exif.getCopyright().trim();
        if (copyright.length() > 0) {
          metadata.put(META_COPYRIGHT, copyright);
        }
      }

      if (exif.isExposureTimeAvailable()) {
        Rational exposure = exif.getExposureTime();
        int n = exposure.getNumerator();
        int d = exposure.getDenominator();
        if (d >= n && d % n == 0) {
          exposure = new Rational(1, d / n);
        }
        metadata.put(META_EXPOSURE, exposure.toString());
      }

      if (exif.isISOSpeedRatingsAvailable()) {
        metadata.put(META_ISOSPEED, "ISO-" + exif.getISOSpeedRatings());
      }

      if (exif.isFocalLengthAvailable()) {
        metadata.put(META_FOCALLENGTH, exif.getFocalLength().doubleValue());
      }

      if (exif.isColorSpaceAvailable()) {
        metadata.put(META_COLORSPACE, exif.getColorSpace().toString());
      }

      if (exif.isWhiteBalanceAvailable()) {
        metadata.put(META_WHITEBALANCE, exif.getWhiteBalance().toString().toLowerCase());
      }

      if (exif.isInterColourProfileAvailable()) {
        metadata.put(META_ICCPROFILE, exif.getICCProfile());
      }

      if (exif.isOrientationAvailable()) {
        metadata.put(META_ORIENTATION, exif.getOrientation().toString());
      }

      if (exif.isFNumberAvailable()) {
        metadata.put(META_FNUMBER, exif.getFNumber().doubleValue());
      }
    } catch (IOException e) {
      log.warn("Failed to get EXIF metadata for the file: " + blob.getFilename());
      log.debug("Failed to get EXIF metadata for the file: " + blob.getFilename(), e);
    }

    try {
      /* IPTC */
      if (JPEG_MIMETYPE.equals(blob.getMimeType())) {
        IPTCHelper.extractMetadata(blob.getStream(), metadata);
      }
    } catch (IOException e) {
      log.error("Failed to get IPTC metadata for the file:" + blob.getFilename(), e);
    } catch (JpegProcessingException e) {
      log.error("Failed to get IPTC metadata for the file:" + blob.getFilename(), e);
    }

    return metadata;
  }
Exemplo n.º 7
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();
          }
        }
      }
    }
  }