summaryrefslogtreecommitdiffstats
path: root/luni/src/main/java/libcore/net/url/FileURLConnection.java
blob: 43eaa7df3183f7acc6a08e220780b5389c05c0ce (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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/*
 *  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 libcore.net.url;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import libcore.net.UriCodec;

/**
 * This subclass extends <code>URLConnection</code>.
 * <p>
 * This class is responsible for connecting, getting content and input stream of
 * the file.
 */
public class FileURLConnection extends URLConnection {

    private static final Comparator<String> HEADER_COMPARATOR = new Comparator<String>() {
        @Override
        public int compare(String a, String b) {
            if (a == b) {
                return 0;
            } else if (a == null) {
                return -1;
            } else if (b == null) {
                return 1;
            } else {
                return String.CASE_INSENSITIVE_ORDER.compare(a, b);
            }
        }
    };

    private String filename;

    private InputStream is;

    private long length = -1;

    private long lastModified = -1;

    private boolean isDir;

    private FilePermission permission;

    /**
     * A set of three key value pairs representing the headers we support.
     */
    private final String[] headerKeysAndValues;

    private static final int CONTENT_TYPE_VALUE_IDX = 1;
    private static final int CONTENT_LENGTH_VALUE_IDX = 3;
    private static final int LAST_MODIFIED_VALUE_IDX = 5;

    private Map<String, List<String>> headerFields;

    /**
     * Creates an instance of <code>FileURLConnection</code> for establishing
     * a connection to the file pointed by this <code>URL<code>
     *
     * @param url The URL this connection is connected to
     */
    public FileURLConnection(URL url) {
        super(url);
        filename = url.getFile();
        if (filename == null) {
            filename = "";
        }
        filename = UriCodec.decode(filename);
        headerKeysAndValues = new String[] {
                "content-type", null,
                "content-length", null,
                "last-modified", null };
    }

    /**
     * This methods will attempt to obtain the input stream of the file pointed
     * by this <code>URL</code>. If the file is a directory, it will return
     * that directory listing as an input stream.
     *
     * @throws IOException
     *             if an IO error occurs while connecting
     */
    @Override
    public void connect() throws IOException {
        File f = new File(filename);
        IOException error = null;
        if (f.isDirectory()) {
            isDir = true;
            is = getDirectoryListing(f);
            // use -1 for the contentLength
            lastModified = f.lastModified();
            headerKeysAndValues[CONTENT_TYPE_VALUE_IDX] = "text/html";
        } else {
            try {
                is = new BufferedInputStream(new FileInputStream(f));
            } catch (IOException ioe) {
                error = ioe;
            }

            if (error == null) {
                length = f.length();
                lastModified = f.lastModified();
                headerKeysAndValues[CONTENT_TYPE_VALUE_IDX] = getContentTypeForPlainFiles();
            } else {
                headerKeysAndValues[CONTENT_TYPE_VALUE_IDX] = "content/unknown";
            }
        }

        headerKeysAndValues[CONTENT_LENGTH_VALUE_IDX] = String.valueOf(length);
        headerKeysAndValues[LAST_MODIFIED_VALUE_IDX] = String.valueOf(lastModified);

        connected = true;
        if (error != null) {
            throw error;
        }
    }

    @Override
    public String getHeaderField(String key) {
        if (!connected) {
            try {
                connect();
            } catch (IOException ioe) {
                return null;
            }
        }

        for (int i = 0; i < headerKeysAndValues.length; i += 2) {
            if (headerKeysAndValues[i].equalsIgnoreCase(key)) {
                return headerKeysAndValues[i + 1];
            }
        }

        return null;
    }

    @Override
    public String getHeaderFieldKey(int position) {
        if (!connected) {
            try {
                connect();
            } catch (IOException ioe) {
                return null;
            }
        }

        if (position < 0 || position > headerKeysAndValues.length / 2) {
            return null;
        }

        return headerKeysAndValues[position * 2];
    }

    @Override
    public String getHeaderField(int position) {
        if (!connected) {
            try {
                connect();
            } catch (IOException ioe) {
                return null;
            }
        }

        if (position < 0 || position > headerKeysAndValues.length / 2) {
            return null;
        }

        return headerKeysAndValues[(position * 2) + 1];
    }

    @Override
    public Map<String, List<String>> getHeaderFields() {
        if (headerFields == null) {
            final TreeMap<String, List<String>> headerFieldsMap = new TreeMap<>(HEADER_COMPARATOR);

            for (int i = 0; i < headerKeysAndValues.length; i+=2) {
                headerFieldsMap.put(headerKeysAndValues[i],
                        Collections.singletonList(headerKeysAndValues[i + 1]));
            }

            headerFields = Collections.unmodifiableMap(headerFieldsMap);
        }

        return headerFields;
    }

    /**
     * Returns the length of the file in bytes, or {@code -1} if the length cannot be
     * represented as an {@code int}. See {@link #getContentLengthLong()} for a method that can
     * handle larger files.
     */
    @Override
    public int getContentLength() {
        long length = getContentLengthLong();
        return length <= Integer.MAX_VALUE ? (int) length : -1;
    }

    /**
     * Returns the length of the file in bytes.
     */
    private long getContentLengthLong() {
        try {
            if (!connected) {
                connect();
            }
        } catch (IOException e) {
            // default is -1
        }
        return length;
    }

    /**
     * Returns the content type of the resource. Just takes a guess based on the
     * name.
     *
     * @return the content type
     */
    @Override
    public String getContentType() {
        // The content-type header field is always at position 0.
        return getHeaderField(0);
    }

    private String getContentTypeForPlainFiles() {
        String result = guessContentTypeFromName(url.getFile());
        if (result != null) {
            return result;
        }

        try {
            result = guessContentTypeFromStream(is);
        } catch (IOException e) {
            // Ignore
        }
        if (result != null) {
            return result;
        }

        return "content/unknown";
    }

    /**
     * Returns the directory listing of the file component as an input stream.
     *
     * @return the input stream of the directory listing
     */
    private InputStream getDirectoryListing(File f) {
        String fileList[] = f.list();
        ByteArrayOutputStream bytes = new java.io.ByteArrayOutputStream();
        PrintStream out = new PrintStream(bytes);
        out.print("<title>Directory Listing</title>\n");
        out.print("<base href=\"file:");
        out.print(f.getPath().replace('\\', '/') + "/\"><h1>" + f.getPath()
                + "</h1>\n<hr>\n");
        int i;
        for (i = 0; i < fileList.length; i++) {
            out.print(fileList[i] + "<br>\n");
        }
        out.close();
        return new ByteArrayInputStream(bytes.toByteArray());
    }

    /**
     * Returns the input stream of the object referred to by this
     * <code>URLConnection</code>
     *
     * File Sample : "/ZIP211/+/harmony/tools/javac/resources/javac.properties"
     * Invalid File Sample:
     * "/ZIP/+/harmony/tools/javac/resources/javac.properties"
     * "ZIP211/+/harmony/tools/javac/resources/javac.properties"
     *
     * @return input stream of the object
     *
     * @throws IOException
     *             if an IO error occurs
     */
    @Override
    public InputStream getInputStream() throws IOException {
        if (!connected) {
            connect();
        }
        return is;
    }

    /**
     * Returns the permission, in this case the subclass, FilePermission object
     * which represents the permission necessary for this URLConnection to
     * establish the connection.
     *
     * @return the permission required for this URLConnection.
     *
     * @throws IOException
     *             if an IO exception occurs while creating the permission.
     */
    @Override
    public java.security.Permission getPermission() throws IOException {
        if (permission == null) {
            String path = filename;
            if (File.separatorChar != '/') {
                path = path.replace('/', File.separatorChar);
            }
            permission = new FilePermission(path, "read");
        }
        return permission;
    }
}