KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > webdav > ant > taskdefs > Get


1 // vi: set ts=3 sw=3:
2
/*
3  * $Header: /home/cvs/jakarta-slide/webdavclient/ant/src/java/org/apache/webdav/ant/taskdefs/Get.java,v 1.3.2.1 2004/08/15 13:01:15 luetzkendorf Exp $
4  * $Revision: 1.3.2.1 $
5  * $Date: 2004/08/15 13:01:15 $
6  * ========================================================================
7  * Copyright 2004 The Apache Software Foundation
8  *
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  * http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ========================================================================
21  */

22 package org.apache.webdav.ant.taskdefs;
23
24 import java.io.File JavaDoc;
25 import java.io.FileNotFoundException JavaDoc;
26 import java.io.FileOutputStream JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.InputStream JavaDoc;
29 import java.io.InputStreamReader JavaDoc;
30 import java.io.OutputStream JavaDoc;
31 import java.io.OutputStreamWriter JavaDoc;
32 import java.util.Iterator JavaDoc;
33
34 import org.apache.commons.httpclient.HttpException;
35 import org.apache.commons.httpclient.HttpURL;
36
37 import org.apache.tools.ant.BuildException;
38 import org.apache.tools.ant.Project;
39 import org.apache.tools.ant.types.FilterSet;
40 import org.apache.tools.ant.types.FilterSetCollection;
41 import org.apache.tools.ant.util.LineTokenizer;
42 import org.apache.webdav.ant.CollectionScanner;
43 import org.apache.webdav.ant.Utils;
44 import org.apache.webdav.ant.WebdavFileSet;
45
46 /**
47  * WebDAV task for retrieving resources.
48  *
49  * @see <a HREF="../doc-files/tasks.htm#davget">Task documentation</a>
50  */

51 public class Get extends WebdavMatchingTask {
52    private File JavaDoc toDir = null;
53    private File JavaDoc toFile = null;
54    private boolean overwrite = false;
55    private String JavaDoc encoding = null;
56    private FilterSetCollection filterSets = new FilterSetCollection();
57    
58    private int countWrittenFiles = 0;
59    private int countOmittedFiles = 0;
60    
61    /*
62     * @see org.apache.tools.ant.Task#execute()
63     */

64    public void execute() throws BuildException {
65       validate();
66       
67       try {
68          if (this.toFile != null) {
69             downloadSingleFile();
70          } else {
71             log("Downloading from: " + getUrl(), ifVerbose());
72             // URL must be a collection
73
if (!getUrl().getPath().endsWith("/")) {
74                getUrl().setPath(getUrl().getPath() + "/");
75             }
76             for(Iterator JavaDoc i = getFileSets(); i.hasNext(); ) {
77                downloadFileset((WebdavFileSet)i.next());
78             }
79          }
80          
81          if (this.countWrittenFiles > 0) {
82             log("Downloaded " + this.countWrittenFiles
83                   + (this.countWrittenFiles == 1 ? " resource" : " resources")
84                   + " from " + getUrl(),
85                   this.countWrittenFiles > 0
86                      ? Project.MSG_INFO
87                      : ifVerbose());
88          }
89       } catch (IOException JavaDoc e) {
90          throw Utils.makeBuildException("Error while downloading!", e);
91       }
92    }
93    
94    protected void validate() {
95       super.validate();
96       
97       if (this.toDir == null && this.toFile == null) {
98          throw new BuildException("Missing one of the required attributes toDir" +
99                " or toFile.");
100       }
101       if (this.toDir != null && this.toFile != null) {
102          throw new BuildException("Only one of the attributes toDir and toFile" +
103                " is alowed.");
104       }
105       if (this.toFile != null && getFileSets().hasNext()) {
106          throw new BuildException("Not filesets allowed if toFile is set.");
107       }
108       if (this.encoding == null && this.filterSets.hasFilters()) {
109          log("If filterSets are used a file encoding should be specified!",
110                Project.MSG_WARN);
111          this.encoding = "ISO-8859-1"; // TODO what should be the default
112
}
113    }
114    
115    protected void downloadFileset(WebdavFileSet fileSet) throws IOException JavaDoc
116    {
117       CollectionScanner scanner =
118           fileSet.getCollectionScanner(getProject(), getHttpClient(), getUrl());
119       HttpURL baseUrl = scanner.getBaseURL();
120       
121       String JavaDoc[] files = scanner.getIncludedFiles();
122       for (int i = 0; i < files.length; i++) {
123          HttpURL url = Utils.createHttpURL(baseUrl, files[i]);
124          downloadFile(url, files[i], scanner);
125       }
126    }
127    
128    protected void downloadSingleFile()
129       throws IOException JavaDoc
130    {
131       long lastMod = Utils.getLastModified(getHttpClient(), getUrl());
132       
133       if (shallWeGetIt(this.toFile, lastMod)) {
134          getAndStoreResource(getUrl(), this.toFile, lastMod, getUrl().getURI());
135       } else {
136          log("Omitted: " + getUrl() + " (uptodate)", ifVerbose());
137          this.countOmittedFiles++;
138       }
139    }
140    
141    protected void downloadFile(HttpURL url,
142                                String JavaDoc relativePath,
143                                CollectionScanner scanner)
144       throws IOException JavaDoc
145    {
146       File JavaDoc target = new File JavaDoc(this.toDir, relativePath);
147       
148       long lastMod = scanner.getProperties().getLastModified(url.toString());
149       
150       if (shallWeGetIt(target, lastMod)) {
151          getAndStoreResource(url, target, lastMod, relativePath);
152       } else {
153          log("Omitted: " + relativePath + " (uptodate)", ifVerbose());
154          this.countOmittedFiles++;
155       }
156    }
157    
158    private boolean shallWeGetIt(File JavaDoc target, long lastMod) {
159       boolean getit = this.overwrite || !target.exists();
160       if (!this.overwrite && target.exists()) {
161          if (lastMod > target.lastModified()) {
162             getit = true;
163          }
164       }
165       return getit;
166    }
167
168    /**
169     * Retrieves the data of a resource and stores it in a file.
170     *
171     * Creates required directories and sets the last modified time of the file.
172     *
173     * @param url url of the resource to be retrieved
174     * @param target file where the resource data ist stored
175     * @param lastMod last modified date of the resource, used to set
176     * the last modified date of the target file
177     * @param relative path og the resource for logging purposes.
178     * @throws IOException
179     * @throws HttpException
180     * @throws FileNotFoundException
181     */

182    private void getAndStoreResource(HttpURL url, File JavaDoc target, long lastMod, String JavaDoc relative)
183       throws IOException JavaDoc, HttpException, FileNotFoundException JavaDoc
184    {
185       log("downloading: " + relative, ifVerbose());
186       File JavaDoc directory = target.getParentFile();
187       if (!directory.exists()) {
188          directory.mkdirs();
189       }
190       
191       InputStream JavaDoc in = Utils.getFile(getHttpClient(), url);
192       
193       if (!target.exists()) {
194          target.createNewFile();
195       }
196       FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(target);
197       
198       copyStream(in, out, this.filterSets, this.encoding);
199       
200       out.close();
201       target.setLastModified(lastMod);
202       this.countWrittenFiles++;
203    }
204
205    protected static void copyStream(InputStream JavaDoc in, OutputStream JavaDoc out,
206          FilterSetCollection filterSets, String JavaDoc encoding)
207       throws IOException JavaDoc
208    {
209       byte[] b = new byte[1024];
210       if (filterSets.hasFilters()) {
211          InputStreamReader JavaDoc reader = new InputStreamReader JavaDoc(in, encoding);
212          OutputStreamWriter JavaDoc writer = new OutputStreamWriter JavaDoc(out, encoding);
213          
214          LineTokenizer tok = new LineTokenizer();
215          tok.setIncludeDelims(true);
216
217          for (String JavaDoc l = tok.getToken(reader); l != null; l = tok.getToken(reader)) {
218             writer.write(filterSets.replaceTokens(l));
219          }
220          writer.close();
221          reader.close();
222       } else {
223          while (in.available() > 0) {
224             int cnt = in.read(b, 0, b.length);
225             if (cnt > -1) {
226                out.write(b, 0, cnt);
227             }
228          }
229       }
230    }
231
232
233    public void setTodir(File JavaDoc directory) {
234       this.toDir = directory;
235       if (this.toDir.isFile()) {
236          throw new BuildException("toDir must not point to a file!");
237       }
238    }
239    
240    public void setTofile(File JavaDoc file) {
241       this.toFile = file;
242       if (this.toFile.isDirectory()) {
243          throw new BuildException("toFile must not point to a directory!");
244       }
245    }
246    
247    public FilterSet createFilterSet() {
248       FilterSet filterSet = new FilterSet();
249       this.filterSets.addFilterSet(filterSet);
250       return filterSet;
251    }
252    public void setEncoding(String JavaDoc enc) {
253       this.encoding = enc;
254    }
255    public void setOverwrite(boolean b) {
256       this.overwrite = b;
257    }
258 }
259
Popular Tags