Example usage for org.apache.poi.openxml4j.opc OPCPackage open

List of usage examples for org.apache.poi.openxml4j.opc OPCPackage open

Introduction

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

Prototype

public static OPCPackage open(File file, PackageAccess access) throws InvalidFormatException 

Source Link

Document

Open a package.

Usage

From source file:org.apache.tika.parser.microsoft.ooxml.OOXMLExtractorFactory.java

License:Apache License

public static void parse(InputStream stream, ContentHandler baseHandler, Metadata metadata,
        ParseContext context) throws IOException, SAXException, TikaException {
    Locale locale = context.get(Locale.class, Locale.getDefault());
    ExtractorFactory.setThreadPrefersEventExtractors(true);

    try {/*from w w w.  j a v  a  2  s  .  c  om*/
        OOXMLExtractor extractor;
        OPCPackage pkg;

        // Locate or Open the OPCPackage for the file
        TikaInputStream tis = TikaInputStream.cast(stream);
        if (tis != null && tis.getOpenContainer() instanceof OPCPackage) {
            pkg = (OPCPackage) tis.getOpenContainer();
        } else if (tis != null && tis.hasFile()) {
            pkg = OPCPackage.open(tis.getFile().getPath(), PackageAccess.READ);
            tis.setOpenContainer(pkg);
        } else {
            InputStream shield = new CloseShieldInputStream(stream);
            pkg = OPCPackage.open(shield);
        }

        // Get the type, and ensure it's one we handle
        MediaType type = ZipContainerDetector.detectOfficeOpenXML(pkg);
        if (type == null || OOXMLParser.UNSUPPORTED_OOXML_TYPES.contains(type)) {
            // Not a supported type, delegate to Empty Parser
            EmptyParser.INSTANCE.parse(stream, baseHandler, metadata, context);
            return;
        }
        metadata.set(Metadata.CONTENT_TYPE, type.toString());

        // Have the appropriate OOXML text extractor picked
        POIXMLTextExtractor poiExtractor = ExtractorFactory.createExtractor(pkg);

        POIXMLDocument document = poiExtractor.getDocument();
        if (poiExtractor instanceof XSSFEventBasedExcelExtractor) {
            extractor = new XSSFExcelExtractorDecorator(context, (XSSFEventBasedExcelExtractor) poiExtractor,
                    locale);
        } else if (document == null) {
            throw new TikaException(
                    "Expecting UserModel based POI OOXML extractor with a document, but none found. "
                            + "The extractor returned was a " + poiExtractor);
        } else if (document instanceof XMLSlideShow) {
            extractor = new XSLFPowerPointExtractorDecorator(context, (XSLFPowerPointExtractor) poiExtractor);
        } else if (document instanceof XWPFDocument) {
            extractor = new XWPFWordExtractorDecorator(context, (XWPFWordExtractor) poiExtractor);
        } else {
            extractor = new POIXMLTextExtractorDecorator(context, poiExtractor);
        }

        // Get the bulk of the metadata first, so that it's accessible during
        //  parsing if desired by the client (see TIKA-1109)
        extractor.getMetadataExtractor().extract(metadata);

        // Extract the text, along with any in-document metadata
        extractor.getXHTML(baseHandler, metadata, context);
    } catch (IllegalArgumentException e) {
        if (e.getMessage() != null && e.getMessage().startsWith("No supported documents found")) {
            throw new TikaException(
                    "TIKA-418: RuntimeException while getting content" + " for thmx and xps file types", e);
        } else {
            throw new TikaException("Error creating OOXML extractor", e);
        }
    } catch (InvalidFormatException e) {
        throw new TikaException("Error creating OOXML extractor", e);
    } catch (OpenXML4JException e) {
        throw new TikaException("Error creating OOXML extractor", e);
    } catch (XmlException e) {
        throw new TikaException("Error creating OOXML extractor", e);

    }
}

From source file:org.apache.tika.parser.pkg.ZipContainerDetector.java

License:Apache License

private static MediaType detectOPCBased(ZipFile zip, TikaInputStream stream) {
    try {//  ww  w .j ava  2  s  .  co  m
        if (zip.getEntry("_rels/.rels") != null || zip.getEntry("[Content_Types].xml") != null) {
            // Use POI to open and investigate it for us
            OPCPackage pkg = OPCPackage.open(stream.getFile().getPath(), PackageAccess.READ);
            stream.setOpenContainer(pkg);

            // Is at an OOXML format?
            MediaType type = detectOfficeOpenXML(pkg);
            if (type != null)
                return type;

            // Is it XPS format?
            type = detectXPSOPC(pkg);
            if (type != null)
                return type;

            // Is it an AutoCAD format?
            type = detectAutoCADOPC(pkg);
            if (type != null)
                return type;

            // We don't know what it is, sorry
            return null;
        } else {
            return null;
        }
    } catch (IOException e) {
        return null;
    } catch (RuntimeException e) {
        return null;
    } catch (InvalidFormatException e) {
        return null;
    }
}

From source file:org.dhatim.fastexcel.reader.ReadableWorkbook.java

License:Apache License

private static OPCPackage open(File file) {
    try {//w  w w.  ja v a 2  s. c om
        return OPCPackage.open(file, PackageAccess.READ);
    } catch (InvalidFormatException e) {
        throw new ExcelReaderException(e);
    }
}

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

public static String runDigitalSignatureVerify(Path input) throws IOException, GeneralSecurityException {
    boolean isValid = true;
    try {/*from   w w  w .  j ava  2s  .  co  m*/
        OPCPackage pkg = OPCPackage.open(input.toString(), PackageAccess.READ);
        SignatureConfig sic = new SignatureConfig();
        sic.setOpcPackage(pkg);

        SignatureInfo si = new SignatureInfo();
        si.setSignatureConfig(sic);
        Iterable<SignaturePart> it = si.getSignatureParts();
        if (it != null) {
            for (SignaturePart sp : it) {
                isValid = isValid && sp.validate();

                Set<Certificate> trustedRootCerts = new HashSet<Certificate>();
                Set<Certificate> intermediateCerts = new HashSet<Certificate>();
                List<X509Certificate> certChain = sp.getCertChain();

                for (X509Certificate c : certChain) {
                    c.checkValidity();

                    if (SignatureUtils.isCertificateSelfSigned(c))
                        trustedRootCerts.add(c);
                    else
                        intermediateCerts.add(c);
                }

                SignatureUtils.verifyCertificateChain(trustedRootCerts, intermediateCerts, certChain.get(0));
            }
        }

        pkg.close();
    } catch (InvalidFormatException e) {
        return "Error opening a document file";
    } catch (CertificateExpiredException e) {
        return "Contains expired certificates";
    } catch (CertificateNotYetValidException e) {
        return "Contains certificates not yet valid";
    }

    return isValid ? "Passed" : "Not passed";
}

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   w  w  w. j  ava 2 s  .  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 w  ww .j a v a  2 s.c  o  m*/
        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 String runDigitalSignatureVerify(Path input) throws IOException, GeneralSecurityException {
    boolean isValid = true;
    try (OPCPackage pkg = OPCPackage.open(input.toString(), PackageAccess.READ)) {
        SignatureConfig sic = new SignatureConfig();
        sic.setOpcPackage(pkg);/*from ww  w .  ja  v a2s. c  o m*/

        SignatureInfo si = new SignatureInfo();
        si.setSignatureConfig(sic);
        Iterable<SignaturePart> it = si.getSignatureParts();
        if (it != null) {
            for (SignaturePart sp : it) {
                isValid = isValid && sp.validate();

                Set<Certificate> trustedRootCerts = new HashSet<>();
                Set<Certificate> intermediateCerts = new HashSet<>();
                List<X509Certificate> certChain = sp.getCertChain();

                for (X509Certificate c : certChain) {
                    c.checkValidity();

                    if (SignatureUtils.isCertificateSelfSigned(c)) {
                        trustedRootCerts.add(c);
                    } else {
                        intermediateCerts.add(c);
                    }
                }

                SignatureUtils.verifyCertificateChain(trustedRootCerts, intermediateCerts, certChain.get(0));
            }
        }
    } catch (InvalidFormatException e) {
        return "Error opening a document file";
    } catch (CertificateExpiredException e) {
        return "Contains expired certificates";
    } catch (CertificateNotYetValidException e) {
        return "Contains certificates not yet valid";
    }

    return isValid ? "Passed" : "Not passed";
}

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  w  w. j  a  v a2 s .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());
            }
        }
    }
}

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);//w  ww . j  a v  a  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;
}

From source file:packtest.FromHowTo.java

License:Apache License

public void processFirstSheet(String filename) throws Exception {
    OPCPackage pkg = OPCPackage.open(filename, PackageAccess.READ);
    try {//from w w w .j a v  a  2s. c  o m
        XSSFReader r = new XSSFReader(pkg);
        SharedStringsTable sst = r.getSharedStringsTable();

        XMLReader parser = fetchSheetParser(sst);

        // process the first sheet
        InputStream sheet2 = r.getSheetsData().next();
        InputSource sheetSource = new InputSource(sheet2);
        parser.parse(sheetSource);
        sheet2.close();
    } finally {
        pkg.close();
    }
}