java/sql-dk/src/main/java/info/globalcode/sql/dk/batch/BatchEncoder.java
author František Kučera <franta-hg@frantovo.cz>
Mon, 04 Mar 2019 20:15:24 +0100
branchv_0
changeset 238 4a1864c3e867
parent 147 java/sql-dk/src/info/globalcode/sql/dk/batch/BatchEncoder.java@4a704c1669f4
child 250 aae5009bd0af
permissions -rw-r--r--
mavenized: sql-dk

/**
 * SQL-DK
 * Copyright © 2014 František Kučera (frantovo.cz)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package info.globalcode.sql.dk.batch;

import info.globalcode.sql.dk.Parameter;
import info.globalcode.sql.dk.SQLCommand;
import info.globalcode.sql.dk.SQLCommandNamed;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import static info.globalcode.sql.dk.batch.BatchConstants.*;
import java.io.ByteArrayOutputStream;
import java.sql.SQLException;
import java.util.List;

/**
 *
 * @author Ing. František Kučera (frantovo.cz)
 */
public class BatchEncoder {

	public int encode(SQLCommand sqlCommand, OutputStream out) throws BatchException {
		try {
			ByteArrayOutputStream bufferAOS = new ByteArrayOutputStream();
			DataOutputStream buffer = new DataOutputStream(bufferAOS);

			buffer.write(BATCH_HEADER);

			if (sqlCommand instanceof SQLCommandNamed) {
				sqlCommand = ((SQLCommandNamed) sqlCommand).getSQLCommandNumbered();
			}

			writeNextString(sqlCommand.getQuery(), buffer);

			List<? extends Parameter> parameters = sqlCommand.getParameters();

			buffer.writeInt(parameters.size());

			for (Parameter p : parameters) {
				buffer.writeInt(p.getType().getCode());
				writeNextString((String) p.getValue(), buffer); // parameters are encoded before any preprocessing
			}

			buffer.flush();
			bufferAOS.writeTo(out);
			out.flush();
			return bufferAOS.size();
		} catch (IOException e) {
			throw new BatchException("Unable to write SQL command: " + sqlCommand, e);
		} catch (SQLException e) {
			throw new BatchException("Unable to converd named SQL command to numbered: " + sqlCommand, e);
		}
	}

	private void writeNextString(String s, DataOutputStream out) throws IOException {
		byte[] bytes = toBytes(s);
		out.writeInt(bytes.length);
		out.write(bytes);
	}

	private static byte[] toBytes(String s) {
		if (s == null) {
			return new byte[]{};
		} else {
			return s.getBytes(CHARSET);
		}
	}
}