You are viewing a plain text version of this content. The canonical link for it is here.
Posted to slide-dev@jakarta.apache.org by re...@apache.org on 2001/02/08 08:54:20 UTC

cvs commit: jakarta-slide/src/stores/slidestore/reference JDBCContentStore.java

remm        01/02/07 23:54:20

  Added:       src/stores/slidestore/reference JDBCContentStore.java
  Log:
  - Add a JDBC content store.
  - There are still issues with this new store.
    For example, creating an object, then deleting it, then recreating it will fail.
    I still can't point out the root cause of the failure, and it may happen in other
    cases.
  - The table creation needs to be done before running Slide (the included
    script will most likely only work with hSQL), similar to what needs to be done
    for the JDBC descriptors store.
  
  Revision  Changes    Path
  1.1                  jakarta-slide/src/stores/slidestore/reference/JDBCContentStore.java
  
  Index: JDBCContentStore.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-slide/src/stores/slidestore/reference/JDBCContentStore.java,v 1.1 2001/02/08 07:54:20 remm Exp $
   * $Revision: 1.1 $
   * $Date: 2001/02/08 07:54:20 $
   *
   * ====================================================================
   *
   * 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 acknowlegement:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowlegement may appear in the software itself,
   *    if and wherever such third-party acknowlegements normally appear.
   *
   * 4. The names "The Jakarta Project", "Tomcat", 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 names without prior written
   *    permission of the Apache 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 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.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   * [Additional notices, if required by prior licensing conditions]
   *
   */
  
  package slidestore.reference;
  
  import java.lang.reflect.Constructor;
  import java.util.Hashtable;
  import java.util.Enumeration;
  import java.util.Vector;
  import java.util.Date;
  import java.io.FileWriter;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.io.InputStreamReader;
  import java.io.IOException;
  import java.io.File;
  import java.sql.*;
  import javax.transaction.xa.XAException;
  import javax.transaction.xa.Xid;
  import org.apache.slide.common.*;
  import org.apache.slide.store.*;
  import org.apache.slide.structure.*;
  import org.apache.slide.security.*;
  import org.apache.slide.content.*;
  
  /**
   * JDBC 2.0 compliant implementation of ContentStore.
   *
   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
   * @version $Revision: 1.1 $
   */
  public class JDBCContentStore extends AbstractSimpleService
      implements ContentStore {
      
      
      // -------------------------------------------------------------- Constants
      
      
      public static final int BUFFER_SIZE = 2048;
      public static final String CHARACTER_ENCODING = "8859_1";
      protected static final int REVISION_URI = 1;
      protected static final int REVISION_NUMBER = 2;
      protected static final int REVISION_CONTENT = 3;
      
      
      // ----------------------------------------------------- Instance Variables
      
      
      /**
       * Database connection.
       */
      private Connection connection;
      
      
      /**
       * Driver class name.
       */
      private String driver;
      
      
      /**
       * Connection URL.
       */
      private String url;
      
      
      /**
       * User name.
       */
      private String user;
      
      
      /**
       * Password.
       */
      private String password;
      
      
      // -------------------------------------------------------- Service Methods
      
      
      /**
       * Read parameters.
       *
       * @param parameters Hashtable containing the parameters' name
       * and associated value
       */
      public synchronized void setParameters(Hashtable parameters)
          throws ServiceParameterErrorException,
          ServiceParameterMissingException {
          
          // Driver classname
          driver = (String) parameters.get("driver");
          
          // Connection url
          url = (String) parameters.get("url");
          
          // User name
          user = (String) parameters.get("user");
          if (user == null) {
              user = new String();
          }
          
          // Password
          password = (String) parameters.get("password");
          if (password == null) {
              password = new String();
          }
          
      }
      
      
      /**
       * Connects to JDBC and creates the basic table structure.
       *
       * @exception ServiceConnectionFailedException Connection to the 
       * database failed
       */
      public synchronized void connect()
          throws ServiceConnectionFailedException {
          try {
              connection = DriverManager.getConnection
                  ("jdbc:" + url, user, password);
          } catch (SQLException e) {
              throw new ServiceConnectionFailedException(this, e);
          }
          try {
              Statement statement = connection.createStatement();
              String s = "create table revisioncontent(uri varchar(65536), "
                  + "xnumber varchar(20), content LONGVARBINARY)";
              statement.execute(s);
          } catch (SQLException e) {
          }
      }
      
      
      /**
       * Disconnects from content store.
       *
       * @exception ServiceDisconnectionFailedException
       */
      public synchronized void disconnect()
          throws ServiceDisconnectionFailedException {
          try {
              if (connection != null)
                  connection.close();
              connection = null;
          } catch (SQLException e) {
              throw new ServiceDisconnectionFailedException(this, e);
          }
      }
      
      
      /**
       * Initializes content store.
       *
       * @exception ServiceInitializationFailedException Throws an exception
       * if the store has already been initialized before
       */
      public synchronized void initialize(NamespaceAccessToken token)
          throws ServiceInitializationFailedException {
          try {
              // Loading and registering driver
              Class driverClass = Class.forName(driver);
              Driver databaseDriver = (Driver) driverClass.newInstance();
              DriverManager.registerDriver(databaseDriver);
          } catch (ClassNotFoundException e) {
              throw new ServiceInitializationFailedException
                  (this, e.getMessage());
          } catch (InstantiationException e) {
              throw new ServiceInitializationFailedException
                  (this, e.getMessage());
          } catch (IllegalAccessException e) {
              throw new ServiceInitializationFailedException
                  (this, e.getMessage());
          } catch (SQLException e) {
              throw new ServiceInitializationFailedException
                  (this, e.getMessage());
          } catch (ClassCastException e) {
              throw new ServiceInitializationFailedException
                  (this, e.getMessage());
          } catch (Exception e) {
              throw new ServiceInitializationFailedException
                  (this, e.getMessage());
          }
      }
      
      
      /**
       * Deletes content store.
       *
       * @exception ServiceResetFailedException
       */
      public void reset()
          throws ServiceResetFailedException {
          try {
              connectIfNeeded();
              Statement statement = connection.createStatement();
              String s = "drop table revisioncontent";
              statement.execute(s);
              disconnect();
          } catch (SQLException e) {
              throw new ServiceResetFailedException(this, e.getMessage());
          } catch (ServiceAccessException e) {
              throw new ServiceResetFailedException(this, e.getMessage());
          } catch (ServiceConnectionFailedException e) {
              throw new ServiceResetFailedException(this, e.getMessage());
          } catch (ServiceDisconnectionFailedException e) {
              throw new ServiceResetFailedException(this, e.getMessage());
          }
      }
      
      
      /**
       * This function tells whether or not the service is connected.
       *
       * @return boolean true if we are connected
       * @exception ServiceAccessException Service access error
       */
      public boolean isConnected()
          throws ServiceAccessException {
          try {
              return ((connection != null) && (!connection.isClosed()));
          } catch (SQLException e) {
              throw new ServiceAccessException(this, e);
          }
      }
      
      
      // ----------------------------------------------------- XAResource Methods
      
      
      /**
       * Commit the global transaction specified by xid.
       */
      public void commit(Xid xid, boolean onePhase)
          throws XAException {
          super.commit(xid, onePhase);
          try {
              connection.commit();
              connection.setAutoCommit(true);
          } catch (SQLException e) {
              throw new XAException(XAException.XA_RBCOMMFAIL);
          }
      }
      
      
      /**
       * Inform the resource manager to roll back work done on behalf of a
       * transaction branch.
       */
      public void rollback(Xid xid)
          throws XAException {
          super.rollback(xid);
          try {
              connection.rollback();
              connection.setAutoCommit(true);
          } catch (SQLException e) {
              throw new XAException(XAException.XA_HEURCOM);
          }
      }
      
      
      /**
       * Start work on behalf of a transaction branch specified in xid.
       */
      public void start(Xid xid, int flags)
          throws XAException {
          super.start(xid, flags);
          try {
              connection.setAutoCommit(false);
          } catch (SQLException e) {
              throw new XAException(XAException.XAER_RMERR);
          }
      }
      
      
      // --------------------------------------------------- ContentStore Methods
      
      
      /**
       * Retrive revision content.
       *
       * @param uri Uri
       * @param revisionNumber Node revision number
       */
      public NodeRevisionContent retrieveRevisionContent
          (Uri uri, NodeRevisionDescriptor revisionDescriptor)
          throws ServiceAccessException, RevisionNotFoundException {
          
          NodeRevisionContent result = null;
          String revisionUri = uri.toString();
          String revisionNumber = 
              revisionDescriptor.getRevisionNumber().toString();
          
          try {
              PreparedStatement selectStatement = connection.prepareStatement
                  ("select * from revisioncontent where uri = ? and "
                   + "xnumber = ?");
              selectStatement.setString(1, revisionUri);
              selectStatement.setString(2, revisionNumber);
              ResultSet rs = selectStatement.executeQuery();
              if (!rs.next()) {
                  throw new RevisionNotFoundException
                      (uri.toString(),
                       revisionDescriptor.getRevisionNumber());
              }
              InputStream is = rs.getBinaryStream(REVISION_CONTENT);
              if (is == null) {
                  throw new RevisionNotFoundException
                      (uri.toString(),
                       revisionDescriptor.getRevisionNumber());
              }
              InputStreamReader reader = new InputStreamReader
                  (is, CHARACTER_ENCODING);
              result = new NodeRevisionContent();
              result.setContent(reader);
              result.setContent(is);
          } catch (SQLException e) {
              throw new ServiceAccessException(this, e.getMessage());
          } catch (Exception e) {
              e.printStackTrace();
              throw new ServiceAccessException(this, e.getMessage());
          }
          
          return result;
          
      }
      
      
      /**
       * Create a new revision
       *
       * @param uri Uri
       * @param revisionDescriptor Node revision descriptor
       * @param revisionContent Node revision content
       */
      public void createRevisionContent
          (Uri uri, NodeRevisionDescriptor revisionDescriptor,
           NodeRevisionContent revisionContent)
          throws ServiceAccessException, RevisionAlreadyExistException {
          
          String revisionUri = uri.toString();
          String revisionNumber = 
              revisionDescriptor.getRevisionNumber().toString();
          long contentLength = revisionDescriptor.getContentLength();
          
          try {
              
              PreparedStatement selectStatement = connection.prepareStatement
                  ("select * from revisioncontent where uri = ? and "
                   + "xnumber = ?");
              selectStatement.setString(1, revisionUri);
              selectStatement.setString(2, revisionNumber);
              ResultSet rs = selectStatement.executeQuery();
              if (rs.next()) {
                  throw new RevisionAlreadyExistException
                      (uri.toString(),
                       revisionDescriptor.getRevisionNumber());
              }
              
              storeContent(revisionUri, revisionNumber, revisionDescriptor, 
                           revisionContent);
              
          } catch (SQLException e) {
              throw new ServiceAccessException(this, e.getMessage());
          } catch (IOException e) {
              throw new ServiceAccessException(this, e.getMessage());
          } catch(RevisionAlreadyExistException e) {
              throw e; // we do NOT want this caught by next clause.
          } catch (Exception e) {
              e.printStackTrace();
              throw new ServiceAccessException(this, e.getMessage());
          }
          
      }
      
      
      /**
       * Modify the latest revision of an object.
       *
       * @param uri Uri
       * @param revisionDescriptor Node revision descriptor
       * @param revisionContent Node revision content
       */
      public void storeRevisionContent
          (Uri uri, NodeRevisionDescriptor revisionDescriptor,
           NodeRevisionContent revisionContent)
          throws ServiceAccessException, RevisionNotFoundException {
          
          String revisionUri = uri.toString();
          String revisionNumber = 
              revisionDescriptor.getRevisionNumber().toString();
          
          try {
              
              PreparedStatement selectStatement = connection.prepareStatement
                  ("select * from revisioncontent where uri = ? and "
                   + "xnumber = ?");
              selectStatement.setString(1, revisionUri);
              selectStatement.setString(2, revisionNumber);
              ResultSet rs = selectStatement.executeQuery();
              if (!rs.next()) {
                  throw new RevisionNotFoundException
                      (uri.toString(),
                       revisionDescriptor.getRevisionNumber());
              }
              
              removeContent(revisionUri, revisionNumber);
              storeContent(revisionUri, revisionNumber, revisionDescriptor, 
                           revisionContent);
              
          } catch (SQLException e) {
              e.printStackTrace();
              throw new ServiceAccessException(this, e.getMessage());
          } catch (IOException e) {
              throw new ServiceAccessException(this, e.getMessage());
          } catch(RevisionNotFoundException e) {
              throw e; // we do NOT want this caught by next clause.
          } catch (Exception e) {
              e.printStackTrace();
              throw new ServiceAccessException(this, e.getMessage());
          }
          
      }
      
      
      /**
       * Remove revision.
       *
       * @param uri Uri
       * @param revisionNumber Node revision number
       */
      public void removeRevisionContent
          (Uri uri, NodeRevisionDescriptor revisionDescriptor)
          throws ServiceAccessException {
          
          String revisionUri = uri.toString();
          String revisionNumber = 
              revisionDescriptor.getRevisionNumber().toString();
          
          try {
              
              removeContent(revisionUri, revisionNumber);
              
          } catch (Exception e) {
              e.printStackTrace();
              throw new ServiceAccessException(this, e.getMessage());
          }
          
      }
      
      
      // ------------------------------------------------------ Protected Methods
      
      
      /**
       * Store a revision.
       */
      protected void storeContent(String revisionUri, String revisionNumber,
                                  NodeRevisionDescriptor revisionDescriptor,
                                  NodeRevisionContent revisionContent)
          throws IOException, SQLException {
          
          PreparedStatement insertStatement = connection.prepareStatement
              ("insert into revisioncontent values(?, ?, ?)");
          insertStatement.setString(1, revisionUri);
          insertStatement.setString(2, revisionNumber);
          
          InputStream is = revisionContent.streamContent();
          
          if (is != null) {
              
              OutputStream os = null;
              // We copy 8 ko with each read
              byte[] buffer = new byte[BUFFER_SIZE];
              long position = 0;
              
              long contentLength = revisionDescriptor.getContentLength();
              File tempFile = null;
              
              if (contentLength == -1) {
                  
                  // If content length is unspecified, we have to buffer
                  // to a temp file.
                  String tempFileName = revisionUri + "-" + revisionNumber;
                  int tempFileNameLength = tempFileName.length();
                  if (tempFileNameLength > 200)
                      tempFileName = tempFileName.substring
                          (tempFileNameLength - 200, tempFileNameLength);
                  tempFile = File.createTempFile(tempFileName, null);
                  
                  FileOutputStream fos = new FileOutputStream(tempFile);
                  while (true) {
                      int nChar = is.read(buffer);
                      if (nChar == -1) {
                          break;
                      }
                      fos.write(buffer, 0, nChar);
                      position = position + nChar;
                  }
                  fos.close();
                  
                  if (position != contentLength) {
                      if (position < contentLength) {
                          // Not enough bytes read !!!
                          throw new IOException("Not enough bytes read");
                      }
                      if (position > contentLength) {
                          // Not enough bytes read !!!
                          throw new IOException("Too many bytes read");
                      }
                      // FIXME : Delete the file
                  }
                  
                  is = new FileInputStream(tempFile);
                  contentLength = tempFile.length();
                  
              }
              
              // FIXME ? Cast from long to int won't allow files > 4GB.
              insertStatement.setBinaryStream(3, is, (int) contentLength);
              insertStatement.executeUpdate();
              
              revisionDescriptor.setContentLength(contentLength);
              
              if (tempFile != null) {
                  is.close();
                  tempFile.delete();
              }
              
          }
          
      }
      
      
      /**
       * Remove content.
       */
      protected void removeContent(String revisionUri, String revisionNumber)
          throws SQLException {
          
          PreparedStatement deleteStatement = connection.prepareStatement
              ("delete from revisioncontent where uri = ? and xnumber = ?");
          deleteStatement.setString(1, revisionUri);
          deleteStatement.setString(2, revisionNumber);
          deleteStatement.executeUpdate();
          
      }
      
      
  }