Example usage for org.apache.poi.openxml4j.opc PackageAccess READ_WRITE

List of usage examples for org.apache.poi.openxml4j.opc PackageAccess READ_WRITE

Introduction

In this page you can find the example usage for org.apache.poi.openxml4j.opc PackageAccess READ_WRITE.

Prototype

PackageAccess READ_WRITE

To view the source code for org.apache.poi.openxml4j.opc PackageAccess READ_WRITE.

Click Source Link

Document

Read and Write mode.

Usage

From source file:com.kplot.web.data.WorkbookFactory.java

License:Apache License

/**
 * Creates the appropriate HSSFWorkbook / XSSFWorkbook from
 *  the given File, which must exist and be readable, and
 *  may be password protected/*www  .j a v a2s . c  o  m*/
 * <p>Note that in order to properly release resources the
 *  Workbook should be closed after use.
 *
 *  @param file The file to read data from.
 *  @param password The password that should be used or null if no password is necessary.
 *  @param readOnly If the Workbook should be opened in read-only mode to avoid writing back
 *     changes when the document is closed.
 *
 *  @return The created Workbook
 *
 *  @throws IOException if an error occurs while reading the data
 *  @throws InvalidFormatException if the contents of the file cannot be parsed into a {@link Workbook}
 *  @throws EncryptedDocumentException If the wrong password is given for a protected file
 *  @throws EmptyFileException If an empty stream is given
 */
public static Workbook create(File file, String password, boolean readOnly)
        throws IOException, InvalidFormatException, EncryptedDocumentException {
    if (!file.exists()) {
        throw new FileNotFoundException(file.toString());
    }

    try {
        System.out.println("NPOIFSFileSystem");
        NPOIFSFileSystem fs = new NPOIFSFileSystem(file, readOnly);
        try {
            return create(fs, password);
        } catch (RuntimeException e) {
            System.out.println("ensure that the file-handle is closed again");
            fs.close();

            throw e;
        }
    } catch (OfficeXmlFileException e) {
        System.out.println("opening as .xls failed => try opening as .xlsx");
        System.out.println("OPCPackage");
        OPCPackage pkg = OPCPackage.open(file, readOnly ? PackageAccess.READ : PackageAccess.READ_WRITE);
        try {
            return new XSSFWorkbook(pkg);
        } catch (IOException ioe) {
            // ensure that file handles are closed (use revert() to not re-write the file)
            pkg.revert();
            //pkg.close();

            // rethrow exception
            throw ioe;
        } catch (RuntimeException ioe) {
            // ensure that file handles are closed (use revert() to not re-write the file)
            pkg.revert();
            //pkg.close();

            // rethrow exception
            throw ioe;
        }
    }
}

From source file:de.jlo.talendcomp.excel.SpreadsheetFile.java

License:Apache License

private static void encryptFile(String inFilePath, String outFilePath, String password) throws Exception {
    if (password == null || password.trim().isEmpty()) {
        throw new Exception("Password cannot be null or empty!");
    }// w  w  w  .  java2s  . co m
    if (inFilePath == null || inFilePath.trim().isEmpty()) {
        throw new Exception("Input file cannot be null or empty!");
    }
    File inFile = new File(inFilePath);
    if (outFilePath == null || outFilePath.trim().isEmpty()) {
        throw new Exception("Output file cannot be null or empty!");
    }
    File outFile = new File(outFilePath);
    if (inFile.exists() == false) {
        throw new Exception("Excel file to encrypt: " + inFile.getAbsolutePath() + " does not exists!");
    }
    ensureDirExists(outFile);
    POIFSFileSystem fs = new POIFSFileSystem();
    EncryptionInfo info = new EncryptionInfo(EncryptionMode.standard);
    Encryptor enc = info.getEncryptor();
    enc.confirmPassword(password);
    OPCPackage opc = OPCPackage.open(inFile, PackageAccess.READ_WRITE);
    OutputStream os = enc.getDataStream(fs);
    opc.save(os);
    opc.close();
    FileOutputStream fos = null;
    Exception ex = null;
    try {
        fos = new FileOutputStream(outFile);
        fs.writeFilesystem(fos);
    } catch (Exception e) {
        ex = e;
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (Exception e1) {
                // ignore
            }
        }
    }
    if (ex != null) {
        throw ex;
    }
}

From source file:net.sourceforge.docfetcher.model.parse.MSOffice2007Parser.java

License:Open Source License

@Override
protected ParseResult parse(File file, ParseContext context) throws ParseException {
    try {//from w w  w .  j  a va2s  . c  om
        return doParse(file, PackageAccess.READ);
    } catch (Exception e) {
        Throwable root = Throwables.getRootCause(e);
        if (root instanceof InvalidOperationException
                && Strings.nullToEmpty(root.getMessage()).contains("open in read only mode")) {
            File tempFile = null;
            try {
                tempFile = Util.createTempFile(file.getName(), "." + Util.getExtension(file));
                Files.copy(file, tempFile);
                return doParse(tempFile, PackageAccess.READ_WRITE);
            } catch (IOException e1) {
                throw new ParseException(e1);
            } finally {
                if (tempFile != null) {
                    tempFile.delete();
                }
            }
        } else {
            throw new ParseException(e);
        }
    }
}

From source file:net.sourceforge.docfetcher.model.parse.MSOffice2007Parser.java

License:Open Source License

@Override
protected final String renderText(File file, String filename) throws ParseException {
    try {//from  w w  w  .j  a  v a2 s  .  c om
        return doRenderText(file, PackageAccess.READ);
    } catch (Exception e) {
        Throwable root = Throwables.getRootCause(e);
        if (root instanceof InvalidOperationException
                && Strings.nullToEmpty(root.getMessage()).contains("open in read only mode")) {
            File tempFile = null;
            try {
                tempFile = Util.createTempFile(file.getName(), "." + Util.getExtension(file));
                Files.copy(file, tempFile);
                return doRenderText(tempFile, PackageAccess.READ_WRITE);
            } catch (IOException e1) {
                throw new ParseException(e1);
            } finally {
                if (tempFile != null) {
                    tempFile.delete();
                }
            }
        } else {
            throw new ParseException(e);
        }
    }
}

From source file:org.roda.common.certification.OOXMLSignatureUtils.java

public static void runDigitalSignatureStrip(Path input, Path output)
        throws IOException, InvalidFormatException {

    CopyOption[] copyOptions = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING };
    Files.copy(input, output, copyOptions);
    OPCPackage pkg = OPCPackage.open(output.toString(), PackageAccess.READ_WRITE);

    ArrayList<PackagePart> pps = pkg.getPartsByContentType(SIGN_CONTENT_TYPE_OOXML);
    for (PackagePart pp : pps) {
        pkg.removePart(pp);//from   ww  w . ja  v  a  2s .  c  o m
    }

    ArrayList<PackagePart> ppct = pkg.getPartsByRelationshipType(SIGN_REL_TYPE_OOXML);
    for (PackagePart pp : ppct) {
        pkg.removePart(pp);
    }

    for (PackageRelationship r : pkg.getRelationships()) {
        if (r.getRelationshipType().equals(SIGN_REL_TYPE_OOXML)) {
            pkg.removeRelationship(r.getId());
        }
    }

    pkg.close();
}

From source file:org.roda.common.certification.OOXMLSignatureUtils.java

public static Path runDigitalSignatureSign(Path input, String keystore, String alias, String password,
        String fileFormat)//from   ww w. j  av  a2  s . c om
        throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException,
        UnrecoverableKeyException, InvalidFormatException, XMLSignatureException, MarshalException {

    Path output = Files.createTempFile("signed", "." + fileFormat);
    CopyOption[] copyOptions = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING };
    Files.copy(input, output, copyOptions);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = new FileInputStream(keystore);
    ks.load(is, password.toCharArray());

    PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray());
    X509Certificate x509 = (X509Certificate) ks.getCertificate(alias);

    SignatureConfig signatureConfig = new SignatureConfig();
    signatureConfig.setKey(pk);
    signatureConfig.setSigningCertificateChain(Collections.singletonList(x509));
    OPCPackage pkg = OPCPackage.open(output.toString(), PackageAccess.READ_WRITE);
    signatureConfig.setOpcPackage(pkg);

    SignatureInfo si = new SignatureInfo();
    si.setSignatureConfig(signatureConfig);
    si.confirmSignature();

    // boolean b = si.verifySignature();
    pkg.close();
    IOUtils.closeQuietly(is);

    return output;
}

From source file:org.roda.core.plugins.plugins.characterization.OOXMLSignatureUtils.java

public static void runDigitalSignatureStrip(Path input, Path output)
        throws IOException, InvalidFormatException {

    CopyOption[] copyOptions = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING };
    Files.copy(input, output, copyOptions);
    try (OPCPackage pkg = OPCPackage.open(output.toString(), PackageAccess.READ_WRITE)) {

        ArrayList<PackagePart> pps = pkg.getPartsByContentType(SIGN_CONTENT_TYPE_OOXML);
        for (PackagePart pp : pps) {
            pkg.removePart(pp);//  w ww .java 2s. com
        }

        ArrayList<PackagePart> ppct = pkg.getPartsByRelationshipType(SIGN_REL_TYPE_OOXML);
        for (PackagePart pp : ppct) {
            pkg.removePart(pp);
        }

        for (PackageRelationship r : pkg.getRelationships()) {
            if (r.getRelationshipType().equals(SIGN_REL_TYPE_OOXML)) {
                pkg.removeRelationship(r.getId());
            }
        }
    }
}

From source file:org.roda.core.plugins.plugins.characterization.OOXMLSignatureUtils.java

public static Path runDigitalSignatureSign(Path input, String keystore, String alias, String password,
        String fileFormat) throws IOException, GeneralSecurityException, InvalidFormatException,
        XMLSignatureException, MarshalException {

    Path output = Files.createTempFile("signed", "." + fileFormat);
    CopyOption[] copyOptions = new CopyOption[] { StandardCopyOption.REPLACE_EXISTING };
    Files.copy(input, output, copyOptions);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

    try (InputStream is = new FileInputStream(keystore)) {
        ks.load(is, password.toCharArray());

        PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray());
        X509Certificate x509 = (X509Certificate) ks.getCertificate(alias);

        SignatureConfig signatureConfig = new SignatureConfig();
        signatureConfig.setKey(pk);//from   w  w  w.  ja va 2 s  .  c  o  m
        signatureConfig.setSigningCertificateChain(Collections.singletonList(x509));

        try (OPCPackage pkg = OPCPackage.open(output.toString(), PackageAccess.READ_WRITE)) {
            signatureConfig.setOpcPackage(pkg);

            SignatureInfo si = new SignatureInfo();
            si.setSignatureConfig(signatureConfig);
            si.confirmSignature();

            // boolean b = si.verifySignature();
        }
    }
    return output;
}