Package org.apache.xindice.client.xmldb.embed

Source Code of org.apache.xindice.client.xmldb.embed.CollectionImpl

package org.apache.xindice.client.xmldb.embed;
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation.  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
*        Apache Software Foundation (http://www.apache.org/)."
*    Alternately, this acknowledgment may appear in the software itself,
*    if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xindice" and "Apache Software Foundation" must
*    not be used to endorse or promote products derived from this
*    software without prior written permission. For written
*    permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
*    nor may "Apache" appear in their name, without prior written
*    permission of the Apache Software Foundation.
*
* 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 APACHE SOFTWARE FOUNDATION 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999-2001, The dbXML
* Group, L.L.C., http://www.dbxmlgroup.com.  For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* $Id: CollectionImpl.java,v 1.10 2002/11/21 07:44:35 vladimir Exp $
*/
import org.apache.xindice.client.xmldb.ResourceSetImpl;
import org.apache.xindice.client.xmldb.XindiceCollection;
import org.apache.xindice.client.xmldb.resources.XMLResourceImpl;
import org.apache.xindice.core.Collection;
import org.apache.xindice.core.Database;
import org.apache.xindice.core.FaultCodes;
import org.apache.xindice.core.data.NodeSet;
import org.apache.xindice.util.Configuration;
import org.apache.xindice.xml.NamespaceMap;
import org.apache.xindice.xml.TextWriter;
import org.apache.xindice.xml.dom.DBNode;
import org.apache.xindice.xml.dom.DocumentImpl;

import org.w3c.dom.*;
import org.xmldb.api.base.ErrorCodes;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.XMLDBException;
import org.xmldb.api.modules.XMLResource;

import java.util.Enumeration;
import java.util.Hashtable;

/**
* Implementation of XML:DB's <code>Collection</code> interface using
* XML-RPC to interact with database server
*
* @author <a href="mailto:james.bates@amplexor.com">James Bates</a>
* @author <a href="mailto:kstaken@xmldatabases.org">Kimbro Staken</a>
*/
public class CollectionImpl extends XindiceCollection {         
    Database db = null;
    Collection col = null;
   
    /**
     * Creates new <code>CollectionImpl</code> instance representing connection
     * to server collection.
     *
     * @exception XMLDBException thrown if a connection could not be established,
     *            because of URL syntax errors, or connection failure, or if no
     *            collection with path <code>collPath</code> could be located.
     */
    public CollectionImpl(Database db, String collPath) throws XMLDBException {
        super(collPath);
        this.db = db;
       
        try {
           this.col = db.getCollection(collPath);
        } catch (Exception e) {
            throw new XMLDBException(ErrorCodes.NO_SUCH_COLLECTION,
                                     "Collection not found: " + collPath, e);
        }
    if(this.col == null) {
            throw new XMLDBException(ErrorCodes.NO_SUCH_COLLECTION,
                                     "Collection not found: " + collPath);
    }
    }
   
   /**
    * Retrieves a <code>Resource</code> from the database. If the
    * <code>Resource</code> could not be
    * located a null value will be returned.
    *
    * @param id the unique id for the requested resource.
    * @return The retrieved <code>Resource</code> instance.
    * @exception XMLDBException with expected error codes.<br />
    <code>ErrorCodes.VENDOR_ERROR</code> for any vendor
    *  specific errors that occur.<br />
    <code>ErrorCodes.COLLECTION_CLOSED</code> if the <code>close</code>
    *  method has been called on the <code>Collection</code><br />
    */
    public Resource getResource(String id) throws XMLDBException {

        checkOpen();
        try {           
            Document doc = col.getDocument(id);

            // This should probably just pass the document.
            return new XMLResourceImpl(id, id, this,
                                       ((DocumentImpl) doc).getSymbols(),
                                       ((DocumentImpl) doc).getDataBytes());           
        } catch (Exception e) {          
            return null;
        }
    }
   
   /**
    * Returns the number of resources currently stored in this collection or 0
    * if the collection is empty.
    *
    * @return the number of resource in the collection.
    * @exception XMLDBException with expected error codes.<br />
    <code>ErrorCodes.VENDOR_ERROR</code> for any vendor
    *  specific errors that occur.<br />
    <code>ErrorCodes.COLLECTION_CLOSED</code> if the <code>close</code>
    *  method has been called on the <code>Collection</code><br />
    */
    public int getResourceCount() throws XMLDBException {
       
        checkOpen();
        try {           
            return (int) col.getDocumentCount();
        } catch (Exception e) {           
            throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e);
        }
    }
   
   /**
    * Stores the provided resource into the database. If the resource does not
    * already exist it will be created. If it does already exist it will be
    * updated.
    *
    * @param res the resource to store in the database.
    * @exception XMLDBException with expected error codes.<br />
    <code>ErrorCodes.VENDOR_ERROR</code> for any vendor
    *  specific errors that occur.<br />
    <code>ErrorCodes.INVALID_RESOURCE</code> if the <code>Resource</code> is
    *   not valid.
    *  <code>ErrorCodes.COLLECTION_CLOSED</code> if the <code>close</code>
    *  method has been called on the <code>Collection</code><br />
    */
    public void storeResource(Resource res) throws XMLDBException {

       if (!(res instanceof XMLResource)) {
          throw new XMLDBException(ErrorCodes.INVALID_RESOURCE,
                                   "Only XML resources supported");
       }

       if (res.getContent() == null) {
          throw new XMLDBException(ErrorCodes.INVALID_RESOURCE,
                                   "no resource data");
       }
      
       checkOpen();

       try {
          String name = "";
          Node content = ((XMLResourceImpl) res).getContentAsDOM();
          if (content != null && content instanceof Document) {          
             if (res.getId() != null) {
                col.insertDocument(res.getId(),
                                   (Document) content);
             }
             else {
                name = col.insertDocument((Document) content).toString();
                ((XMLResourceImpl) res).setId(name);
             }
          }
          else {
             throw new XMLDBException(ErrorCodes.INVALID_RESOURCE,
                                      "A resource must be a document in order to be stored.");
          }
       } catch (Exception e) {
          throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e);
       }
    }
   
   /* see superclass for documentation */
    public boolean isOpen() {
       return (col != null);
    }
   
   /* see superclass for documentation */
    public String getURI() {
        return "xmldb:" + DatabaseImpl.DRIVER_NAME + "://" + collPath;
    }
   
   /**
    * Returns a <code>Collection</code> instance for the requested child collection
    * if it exists.
    *
    * @param name the name of the child collection to retrieve.
    * @return the requested child collection or null if it couldn't be found.
    * @exception XMLDBException with expected error codes.<br />
    <code>ErrorCodes.VENDOR_ERROR</code> for any vendor
    *  specific errors that occur.<br />
    <code>ErrorCodes.COLLECTION_CLOSED</code> if the <code>close</code>
    *  method has been called on the <code>Collection</code><br />
    */
   public org.xmldb.api.base.Collection getChildCollection(String name) throws XMLDBException {

      if (name.indexOf('/') != -1) {
         throw new XMLDBException(ErrorCodes.INVALID_COLLECTION);
      }

      try {
         return new CollectionImpl(db, collPath + "/" + name);
      }
      catch (XMLDBException e) {
         if (e.errorCode == ErrorCodes.NO_SUCH_COLLECTION) {
            // per getChildCollection contract, return null if not found
            return null;
         }
         throw e;
      }
   }
       
   /**
    * Creates a new unique ID within the context of the <code>Collection</code>
    *
    * @return the created id as a string.
    * @exception XMLDBException with expected error codes.<br />
    <code>ErrorCodes.VENDOR_ERROR</code> for any vendor
    *  specific errors that occur.<br />
    <code>ErrorCodes.COLLECTION_CLOSED</code> if the <code>close</code>
    *  method has been called on the <code>Collection</code><br />
    */
    public String createId() throws XMLDBException {

        checkOpen();
        try {           
            return col.createNewOID().toString();
        } catch (Exception e) {           
            throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e);
        }
    }
   
   /**
    * Releases all resources consumed by the <code>Collection</code>.
    * The <code>close</code> method must
    * always be called when use of a <code>Collection</code> is complete. It is
    * not safe to use a  <code>Collection</code> after the <code>close</code>
    * method has been called.
    *
    * @exception XMLDBException with expected error codes.<br />
    <code>ErrorCodes.VENDOR_ERROR</code> for any vendor
    *  specific errors that occur.<br />
    */
    public void close() throws org.xmldb.api.base.XMLDBException {
       col = null;
       db.flushConfig();
    }
   
   /**
    * Returns the parent collection for this collection or null if no parent
    * collection exists.
    *
    * @return the parent <code>Collection</code> instance.
    * @exception XMLDBException with expected error codes.<br />
    <code>ErrorCodes.VENDOR_ERROR</code> for any vendor
    *  specific errors that occur.<br />
    <code>ErrorCodes.COLLECTION_CLOSED</code> if the <code>close</code>
    *  method has been called on the <code>Collection</code><br />
    */
   public org.xmldb.api.base.Collection getParentCollection() throws XMLDBException {
      // If there's only one slash then it's the root.
      // Not too sure about the robustness of this code.
      if (collPath.equals("/") || collPath.equals("")) {
         return null;
      }

      try {
         return new CollectionImpl(db, collPath.substring(0,
               collPath.lastIndexOf('/')));
      }
      catch (XMLDBException e) {
         if (e.errorCode == ErrorCodes.NO_SUCH_COLLECTION) {
            // per getParentCollection contract, return null if no parent
            return null;
         }
         throw e;
      }
   }
   
   /**
    * Removes the <code>Resource</code> from the database.
    *
    * @param res the resource to remove.
    * @exception XMLDBException with expected error codes.<br />
    <code>ErrorCodes.VENDOR_ERROR</code> for any vendor
    *  specific errors that occur.<br />
    <code>ErrorCodes.INVALID_RESOURCE</code> if the <code>Resource</code> is
    *   not valid.<br />
    <code>ErrorCodes.NO_SUCH_RESOURCE</code> if the <code>Resource</code> is
    *   not known to this <code>Collection</code>.
    *  <code>ErrorCodes.COLLECTION_CLOSED</code> if the <code>close</code>
    *  method has been called on the <code>Collection</code><br />
    */
    public void removeResource(Resource res) throws XMLDBException {

       if (!(res instanceof XMLResource)) {
          throw new XMLDBException(ErrorCodes.INVALID_RESOURCE,
                                   "Only XML resources supported");
       }

       if (res.getId() == null) {
          throw new XMLDBException(ErrorCodes.VENDOR_ERROR,
                                   "This resource is a query result and can " +
                                   "not be removed from the database.");
       }
      
       checkOpen();
       try {
          col.remove(res.getId());
       } catch (Exception e) {
          throw new XMLDBException(ErrorCodes.NO_SUCH_RESOURCE, e);
       }
    }
   
   /**
    * Returns a list of collection names naming all child collections
    * of the current collection. If no child collections exist an empty list is
    * returned.
    *
    * @return an array containing collection names for all child
    *      collections.
    * @exception XMLDBException with expected error codes.<br />
    <code>ErrorCodes.VENDOR_ERROR</code> for any vendor
    *  specific errors that occur.<br />
    <code>ErrorCodes.COLLECTION_CLOSED</code> if the <code>close</code>
    *  method has been called on the <code>Collection</code><br />
    */
    public String[] listChildCollections() throws XMLDBException {
       
        checkOpen();
        try {           
            return col.listCollections();
        } catch (Exception e) {           
            throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e);
        }  
    }
   
   /**
    * Returns the number of child collections under this
    * <code>Collection</code> or 0 if no child collections exist.
    *
    * @return the number of child collections.
    * @exception XMLDBException with expected error codes.<br />
    <code>ErrorCodes.VENDOR_ERROR</code> for any vendor
    *  specific errors that occur.<br />
    <code>ErrorCodes.COLLECTION_CLOSED</code> if the <code>close</code>
    *  method has been called on the <code>Collection</code><br />
    */
    public int getChildCollectionCount() throws XMLDBException {

        checkOpen();
        try {           
            return (int) col.countCollections();           
        } catch (Exception e) {
            throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e);
        }  
    }
   
   /**
    * Returns a list of the ids for all resources stored in the collection.
    *
    * @return a string array containing the names for all
    *  <code>Resource</code>s in the collection.
    * @exception XMLDBException with expected error codes.<br />
    <code>ErrorCodes.VENDOR_ERROR</code> for any vendor
    *  specific errors that occur.<br />
    <code>ErrorCodes.COLLECTION_CLOSED</code> if the <code>close</code>
    *  method has been called on the <code>Collection</code><br />
    */
    public String[] listResources() throws XMLDBException {
       
        checkOpen();
        try {
            return col.listDocuments();
        } catch (Exception e) {           
            throw new XMLDBException(ErrorCodes.UNKNOWN_ERROR, e);
        }  
    } 

   /* see superclass for documentation */
    public ResourceSet query(String name, String queryLang, String query, Hashtable nsMap)
            throws XMLDBException {
               
        checkOpen();
        try {
            // Copy the namespaces into a NamespaceMap.
            NamespaceMap namespaces = new NamespaceMap();
            Enumeration keys = nsMap.keys();
            while (keys.hasMoreElements()) {
               String key = (String) keys.nextElement();
               namespaces.put(key, nsMap.get(key));
            }

            NodeSet result;
            if (name != null) {               
               result = col.queryDocument(queryLang, query, namespaces, name);
            }
            else {
               result = col.queryCollection(queryLang, query, namespaces);
            }
           
            ResourceSetImpl rs = new ResourceSetImpl(this, null);

            while (result.hasMoreNodes()) {

               Node n = result.getNextNode();
               if ( n instanceof DBNode ) {
                  ( ( DBNode ) n ).expandSource();
               }

               String documentId = ((Element) n).getAttributeNS(QUERY_NS, "key");

               XMLResourceImpl resource = new XMLResourceImpl(null, documentId, this,
                    TextWriter.toString( n ));
               rs.addResource(resource);
            }
        
            return rs;
        } catch (Exception e) {           
            throw FaultCodes.createXMLDBException(FaultCodes.QRY_PROCESSING_ERROR, "Query error", e);
        }
    }
   
   /* see superclass for documentation */
    public org.xmldb.api.base.Collection createCollection(String name)
            throws XMLDBException {

        checkOpen();
        try {
           Document doc = new DocumentImpl();

           Element colEle = doc.createElement("collection");
           colEle.setAttribute("compressed", "true");
           colEle.setAttribute("name", name);
           doc.appendChild(colEle);

           Element filEle = doc.createElement("filer");
           filEle.setAttribute("class", "org.apache.xindice.core.filer.BTreeFiler");
           colEle.appendChild(filEle);          

           return createCollection(name, doc);
        } catch (Exception e) {           
            throw new XMLDBException(ErrorCodes.INVALID_COLLECTION,
                    "Cannot create child collection", e);
        }
    }

   /* see superclass for documentation */
     public org.xmldb.api.base.Collection createCollection(String name, Document configuration) throws XMLDBException {
        checkOpen();
        try {
           Configuration config = new Configuration(configuration.getDocumentElement(), false);
           col.createCollection( name, config );

           return getChildCollection(name);
        }
        catch (Exception e) {        
           throw new XMLDBException(ErrorCodes.INVALID_COLLECTION,
                    "Cannot create child collection", e);
        }
     }

   /* see superclass for documentation */
    public void removeCollection(String childName) throws XMLDBException {
       
        checkOpen();
        try {
            col.dropCollection( col.getCollection( childName ) );
        } catch (Exception e) {
            throw new XMLDBException(ErrorCodes.INVALID_COLLECTION,
                    "Cannot remove child collection", e);
        }
    }

   /* see superclass for documentation */
     public String[] listIndexers() throws XMLDBException {
        checkOpen();
        try {
           return col.listIndexers();
        }
        catch (Exception e) {
           throw FaultCodes.createXMLDBException(e);
        }
     }

   /* see superclass for documentation */
     public void createIndexer(Document configuration) throws XMLDBException {
        checkOpen();
        try {
           col.createIndexer(new Configuration(configuration, false));
        }
        catch (Exception e) {
           throw FaultCodes.createXMLDBException(e);
        }
     }

   /* see superclass for documentation */
     public void dropIndexer(String name) throws XMLDBException {
        checkOpen();
        try {
           col.dropIndexer(col.getIndexer(name));
        }
        catch (Exception e) {
           throw FaultCodes.createXMLDBException(e);
        }
     }

   /* see superclass for documentation */
     public void shutdown() throws XMLDBException {
        try {
           db.close();
        }
        catch (Exception e) {
           throw FaultCodes.createXMLDBException(e);
        }
     }

}
TOP

Related Classes of org.apache.xindice.client.xmldb.embed.CollectionImpl

TOP
Copyright © 2015 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.