package org.dbxml.core.filer;

/*
 * 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: FSFiler.java,v 1.16 2001/06/25 01:08:23 tom Exp $
 */

import org.dbxml.server.*;
import org.dbxml.core.*;
import org.dbxml.core.Collection;
import org.dbxml.core.data.*;
import org.dbxml.server.util.*;
import java.io.*;
import java.util.*;

/**
 * FSFiler allows you to use existing file systems withing dbXML.
 */

public final class FSFiler extends SimpleConfigurable implements Filer {
   private static final String LOCATION = "location";
   private static final String EXT = "ext";
   private static final String READONLY = "readonly";

   private FileCache cache = new FileCache();
   private LockManager locks = new LockManager(16);

   private Set extensions = null;
   
   private String location;
   private Collection collection;
   private File dir;
   private boolean opened = false;
   private boolean readOnly = false;

   public FSFiler() {
   }

   public String getName() {
      return "FSFiler";
   }

   public void setCollection(Collection collection) {
      this.collection = collection;
   }

   public void setConfig(Configuration config) throws dbXMLException {
      super.setConfig(config);
      location = config.getAttribute(LOCATION);
      readOnly = config.getBooleanAttribute(READONLY, readOnly);
      String exts = config.getAttribute(EXT);
      if ( exts != null && exts.trim().length() > 0 ) {
         extensions = new HashSet();
         StringTokenizer st = new StringTokenizer(exts);
         while ( st.hasMoreTokens() )
            extensions.add(st.nextToken());
      }
      dir = new File(location);
      opened = false;
   }

   private void checkOpened() throws DBException {
      if ( !opened )
         throw new FilerException(FaultCodes.COL_COLLECTION_CLOSED, "Filer is closed");
   }

   private void checkReadOnly() throws DBException {
      if ( readOnly )
         throw new FilerException(FaultCodes.COL_COLLECTION_READ_ONLY, "Filer is read-only");
   }
   
   public boolean close() {
      opened = false;
      return true;
   }

   public boolean open() {
      opened = ( dir.exists() && dir.isDirectory() );
      return opened;
   }

   public boolean drop() {
      opened = false;
      return true;
   }

   public boolean isOpened() {
      return opened;
   }

   public boolean exists() {
      return dir.exists();
   }

   public boolean create() {
      if ( !dir.exists() )
         return dir.mkdirs();
      else
         return true;
   }

   public Record readRecord(Key key) throws DBException {
      checkOpened();
      
      String fname = key.toString();
      if ( !isExtensionValid(fname) )
         return null;
      
      File file = new File(dir, fname);
      try {
         locks.acquireSharedLock(file);
         
         HashMap meta = new HashMap(1);
         meta.put(Record.MODIFIED, new Long(file.lastModified()));
         
         byte[] valueData = cache.getFile(file);
         if ( valueData != null )
            return new Record(key, new Value(valueData), meta);
      }
      catch ( Exception e ) {
         org.dbxml.Debug.printStackTrace(e);
      }
      finally {
         locks.releaseSharedLock(file);
      }
      return null;
   }

   public boolean writeRecord(Key key, Value value) throws DBException {
      checkOpened();
      checkReadOnly();
            
      String fname = key.toString();
      if ( !isExtensionValid(fname) )
         return false;
      
      File file = new File(dir, fname);
      try {
         locks.acquireExclusiveLock(file);
         FileOutputStream fos = new FileOutputStream(file);
         value.streamTo(fos);
         fos.close();
         return true;
      }
      catch ( Exception e ) {
         org.dbxml.Debug.printStackTrace(e);
      }
      finally {
         locks.releaseExclusiveLock(file);
      }
      return true;
   }

   /**
    * deleteRecord removes a Record from the Filer based on the
    * specified Key.
    *
    * @param key The Record's Key
    * @return Whether or not the Record was deleted
    */
   public boolean deleteRecord(Key key) throws DBException {
      checkOpened();
      checkReadOnly();
      
      String fname = key.toString();
      if ( !isExtensionValid(fname) )
         return false;
      
      File file = new File(dir, fname);
      try {
         locks.acquireExclusiveLock(file);
         return file.delete();
      }
      catch ( Exception e ) {
         org.dbxml.Debug.printStackTrace(e);
      }
      finally {
         locks.releaseExclusiveLock(file);
      }
      return true;
   }

   public long getRecordCount() throws DBException {
      checkOpened();
      
      File[] files = dir.listFiles(new FileFilter() {
         public boolean accept(File file) {
            return file.isFile() && isExtensionValid(file.getName());
         }
      });
      return files.length;
   }

   public RecordSet getRecordSet() throws DBException {
      checkOpened();
      return new FSRecordSet();
   }

   private boolean isExtensionValid(String fname) {
      if ( extensions != null ) {
         int idx = fname.lastIndexOf('.');
         if ( idx == -1 )
            return false;
         String ext = fname.substring(idx+1);
         if ( !extensions.contains(ext) )
            return false;
      }
      return true;
   }

   /**
    * FSRecordSet
    */
   private class FSRecordSet implements RecordSet {
      public File[] files;
      public int pos = 0;

      public FSRecordSet() {
         files = dir.listFiles(new FileFilter() {
            public boolean accept(File file) {
               return file.isFile() && isExtensionValid(file.getName());
            }
         });
      }

      public boolean hasMoreRecords() {
         return pos < files.length;
      }

      public Record getNextRecord() throws DBException {
         File file = files[pos++];
         return readRecord(new Key(file.getName()));
      }

      public Value getNextValue() throws DBException {
         return getNextRecord().getValue();
      }
      
      public Key getNextKey() {
         return new Key(files[pos++].getName());
      }
   }
}

