You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by ah...@apache.org on 2012/09/05 00:12:52 UTC

[27/50] [abbrv] Moved Awsapi (EC2/S3) from Hibernate framework to CloudStack Generic Dao Framework

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/39aa7d86/awsapi/src/com/cloud/bridge/persist/dao/SObjectItemDao.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/persist/dao/SObjectItemDao.java b/awsapi/src/com/cloud/bridge/persist/dao/SObjectItemDao.java
index f91d180..2258309 100644
--- a/awsapi/src/com/cloud/bridge/persist/dao/SObjectItemDao.java
+++ b/awsapi/src/com/cloud/bridge/persist/dao/SObjectItemDao.java
@@ -1,30 +1,14 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License.
 package com.cloud.bridge.persist.dao;
 
-import com.cloud.bridge.model.SObjectItem;
-import com.cloud.bridge.persist.EntityDao;
+import java.util.List;
+
+import com.cloud.bridge.model.SObjectItemVO;
+import com.cloud.utils.db.GenericDao;
+
+public interface SObjectItemDao extends GenericDao<SObjectItemVO, Long> {
+
+    SObjectItemVO getByObjectIdNullVersion(long id);
+
+    List<SObjectItemVO> getItems(long sobjectID);
 
-public class SObjectItemDao extends EntityDao<SObjectItem> {
-	public SObjectItemDao() {
-		super(SObjectItem.class);
-	}
-	
-	public SObjectItem getByObjectIdNullVersion(long id) {
-		return queryEntity("from SObjectItem where theObject=? and version is null", new Object[] { id });
-	}
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/39aa7d86/awsapi/src/com/cloud/bridge/persist/dao/SObjectItemDaoImpl.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/persist/dao/SObjectItemDaoImpl.java b/awsapi/src/com/cloud/bridge/persist/dao/SObjectItemDaoImpl.java
new file mode 100644
index 0000000..ec632bb
--- /dev/null
+++ b/awsapi/src/com/cloud/bridge/persist/dao/SObjectItemDaoImpl.java
@@ -0,0 +1,71 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.bridge.persist.dao;
+
+import java.util.List;
+
+import javax.ejb.Local;
+
+import com.cloud.bridge.model.SObjectItemVO;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.Transaction;
+
+@Local(value={SObjectItemDao.class})
+public class SObjectItemDaoImpl extends GenericDaoBase<SObjectItemVO, Long> implements SObjectItemDao {
+    
+    	
+	public SObjectItemDaoImpl() {
+	}
+	
+	@Override
+	public SObjectItemVO getByObjectIdNullVersion(long id) {
+	    
+	    Transaction txn = Transaction.open(Transaction.AWSAPI_DB);
+	    SearchBuilder <SObjectItemVO> SearchByID = createSearchBuilder();
+	    SearchByID.and("ID", SearchByID.entity().getId(), SearchCriteria.Op.EQ);
+	    
+	    try {
+    		txn.start();
+    		SearchCriteria<SObjectItemVO> sc = SearchByID.create();
+    		sc.setParameters("ID", id);
+		return findOneBy(sc);
+	    }finally {
+		txn.close();
+	    }
+   	}
+	
+	@Override
+    public List<SObjectItemVO> getItems(long sobjectID) {
+
+        Transaction txn = Transaction.open(Transaction.AWSAPI_DB);
+        SearchBuilder<SObjectItemVO> SearchBySobjectID = createSearchBuilder();
+        SearchBySobjectID.and("SObjectID", SearchBySobjectID.entity().getId(), SearchCriteria.Op.EQ);
+
+        try {
+            txn.start();
+            SearchCriteria<SObjectItemVO> sc = SearchBySobjectID.create();
+            sc.setParameters("SObjectID", sobjectID);
+            return listBy(sc);
+            //findOneIncludingRemovedBy(sc);
+        } finally {
+            txn.close();
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/39aa7d86/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDao.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDao.java b/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDao.java
index 4beb7a3..c178bf8 100644
--- a/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDao.java
+++ b/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDao.java
@@ -1,169 +1,12 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements.  See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership.  The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License.  You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied.  See the License for the
-// specific language governing permissions and limitations
-// under the License.
 package com.cloud.bridge.persist.dao;
 
-import java.sql.*;
+import com.cloud.bridge.model.UserCredentialsVO;
+import com.cloud.utils.db.GenericDao;
 
-import org.apache.log4j.Logger;
+public interface UserCredentialsDao extends GenericDao<UserCredentialsVO, Long> {
 
-import com.cloud.bridge.model.UserCredentials;
-import com.cloud.bridge.service.exception.NoSuchObjectException;
+    UserCredentialsVO getByAccessKey(String cloudAccessKey);
 
+    UserCredentialsVO getByCertUniqueId(String certId);
 
-public class UserCredentialsDao extends BaseDao{
-	public static final Logger logger = Logger.getLogger(UserCredentialsDao.class);
-
-	private Connection conn       = null;
-	
-	public UserCredentialsDao() {
-	}
-	
-	public void setUserKeys( String cloudAccessKey, String cloudSecretKey ) 
-	    throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
-		UserCredentials user = getByAccessKey( cloudAccessKey );
-		PreparedStatement statement = null;
-	
-	    openConnection();	
-        try {
-		    if ( null == user ) {
-			     // -> do an insert since the user does not exist yet
-		         statement = conn.prepareStatement ( "INSERT INTO usercredentials (AccessKey, SecretKey) VALUES(?,?)" );
-		         statement.setString( 1, cloudAccessKey );
-		         statement.setString( 2, cloudSecretKey );
-		    }
-		    else {
-			     // -> do an update since the user exists
-			     statement = conn.prepareStatement ( "UPDATE usercredentials SET SecretKey=? WHERE AccessKey=?" );
-		         statement.setString( 1, cloudSecretKey );
-		         statement.setString( 2, cloudAccessKey );
-		    }
-	        int count = statement.executeUpdate();
-	        statement.close();		    
-
-	    } finally {
-            closeConnection();
-	    }
-	}
-
-	public void setCertificateId( String cloudAccessKey, String certId ) 
-        throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
-	    UserCredentials user = getByAccessKey( cloudAccessKey );
-	    PreparedStatement statement = null;
-
-	    if (null == user) throw new NoSuchObjectException( "Cloud API Access Key [" + cloudAccessKey + "] is unknown" );
-	    
-        openConnection();	
-        try {
-		    statement = conn.prepareStatement ( "UPDATE usercredentials SET CertUniqueId=? WHERE AccessKey=?" );
-	        statement.setString( 1, certId );
-	        statement.setString( 2, cloudAccessKey );
-            int count = statement.executeUpdate();
-            statement.close();		    
-        
-        } finally {
-            closeConnection();
-        }
-    }
-
-	public UserCredentials getByAccessKey( String cloudAccessKey ) 
-	    throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
-		openConnection();
-		
-		UserCredentials user = null;
-		
-		try {
-		    PreparedStatement statement = conn.prepareStatement ( "SELECT SecretKey, CertUniqueId FROM usercredentials WHERE AccessKey=?" );
-		    statement.setString( 1, cloudAccessKey );
-		    statement.executeQuery();
-		    ResultSet rs = statement.getResultSet ();
-		    if (rs.next()) {
-		    	user = new UserCredentials();
-		    	user.setAccessKey( cloudAccessKey );
-		        user.setSecretKey( rs.getString( "SecretKey" ));
-		        user.setCertUniqueId( rs.getString( "CertUniqueId" ));
-		    }
-
-		} finally {
-             closeConnection();
-		}	
-		return user;
-	}
-
-	public UserCredentials getByCertUniqueId( String certId ) 
-        throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
-	    openConnection();
-	
-	    UserCredentials user = null;
-	
-	    try {
-	        PreparedStatement statement = conn.prepareStatement ( "SELECT AccessKey, SecretKey FROM usercredentials WHERE CertUniqueId=?" );
-	        statement.setString( 1, certId );
-	        statement.executeQuery();
-	        ResultSet rs = statement.getResultSet ();
-	        if (rs.next()) {
-	    	    user = new UserCredentials();
-	    	    user.setAccessKey( rs.getString( "AccessKey" ));
-	            user.setSecretKey( rs.getString( "SecretKey" ));
-	            user.setCertUniqueId( certId );
-	        }
-
-	    } finally {
-            closeConnection();
-	    }	
-	    return user;
-    }
-
-	private void openConnection() 
-	    throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
-        if (null == conn) {
-		    Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
-            conn = DriverManager.getConnection( "jdbc:mysql://" + dbHost + "/" + awsapi_dbName, dbUser, dbPassword );
-        }
-	}
-	
-	private void closeConnection() throws SQLException {
-		if (null != conn) conn.close();
-		conn = null;
-	}
-
-	public static void preCheckTableExistence() throws Exception{
-		UserCredentialsDao dao = new UserCredentialsDao();
-		dao.checkTableExistence();
-	}
-
-	private void checkTableExistence() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
-	    openConnection();
-	
-	    try {
-	        PreparedStatement statement = conn.prepareStatement ( "SELECT * FROM usercredentials " );
-	        statement.executeQuery();
-	        ResultSet rs = statement.getResultSet ();
-	        if (rs.next()) {
-	        	return;
-	        }
-	        return;
-
-	    } catch(Exception e) {
-	    	Statement statement = conn.createStatement();
-	    	statement.execute( "create table usercredentials(id integer auto_increment primary key, AccessKey varchar(1000), SecretKey varchar(1000), CertUniqueId varchar(1000))" );
-	    	statement.close();
-	    }
-	    finally{
-	    	closeConnection();
-	    }
-	}
 }

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/39aa7d86/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDaoImpl.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDaoImpl.java b/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDaoImpl.java
new file mode 100644
index 0000000..c19c757
--- /dev/null
+++ b/awsapi/src/com/cloud/bridge/persist/dao/UserCredentialsDaoImpl.java
@@ -0,0 +1,73 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package com.cloud.bridge.persist.dao;
+
+import java.sql.*;
+
+import javax.ejb.Local;
+
+import org.apache.log4j.Logger;
+
+import com.cloud.bridge.model.UserCredentialsVO;
+import com.cloud.utils.db.DB;
+import com.cloud.utils.db.GenericDaoBase;
+import com.cloud.utils.db.SearchBuilder;
+import com.cloud.utils.db.SearchCriteria;
+import com.cloud.utils.db.Transaction;
+
+@Local(value={UserCredentialsDao.class})
+public class UserCredentialsDaoImpl extends GenericDaoBase<UserCredentialsVO, Long> implements UserCredentialsDao {
+	public static final Logger logger = Logger.getLogger(UserCredentialsDaoImpl.class);
+
+	public UserCredentialsDaoImpl() {}
+	
+	@DB
+	@Override
+	public UserCredentialsVO getByAccessKey( String cloudAccessKey ) {
+	        SearchBuilder<UserCredentialsVO> SearchByAccessKey = createSearchBuilder();
+	        Transaction txn = Transaction.open(Transaction.AWSAPI_DB);
+	    try {
+            txn.start();
+            SearchByAccessKey.and("AccessKey", SearchByAccessKey.entity()
+                    .getAccessKey(), SearchCriteria.Op.EQ);
+            SearchByAccessKey.done();
+            SearchCriteria<UserCredentialsVO> sc = SearchByAccessKey.create();
+            sc.setParameters("AccessKey", cloudAccessKey);
+            return findOneBy(sc);
+	    }finally {
+            txn.commit();
+            txn.close();
+	    }
+	}
+	
+	@Override
+	public UserCredentialsVO getByCertUniqueId( String certId ) {
+	    SearchBuilder<UserCredentialsVO> SearchByCertID = createSearchBuilder();
+	    SearchByCertID.and("CertUniqueId", SearchByCertID.entity().getCertUniqueId(), SearchCriteria.Op.EQ);
+	    Transaction txn = Transaction.open(Transaction.AWSAPI_DB);
+	    try {
+            txn.start();
+            SearchCriteria<UserCredentialsVO> sc = SearchByCertID.create();
+            sc.setParameters("CertUniqueId", certId);
+            return findOneBy(sc);
+	    }finally {
+	        txn.close();
+	    }
+	    
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/39aa7d86/awsapi/src/com/cloud/bridge/service/EC2MainServlet.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/service/EC2MainServlet.java b/awsapi/src/com/cloud/bridge/service/EC2MainServlet.java
index 0c904a1..dceb665 100644
--- a/awsapi/src/com/cloud/bridge/service/EC2MainServlet.java
+++ b/awsapi/src/com/cloud/bridge/service/EC2MainServlet.java
@@ -27,12 +27,18 @@ import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
+import org.apache.log4j.Logger;
 
-import com.cloud.bridge.persist.PersistContext;
 import com.cloud.bridge.persist.dao.CloudStackConfigurationDao;
-import com.cloud.bridge.persist.dao.UserCredentialsDao;
+import com.cloud.bridge.persist.dao.CloudStackConfigurationDaoImpl;
 import com.cloud.bridge.util.ConfigurationHelper;
+import com.cloud.utils.component.ComponentLocator;
+import com.cloud.utils.component.Inject;
+import com.cloud.utils.db.DB;
+import com.cloud.utils.db.Transaction;
 
+import net.sf.ehcache.Cache;
+@DB
 public class EC2MainServlet extends HttpServlet{
 
 	private static final long serialVersionUID = 2201599478145974479L;
@@ -41,23 +47,23 @@ public class EC2MainServlet extends HttpServlet{
 	public static final String EC2_SOAP_SERVLET_PATH="/services/AmazonEC2/";
 	public static final String ENABLE_EC2_API="enable.ec2.api";
 	private static boolean isEC2APIEnabled = false;
+	public static final Logger logger = Logger.getLogger(EC2MainServlet.class);
+	CloudStackConfigurationDao csDao = ComponentLocator.inject(CloudStackConfigurationDaoImpl.class);
 	
 	/**
 	 * We build the path to where the keystore holding the WS-Security X509 certificates
 	 * are stored.
 	 */
+	@DB
 	public void init( ServletConfig config ) throws ServletException {
 		try{
-    	    ConfigurationHelper.preConfigureConfigPathFromServletContext(config.getServletContext());
-    		UserCredentialsDao.preCheckTableExistence();
+		    ConfigurationHelper.preConfigureConfigPathFromServletContext(config.getServletContext());
     		// check if API is enabled
-    		CloudStackConfigurationDao csDao = new CloudStackConfigurationDao();
     		String value = csDao.getConfigValue(ENABLE_EC2_API);
     		if(value != null){
     		    isEC2APIEnabled = Boolean.valueOf(value);
     		}
-    		PersistContext.commitTransaction(true);
-            PersistContext.closeSession(true);
+    		logger.info("Value of EC2 API Flag ::" + value);
 		}catch(Exception e){
 		    throw new ServletException("Error initializing awsapi: " + e.getMessage());
 		}

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/39aa7d86/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java b/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java
index ceaf59d..4f74873 100644
--- a/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java
+++ b/awsapi/src/com/cloud/bridge/service/EC2RestServlet.java
@@ -94,10 +94,9 @@ import com.amazon.ec2.RunInstancesResponse;
 import com.amazon.ec2.StartInstancesResponse;
 import com.amazon.ec2.StopInstancesResponse;
 import com.amazon.ec2.TerminateInstancesResponse;
-import com.cloud.bridge.model.UserCredentials;
-import com.cloud.bridge.persist.PersistContext;
-import com.cloud.bridge.persist.dao.OfferingDao;
-import com.cloud.bridge.persist.dao.UserCredentialsDao;
+import com.cloud.bridge.model.UserCredentialsVO;
+import com.cloud.bridge.persist.dao.OfferingDaoImpl;
+import com.cloud.bridge.persist.dao.UserCredentialsDaoImpl;
 import com.cloud.bridge.service.controller.s3.ServiceProvider;
 import com.cloud.bridge.service.core.ec2.EC2AssociateAddress;
 import com.cloud.bridge.service.core.ec2.EC2AuthorizeRevokeSecurityGroup;
@@ -140,11 +139,15 @@ import com.cloud.bridge.util.AuthenticationUtils;
 import com.cloud.bridge.util.ConfigurationHelper;
 import com.cloud.bridge.util.EC2RestAuth;
 import com.cloud.stack.models.CloudStackAccount;
+import com.cloud.utils.component.ComponentLocator;
+import com.cloud.utils.db.Transaction;
 
 
 public class EC2RestServlet extends HttpServlet {
 
 	private static final long serialVersionUID = -6168996266762804888L;
+	protected final UserCredentialsDaoImpl ucDao = ComponentLocator.inject(UserCredentialsDaoImpl.class);
+	protected final OfferingDaoImpl ofDao = ComponentLocator.inject(OfferingDaoImpl.class);
 	
 	public static final Logger logger = Logger.getLogger(EC2RestServlet.class);
 	
@@ -278,8 +281,6 @@ public class EC2RestServlet extends HttpServlet {
         		logger.error("Unsupported action " + action);
         		throw new EC2ServiceException(ClientError.Unsupported, "This operation is not available");
     	    }
-    	    PersistContext.commitTransaction();     
-    	    PersistContext.commitTransaction(true);
     	    
         } catch( EC2ServiceException e ) {
     		response.setStatus(e.getErrorCode());
@@ -306,8 +307,6 @@ public class EC2RestServlet extends HttpServlet {
 			} catch (IOException e) {
 	    		logger.error("Unexpected exception " + e.getMessage(), e);
 			}
-			PersistContext.closeSession();
-			PersistContext.closeSession(true);
         }       
     }
    
@@ -343,7 +342,7 @@ public class EC2RestServlet extends HttpServlet {
     private void setUserKeys( HttpServletRequest request, HttpServletResponse response ) {
     	String[] accessKey = null;
     	String[] secretKey = null;
-    	
+    	Transaction txn = null;
     	try {
 		    // -> all these parameters are required
             accessKey = request.getParameterValues( "accesskey" );
@@ -369,15 +368,20 @@ public class EC2RestServlet extends HttpServlet {
     	UserContext context = UserContext.current();
 
         try {
+            txn = Transaction.open(Transaction.AWSAPI_DB);
             // -> use the keys to see if the account actually exists
     	    ServiceProvider.getInstance().getEC2Engine().validateAccount( accessKey[0], secretKey[0] );
-    	    UserCredentialsDao credentialDao = new UserCredentialsDao();
-    	    credentialDao.setUserKeys( accessKey[0], secretKey[0] ); 
-    	    
+/*    	    UserCredentialsDao credentialDao = new UserCredentialsDao();
+    	    credentialDao.setUserKeys(  ); 
+*/    	    UserCredentialsVO user = new UserCredentialsVO(accessKey[0], secretKey[0]);
+	        ucDao.persist(user);
+	        txn.commit();
+	    
         } catch( Exception e ) {
    		    logger.error("SetUserKeys " + e.getMessage(), e);
     		response.setStatus(401);
         	endResponse(response, e.toString());
+        	txn.close();
         	return;
         }
     	response.setStatus(200);	
@@ -402,6 +406,7 @@ public class EC2RestServlet extends HttpServlet {
      */
     private void setCertificate( HttpServletRequest request, HttpServletResponse response ) 
         throws Exception { 
+        Transaction txn = null;
     	try {
     	    // [A] Pull the cert and cloud AccessKey from the request
             String[] certificate = request.getParameterValues( "cert" );
@@ -437,10 +442,16 @@ public class EC2RestServlet extends HttpServlet {
     	    // [C] Associate the cert's uniqueId with the Cloud API keys
             String uniqueId = AuthenticationUtils.X509CertUniqueId( userCert );
             logger.debug( "SetCertificate, uniqueId: " + uniqueId );
-    	    UserCredentialsDao credentialDao = new UserCredentialsDao();
-    	    credentialDao.setCertificateId( accessKey[0], uniqueId ); 
-    		response.setStatus(200);
+/*    	    UserCredentialsDao credentialDao = new UserCredentialsDao();
+    	    credentialDao.setCertificateId( accessKey[0], uniqueId );
+*/	        
+            txn = Transaction.open(Transaction.AWSAPI_DB);
+            UserCredentialsVO user = ucDao.getByAccessKey(accessKey[0]);
+            user.setCertUniqueId(uniqueId);
+            ucDao.update(user.getId(), user);
+            response.setStatus(200);
             endResponse(response, "User certificate set successfully");
+            txn.commit();
     	    
     	} catch( NoSuchObjectException e ) {
     		logger.error("SetCertificate exception " + e.getMessage(), e);
@@ -449,7 +460,10 @@ public class EC2RestServlet extends HttpServlet {
         } catch( Exception e ) {
     		logger.error("SetCertificate exception " + e.getMessage(), e);
     		response.sendError(500, "SetCertificate exception " + e.getMessage());
+        } finally {
+            txn.close();
         }
+    	
     }
  
     /**
@@ -464,7 +478,8 @@ public class EC2RestServlet extends HttpServlet {
      * algorithm.
      */
     private void deleteCertificate( HttpServletRequest request, HttpServletResponse response ) 
-        throws Exception { 
+        throws Exception {
+        Transaction txn = null;
 	    try {
             String [] accessKey = request.getParameterValues( "AWSAccessKeyId" );
 		    if ( null == accessKey || 0 == accessKey.length ) { 
@@ -483,10 +498,16 @@ public class EC2RestServlet extends HttpServlet {
 	             certStore.store( fsOut, keystorePassword.toCharArray());
 	             
 	     	     // -> dis-associate the cert's uniqueId with the Cloud API keys
-	     	     UserCredentialsDao credentialDao = new UserCredentialsDao();
-	     	     credentialDao.setCertificateId( accessKey[0], null ); 
+/*	     	     UserCredentialsDao credentialDao = new UserCredentialsDao();
+	     	     credentialDao.setCertificateId( accessKey[0], null );
+	     	     
+*/	     	     txn = Transaction.open(Transaction.AWSAPI_DB);
+	             UserCredentialsVO user = ucDao.getByAccessKey(accessKey[0]);
+	     	     user.setCertUniqueId(null);
+	     	     ucDao.update(user.getId(), user);
 		         response.setStatus(200);
-		           endResponse(response, "User certificate deleted successfully");
+		         endResponse(response, "User certificate deleted successfully");
+		         txn.commit();
 	        }
 	        else response.setStatus(404);
 	        
@@ -497,6 +518,8 @@ public class EC2RestServlet extends HttpServlet {
         } catch( Exception e ) {
 		    logger.error("DeleteCertificate exception " + e.getMessage(), e);
 		    response.sendError(500, "DeleteCertificate exception " + e.getMessage());
+        } finally {
+            txn.close();
         }
     }
    
@@ -547,7 +570,7 @@ public class EC2RestServlet extends HttpServlet {
     	}
 
         try {
-    	    OfferingDao ofDao = new OfferingDao();
+    	    
     	    ofDao.setOfferMapping( amazonOffer, cloudOffer ); 
     	    
         } catch( Exception e ) {
@@ -596,9 +619,7 @@ public class EC2RestServlet extends HttpServlet {
         }
 
         try {
-    	    OfferingDao ofDao = new OfferingDao();
     	    ofDao.deleteOfferMapping( amazonOffer ); 
-    	    
         } catch( Exception e ) {
    		    logger.error("DeleteOfferMapping " + e.getMessage(), e);
     		response.setStatus(401);
@@ -1695,8 +1716,8 @@ public class EC2RestServlet extends HttpServlet {
 		} 
 		
 		// [B] Use the cloudAccessKey to get the users secret key in the db
-	    UserCredentialsDao credentialDao = new UserCredentialsDao();
-	    UserCredentials cloudKeys = credentialDao.getByAccessKey( cloudAccessKey ); 
+	    UserCredentialsVO cloudKeys = ucDao.getByAccessKey( cloudAccessKey );
+
 	    if ( null == cloudKeys ) 
 	    {
 	    	 logger.debug( cloudAccessKey + " is not defined in the EC2 service - call SetUserKeys" );

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/39aa7d86/awsapi/src/com/cloud/bridge/service/S3RestServlet.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/service/S3RestServlet.java b/awsapi/src/com/cloud/bridge/service/S3RestServlet.java
index 282385b..c1458a7 100644
--- a/awsapi/src/com/cloud/bridge/service/S3RestServlet.java
+++ b/awsapi/src/com/cloud/bridge/service/S3RestServlet.java
@@ -43,9 +43,12 @@ import org.w3c.dom.NodeList;
 
 import com.cloud.bridge.io.MultiPartDimeInputStream;
 import com.cloud.bridge.model.SAcl;
-import com.cloud.bridge.persist.PersistContext;
+import com.cloud.bridge.model.UserCredentialsVO;
 import com.cloud.bridge.persist.dao.CloudStackConfigurationDao;
+import com.cloud.bridge.persist.dao.CloudStackConfigurationDaoImpl;
 import com.cloud.bridge.persist.dao.UserCredentialsDao;
+
+import com.cloud.bridge.persist.dao.UserCredentialsDaoImpl;
 import com.cloud.bridge.service.controller.s3.S3BucketAction;
 import com.cloud.bridge.service.controller.s3.S3ObjectAction;
 import com.cloud.bridge.service.controller.s3.ServiceProvider;
@@ -57,26 +60,29 @@ import com.cloud.bridge.service.core.s3.S3Grant;
 import com.cloud.bridge.service.core.s3.S3MetaDataEntry;
 import com.cloud.bridge.service.core.s3.S3PutObjectRequest;
 import com.cloud.bridge.service.core.s3.S3PutObjectResponse;
-import com.cloud.bridge.service.exception.InternalErrorException;
 import com.cloud.bridge.service.exception.InvalidBucketName;
-import com.cloud.bridge.service.exception.NoSuchObjectException;
 import com.cloud.bridge.service.exception.PermissionDeniedException;
-import com.cloud.bridge.util.AuthenticationUtils;
 import com.cloud.bridge.util.ConfigurationHelper;
 import com.cloud.bridge.util.HeaderParam;
 import com.cloud.bridge.util.RestAuth;
 import com.cloud.bridge.util.S3SoapAuth;
+import com.cloud.utils.component.ComponentLocator;
+import com.cloud.utils.db.DB;
+import com.cloud.utils.db.Transaction;
 
+import net.sf.ehcache.Cache;
 public class S3RestServlet extends HttpServlet {
 	private static final long serialVersionUID = -6168996266762804877L;
 	public static final String ENABLE_S3_API="enable.s3.api";
 	private static boolean isS3APIEnabled = false;
 
 	public static final Logger logger = Logger.getLogger(S3RestServlet.class);
+	protected final CloudStackConfigurationDao csDao = ComponentLocator.inject(CloudStackConfigurationDaoImpl.class);
+	protected final UserCredentialsDao ucDao = ComponentLocator.inject(UserCredentialsDaoImpl.class);
 	
 	protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
 	    processRequest( req, resp, "GET" );
-    }
+	}
 	
     protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
     {
@@ -106,15 +112,13 @@ public class S3RestServlet extends HttpServlet {
     public void init( ServletConfig config ) throws ServletException {
 		try{
     	    ConfigurationHelper.preConfigureConfigPathFromServletContext(config.getServletContext());
-    		UserCredentialsDao.preCheckTableExistence();
     		// check if API is enabled
-    		CloudStackConfigurationDao csDao = new CloudStackConfigurationDao();
     		String value = csDao.getConfigValue(ENABLE_S3_API);
     		if(value != null) {
     		    isS3APIEnabled = Boolean.valueOf(value);
     		}
-    		PersistContext.commitTransaction(true);
-            PersistContext.closeSession(true);
+    		logger.info("S3Engine :: Configuration value is : " + value);
+    		
 		}catch(Exception e){
 		    throw new ServletException("Error initializing awsapi: " + e.getMessage());
         }
@@ -130,6 +134,7 @@ public class S3RestServlet extends HttpServlet {
 	 */
     private void processRequest( HttpServletRequest request, HttpServletResponse response, String method ) 
     {
+        Transaction txn = Transaction.open("cloudbridge", Transaction.AWSAPI_DB, true);
         try {
         	logRequest(request);
         	
@@ -164,12 +169,13 @@ public class S3RestServlet extends HttpServlet {
     	    }
 
             
+            txn.start();
     	    // -> authenticated calls
         	if ( !((method.equalsIgnoreCase( "POST" ) && !(request.getQueryString().equalsIgnoreCase("delete"))) ) ){
         	    S3AuthParams params = extractRequestHeaders( request );
         		authenticateRequest( request, params );
         	}
-        	
+
         	ServletAction action = routeRequest(request);
         	if ( action != null ) {
         		 action.execute(request, response);
@@ -178,35 +184,30 @@ public class S3RestServlet extends HttpServlet {
         		 response.setStatus(404);
             	 endResponse(response, "File not found");
         	}
-        	
-			PersistContext.commitTransaction();
-			
+        	txn.close();
         } 
         catch( InvalidBucketName e) {
-            PersistContext.rollbackTransaction();
     		logger.error("Unexpected exception " + e.getMessage(), e);
     		response.setStatus(400);
         	endResponse(response, "Invalid Bucket Name - " + e.toString());    	
         } 
         catch(PermissionDeniedException e) {
-            PersistContext.rollbackTransaction();
     		logger.error("Unexpected exception " + e.getMessage(), e);
     		response.setStatus(403);
         	endResponse(response, "Access denied - " + e.toString());
         } 
         catch(Throwable e) {
-            PersistContext.rollbackTransaction();
     		logger.error("Unexpected exception " + e.getMessage(), e);
     		response.setStatus(404);
         	endResponse(response, "Bad request");
         	
         } finally {
+            
         	try {
 				response.flushBuffer();
 			} catch (IOException e) {
 	    		logger.error("Unexpected exception " + e.getMessage(), e);
 			}
-			PersistContext.closeSession();
         }
     }
  
@@ -239,6 +240,7 @@ public class S3RestServlet extends HttpServlet {
      * 
      * As with all REST calls HTTPS should be used to ensure their security.
      */
+    @DB
     private void setUserKeys( HttpServletRequest request, HttpServletResponse response ) {
     	String[] accessKey = null;
     	String[] secretKey = null;
@@ -266,8 +268,14 @@ public class S3RestServlet extends HttpServlet {
         try {
             // -> use the keys to see if the account actually exists
     	    //ServiceProvider.getInstance().getEC2Engine().validateAccount( accessKey[0], secretKey[0] );
-    	    UserCredentialsDao credentialDao = new UserCredentialsDao();
-    	    credentialDao.setUserKeys( accessKey[0], secretKey[0] ); 
+    	    //UserCredentialsDaoImpl credentialDao = new UserCredentialsDao();
+            Transaction txn = Transaction.open(Transaction.AWSAPI_DB);
+            txn.start();
+    	    UserCredentialsVO user = new UserCredentialsVO(accessKey[0], secretKey[0]);
+    	    user = ucDao.persist(user);
+    	    txn.commit();
+    	    txn.close();
+    	    //credentialDao.setUserKeys( accessKey[0], secretKey[0] ); 
     	    
         } catch( Exception e ) {
    		    logger.error("SetUserKeys " + e.getMessage(), e);
@@ -586,7 +594,6 @@ private S3ObjectAction routePlainPostRequest (HttpServletRequest request)
                 xml.append( "</soap:Body></soap:Envelope>" );
       		
           	    endResponse(response, xml.toString());
-  			    PersistContext.commitTransaction();
   			    return;
     		}
     		   		
@@ -605,7 +612,6 @@ private S3ObjectAction routePlainPostRequest (HttpServletRequest request)
             xml.append( "</soap:Body></soap:Envelope>" );
             		
         	endResponse(response, xml.toString());
-			PersistContext.commitTransaction();
         } 
         catch(PermissionDeniedException e) {
 		    logger.error("Unexpected exception " + e.getMessage(), e);
@@ -618,7 +624,6 @@ private S3ObjectAction routePlainPostRequest (HttpServletRequest request)
         } 
         finally 
         {
-			PersistContext.closeSession();
         }
     }
 

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/39aa7d86/awsapi/src/com/cloud/bridge/service/controller/s3/S3BucketAction.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/service/controller/s3/S3BucketAction.java b/awsapi/src/com/cloud/bridge/service/controller/s3/S3BucketAction.java
index 0ea862d..8f77916 100644
--- a/awsapi/src/com/cloud/bridge/service/controller/s3/S3BucketAction.java
+++ b/awsapi/src/com/cloud/bridge/service/controller/s3/S3BucketAction.java
@@ -49,14 +49,18 @@ import com.amazon.s3.GetBucketAccessControlPolicyResponse;
 import com.amazon.s3.ListAllMyBucketsResponse;
 import com.amazon.s3.ListBucketResponse;
 import com.cloud.bridge.io.MTOMAwareResultStreamWriter;
+import com.cloud.bridge.model.BucketPolicyVO;
 import com.cloud.bridge.model.SAcl;
+import com.cloud.bridge.model.SAclVO;
 import com.cloud.bridge.model.SBucket;
+import com.cloud.bridge.model.SBucketVO;
 import com.cloud.bridge.model.SHost;
-import com.cloud.bridge.persist.PersistContext;
 import com.cloud.bridge.persist.dao.BucketPolicyDao;
+import com.cloud.bridge.persist.dao.BucketPolicyDaoImpl;
 import com.cloud.bridge.persist.dao.MultipartLoadDao;
-import com.cloud.bridge.persist.dao.SAclDao;
+import com.cloud.bridge.persist.dao.SAclDaoImpl;
 import com.cloud.bridge.persist.dao.SBucketDao;
+import com.cloud.bridge.persist.dao.SBucketDaoImpl;
 import com.cloud.bridge.service.S3Constants;
 import com.cloud.bridge.service.S3RestServlet;
 import com.cloud.bridge.service.controller.s3.ServiceProvider;
@@ -81,16 +85,13 @@ import com.cloud.bridge.service.core.s3.S3ListAllMyBucketsResponse;
 import com.cloud.bridge.service.core.s3.S3ListBucketObjectEntry;
 import com.cloud.bridge.service.core.s3.S3ListBucketRequest;
 import com.cloud.bridge.service.core.s3.S3ListBucketResponse;
-import com.cloud.bridge.service.core.s3.S3MetaDataEntry;
 import com.cloud.bridge.service.core.s3.S3MultipartUpload;
 import com.cloud.bridge.service.core.s3.S3PolicyContext;
-import com.cloud.bridge.service.core.s3.S3PutObjectRequest;
 import com.cloud.bridge.service.core.s3.S3Response;
 import com.cloud.bridge.service.core.s3.S3SetBucketAccessControlPolicyRequest;
 import com.cloud.bridge.service.core.s3.S3BucketPolicy.PolicyAccess;
 import com.cloud.bridge.service.core.s3.S3PolicyAction.PolicyActions;
 import com.cloud.bridge.service.core.s3.S3PolicyCondition.ConditionKeys;
-import com.cloud.bridge.service.exception.InternalErrorException;
 import com.cloud.bridge.service.exception.InvalidBucketName;
 import com.cloud.bridge.service.exception.InvalidRequestContentException;
 import com.cloud.bridge.service.exception.NetworkIOException;
@@ -108,10 +109,14 @@ import com.cloud.bridge.util.Triple;
 import com.cloud.bridge.util.XSerializer;
 import com.cloud.bridge.util.XSerializerXmlAdapter;
 import com.cloud.bridge.util.XmlHelper;
+import com.cloud.utils.component.ComponentLocator;
+import com.cloud.utils.db.Transaction;
 
 
 public class S3BucketAction implements ServletAction {
     protected final static Logger logger = Logger.getLogger(S3BucketAction.class);
+    protected final BucketPolicyDao bPolicyDao = ComponentLocator.inject(BucketPolicyDaoImpl.class);
+    protected final SBucketDao bucketDao = ComponentLocator.inject(SBucketDaoImpl.class);
     
     private DocumentBuilderFactory dbf = null;
 	public S3BucketAction() {
@@ -347,18 +352,16 @@ private void executeMultiObjectDelete(HttpServletRequest request, HttpServletRes
 		String policy = streamToString( request.getInputStream());
 		        
 		// [A] Is there an owner of an existing policy or bucket?
-        BucketPolicyDao policyDao = new BucketPolicyDao();
-		SBucketDao bucketDao = new SBucketDao();
-		SBucket bucket = bucketDao.getByName( bucketName );
+        SBucketVO bucket = bucketDao.getByName( bucketName );
         String owner = null;
         
         if ( null != bucket ) 
         {
-        	 owner = bucket.getOwnerCanonicalId();
+            owner = bucket.getOwnerCanonicalId();
         }
         else 
         {    try {
-        	     owner = policyDao.getPolicyOwner( bucketName );
+        	     owner = bPolicyDao.getByName(bucketName).getOwnerCanonicalID();
              }
              catch( Exception e ) {}
         }
@@ -366,36 +369,42 @@ private void executeMultiObjectDelete(HttpServletRequest request, HttpServletRes
         
 		// [B] "The bucket owner by default has permissions to attach bucket policies to their buckets using PUT Bucket policy." 
 		//  -> the bucket owner may want to restrict the IP address from where this can be executed
-	    String client = UserContext.current().getCanonicalUserId();
-		S3PolicyContext context = new S3PolicyContext( PolicyActions.PutBucketPolicy, bucketName );
-	    switch( S3Engine.verifyPolicy( context )) {
-	    case ALLOW:
-             break;
-             
-		case DEFAULT_DENY:
-		     if (null != owner && !client.equals( owner )) {
-		    	 response.setStatus(405);
-		    	 return;
-		     }
-		     break;
-		    	 
-		case DENY:
-             response.setStatus(403);
-             return;
-		}
-			
-	    
+	String client = UserContext.current().getCanonicalUserId();
+	S3PolicyContext context = new S3PolicyContext(
+		PolicyActions.PutBucketPolicy, bucketName);
+	
+	switch (S3Engine.verifyPolicy(context)) {
+	case ALLOW:
+	    break;
+
+	case DEFAULT_DENY:
+	    if (null != owner && !client.equals(owner)) {
+		response.setStatus(405);
+		return;
+	    }
+	    break;
+	case DENY:
+	    response.setStatus(403);
+	    return;
+	}			
+	    Transaction txn = Transaction.open(Transaction.AWSAPI_DB);
 	    // [B] Place the policy into the database over writting an existing policy
     	try {
     		// -> first make sure that the policy is valid by parsing it
        		PolicyParser parser = new PolicyParser();
     		S3BucketPolicy sbp = parser.parse( policy, bucketName );
-
-	        policyDao.deletePolicy( bucketName );
-	        if (null != policy && !policy.isEmpty()) policyDao.addPolicy( bucketName, client, policy );
+    		bPolicyDao.deletePolicy(bucketName);
+    		
+	        if (null != policy && !policy.isEmpty()) {
+	            BucketPolicyVO bpolicy = new BucketPolicyVO(bucketName, client, policy);
+	            bpolicy = bPolicyDao.persist(bpolicy);
+	            //policyDao.addPolicy( bucketName, client, policy );
+	        }
 	                
     		if (null != sbp) ServiceProvider.getInstance().setBucketPolicy( bucketName, sbp );
-    		response.setStatus(200);  		
+    		response.setStatus(200);
+    		txn.commit();
+    		txn.close();
     	}
     	catch( PermissionDeniedException e ) {
 			logger.error("Put Bucket Policy failed due to " + e.getMessage(), e);	
@@ -416,185 +425,193 @@ private void executeMultiObjectDelete(HttpServletRequest request, HttpServletRes
 		String bucketName = (String)request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
 
 		// [A] Is there an owner of an existing policy or bucket?
-        BucketPolicyDao policyDao = new BucketPolicyDao();
-		SBucketDao bucketDao = new SBucketDao();
-		SBucket bucket = bucketDao.getByName( bucketName );
-        String owner = null;
-        
-        if ( null != bucket ) 
-        {
-        	 owner = bucket.getOwnerCanonicalId();
-        }
-        else 
-        {    try {
-        	     owner = policyDao.getPolicyOwner( bucketName );
-             }
-             catch( Exception e ) {}
-        }
+	SBucketVO bucket = bucketDao.getByName(bucketName);
+	String owner = null;
 
-        
-		// [B] "The bucket owner by default has permissions to retrieve bucket policies using GET Bucket policy."
-		//  -> the bucket owner may want to restrict the IP address from where this can be executed
-		String client = UserContext.current().getCanonicalUserId();
-		S3PolicyContext context = new S3PolicyContext( PolicyActions.GetBucketPolicy, bucketName );
-		switch( S3Engine.verifyPolicy( context )) {
-		case ALLOW:
-             break;
-             
-		case DEFAULT_DENY:
-		  	 if (null != owner && !client.equals( owner )) {
-		   		 response.setStatus(405);
-		   		 return;
-		   	 }
-		   	 break;
-		    	 
-		case DENY:
-             response.setStatus(403);
-             return;
-		}
+	if (null != bucket) {
+	    owner = bucket.getOwnerCanonicalId();
+	} else {
+	    try {
+		owner = bPolicyDao.getByName(bucketName).getOwnerCanonicalID();
+	    } catch (Exception e) {
+	    }
+	}
 
-	    
-	    // [B] Pull the policy from the database if one exists
-    	try {
-	        String policy = policyDao.getPolicy( bucketName );
-	        if ( null == policy ) {
-	    		 response.setStatus(404);
-	        }
-	        else {
-    		     response.setStatus(200);
-    			 response.setContentType("application/json");
-    			 S3RestServlet.endResponse(response, policy);
-	        }
-    	}
-		catch( Exception e ) {
-			logger.error("Get Bucket Policy failed due to " + e.getMessage(), e);	
-			response.setStatus(500);
-		}
+	// [B]
+	// "The bucket owner by default has permissions to retrieve bucket policies using GET Bucket policy."
+	// -> the bucket owner may want to restrict the IP address from where
+	// this can be executed
+	String client = UserContext.current().getCanonicalUserId();
+	S3PolicyContext context = new S3PolicyContext(
+		PolicyActions.GetBucketPolicy, bucketName);
+	switch (S3Engine.verifyPolicy(context)) {
+	case ALLOW:
+	    break;
+
+	case DEFAULT_DENY:
+	    if (null != owner && !client.equals(owner)) {
+		response.setStatus(405);
+		return;
+	    }
+	    break;
+
+	case DENY:
+	    response.setStatus(403);
+	    return;
 	}
 
-	private void executeDeleteBucketPolicy(HttpServletRequest request, HttpServletResponse response) 
-	{
-		String bucketName = (String)request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
-		
-		SBucketDao bucketDao = new SBucketDao();
-		SBucket bucket = bucketDao.getByName( bucketName );
-		if (bucket != null) 
-		{
-		    String client = UserContext.current().getCanonicalUserId();
-		    if (!client.equals( bucket.getOwnerCanonicalId())) {
-		        response.setStatus(405);
-		        return;
-		    }
-		}
+	// [B] Pull the policy from the database if one exists
+	try {
+	    String policy = bPolicyDao.getByName(bucketName).getPolicy();
+	    if (null == policy) {
+		response.setStatus(404);
+	    } else {
+		response.setStatus(200);
+		response.setContentType("application/json");
+		S3RestServlet.endResponse(response, policy);
+	    }
+	} catch (Exception e) {
+	    logger.error("Get Bucket Policy failed due to " + e.getMessage(), e);
+	    response.setStatus(500);
+	}
+    }
 
-    	try {
-	        BucketPolicyDao policyDao = new BucketPolicyDao();
-	        String policy = policyDao.getPolicy( bucketName );
-	        if ( null == policy ) {
-	    		 response.setStatus(204);
-	        }
-	        else {
-	   	         ServiceProvider.getInstance().deleteBucketPolicy( bucketName );
-    	         policyDao.deletePolicy( bucketName );
-    		     response.setStatus(200);
-	        }
-    	}
-		catch( Exception e ) {
-			logger.error("Delete Bucket Policy failed due to " + e.getMessage(), e);	
-			response.setStatus(500);
-		}
+    private void executeDeleteBucketPolicy(HttpServletRequest request,
+	    HttpServletResponse response) {
+	String bucketName = (String) request
+		.getAttribute(S3Constants.BUCKET_ATTR_KEY);
+
+	SBucketVO bucket = bucketDao.getByName(bucketName);
+	if (bucket != null) {
+	    String client = UserContext.current().getCanonicalUserId();
+	    if (!client.equals(bucket.getOwnerCanonicalId())) {
+		response.setStatus(405);
+		return;
+	    }
 	}
 
-	public void executeGetAllBuckets(HttpServletRequest request, HttpServletResponse response) 
-	    throws IOException, XMLStreamException 
-	{
-		Calendar cal = Calendar.getInstance();
-		cal.set( 1970, 1, 1 );    
-		S3ListAllMyBucketsRequest engineRequest = new S3ListAllMyBucketsRequest();
-		engineRequest.setAccessKey(UserContext.current().getAccessKey());
-		engineRequest.setRequestTimestamp( cal );
-		engineRequest.setSignature( "" );
-		
-		
+	try {
 
+	    String policy = bPolicyDao.getByName(bucketName).getPolicy();
+	    if (null == policy) {
+		response.setStatus(204);
+	    } else {
+		ServiceProvider.getInstance().deleteBucketPolicy(bucketName);
+		bPolicyDao.deletePolicy(bucketName);
+		response.setStatus(200);
+	    }
+	} catch (Exception e) {
+	    logger.error(
+		    "Delete Bucket Policy failed due to " + e.getMessage(), e);
+	    response.setStatus(500);
+	}
+    }
 
-		S3ListAllMyBucketsResponse engineResponse = ServiceProvider.getInstance().getS3Engine().handleRequest(engineRequest);
-		
-		// To allow the all buckets list to be serialized via Axiom classes
-		ListAllMyBucketsResponse allBuckets = S3SerializableServiceImplementation.toListAllMyBucketsResponse( engineResponse );
-		
-		OutputStream outputStream = response.getOutputStream();
-		response.setStatus(200);	
-	    response.setContentType("application/xml");   
-	         // The content-type literally should be "application/xml; charset=UTF-8" 
-	         // but any compliant JVM supplies utf-8 by default
-		
-//		MTOMAwareResultStreamWriter resultWriter = new MTOMAwareResultStreamWriter ("ListAllMyBucketsResult", outputStream );
-//		resultWriter.startWrite();
-//		resultWriter.writeout(allBuckets);
-//		resultWriter.stopWrite();
-	    StringBuffer xml = new StringBuffer();
-        xml.append( "<?xml version=\"1.0\" encoding=\"utf-8\"?>" );
-        xml.append("<ListAllMyBucketsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">");
-        xml.append("<Owner><ID>");
-        xml.append(engineResponse.getOwner().getID()).append("</ID>");
-        xml.append("<DisplayName>").append(engineResponse.getOwner().getDisplayName()).append("</DisplayName>");
-        xml.append("</Owner>").append("<Buckets>");
-        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
-        for (S3ListAllMyBucketsEntry entry :engineResponse.getBuckets()) {
-            xml.append("<Bucket>").append("<Name>").append(entry.getName()).append("</Name>");
-            xml.append("<CreationDate>").append(sdf.format(entry.getCreationDate().getTime())).append("</CreationDate>");
-            xml.append("</Bucket>");
-        }
-        xml.append("</Buckets>").append("</ListAllMyBucketsResult>");
-        response.setStatus(200);
-        response.setContentType("text/xml; charset=UTF-8");
-        S3RestServlet.endResponse(response, xml.toString());
+    public void executeGetAllBuckets(HttpServletRequest request,
+	    HttpServletResponse response) throws IOException,
+	    XMLStreamException {
+	Calendar cal = Calendar.getInstance();
+	cal.set(1970, 1, 1);
+	S3ListAllMyBucketsRequest engineRequest = new S3ListAllMyBucketsRequest();
+	engineRequest.setAccessKey(UserContext.current().getAccessKey());
+	engineRequest.setRequestTimestamp(cal);
+	engineRequest.setSignature("");
+
+	S3ListAllMyBucketsResponse engineResponse = ServiceProvider
+		.getInstance().getS3Engine().handleRequest(engineRequest);
+
+	// To allow the all buckets list to be serialized via Axiom classes
+	ListAllMyBucketsResponse allBuckets = S3SerializableServiceImplementation
+		.toListAllMyBucketsResponse(engineResponse);
+
+	OutputStream outputStream = response.getOutputStream();
+	response.setStatus(200);
+	response.setContentType("application/xml");
+	// The content-type literally should be "application/xml; charset=UTF-8"
+	// but any compliant JVM supplies utf-8 by default
+
+	// MTOMAwareResultStreamWriter resultWriter = new
+	// MTOMAwareResultStreamWriter ("ListAllMyBucketsResult", outputStream
+	// );
+	// resultWriter.startWrite();
+	// resultWriter.writeout(allBuckets);
+	// resultWriter.stopWrite();
+	StringBuffer xml = new StringBuffer();
+	xml.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
+	xml.append("<ListAllMyBucketsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">");
+	xml.append("<Owner><ID>");
+	xml.append(engineResponse.getOwner().getID()).append("</ID>");
+	xml.append("<DisplayName>")
+		.append(engineResponse.getOwner().getDisplayName())
+		.append("</DisplayName>");
+	xml.append("</Owner>").append("<Buckets>");
+	SimpleDateFormat sdf = new SimpleDateFormat(
+		"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
+	for (S3ListAllMyBucketsEntry entry : engineResponse.getBuckets()) {
+	    xml.append("<Bucket>").append("<Name>").append(entry.getName())
+		    .append("</Name>");
+	    xml.append("<CreationDate>")
+		    .append(sdf.format(entry.getCreationDate().getTime()))
+		    .append("</CreationDate>");
+	    xml.append("</Bucket>");
+	}
+	xml.append("</Buckets>").append("</ListAllMyBucketsResult>");
+	response.setStatus(200);
+	response.setContentType("text/xml; charset=UTF-8");
+	S3RestServlet.endResponse(response, xml.toString());
 		
 	}
 
 	public void executeGetBucket(HttpServletRequest request, HttpServletResponse response) 
 	    throws IOException, XMLStreamException 
 	{
-		S3ListBucketRequest engineRequest = new S3ListBucketRequest();
-		engineRequest.setBucketName((String)request.getAttribute(S3Constants.BUCKET_ATTR_KEY));
-		engineRequest.setDelimiter(request.getParameter("delimiter"));
-		engineRequest.setMarker(request.getParameter("marker"));
-		engineRequest.setPrefix(request.getParameter("prefix"));
-		
-		int maxKeys = Converter.toInt(request.getParameter("max-keys"), 1000);
-		engineRequest.setMaxKeys(maxKeys);
-		try {
-		S3ListBucketResponse engineResponse = ServiceProvider.getInstance().getS3Engine().listBucketContents( engineRequest, false );
-		
-		// To allow the all list buckets result to be serialized via Axiom classes
-		ListBucketResponse oneBucket = S3SerializableServiceImplementation.toListBucketResponse( engineResponse );
-	
-		OutputStream outputStream = response.getOutputStream();
-		response.setStatus(200);	
-	    response.setContentType("application/xml");   
-	         // The content-type literally should be "application/xml; charset=UTF-8" 
-	         // but any compliant JVM supplies utf-8 by default;
-	    
-		MTOMAwareResultStreamWriter resultWriter = new MTOMAwareResultStreamWriter ("ListBucketResult", outputStream );
-		resultWriter.startWrite();
-		resultWriter.writeout(oneBucket);
-		resultWriter.stopWrite();
-		} catch (NoSuchObjectException nsoe) {
-		    response.setStatus(404);
-		    response.setContentType("application/xml");   
+	S3ListBucketRequest engineRequest = new S3ListBucketRequest();
+	engineRequest.setBucketName((String) request
+		.getAttribute(S3Constants.BUCKET_ATTR_KEY));
+	engineRequest.setDelimiter(request.getParameter("delimiter"));
+	engineRequest.setMarker(request.getParameter("marker"));
+	engineRequest.setPrefix(request.getParameter("prefix"));
 
-		    StringBuffer xmlError = new StringBuffer();
-		    xmlError.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
+	int maxKeys = Converter.toInt(request.getParameter("max-keys"), 1000);
+	engineRequest.setMaxKeys(maxKeys);
+	try {
+	    S3ListBucketResponse engineResponse = ServiceProvider.getInstance()
+		    .getS3Engine().listBucketContents(engineRequest, false);
+
+	    // To allow the all list buckets result to be serialized via Axiom
+	    // classes
+	    ListBucketResponse oneBucket = S3SerializableServiceImplementation
+		    .toListBucketResponse(engineResponse);
+
+	    OutputStream outputStream = response.getOutputStream();
+	    response.setStatus(200);
+	    response.setContentType("application/xml");
+	    // The content-type literally should be
+	    // "application/xml; charset=UTF-8"
+	    // but any compliant JVM supplies utf-8 by default;
+
+	    MTOMAwareResultStreamWriter resultWriter = new MTOMAwareResultStreamWriter(
+		    "ListBucketResult", outputStream);
+	    resultWriter.startWrite();
+	    resultWriter.writeout(oneBucket);
+	    resultWriter.stopWrite();
+	} catch (NoSuchObjectException nsoe) {
+	    response.setStatus(404);
+	    response.setContentType("application/xml");
+
+	    StringBuffer xmlError = new StringBuffer();
+	    xmlError.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
 		    .append("<Error><Code>NoSuchBucket</Code><Message>The specified bucket does not exist</Message>")
-		    .append("<BucketName>").append((String)request.getAttribute(S3Constants.BUCKET_ATTR_KEY))
+		    .append("<BucketName>")
+		    .append((String) request
+			    .getAttribute(S3Constants.BUCKET_ATTR_KEY))
 		    .append("</BucketName>")
-		    .append("<RequestId>1DEADBEEF9</RequestId>") //TODO
-		    .append("<HostId>abCdeFgHiJ1k2LmN3op4q56r7st89</HostId>") //TODO
+		    .append("<RequestId>1DEADBEEF9</RequestId>") // TODO
+		    .append("<HostId>abCdeFgHiJ1k2LmN3op4q56r7st89</HostId>") // TODO
 		    .append("</Error>");
-	        S3RestServlet.endResponse(response, xmlError.toString());
+	    S3RestServlet.endResponse(response, xmlError.toString());
 
-		}
+	}
 
 	}
 	
@@ -640,8 +657,7 @@ private void executeMultiObjectDelete(HttpServletRequest request, HttpServletRes
 			return; 
 		}
 		
-		SBucketDao bucketDao = new SBucketDao();
-		SBucket sbucket = bucketDao.getByName( bucketName );
+		SBucketVO sbucket = bucketDao.getByName( bucketName );
 		if (sbucket == null) {
 			response.setStatus( 404 );
 			return;
@@ -834,111 +850,124 @@ private void executeMultiObjectDelete(HttpServletRequest request, HttpServletRes
 	public void executePutBucketAcl(HttpServletRequest request, HttpServletResponse response) throws IOException 
 	{ 
 		// [A] Determine that there is an applicable bucket which might have an ACL set
-		
-		String bucketName = (String)request.getAttribute(S3Constants.BUCKET_ATTR_KEY);	
-		SBucketDao bucketDao = new SBucketDao();
-		SBucket bucket = bucketDao.getByName( bucketName );
-		String owner = null;        
-        if ( null != bucket ) 
-        	 owner = bucket.getOwnerCanonicalId();
-        if (null == owner)
-                {
-            	   logger.error( "ACL update failed since " + bucketName + " does not exist" );
-                   throw new IOException("ACL update failed");
-                 }
-        
-        // [B] Obtain the grant request which applies to the acl request string.  This latter is supplied as the value of the x-amz-acl header.
-        
-		S3SetBucketAccessControlPolicyRequest engineRequest = new S3SetBucketAccessControlPolicyRequest();
-		S3Grant grantRequest = new S3Grant();
-		S3AccessControlList aclRequest = new S3AccessControlList();
-		
-		String aclRequestString = request.getHeader("x-amz-acl");
-		OrderedPair <Integer,Integer> accessControlsForBucketOwner = SAcl.getCannedAccessControls(aclRequestString,"SBucket");
-		grantRequest.setPermission(accessControlsForBucketOwner.getFirst());
-		grantRequest.setGrantee(accessControlsForBucketOwner.getSecond());
-		grantRequest.setCanonicalUserID(owner);
-		aclRequest.addGrant(grantRequest);
-		engineRequest.setAcl(aclRequest);
-		engineRequest.setBucketName(bucketName);
-		
-		
-		// [C] Allow an S3Engine to handle the S3SetBucketAccessControlPolicyRequest
-	    S3Response engineResponse = ServiceProvider.getInstance().getS3Engine().handleRequest(engineRequest);	
-	    response.setStatus( engineResponse.getResultCode());
+
+	String bucketName = (String) request
+		.getAttribute(S3Constants.BUCKET_ATTR_KEY);
+	SBucketVO bucket = bucketDao.getByName(bucketName);
+	String owner = null;
+	if (null != bucket)
+	    owner = bucket.getOwnerCanonicalId();
+	if (null == owner) {
+	    logger.error("ACL update failed since " + bucketName
+		    + " does not exist");
+	    throw new IOException("ACL update failed");
+	}
+
+	// [B] Obtain the grant request which applies to the acl request string.
+	// This latter is supplied as the value of the x-amz-acl header.
+
+	S3SetBucketAccessControlPolicyRequest engineRequest = new S3SetBucketAccessControlPolicyRequest();
+	S3Grant grantRequest = new S3Grant();
+	S3AccessControlList aclRequest = new S3AccessControlList();
+
+	String aclRequestString = request.getHeader("x-amz-acl");
+	OrderedPair<Integer, Integer> accessControlsForBucketOwner = SAclVO.getCannedAccessControls(aclRequestString, "SBucket");
+	grantRequest.setPermission(accessControlsForBucketOwner.getFirst());
+	grantRequest.setGrantee(accessControlsForBucketOwner.getSecond());
+	grantRequest.setCanonicalUserID(owner);
+	aclRequest.addGrant(grantRequest);
+	engineRequest.setAcl(aclRequest);
+	engineRequest.setBucketName(bucketName);
+
+	// [C] Allow an S3Engine to handle the
+	// S3SetBucketAccessControlPolicyRequest
+	S3Response engineResponse = ServiceProvider.getInstance().getS3Engine()
+		.handleRequest(engineRequest);
+	response.setStatus(engineResponse.getResultCode());
 
 	}
 	
 	public void executePutBucketVersioning(HttpServletRequest request, HttpServletResponse response) throws IOException 
 	{
-		String bucketName       = (String)request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
-		String versioningStatus = null;
-		Node   item             = null;
+	String bucketName = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
+	String versioningStatus = null;
+	Node item = null;
 
-		if (null == bucketName) {
-			logger.error( "executePutBucketVersioning - no bucket name given" );
-			response.setStatus( 400 ); 
-			return; 
-		}
-		
-		// -> is the XML as defined?
-		try {
-		    DocumentBuilder db = dbf.newDocumentBuilder();
-		    Document restXML = db.parse( request.getInputStream());
-		    NodeList match = S3RestServlet.getElement( restXML, "http://s3.amazonaws.com/doc/2006-03-01/", "Status" ); 
-	        if ( 0 < match.getLength()) 
-	        {
-	    	     item = match.item(0);
-	    	     versioningStatus = new String( item.getFirstChild().getNodeValue());
-	        }
-	        else
-	        {    logger.error( "executePutBucketVersioning - cannot find Status tag in XML body" );
-				 response.setStatus( 400 ); 
-				 return; 
-	        }
-		}
-		catch( Exception e ) {
-			logger.error( "executePutBucketVersioning - failed to parse XML due to " + e.getMessage(), e);
-			response.setStatus(400);
-			return;
-		}
-	     
-	    try {
-			// Irrespective of what the ACLs say only the owner can turn on versioning on a bucket.
-	        // The bucket owner may want to restrict the IP address from which this can occur.
-			SBucketDao bucketDao = new SBucketDao();
-			SBucket sbucket = bucketDao.getByName( bucketName );
-		
-			String client = UserContext.current().getCanonicalUserId();
-			if (!client.equals( sbucket.getOwnerCanonicalId()))
-			    throw new PermissionDeniedException( "Access Denied - only the owner can turn on versioing on a bucket" );
-		
-			S3PolicyContext context = new S3PolicyContext( PolicyActions.PutBucketVersioning, bucketName );
-		    if (PolicyAccess.DENY == S3Engine.verifyPolicy( context )) {
-	             response.setStatus(403);
-	             return;
-		    }
+	if (null == bucketName) {
+	    logger.error("executePutBucketVersioning - no bucket name given");
+	    response.setStatus(400);
+	    return;
+	}
 
-			
-			     if (versioningStatus.equalsIgnoreCase( "Enabled"  )) sbucket.setVersioningStatus( 1 );
-			else if (versioningStatus.equalsIgnoreCase( "Suspended")) sbucket.setVersioningStatus( 2 );
-			else { 
-				 logger.error( "executePutBucketVersioning - unknown state: [" + versioningStatus + "]" );
-				 response.setStatus( 400 ); 
-				 return; 
-		    }
-			bucketDao.update( sbucket );
-			
-		} catch( PermissionDeniedException e ) {
-			logger.error( "executePutBucketVersioning - failed due to " + e.getMessage(), e);
-			throw e;
-			
-		} catch( Exception e ) {
-			logger.error( "executePutBucketVersioning - failed due to " + e.getMessage(), e);
-			response.setStatus(500);
-			return;
-		}		
-		response.setStatus(200);
+	// -> is the XML as defined?
+	try {
+	    DocumentBuilder db = dbf.newDocumentBuilder();
+	    Document restXML = db.parse(request.getInputStream());
+	    NodeList match = S3RestServlet.getElement(restXML,
+		    "http://s3.amazonaws.com/doc/2006-03-01/", "Status");
+	    if (0 < match.getLength()) {
+		item = match.item(0);
+		versioningStatus = new String(item.getFirstChild()
+			.getNodeValue());
+	    } else {
+		logger.error("executePutBucketVersioning - cannot find Status tag in XML body");
+		response.setStatus(400);
+		return;
+	    }
+	} catch (Exception e) {
+	    logger.error(
+		    "executePutBucketVersioning - failed to parse XML due to "
+			    + e.getMessage(), e);
+	    response.setStatus(400);
+	    return;
+	}
+
+	try {
+	    // Irrespective of what the ACLs say only the owner can turn on
+	    // versioning on a bucket.
+	    // The bucket owner may want to restrict the IP address from which
+	    // this can occur.
+	    
+	    SBucketVO sbucket = bucketDao.getByName(bucketName);
+
+	    String client = UserContext.current().getCanonicalUserId();
+	    if (!client.equals(sbucket.getOwnerCanonicalId()))
+		throw new PermissionDeniedException(
+			"Access Denied - only the owner can turn on versioing on a bucket");
+
+	    S3PolicyContext context = new S3PolicyContext(
+		    PolicyActions.PutBucketVersioning, bucketName);
+	    if (PolicyAccess.DENY == S3Engine.verifyPolicy(context)) {
+		response.setStatus(403);
+		return;
+	    }
+
+	    if (versioningStatus.equalsIgnoreCase("Enabled"))
+		sbucket.setVersioningStatus(1);
+	    else if (versioningStatus.equalsIgnoreCase("Suspended"))
+		sbucket.setVersioningStatus(2);
+	    else {
+		logger.error("executePutBucketVersioning - unknown state: ["
+			+ versioningStatus + "]");
+		response.setStatus(400);
+		return;
+	    }
+	    bucketDao.update(sbucket.getId(), sbucket);
+
+	} catch (PermissionDeniedException e) {
+	    logger.error(
+		    "executePutBucketVersioning - failed due to "
+			    + e.getMessage(), e);
+	    throw e;
+
+	} catch (Exception e) {
+	    logger.error(
+		    "executePutBucketVersioning - failed due to "
+			    + e.getMessage(), e);
+	    response.setStatus(500);
+	    return;
+	}
+	response.setStatus(200);
 	}
 	
 	public void executePutBucketLogging(HttpServletRequest request, HttpServletResponse response) throws IOException {
@@ -949,7 +978,7 @@ private void executeMultiObjectDelete(HttpServletRequest request, HttpServletRes
 	public void executePutBucketWebsite(HttpServletRequest request, HttpServletResponse response) throws IOException {
 		// TODO -- LoPri - Undertake checks on Put Bucket Website
 		// Tested using configuration <Directory /Users/john1/S3-Mount>\nAllowOverride FileInfo AuthConfig Limit...</Directory> in httpd.conf
-        // Need some way of using  AllowOverride to allow use of .htaccess and then pushing .httaccess file to bucket subdirectory of mount point
+	    // 	Need some way of using  AllowOverride to allow use of .htaccess and then pushing .httaccess file to bucket subdirectory of mount point
 		// Currently has noop effect in the sense that a running apachectl process sees the directory contents without further action
 		response.setStatus(200);
 	}
@@ -976,128 +1005,145 @@ private void executeMultiObjectDelete(HttpServletRequest request, HttpServletRes
 	public void executeListMultipartUploads(HttpServletRequest request, HttpServletResponse response) throws IOException 
 	{
 		// [A] Obtain parameters and do basic bucket verification
-		String bucketName     = (String)request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
-		String delimiter      = request.getParameter("delimiter");
-		String keyMarker      = request.getParameter("key-marker");
-		String prefix         = request.getParameter("prefix");
-		int maxUploads        = 1000;
-		int nextUploadId      = 0;
-		String nextKey        = null;
-		boolean isTruncated   = false;
-		S3MultipartUpload[] uploads = null;
-		S3MultipartUpload onePart = null;
-		
-		String temp = request.getParameter("max-uploads");
-    	if (null != temp) {
-    		maxUploads = Integer.parseInt( temp );
-    		if (maxUploads > 1000 || maxUploads < 0) maxUploads = 1000;
-    	}
-    	
-    	// -> upload-id-marker is ignored unless key-marker is also specified
-		String uploadIdMarker = request.getParameter("upload-id-marker");
-        if (null == keyMarker) uploadIdMarker = null;
-    	
-		// -> does the bucket exist, we may need it to verify access permissions
-		SBucketDao bucketDao = new SBucketDao();
-		SBucket bucket = bucketDao.getByName(bucketName);
-		if (bucket == null) {
-			logger.error( "listMultipartUpload failed since " + bucketName + " does not exist" );
-	    	response.setStatus(404);
-	    	return;
-		}
-		
-		S3PolicyContext context = new S3PolicyContext( PolicyActions.ListBucketMultipartUploads, bucketName );
-		context.setEvalParam( ConditionKeys.Prefix, prefix );
-		context.setEvalParam( ConditionKeys.Delimiter, delimiter );
-		S3Engine.verifyAccess( context, "SBucket", bucket.getId(), SAcl.PERMISSION_READ );
+	String bucketName = (String) request
+		.getAttribute(S3Constants.BUCKET_ATTR_KEY);
+	String delimiter = request.getParameter("delimiter");
+	String keyMarker = request.getParameter("key-marker");
+	String prefix = request.getParameter("prefix");
+	int maxUploads = 1000;
+	int nextUploadId = 0;
+	String nextKey = null;
+	boolean isTruncated = false;
+	S3MultipartUpload[] uploads = null;
+	S3MultipartUpload onePart = null;
+	String temp = request.getParameter("max-uploads");
+	if (null != temp) {
+	    maxUploads = Integer.parseInt(temp);
+	    if (maxUploads > 1000 || maxUploads < 0)
+		maxUploads = 1000;
+	}
 
-  			
-		// [B] Query the multipart table to get the list of current uploads
-    	try {
-	        MultipartLoadDao uploadDao = new MultipartLoadDao();
-	        OrderedPair<S3MultipartUpload[],Boolean> result = uploadDao.getInitiatedUploads( bucketName, maxUploads, prefix, keyMarker, uploadIdMarker );
-    	    uploads = result.getFirst();
-    	    isTruncated = result.getSecond().booleanValue();
-    	}
-		catch( Exception e ) {
-			logger.error("List Multipart Uploads failed due to " + e.getMessage(), e);	
-			response.setStatus(500);
-		}
+	// -> upload-id-marker is ignored unless key-marker is also specified
+	String uploadIdMarker = request.getParameter("upload-id-marker");
+	if (null == keyMarker)
+	    uploadIdMarker = null;
 
-		StringBuffer xml = new StringBuffer();
-	    xml.append( "<?xml version=\"1.0\" encoding=\"utf-8\"?>" );
-	    xml.append( "<ListMultipartUploadsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">" );
-	    xml.append( "<Bucket>" ).append( bucketName ).append( "</Bucket>" );
-	    xml.append( "<KeyMarker>").append((null == keyMarker ? "" : keyMarker)).append( "</KeyMarker>" );
-	    xml.append( "<UploadIdMarker>").append((null == uploadIdMarker ? "" : uploadIdMarker)).append( "</UploadIdMarker>" );
-	    
-	    
-	    // [C] Construct the contents of the <Upload> element
-		StringBuffer partsList = new StringBuffer();
-	    for( int i=0; i < uploads.length; i++ ) 
-	    {
-	        onePart = uploads[i];
-	        if (null == onePart) break;
-	        
-			if (delimiter != null && !delimiter.isEmpty()) 
-			{
-				// -> is this available only in the CommonPrefixes element?
-				if (StringHelper.substringInBetween(onePart.getKey(), prefix, delimiter) != null)
-					continue;
-			}
-	        	
-	        nextKey      = onePart.getKey();
-	        nextUploadId = onePart.getId();
-	        partsList.append( "<Upload>" );
-	        partsList.append( "<Key>" ).append( nextKey ).append( "</Key>" );
-	        partsList.append( "<UploadId>" ).append( nextUploadId ).append( "</UploadId>" );
-	        partsList.append( "<Initiator>" );
-	        partsList.append( "<ID>" ).append( onePart.getAccessKey()).append( "</ID>" );
-	        partsList.append( "<DisplayName></DisplayName>" );
-	        partsList.append( "</Initiator>" );
-	        partsList.append( "<Owner>" );
-	        partsList.append( "<ID>" ).append( onePart.getAccessKey()).append( "</ID>" );
-	        partsList.append( "<DisplayName></DisplayName>" );
-	        partsList.append( "</Owner>" );       
-	        partsList.append( "<StorageClass>STANDARD</StorageClass>" );
-	        partsList.append( "<Initiated>" ).append( DatatypeConverter.printDateTime( onePart.getLastModified())).append( "</Initiated>" );
-	        partsList.append( "</Upload>" );        	
-	    }  
-	        
-	    // [D] Construct the contents of the <CommonPrefixes> elements (if any)
-	    for( int i=0; i < uploads.length; i++ ) 
-	    {
-	        onePart = uploads[i];
-	        if (null == onePart) break;
-
-			if (delimiter != null && !delimiter.isEmpty()) 
-			{
-				String subName = StringHelper.substringInBetween(onePart.getKey(), prefix, delimiter);
-				if (subName != null) 
-				{
-			        partsList.append( "<CommonPrefixes>" );
-			        partsList.append( "<Prefix>" );
-					if ( prefix != null && prefix.length() > 0 )
-						partsList.append( prefix + delimiter + subName );
-					else partsList.append( subName );
-			        partsList.append( "</Prefix>" );
-			        partsList.append( "</CommonPrefixes>" );
-				}
-			}		
+	// -> does the bucket exist, we may need it to verify access permissions
+	SBucketVO bucket = bucketDao.getByName(bucketName);
+	if (bucket == null) {
+	    logger.error("listMultipartUpload failed since " + bucketName
+		    + " does not exist");
+	    response.setStatus(404);
+	    return;
+	}
+
+	S3PolicyContext context = new S3PolicyContext(
+		PolicyActions.ListBucketMultipartUploads, bucketName);
+	context.setEvalParam(ConditionKeys.Prefix, prefix);
+	context.setEvalParam(ConditionKeys.Delimiter, delimiter);
+	S3Engine.verifyAccess(context, "SBucket", bucket.getId(),
+		SAcl.PERMISSION_READ);
+
+	// [B] Query the multipart table to get the list of current uploads
+	try {
+	    MultipartLoadDao uploadDao = new MultipartLoadDao();
+	    OrderedPair<S3MultipartUpload[], Boolean> result = uploadDao
+		    .getInitiatedUploads(bucketName, maxUploads, prefix,
+			    keyMarker, uploadIdMarker);
+	    uploads = result.getFirst();
+	    isTruncated = result.getSecond().booleanValue();
+	} catch (Exception e) {
+	    logger.error(
+		    "List Multipart Uploads failed due to " + e.getMessage(), e);
+	    response.setStatus(500);
+	}
+
+	StringBuffer xml = new StringBuffer();
+	xml.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
+	xml.append("<ListMultipartUploadsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">");
+	xml.append("<Bucket>").append(bucketName).append("</Bucket>");
+	xml.append("<KeyMarker>").append((null == keyMarker ? "" : keyMarker))
+		.append("</KeyMarker>");
+	xml.append("<UploadIdMarker>")
+		.append((null == uploadIdMarker ? "" : uploadIdMarker))
+		.append("</UploadIdMarker>");
+
+	// [C] Construct the contents of the <Upload> element
+	StringBuffer partsList = new StringBuffer();
+	for (int i = 0; i < uploads.length; i++) {
+	    onePart = uploads[i];
+	    if (null == onePart)
+		break;
+
+	    if (delimiter != null && !delimiter.isEmpty()) {
+		// -> is this available only in the CommonPrefixes element?
+		if (StringHelper.substringInBetween(onePart.getKey(), prefix,
+			delimiter) != null)
+		    continue;
+	    }
+
+	    nextKey = onePart.getKey();
+	    nextUploadId = onePart.getId();
+	    partsList.append("<Upload>");
+	    partsList.append("<Key>").append(nextKey).append("</Key>");
+	    partsList.append("<UploadId>").append(nextUploadId)
+		    .append("</UploadId>");
+	    partsList.append("<Initiator>");
+	    partsList.append("<ID>").append(onePart.getAccessKey())
+		    .append("</ID>");
+	    partsList.append("<DisplayName></DisplayName>");
+	    partsList.append("</Initiator>");
+	    partsList.append("<Owner>");
+	    partsList.append("<ID>").append(onePart.getAccessKey())
+		    .append("</ID>");
+	    partsList.append("<DisplayName></DisplayName>");
+	    partsList.append("</Owner>");
+	    partsList.append("<StorageClass>STANDARD</StorageClass>");
+	    partsList
+		    .append("<Initiated>")
+		    .append(DatatypeConverter.printDateTime(onePart
+			    .getLastModified())).append("</Initiated>");
+	    partsList.append("</Upload>");
+	}
+
+	// [D] Construct the contents of the <CommonPrefixes> elements (if any)
+	for (int i = 0; i < uploads.length; i++) {
+	    onePart = uploads[i];
+	    if (null == onePart)
+		break;
+
+	    if (delimiter != null && !delimiter.isEmpty()) {
+		String subName = StringHelper.substringInBetween(
+			onePart.getKey(), prefix, delimiter);
+		if (subName != null) {
+		    partsList.append("<CommonPrefixes>");
+		    partsList.append("<Prefix>");
+		    if (prefix != null && prefix.length() > 0)
+			partsList.append(prefix + delimiter + subName);
+		    else
+			partsList.append(subName);
+		    partsList.append("</Prefix>");
+		    partsList.append("</CommonPrefixes>");
 		}
-	    
-	    // [D] Finish off the response
-	    xml.append( "<NextKeyMarker>" ).append((null == nextKey ? "" : nextKey)).append( "</NextKeyMarker>" );
-	    xml.append( "<NextUploadIdMarker>" ).append((0 == nextUploadId ? "" : nextUploadId)).append( "</NextUploadIdMarker>" );
-	    xml.append( "<MaxUploads>" ).append( maxUploads ).append( "</MaxUploads>" );   
-	    xml.append( "<IsTruncated>" ).append( isTruncated ).append( "</IsTruncated>" );
-
-	    xml.append( partsList.toString());
-	    xml.append( "</ListMultipartUploadsResult>" );
-	      
-		response.setStatus(200);
-		response.setContentType("text/xml; charset=UTF-8");
-	    S3RestServlet.endResponse(response, xml.toString());
+	    }
+	}
+
+	// [D] Finish off the response
+	xml.append("<NextKeyMarker>").append((null == nextKey ? "" : nextKey))
+		.append("</NextKeyMarker>");
+	xml.append("<NextUploadIdMarker>")
+		.append((0 == nextUploadId ? "" : nextUploadId))
+		.append("</NextUploadIdMarker>");
+	xml.append("<MaxUploads>").append(maxUploads).append("</MaxUploads>");
+	xml.append("<IsTruncated>").append(isTruncated)
+		.append("</IsTruncated>");
+
+	xml.append(partsList.toString());
+	xml.append("</ListMultipartUploadsResult>");
+
+	response.setStatus(200);
+	response.setContentType("text/xml; charset=UTF-8");
+	S3RestServlet.endResponse(response, xml.toString());
 	}
 	
 	private String streamToString( InputStream is ) throws IOException 

http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/39aa7d86/awsapi/src/com/cloud/bridge/service/controller/s3/S3ObjectAction.java
----------------------------------------------------------------------
diff --git a/awsapi/src/com/cloud/bridge/service/controller/s3/S3ObjectAction.java b/awsapi/src/com/cloud/bridge/service/controller/s3/S3ObjectAction.java
index 8fb89f9..ee4cec6 100644
--- a/awsapi/src/com/cloud/bridge/service/controller/s3/S3ObjectAction.java
+++ b/awsapi/src/com/cloud/bridge/service/controller/s3/S3ObjectAction.java
@@ -45,9 +45,12 @@ import com.amazon.s3.CopyObjectResponse;
 import com.amazon.s3.GetObjectAccessControlPolicyResponse;
 import com.cloud.bridge.io.MTOMAwareResultStreamWriter;
 import com.cloud.bridge.model.SAcl;
+import com.cloud.bridge.model.SAclVO;
 import com.cloud.bridge.model.SBucket;
+import com.cloud.bridge.model.SBucketVO;
 import com.cloud.bridge.persist.dao.MultipartLoadDao;
 import com.cloud.bridge.persist.dao.SBucketDao;
+import com.cloud.bridge.persist.dao.SBucketDaoImpl;
 import com.cloud.bridge.service.S3Constants;
 import com.cloud.bridge.service.S3RestServlet;
 import com.cloud.bridge.service.UserContext;
@@ -79,9 +82,11 @@ import com.cloud.bridge.util.DateHelper;
 import com.cloud.bridge.util.HeaderParam;
 import com.cloud.bridge.util.ServletRequestDataSource;
 import com.cloud.bridge.util.OrderedPair;
+import com.cloud.utils.component.ComponentLocator;
 
 public class S3ObjectAction implements ServletAction {
     protected final static Logger logger = Logger.getLogger(S3ObjectAction.class);
+    protected final SBucketDao bucketDao = ComponentLocator.inject(SBucketDaoImpl.class);
 
     private DocumentBuilderFactory dbf = null;
     
@@ -273,8 +278,7 @@ public class S3ObjectAction implements ServletAction {
 		String bucketName = (String)request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
 		String key        = (String)request.getAttribute(S3Constants.OBJECT_ATTR_KEY);
 		
-		SBucketDao bucketDao = new SBucketDao();
-		SBucket bucket = bucketDao.getByName( bucketName );
+		SBucketVO bucket = bucketDao.getByName( bucketName );
 		String owner = null;        
         if ( null != bucket ) 
         	 owner = bucket.getOwnerCanonicalId();
@@ -296,7 +300,7 @@ public class S3ObjectAction implements ServletAction {
      	 S3AccessControlList aclRequest = new S3AccessControlList();
      		
      	 String aclRequestString = request.getHeader("x-amz-acl");
-     	 OrderedPair <Integer,Integer> accessControlsForObjectOwner = SAcl.getCannedAccessControls(aclRequestString,"SObject");
+     	 OrderedPair <Integer,Integer> accessControlsForObjectOwner = SAclVO.getCannedAccessControls(aclRequestString,"SObject");
      	 grantRequest.setPermission(accessControlsForObjectOwner.getFirst());
      	 grantRequest.setGrantee(accessControlsForObjectOwner.getSecond());
      	 grantRequest.setCanonicalUserID(owner);
@@ -484,6 +488,11 @@ public class S3ObjectAction implements ServletAction {
 
 		S3GetObjectResponse engineResponse = ServiceProvider.getInstance().getS3Engine().handleRequest( engineRequest );		
 		response.setStatus( engineResponse.getResultCode());
+
+		//bucket lookup for non-existance key 
+		
+		if ( engineResponse.getResultCode() == 404 )
+		    return;
 		
 		String deleteMarker = engineResponse.getDeleteMarker();
 		if ( null != deleteMarker ) {
@@ -891,8 +900,7 @@ public class S3ObjectAction implements ServletAction {
 
     	
 		// -> does the bucket exist, we may need it to verify access permissions
-		SBucketDao bucketDao = new SBucketDao();
-		SBucket bucket = bucketDao.getByName(bucketName);
+		SBucketVO bucket = bucketDao.getByName(bucketName);
 		if (bucket == null) {
 			logger.error( "listUploadParts failed since " + bucketName + " does not exist" );
 	    	response.setStatus(404);