Search in sources :

Example 26 with PackageRelationship

use of org.apache.poi.openxml4j.opc.PackageRelationship in project poi by apache.

the class TestXSLFHyperlink method testCreate.

@Test
public void testCreate() throws IOException, InvalidFormatException {
    XMLSlideShow ppt = new XMLSlideShow();
    XSLFSlide slide1 = ppt.createSlide();
    XSLFSlide slide2 = ppt.createSlide();
    int numRel = slide1.getPackagePart().getRelationships().size();
    assertEquals(1, numRel);
    XSLFTextBox sh1 = slide1.createTextBox();
    XSLFTextRun r1 = sh1.addNewTextParagraph().addNewTextRun();
    r1.setText("Web Page");
    XSLFHyperlink link1 = r1.createHyperlink();
    link1.setAddress("http://poi.apache.org/");
    assertEquals("http://poi.apache.org/", link1.getAddress());
    assertEquals(numRel + 1, slide1.getPackagePart().getRelationships().size());
    String id1 = link1.getXmlObject().getId();
    assertNotNull(id1);
    PackageRelationship rel1 = slide1.getPackagePart().getRelationship(id1);
    assertNotNull(rel1);
    assertEquals(id1, rel1.getId());
    assertEquals(TargetMode.EXTERNAL, rel1.getTargetMode());
    assertEquals(XSLFRelation.HYPERLINK.getRelation(), rel1.getRelationshipType());
    XSLFTextBox sh2 = slide1.createTextBox();
    XSLFTextRun r2 = sh2.addNewTextParagraph().addNewTextRun();
    r2.setText("Place in this document");
    XSLFHyperlink link2 = r2.createHyperlink();
    link2.linkToSlide(slide2);
    assertEquals("/ppt/slides/slide2.xml", link2.getAddress());
    assertEquals(numRel + 2, slide1.getPackagePart().getRelationships().size());
    String id2 = link2.getXmlObject().getId();
    assertNotNull(id2);
    PackageRelationship rel2 = slide1.getPackagePart().getRelationship(id2);
    assertNotNull(rel2);
    assertEquals(id2, rel2.getId());
    assertEquals(TargetMode.INTERNAL, rel2.getTargetMode());
    assertEquals(XSLFRelation.SLIDE.getRelation(), rel2.getRelationshipType());
    ppt.close();
}
Also used : PackageRelationship(org.apache.poi.openxml4j.opc.PackageRelationship) Test(org.junit.Test)

Example 27 with PackageRelationship

use of org.apache.poi.openxml4j.opc.PackageRelationship in project poi by apache.

the class ZipPartMarshaller method marshallRelationshipPart.

/**
	 * Save relationships into the part.
	 *
	 * @param rels
	 *            The relationships collection to marshall.
	 * @param relPartName
	 *            Part name of the relationship part to marshall.
	 * @param zos
	 *            Zip output stream in which to save the XML content of the
	 *            relationships serialization.
	 */
public static boolean marshallRelationshipPart(PackageRelationshipCollection rels, PackagePartName relPartName, ZipOutputStream zos) {
    // Building xml
    Document xmlOutDoc = DocumentHelper.createDocument();
    // make something like <Relationships
    // xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
    Element root = xmlOutDoc.createElementNS(PackageNamespaces.RELATIONSHIPS, PackageRelationship.RELATIONSHIPS_TAG_NAME);
    xmlOutDoc.appendChild(root);
    // <Relationship
    // TargetMode="External"
    // Id="rIdx"
    // Target="http://www.custom.com/images/pic1.jpg"
    // Type="http://www.custom.com/external-resource"/>
    URI sourcePartURI = PackagingURIHelper.getSourcePartUriFromRelationshipPartUri(relPartName.getURI());
    for (PackageRelationship rel : rels) {
        // the relationship element
        Element relElem = xmlOutDoc.createElementNS(PackageNamespaces.RELATIONSHIPS, PackageRelationship.RELATIONSHIP_TAG_NAME);
        root.appendChild(relElem);
        // the relationship ID
        relElem.setAttribute(PackageRelationship.ID_ATTRIBUTE_NAME, rel.getId());
        // the relationship Type
        relElem.setAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME, rel.getRelationshipType());
        // the relationship Target
        String targetValue;
        URI uri = rel.getTargetURI();
        if (rel.getTargetMode() == TargetMode.EXTERNAL) {
            // Save the target as-is - we don't need to validate it,
            //  alter it etc
            targetValue = uri.toString();
            // add TargetMode attribute (as it is external link external)
            relElem.setAttribute(PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME, "External");
        } else {
            URI targetURI = rel.getTargetURI();
            targetValue = PackagingURIHelper.relativizeURI(sourcePartURI, targetURI, true).toString();
        }
        relElem.setAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME, targetValue);
    }
    xmlOutDoc.normalize();
    // String schemaFilename = Configuration.getPathForXmlSchema()+
    // File.separator + "opc-relationships.xsd";
    // Save part in zip
    ZipEntry ctEntry = new ZipEntry(ZipHelper.getZipURIFromOPCName(relPartName.getURI().toASCIIString()).getPath());
    try {
        zos.putNextEntry(ctEntry);
        if (!StreamHelper.saveXmlInStream(xmlOutDoc, zos)) {
            return false;
        }
        zos.closeEntry();
    } catch (IOException e) {
        logger.log(POILogger.ERROR, "Cannot create zip entry " + relPartName, e);
        return false;
    }
    // success
    return true;
}
Also used : PackageRelationship(org.apache.poi.openxml4j.opc.PackageRelationship) Element(org.w3c.dom.Element) ZipEntry(java.util.zip.ZipEntry) IOException(java.io.IOException) Document(org.w3c.dom.Document) URI(java.net.URI)

Example 28 with PackageRelationship

use of org.apache.poi.openxml4j.opc.PackageRelationship in project poi by apache.

the class OOXMLLister method displayParts.

/**
	 * Displays information on all the different
	 *  parts of the OOXML file container.
	 * @throws InvalidFormatException if the package relations are invalid
	 * @throws IOException if the package can't be read 
	 */
public void displayParts() throws InvalidFormatException, IOException {
    ArrayList<PackagePart> parts = container.getParts();
    for (PackagePart part : parts) {
        disp.println(part.getPartName());
        disp.println("\t" + part.getContentType());
        if (!part.getPartName().toString().equals("/docProps/core.xml")) {
            disp.println("\t" + getSize(part) + " bytes");
        }
        if (!part.isRelationshipPart()) {
            disp.println("\t" + part.getRelationships().size() + " relations");
            for (PackageRelationship rel : part.getRelationships()) {
                displayRelation(rel, "\t  ");
            }
        }
    }
}
Also used : PackageRelationship(org.apache.poi.openxml4j.opc.PackageRelationship) PackagePart(org.apache.poi.openxml4j.opc.PackagePart)

Example 29 with PackageRelationship

use of org.apache.poi.openxml4j.opc.PackageRelationship in project poi by apache.

the class POIXMLDocumentPart method createRelationship.

/**
     * Create a new child POIXMLDocumentPart
     *
     * @param descriptor the part descriptor
     * @param factory the factory that will create an instance of the requested relation
     * @param idx part number
     * @param noRelation if true, then no relationship is added.
     * @return the created child POIXMLDocumentPart
     * @throws PartAlreadyExistsException
     *             If rule M1.12 is not verified : Packages shall not contain
     *             equivalent part names and package implementers shall neither
     *             create nor recognize packages with equivalent part names.
     */
protected final RelationPart createRelationship(POIXMLRelation descriptor, POIXMLFactory factory, int idx, boolean noRelation) {
    try {
        PackagePartName ppName = PackagingURIHelper.createPartName(descriptor.getFileName(idx));
        PackageRelationship rel = null;
        PackagePart part = packagePart.getPackage().createPart(ppName, descriptor.getContentType());
        if (!noRelation) {
            /* only add to relations, if according relationship is being created. */
            rel = packagePart.addRelationship(ppName, TargetMode.INTERNAL, descriptor.getRelation());
        }
        POIXMLDocumentPart doc = factory.newDocumentPart(descriptor);
        doc.packagePart = part;
        doc.parent = this;
        if (!noRelation) {
            /* only add to relations, if according relationship is being created. */
            addRelation(rel, doc);
        }
        return new RelationPart(rel, doc);
    } catch (PartAlreadyExistsException pae) {
        //  that the name is already taken
        throw pae;
    } catch (Exception e) {
        // Give a general wrapped exception for the problem
        throw new POIXMLException(e);
    }
}
Also used : PackagePartName(org.apache.poi.openxml4j.opc.PackagePartName) PackageRelationship(org.apache.poi.openxml4j.opc.PackageRelationship) PackagePart(org.apache.poi.openxml4j.opc.PackagePart) InvalidFormatException(org.apache.poi.openxml4j.exceptions.InvalidFormatException) OpenXML4JException(org.apache.poi.openxml4j.exceptions.OpenXML4JException) IOException(java.io.IOException) PartAlreadyExistsException(org.apache.poi.openxml4j.exceptions.PartAlreadyExistsException) PartAlreadyExistsException(org.apache.poi.openxml4j.exceptions.PartAlreadyExistsException)

Example 30 with PackageRelationship

use of org.apache.poi.openxml4j.opc.PackageRelationship in project poi by apache.

the class POIXMLDocumentPart method read.

/**
     * Iterate through the underlying PackagePart and create child POIXMLFactory instances
     * using the specified factory
     *
     * @param factory   the factory object that creates POIXMLFactory instances
     * @param context   context map containing already visited noted keyed by targetURI
     * 
     * @throws OpenXML4JException thrown when a related part can't be read
     */
protected void read(POIXMLFactory factory, Map<PackagePart, POIXMLDocumentPart> context) throws OpenXML4JException {
    PackagePart pp = getPackagePart();
    // add mapping a second time, in case of initial caller hasn't done so
    POIXMLDocumentPart otherChild = context.put(pp, this);
    if (otherChild != null && otherChild != this) {
        throw new POIXMLException("Unique PackagePart-POIXMLDocumentPart relation broken!");
    }
    if (!pp.hasRelationships())
        return;
    PackageRelationshipCollection rels = packagePart.getRelationships();
    List<POIXMLDocumentPart> readLater = new ArrayList<POIXMLDocumentPart>();
    // scan breadth-first, so parent-relations are hopefully the shallowest element
    for (PackageRelationship rel : rels) {
        if (rel.getTargetMode() == TargetMode.INTERNAL) {
            URI uri = rel.getTargetURI();
            // check for internal references (e.g. '#Sheet1!A1')
            PackagePartName relName;
            if (uri.getRawFragment() != null) {
                relName = PackagingURIHelper.createPartName(uri.getPath());
            } else {
                relName = PackagingURIHelper.createPartName(uri);
            }
            final PackagePart p = packagePart.getPackage().getPart(relName);
            if (p == null) {
                logger.log(POILogger.ERROR, "Skipped invalid entry " + rel.getTargetURI());
                continue;
            }
            POIXMLDocumentPart childPart = context.get(p);
            if (childPart == null) {
                childPart = factory.createDocumentPart(this, p);
                childPart.parent = this;
                // already add child to context, so other children can reference it
                context.put(p, childPart);
                readLater.add(childPart);
            }
            addRelation(rel, childPart);
        }
    }
    for (POIXMLDocumentPart childPart : readLater) {
        childPart.read(factory, context);
    }
}
Also used : PackageRelationship(org.apache.poi.openxml4j.opc.PackageRelationship) PackagePartName(org.apache.poi.openxml4j.opc.PackagePartName) PackageRelationshipCollection(org.apache.poi.openxml4j.opc.PackageRelationshipCollection) ArrayList(java.util.ArrayList) PackagePart(org.apache.poi.openxml4j.opc.PackagePart) URI(java.net.URI)

Aggregations

PackageRelationship (org.apache.poi.openxml4j.opc.PackageRelationship)50 PackagePart (org.apache.poi.openxml4j.opc.PackagePart)28 InvalidFormatException (org.apache.poi.openxml4j.exceptions.InvalidFormatException)21 PackageRelationshipCollection (org.apache.poi.openxml4j.opc.PackageRelationshipCollection)15 PackagePartName (org.apache.poi.openxml4j.opc.PackagePartName)13 IOException (java.io.IOException)11 POIXMLException (org.apache.poi.POIXMLException)8 OPCPackage (org.apache.poi.openxml4j.opc.OPCPackage)5 TikaException (org.apache.tika.exception.TikaException)5 ArrayList (java.util.ArrayList)4 XmlException (org.apache.xmlbeans.XmlException)4 Test (org.junit.Test)4 InputStream (java.io.InputStream)3 URI (java.net.URI)3 HashMap (java.util.HashMap)3 OpenXML4JException (org.apache.poi.openxml4j.exceptions.OpenXML4JException)3 SAXException (org.xml.sax.SAXException)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2 FileNotFoundException (java.io.FileNotFoundException)2