Search in sources :

Example 1 with InvalidOperationException

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

the class OPCPackage method getParts.

/**
	 * Load the parts of the archive if it has not been done yet. The
	 * relationships of each part are not loaded.
	 * 
	 * Note - Rule M4.1 states that there may only ever be one Core
	 *  Properties Part, but Office produced files will sometimes
	 *  have multiple! As Office ignores all but the first, we relax
	 *  Compliance with Rule M4.1, and ignore all others silently too. 
	 *
	 * @return All this package's parts.
	 * @throws InvalidFormatException if the package is not valid.
	 */
public ArrayList<PackagePart> getParts() throws InvalidFormatException {
    throwExceptionIfWriteOnly();
    // If the part list is null, we parse the package to retrieve all parts.
    if (partList == null) {
        /* Variables use to validate OPC Compliance */
        // Check rule M4.1 -> A format consumer shall consider more than
        // one core properties relationship for a package to be an error
        // (We just log it and move on, as real files break this!)
        boolean hasCorePropertiesPart = false;
        boolean needCorePropertiesPart = true;
        PackagePart[] parts = this.getPartsImpl();
        this.partList = new PackagePartCollection();
        for (PackagePart part : parts) {
            if (partList.containsKey(part._partName)) {
                throw new InvalidFormatException("A part with the name '" + part._partName + "' already exist : Packages shall not contain equivalent " + "part names and package implementers shall neither create " + "nor recognize packages with equivalent part names. [M1.12]");
            }
            // Check OPC compliance rule M4.1
            if (part.getContentType().equals(ContentTypes.CORE_PROPERTIES_PART)) {
                if (!hasCorePropertiesPart) {
                    hasCorePropertiesPart = true;
                } else {
                    logger.log(POILogger.WARN, "OPC Compliance error [M4.1]: " + "there is more than one core properties relationship in the package! " + "POI will use only the first, but other software may reject this file.");
                }
            }
            PartUnmarshaller partUnmarshaller = partUnmarshallers.get(part._contentType);
            if (partUnmarshaller != null) {
                UnmarshallContext context = new UnmarshallContext(this, part._partName);
                try {
                    PackagePart unmarshallPart = partUnmarshaller.unmarshall(context, part.getInputStream());
                    partList.put(unmarshallPart._partName, unmarshallPart);
                    // and ignore any subsequent ones
                    if (unmarshallPart instanceof PackagePropertiesPart && hasCorePropertiesPart && needCorePropertiesPart) {
                        this.packageProperties = (PackagePropertiesPart) unmarshallPart;
                        needCorePropertiesPart = false;
                    }
                } catch (IOException ioe) {
                    logger.log(POILogger.WARN, "Unmarshall operation : IOException for " + part._partName);
                    continue;
                } catch (InvalidOperationException invoe) {
                    throw new InvalidFormatException(invoe.getMessage(), invoe);
                }
            } else {
                try {
                    partList.put(part._partName, part);
                } catch (InvalidOperationException e) {
                    throw new InvalidFormatException(e.getMessage(), e);
                }
            }
        }
    }
    return new ArrayList<PackagePart>(partList.sortedValues());
}
Also used : UnmarshallContext(org.apache.poi.openxml4j.opc.internal.unmarshallers.UnmarshallContext) PartUnmarshaller(org.apache.poi.openxml4j.opc.internal.PartUnmarshaller) PackagePropertiesPart(org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart) InvalidOperationException(org.apache.poi.openxml4j.exceptions.InvalidOperationException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException)

Example 2 with InvalidOperationException

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

the class PackagingURIHelper method getRelationshipPartName.

/**
	 * Build a part name where the relationship should be stored ((ex
	 * /word/document.xml -> /word/_rels/document.xml.rels)
	 *
	 * @param partName
	 *            Source part URI
	 * @return the full path (as URI) of the relation file
	 * @throws InvalidOperationException
	 *             Throws if the specified URI is a relationshp part.
	 */
public static PackagePartName getRelationshipPartName(PackagePartName partName) {
    if (partName == null)
        throw new IllegalArgumentException("partName");
    if (PackagingURIHelper.PACKAGE_ROOT_URI.getPath().equals(partName.getURI().getPath()))
        return PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_PART_NAME;
    if (partName.isRelationshipPartURI())
        throw new InvalidOperationException("Can't be a relationship part");
    String fullPath = partName.getURI().getPath();
    String filename = getFilename(partName.getURI());
    fullPath = fullPath.substring(0, fullPath.length() - filename.length());
    fullPath = combine(fullPath, PackagingURIHelper.RELATIONSHIP_PART_SEGMENT_NAME);
    fullPath = combine(fullPath, filename);
    fullPath = fullPath + PackagingURIHelper.RELATIONSHIP_PART_EXTENSION_NAME;
    PackagePartName retPartName;
    try {
        retPartName = createPartName(fullPath);
    } catch (InvalidFormatException e) {
        // case of return null:
        return null;
    }
    return retPartName;
}
Also used : InvalidOperationException(org.apache.poi.openxml4j.exceptions.InvalidOperationException) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException)

Example 3 with InvalidOperationException

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

the class ZipPackage method closeImpl.

/**
     * Close and save the package.
     *
     * @see #close()
     */
@Override
protected void closeImpl() throws IOException {
    // Flush the package
    flush();
    if (this.originalPackagePath == null || "".equals(this.originalPackagePath)) {
        return;
    }
    // Save the content
    File targetFile = new File(this.originalPackagePath);
    if (!targetFile.exists()) {
        throw new InvalidOperationException("Can't close a package not previously open with the open() method !");
    }
    // Case of a package previously open
    String tempFileName = generateTempFileName(FileHelper.getDirectory(targetFile));
    File tempFile = TempFile.createTempFile(tempFileName, ".tmp");
    // Save the final package to a temporary file
    try {
        save(tempFile);
    } finally {
        // Close the current zip file, so we can overwrite it on all platforms
        IOUtils.closeQuietly(this.zipArchive);
        try {
            // Copy the new file over the old one
            FileHelper.copyFile(tempFile, targetFile);
        } finally {
            // Either the save operation succeed or not, we delete the temporary file
            if (!tempFile.delete()) {
                LOG.log(POILogger.WARN, "The temporary file: '" + targetFile.getAbsolutePath() + "' cannot be deleted ! Make sure that no other application use it.");
            }
        }
    }
}
Also used : InvalidOperationException(org.apache.poi.openxml4j.exceptions.InvalidOperationException) TempFile(org.apache.poi.util.TempFile) ZipFile(java.util.zip.ZipFile) File(java.io.File)

Example 4 with InvalidOperationException

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

the class TestOPCComplianceCoreProperties method testOnlyOneCorePropertiesPart_AddPart.

/**
     * Test M4.1 rule.
     */
@Test
public void testOnlyOneCorePropertiesPart_AddPart() throws InvalidFormatException {
    String sampleFileName = "OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx";
    OPCPackage pkg = OPCPackage.open(POIDataSamples.getOpenXML4JInstance().getFile(sampleFileName).getPath());
    URI partUri = createURI("/docProps/core2.xml");
    try {
        pkg.createPart(PackagingURIHelper.createPartName(partUri), ContentTypes.CORE_PROPERTIES_PART);
    // no longer fail on compliance error
    //fail("expected OPC compliance exception was not thrown");
    } catch (InvalidOperationException e) {
        // expected during successful test
        assertEquals("OPC Compliance error [M4.1]: you try to add more than one core properties relationship in the package !", e.getMessage());
    }
    pkg.revert();
}
Also used : InvalidOperationException(org.apache.poi.openxml4j.exceptions.InvalidOperationException) OPCPackage(org.apache.poi.openxml4j.opc.OPCPackage) URI(java.net.URI) Test(org.junit.Test)

Example 5 with InvalidOperationException

use of org.apache.poi.openxml4j.exceptions.InvalidOperationException 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)

Aggregations

InvalidOperationException (org.apache.poi.openxml4j.exceptions.InvalidOperationException)15 InvalidFormatException (org.apache.poi.openxml4j.exceptions.InvalidFormatException)9 OPCPackage (org.apache.poi.openxml4j.opc.OPCPackage)7 IOException (java.io.IOException)6 Test (org.junit.Test)6 PackagePartName (org.apache.poi.openxml4j.opc.PackagePartName)3 File (java.io.File)2 URI (java.net.URI)2 ArrayList (java.util.ArrayList)2 NotOfficeXmlFileException (org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException)2 TempFile (org.apache.poi.util.TempFile)2 XLSX2CSV (com.jeesuite.common2.excel.convert.XLSX2CSV)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 FileOutputStream (java.io.FileOutputStream)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 ZipEntry (java.util.zip.ZipEntry)1 ZipFile (java.util.zip.ZipFile)1 ODFNotOfficeXmlFileException (org.apache.poi.openxml4j.exceptions.ODFNotOfficeXmlFileException)1