--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/java/sql-dk/src/main/java/info/globalcode/sql/dk/batch/BatchEncoder.java Mon Mar 04 20:15:24 2019 +0100
@@ -0,0 +1,83 @@
+/**
+ * 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);
+ }
+ }
+}