aboutsummaryrefslogtreecommitdiffstats
path: root/framework/src/ant/apache-ant-1.9.6/src/main/org/apache/tools/ant/types/resources/URLResource.java
blob: 70d6c9baae62d1ab8063dbe96d3d1873e56dd123 (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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/*
 *  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.tools.ant.types.resources;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Reference;
import org.apache.tools.ant.types.Resource;
import org.apache.tools.ant.util.FileUtils;

/**
 * Exposes a URL as a Resource.
 * @since Ant 1.7
 */
public class URLResource extends Resource implements URLProvider {
    private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
    private static final int NULL_URL
        = Resource.getMagicNumber("null URL".getBytes());

    private URL url;
    private URLConnection conn;
    private URL baseURL;
    private String relPath;

    /**
     * Default constructor.
     */
    public URLResource() {
    }

    /**
     * Convenience constructor.
     * @param u the URL to expose.
     */
    public URLResource(URL u) {
        setURL(u);
    }

    /**
     * Convenience constructor.
     * @param u holds the URL to expose.
     */
    public URLResource(URLProvider u) {
        setURL(u.getURL());
    }

    /**
     * Convenience constructor.
     * @param f the File to set as a URL.
     */
    public URLResource(File f) {
        setFile(f);
    }

    /**
     * String constructor for Ant attribute introspection.
     * @param u String representation of this URL.
     * @see org.apache.tools.ant.IntrospectionHelper
     */
    public URLResource(String u) {
        this(newURL(u));
    }

    /**
     * Set the URL for this URLResource.
     * @param u the URL to expose.
     */
    public synchronized void setURL(URL u) {
        checkAttributesAllowed();
        url = u;
    }

    /**
     * Set the URL from a File.
     * @param f the File to set as a URL.
     */
    public synchronized void setFile(File f) {
        try {
            setURL(FILE_UTILS.getFileURL(f));
        } catch (MalformedURLException e) {
            throw new BuildException(e);
        }
    }

    /**
     * Base URL which combined with the relativePath attribute defines
     * the URL.
     * @since Ant 1.8.0
     */
    public synchronized void setBaseURL(URL base) {
        checkAttributesAllowed();
        if (url != null) {
            throw new BuildException("can't define URL and baseURL attribute");
        }
        baseURL = base;
    }

    /**
     * Relative path which combined with the baseURL attribute defines
     * the URL.
     * @since Ant 1.8.0
     */
    public synchronized void setRelativePath(String r) {
        checkAttributesAllowed();
        if (url != null) {
            throw new BuildException("can't define URL and relativePath"
                                     + " attribute");
        }
        relPath = r;
    }


    /**
     * Get the URL used by this URLResource.
     * @return a URL object.
     */
    public synchronized URL getURL() {
        if (isReference()) {
            return ((URLResource) getCheckedRef()).getURL();
        }
        if (url == null) {
            if (baseURL != null) {
                if (relPath == null) {
                    throw new BuildException("must provide relativePath"
                                             + " attribute when using baseURL.");
                }
                try {
                    url = new URL(baseURL, relPath);
                } catch (MalformedURLException e) {
                    throw new BuildException(e);
                }
            }
        }
        return url;
     }

    /**
     * Overrides the super version.
     * @param r the Reference to set.
     */
    public synchronized void setRefid(Reference r) {
        //not using the accessor in this case to avoid side effects
        if (url != null || baseURL != null || relPath != null) {
            throw tooManyAttributes();
        }
        super.setRefid(r);
    }

    /**
     * Get the name of this URLResource
     * (its file component minus the leading separator).
     * @return the name of this resource.
     */
    public synchronized String getName() {
        if (isReference()) {
            return ((Resource) getCheckedRef()).getName();
        }
        String name = getURL().getFile();
        return "".equals(name) ? name : name.substring(1);
    }

    /**
     * Return this URLResource formatted as a String.
     * @return a String representation of this URLResource.
     */
    public synchronized String toString() {
        return isReference()
            ? getCheckedRef().toString() : String.valueOf(getURL());
    }

    /**
     * Find out whether the URL exists .
     * @return true if this resource exists.
     */
    public synchronized boolean isExists() {
        if (isReference()) {
            return ((Resource) getCheckedRef()).isExists();
        }
        return isExists(false);
    }

    /**
     * Find out whether the URL exists, and close the connection
     * opened to the URL if closeConnection is true.
     *
     * Note that this method does ensure that if:
     * - the resource exists (if it returns true)
     * - and if the current object is not a reference
     * (isReference() returns false)
     * - and if it was called with closeConnection to false,
     *
     * then the connection to the URL (stored in the conn
     * private field) will be opened, and require to be closed
     * by the caller.
     *
     * @param closeConnection true if the connection should be closed
     * after the call, false if it should stay open.
     * @return true if this resource exists.
     */
    private synchronized boolean isExists(boolean closeConnection) {
        if (getURL() == null) {
            return false;
        }
        try {
            connect(Project.MSG_VERBOSE);
            if (conn instanceof HttpURLConnection) {
                int sc = ((HttpURLConnection) conn).getResponseCode();
                // treating inaccessible resources as non-existent
                return sc < 400;
            } else if (url.getProtocol().startsWith("ftp")) {
                closeConnection = true;
                InputStream in = null;
                try {
                    in = conn.getInputStream();
                } finally {
                    FileUtils.close(in);
                }
            }
            return true;
        } catch (IOException e) {
            return false;
        } finally {
            if (closeConnection) {
                close();
            }
        }
    }


    /**
     * Tells the modification time in milliseconds since 01.01.1970 .
     *
     * @return 0 if the resource does not exist to mirror the behavior
     * of {@link java.io.File File}.
     */
    public synchronized long getLastModified() {
        if (isReference()) {
            return ((Resource) getCheckedRef()).getLastModified();
        }
        if (!isExists(false)) {
            return UNKNOWN_DATETIME;
        }
        return withConnection(new ConnectionUser() {
                public long useConnection(URLConnection c) {
                    return conn.getLastModified();
                }
            }, UNKNOWN_DATETIME);
    }

    /**
     * Tells if the resource is a directory.
     * @return boolean whether the resource is a directory.
     */
    public synchronized boolean isDirectory() {
        return isReference()
            ? ((Resource) getCheckedRef()).isDirectory()
            : getName().endsWith("/");
    }

    /**
     * Get the size of this Resource.
     * @return the size, as a long, 0 if the Resource does not exist (for
     *         compatibility with java.io.File), or UNKNOWN_SIZE if not known.
     */
    public synchronized long getSize() {
        if (isReference()) {
            return ((Resource) getCheckedRef()).getSize();
        }
        if (!isExists(false)) {
            return 0L;
        }
        return withConnection(new ConnectionUser() {
                public long useConnection(URLConnection c) {
                    return conn.getContentLength();
                }
            }, UNKNOWN_SIZE);
    }

    /**
     * Test whether an Object equals this URLResource.
     * @param another the other Object to compare.
     * @return true if the specified Object is equal to this Resource.
     */
    public synchronized boolean equals(Object another) {
        if (this == another) {
            return true;
        }
        if (isReference()) {
            return getCheckedRef().equals(another);
        }
        if (another == null || !(another.getClass().equals(getClass()))) {
            return false;
        }
        URLResource otheru = (URLResource) another;
        return getURL() == null
            ? otheru.getURL() == null
            : getURL().equals(otheru.getURL());
    }

    /**
     * Get the hash code for this Resource.
     * @return hash code as int.
     */
    public synchronized int hashCode() {
        if (isReference()) {
            return getCheckedRef().hashCode();
        }
        return MAGIC * ((getURL() == null) ? NULL_URL : getURL().hashCode());
    }

    /**
     * Get an InputStream for the Resource.
     * @return an InputStream containing this Resource's content.
     * @throws IOException if unable to provide the content of this
     *         Resource as a stream.
     * @throws UnsupportedOperationException if InputStreams are not
     *         supported for this Resource type.
     */
    public synchronized InputStream getInputStream() throws IOException {
        if (isReference()) {
            return ((Resource) getCheckedRef()).getInputStream();
        }
        connect();
        try {
            return conn.getInputStream();
        } finally {
            conn = null;
        }
    }

    /**
     * Get an OutputStream for the Resource.
     * @return an OutputStream to which content can be written.
     * @throws IOException if unable to provide the content of this
     *         Resource as a stream.
     * @throws UnsupportedOperationException if OutputStreams are not
     *         supported for this Resource type.
     * @throws IOException if the URL cannot be opened.
     */
    public synchronized OutputStream getOutputStream() throws IOException {
        if (isReference()) {
            return ((Resource) getCheckedRef()).getOutputStream();
        }
        connect();
        try {
            return conn.getOutputStream();
        } finally {
            conn = null;
        }
    }

    /**
     * Ensure that we have a connection.
     * @throws IOException if the connection cannot be established.
     */
    protected void connect() throws IOException {
        connect(Project.MSG_ERR);
    }

    /**
     * Ensure that we have a connection.
     * @param logLevel severity to use when logging connection errors.
     * Should be one of the <code>MSG_</code> constants in {@link
     * Project Project}.
     * @throws IOException if the connection cannot be established.
     * @since Ant 1.8.2
     */
    protected synchronized void connect(int logLevel) throws IOException {
        URL u = getURL();
        if (u == null) {
            throw new BuildException("URL not set");
        }
        if (conn == null) {
            try {
                conn = u.openConnection();
                conn.connect();
            } catch (IOException e) {
                log(e.toString(), logLevel);
                conn = null;
                throw e;
            }
        }
    }

    /**
     * Closes the URL connection if:
     * - it is opened (i.e. the field conn is not null)
     * - this type of URLConnection supports some sort of close mechanism
     *
     * This method ensures the field conn will be null after the call.
     *
     */
    private synchronized void close() {
        try {
            FileUtils.close(conn);
        } finally {
            conn = null;
        }
    }

    private static URL newURL(String u) {
        try {
            return new URL(u);
        } catch (MalformedURLException e) {
            throw new BuildException(e);
        }
    }

    private interface ConnectionUser {
        long useConnection(URLConnection c);
    }

    private long withConnection(ConnectionUser u, long defaultValue) {
        try {
            if (conn != null) {
                return u.useConnection(conn);
            } else {
                try {
                    connect();
                    return u.useConnection(conn);
                } finally {
                    close();
                }
            }
        } catch (IOException ex) {
            return defaultValue;
        }
    }
}