e.g. Calendar Search Help
You must enter a value before pressing Search
ant

Class: org.apache.tools.ant.taskdefs.Get   ©

 OK to copy?
001 /*
002  * Copyright  2000-2004 The Apache Software Foundation
003  *
004  *  Licensed under the Apache License, Version 2.0 (the "License");
005  *  you may not use this file except in compliance with the License.
006  *  You may obtain a copy of the License at
007  *
008  *      http://www.apache.org/licenses/LICENSE-2.0
009  *
010  *  Unless required by applicable law or agreed to in writing, software
011  *  distributed under the License is distributed on an "AS IS" BASIS,
012  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013  *  See the License for the specific language governing permissions and
014  *  limitations under the License.
015  *
016  */
017 
018 package org.apache.tools.ant.taskdefs;
019 
020 import java.io.File;
021 import java.io.FileOutputStream;
022 import java.io.IOException;
023 import java.io.InputStream;
024 import java.net.HttpURLConnection;
025 import java.net.URL;
026 import java.net.URLConnection;
027 import java.util.Date;
028 import org.apache.tools.ant.BuildException;
029 import org.apache.tools.ant.Project;
030 import org.apache.tools.ant.Task;
031 import org.apache.tools.ant.util.FileUtils;
032 import org.apache.tools.ant.util.JavaEnvUtils;
033 
034 /**
035  * Gets a particular file from a URL source.
036  * Options include verbose reporting, timestamp based fetches and controlling
037  * actions on failures. NB: access through a firewall only works if the whole
038  * Java runtime is correctly configured.
039  *
040  *
041  * @since Ant 1.1
042  *
043  * @ant.task category="network"
044  */
045 public class Get extends Task {
046     private URL source; // required
047     private File dest; // required
048     private boolean verbose = false;
049     private boolean useTimestamp = false; //off by default
050     private boolean ignoreErrors = false;
051     private String uname = null;
052     private String pword = null;
053 
054 
055     /**
056      * Does the work.
057      *
058      * @exception BuildException Thrown in unrecoverable error.
059      */
060     public void execute() throws BuildException {
061         if (source == null) {
062             throw new BuildException("src attribute is required", getLocation());
063         }
064 
065         if (dest == null) {
066             throw new BuildException("dest attribute is required", getLocation());
067         }
068 
069         if (dest.exists() && dest.isDirectory()) {
070             throw new BuildException("The specified destination is a directory",
071                                      getLocation());
072         }
073 
074         if (dest.exists() && !dest.canWrite()) {
075             throw new BuildException("Can't write to " + dest.getAbsolutePath(),
076                                      getLocation());
077         }
078 
079         try {
080 
081             log("Getting: " + source);
082 
083             //set the timestamp to the file date.
084             long timestamp = 0;
085 
086             boolean hasTimestamp = false;
087             if (useTimestamp && dest.exists()) {
088                 timestamp = dest.lastModified();
089                 if (verbose) {
090                     Date t = new Date(timestamp);
Rate091                     log("local file date : " + t.toString());
092                 }
093 
094                 hasTimestamp = true;
095             }
096 
097             //set up the URL connection
098             URLConnection connection = source.openConnection();
099             //modify the headers
100             //NB: things like user authentication could go in here too.
101             if (useTimestamp && hasTimestamp) {
102                 connection.setIfModifiedSince(timestamp);
103             }
104             // prepare Java 1.1 style credentials
105             if (uname != null || pword != null) {
106                 String up = uname + ":" + pword;
107                 String encoding;
108                 // check to see if sun's Base64 encoder is available.
109                 try {
110                     Object encoder =
111                             Class.forName("sun.misc.BASE64Encoder").newInstance();
112                     encoding = (String)
113                             encoder.getClass().getMethod("encode", new Class[] {byte[].class})
114                             .invoke(encoder, new Object[] {up.getBytes()});
115 
116                 } catch (Exception ex) { // sun's base64 encoder isn't available
117                     Base64Converter encoder = new Base64Converter();
118                     encoding = encoder.encode(up.getBytes());
119                 }
120                 connection.setRequestProperty ("Authorization",
121                                                "Basic " + encoding);
122             }
123 
124             //connect to the remote site (may take some time)
125             connection.connect();
126             //next test for a 304 result (HTTP only)
127             if (connection instanceof HttpURLConnection) {
128                 HttpURLConnection httpConnection
129                     = (HttpURLConnection) connection;
130                 if (httpConnection.getResponseCode()
131                     == HttpURLConnection.HTTP_NOT_MODIFIED)  {
132                     //not modified so no file download. just return
133                     //instead and trace out something so the user
134                     //doesn't think that the download happened when it
135                     //didn't
136                     log("Not modified - so not downloaded");
137                     return;
138                 }
139                 // test for 401 result (HTTP only)
140                 if (httpConnection.getResponseCode()
141                     == HttpURLConnection.HTTP_UNAUTHORIZED)  {
142                     String message = "HTTP Authorization failure";
143                     if (ignoreErrors) {
144                         log(message, Project.MSG_WARN);
145                         return;
146                     } else {
147                         throw new BuildException(message);
148                     }
149                 }
150 
151             }
152 
153             //REVISIT: at this point even non HTTP connections may
154             //support the if-modified-since behaviour -we just check
155             //the date of the content and skip the write if it is not
156             //newer. Some protocols (FTP) don't include dates, of
157             //course.
158 
159             InputStream is = null;
160             for (int i = 0; i < 3; i++) {
161                 try {
162                     is = connection.getInputStream();
163                     break;
164                 } catch (IOException ex) {
165                     log("Error opening connection " + ex);
166                 }
167             }
168             if (is == null) {
169                 log("Can't get " + source + " to " + dest);
170                 if (ignoreErrors) {
171                     return;
172                 }
173                 throw new BuildException("Can't get " + source + " to " + dest,
174                                          getLocation());
175             }
176 
177             FileOutputStream fos = new FileOutputStream(dest);
178             boolean finished = false;
179             try {
180                 byte[] buffer = new byte[100 * 1024];
181                 int length;
182                 int dots = 0;
183 
184                 while ((length = is.read(buffer)) >= 0) {
185                     fos.write(buffer, 0, length);
186                     if (verbose) {
187                         System.out.print(".");
188                         if (dots++ > 50) {
189                             System.out.flush();
190                             dots = 0;
191                         }
192                     }
193                 }
194                 if (verbose) {
195                     System.out.println();
196                 }
197                 finished = true;
198             } finally {
199                 if (fos != null) {
200                     fos.close();
201                 }
202                 is.close();
203                 // we have started to (over)write dest, but failed.
204                 // Try to delete the garbage we'd otherwise leave
205                 // behind.
206                 if (!finished) {
207                     dest.delete();
208                 }
209             }
210 
211             //if (and only if) the use file time option is set, then
212             //the saved file now has its timestamp set to that of the
213             //downloaded file
214             if (useTimestamp)  {
215                 long remoteTimestamp = connection.getLastModified();
216                 if (verbose)  {
217                     Date t = new Date(remoteTimestamp);
Rate218                     log("last modified = " + t.toString()
219                         + ((remoteTimestamp == 0)
220                           ? " - using current time instead"
221                           : ""));
222                 }
223                 if (remoteTimestamp != 0) {
224                     FileUtils.newFileUtils()
225                         .setFileLastModified(dest, remoteTimestamp);
226                 }
227             }
228         } catch (IOException ioe) {
229             log("Error getting " + source + " to " + dest);
230             if (ignoreErrors) {
231                 return;
232             }
233             throw new BuildException(ioe, getLocation());
234         }
235     }
236 
237     /**
238      * Set the URL to get.
239      *
240      * @param u URL for the file.
241      */
242     public void setSrc(URL u) {
243         this.source = u;
244     }
245 
246     /**
247      * Where to copy the source file.
248      *
249      * @param dest Path to file.
250      */
251     public void setDest(File dest) {
252         this.dest = dest;
253     }
254 
255     /**
256      * If true, show verbose progress information.
257      *
258      * @param v if "true" then be verbose
259      */
260     public void setVerbose(boolean v) {
261         verbose = v;
262     }
263 
264     /**
265      * If true, log errors but do not treat as fatal.
266      *
267      * @param v if "true" then don't report download errors up to ant
268      */
269     public void setIgnoreErrors(boolean v) {
270         ignoreErrors = v;
271     }
272 
273     /**
274      * If true, conditionally download a file based on the timestamp
275      * of the local copy.
276      *
277      * <p>In this situation, the if-modified-since header is set so
278      * that the file is only fetched if it is newer than the local
279      * file (or there is no local file) This flag is only valid on
280      * HTTP connections, it is ignored in other cases.  When the flag
281      * is set, the local copy of the downloaded file will also have
282      * its timestamp set to the remote file time.</p>
283      *
284      * <p>Note that remote files of date 1/1/1970 (GMT) are treated as
285      * 'no timestamp', and web servers often serve files with a
286      * timestamp in the future by replacing their timestamp with that
287      * of the current time. Also, inter-computer clock differences can
288      * cause no end of grief.</p>
289      * @param v "true" to enable file time fetching
290      */
291     public void setUseTimestamp(boolean v) {
292         if (!JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_1)) {
293             useTimestamp = v;
294         }
295     }
296 
297 
298     /**
299      * Username for basic auth.
300      *
301      * @param u username for authentication
302      */
303     public void setUsername(String u) {
304         this.uname = u;
305     }
306 
307     /**
308      * password for the basic authentication.
309      *
310      * @param p password for authentication
311      */
312     public void setPassword(String p) {
313         this.pword = p;
314     }
315 
316     /*********************************************************************
317     * BASE 64 encoding of a String or an array of bytes.
318     *
319     * Based on RFC 1421.
320     *
321     *********************************************************************/
322 
323     private static class  Base64Converter {
324 
325         public final char [ ]  alphabet = {
326             'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',   //  0 to  7
327             'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',   //  8 to 15
328             'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',   // 16 to 23
329             'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',   // 24 to 31
330             'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',   // 32 to 39
331             'o', 'p', 'q', 'r', 's', 't', 'u', 'v',   // 40 to 47
332             'w', 'x', 'y', 'z', '0', '1', '2', '3',   // 48 to 55
333             '4', '5', '6', '7', '8', '9', '+', '/' }; // 56 to 63
334 
335 
336         public String  encode(String  s) {
337             return encode (s.getBytes());
338         }
339 
340         public String  encode(byte[ ] octetString) {
341             int  bits24;
342             int  bits6;
343 
344             char [ ]  out
345               = new char[((octetString.length - 1) / 3 + 1) * 4];
346 
347             int outIndex = 0;
348             int i = 0;
349 
350             while ((i + 3) <= octetString.length) {
351                 // store the octets
352                 bits24 = (octetString[i++] & 0xFF) << 16;
353                 bits24 |= (octetString[i++] & 0xFF) << 8;
354 
355                 bits6 = (bits24 & 0x00FC0000) >> 18;
356                 out[outIndex++] = alphabet[bits6];
357                 bits6 = (bits24 & 0x0003F000) >> 12;
358                 out[outIndex++] = alphabet[bits6];
359                 bits6  = (bits24 & 0x00000FC0) >> 6;
360                 out[outIndex++] = alphabet[bits6];
361                 bits6 = (bits24 & 0x0000003F);
362                 out[outIndex++] = alphabet[bits6];
363             }
364 
365             if (octetString.length - i == 2) {
366                 // store the octets
367                 bits24 = (octetString[i] & 0xFF) << 16;
368                 bits24 |= (octetString[i + 1] & 0xFF) << 8;
369                 bits6 = (bits24 & 0x00FC0000) >> 18;
370                 out[outIndex++] = alphabet[bits6];
371                 bits6 = (bits24 & 0x0003F000) >> 12;
372                 out[outIndex++] = alphabet[bits6];
373                 bits6 = (bits24 & 0x00000FC0) >> 6;
374                 out[outIndex++] = alphabet[bits6];
375 
376                 // padding
377                 out[outIndex++] = '=';
378             } else if (octetString.length - i == 1) {
379                 // store the octets
380                 bits24 = (octetString[i] & 0xFF) << 16;
381                 bits6 = (bits24 & 0x00FC0000) >> 18;
382                 out[outIndex++] = alphabet[bits6];
383                 bits6 = (bits24 & 0x0003F000) >> 12;
384                 out[outIndex++] = alphabet[ bits6 ];
385 
386                 // padding
387                 out[outIndex++] = '=';
388                 out[outIndex++] = '=';
389             }
390 
391             return new String(out);
392         }
393      }
394 }

            
All Examples in File:
Example
Line
Rating (found
useful by...)
91 0% of 0
218 0% of 0