use of org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException in project poi by apache.
the class OPCPackage method init.
/**
* Initialize the package instance.
*/
private void init() {
this.partMarshallers = new HashMap<ContentType, PartMarshaller>(5);
this.partUnmarshallers = new HashMap<ContentType, PartUnmarshaller>(2);
try {
// Add 'default' unmarshaller
this.partUnmarshallers.put(new ContentType(ContentTypes.CORE_PROPERTIES_PART), new PackagePropertiesUnmarshaller());
// Add default marshaller
this.defaultPartMarshaller = new DefaultMarshaller();
// TODO Delocalize specialized marshallers
this.partMarshallers.put(new ContentType(ContentTypes.CORE_PROPERTIES_PART), new ZipPackagePropertiesMarshaller());
} catch (InvalidFormatException e) {
// Should never happen
throw new OpenXML4JRuntimeException("Package.init() : this exception should never happen, " + "if you read this message please send a mail to the developers team. : " + e.getMessage(), e);
}
}
use of org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException in project poi by apache.
the class TestPOIXMLDocument method assertReadWrite.
public void assertReadWrite(OPCPackage pkg1) throws Exception {
OPCParser doc = new OPCParser(pkg1);
doc.parse(new TestFactory());
traverse(doc);
File tmp = TempFile.createTempFile("poi-ooxml", ".tmp");
FileOutputStream out = new FileOutputStream(tmp);
doc.write(out);
out.close();
// Should not be able to write to an output stream that has been closed
try {
doc.write(out);
fail("Should not be able to write to an output stream that has been closed.");
} catch (final OpenXML4JRuntimeException e) {
// see {@link org.apache.poi.openxml4j.opc.ZipPackage#saveImpl(java.io.OutputStream)}
if (e.getMessage().matches("Fail to save: an error occurs while saving the package : The part .+ failed to be saved in the stream with marshaller .+")) {
// expected
} else {
throw e;
}
}
// Should not be able to write a document that has been closed
doc.close();
try {
doc.write(new NullOutputStream());
fail("Should not be able to write a document that has been closed.");
} catch (final IOException e) {
if (e.getMessage().equals("Cannot write data, document seems to have been closed already")) {
// expected
} else {
throw e;
}
}
// Should be able to close a document multiple times, though subsequent closes will have no effect.
doc.close();
@SuppressWarnings("resource") OPCPackage pkg2 = OPCPackage.open(tmp.getAbsolutePath());
doc = new OPCParser(pkg1);
try {
doc.parse(new TestFactory());
traverse(doc);
assertEquals(pkg1.getRelationships().size(), pkg2.getRelationships().size());
ArrayList<PackagePart> l1 = pkg1.getParts();
ArrayList<PackagePart> l2 = pkg2.getParts();
assertEquals(l1.size(), l2.size());
for (int i = 0; i < l1.size(); i++) {
PackagePart p1 = l1.get(i);
PackagePart p2 = l2.get(i);
assertEquals(p1.getContentType(), p2.getContentType());
assertEquals(p1.hasRelationships(), p2.hasRelationships());
if (p1.hasRelationships()) {
assertEquals(p1.getRelationships().size(), p2.getRelationships().size());
}
assertEquals(p1.getPartName(), p2.getPartName());
}
} finally {
doc.close();
pkg1.close();
pkg2.close();
}
}
use of org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException in project poi by apache.
the class ZipPackage method saveImpl.
/**
* Save this package into the specified stream
*
*
* @param outputStream
* The stream use to save this package.
*
* @see #save(OutputStream)
*/
@Override
public void saveImpl(OutputStream outputStream) {
// Check that the document was open in write mode
throwExceptionIfReadOnly();
final ZipOutputStream zos;
try {
if (!(outputStream instanceof ZipOutputStream)) {
zos = new ZipOutputStream(outputStream);
} else {
zos = (ZipOutputStream) outputStream;
}
// we save it as well
if (this.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).size() == 0 && this.getPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES_ECMA376).size() == 0) {
LOG.log(POILogger.DEBUG, "Save core properties part");
// Ensure that core properties are added if missing
getPackageProperties();
// Add core properties to part list ...
addPackagePart(this.packageProperties);
// ... and to add its relationship ...
this.relationships.addRelationship(this.packageProperties.getPartName().getURI(), TargetMode.INTERNAL, PackageRelationshipTypes.CORE_PROPERTIES, null);
// ... and the content if it has not been added yet.
if (!this.contentTypeManager.isContentTypeRegister(ContentTypes.CORE_PROPERTIES_PART)) {
this.contentTypeManager.addContentType(this.packageProperties.getPartName(), ContentTypes.CORE_PROPERTIES_PART);
}
}
// Save package relationships part.
LOG.log(POILogger.DEBUG, "Save package relationships");
ZipPartMarshaller.marshallRelationshipPart(this.getRelationships(), PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_PART_NAME, zos);
// Save content type part.
LOG.log(POILogger.DEBUG, "Save content types part");
this.contentTypeManager.save(zos);
// Save parts.
for (PackagePart part : getParts()) {
// the source part that will do the job.
if (part.isRelationshipPart()) {
continue;
}
final PackagePartName ppn = part.getPartName();
LOG.log(POILogger.DEBUG, "Save part '" + ZipHelper.getZipItemNameFromOPCName(ppn.getName()) + "'");
PartMarshaller marshaller = partMarshallers.get(part._contentType);
String errMsg = "The part " + ppn.getURI() + " failed to be saved in the stream with marshaller ";
if (marshaller != null) {
if (!marshaller.marshall(part, zos)) {
throw new OpenXML4JException(errMsg + marshaller);
}
} else {
if (!defaultPartMarshaller.marshall(part, zos)) {
throw new OpenXML4JException(errMsg + defaultPartMarshaller);
}
}
}
zos.close();
} catch (OpenXML4JRuntimeException e) {
// no need to wrap this type of Exception
throw e;
} catch (Exception e) {
throw new OpenXML4JRuntimeException("Fail to save: an error occurs while saving the package : " + e.getMessage(), e);
}
}
use of org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException in project poi by apache.
the class OPCPackage method replaceContentType.
/**
* Replace a content type in this package.
*
* <p>
* A typical scneario to call this method is to rename a template file to the main format, e.g.
* ".dotx" to ".docx"
* ".dotm" to ".docm"
* ".xltx" to ".xlsx"
* ".xltm" to ".xlsm"
* ".potx" to ".pptx"
* ".potm" to ".pptm"
* </p>
* For example, a code converting a .xlsm macro workbook to .xlsx would look as follows:
* <p>
* <pre><code>
*
* OPCPackage pkg = OPCPackage.open(new FileInputStream("macro-workbook.xlsm"));
* pkg.replaceContentType(
* "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
* "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml");
*
* FileOutputStream out = new FileOutputStream("workbook.xlsx");
* pkg.save(out);
* out.close();
*
* </code></pre>
* </p>
*
* @param oldContentType the content type to be replaced
* @param newContentType the replacement
* @return whether replacement was succesfull
* @since POI-3.8
*/
public boolean replaceContentType(String oldContentType, String newContentType) {
boolean success = false;
ArrayList<PackagePart> list = getPartsByContentType(oldContentType);
for (PackagePart packagePart : list) {
if (packagePart.getContentType().equals(oldContentType)) {
PackagePartName partName = packagePart.getPartName();
contentTypeManager.addContentType(partName, newContentType);
try {
packagePart.setContentType(newContentType);
} catch (InvalidFormatException e) {
throw new OpenXML4JRuntimeException("invalid content type - " + newContentType, e);
}
success = true;
this.isDirty = true;
}
}
return success;
}
Aggregations