01: package com.xoetrope.deploy;
02:
03: import java.io.BufferedInputStream;
04: import java.io.BufferedOutputStream;
05: import java.io.File;
06: import java.io.FileOutputStream;
07: import java.io.OutputStream;
08: import java.net.URL;
09: import java.text.ParseException;
10: import java.text.SimpleDateFormat;
11: import java.util.Date;
12: import java.util.Locale;
13: import net.xoetrope.xui.build.BuildProperties;
14:
15: /**
16: * A utility to download a file and store it in the local files system. It is
17: * required that the application is signed for this to work
18: *
19: * <p> Copyright (c) Xoetrope Ltd., 2001-2007, This software is licensed under
20: * the GNU Public License (GPL), please see license.txt for more details. If
21: * you make commercial use of this software you must purchase a commercial
22: * license from Xoetrope.</p>
23: */
24: public class XUrlResourceStorageService {
25: public static boolean storeFile(URL src, File dest) {
26: byte[] fileBytes = new byte[0];
27:
28: try {
29: dest.getParentFile().mkdirs();
30:
31: // Check the file date
32: // See http://www.w3.org/Protocols/HTTP/1.0/draft-ietf-http-spec.html#DateFormats
33: // for a description of the date formats
34: String lm = src.openConnection().getHeaderField(
35: "Last-Modified");
36: Date lmd = null;
37: if (lm != null) {
38: String[] formats = { "EEE, d MMM yyyy HH:mm:ss Z",
39: "EEEE, d-MMM-yyyy HH:mm:ss Z",
40: "EEE MMM d HH:mm:ss yyyy" };
41: for (int i = 0; i < formats.length; i++) {
42: SimpleDateFormat sdf = new SimpleDateFormat(
43: formats[i], Locale.ENGLISH);
44: try {
45: lmd = sdf.parse(lm);
46: break;
47: } catch (ParseException ex) {
48: }
49: }
50: } else
51: return true;
52:
53: if ((lmd != null) && dest.exists()) {
54: if (dest.lastModified() >= lmd.getTime())
55: return true;
56: }
57:
58: BufferedInputStream is = new BufferedInputStream(src
59: .openStream());
60: byte[] b = new byte[1024];
61:
62: if (is != null) {
63: OutputStream fos = new BufferedOutputStream(
64: new FileOutputStream(dest));
65: int i = is.read(b);
66: while (i != -1) {
67: fileBytes = new byte[i];
68: System.arraycopy(b, 0, fileBytes, 0, i);
69: fos.write(fileBytes);
70: b = new byte[1024];
71: i = is.read(b);
72: }
73: fos.flush();
74: fos.close();
75: } else
76: return false;
77: } catch (Exception ex) {
78: if (BuildProperties.DEBUG)
79: ex.printStackTrace();
80: return false;
81: }
82:
83: return true;
84: }
85: }
|