You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@jackrabbit.apache.org by ju...@apache.org on 2006/08/08 09:18:06 UTC

svn commit: r429606 [2/2] - in /jackrabbit/trunk/contrib/backup/src: main/java/org/apache/jackrabbit/backup/ test/ test/java/org/apache/jackrabbit/backup/

Added: jackrabbit/trunk/contrib/backup/src/main/java/org/apache/jackrabbit/backup/ZipBackupIOHandler.java
URL: http://svn.apache.org/viewvc/jackrabbit/trunk/contrib/backup/src/main/java/org/apache/jackrabbit/backup/ZipBackupIOHandler.java?rev=429606&view=auto
==============================================================================
--- jackrabbit/trunk/contrib/backup/src/main/java/org/apache/jackrabbit/backup/ZipBackupIOHandler.java (added)
+++ jackrabbit/trunk/contrib/backup/src/main/java/org/apache/jackrabbit/backup/ZipBackupIOHandler.java Tue Aug  8 00:18:05 2006
@@ -0,0 +1,195 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.backup;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Enumeration;
+import java.util.zip.CRC32;
+import java.util.zip.CheckedInputStream;
+import java.util.zip.Checksum;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import java.util.zip.ZipFile;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+
+/**
+ * Question: ZipFile
+ *
+ * @author ntoper
+ *
+ */
+public class ZipBackupIOHandler implements BackupIOHandler {
+    
+    private static int BUFFER_SIZE = 1024;
+    
+    private File zip;
+    private FileOutputStream fout;
+    private ZipOutputStream zipOut;
+
+    private FileInputStream fin;
+    private ZipInputStream zipIn;
+
+    private boolean isBackup = false;
+
+
+    public ZipBackupIOHandler(String zipFile, boolean isBackup) throws IOException {
+        this.zip = new File(zipFile);
+        this.isBackup = isBackup;
+
+        if (isBackup) {
+            this.fout = new FileOutputStream(this.zip);
+            this.zipOut = new ZipOutputStream(this.fout);
+        }
+        else {
+            this.fin = new FileInputStream(this.zip);
+            this.zipIn = new ZipInputStream(this.fin);
+        }
+    }
+
+    public void close() throws IOException {
+        if (isBackup) {
+            zipOut.finish();
+            zipOut.close();
+        }
+        else {
+            zipIn.close();
+        }
+    }
+
+    /**
+     * Create a directory per resources
+     *   Backup the resource and zip it
+     * @param string
+     * @param content
+     */
+    public void write(String name, File f) throws IOException {
+        zipOut.flush();
+        ZipEntry e = new ZipEntry(name);
+        zipOut.putNextEntry(e);
+
+        Checksum crc = new CRC32();
+        CheckedInputStream i = new CheckedInputStream(new FileInputStream(f), crc);
+
+        byte[] buffer = new byte[BUFFER_SIZE];
+        int len;       while ( (len = i.read(buffer, 0, BUFFER_SIZE)) != -1) {
+            zipOut.write(buffer, 0, len);
+        }
+
+        //Checksum management
+        // TODO Is crc up to date? To be checked...
+        long check = crc.getValue();
+        e.setCrc(check);
+        zipOut.closeEntry();
+    }
+    
+    /**
+     * 
+     * TODO: refactor this method with the one upper.
+     * 
+     * 
+     * Used for small I/O operations (no NIO used there). Take a file and zip it.
+     *
+     * Most I/O operations are operated on RAM.
+     *
+     */
+    public void write(String name, ByteArrayOutputStream fos) throws IOException {
+        zipOut.flush();
+        ZipEntry e = new ZipEntry(name);
+        zipOut.putNextEntry(e);
+        
+        Checksum crc = new CRC32();
+        
+        InputStream io = new ByteArrayInputStream(fos.toByteArray());
+        
+        CheckedInputStream i = new CheckedInputStream(io, crc);
+        
+        byte[] buffer = new byte[BUFFER_SIZE];
+        int len;
+        while ( (len = i.read(buffer, 0, BUFFER_SIZE)) != -1) {
+            zipOut.write(buffer, 0, len);
+        }
+        
+        //Checksum management
+        // TODO Is crc up to date? To be checked...
+        long check = crc.getValue();
+        e.setCrc(check);
+        zipOut.closeEntry();
+    }
+    
+    public byte[] read(String zipEntry) throws ZipException, IOException {
+        ZipFile zf = new ZipFile(this.zip);
+        ZipEntry ze = new ZipEntry(zipEntry);
+        long crc1 = ze.getCrc();
+        
+        Checksum chkCrc2 = new CRC32();
+        InputStream is = zf.getInputStream(ze);
+        CheckedInputStream cis = new CheckedInputStream(is, chkCrc2);
+        
+        ByteArrayOutputStream os = new ByteArrayOutputStream();
+        
+        byte[] buffer = new byte[BUFFER_SIZE];
+        int len;
+        while ( (len = cis.read(buffer, 0, BUFFER_SIZE)) != -1) {
+            os.write(buffer, 0, len);
+        }
+        //TODO check CRC
+       /* if (crc1 == chkCrc2.getValue()) {*/
+            return os.toByteArray();
+/*        }
+        else {
+            throw new ZipException();
+        }*/
+    }
+    
+    //TODO Refactor: the two upper are the same!! + quite similar to Backup
+    public void read(String zipEntry, File myFile) throws ZipException, IOException {
+        ZipFile zf = new ZipFile(this.zip);
+        ZipEntry ze = new ZipEntry(zipEntry);
+        //TODO check CRC
+
+        Checksum chkCrc2 = new CRC32();
+        InputStream is = zf.getInputStream(ze);
+        CheckedInputStream cis = new CheckedInputStream(is, chkCrc2);
+        
+        OutputStream os = new FileOutputStream(myFile);
+
+        
+        byte[] buffer = new byte[BUFFER_SIZE];
+        int len;
+        while ( (len = cis.read(buffer, 0, BUFFER_SIZE)) != -1) {
+            os.write(buffer, 0, len);
+        }
+        
+     /*   if (!(crc1 == chkCrc2.getValue())) {
+            System.out.println("crc1:" + crc1 + "a crc2:"+ chkCrc2.getValue()  );
+            throw new ZipException();
+        }*/
+    }
+
+    public Enumeration getEntries() throws ZipException, IOException {
+        ZipFile zf = new ZipFile(this.zip);
+        return zf.entries();
+    }
+}

Propchange: jackrabbit/trunk/contrib/backup/src/main/java/org/apache/jackrabbit/backup/ZipBackupIOHandler.java
------------------------------------------------------------------------------
    svn:eol-style = native

Modified: jackrabbit/trunk/contrib/backup/src/test/backup.xml
URL: http://svn.apache.org/viewvc/jackrabbit/trunk/contrib/backup/src/test/backup.xml?rev=429606&r1=429605&r2=429606&view=diff
==============================================================================
--- jackrabbit/trunk/contrib/backup/src/test/backup.xml (original)
+++ jackrabbit/trunk/contrib/backup/src/test/backup.xml Tue Aug  8 00:18:05 2006
@@ -1,16 +1,12 @@
 <?xml version="1.0"?>
 
 <Backup>
-<WorkingFolder path="tmp" />
-<!-- For now only ObjectPersistenceManager and XMLPersistenceManager -->
-<PersistenceManager class="org.apache.jackrabbit.core.state.xml.XMLPersistenceManager" />
-
+<WorkingFolder path="tmp/" />
   <Resources>
-    <Resource savingClass="org.apache.jackrabbit.backup.BackupConfigurationBackup" />
-    <Resource savingClass="org.apache.jackrabbit.backup.RepositoryBackup" />
+  <!-- The repository and the config file are automatically backupped -->
     <Resource savingClass="org.apache.jackrabbit.backup.NodeTypeBackup" />
     <Resource savingClass="org.apache.jackrabbit.backup.NamespaceBackup" />
     <Resource savingClass="org.apache.jackrabbit.backup.AllWorkspacesBackup" />
-    <Resource savingClass="org.apache.jackrabbit.backup.NodeVersionHistoriesBackup" />
+    <!--<Resource savingClass="org.apache.jackrabbit.backup.NodeVersionHistoriesBackup" />-->
    </Resources>
 </Backup>

Modified: jackrabbit/trunk/contrib/backup/src/test/java/org/apache/jackrabbit/backup/BackupTest.java
URL: http://svn.apache.org/viewvc/jackrabbit/trunk/contrib/backup/src/test/java/org/apache/jackrabbit/backup/BackupTest.java?rev=429606&r1=429605&r2=429606&view=diff
==============================================================================
--- jackrabbit/trunk/contrib/backup/src/test/java/org/apache/jackrabbit/backup/BackupTest.java (original)
+++ jackrabbit/trunk/contrib/backup/src/test/java/org/apache/jackrabbit/backup/BackupTest.java Tue Aug  8 00:18:05 2006
@@ -18,15 +18,18 @@
 package org.apache.jackrabbit.backup;
 
 import javax.jcr.*;
-import javax.jcr.nodetype.NodeTypeManager;
 
+import org.apache.jackrabbit.core.NamespaceRegistryImpl;
 import org.apache.jackrabbit.core.TransientRepository;
 import org.apache.jackrabbit.core.WorkspaceImpl;
 import org.apache.jackrabbit.core.nodetype.InvalidNodeTypeDefException;
 import org.apache.jackrabbit.core.nodetype.NodeTypeDef;
 import org.apache.jackrabbit.core.nodetype.NodeTypeManagerImpl;
 import org.apache.jackrabbit.core.nodetype.NodeTypeRegistry;
+import org.apache.jackrabbit.name.IllegalNameException;
+import org.apache.jackrabbit.name.NameFormat;
 import org.apache.jackrabbit.name.QName;
+import org.apache.jackrabbit.name.UnknownPrefixException;
 
 import java.io.File;
 import java.io.FileInputStream;
@@ -38,20 +41,20 @@
  * and outputs the contents of the entire workspace.
  */
 public class BackupTest {
-
+    
     /** Runs the ThirdHop example. */
     public static void main(String[] args) throws Exception {
         // Set up a Jackrabbit repository with the specified
         // configuration file and repository directory
         Repository repository = new TransientRepository();
-
+        
         // Login to the default workspace as a dummy user
         Session session = repository.login(
-            new SimpleCredentials("username", "password".toCharArray()));
+                new SimpleCredentials("username", "password".toCharArray()));
         try {
             // Use the root node as a starting point
             Node root = session.getRootNode();
-
+            
             // Import the XML file unless already imported
             if (!root.hasNode("importxml")) {
                 System.out.print("Importing xml... ");
@@ -60,7 +63,7 @@
                 // Import the file "test.xml" under the created node
                 FileInputStream xml = new FileInputStream("src/test/test.xml");
                 session.importXML(
-                    "/importxml", xml, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
+                        "/importxml", xml, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
                 xml.close();
                 // Save the changes to the repository
                 session.save();
@@ -74,7 +77,7 @@
             n.setProperty("anyProperty", "Blah");
             session.save();
             n.checkin();
-
+            
             //add new version
             Node child = root.getNode("childNode");
             child.checkout();
@@ -82,13 +85,16 @@
             session.save();
             child.checkin();
             
+            //Register a namespace if not already existing
+            NamespaceRegistryImpl nr = (NamespaceRegistryImpl) session.getWorkspace().getNamespaceRegistry();
+            nr.safeRegisterNamespace("backup_example","http://www.deviant-abstraction.net");
             //Creating a second workspace
             Workspace wsp = session.getWorkspace();
             String[] allWsp = wsp.getAccessibleWorkspaceNames();
             
             if (allWsp.length < 2) {
                 ((WorkspaceImpl)wsp).createWorkspace("secondTest");
-                session.logout();
+                
                 Session session2 = repository.login(new SimpleCredentials("username", "password".toCharArray()), "secondTest");
                 root = session2.getRootNode();
                 
@@ -99,25 +105,22 @@
                 // Import the file "test.xml" under the created node
                 FileInputStream xml = new FileInputStream("src/test/test.xml");
                 session2.importXML(
-                    "/importxml", xml, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
+                        "/importxml", xml, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
                 xml.close();
                 // Save the changes to the repository
                 session2.save();
-                System.out.println("done.");         
-              
+                session2.logout();
+                System.out.println("done.");
             }
             
-
-            
             //Registering a NodeType
-      /*      System.out.print("Registering a test nodeType...\r\n ");
-       
+            System.out.print("Registering a test nodeType...\r\n ");
             NodeTypeDef ntd = new NodeTypeDef();
             ntd.setMixin(true);
             ntd.setName(new QName("http://www.jcp.org/jcr/nt/1.0", "example"));
             registerNodeType(ntd, session);
-            
-            */
+            session.save();
+            session.logout();
             
             System.out.print("Launching backup...\r\n ");
             
@@ -126,31 +129,72 @@
              */
             
             //Delete the zip file if existing
-            File zip = new File("myzip.zip");
-            zip.delete();
+            //File zip = new File("myzip.zip");
+            //zip.delete();
+            File zip2 = new File("myzip2.zip");
+            zip2.delete();
+            
+            
             
             String[] argsBackup ="--zip myzip.zip --login username --password password --conf src/test/backup.xml backup repository.xml repository/".split(" ");
-            LaunchBackup.main(argsBackup); 
+            //LaunchBackup.main(argsBackup); 
             System.out.print("Backup done. ");
-
-          
+            
+            //Launching restore in another repository instance
+            
+            //Delete all previous resource
+            File f = new File("repository2.xml");
+            f.delete();
+            
+            File f1 = new File("repository2/");
+            deleteDir(f1);
+            f1.delete();
+            
+            String[] argsBackup1 ="--zip myzip.zip --login username --password password restore repository2.xml repository2/".split(" ");
+            LaunchBackup.main(argsBackup1); 
+            System.out.print("Restore done. ");
+            
+            String[] argsBackup2 ="--zip myzip2.zip --login username --password password --conf src/test/backup.xml backup repository2.xml repository2/".split(" ");
+            LaunchBackup.main(argsBackup2); 
+            System.out.print("Backup done. ");
+            
         } finally {
             session.logout();
         }
     }
-  
-    private static void registerNodeType(NodeTypeDef nodeTypeDef, Session session) throws RepositoryException, InvalidNodeTypeDefException
+    
+    private static void registerNodeType(NodeTypeDef nodeTypeDef, Session session) throws RepositoryException, InvalidNodeTypeDefException, IllegalNameException, UnknownPrefixException
     {
         //NodeTypeRegistry object
         Workspace wsp = session.getWorkspace();
-        NodeTypeManager ntMgr = wsp.getNodeTypeManager();
+        NodeTypeManagerImpl ntMgr = (NodeTypeManagerImpl) wsp.getNodeTypeManager();
+        
         
         //non-JSR 170 - jackrabbit specific
         NodeTypeRegistry ntReg = 
-                ((NodeTypeManagerImpl) ntMgr).getNodeTypeRegistry();
+            ((NodeTypeManagerImpl) ntMgr).getNodeTypeRegistry();
         
-        ntReg.registerNodeType(nodeTypeDef);
+        if (!ntReg.isRegistered(nodeTypeDef.getName()))
+            ntReg.registerNodeType(nodeTypeDef);
     }
-
-
+    
+    // Deletes all files and subdirectories under dir.
+    // Returns true if all deletions were successful.
+    // If a deletion fails, the method stops attempting to delete and returns false.
+    public static boolean deleteDir(File dir) {
+        if (dir.isDirectory()) {
+            String[] children = dir.list();
+            for (int i=0; i<children.length; i++) {
+                boolean success = deleteDir(new File(dir, children[i]));
+                if (!success) {
+                    return false;
+                }
+            }
+        }
+        
+        // The directory is now empty so delete it
+        return dir.delete();
+    }
+    
+    
 }