Search in sources :

Example 16 with InvalidFormatException

use of org.apache.poi.openxml4j.exceptions.InvalidFormatException in project poi by apache.

the class XSSFWorkbook method cloneSheet.

/**
     * Create an XSSFSheet from an existing sheet in the XSSFWorkbook.
     *  The cloned sheet is a deep copy of the original but with a new given
     *  name.
     *
     * @param sheetNum The index of the sheet to clone
     * @param newName The name to set for the newly created sheet
     * @return XSSFSheet representing the cloned sheet.
     * @throws IllegalArgumentException if the sheet index or the sheet
     *         name is invalid
     * @throws POIXMLException if there were errors when cloning
     */
public XSSFSheet cloneSheet(int sheetNum, String newName) {
    validateSheetIndex(sheetNum);
    XSSFSheet srcSheet = sheets.get(sheetNum);
    if (newName == null) {
        String srcName = srcSheet.getSheetName();
        newName = getUniqueSheetName(srcName);
    } else {
        validateSheetName(newName);
    }
    XSSFSheet clonedSheet = createSheet(newName);
    // copy sheet's relations
    List<RelationPart> rels = srcSheet.getRelationParts();
    // if the sheet being cloned has a drawing then rememebr it and re-create it too
    XSSFDrawing dg = null;
    for (RelationPart rp : rels) {
        POIXMLDocumentPart r = rp.getDocumentPart();
        // do not copy the drawing relationship, it will be re-created
        if (r instanceof XSSFDrawing) {
            dg = (XSSFDrawing) r;
            continue;
        }
        addRelation(rp, clonedSheet);
    }
    try {
        for (PackageRelationship pr : srcSheet.getPackagePart().getRelationships()) {
            if (pr.getTargetMode() == TargetMode.EXTERNAL) {
                clonedSheet.getPackagePart().addExternalRelationship(pr.getTargetURI().toASCIIString(), pr.getRelationshipType(), pr.getId());
            }
        }
    } catch (InvalidFormatException e) {
        throw new POIXMLException("Failed to clone sheet", e);
    }
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        srcSheet.write(out);
        clonedSheet.read(new ByteArrayInputStream(out.toByteArray()));
    } catch (IOException e) {
        throw new POIXMLException("Failed to clone sheet", e);
    }
    CTWorksheet ct = clonedSheet.getCTWorksheet();
    if (ct.isSetLegacyDrawing()) {
        logger.log(POILogger.WARN, "Cloning sheets with comments is not yet supported.");
        ct.unsetLegacyDrawing();
    }
    if (ct.isSetPageSetup()) {
        logger.log(POILogger.WARN, "Cloning sheets with page setup is not yet supported.");
        ct.unsetPageSetup();
    }
    clonedSheet.setSelected(false);
    // clone the sheet drawing alongs with its relationships
    if (dg != null) {
        if (ct.isSetDrawing()) {
            // unset the existing reference to the drawing,
            // so that subsequent call of clonedSheet.createDrawingPatriarch() will create a new one
            ct.unsetDrawing();
        }
        XSSFDrawing clonedDg = clonedSheet.createDrawingPatriarch();
        // copy drawing contents
        clonedDg.getCTDrawing().set(dg.getCTDrawing());
        clonedDg = clonedSheet.createDrawingPatriarch();
        // Clone drawing relations
        List<RelationPart> srcRels = srcSheet.createDrawingPatriarch().getRelationParts();
        for (RelationPart rp : srcRels) {
            addRelation(rp, clonedDg);
        }
    }
    return clonedSheet;
}
Also used : POIXMLDocumentPart(org.apache.poi.POIXMLDocumentPart) CTWorksheet(org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet) POIXMLException(org.apache.poi.POIXMLException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) PackageRelationship(org.apache.poi.openxml4j.opc.PackageRelationship) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 17 with InvalidFormatException

use of org.apache.poi.openxml4j.exceptions.InvalidFormatException in project poi by apache.

the class XSSFWorkbook method addOlePackage.

@Override
public int addOlePackage(byte[] oleData, String label, String fileName, String command) throws IOException {
    // find an unused part name
    OPCPackage opc = getPackage();
    PackagePartName pnOLE;
    int oleId = 0;
    do {
        try {
            pnOLE = PackagingURIHelper.createPartName("/xl/embeddings/oleObject" + (++oleId) + ".bin");
        } catch (InvalidFormatException e) {
            throw new IOException("ole object name not recognized", e);
        }
    } while (opc.containPart(pnOLE));
    PackagePart pp = opc.createPart(pnOLE, "application/vnd.openxmlformats-officedocument.oleObject");
    Ole10Native ole10 = new Ole10Native(label, fileName, command, oleData);
    ByteArrayOutputStream bos = new ByteArrayOutputStream(oleData.length + 500);
    ole10.writeOut(bos);
    POIFSFileSystem poifs = new POIFSFileSystem();
    DirectoryNode root = poifs.getRoot();
    root.createDocument(Ole10Native.OLE10_NATIVE, new ByteArrayInputStream(bos.toByteArray()));
    root.setStorageClsid(ClassID.OLE10_PACKAGE);
    // TODO: generate CombObj stream
    OutputStream os = pp.getOutputStream();
    poifs.writeFilesystem(os);
    os.close();
    poifs.close();
    return oleId;
}
Also used : PackagePartName(org.apache.poi.openxml4j.opc.PackagePartName) Ole10Native(org.apache.poi.poifs.filesystem.Ole10Native) ByteArrayInputStream(java.io.ByteArrayInputStream) POIFSFileSystem(org.apache.poi.poifs.filesystem.POIFSFileSystem) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) DirectoryNode(org.apache.poi.poifs.filesystem.DirectoryNode) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PackagePart(org.apache.poi.openxml4j.opc.PackagePart) OPCPackage(org.apache.poi.openxml4j.opc.OPCPackage) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException)

Example 18 with InvalidFormatException

use of org.apache.poi.openxml4j.exceptions.InvalidFormatException in project poi by apache.

the class TestOPCComplianceCoreProperties method testOnlyOneCorePropertiesPart_AddRelationship.

/**
     * Test M4.1 rule.
     */
@Test
public void testOnlyOneCorePropertiesPart_AddRelationship() {
    InputStream is = OpenXML4JTestDataSamples.openComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx");
    OPCPackage pkg;
    try {
        pkg = OPCPackage.open(is);
    } catch (InvalidFormatException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    URI partUri = createURI("/docProps/core2.xml");
    try {
        pkg.addRelationship(PackagingURIHelper.createPartName(partUri), TargetMode.INTERNAL, PackageRelationshipTypes.CORE_PROPERTIES);
    // no longer fail on compliance error
    //fail("expected OPC compliance exception was not thrown");
    } catch (InvalidFormatException e) {
        throw new RuntimeException(e);
    } catch (InvalidOperationException e) {
        // expected during successful test
        assertEquals("OPC Compliance error [M4.1]: can't add another core properties part ! Use the built-in package method instead.", e.getMessage());
    }
    pkg.revert();
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) InvalidOperationException(org.apache.poi.openxml4j.exceptions.InvalidOperationException) IOException(java.io.IOException) OPCPackage(org.apache.poi.openxml4j.opc.OPCPackage) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) URI(java.net.URI) Test(org.junit.Test)

Example 19 with InvalidFormatException

use of org.apache.poi.openxml4j.exceptions.InvalidFormatException in project poi by apache.

the class TestOPCCompliancePackageModel method testAddPackageAlreadyAddFailure.

/**
     * Rule M1.12 : Packages shall not contain equivalent part names and package
     * implementers shall neither create nor recognize packages with equivalent
     * part names.
     */
@Test
public void testAddPackageAlreadyAddFailure() throws Exception {
    OPCPackage pkg = OPCPackage.create("DELETEIFEXISTS.docx");
    PackagePartName name1 = null;
    PackagePartName name2 = null;
    try {
        name1 = PackagingURIHelper.createPartName("/word/document.xml");
        name2 = PackagingURIHelper.createPartName("/word/document.xml");
    } catch (InvalidFormatException e) {
        throw new Exception(e.getMessage());
    }
    pkg.createPart(name1, ContentTypes.XML);
    try {
        pkg.createPart(name2, ContentTypes.XML);
    } catch (PartAlreadyExistsException e) {
        return;
    }
    fail("Packages shall not contain equivalent part names and package implementers shall neither create nor recognize packages with equivalent part names. [M1.12]");
}
Also used : PackagePartName(org.apache.poi.openxml4j.opc.PackagePartName) OPCPackage(org.apache.poi.openxml4j.opc.OPCPackage) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) IOException(java.io.IOException) InvalidOperationException(org.apache.poi.openxml4j.exceptions.InvalidOperationException) PartAlreadyExistsException(org.apache.poi.openxml4j.exceptions.PartAlreadyExistsException) PartAlreadyExistsException(org.apache.poi.openxml4j.exceptions.PartAlreadyExistsException) Test(org.junit.Test)

Example 20 with InvalidFormatException

use of org.apache.poi.openxml4j.exceptions.InvalidFormatException in project poi by apache.

the class TestOPCCompliancePartName method testPartNameEndsWithAForwardSlashFailure.

/**
     * A part name shall not have a forward slash as the last character. [M1.5]
     */
@Test
public void testPartNameEndsWithAForwardSlashFailure() throws URISyntaxException {
    try {
        PackagingURIHelper.createPartName(new URI("/document.xml/"));
        fail("A part name shall not have a forward slash as the last character. [M1.5]");
    } catch (InvalidFormatException e) {
    // Normal behaviour
    }
}
Also used : URI(java.net.URI) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) Test(org.junit.Test)

Aggregations

InvalidFormatException (org.apache.poi.openxml4j.exceptions.InvalidFormatException)71 IOException (java.io.IOException)24 PackagePart (org.apache.poi.openxml4j.opc.PackagePart)22 PackageRelationship (org.apache.poi.openxml4j.opc.PackageRelationship)18 OPCPackage (org.apache.poi.openxml4j.opc.OPCPackage)17 PackagePartName (org.apache.poi.openxml4j.opc.PackagePartName)16 PackageRelationshipCollection (org.apache.poi.openxml4j.opc.PackageRelationshipCollection)15 InputStream (java.io.InputStream)12 InvalidOperationException (org.apache.poi.openxml4j.exceptions.InvalidOperationException)11 Test (org.junit.Test)10 URI (java.net.URI)9 POIXMLException (org.apache.poi.POIXMLException)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 ArrayList (java.util.ArrayList)7 TikaException (org.apache.tika.exception.TikaException)7 XmlException (org.apache.xmlbeans.XmlException)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 FileNotFoundException (java.io.FileNotFoundException)6 HashMap (java.util.HashMap)6 Workbook (org.apache.poi.ss.usermodel.Workbook)6