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

base.query.SqlImport Maven / Gradle / Ivy

/*
 This is free and unencumbered software released into the public domain.

 Anyone is free to copy, modify, publish, use, compile, sell, or
 distribute this software, either in source code form or as a compiled
 binary, for any purpose, commercial or non-commercial, and by any
 means.

 In jurisdictions that recognize copyright laws, the author or authors
 of this software dedicate any and all copyright interest in the
 software to the public domain. We make this dedication for the benefit
 of the public at large and to the detriment of our heirs and
 successors. We intend this dedication to be an overt act of
 relinquishment in perpetuity of all present and future rights to this
 software under copyright law.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
 */
package base.query;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.sql.DataSource;


import base.Command;
import base.json.Json;
import base.json.JsonParser;

/**
 * Insert data loaded from a JSON file into a database table. JSON file
 * is expected to be in the format output by the SqlQuery command.
 */
public class SqlImport extends Command {

	private DataSource ds;
	private String table;
	private InputStream is;

	/**
	 * Unused constructor for the ServiceLoader
	 */
	public SqlImport() {
	}

	/**
	 * Insert data loaded from a JSON file into a database table. JSON file
	 * is expected to be in the format output by the SqlQuery command.
	 *
	 * @param ds
	 * @throws SQLException
	 */
	public SqlImport(DataSource ds, String table, InputStream is) throws SQLException {
		this.ds = ds;
		this.table = table;
		this.is = is;
	}

	public String getJsonParameters() {
		return "\"table\":\"" + Json.escape(table) + "\"";
	}

	@SuppressWarnings("unchecked")
	public void execute() throws IOException {
		Connection c = null;

		try {
			c = ds.getConnection();
			c.setAutoCommit(false);

			JsonParser parser = new JsonParser(new BufferedReader(new InputStreamReader(is, "UTF-8")));
			Object items = parser.parse();

			if(!(items instanceof List)) {
				throw new IOException("Import file must contain a JSON list");
			}
			List itemList = (List)(List)items;
			if(itemList.size() == 0) {
				return;
			}

			if(!(itemList.get(0) instanceof Map)) {
				throw new IOException("Import file must contain a JSON list of maps");
			}
			if(((Map)(Map)itemList.get(0)).size() == 0) {
				return;
			}

			executeImport(c, (List>)(List)itemList);

			c.commit();
			c.close();
		} catch (SQLException e) {
			if(c != null) {
				try { c.rollback(); } catch (SQLException e1) { }
				try { c.close(); } catch (SQLException e1) { }
			}
			throw new IOException(e);
		}

	}

	/**
	 * Return each setting in the form of key value pairs.
	 */
	public void executeImport(Connection c, List> items) throws SQLException {

		PreparedStatement s = null;
		try {

			s = c.prepareStatement("delete from " + table);
			s.executeUpdate();
			s.close();

			for(Map row : items) {

				String sql = "insert into " + table + " (";
				Set keys = row.keySet();
				for(String key : keys) {
					sql += key + ",";
				}
				sql = sql.substring(0, sql.length()-1);
				sql += ") ";
				sql += " values(";
				for(int i = 0; i < row.size(); i++) {
					sql += "?,";
				}
				sql = sql.substring(0, sql.length()-1);
				sql += ")";
				s = c.prepareStatement(sql);

				int i = 1;
				for(String key : keys) {
					s.setObject(i++, row.get(key));
				}
				s.executeUpdate();
				s.close();
				s = null;
			}

		} finally {
			if(s != null) { try { s.close(); } catch(Exception f) {} }
		}

	}

}