package org.dbxml.tools.command;

/*
 * dbXML License, Version 1.0
 *
 *
 * Copyright (c) 1999-2001 The dbXML Group, L.L.C.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by
 *        The dbXML Group (http://www.dbxml.com/)."
 *    Alternately, this acknowledgment may appear in the software
 *    itself, if and wherever such third-party acknowledgments normally
 *    appear.
 *
 * 4. The names "dbXML" and "The dbXML Group" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    info@dbxml.com.
 *
 * 5. Products derived from this software may not be called "dbXML",
 *    nor may "dbXML" appear in their name, without prior written
 *    permission of The dbXML Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE DBXML GROUP OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: ExportTree.java,v 1.19 2001/08/08 04:57:39 kstaken Exp $
 */
import java.util.Hashtable;
import java.io.*;

import org.xmldb.api.base.*;
import org.xmldb.api.modules.*;
import org.xmldb.api.DatabaseManager;

import org.w3c.dom.*;

/**
 * ExportTree.java is designed to take a Collection tree and create a Directory
 * tree from it.  Export tree requires a collection name and a file path to create the tree
 */

public class ExportTree extends Command {
   /**
    * TODO: Description of the Method
    *
    * @param table Description of Parameter
    * @return Description of the Returned Value
    */
   public boolean execute(Hashtable table) throws Exception {

      Collection col = null;

      try {

         if (table.get("filePath").equals("")) {
            System.out.println("ERROR: Directory name and switch required");
            return false;
         }

         if (table.get("collection") == null) {
            System.out.println("ERROR : Collection name and switch required");
            return false;
         }

         File fp = new File((String) table.get("filePath"));

         System.out.println();

         if (table.get("collection") != null) {
            String parent = parentDir((String) table.get("collection"));
            File dir = new File(fp, parent);

            System.out.println("Creating directory " + dir.getPath());

            dir.mkdir();

            process(dir, table, col);
         }

      }
      catch (Exception e) {
         System.out.println("ERROR : " + e.getMessage());
         if (table.get("verbose").equals("true")) {
            org.dbxml.Debug.printStackTrace(e);
         }
      }

      return true;
   }

   /**
    * TODO: Description of the Method
    *
    * @param parent Description of Parameter
    * @return Description of the Returned Value
    */
   public String parentDir(String parent) {
      String dirName = "";
      String parName = parent;

      int idx = parName.lastIndexOf("/");

      if (idx != -1) {
         dirName = parName.substring(idx + 1);
         parName = parName.substring(0, idx);
      }
      else if (idx == -1) {
         dirName = parName;
      }
      return dirName;
   }

   /**
    * TODO: Description of the Method
    *
    * @param directory Description of Parameter
    * @param table Description of Parameter
    * @param col Description of Parameter
    * @return Description of the Returned Value
    */
   boolean process(File directory, Hashtable table, Collection col) throws Exception {
      try {
         String[] list = null;
         String collection = (String) table.get("collection");

         // Get a Collection reference to the collection
         String colstring = normalizeCollectionURI((String) table.get("collection"));
         col = DatabaseManager.getCollection(colstring);
         if (col == null) {
            System.out.println("ERROR : Collection not found!");
            return false;
         }

         String[] files = null;
         try {
             files = col.listResources();
         }
         catch (XMLDBException e) {
            // dbXML will throw an error if there is no indexer
            if (e.errorCode != ErrorCodes.VENDOR_ERROR) {
               throw e;
            }
         }
         
         if (files != null) {
            System.out.println("Extracting " + files.length + " files from " + 
               (String) table.get("collection"));
            for (int j = 0; j < files.length; j++) {
               XMLResource res = 
                  (XMLResource) col.getResource(files[j]);
               String content = (String) res.getContent();
               FileOutputStream output =
                     new FileOutputStream(new File(directory, files[j]));
               output.write(content.getBytes());
               output.close();
            }
         }
         
         list = col.listChildCollections();
         for (int i = 0; i < list.length; i++) {
            File file = new File(directory, list[i]);

            System.out.println("Creating directory " + file.getPath());
            file.mkdirs();

            table.put("collection", (collection + "/" + file.getName()));

            process(new File(directory + "//" + file.getName()), table, col);
         }

      }
      catch (Exception e) {
         System.out.println("ERROR : " + e.getMessage());
         if (table.get("verbose").equals("true")) {
            org.dbxml.Debug.printStackTrace(e);
         }
      }
      finally {
         if (col != null) {
            col.close();
         }
      }
      return true;
   }
}

