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());
}
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;
}
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.");
}
}
}
}
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();
}
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();
}
Aggregations