aboutsummaryrefslogtreecommitdiffstats
path: root/poi-ooxml/src/main/java/org/apache/poi/ooxml/POIXMLRelation.java
blob: aa1812aa2595c73c4ecc7c615005bd1958101306 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
/* ====================================================================
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
==================================================================== */
package org.apache.poi.ooxml;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import org.apache.logging.log4j.Logger;
import org.apache.poi.logging.PoiLogManager;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackagePartName;
import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
import org.apache.poi.openxml4j.opc.PackagingURIHelper;
import org.apache.poi.util.Internal;
import org.apache.xmlbeans.XmlException;

/**
 * Represents a descriptor of a OOXML relation.
 */
public abstract class POIXMLRelation {

    @Internal
    public interface NoArgConstructor {
        POIXMLDocumentPart init();
    }

    @Internal
    public interface PackagePartConstructor {
        POIXMLDocumentPart init(PackagePart part) throws IOException, XmlException;
    }

    @Internal
    public interface ParentPartConstructor {
        POIXMLDocumentPart init(POIXMLDocumentPart parent, PackagePart part) throws IOException, XmlException;
    }

    private static final Logger LOGGER = PoiLogManager.getLogger(POIXMLRelation.class);

    /**
     * Describes the content stored in a part.
     */
    private final String _type;

    /**
     * The kind of connection between a source part and a target part in a package.
     */
    private final String _relation;

    /**
     * The path component of a pack URI.
     */
    private final String _defaultName;

    /**
     * Constructors or factory method to construct instances of this relationship
     */
    private final NoArgConstructor noArgConstructor;
    private final PackagePartConstructor packagePartConstructor;
    private final ParentPartConstructor parentPartConstructor;

    /**
     * Instantiates a POIXMLRelation.
     *
     * @param type content type
     * @param rel  relationship
     * @param defaultName default item name
     * @param noArgConstructor method used to construct instances of this relationship from scratch
     * @param packagePartConstructor method used to construct instances of this relationship with a package part
     */
    protected POIXMLRelation(String type, String rel, String defaultName,
                             NoArgConstructor noArgConstructor,
                             PackagePartConstructor packagePartConstructor,
                             ParentPartConstructor parentPartConstructor) {
        _type = type;
        _relation = rel;
        _defaultName = defaultName;
        this.noArgConstructor = noArgConstructor;
        this.packagePartConstructor = packagePartConstructor;
        this.parentPartConstructor = parentPartConstructor;
    }

    /**
     * Instantiates a POIXMLRelation.
     *
     * @param type content type
     * @param rel  relationship
     * @param defaultName default item name
     */
    protected POIXMLRelation(String type, String rel, String defaultName) {
        this(type, rel, defaultName, null, null, null);
    }
    /**
     * Return the content type. Content types define a media type, a subtype, and an
     * optional set of parameters, as defined in RFC 2616.
     *
     * @return the content type
     */
    public String getContentType() {
        return _type;
    }

    /**
     * Return the relationship, the kind of connection between a source part and a target part in a package.
     * Relationships make the connections between parts directly discoverable without looking at the content
     * in the parts, and without altering the parts themselves.
     *
     * @return the relationship
     */
    public String getRelation() {
        return _relation;
    }

    /**
     * Return the default part name. Part names are used to refer to a part in the context of a
     * package, typically as part of a URI.
     *
     * @return the default part name
     */
    public String getDefaultFileName() {
        return _defaultName;
    }

    /**
     * Returns the filename for the nth one of these, e.g. /xl/comments4.xml
     *
     * @param index the suffix for the document type
     * @return the filename including the suffix
     */
    public String getFileName(int index) {
        if(! _defaultName.contains("#")) {
            // Generic filename in all cases
            return getDefaultFileName();
        }
        return _defaultName.replace("#", Integer.toString(index));
    }

    /**
     * Returns the index of the filename within the package for the given part.
     *  e.g. 4 for /xl/comments4.xml
     *
     * @param part the part to read the suffix from
     * @return the suffix
     */
    public Integer getFileNameIndex(POIXMLDocumentPart part) {
        String regex = _defaultName.replace("#", "(\\d+)");
        return Integer.valueOf(part.getPackagePart().getPartName().getName().replaceAll(regex, "$1"));
    }

    /**
     * @return the constructor method used to construct instances of this relationship from scratch
     *
     *  @since 4.1.2
     */
    public NoArgConstructor getNoArgConstructor() {
        return noArgConstructor;
    }

    /**
     * @return the constructor method used to construct instances of this relationship with a package part
     *
     *  @since 4.1.2
     */
    public PackagePartConstructor getPackagePartConstructor() {
        return packagePartConstructor;
    }

    /**
     * @return the constructor method used to construct instances of this relationship with a package part
     *
     *  @since 4.1.2
     */
    public ParentPartConstructor getParentPartConstructor() {
        return parentPartConstructor;
    }

    /**
     *  Fetches the InputStream to read the contents, based
     *  of the specified core part, for which we are defined
     *  as a suitable relationship
     *
     *  @since 3.16-beta3
     */
    public InputStream getContents(PackagePart corePart) throws IOException, InvalidFormatException {
        if (corePart == null) {
            throw new IllegalArgumentException("Core-Part cannot be empty");
        }
        PackageRelationshipCollection prc =
                corePart.getRelationshipsByType(getRelation());
        Iterator<PackageRelationship> it = prc.iterator();
        if(it.hasNext()) {
            PackageRelationship rel = it.next();
            PackagePartName relName = PackagingURIHelper.createPartName(rel.getTargetURI());
            PackagePart part = corePart.getPackage().getPart(relName);
            if (part == null) {
                throw new IllegalArgumentException("Could not read part " + relName + " from " + corePart);
            }
            return part.getInputStream();
        }
        LOGGER.atWarn().log("No part {} found", getDefaultFileName());
        return null;
    }
}