3 * Copyright © 2014 František Kučera (frantovo.cz)
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 3 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package info.globalcode.sql.dk.batch;
19 import info.globalcode.sql.dk.Parameter;
20 import info.globalcode.sql.dk.SQLCommand;
21 import info.globalcode.sql.dk.SQLCommandNamed;
22 import java.io.DataOutputStream;
23 import java.io.IOException;
24 import java.io.OutputStream;
25 import static info.globalcode.sql.dk.batch.BatchConstants.*;
26 import java.io.ByteArrayOutputStream;
27 import java.sql.SQLException;
28 import java.util.List;
32 * @author Ing. František Kučera (frantovo.cz)
34 public class BatchEncoder {
36 public int encode(SQLCommand sqlCommand, OutputStream out) throws BatchException {
38 ByteArrayOutputStream bufferAOS = new ByteArrayOutputStream();
39 DataOutputStream buffer = new DataOutputStream(bufferAOS);
41 buffer.write(BATCH_HEADER);
43 if (sqlCommand instanceof SQLCommandNamed) {
44 sqlCommand = ((SQLCommandNamed) sqlCommand).getSQLCommandNumbered();
47 writeNextString(sqlCommand.getQuery(), buffer);
49 List<? extends Parameter> parameters = sqlCommand.getParameters();
51 buffer.writeInt(parameters.size());
53 for (Parameter p : parameters) {
54 buffer.writeInt(p.getType().getCode());
55 writeNextString((String) p.getValue(), buffer); // parameters are encoded before any preprocessing
59 bufferAOS.writeTo(out);
61 return bufferAOS.size();
62 } catch (IOException e) {
63 throw new BatchException("Unable to write SQL command: " + sqlCommand, e);
64 } catch (SQLException e) {
65 throw new BatchException("Unable to converd named SQL command to numbered: " + sqlCommand, e);
69 private void writeNextString(String s, DataOutputStream out) throws IOException {
70 byte[] bytes = toBytes(s);
71 out.writeInt(bytes.length);
75 private static byte[] toBytes(String s) {
79 return s.getBytes(CHARSET);