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: AddMultipleDocuments.java,v 1.25 2001/09/04 11:13:48 kstaken Exp $
 */

import java.util.Hashtable;
import java.io.*;

import org.dbxml.client.xmldb.services.*;

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


/**
 * AddMultipleDocuments.java is designed to let the user add several Documents
 * to an existing Collection at one time.
 *
 * Documents are added with an ID the same as the file name.
 * This command assumes that the collection being added to already exists!
 */

public class AddMultipleDocuments extends Command {

   public boolean execute(Hashtable table ) throws Exception {

        Collection col = null;
        
        try {

            // Verify that user has supplied necessary arguments
            if ( table.get("collection") == null ) {
                System.out.println("ERROR : Collection and switch required");
                return false;
            }
            
            if ( table.get("filePath") == "" ) {
                System.out.println("ERROR : Directory name and switch required");
                return false;
            }

            // 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;
            }
                
            // Create a collection manager instance for the collection
            CollectionManager colman = (CollectionManager)col.getService("CollectionManager",XMLDBAPIVERSION);

            // Get a File object for the Directory passed in
            File dir = new File((String)table.get("filePath"));

            if (dir.isDirectory()) {
            
                String[] children = new String[] {};
                final String ext = (String)table.get("extension");

                // If the user supplied a file extension, filter on it, else use entire contents of the directory
                if (!ext.equals("")) {

                    children = dir.list( new FilenameFilter() { public boolean accept(File none, String name)
                                                                                        {
                                                                                            return name.endsWith("." + ext);
                                                                                        }
                                                                } );
                }
                
                else if (ext.equals("")) {
                    children = dir.list();
                }

                System.out.println("Reading files from: " + dir.getName());

                // Loop over documents, adding to db
                for (int i=0; i < children.length; i++) {
                    
                    File files = new File(dir, children[i]);

                    if (files.isFile()) {
                        FileInputStream insr = new FileInputStream(files);
                        byte[] fileBuffer = new byte[(int)files.length()];
                        insr.read(fileBuffer);

                        try {
                            
                            // Use the functionality already provided in Command.AddDocument to add this document
                            Command cmd = (Command)Class.forName("org.dbxml.tools.command.AddDocument").newInstance();
                            Hashtable localtable = new Hashtable();
                            String filepath = dir.getPath() + "/" + files.getName();
                            
                            // Populate hashtable to pass to AddDocument class
                            localtable.put("collection",table.get("collection"));
                            localtable.put("nameOf",files.getName() );
                            localtable.put("filePath",filepath);
                            
                            // Execute the class!
                            cmd.execute(localtable);

                        } catch (Exception e) {
                            System.out.println("Error Adding File: " + files.getName());
                            //System.out.println(e);
                            continue;
                        }
                    }
                    else
                        continue;
                } // for loop
            }
            
        } catch (Exception e) {
            System.out.println("ERROR : " + e.getMessage() );
            if (table.get("verbose").equals("true")) {
                e.printStackTrace(System.out);
            }
            return false;
            
        } finally {
            // Release all resources
            if ( col != null ) {
                col.close();
            }
        }

        return true;
    }
   
}

