Commit a809df92 authored by Sara Bertocco's avatar Sara Bertocco
Browse files

New working version after Victoria trip - new version reading base url from...

New working version after Victoria trip - new version reading base url from config file and passind the jobid to the backend
parent 33b4bae1
Loading
Loading
Loading
Loading
+21 −188
Original line number Diff line number Diff line
@@ -30,28 +30,25 @@ import java.net.MalformedURLException;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import java.sql.*;

import ca.nrc.cadc.net.TransientException;
import ca.nrc.cadc.util.RsaSignatureGenerator;
import ca.nrc.cadc.util.RsaSignatureVerifier;
import ca.nrc.cadc.uws.Job;
import ca.nrc.cadc.uws.Parameter;
import ca.nrc.cadc.vos.Protocol;
import ca.nrc.cadc.vos.VOSURI;
import ca.nrc.cadc.vos.View;
import ca.nrc.cadc.vos.server.transfers.TransferGenerator;
import it.inaf.oats.vospacebackend.exceptions.ExceptionMessage;
import it.inaf.oats.vospacebackend.exceptions.VOSpaceBackendException;
import it.inaf.oats.vospacebackend.utils.ConfigReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.UUID;
import java.util.logging.Level;
import javax.sql.DataSource;
   
import java.io.UnsupportedEncodingException;    
import java.security.InvalidKeyException;
import javax.servlet.ServletContext;
import java.text.MessageFormat;
import java.util.logging.Level;

import javax.xml.bind.DatatypeConverter;

import org.apache.log4j.Logger;
@@ -60,7 +57,7 @@ import org.apache.log4j.Logger;
 *
 * @author bertocco
 */
public class TransferGeneratorImpl {
public class TransferGeneratorImpl implements TransferGenerator{
    
    Logger log = Logger.getLogger(TransferGeneratorImpl.class);
    
@@ -83,195 +80,31 @@ public class TransferGeneratorImpl {
        String path = target.getPath();
        String fileName = target.getName();
        String vosuri = target.toString();                      
        /*
        HashMap myMetadata;
        try {
            myMetadata = setPutRequest(unique_file_id_str, vosuri);
        String jobID = job.getID();
        
            if ((boolean)myMetadata.get("ifSuccessful")) {
                log.debug("File Put Request correctly set");            
            } else {
                log.debug("File Put Request NOT set, return null");
                return null;
            }
            
 
        } catch (MalformedURLException e) {
            log.debug("Error parsing target");
            return null;            
        } catch (VOSpaceBackendException ex) {
            java.util.logging.Logger.getLogger(TransferGeneratorImpl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            java.util.logging.Logger.getLogger(TransferGeneratorImpl.class.getName()).log(Level.SEVERE, null, ex);
        } 
        */
        
        try {
            String parametersToEncode = vosuri;
            String encodedParams = manageParametersEncoding(parametersToEncode);
            result.add(new URL("http://localhost/VOSpaceBackend/service/myResource/" + encodedParams));
            ConfigReader myConf = new ConfigReader("VOSpace.properties");
            String serviceBaseURL= myConf.getProperty("vospacebackend.service.base.url"); 
            
            result.add(new URL(serviceBaseURL + encodedParams + "/" + jobID));
        } catch (MalformedURLException e) {
            log.debug("Error parsing target");
            return null;
        }
    
        return result;
    }
    
/*    
    public HashMap getPutRequests(String stored_f_name) 
                                  throws VOSpaceBackendException, SQLException {
        
        String myOp = "GET_PUT_REQ";
        
        String myQuery = "SELECT * FROM vosbackend.RequestedPuts " +
                "WHERE storedFileID=?";
        
        FileRecord myParams = new FileRecord("", stored_f_name, "", "");
        
        myResult = excuteQuery(myOp, myQuery, myParams);
        
        return myResult;
        
    }
    
    
    public HashMap setPutRequest(String stored_f_name, String vosuriStr) 
                                  throws VOSpaceBackendException, SQLException {
       
        String myOp = "SET_PUT_REQ";
        String myQuery = "INSERT INTO vosbackend.RequestedPuts " +
                "(storedFileID, vosuri)" +
                " VALUES (?, ?);";
        log.debug("Received params: " + stored_f_name + " " + vosuriStr );
        FileRecord myParams = new FileRecord("", stored_f_name, "", "", vosuriStr);       
        
        myResult = excuteQuery(myOp, myQuery, myParams);
        
        return myResult;
        
    }
    
    private HashMap excuteQuery(String operation, String query, FileRecord fileToStore) 
                                                throws VOSpaceBackendException, SQLException {
        PreparedStatement preparedStatementInsert = null;
       
        Connection dbConnection = null;
        
        try {
	    dbConnection = getDBConnection();
            log.debug("Database connection get");
        } catch (SQLException e) {
            log.fatal(e);
            ExceptionMessage exMsg = new ExceptionMessage();
            throw new VOSpaceBackendException(ExceptionMessage.getMessage("UNABLE_TO_GET_DB_CONNECTION"));
	}

	try {
	    dbConnection.setAutoCommit(false);
            log.debug("Autocommit set false");
	} catch (SQLException e) {
            log.fatal(e);
            ExceptionMessage exMsg = new ExceptionMessage();
            throw new VOSpaceBackendException(ExceptionMessage.getMessage("ERROR_DISABLING_DB_AUTOCOMMIT"));
	}
        
	// Starts JDBC Transaction
        PreparedStatement preparedQuery = null;
	try {
            
            HashMap fileToStoreFields = fileToStore.getFileRecord();
            ResultSet rs = null;   
            int rowCounter = 0;
            switch (operation) {
                case "GET_PUT_REQ":
                    preparedQuery = dbConnection.prepareStatement(query);
                    preparedQuery.setString(1, (String)fileToStoreFields.get("stored_file_name"));
                    preparedQuery.setString(2, (String)fileToStoreFields.get("vosuri"));
                    rs = preparedQuery.executeQuery();
                    rowCounter = 0;
                    while (rs.next()) {
                        rowCounter = rowCounter +1;
                        myResult.put("stored_file_name", rs.getString("storedFileID"));
                        myResult.put("vosuri", rs.getString("vosuri"));
                    }
                    if (rowCounter == 0) {
                        log.debug("GET_PUT_REQ: query successfully executed. File " + (String)fileToStoreFields.get("stored_file_name") + " not found");                      
                        myResult.put("ifSuccessful", false);
                    } else {
                        log.debug("GET_PUT_REQ: query successfully executed. File " + (String)fileToStoreFields.get("stored_file_name") + " found");
                        myResult.put("ifSuccessful", true);
                    }
                    break;
                case "SET_PUT_REQ":                   
                    log.debug("Going to prepare query for SET_PUT_REQ operation");
                    preparedQuery = dbConnection.prepareStatement(query);
                    log.debug("StoredFileName to set in db reqs " + (String)fileToStoreFields.get("stored_file_name"));                    
                    log.debug("vosuri to set in db reqs " + (String)fileToStoreFields.get("vosuri"));
                    preparedQuery.setString(1, (String)fileToStoreFields.get("stored_file_name"));
                    preparedQuery.setString(2, (String)fileToStoreFields.get("vosuri"));
                    log.debug("Going to execute query");
                    preparedQuery.executeUpdate();
                    log.debug("Query executed");
                    dbConnection.commit();
                    log.debug("Query committed");                    
                    myResult.put("ifSuccessful", true);
                    break;                    
                    
                default:                  
                    myResult.put("ifSuccessful", false);
        } catch (VOSpaceBackendException ex) {
            ExceptionMessage exMsg = new ExceptionMessage();
                    log.fatal(ExceptionMessage.getMessage("DB_OPERATION_NOT_RECOGNIZED"));
                    throw new VOSpaceBackendException(ExceptionMessage.getMessage("DB_OPERATION_NOT_RECOGNIZED"));                    
                }
            
            dbConnection.setAutoCommit(true);
                        
            dbConnection.close();
            
        } catch (SQLException e) {

            log.error("SQLException exception executing SET file" + e.getMessage());
	    dbConnection.rollback();

	} finally {

            if (preparedQuery != null) {
		preparedQuery.close();
            }

            if (dbConnection != null) {
		dbConnection.close();
            }
            
	}
        
        return myResult;
       
            log.debug(MessageFormat.format(
                      exMsg.getMessage("UNABLE_TO_READ_PROPERTIES"), "VOSpace.properties"));
            log.debug(MessageFormat.format(
                             exMsg.getMessage("PROPERTY_NOT_FOUND"), "fs.posix.tmp.storage.root", "VOSpace.properties"));
            return null;
        }
    
    
    public Connection getDBConnection() throws SQLException {

        String url = "jdbc:mysql://localhost:3306/vosbackend";
        String username = "vosbackadmin";
        String password = "Peper0ne";

        System.out.println("Connecting database...");
    
        Connection connection;
        try {
           connection = DriverManager.getConnection(url, username, password);
          System.out.println("Database connected!");
        } catch (SQLException e) {
          throw new IllegalStateException("Cannot connect the database!", e);

        return result;
    }
    
        return connection;
    
    }
    */
    
    private String manageParametersEncoding(String toBeSigned) {