All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.kawanfw.sql.jdbc.http.JdbcHttpBatchTransfer Maven / Gradle / Ivy

/*
 * This file is part of AceQL. 
 * AceQL: Remote JDBC access over HTTP.                                     
 * Copyright (C) 2015,  KawanSoft SAS
 * (http://www.kawansoft.com). All rights reserved.                                
 *                                                                               
 * AceQL is free software; you can redistribute it and/or                 
 * modify it under the terms of the GNU Lesser General Public                    
 * License as published by the Free Software Foundation; either                  
 * version 2.1 of the License, or (at your option) any later version.            
 *                                                                               
 * AceQL is distributed in the hope that it will be useful,               
 * but WITHOUT ANY WARRANTY; without even the implied warranty of                
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU             
 * Lesser General Public License for more details.                               
 *                                                                               
 * You should have received a copy of the GNU Lesser General Public              
 * License along with this library; if not, write to the Free Software           
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  
 * 02110-1301  USA
 *
 * Any modifications to this file must keep this entire header
 * intact.
 */
package org.kawanfw.sql.jdbc.http;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;

import org.kawanfw.commons.api.client.InvalidLoginException;
import org.kawanfw.commons.client.http.HttpTransfer;
import org.kawanfw.commons.client.http.SimpleNameValuePair;
import org.kawanfw.commons.util.ClientLogger;
import org.kawanfw.commons.util.FrameworkDebug;
import org.kawanfw.commons.util.Tag;
import org.kawanfw.file.util.parms.Parameter;
import org.kawanfw.file.util.parms.ReturnCode;
import org.kawanfw.sql.api.client.InvalidatedSessionException;
import org.kawanfw.sql.jdbc.ConnectionHttp;
import org.kawanfw.sql.jdbc.util.StatementHolderFileList;
import org.kawanfw.sql.jdbc.util.StatementHolderListEncryptor;
import org.kawanfw.sql.json.ConnectionHolder;
import org.kawanfw.sql.json.ConnectionHolderTransport;
import org.kawanfw.sql.json.StatementHolder;
import org.kawanfw.sql.json.StatementHolderTransport;
import org.kawanfw.sql.transport.TransportConverter;
import org.kawanfw.sql.util.ConnectionParms;
import org.kawanfw.sql.util.SqlAction;
import org.kawanfw.sql.util.SqlReturnCode;

/**
 * 
 * Class that execute all http batch transfer to the server, and gets back the
 * results
 * 
 */
public class JdbcHttpBatchTransfer {
    /** Set to true to display/log debug info */
    private static boolean DEBUG = FrameworkDebug
	    .isSet(JdbcHttpBatchTransfer.class);

    /** The Http Connection */
    private ConnectionHttp connectionHttp = null;

    /** The Authentication Token */
    private String authenticationToken = null;

    /**
     * Protected constructor, not callable
     */
    protected JdbcHttpBatchTransfer() {
    }

    /**
     * Constructor
     * 
     * @param connectionHttp
     *            the http Connection
     * @param authenticationToken
     *            the Http Connection Authentication Token
     */

    public JdbcHttpBatchTransfer(ConnectionHttp connectionHttp,
	    String authenticationToken) {
	this.connectionHttp = connectionHttp;
	this.authenticationToken = authenticationToken;
    }

    /**
     * /** Execute a remote sql execute update of batchs prepared statement and
     * get the string
     * 
     * @param statementHolder
     *            the statement or prepared statement
     * @param batchHolderFileList
     *            the batch parameter list
     * @return the result of the execute update
     */
    public String getStringFromExecutePrepStatementBatchOnServer(
	    StatementHolder statementHolder,
	    StatementHolderFileList batchHolderFileList) throws SQLException {

	// First, we close the file!
	batchHolderFileList.close();

	if (batchHolderFileList.isEmpty()) {
	    String message = Tag.PRODUCT_PRODUCT_FAIL
		    + "Nothing to execute: batchHolderList is empty!";
	    throw new SQLException(message, new IOException(message));
	}

	HttpTransfer httpTransfer = connectionHttp.getHttpTransfer();

	debug("this.connectionHttp.getHost()    : " + connectionHttp.getUrl());

	// Launch the Servlet

	List requestParams = new Vector();
	requestParams.add(new SimpleNameValuePair(Parameter.ACTION,
		SqlAction.ACTION_SQL_PREP_STATEMENT_BATCH));
	requestParams.add(new SimpleNameValuePair(Parameter.USERNAME,
		connectionHttp.getUsername()));
	requestParams.add(new SimpleNameValuePair(Parameter.TOKEN,
		authenticationToken));

	requestParams.add(new SimpleNameValuePair(ConnectionParms.CONNECTION_ID,
		connectionHttp.getConnectionId()));

	// Store the Connections commit mode / read only mode / transaction
	// isolation
	ConnectionHolder connectionHolder = new ConnectionHolder(connectionHttp);
	String jsonString = ConnectionHolderTransport.toJson(connectionHolder);
	requestParams.add(new SimpleNameValuePair(SqlAction.CONNECTION_HOLDER,
		jsonString));

	// Execute the statement waiting
	List statementHolderList = new Vector();
	statementHolderList.add(statementHolder); // Only one StatementHolder

	StatementHolderListEncryptor.encrypt(statementHolderList,
		connectionHttp);

	jsonString = StatementHolderTransport.toJson(statementHolderList);
	requestParams.add(new SimpleNameValuePair(SqlAction.STATEMENT_HOLDER,
		jsonString));

	// StatementHolderCrypto.encrypt(batchHolderList, connectionHttp);

	// Execute all the statements waiting
	if (batchHolderFileList.size() < connectionHttp
		.getMaxStatementsForMemoryTransport()) {

	    jsonString = StatementHolderTransport.toJson(batchHolderFileList
		    .getStatementHolderList());
	    debug("batchHolderList in jsonString: " + jsonString);

	    // Delete the associated file
	    batchHolderFileList.delete();

	    requestParams.add(new SimpleNameValuePair(
		    SqlAction.BATCH_PARAMS_HOLDER, jsonString));

	    try {
		httpTransfer.send(requestParams);
	    } catch (Exception e) {
		JdbcHttpTransferUtil.wrapExceptionAsSQLException(e);
	    }

	} else {
	    debug("batchHolderList.size() >= connectionHttp.getMaxStatementsForMemoryTransport())");

	    // StatementHolderFileCreator statementHolderFileCreator = new
	    // StatementHolderFileCreator(
	    // batchHolderList);

	    JdbcHttpFileTransfer jdbcHttpFileTransfer = new JdbcHttpFileTransfer(
		    this.connectionHttp);
	    jdbcHttpFileTransfer.uploadFile(batchHolderFileList.getLocalFile(),
		    batchHolderFileList.getRemoteFileName());

	    String statementHolderParam = TransportConverter.KAWANFW_BYTES_STREAM_FILE
		    + batchHolderFileList.getRemoteFileName();
	    requestParams.add(new SimpleNameValuePair(
		    SqlAction.BATCH_PARAMS_HOLDER, statementHolderParam));

	    try {
		httpTransfer.send(requestParams);
	    } catch (Exception e) {
		JdbcHttpTransferUtil.wrapExceptionAsSQLException(e);
	    }

	}

	String receive = httpTransfer.recv();

	debug("httpTransfer.recv(): " + receive + ":");

	if (receive.startsWith(ReturnCode.INVALID_LOGIN_OR_PASSWORD)) {
	    throw new SQLException(new InvalidLoginException());
	}

	if (receive.startsWith(SqlReturnCode.SESSION_INVALIDATED)) {
	    throw new SQLException(new InvalidatedSessionException());
	}

	// We are done: return the received string
	return receive;

    }

    /**
     * Execute a remote sql execute update of batchs statement and get the
     * string
     * 
     * @param batchHolderFileList
     *            the batch statement parameter list
     * @return the result of the execute update
     */
    public String getStringFromExecuteStatementBatchOnServer(
	    StatementHolderFileList batchHolderFileList) throws SQLException {

	// First, we close the file!
	batchHolderFileList.close();

	if (batchHolderFileList.isEmpty()) {
	    String message = Tag.PRODUCT_PRODUCT_FAIL
		    + "Nothing to execute: batchHolderList is empty!";
	    throw new SQLException(message, new IOException(message));
	}

	HttpTransfer httpTransfer = connectionHttp.getHttpTransfer();

	debug("this.connectionHttp.getHost()    : " + connectionHttp.getUrl());

	// Launch the Servlet

	List requestParams = new Vector();
	requestParams.add(new SimpleNameValuePair(Parameter.ACTION,
		SqlAction.ACTION_SQL_STATEMENT_BATCH));
	requestParams.add(new SimpleNameValuePair(Parameter.USERNAME,
		connectionHttp.getUsername()));
	requestParams.add(new SimpleNameValuePair(Parameter.TOKEN,
		authenticationToken));

	requestParams.add(new SimpleNameValuePair(ConnectionParms.CONNECTION_ID,
		connectionHttp.getConnectionId()));

	// Store the Connections commit mode / read only mode / transaction
	// isolation
	ConnectionHolder connectionHolder = new ConnectionHolder(connectionHttp);
	String jsonString = ConnectionHolderTransport.toJson(connectionHolder);
	requestParams.add(new SimpleNameValuePair(SqlAction.CONNECTION_HOLDER,
		jsonString));

	// StatementHolderCrypto.encrypt(batchHolderList, connectionHttp);

	// Execute all the statements waiting
	if (batchHolderFileList.size() < connectionHttp
		.getMaxStatementsForMemoryTransport()) {

	    jsonString = StatementHolderTransport.toJson(batchHolderFileList
		    .getStatementHolderList());
	    requestParams.add(new SimpleNameValuePair(
		    SqlAction.STATEMENT_HOLDER, jsonString));

	    // Delete the associated file
	    batchHolderFileList.delete();

	    try {
		httpTransfer.send(requestParams);
	    } catch (Exception e) {
		JdbcHttpTransferUtil.wrapExceptionAsSQLException(e);
	    }

	} else {
	    debug("batchHolderList.size() >= connectionHttp.getMaxStatementsForMemoryTransport())");

	    // StatementHolderFileCreator statementHolderFileCreator = new
	    // StatementHolderFileCreator(
	    // batchHolderList);

	    JdbcHttpFileTransfer jdbcHttpFileTransfer = new JdbcHttpFileTransfer(
		    this.connectionHttp);
	    jdbcHttpFileTransfer.uploadFile(batchHolderFileList.getLocalFile(),
		    batchHolderFileList.getRemoteFileName());

	    String statementHolderParam = TransportConverter.KAWANFW_BYTES_STREAM_FILE
		    + batchHolderFileList.getRemoteFileName();
	    requestParams.add(new SimpleNameValuePair(
		    SqlAction.STATEMENT_HOLDER, statementHolderParam));

	    try {
		httpTransfer.send(requestParams);
	    } catch (Exception e) {
		JdbcHttpTransferUtil.wrapExceptionAsSQLException(e);
	    }

	}

	String receive = httpTransfer.recv();

	debug("httpTransfer.recv(): " + receive + ":");

	if (receive.startsWith(ReturnCode.INVALID_LOGIN_OR_PASSWORD)) {
	    throw new SQLException(new InvalidLoginException());
	}

	if (receive.startsWith(SqlReturnCode.SESSION_INVALIDATED)) {
	    throw new SQLException(new InvalidatedSessionException());
	}

	// We are done: return the received string
	return receive;

    }

    /**
     * Debug tool
     * 
     * @param s
     */

    // @SuppressWarnings("unused")
    private void debug(String s) {
	if (DEBUG) {
	    ClientLogger.getLogger().log(Level.WARNING, s);
	}
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy