Package com.dbxml.db.common.filers

Source Code of com.dbxml.db.common.filers.FSFiler$FSRecordSet

package com.dbxml.db.common.filers;

/*
* dbXML - Native XML Database
* Copyright (c) 1999-2006 The dbXML Group, L.L.C.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* $Id: FSFiler.java,v 1.5 2006/02/02 18:53:52 bradford Exp $
*/

import com.dbxml.db.core.Collection;
import com.dbxml.db.core.DBException;
import com.dbxml.db.core.FaultCodes;
import com.dbxml.db.core.data.Key;
import com.dbxml.db.core.data.Record;
import com.dbxml.db.core.data.RecordMetaData;
import com.dbxml.db.core.data.RecordSet;
import com.dbxml.db.core.data.Value;
import com.dbxml.db.core.filer.Filer;
import com.dbxml.db.core.filer.FilerException;
import com.dbxml.db.core.transaction.Transaction;
import com.dbxml.db.core.transaction.TransactionLog;
import com.dbxml.util.Configuration;
import com.dbxml.util.SimpleConfigurable;
import com.dbxml.util.SimpleLockManager;
import com.dbxml.util.dbXMLException;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import java.io.BufferedOutputStream;

/**
* 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 SimpleLockManager locks = new SimpleLockManager();

   private Set extensions;

   private String location;
   private Collection collection;
   private File dir;
   private boolean opened;
   private boolean readOnly;

   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 void flush(Transaction tx) {
   }

   private RecordMetaData buildMetaData(File f) {
      HashMap meta = new HashMap(2);
      meta.put(RecordMetaData.MODIFIED, new Long(f.lastModified()));
      meta.put(RecordMetaData.SIZE, new Long(f.length()));
      return new RecordMetaData(meta);
   }

   public RecordMetaData getRecordMetaData(Transaction tx, Key key) throws DBException {
      checkOpened();

      String fname = key.toString();
      if ( !isExtensionValid(fname) )
         return null;

      File file = new File(dir, fname);
      try {
         locks.acquireLock(file);

         if ( file.exists() && file.isFile() )
            return buildMetaData(file);
      }
      catch ( Exception e ) {
         e.printStackTrace(System.err);
      }
      finally {
         locks.releaseLock(file);
      }
      return null;
   }

   public Record readRecord(Transaction tx, Key key) throws DBException {
      checkOpened();

      String fname = key.toString();
      if ( !isExtensionValid(fname) )
         return null;

      File file = new File(dir, fname);
      try {
         locks.acquireLock(file);

         if ( file.exists() && file.isFile() ) {
            byte[] valueData = new byte[(int)file.length()];
            FileInputStream fis = new FileInputStream(file);
            RecordMetaData md = buildMetaData(file);

            fis.read(valueData);
            fis.close();

            return new Record(key, new Value(valueData), md);
         }
      }
      catch ( Exception e ) {
         e.printStackTrace(System.err);
      }
      finally {
         locks.releaseLock(file);
      }
      return null;
   }

   public boolean writeRecord(Transaction tx, 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.acquireLock(file);
         FileOutputStream fos = new FileOutputStream(file);
         BufferedOutputStream bos = new BufferedOutputStream(fos, 4096);
         value.streamTo(bos);
         bos.flush();
         bos.close();
         return true;
      }
      catch ( Exception e ) {
         e.printStackTrace(System.err);
      }
      finally {
         locks.releaseLock(file);
      }
      return true;
   }

   public boolean deleteRecord(Transaction tx, Key key) throws DBException {
      checkOpened();
      checkReadOnly();

      String fname = key.toString();
      if ( !isExtensionValid(fname) )
         return false;

      File file = new File(dir, fname);
      try {
         locks.acquireLock(file);
         return file.delete();
      }
      catch ( Exception e ) {
         e.printStackTrace(System.err);
      }
      finally {
         locks.releaseLock(file);
      }
      return true;
   }

   public long getRecordCount(Transaction tx) 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(Transaction tx) throws DBException {
      checkOpened();
      return new FSRecordSet(tx);
   }

   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;
   }

   public TransactionLog getTransactionLog() {
      return null;
   }


   /**
    * FSRecordSet
    */

   private class FSRecordSet implements RecordSet {
      private Transaction tx;
      private File[] files;
      private int pos;

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

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

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

      public synchronized Value getNextValue() throws DBException {
         return getNextRecord().getValue();
      }

      public synchronized Key getNextKey() {
         return new Key(files[pos++].getName());
      }
   }
}
TOP

Related Classes of com.dbxml.db.common.filers.FSFiler$FSRecordSet

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.