Debian Codegraph @

src/com/bulenkov/iconloader/util/URLUtil.java

raw symbols SCIP
1 /*
2 * Copyright 2000-2014 JetBrains s.r.o.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.bulenkov.iconloader.util;
18
19 import java.io.*;
20 import java.net.MalformedURLException;
21 import java.net.URL;
22 import java.nio.charset.Charset;
23 import java.util.ArrayList;
24 import java.util.regex.Matcher;
25 import java.util.regex.Pattern;
26 import java.util.zip.ZipEntry;
27 import java.util.zip.ZipFile;
28
29 /**
30 * @author Konstantin Bulenkov
31 */
32 public class URLUtil {
33 public static final String SCHEME_SEPARATOR = "://";
34 public static final String FILE_PROTOCOL = "file";
35 public static final String HTTP_PROTOCOL = "http";
36 public static final String JAR_PROTOCOL = "jar";
37 public static final String JAR_SEPARATOR = "!/";
38
39 public static final Pattern DATA_URI_PATTERN = Pattern.compile("data:([^,;]+/[^,;]+)(;charset=[^,;]+)?(;base64)?,(.+)");
40
41 private URLUtil() {
42 }
43
44 /**
45 * Opens a url stream. The semantics is the sames as {@link java.net.URL#openStream()}. The
46 * separate method is needed, since jar URLs open jars via JarFactory and thus keep them
47 * mapped into memory.
48 */
49
50 public static InputStream openStream(URL url) throws IOException {
51 String protocol = url.getProtocol();
52 boolean isFile = protocol.equals(JAR_PROTOCOL) && !url.getFile().startsWith(HTTP_PROTOCOL);
53 return isFile ? openJarStream(url) : url.openStream();
54 }
55
56
57 public static InputStream openResourceStream(final URL url) throws IOException {
58 try {
59 return openStream(url);
60 } catch (FileNotFoundException ex) {
61 final String protocol = url.getProtocol();
62 String file = null;
63 if (protocol.equals(FILE_PROTOCOL)) {
64 file = url.getFile();
65 } else if (protocol.equals(JAR_PROTOCOL)) {
66 int pos = url.getFile().indexOf("!");
67 if (pos >= 0) {
68 file = url.getFile().substring(pos + 1);
69 }
70 }
71 if (file != null && file.startsWith("/")) {
72 InputStream resourceStream = URLUtil.class.getResourceAsStream(file);
73 if (resourceStream != null) return resourceStream;
74 }
75 throw ex;
76 }
77 }
78
79
80 private static InputStream openJarStream(URL url) throws IOException {
81 Pair<String, String> paths = splitJarUrl(url.getFile());
82 if (paths == null) {
83 throw new MalformedURLException(url.getFile());
84 }
85
86 @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") final ZipFile zipFile = new ZipFile(unquote(paths.first));
87 ZipEntry zipEntry = zipFile.getEntry(paths.second);
88 if (zipEntry == null) {
89 throw new FileNotFoundException("Entry " + paths.second + " not found in " + paths.first);
90 }
91
92 return new FilterInputStream(zipFile.getInputStream(zipEntry)) {
93 @Override
94 public void close() throws IOException {
95 super.close();
96 zipFile.close();
97 }
98 };
99 }
100
101 public static String unquote(String urlString) {
102 urlString = urlString.replace('/', File.separatorChar);
103 return unescapePercentSequences(urlString);
104 }
105
106
107 public static Pair<String, String> splitJarUrl(String fullPath) {
108 int delimiter = fullPath.indexOf(JAR_SEPARATOR);
109 if (delimiter >= 0) {
110 String resourcePath = fullPath.substring(delimiter + 2);
111 String jarPath = fullPath.substring(0, delimiter);
112 if (StringUtil.startsWithConcatenation(jarPath, FILE_PROTOCOL, ":")) {
113 jarPath = jarPath.substring(FILE_PROTOCOL.length() + 1);
114 return Pair.create(jarPath, resourcePath);
115 }
116 }
117 return null;
118 }
119
120
121 public static String unescapePercentSequences(String s) {
122 if (s.indexOf('%') == -1) {
123 return s;
124 }
125
126 StringBuilder decoded = new StringBuilder();
127 final int len = s.length();
128 int i = 0;
129 while (i < len) {
130 char c = s.charAt(i);
131 if (c == '%') {
132 ArrayList<Integer> bytes = new ArrayList<Integer>();
133 while (i + 2 < len && s.charAt(i) == '%') {
134 final int d1 = decode(s.charAt(i + 1));
135 final int d2 = decode(s.charAt(i + 2));
136 if (d1 != -1 && d2 != -1) {
137 bytes.add(((d1 & 0xf) << 4 | d2 & 0xf));
138 i += 3;
139 } else {
140 break;
141 }
142 }
143 if (!bytes.isEmpty()) {
144 final byte[] bytesArray = new byte[bytes.size()];
145 for (int j = 0; j < bytes.size(); j++) {
146 bytesArray[j] = bytes.get(j).byteValue();
147 }
148 decoded.append(new String(bytesArray, Charset.forName("UTF-8")));
149 continue;
150 }
151 }
152
153 decoded.append(c);
154 i++;
155 }
156 return decoded.toString();
157 }
158
159 private static int decode(char c) {
160 if ((c >= '0') && (c <= '9'))
161 return c - '0';
162 if ((c >= 'a') && (c <= 'f'))
163 return c - 'a' + 10;
164 if ((c >= 'A') && (c <= 'F'))
165 return c - 'A' + 10;
166 return -1;
167 }
168
169 public static boolean containsScheme(String url) {
170 return url.contains(SCHEME_SEPARATOR);
171 }
172
173 public static boolean isDataUri(String value) {
174 return !value.isEmpty() && value.startsWith("data:", value.charAt(0) == '"' || value.charAt(0) == '\'' ? 1 : 0);
175 }
176
177 /**
178 * Extracts byte array from given data:URL string.
179 * data:URL will be decoded from base64 if it contains the marker of base64 encoding.
180 *
181 * @param dataUrl data:URL-like string (may be quoted)
182 * @return extracted byte array or {@code null} if it cannot be extracted.
183 */
184
185 public static byte[] getBytesFromDataUri(String dataUrl) {
186 Matcher matcher = DATA_URI_PATTERN.matcher(StringUtil.stripQuotesAroundValue(dataUrl));
187 if (matcher.matches()) {
188 try {
189 String content = matcher.group(4);
190 final Charset charset = Charset.forName("UTF-8");
191 final byte[] bytes = content.getBytes(charset);
192 return ";base64".equalsIgnoreCase(matcher.group(3)) ? Base64Converter.decode(bytes) : bytes;
193 } catch (IllegalArgumentException e) {
194 return null;
195 }
196 }
197 return null;
198 }
199 }