Search in sources :

Example 41 with InvalidFormatException

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());
    }
}
Also used : Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) URISyntaxException(java.net.URISyntaxException) Document(org.w3c.dom.Document) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) URI(java.net.URI) Attr(org.w3c.dom.Attr) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) URISyntaxException(java.net.URISyntaxException) InvalidOperationException(org.apache.poi.openxml4j.exceptions.InvalidOperationException)

Example 42 with InvalidFormatException

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;
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException)

Example 43 with InvalidFormatException

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);
}
Also used : Matcher(java.util.regex.Matcher) SimpleDateFormat(java.text.SimpleDateFormat) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) Nullable(org.apache.poi.openxml4j.util.Nullable) Date(java.util.Date) ParsePosition(java.text.ParsePosition)

Example 44 with InvalidFormatException

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;
}
Also used : InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) OpenXML4JRuntimeException(org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException)

Example 45 with InvalidFormatException

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);
    }
}
Also used : PackagePropertiesPart(org.apache.poi.openxml4j.opc.internal.PackagePropertiesPart) ZipContentTypeManager(org.apache.poi.openxml4j.opc.internal.ZipContentTypeManager) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) Date(java.util.Date)

Aggregations

InvalidFormatException (org.apache.poi.openxml4j.exceptions.InvalidFormatException)72 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