01: // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
02: // Released under the terms of the GNU General Public License version 2 or later.
03: package fitnesse.updates;
04:
05: import java.io.*;
06: import java.net.URL;
07:
08: public class FileUpdate implements Update {
09: private static final String slash = "/";
10:
11: protected String destination;
12:
13: protected String source;
14:
15: protected File destinationDir;
16:
17: protected String rootDir;
18:
19: protected String filename;
20:
21: public FileUpdate(Updater updater, String source, String destination)
22: throws Exception {
23: this .destination = destination;
24: this .source = source;
25: rootDir = updater.context.rootPagePath;
26: destinationDir = new File(new File(rootDir), destination);
27:
28: filename = new File(source).getName();
29: }
30:
31: public void doUpdate() throws Exception {
32: makeSureDirectoriesExist();
33: copyResource();
34: }
35:
36: private void makeSureDirectoriesExist() {
37: String[] subDirectories = destination.split(slash);
38: String currentDirPath = rootDir;
39:
40: for (int i = 0; i < subDirectories.length; i++) {
41: String subDirectory = subDirectories[i];
42: currentDirPath = currentDirPath + slash + subDirectory;
43: File directory = new File(currentDirPath);
44: directory.mkdir();
45: }
46: }
47:
48: private void copyResource() throws Exception {
49: URL url = getResource(source);
50: InputStream input;
51: if (url != null) {
52: input = url.openStream();
53: } else if (new File(source).exists()) {
54: input = new FileInputStream(source);
55: } else {
56: throw new Exception("Could not load resource: " + source);
57: }
58: OutputStream output = new FileOutputStream(destinationFile());
59:
60: int b;
61: while ((b = input.read()) != -1)
62: output.write(b);
63:
64: input.close();
65: output.close();
66: }
67:
68: protected URL getResource(String resource) {
69: return ClassLoader.getSystemResource(resource);
70: }
71:
72: public String getMessage() {
73: return "Installing file: " + destinationFile();
74: }
75:
76: protected File destinationFile() {
77: return new File(destinationDir, filename);
78: }
79:
80: public String getName() {
81: return "FileUpdate(" + filename + ")";
82: }
83:
84: public boolean shouldBeApplied() throws Exception {
85: return !destinationFile().exists();
86: }
87: }
|