Debian Codegraph @

src/com/github/weisj/jsvg/util/DataUri.java

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
•1 /*
2 * MIT License
3 *
4 * Copyright (c) 2013-2024 Jannis Weis
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
7 * associated documentation files (the "Software"), to deal in the Software without restriction,
8 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
9 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in all copies or
13 * substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
16 * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 *
21 */
22 package com.github.weisj.jsvg.util;
23
24 import java.io.IOException;
25 import java.io.UnsupportedEncodingException;
26 import java.net.URLDecoder;
27 import java.nio.charset.Charset;
28 import java.nio.charset.StandardCharsets;
29 import java.util.*;
30 import java.util.regex.Pattern;
31
32 import org.jetbrains.annotations.NotNull;
33 import org.jetbrains.annotations.Nullable;
34
35 /**
36 * Copyright (c) 2013 ooxi
37 * <a href="https://github.com/ooxi/jdatauri">...</a>
38 * <p>
39 * This software is provided 'as-is', without any express or implied warranty.
40 * In no event will the authors be held liable for any damages arising from the
41 * use of this software.
42 * <p>
43 * Permission is granted to anyone to use this software for any purpose,
44 * including commercial applications, and to alter it and redistribute it
45 * freely, subject to the following restrictions:
46 * <p>
47 * 1. The origin of this software must not be misrepresented; you must not
48 * claim that you wrote the original software. If you use this software in a
49 * product, an acknowledgment in the product documentation would be
50 * appreciated but is not required.
51 * <p>
52 * 2. Altered source versions must be plainly marked as such, and must not be
53 * misrepresented as being the original software.
54 * <p>
55 * 3. This notice may not be removed or altered from any source distribution.
56 * <p>
57 * Note: This file has been modified for usage in the JSVG project.
58 */
59 final class DataUri {
60 private static final String CHARSET_OPTION_NAME = "charset";
61 private static final String FILENAME_OPTION_NAME = "filename";
62 private static final String CONTENT_DISPOSITION_OPTION_NAME = "content-disposition";
63
64 private final @NotNull String mime;
65 private final @Nullable Charset charset;
66 private final @Nullable String filename;
67 private final @Nullable String contentDisposition;
68 private final byte @NotNull [] data;
69
70 public DataUri(String mime, Charset charset, byte[] data) {
71 this(mime, charset, null, null, data);
72 }
73
74 public DataUri(@NotNull String mime, @Nullable Charset charset, @Nullable String filename,
75 @Nullable String contentDisposition, byte @NotNull [] data) {
76 this.mime = mime;
77 this.charset = charset;
78 this.filename = filename;
79 this.contentDisposition = contentDisposition;
80 this.data = data;
81 }
82
83 public @NotNull String mime() {
84 return mime;
85 }
86
87 public byte @NotNull [] data() {
88 return data;
89 }
90
91 public @Nullable Charset charset() {
92 return charset;
93 }
94
95 public @Nullable String contentDisposition() {
96 return contentDisposition;
97 }
98
99 public @Nullable String filename() {
100 return filename;
101 }
102
103 @Override
104 public boolean equals(Object o) {
105 if (this == o) return true;
106 if (!(o instanceof DataUri)) return false;
107 DataUri dataUri = (DataUri) o;
108 return mime.equals(dataUri.mime)
109 && Objects.equals(charset, dataUri.charset)
110 && Objects.equals(filename, dataUri.filename)
111 && Objects.equals(contentDisposition, dataUri.contentDisposition)
112 && Arrays.equals(data, dataUri.data);
113 }
114
115 @Override
116 public int hashCode() {
117 int result = Objects.hash(mime, charset, filename, contentDisposition);
118 result = 31 * result + Arrays.hashCode(data);
119 return result;
120 }
121
122 static final class MalformedDataUriException extends IOException {
123 MalformedDataUriException(@NotNull String reason) {
124 super(reason);
125 }
126
127 MalformedDataUriException(@NotNull Exception reason) {
128 super(reason);
129 }
130 }
131
132 /**
133 * Tries to parse a data URI described in RFC2397
134 *
135 * @param uri A string representing the data URI
136 * @param charset Charset to use when decoding percent encoded options
137 * like filename
138 *
139 * @return Parsed data URI
140 * @throws IllegalArgumentException iff an error occurred during parse
141 * process
142 */
143 public static DataUri parse(@NotNull String uri, Charset charset) throws MalformedDataUriException {
144
145 // If URI does not start with a case-insensitive "data:": Throw a MALFORMED_URI exception.
146 if (!uri.toLowerCase(Locale.ENGLISH).startsWith("data:"))
147 throw new MalformedDataUriException("URI must start with a case-insensitive `data:'");
148
149 // If URI does not contain a ",": Throw a MALFORMED_URI exception.
150 if (-1 == uri.indexOf(',')) throw new MalformedDataUriException("URI must contain a `,'");
151
152 // Let supportedContentEncodings be an array of strings
153 // representing the supported content encodings. (["base64"] for example)
154 Collection<String> supportedContentEncodings = Collections.singletonList("base64");
155
156 // Let mimeType be a string with the value "text/plain".
157 String mimeType = "text/plain";
158
159 // Let contentEncoding be an empy string.
160 String contentEncoding = "";
161
162 /*
163 * Let contentEncodingAlreadySet be a boolean with a value of false.
164 */
165 boolean contentEncodingAlreadySet = false;
166
167 // Let supportedValues be a map of string:string pairs where the
168 // first string in each pair represents the name of the
169 // supported value and the second string in each pair represents
170 // an empty string or default string value.
171 // (Example: {"charset" : "", "filename" : "", "content-disposition" : ""})
172 final Map<String, String> supportedValues = new HashMap<>();
173 supportedValues.put(CHARSET_OPTION_NAME, "");
174 supportedValues.put(FILENAME_OPTION_NAME, "");
175 supportedValues.put(CONTENT_DISPOSITION_OPTION_NAME, "");
176
177 // Let supportedValueSetBits be a map of string:bool pairs
178 // representing each of the names in supportedValues with each
179 // name set to false.
180 final Map<String, Boolean> supportedValueSetBits = new HashMap<>();
181 for (String key : supportedValues.keySet()) {
182 supportedValueSetBits.put(key, false);
183 }
184
185 // Let comma be the position of the first "," found in URI.
186 int comma = uri.indexOf(',');
187
188 // Let temp be the substring of URI from, and including,
189 // position 5 to, and excluding, the comma position. (between "data:" and first ",")
190 String temp = uri.substring("data:".length(), comma);
191
192 // Let headers be an array of strings returned by splitting temp by ";".
193 String[] headers = temp.split(";");
194
195 // For each string s in headers:
196 for (int header = 0; header < headers.length; ++header) {
197 String s = headers[header];
198
199 // Let s equal the lowercase version of s
200 s = s.toLowerCase(Locale.ENGLISH);
201
202 // Let eq be the position result of searching for "=" in s.
203 int eq = s.indexOf('=');
204
205 // Let name and value be empty strings.
206 String name;
207 String value = "";
208
209 // If eq is not a valid position in s:
210 if (-1 == eq) {
211
212 // Let name equal the result of percent-decoding s.
213 name = percentDecode(s, charset);
214
215 // Let name equal the result of trimming leading and trailing white-space from name.
216 name = name.trim();
217
218 // Else:
219 } else {
220
221 // Let name equal the substring of s from position 0 to, but not including, position eq.
222 name = s.substring(0, eq);
223
224 // Let name equal the result of percent-decoding name.
225 name = percentDecode(name, charset);
226
227 // Let name equal the result of trimming leading and trailing white-space from name.
228 name = name.trim();
229
230 // Let value equal the substring of s from position eq + 1 to the end of s.
231 value = s.substring(eq + 1);
232
233 // Let value equal the result of percent-decoding value.
234 value = percentDecode(value, charset);
235
236 // Let value equal the result of trimming leading and trailing white-space from value.
237 value = value.trim();
238 }
239
240 // If s is the first element in headers and eq is not a valid position in s and the length
241 // of name is greater than 0:
242 if ((0 == header) && (-1 == eq) && !name.isEmpty()) {
243
244 // Let mimeType equal name.
245 mimeType = name;
246
247 // Else:
248 } else {
249
250 // If eq is not a valid position in s:
251 if (-1 == eq) {
252
253 // If name is found case-insensitively in supportedContentEncodings:
254 final String nameCaseInsensitive = name.toLowerCase(Locale.ENGLISH);
255
256 if (supportedContentEncodings.contains(nameCaseInsensitive)) {
257
258 // If contentEncodingAlreadySet is false:
259 if (!contentEncodingAlreadySet) {
260
261 // Let contentEncoding equal name.
262 contentEncoding = name;
263
264 // Let contentEncodingAlreadySet equal true.
265 contentEncodingAlreadySet = true;
266 }
267 }
268
269 // Else:
270 } else {
271
272 // If the length of value is greater than 0 and name is found case-insensitively
273 // in supportedValues:
274 final String nameCaseInsensitive = name.toLowerCase(Locale.ENGLISH);
275
276 if (!value.isEmpty() && supportedValues.containsKey(nameCaseInsensitive)) {
277
278 // If the corresponding value for name found (case-insensitively) in
279 // supportedValueSetBits is false:
280 boolean valueSet = supportedValueSetBits.get(nameCaseInsensitive);
281
282 if (!valueSet) {
283
284 // Let the corresponding value for name found (case-insensitively)
285 // in supportedValues equal value.
286 supportedValues.put(nameCaseInsensitive, value);
287
288 // Let the corresponding value for name found (case-insensitively)
289 // in supportedValueSetBits equal true.
290 supportedValueSetBits.put(nameCaseInsensitive, true);
291 }
292 }
293 }
294 }
295
296 }
297
298 // Let data be the substring of URI from position comma + 1 to the end of URI.
299 String data = uri.substring(comma + 1);
300
301 // Let data be the result of percent-decoding data.
302 data = percentDecode(data, charset);
303
304 // Let dataURIObject be an object consisting of the mimeType,
305 // contentEncoding, data and supportedValues objects.
306 final String finalMimeType = mimeType;
307 final Charset finalCharset = supportedValues.get(CHARSET_OPTION_NAME).isEmpty()
308 ? null
309 : Charset.forName(supportedValues.get(CHARSET_OPTION_NAME));
310 final String finalFilename = supportedValues.get(FILENAME_OPTION_NAME).isEmpty()
311 ? null
312 : supportedValues.get(FILENAME_OPTION_NAME);
313 final String finalContentDisposition = supportedValues.get(CONTENT_DISPOSITION_OPTION_NAME).isEmpty()
314 ? null
315 : supportedValues.get(CONTENT_DISPOSITION_OPTION_NAME);
316
317 final byte[] finalData;
318 try {
319 finalData = "base64".equalsIgnoreCase(contentEncoding)
320 ? Base64.getMimeDecoder().decode(data)
321 : data.getBytes(charset);
322 } catch (RuntimeException e) {
323 throw new MalformedDataUriException(e);
324 }
325
326 // return dataURIObject.
327 return new DataUri(
328 finalMimeType,
329 finalCharset,
330 finalFilename,
331 finalContentDisposition,
332 finalData);
333 }
334
335 @Override
336 public String toString() {
337 StringBuilder s = new StringBuilder();
338 s.append("data:").append(this.mime()).append(";");
339
340 if (this.charset != null) s.append(CHARSET_OPTION_NAME + "=").append(this.charset.name()).append(";");
341 if (this.contentDisposition != null)
342 s.append(CONTENT_DISPOSITION_OPTION_NAME + "=").append(this.contentDisposition).append(";");
343 if (this.filename != null) s.append(FILENAME_OPTION_NAME + "=").append(this.filename).append(";");
344
345 s.append("base64,").append(new String(Base64.getEncoder().encode(this.data()), StandardCharsets.UTF_8));
346
347 return s.toString();
348 }
349
350 private static final Pattern PLUS = Pattern.compile("+", Pattern.LITERAL);
351
352 private static String percentDecode(String s, Charset cs) {
353 try {
354 // We only need to decode %hh escape sequences, while
355 // URLDecoder.decode in addition to that also replaces '+' with space.
356 // As a workaround we first replace all pluses with %2B sequence,
357 // so that they are preserved after decoding.
358 s = PLUS.matcher(s).replaceAll("%2B");
359
360 return URLDecoder.decode(s, cs.name());
361 } catch (UnsupportedEncodingException e) {
362 throw new IllegalStateException("Charset `" + cs.name() + "' not supported", e);
363 }
364 }
365 }