Coverage details for base.backup.BackupFactory

LineHitsSource
1 /*******************************************************************************
2  * InternetCafe is a software solution that helps the management of Cybercafes
3  * according with the ITALIAN DECREE LAW ON ANTI-TERROR MEASURES, 27 JULY 2005.
4  * Copyright (C) 2006 Guido Angelo Ingenito
5  
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *******************************************************************************/
20 package base.backup;
21  
22 import java.io.BufferedInputStream;
23 import java.io.BufferedOutputStream;
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.PrintStream;
30 import java.util.Date;
31 import java.util.Enumeration;
32 import java.util.zip.ZipEntry;
33 import java.util.zip.ZipFile;
34 import java.util.zip.ZipInputStream;
35 import java.util.zip.ZipOutputStream;
36  
37 import javax.xml.parsers.DocumentBuilder;
38 import javax.xml.parsers.DocumentBuilderFactory;
39 import javax.xml.transform.Transformer;
40 import javax.xml.transform.TransformerFactory;
41 import javax.xml.transform.dom.DOMSource;
42 import javax.xml.transform.stream.StreamResult;
43  
44 import org.apache.log4j.Logger;
45 import org.w3c.dom.Document;
46  
47 import base.ConfigurationManager;
48 import base.IdManager;
49  
500public class BackupFactory {
510    private static final transient Logger logger = Logger
520            .getLogger(BackupFactory.class.getName());
530 
54     public static Backup newBackup(String name, String description, Date date,
55             String dbLocationPath, String zipLocationPath) {
560        int id = IdManager.getInstance().getNextBackupId();
570 
580        return new Backup(id, name, description, date, dbLocationPath,
590                zipLocationPath);
60     }
61  
62     public static Backup newBackupFromZipArchive(File backupFile)
63             throws Exception {
640        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
650 
660        factory.setIgnoringComments(true);
670        factory.setValidating(false);
680        factory.setIgnoringElementContentWhitespace(true);
690 
700        DocumentBuilder docBuilder = factory.newDocumentBuilder();
710        File unzipFolder = new File(backupFile.getParent(), backupFile
720                .getName().substring(0, backupFile.getName().lastIndexOf(".")));
73  
740        unzipFolder.mkdir();
750        unZipFile(new ZipFile(backupFile), unzipFolder);
760 
770        // Now we must retrieve the details file
780        File xmlDetailsFile = new File(unzipFolder,
790                ConfigurationManager.BACKUP_DETAILS_FILE);
800        Document document = docBuilder
810                .parse(new FileInputStream(xmlDetailsFile));
820        Backup backup = new Backup(document);
830 
840        backup.setZipLocationPath(backupFile.getAbsolutePath());
850 
860        return backup;
870    }
880 
890    public static File createDetailsFile(Backup backup) throws Exception {
900        Document doc = DocumentBuilderFactory.newInstance()
910                .newDocumentBuilder().newDocument();
920 
930        doc.appendChild(backup.toXml(doc));
940 
950        String detailsfileName = ConfigurationManager.BACKUP_DETAILS_FILE;
960 
970        if (!detailsfileName.endsWith(".xml")) {
980            detailsfileName += ".xml";
990        }
1000 
1010        Transformer transformer = TransformerFactory.newInstance()
102                 .newTransformer();
1030        DOMSource source = new DOMSource(doc);
1040        StreamResult streamResult = new StreamResult(new PrintStream(
1050                detailsfileName));
1060 
1070        transformer.transform(source, streamResult);
108  
1090        return new File(detailsfileName);
1100    }
1110 
1120    public static void backupToZipArchive(Backup backup) throws Exception {
1130        // Create the ZIP file, will be rappresented by the backup's name
114         // followed by its id.
1150        String outFilename = backup.getName() + backup.getId() + ".zip";
1160        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
117                 new File(backup.getZipLocationPath(), outFilename)));
1180 
1190        out.setComment(backup.getDescription());
1200 
121         // Link the db path to the current zip location
1220        String dbFileName = backup.getDbLocationPath().substring(
1230                backup.getDbLocationPath().lastIndexOf(File.separatorChar),
1240                backup.getDbLocationPath().length());
1250 
1260        backup.setDbLocationPath(new File(backup.getZipLocationPath(),
1270                dbFileName).getAbsolutePath());
1280 
1290        // We must create the backup's details file (xml)
1300        File details = createDetailsFile(backup);
131  
1320        // We must zip it
1330        zipFile(details, out);
1340 
1350        // Lets delete the backup's details file (xml) it doesn't serve anymore
1360        details.delete();
1370 
1380        File resourcesFolder = new File(
1390                ConfigurationManager.RESOURCES_DIRECTORY);
1400 
1410        zipDirectory(resourcesFolder, out);
1420 
1430        // Complete the ZIP file
1440        out.close();
1450    }
1460 
1470    public static void zipDirectory(File file, ZipOutputStream out)
1480            throws Exception {
1490        String[] dirList = file.list();
1500        byte[] readBuffer = new byte[1024];
1510        int bytesIn = 0;
1520 
1530        for (int i = 0; i < dirList.length; i++) {
1540            File f = new File(file, dirList[i]);
1550 
1560            if (f.isDirectory()) {
157                 // if the File object is a directory, call this
1580                // function again to add its content recursively
1590                zipDirectory(f, out);
160  
1610                // loop again
1620                continue;
1630            }
1640 
165             // if we reached here, the File object f was not a directory
166             // create a FileInputStream on top of f
1670            FileInputStream fis = new FileInputStream(f);
1680 
1690            // create a new zip entry
1700            ZipEntry zipEntry = new ZipEntry(f.getPath());
171  
1720            // place the zip entry in the ZipOutputStream object
1730            out.putNextEntry(zipEntry);
174  
1750            // now write the content of the file to the ZipOutputStream
1760            while ((bytesIn = fis.read(readBuffer)) != -1) {
1770                out.write(readBuffer, 0, bytesIn);
1780            }
1790 
1800            // close the Stream
1810            fis.close();
182         }
1830    }
184  
1850    public static void zipFile(File file, ZipOutputStream out) throws Exception {
1860        // Create a buffer for reading the file
1870        byte[] buf = new byte[1024];
1880 
1890        out.putNextEntry(new ZipEntry(file.getName()));
1900 
1910        FileInputStream in = new FileInputStream(file);
1920 
1930        // Transfer bytes from the file to the ZIP file
1940        int len;
1950 
1960        while ((len = in.read(buf)) > 0) {
1970            out.write(buf, 0, len);
1980        }
1990 
2000        in.close();
2010 
202         // Complete the entry
2030        out.closeEntry();
2040    }
2050 
2060    public static void unZipFile(ZipFile zipFile, File destinationDirectory)
2070            throws Exception {
2080        logger.debug("unZipFile: " + zipFile.getName()
2090                + " destination directory: " + destinationDirectory);
2100 
2110        Enumeration enumeration = zipFile.entries();
212  
2130        while (enumeration.hasMoreElements()) {
2140            ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
2150 
2160            File file = new File(destinationDirectory.getCanonicalPath(),
2170                    zipEntry.getName().replaceFirst(".." + File.separatorChar,
2180                            ""));
2190 
2200            logger.debug("File: " + file);
2210 
2220            if (zipEntry.isDirectory()) {
2230                file.mkdirs();
2240            } else {
2250                InputStream is = zipFile.getInputStream(zipEntry);
2260                BufferedInputStream bis = new BufferedInputStream(is);
2270 
2280                if (file.getParent() != null) {
2290                    File dir = new File(file.getParent());
2300 
2310                    dir.mkdirs();
2320                }
2330 
2340                FileOutputStream fos = new FileOutputStream(file);
2350                BufferedOutputStream bos = new BufferedOutputStream(fos);
2360 
237                 int c;
2380 
2390                while ((c = bis.read()) != -1) {
2400                    bos.write((byte) c);
2410                }
2420 
2430                bos.close();
2440                fos.close();
2450            }
246  
2470            logger.debug(" unzipped.");
2480        }
2490    }
250  
2510    public static void unzip(ZipInputStream zin, String zipEntry,
2520            File destinationFolder) throws IOException {
2530        System.out
254                 .println("unzipping " + zipEntry + " to " + destinationFolder);
255  
2560        FileOutputStream out = new FileOutputStream(new File(destinationFolder,
257                 new File(zipEntry).getName()));
2580        byte[] b = new byte[1024];
2590        int len = 0;
2600 
2610        while ((len = zin.read(b)) != -1) {
2620            out.write(b, 0, len);
2630        }
264  
2650        out.close();
2660    }
2670 
268     public static long fileSizeInKB(File file) {
2690        long size = 0;
2700 
2710        if (file.isDirectory()) {
2720            File[] filelist = file.listFiles();
2730 
2740            for (int i = 0; i < filelist.length; i++) {
2750                if (filelist[i].isDirectory()) {
2760                    size += fileSizeInKB(filelist[i]);
2770                } else {
2780                    size += filelist[i].length();
2790                }
2800            }
2810        } else {
2820            size += file.length();
2830        }
284  
2850        return size / 1024;
2860    }
287 }

this report was generated by version 1.0.5 of jcoverage.
visit www.jcoverage.com for updates.

copyright © 2003, jcoverage ltd. all rights reserved.
Java is a trademark of Sun Microsystems, Inc. in the United States and other countries.