A user has a few Lookup selections on a JSP page. After he's selected what data he wants exported, the JSP calls my servlet which should do something like this:
- get request data
- generate SQL for the request data
- execute the SQL and write it to a XML file
- package the XML file to a ZIP file and return it as a response
Now, the first two points are trivial, but the second two are what I'm unsure of:
//3. execute the SQL and write it to a XML file
ConnectionManager cm = new ConnectionManager();
Connection conn = null;
ResultSet rs = null;
Statement stmt = null;
try {
conn =cm.getConnection();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(sqlQuery);
// generates XML and writes it to a java.io.Writer
OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream(Konstante.zipFolder + idVrsteSifarnika+ ".xml"), "UTF8");
XMLWriter.writeXMLToWriter(rs,writer);
} catch (Exception ex) {
logger.error(ex);
} finally {
ConnectionManager.close(rs, stmt, conn);
}
//4. package the XML file to a ZIP file and return it as a response
ZipEntry ze = new ZipEntry(idVrsteSifarnika + ".xml");
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
ZipOutputStream zos = new ZipOutputStream(bos);
zos.putNextEntry(ze);
FileInputStream fis = new FileInputStream(new File(Konstante.zipFolder + idVrsteSifarnika+ ".xml"));
final byte[] buffer = new byte[1024];
int n;
while ((n = fis.read(buffer)) != -1)
zos.write(buffer, 0, n);
zos.closeEntry();
zos.flush();
zos.close();
fis.close();
bos.close();
What I would like to know is if could optimize memory usage/execution speed by changing the way I do all this/changing the various streams?
P.S. This is the writeXMLToWriter method
//Set up XML
DataWriter w = new DataWriter(writer);
w.startDocument();
w.setIndentStep(2);
w.startElement(startingXMLElement);
// Get the metadata
ResultSetMetaData meta = rs.getMetaData();
int count = meta.getColumnCount();
// Iterate over the set
while (rs.next()) {
w.startElement(rowElement);
for (int i = 0; i < count; i++) {
Object ob = rs.getObject(i + 1);
if (rs.wasNull()) {
ob = null;
}
String colName = meta.getColumnLabel(i + 1);
if (ob != null ) {
if (ob instanceof Timestamp) {
w.dataElement(colName, Util.formatDate((Timestamp)ob, dateFormat));
}
else if (ob instanceof BigDecimal){
w.dataElement(colName, Util.transformToHTML(new Integer(((BigDecimal)ob).intValue())));
}
else {
w.dataElement(colName, ob.toString());
}
} else {
w.emptyElement(colName);
}
}
w.endElement(rowElement);
}
w.endElement(startingXMLElement);
w.endDocument();