KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > outerj > daisy > backupTool > BackupHelper


1 /*
2  * Copyright 2004 Outerthought bvba and Schaubroeck nv
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.outerj.daisy.backupTool;
17
18 import java.io.*;
19 import java.nio.channels.FileChannel JavaDoc;
20 import java.security.MessageDigest JavaDoc;
21 import java.util.Enumeration JavaDoc;
22 import java.util.zip.Deflater JavaDoc;
23 import java.util.zip.ZipEntry JavaDoc;
24 import java.util.zip.ZipFile JavaDoc;
25 import java.util.zip.ZipOutputStream JavaDoc;
26
27 import javax.xml.parsers.DocumentBuilder JavaDoc;
28 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
29 import javax.xml.transform.Transformer JavaDoc;
30 import javax.xml.transform.TransformerFactory JavaDoc;
31 import javax.xml.transform.dom.DOMSource JavaDoc;
32 import javax.xml.transform.stream.StreamResult JavaDoc;
33
34 import org.apache.commons.codec.binary.Base64;
35 import org.jaxen.dom.DOMXPath;
36 import org.w3c.dom.Document JavaDoc;
37 import org.w3c.dom.Element JavaDoc;
38 import org.w3c.dom.Node JavaDoc;
39
40 public class BackupHelper {
41     private static int BUFFER_SIZE = 1024;
42
43     public static Document JavaDoc parseFile(File JavaDoc file) throws Exception JavaDoc {
44         DocumentBuilderFactory JavaDoc documentBuilderFactory = DocumentBuilderFactory.newInstance();
45         documentBuilderFactory.setNamespaceAware(true);
46         DocumentBuilder JavaDoc documentBuilder = documentBuilderFactory.newDocumentBuilder();
47         return documentBuilder.parse(file);
48     }
49
50     public static void streamCopy(InputStream is, OutputStream JavaDoc os) throws IOException {
51         byte[] buffer = new byte[BUFFER_SIZE];
52         int len;
53         while ((len = is.read(buffer)) > 0) {
54             os.write(buffer, 0, len);
55         }
56     }
57
58     public static void copyFile(File JavaDoc source, File JavaDoc destination) throws Exception JavaDoc {
59         if (source.isDirectory()) {
60             destination.mkdirs();
61             File JavaDoc[] files = source.listFiles();
62             for (int i = 0; i < files.length; i++) {
63                 copyFile(files[i], new File JavaDoc(destination, files[i].getName()));
64             }
65         } else {
66             destination.getParentFile().mkdirs();
67             destination.createNewFile();
68             copyFileFile(source, destination);
69         }
70     }
71
72     private static void copyFileFile(File JavaDoc source, File JavaDoc destination) throws Exception JavaDoc {
73         FileChannel JavaDoc srcChannel = new FileInputStream(source).getChannel();
74         FileChannel JavaDoc dstChannel = new FileOutputStream(destination).getChannel();
75         dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
76         srcChannel.close();
77         dstChannel.close();
78     }
79
80     public static void deleteFile(File JavaDoc file) throws Exception JavaDoc {
81         deleteFile(file, false);
82     }
83
84     public static void deleteFile(File JavaDoc file, boolean quiet) throws Exception JavaDoc {
85         if (file.isDirectory()) {
86             File JavaDoc[] files = file.listFiles();
87             for (int i = 0; i < files.length; i++)
88                 deleteFile(files[i], quiet);
89         }
90
91         boolean success = file.delete();
92         if (!success && !quiet)
93             throw new Exception JavaDoc("Could not delete file " + file.getAbsolutePath());
94     }
95
96     public static class RunnableStreamCopy implements Runnable JavaDoc {
97         private InputStream is;
98
99         private OutputStream JavaDoc os;
100
101         public RunnableStreamCopy(InputStream is, OutputStream JavaDoc os) {
102             this.is = is;
103             this.os = os;
104         }
105
106         public void run() {
107             try {
108                 streamCopy(is, os);
109                 os.flush();
110             } catch (Exception JavaDoc e) {
111                 e.printStackTrace();
112             }
113
114         }
115     }
116     
117     public static void unzipToDirectory(File JavaDoc zippedFile, File JavaDoc file) throws Exception JavaDoc{
118         file.mkdirs();
119         unzipToFile(zippedFile, file);
120     }
121
122     public static void unzipToFile(File JavaDoc zippedFile, File JavaDoc file) throws Exception JavaDoc {
123         if (!zippedFile.exists())
124             throw new FileNotFoundException("The zipfile " + zippedFile.getPath() + " could not be found");
125         ZipFile JavaDoc zipFile = new ZipFile JavaDoc(zippedFile);
126         Enumeration JavaDoc entries = zipFile.entries();
127         File JavaDoc baseDir = null;
128         if (file.isDirectory()) {
129             baseDir = file;
130         } else {
131             file.createNewFile();
132             baseDir = file.getParentFile();
133         }
134         while (entries.hasMoreElements()) {
135             ZipEntry JavaDoc entry = (ZipEntry JavaDoc) entries.nextElement();
136             BackupHelper.unzipToFile(zipFile, entry, baseDir);
137         }
138     }
139
140     private static void unzipToFile(ZipFile JavaDoc zipFile, ZipEntry JavaDoc entry, File JavaDoc basedir) throws Exception JavaDoc {
141         File JavaDoc entryFile = new File JavaDoc(basedir, entry.getName());
142         if (entry.isDirectory()) {
143             entryFile.mkdir();
144         } else {
145             InputStream is = zipFile.getInputStream(entry);
146             OutputStream JavaDoc os = new FileOutputStream(entryFile);
147             try {
148                 streamCopy(is, os);
149             } finally {
150                 is.close();
151                 os.close();
152             }
153         }
154     }
155
156     public static void fileToZip(File JavaDoc file, File JavaDoc zipFile) throws Exception JavaDoc {
157         zipFile.createNewFile();
158         FileOutputStream fout = new FileOutputStream(zipFile);
159         ZipOutputStream JavaDoc zout = null;
160         try {
161             zout = new ZipOutputStream JavaDoc(new BufferedOutputStream(fout));
162             zout.setLevel(Deflater.BEST_COMPRESSION);
163             if (file.isDirectory()) {
164                 File JavaDoc[] files = file.listFiles();
165                 for (int i = 0; i < files.length; i++)
166                     BackupHelper.fileToZip(files[i], zout, file);
167             }else if (file.isFile()) {
168                 BackupHelper.fileToZip(file, zout, file.getParentFile());
169             }
170         } finally {
171             if (zout != null)
172                 zout.close();
173         }
174     }
175
176     private static void fileToZip(File JavaDoc file, ZipOutputStream JavaDoc zout, File JavaDoc baseDir) throws Exception JavaDoc {
177         String JavaDoc entryName = file.getPath().substring(baseDir.getPath().length() + 1);
178         if (file.isDirectory()) {
179             zout.putNextEntry(new ZipEntry JavaDoc(entryName + "/"));
180             zout.closeEntry();
181             File JavaDoc[] files = file.listFiles();
182             for (int i = 0; i < files.length; i++)
183                 fileToZip(files[i], zout, baseDir);
184         } else {
185             FileInputStream is = null;
186             try {
187                 is = new FileInputStream(file);
188                 zout.putNextEntry(new ZipEntry JavaDoc(entryName));
189                 streamCopy(is, zout);
190             } finally {
191                 zout.closeEntry();
192                 if (is != null)
193                     is.close();
194             }
195         }
196     }
197
198     public static String JavaDoc prompt(String JavaDoc message) throws Exception JavaDoc {
199         System.out.println(message);
200         System.out.flush();
201         String JavaDoc input = null;
202         while (input == null || input.trim().equals("")) {
203             BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
204             try {
205                 input = in.readLine();
206             } catch (IOException e) {
207                 throw new Exception JavaDoc("Error reading input from console.", e);
208             }
209         }
210         return input;
211     }
212
213     public static String JavaDoc prompt(String JavaDoc message, String JavaDoc defaultInput) throws Exception JavaDoc {
214         System.out.println(message);
215         System.out.flush();
216         BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
217         String JavaDoc input;
218         try {
219             input = in.readLine();
220         } catch (IOException e) {
221             throw new Exception JavaDoc("Error reading input from console.", e);
222         }
223         if (input == null || input.trim().equals(""))
224             input = defaultInput;
225         return input;
226     }
227
228     public static boolean promptYesNo(String JavaDoc message, boolean defaultInput) throws Exception JavaDoc {
229         String JavaDoc input = "";
230         while (!input.equals("yes") && !input.equals("no")) {
231             input = prompt(message, defaultInput ? "yes" : "no");
232             input = input.toLowerCase();
233         }
234         return input.equals("yes");
235     }
236
237     public static void saveDocument(File JavaDoc file, Document JavaDoc document) throws Exception JavaDoc {
238         TransformerFactory JavaDoc transformerFactory = TransformerFactory.newInstance();
239         Transformer JavaDoc transformer = transformerFactory.newTransformer();
240         DOMSource JavaDoc source = new DOMSource JavaDoc(document);
241         StreamResult JavaDoc result = new StreamResult JavaDoc(file);
242         transformer.setOutputProperty("encoding", "UTF-8");
243         transformer.setOutputProperty("indent", "yes");
244         transformer.transform(source, result);
245     }
246
247     public static String JavaDoc generateMD5Hash(File JavaDoc file) throws Exception JavaDoc {
248         byte[] buffer = new byte[1024];
249         int len;
250         InputStream fis = new FileInputStream(file);
251         MessageDigest JavaDoc hash = MessageDigest.getInstance("MD5");
252
253         try {
254             while ((len = fis.read(buffer)) > 0)
255                 hash.update(buffer, 0, len);
256         } finally {
257             fis.close();
258         }
259
260         return new String JavaDoc(Base64.encodeBase64(hash.digest()));
261     }
262
263     public static Element JavaDoc getElementFromDom(Node JavaDoc domNode, String JavaDoc xpath) throws Exception JavaDoc {
264         return getElementFromDomNS(domNode, xpath, null, null);
265     }
266     
267     public static Element JavaDoc getElementFromDom(Node JavaDoc domNode, String JavaDoc xpath, boolean fail) throws Exception JavaDoc {
268         return getElementFromDomNS(domNode, xpath, null, null, fail);
269     }
270
271     public static Element JavaDoc getElementFromDomNS(Node JavaDoc domNode, String JavaDoc xpath, String JavaDoc prefix, String JavaDoc namespace, boolean fail) throws Exception JavaDoc {
272         DOMXPath path = new DOMXPath(xpath);
273         if (namespace != null)
274             path.addNamespace(prefix, namespace);
275         
276         Element JavaDoc element = (Element JavaDoc) path.selectSingleNode(domNode);
277         if (element == null && fail) {
278             throw new Exception JavaDoc("Node with XPath '" + xpath + "' could not be found.");
279         }
280         return element;
281     }
282
283     public static Element JavaDoc getElementFromDomNS(Node JavaDoc domNode, String JavaDoc xpath, String JavaDoc prefix, String JavaDoc namespace) throws Exception JavaDoc {
284         return getElementFromDomNS(domNode, xpath, prefix, namespace, true);
285     }
286
287     public static String JavaDoc getStringFromDom(Node JavaDoc domNode, String JavaDoc xpath) throws Exception JavaDoc {
288         return getStringFromDomNS(domNode, xpath, null, null);
289     }
290     
291     public static String JavaDoc getStringFromDomNS(Node JavaDoc domNode, String JavaDoc xpath, String JavaDoc prefix, String JavaDoc namespace, String JavaDoc defaultValue) throws Exception JavaDoc {
292         DOMXPath path = new DOMXPath(xpath);
293         if (namespace != null)
294             path.addNamespace(prefix, namespace);
295
296         String JavaDoc value = path.stringValueOf(domNode);
297         if (value == null) {
298             return defaultValue;
299         }
300         return value;
301     }
302
303     public static String JavaDoc getStringFromDomNS(Node JavaDoc domNode, String JavaDoc xpath, String JavaDoc prefix, String JavaDoc namespace) throws Exception JavaDoc {
304         DOMXPath path = new DOMXPath(xpath);
305         if (namespace != null)
306             path.addNamespace(prefix, namespace);
307
308         String JavaDoc value = path.stringValueOf(domNode);
309         if (value == null) {
310             throw new Exception JavaDoc("Node with XPath '" + xpath + "' could not be found.");
311         }
312         return value;
313     }
314 }
315
Popular Tags