use of org.apache.poi.openxml4j.exceptions.InvalidFormatException in project poi by apache.
the class PackageRelationshipCollection method parseRelationshipsPart.
/**
* Parse the relationship part and add all relationship in this collection.
*
* @param relPart
* The package part to parse.
* @throws InvalidFormatException
* Throws if the relationship part is invalid.
*/
public void parseRelationshipsPart(PackagePart relPart) throws InvalidFormatException {
try {
logger.log(POILogger.DEBUG, "Parsing relationship: " + relPart.getPartName());
Document xmlRelationshipsDoc = DocumentHelper.readDocument(relPart.getInputStream());
// Browse default types
Element root = xmlRelationshipsDoc.getDocumentElement();
// Check OPC compliance M4.1 rule
boolean fCorePropertiesRelationship = false;
NodeList nodeList = root.getElementsByTagNameNS(PackageNamespaces.RELATIONSHIPS, PackageRelationship.RELATIONSHIP_TAG_NAME);
int nodeCount = nodeList.getLength();
for (int i = 0; i < nodeCount; i++) {
Element element = (Element) nodeList.item(i);
// Relationship ID
String id = element.getAttribute(PackageRelationship.ID_ATTRIBUTE_NAME);
// Relationship type
String type = element.getAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME);
// Check Rule M4.1
if (type.equals(PackageRelationshipTypes.CORE_PROPERTIES))
if (!fCorePropertiesRelationship)
fCorePropertiesRelationship = true;
else
throw new InvalidFormatException("OPC Compliance error [M4.1]: there is more than one core properties relationship in the package !");
/* End OPC Compliance */
// TargetMode (default value "Internal")
Attr targetModeAttr = element.getAttributeNode(PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME);
TargetMode targetMode = TargetMode.INTERNAL;
if (targetModeAttr != null) {
targetMode = targetModeAttr.getValue().toLowerCase(Locale.ROOT).equals("internal") ? TargetMode.INTERNAL : TargetMode.EXTERNAL;
}
// Target converted in URI
// dummy url
URI target = PackagingURIHelper.toURI("http://invalid.uri");
String value = element.getAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME);
try {
// when parsing of the given uri fails, we can either
// ignore this relationship, which leads to IllegalStateException
// later on, or use a dummy value and thus enable processing of the
// package
target = PackagingURIHelper.toURI(value);
} catch (URISyntaxException e) {
logger.log(POILogger.ERROR, "Cannot convert " + value + " in a valid relationship URI-> dummy-URI used", e);
}
addRelationship(target, targetMode, type, id);
}
} catch (Exception e) {
logger.log(POILogger.ERROR, e);
throw new InvalidFormatException(e.getMessage());
}
}
use of org.apache.poi.openxml4j.exceptions.InvalidFormatException in project poi by apache.
the class MemoryPackagePart method load.
@Override
public boolean load(InputStream ios) throws InvalidFormatException {
// Grab the data
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
IOUtils.copy(ios, baos);
} catch (IOException e) {
throw new InvalidFormatException(e.getMessage());
}
// Save it
data = baos.toByteArray();
// All done
return true;
}
use of org.apache.poi.openxml4j.exceptions.InvalidFormatException in project poi by apache.
the class PackagePropertiesPart method setDateValue.
/**
* Convert a string value represented a date into a Nullable<Date>.
*
* @throws InvalidFormatException
* Throws if the date format isnot valid.
*/
private Nullable<Date> setDateValue(String dateStr) throws InvalidFormatException {
if (dateStr == null || dateStr.equals("")) {
return new Nullable<Date>();
}
Matcher m = TIME_ZONE_PAT.matcher(dateStr);
if (m.find()) {
String dateTzStr = dateStr.substring(0, m.start()) + m.group(1) + m.group(2);
for (String fStr : TZ_DATE_FORMATS) {
SimpleDateFormat df = new SimpleDateFormat(fStr, Locale.ROOT);
df.setTimeZone(LocaleUtil.TIMEZONE_UTC);
Date d = df.parse(dateTzStr, new ParsePosition(0));
if (d != null) {
return new Nullable<Date>(d);
}
}
}
String dateTzStr = dateStr.endsWith("Z") ? dateStr : (dateStr + "Z");
for (String fStr : DATE_FORMATS) {
SimpleDateFormat df = new SimpleDateFormat(fStr, Locale.ROOT);
df.setTimeZone(LocaleUtil.TIMEZONE_UTC);
Date d = df.parse(dateTzStr, new ParsePosition(0));
if (d != null) {
return new Nullable<Date>(d);
}
}
//if you're here, no pattern matched, throw exception
StringBuilder sb = new StringBuilder();
int i = 0;
for (String fStr : TZ_DATE_FORMATS) {
if (i++ > 0) {
sb.append(", ");
}
sb.append(fStr);
}
for (String fStr : DATE_FORMATS) {
sb.append(", ").append(fStr);
}
throw new InvalidFormatException("Date " + dateStr + " not well formatted, " + "expected format in: " + sb);
}
use of org.apache.poi.openxml4j.exceptions.InvalidFormatException 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;
}
use of org.apache.poi.openxml4j.exceptions.InvalidFormatException in project poi by apache.
the class OPCPackage method configurePackage.
private static void configurePackage(OPCPackage pkg) {
try {
// Content type manager
pkg.contentTypeManager = new ZipContentTypeManager(null, pkg);
// Add default content types for .xml and .rels
pkg.contentTypeManager.addContentType(PackagingURIHelper.createPartName(PackagingURIHelper.PACKAGE_RELATIONSHIPS_ROOT_URI), ContentTypes.RELATIONSHIPS_PART);
pkg.contentTypeManager.addContentType(PackagingURIHelper.createPartName("/default.xml"), ContentTypes.PLAIN_OLD_XML);
// Initialise some PackageBase properties
pkg.packageProperties = new PackagePropertiesPart(pkg, PackagingURIHelper.CORE_PROPERTIES_PART_NAME);
pkg.packageProperties.setCreatorProperty("Generated by Apache POI OpenXML4J");
pkg.packageProperties.setCreatedProperty(new Nullable<Date>(new Date()));
} catch (InvalidFormatException e) {
// Should never happen
throw new IllegalStateException(e);
}
}
Aggregations