I try to read CSV files into a MySQL-DB but the files have more than 40000 lines. The CSV-Reader is not the problem. And I can write the lines into the MySQL-DB. But when I will read and write all lines of the CSV my Connection to the MySQL-Server gets killed in the process. The Program reads and writes successfully more than 1000 lines before my connection ends. I get the following errors:
java.sql.SQLException: Could not retrieve transation read-only status server
Or
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet successfully received from the server was 328.971 milliseconds ago. The last packet sent successfully to the server was 328.971 milliseconds ago.
Do you have any idea why this is?
I wrote in the catch-block a method that renews the connection but it read few rows and the connection was kill again.
The Code to get the lines from the CSV and load into the MySQL-DB
kptoolsDB.setAutoCommit(false);
dateiImpDB.setAutoCommit(false);
while(prop != null && this.isInterrupted() == false)
{
vertragsID = null;
rufNr = null;
try {
setDaten(prop);
kptoolsDB.commit();
dateiImpDB.commit();
} catch (SQLException e) {
e.printStackTrace();
log.log(LogLevel.ERROR, e.toString(), this);
setDBConnections(hilfstabelle);
try {
setDaten(prop);
kptoolsDB.commit();
dateiImpDB.commit();
} catch (SQLException e1) {
log.log(LogLevel.ERROR, e.toString(), this);
setDBConnections(hilfstabelle);
}
}
view.setProgessBarVal(count);
prop = reader.getNextLine();
count++;
}
kptoolsDB.setAutoCommit(true);
dateiImpDB.setAutoCommit(true);
The method setDaten()
private void setDaten(Properties prop) throws SQLException
{
ResultSet rst;
rst = statKPTools.executeQuery("select rechnungsID from isimrechnungeintrag where rawcdr = " + prop.get("i_rawcdr") + ";");
if(rst.next())
{
log.log(LogLevel.INFO, "Die CDR-Nummer " + prop.get("i_rawcdr") + " ist schon eingetragen!", this);
} else {
rst.close();
rufNr = "+" + prop.get("MSISDN").toString().replace("-", "").replace(" ", "");
if(!pruefeRufnummer(rufNr))
{
setRufNrNichtGefunden(rufNr);
} else {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
Date datum = null;
try {
datum = sdf.parse(prop.get("call_start_datetime").toString());
} catch (ParseException e) {
log.log(LogLevel.ERROR, e.toString(), this);
}
prepSetRechEintrag.setInt(1, 5);
prepSetRechEintrag.setLong(3, vertragsID);
prepSetRechEintrag.setDate(2, new java.sql.Date(datum.getTime()));
prepSetRechEintrag.executeUpdate();
rst = statKPTools.executeQuery("select max(ID) from rechnungseintrag;");
if(rst.next())
{
prepSetISIMRechEintag.setLong(1, rst.getLong(1));
prepSetISIMRechEintag.setDouble(2, new Double(prop.get("VK netto").toString().replace(",", ".")));
prepSetISIMRechEintag.setDouble(3, new Double(prop.get("EK netto").toString().replace(",", ".")));
prepSetISIMRechEintag.setInt(4, new Integer(prop.get("event_id").toString()));
prepSetISIMRechEintag.setString(5, prop.get("event").toString());
prepSetISIMRechEintag.setLong(6, new Long(prop.get("i_rawcdr").toString()));
prepSetISIMRechEintag.executeUpdate();
Calendar cal = Calendar.getInstance();
cal.setTime(datum);
prepInsertVolumHilfe.setLong(1, vertragsID);
prepInsertVolumHilfe.setInt(2, new Integer(prop.get("event_id").toString()));
prepInsertVolumHilfe.setString(3, prop.get("event").toString());
prepInsertVolumHilfe.setLong(4, new Long(prop.get("charged_quantity").toString()));
prepInsertVolumHilfe.setInt(5, cal.get(Calendar.MONTH));
prepInsertVolumHilfe.setInt(6, cal.get(Calendar.YEAR));
prepInsertVolumHilfe.executeUpdate();
}
}
}
rst.close();
}
The MySQL-Connection Class
package DatenbankConector;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import EigeneExceptions.FehlendeLoginDaten;
import Enums.LogLevel;
import Enums.MySQLDatenbanken;
import Hilfsklassen.Logger;
public class MYSQLDB {
private static MYSQLDB loginDB = null;
private static MYSQLDB kptoolsDB = null;
private static MYSQLDB datenImpDB = null;
private static String loginUser = null;
private static String loginPass = null;
private Logger log = Logger.getInstance();
private Connection connect;
private String dbHost = "XXX.XXX.XXX.XXX"; // Hostname
private String dbPort = "3306"; // Port -- Standard: 3306
private String logindbUser = "******"; // Login-Datenbankuser
private String logindbPass = "********"; // Login-Datenbankpasswort
private boolean kannStarten = false;
private MySQLDatenbanken dbEnum;
private MYSQLDB(MySQLDatenbanken db)
{
String strConnect = "";
dbEnum = db;
switch(db)
{
case LOGIN_DB:
strConnect = "jdbc:mysql://"+dbHost+":"+ dbPort+"/logindb?"+"user="+logindbUser+"&"+"password="+logindbPass;
break;
case KPTOOLS_DB:
strConnect = "jdbc:mysql://"+dbHost+":"+ dbPort+"/kptools?"+"user="+loginUser+"&"+"password="+loginPass;
break;
case DATEI_IMP_DB:
strConnect = "jdbc:mysql://"+dbHost+":"+ dbPort+"/dateiimporter?"+"user="+loginUser+"&"+"password="+loginPass;
break;
}
try
{
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection(strConnect);
kannStarten = true;
}
catch (SQLException e) {
log.log(LogLevel.ERROR, e.toString(), this);
kannStarten = false;
}
catch (ClassNotFoundException e) {
log.log(LogLevel.ERROR, e.toString(), this);
kannStarten = false;
}
}
/**
* Gibt eine Instanz von MYSQLDB zurueck.
*
* #param db Angabe welche Datenbank aufgerufen werden soll.
*
* #return ein MYSQLDB Objekt
*
* #throws FehlendeLoginDaten Fehler fals noch keine Logindaten gesetzt wurden.
*/
public static MYSQLDB getInstance(MySQLDatenbanken db) throws FehlendeLoginDaten
{
MYSQLDB obj = null;
switch(db)
{
case LOGIN_DB:
if(loginDB == null)
{
loginDB = new MYSQLDB(MySQLDatenbanken.LOGIN_DB);
obj = loginDB;
} else {
obj = loginDB;
}
break;
case KPTOOLS_DB:
if(kptoolsDB == null)
{
if(loginUser != null && loginPass != null)
{
kptoolsDB = new MYSQLDB(MySQLDatenbanken.KPTOOLS_DB);
obj = kptoolsDB;
} else {
throw new FehlendeLoginDaten();
}
} else {
obj = kptoolsDB;
}
break;
case DATEI_IMP_DB:
if(datenImpDB == null)
{
if(loginUser != null && loginPass != null)
{
datenImpDB = new MYSQLDB(MySQLDatenbanken.DATEI_IMP_DB);
obj = datenImpDB;
} else {
throw new FehlendeLoginDaten();
}
} else {
obj = datenImpDB;
}
break;
}
return obj;
}
/**
* Gibt eine Instanz von MYSQLDB zurueck.
*
* #param db Angabe welche Datenbank aufgerufen werden soll.
* #param user Benutzername für den Datenbanklogin
* #param pass Passwort für den Datenbanklogin
*
* #return ein MYSQLDB Objekt
*
* #throws FehlendeLoginDaten Fehler fals noch keine Logindaten gesetzt wurden.
*/
public static MYSQLDB getInstance(MySQLDatenbanken db, String user, String pass) throws FehlendeLoginDaten
{
MYSQLDB objekt = null;
loginUser = user;
loginPass = pass;
switch(db)
{
case LOGIN_DB:
if(loginDB == null)
{
loginDB = new MYSQLDB(MySQLDatenbanken.LOGIN_DB);
objekt = loginDB;
} else {
objekt = loginDB;
}
break;
case KPTOOLS_DB:
if(kptoolsDB == null)
{
if(loginUser != null && loginPass != null)
{
kptoolsDB = new MYSQLDB(MySQLDatenbanken.KPTOOLS_DB);
objekt = kptoolsDB;
} else {
throw new FehlendeLoginDaten();
}
} else {
objekt = kptoolsDB;
}
break;
case DATEI_IMP_DB:
if(datenImpDB == null)
{
if(loginUser != null && loginPass != null)
{
datenImpDB = new MYSQLDB(MySQLDatenbanken.DATEI_IMP_DB);
objekt = datenImpDB;
} else {
throw new FehlendeLoginDaten();
}
} else {
objekt = datenImpDB;
}
break;
}
return objekt;
}
/**
* Gibt ein Satement Objekt du einer Datenbank zurueck.
*
* #return ein Statement der Datenbankconektion
* #throws SQLException
*/
public Statement getStatement() throws SQLException
{
Statement stat = connect.createStatement();
return stat;
}
/**
* Commitet die Datebankaktionen.
*
* #throws SQLException
*/
public void commit() throws SQLException
{
this.connect.commit();
}
/**
* Gibt ein PreparedStatement zu einem SQL-Statement zurueck.
*
* #param sqlString das SQL-Statement
* #return das PreparedStatement
*/
public PreparedStatement getPreparedStatement(String sqlString)
{
try {
return connect.prepareStatement(sqlString);
} catch (SQLException e) {
log.log(LogLevel.ERROR, e.toString(), this);
}
return null;
}
/**
* Schließt eine Datenbankconnection.
*/
public void close()
{
try
{
connect.close();
switch(dbEnum)
{
case LOGIN_DB:
loginDB = null;
break;
case KPTOOLS_DB:
kptoolsDB = null;
break;
case DATEI_IMP_DB:
datenImpDB = null;
break;
}
}
catch (SQLException e) {
log.log(LogLevel.ERROR, e.toString(), this);
}
}
/**
* Gibt zurueck ob beim setzen der Datenbankconnektion ein Fehler aufgetreten ist.
*
* #return funktionstuechtig oder nicht
*/
public boolean getKannStarten()
{
return kannStarten;
}
/**
* Setzt die Auto-Commit Variable der Datenbankconnektion
*
* #param autocom true = Auto-Commit
*/
public void setAutoCommit(boolean autocom)
{
try {
connect.setAutoCommit(autocom);
} catch (SQLException e) {
log.log(LogLevel.ERROR, e.toString(), this);
}
}
}
Check the error logs in your MySQL server. They should tell you why MySQL terminates the connection.
My guess is that the database limits the size of a transaction. Simply put: You're trying to insert too much data at once.
If that's the case, commit the transaction after every 1000 rows.
java.sql.SQLException: Could not retrieve transation read-only status
Use older version of MySQL .
I tested MySQL-connector JDBC driver with both Appserv version and appserv-win32-2.5.9
With Appserv 2.6 I get the above error.
With Appserv version 5 it works fine.
Related
I'm working with Teamcenter and Catia via the Java SOA libraries. I'm running into an issue where the demo code appears broken and I can't find a good example or documentation to work towards. The following code results in a null value exception. Specifically the line "session = PortalContext.getContext().getSession();" is where I'm crashing.
package com.ebsolutions.catiman.actions;
import java.io.File;
import java.io.RandomAccessFile;
/*
* Tc java classes
*/
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemType;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentBOMWindow;
import com.teamcenter.rac.kernel.TCComponentBOMWindowType;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentRevisionRuleType;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
/*
* Catia integration java classes
*/
import com.ebsolutions.catiman.ErrorWarningMessages;
import com.ebsolutions.catiman.PortalContext;
import com.ebsolutions.catiman.commands.TClassUserLUSCommand;
/**
* Sample file.
* This class is not launched by the CATIAV5 integration
*
* #date 02/06/2008
*/
public class SampleIndependentSilentLUS
{
/**
* Current TC session: needed to access Tc server (service.call)
* null value is not allowed.
*/
protected TCSession session = null;
/**
* This flag defines wether the LUS should be performed in silent mode or not
*/
protected boolean is_silent[];
/**
* title of the messages
*/
private String _title = "Sample Independent SilentLUS";
/**
* components that contains the assembly to LUS.
*/
private TCComponentItem[] item = null;
private TCComponentItemRevision[] item_revision = null;
private TCComponentDataset[] part_dataset = null;
private TCComponentDataset[] product_dataset = null;
private TCComponentDataset[] drawing_dataset = null;
private TCComponentForm[] other = null;
private TCComponentBOMWindow bom_window[] = null;
/**
* The constructor.
*/
public SampleIndependentSilentLUS()
{
/* try to find the TCSession
note: this is not the only way to retrieve the TCSession. */
session = PortalContext.getContext().getSession();
}
/* --------------------------------------------------------------------- */
/*
* Sample main function
* #date 02/06/2008
*/
public void customerProcess() {
showInformationMessage("START of silent LUS");
TClassUserLUSCommand silent_lus_command = null;
/*
* example of searching items to LUS
*/
int return_value = findItemToLUS();
if (return_value < 0)
{
/* Unable to find any item to LUS */
return;
}
/**
* Initialize the API
*/
silent_lus_command = new TClassUserLUSCommand(session);
/*
* API: LUS process.
* call the "executeLUS" function
*/
/******* Item ********/
try
{
if (item[0] != null)
{
silent_lus_command.executeLUS(item[0], is_silent[0]);
showInformationMessage("pause in silent LUS after Item");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (1) Exception : " + ex);
}
/******* Item Revision ********/
try
{
if (item_revision[1] != null)
{
silent_lus_command.executeLUS(item_revision[1], is_silent[1]);
showInformationMessage("pause in silent LUS after Item_rev");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (2) Exception : " + ex);
}
/******* bom window ********/
try
{
if (bom_window[2] != null)
{
silent_lus_command.executeLUS(bom_window[2], is_silent[2]);
showInformationMessage("pause in silent LUS after bom_widow");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (3) Exception : " + ex);
}
/******* CATPart dataset ********/
try
{
if (part_dataset[3] != null)
{
silent_lus_command.executeLUS(part_dataset[3], is_silent[3]);
showInformationMessage("pause in silent LUS after CATPart");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (4) Exception : " + ex);
}
/******* CATProduct dataset ********/
try
{
if (product_dataset[4] != null)
{
silent_lus_command.executeLUS(product_dataset[4], is_silent[4]);
showInformationMessage("pause in silent LUS after CATProduct");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (5) Exception : " + ex);
}
/******* CATDrawing dataset ********/
try
{
if (drawing_dataset[5] != null)
{
silent_lus_command.executeLUS(drawing_dataset[5], is_silent[5]);
showInformationMessage("pause in silent LUS after CATDrawing");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (6) Exception : " + ex);
}
/******* other dataset ********/
try
{
if (other[6] != null)
{
silent_lus_command.executeLUS(other[6], is_silent[6]);
showInformationMessage("pause in silent LUS ");
}
}
catch (Exception ex)
{
showErrorMessage("SampleLUS error (7) Exception : " + ex);
}
silent_lus_command.stopProcess();
}
/**
* is used to display an Error message
* #param i_msg (I) the message to be displayed
*/
private void showErrorMessage(final String i_msg)
{
ErrorWarningMessages.showErrorMessage(i_msg, _title);
}
/**
* is used to display an Information message
* #param i_msg (I) the message to display
*/
private void showInformationMessage(final String i_msg)
{
ErrorWarningMessages.showInformationMessage(i_msg, _title);
}
/**
* Sample of searching item to LUS.
* read the query.txt file that contains the item_id, item_rev_id and silent mode of the selected item
* The first line contains the number of assembly to LUS
* Then, for each assembly, we need 3 lines : item_id, item_rev_id and silent_mode
* example :
* 2
* 000010
* A
* true
* 000020
* B
* false
*/
protected int findItemToLUS()
{
String item_id = null;
String item_rev_id = null;
int return_value = 0;
int nb_assy = 0;
RandomAccessFile reader = null;
File file = null;
try
{
String file_path = "c:\\catiman_tmp\\tmp\\query.txt";
file = new File(file_path);
reader = new RandomAccessFile(file, "r");
nb_assy = Integer.valueOf(reader.readLine()).intValue();
is_silent = new boolean[nb_assy];
item = new TCComponentItem[nb_assy];
item_revision = new TCComponentItemRevision[nb_assy];
part_dataset = new TCComponentDataset[nb_assy];
product_dataset = new TCComponentDataset[nb_assy];
drawing_dataset = new TCComponentDataset[nb_assy];
other = new TCComponentForm[nb_assy];
bom_window = new TCComponentBOMWindow[nb_assy];
}
catch (Exception ex)
{
showErrorMessage("error 0 - " + ex);
return_value = -1;
}
for (int i = 0 ; i < (nb_assy) ; i++)
{
try
{
item_id = reader.readLine();
item_rev_id = reader.readLine();
is_silent[i] = Boolean.valueOf(reader.readLine()).booleanValue();
// search item name item_id
TCComponentItemType it = (TCComponentItemType)(session.getTypeComponent("Item"));
item[i] = it.find(item_id);
if (item[i] == null)
{
showErrorMessage("Error : item <" + item_id + ">not found");
return_value = -1;
}
else
{
// the item was found, search the correction item revision
AIFComponentContext[] revisions = item[i].getChildren();
TCComponentItemRevision revision_component = null;
for (int j = 0; j < revisions.length; j++)
{
InterfaceAIFComponent component = revisions[j].getComponent();
if (component instanceof TCComponentItemRevision)
{
revision_component = (TCComponentItemRevision) component;
if (revision_component.getProperty("item_revision_id").equals(item_rev_id))
{
item_revision[i] = revision_component;
break;
}
}
}
if (item_revision[i] == null)
{
showErrorMessage("Error : Item revision [" + item_rev_id + "] doesn't exist for item [" + item_id + "]");
return_value = -1;
}
else
{
// create the BOMWindow with the item revision previously found
TCComponentBOMWindowType type = (TCComponentBOMWindowType)session.getTypeComponent("BOMWindow");
TCComponentRevisionRuleType rule = (TCComponentRevisionRuleType)session.getTypeComponent("RevisionRule");
bom_window[i] = type.create(rule.getDefaultRule());
/* Define the BOMWindow top line */
TCComponentBOMLine top_line = bom_window[i].setWindowTopLine(item[i], item_revision[i], null, null);
}
}
}
catch (Exception ex)
{
showErrorMessage("error 1 - " + ex);
return_value = -1;
}
// search for a dataset (CATPart or CATProduct and/or CATDrawing)
try
{
int nb = item_revision[i].getChildrenCount();
if (nb > 0)
{
AIFComponentContext[] aif_comp_cont = item_revision[i].getChildren();
for (int j = 0 ; j < nb ; j++)
{
InterfaceAIFComponent int_aif_comp = aif_comp_cont[j].getComponent();
if (int_aif_comp.getType().equals("CATPart"))
{
part_dataset[i] = (TCComponentDataset)int_aif_comp;
}
else if (int_aif_comp.getType().equals("CATProduct"))
{
product_dataset[i] = (TCComponentDataset)int_aif_comp;
}
else if (int_aif_comp.getType().equals("CATDrawing"))
{
drawing_dataset[i] = (TCComponentDataset)int_aif_comp;
}
else if (int_aif_comp.getType().equals("ItemRevision Master"))
{
other[i] = (TCComponentForm)int_aif_comp;
}
}
}
}
catch (Exception ex)
{
showErrorMessage("error 2 - " + ex);
return_value = -1;
}
}
try
{
reader.close();
}
catch (Exception ex)
{
showErrorMessage("error 3 - " + ex);
}
return return_value;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Lets try this");
SampleIndependentSilentLUS test = new SampleIndependentSilentLUS();
//test.customerProcess();
}
}
There are two ways to get TCSession.
1) If you writing a Rich-Client Plugin
//numTry - number of attemts
private static TCSession getCurrentSession(int numTry) throws Exception {
try {
TCSession session = null;
ISessionService iss=null;
int numtry=numTry;
while (iss==null && numtry>0) {
iss = AifrcpPlugin.getSessionService();
numtry--;
}
session=(TCSession)iss.getSession("com.teamcenter.rac.kernel.TCSession");
return session;
}
catch (Exception ex) {
throw ex;
}
}
2) If you writing a stand-alone application, using SOA to work with Teamcenter API.
In this case, you need to connect teamcenter first. View "HelloTeamcenter" example in documentation for details.
did you get a solution for this?
SampleIndependentSilentLUS is a very good way of automating LUS process.but i prefer using the other class(SampleSilentLUS ) that can be called from command line because TCIC will automatically provide a TCSession
the session object you get from SOA(com.teamcenter.services.strong.core._2008_06.Session) is not compatible with RAC Session(com.teamcenter.rac.TCSession).
but if you use loose services(com.teamcenter.services.loose.core), i think you can simply typecast to TCSession
i want the below program to write the logs to a file ,its printing both errors and info but same needs to be captured into a file.can any one suggest the chnages .
i tried using buffer writer but dint succeed.
/**
* Tool to run database scripts
*/
/*BufferedWriter bw = null;
String path = "logs/sql.log";
try {
bw = new BufferedWriter(new FileWriter(new File(path)));
}*/
public class ScriptRunner {
private static final String DEFAULT_DELIMITER = ";";
private Connection connection;
private boolean stopOnError;
private boolean autoCommit;
private PrintWriter logWriter = new PrintWriter(System.out);
private PrintWriter errorLogWriter = new PrintWriter(System.err);
private String delimiter = DEFAULT_DELIMITER;
private boolean fullLineDelimiter = false;
private static final String DELIMITER_LINE_REGEX = "(?i)DELIMITER.+";
private static final String DELIMITER_LINE_SPLIT_REGEX = "(?i)DELIMITER";
/**
* Default constructor
*/
public ScriptRunner(Connection connection, boolean autoCommit,
boolean stopOnError) {
this.connection = connection;
this.autoCommit = autoCommit;
this.stopOnError = stopOnError;
}
public void setDelimiter(String delimiter, boolean fullLineDelimiter) {
this.delimiter = delimiter;
this.fullLineDelimiter = fullLineDelimiter;
}
/**
* Setter for logWriter property
*
* #param logWriter
* - the new value of the logWriter property
* #throws IOException
*/
public void setLogWriter(PrintWriter logWriter) throws IOException {
this.logWriter = logWriter;
}
/**
* Setter for errorLogWriter property
*
* #param errorLogWriter
* - the new value of the errorLogWriter property
*/
public void setErrorLogWriter(PrintWriter errorLogWriter) {
this.errorLogWriter = errorLogWriter;
}
/**
* Runs an SQL script (read in using the Reader parameter)
*
* #param reader
* - the source of the script
*/
public void runScript(Reader reader) throws IOException, SQLException {
try {
boolean originalAutoCommit = connection.getAutoCommit();
try {
if (originalAutoCommit != this.autoCommit) {
connection.setAutoCommit(this.autoCommit);
}
runScript(connection, reader);
} finally {
connection.setAutoCommit(originalAutoCommit);
}
} catch (IOException e) {
throw e;
} catch (SQLException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Error running script. Cause: " + e, e);
}
}
/**
* Runs an SQL script (read in using the Reader parameter) using the
* connection passed in
*
* #param conn
* - the connection to use for the script
* #param reader
* - the source of the script
* #throws SQLException
* if any SQL errors occur
* #throws IOException
* if there is an error reading from the Reader
*/
private void runScript(Connection conn, Reader reader) throws IOException,
SQLException {
StringBuffer command = null;
try {
LineNumberReader lineReader = new LineNumberReader(reader);
String line = null;
while ((line = lineReader.readLine()) != null) {
if (command == null) {
command = new StringBuffer();
}
String trimmedLine = line.trim();
if (trimmedLine.startsWith("--")) {
println(trimmedLine);
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("//")) {
// Do nothing
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("--")) {
// Do nothing
} else if (!fullLineDelimiter
&& trimmedLine.endsWith(getDelimiter())
|| fullLineDelimiter
&& trimmedLine.equals(getDelimiter())) {
Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX);
Matcher matcher = pattern.matcher(trimmedLine);
if (matcher.matches()) {
setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(), fullLineDelimiter);
line = lineReader.readLine();
if (line == null) {
break;
}
trimmedLine = line.trim();
}
command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
command.append(" ");
Statement statement = conn.createStatement();
println(command);
boolean hasResults = false;
if (stopOnError) {
hasResults = statement.execute(command.toString());
} else {
try {
statement.execute(command.toString());
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
}
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
ResultSet rs = statement.getResultSet();
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 0; i < cols; i++) {
String name = md.getColumnLabel(i);
print(name + "\t");
}
println("");
while (rs.next()) {
for (int i = 0; i < cols; i++) {
String value = rs.getString(i);
print(value + "\t");
}
println("");
}
}
command = null;
try {
statement.close();
} catch (Exception e) {
e.printStackTrace();
// Ignore to workaround a bug in Jakarta DBCP
}
Thread.yield();
} else {
Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX);
Matcher matcher = pattern.matcher(trimmedLine);
if (matcher.matches()) {
setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(), fullLineDelimiter);
line = lineReader.readLine();
if (line == null) {
break;
}
trimmedLine = line.trim();
}
command.append(line);
command.append(" ");
}
}
if (!autoCommit) {
conn.commit();
}
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} catch (IOException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} finally {
conn.rollback();
flush();
}
}
private String getDelimiter() {
return delimiter;
}
private void print(Object o) {
if (logWriter != null) {
System.out.print(o);
// bw.write("logs/sql.log");
// bw.flush();
}
}
private void println(Object o) {
if (logWriter != null) {
logWriter.println(o);
}
}
private void printlnError(Object o) {
if (errorLogWriter != null) {
errorLogWriter.println(o);
}
}
private void flush() {
if (logWriter != null) {
logWriter.flush();
}
if (errorLogWriter != null) {
errorLogWriter.flush();
}
}
}
Im able to connect with xmpp server and login authentication is done but when im sending roster the inputstream is.read() giving me -1 and thrown an exception i dont know what to do now.please help me out.
My XMppCOnnection class:
package mypackage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.io.ConnectionNotFoundException
import javax.microedition.io.SecureConnection;
import javax.microedition.io.StreamConnection;
import net.rim.device.api.io.File;
import net.rim.device.api.io.FileInputStream;
import net.rim.device.api.io.FileOutputStream;
public class XMPPConnection extends XMPPThread {
private XmlReader reader;
private XmlWriter writer;
private InputStream is;
private OutputStream os;
FileInputStream fis;
FileOutputStream fos;
File file;
/**
* If you create this object all variables will be saved and the
* method {#link #run()} is started to log in on jabber server and
* listen to parse incomming xml stanzas. Use
* {#link #addListener(XmppListener xl)} to listen to events of this object.
*/
// jid must in the form "username#host"
// to login Google Talk, set port to 5223 (NOT 5222 in their offical guide)
public XMPPConnection(Connection connection) {
super(connection);
this.host = connection.getHost();
this.port = connection.getPort();
this.username = connection.getUsername();
this.password = connection.getPassword();
this.resource = "mobile";
this.myjid = this.username + "#" + this.host;
if (connection.getServer() == null)
this.server = host;
else
this.server = connection.getServer();
this.use_ssl = connection.isSSL();
this.connectionMaskIndex = connection.getNetworkType();
}
/**
* The <code>run</code> method is called when {#link XMPPConnection} object is
* created. It sets up the reader and writer, calls {#link #login()}
* methode and listens on the reader to parse incomming xml stanzas.
*/
public void run() {
try {
this.connect();
} catch (final IOException e) {
e.printStackTrace();
this.connectionFailed(e.getMessage());
return;
} catch (Exception e) {
e.printStackTrace();
this.connectionFailed(e.getMessage());
return;
}
// connected
try {
boolean loginSuccess = this.login();
if (loginSuccess) {
this.parse();
}
} catch (final Exception e) {
// hier entsteht der connection failed bug (Network Down)
java.lang.System.out.println(e);
this.connectionFailed(e.toString());
}
}
protected void connect() throws IOException, Exception {
if (!use_ssl) {
//final StreamConnection connection = (StreamConnection) Connector.open("http://" + this.server + ":" + this.port+this.connectionMask, Connector.READ_WRITE);
ConnectionFactory connectionFactory = new ConnectionFactory("socket://" + this.server + ":" + this.port, this.connectionMaskIndex);
StreamConnection connection = null;
try {
connection = (StreamConnection) connectionFactory.getNextConnection();
} catch (NoMoreTransportsException e) {
throw new Exception("Connection failed. No transport available.");
} catch (ConnectionNotFoundException e) {
throw new Exception("ConnectionNotFoundException:" + e.getMessage());
} catch (IllegalArgumentException e) {
throw new Exception("IllegalArgumentException: " + e.getMessage());
} catch (IOException e) {
throw new Exception("IOException: " + e.getMessage());
}
is = connection.openInputStream();
os = connection.openOutputStream();
this.reader = new XmlReader(is);
this.writer = new XmlWriter(os);
} else {
//final SecureConnection sc = (SecureConnection) Connector.open("ssl://" + this.server + ":" + this.port+this.connectionMask, Connector.READ_WRITE);
ConnectionFactory connectionFactory = new ConnectionFactory("ssl://" + this.server + ":" + this.port, this.connectionMaskIndex);
SecureConnection sc = null;
try {
sc = (SecureConnection) connectionFactory.getNextConnection();
} catch (NoMoreTransportsException e) {
throw new Exception("Connection failed. No transport available.");
} catch (ConnectionNotFoundException e) {
throw new Exception("ConnectionNotFoundException: " + e.getMessage());
} catch (IllegalArgumentException e) {
throw new Exception("IllegalArgumentException: " + e.getMessage());
} catch (IOException e) {
throw new Exception("IOException: " + e.getMessage());
}
if (sc != null) {
//sc.setSocketOption(SocketConnection.DELAY, 1);
//sc.setSocketOption(SocketConnection.LINGER, 0);
is = sc.openInputStream();
os = sc.openOutputStream();
this.reader = new XmlReader(is);
this.writer = new XmlWriter(os);
}
}
}
/**
* Opens the connection with a stream-tag, queries authentication type and
* sends authentication data, which is username, password and resource.
* #return
* #throws Exception
*/
protected boolean login() throws Exception {
String msg = "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' to='" + this.host + "' version='1.0'>";
os.write(msg.getBytes());
os.flush();
do {
reader.next();
if (reader.getType() == XmlReader.START_TAG && reader.getName().equals("stream:features")) {
this.packetParser.parseFeatures(reader);
}
} while (!(reader.getType() == XmlReader.END_TAG && reader.getName().equals("stream:features")));
boolean loginSuccess = this.doAuthentication();
msg = "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' to='" + this.host + "' version='1.0'>";
os.write(msg.getBytes());
os.flush();
reader.next();
while (true) {
if ((reader.getType() == XmlReader.END_TAG) && reader.getName().equals("stream:features")) {
break;
}
reader.next();
}
if (resource == null) {
msg = "<iq type='set' id='res_binding'><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'/></iq>";
} else {
msg = "<iq type='set' id='res_binding'><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><resource>" + resource + "</resource></bind></iq>";
}
os.write(msg.getBytes());
os.flush();
return loginSuccess;
}
protected void parse() throws IOException {
while (true) {
int nextTag = this.reader.next();
switch (nextTag) {
case XmlReader.START_TAG:
final String tmp = this.reader.getName();
if (tmp.equals("message")) {
this.packetParser.parseMessage(this.reader);
} else if (tmp.equals("presence")) {
this.packetParser.parsePresence(this.reader);
} else if (tmp.equals("iq")) {
this.packetParser.parseIq(this.reader, this.writer);
} else {
this.packetParser.parseIgnore(this.reader);
}
break;
case XmlReader.END_TAG:
this.reader.close();
throw new IOException("Unexpected END_TAG "+this.reader.getName());
default:
this.reader.close();
throw new IOException("Bad XML tag");
}
}
}
protected boolean doAuthentication() throws Exception {
boolean loginSuccess = false;
Vector mechanismList = this.packetParser.getMechanism();
System.out.println(mechanismList.toString());
if (mechanismList.contains("X-GOOGLE-TOKEN")) {
// X-GOOGLE-TOKEN authorization doing. User can disable
// google features using by deselecting corresponding
// checkbox in profile
String resp = this.packetParser.getGoogleToken(this.myjid, this.password);
String msg = "<auth xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\" mechanism=\"X-GOOGLE-TOKEN\">" + resp + "</auth>";
os.write(msg.getBytes());
//os.flush();
reader.next();
if (reader.getName().equals("success")) {
loginSuccess = true;
while (true) {
if ((reader.getType() == XmlReader.END_TAG) && reader.getName().equals("success")) {
break;
}
reader.next();
}
}
}
if (mechanismList.contains("PLAIN") && loginSuccess == false) {
String msg = "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>";
byte[] auth_msg = (username + "#" + host + "\0" + username + "\0" + password).getBytes();
msg = msg + MD5.toBase64(auth_msg) + "</auth>";
os.write(msg.getBytes());
os.flush();
reader.next();
if (reader.getName().equals("success")) {
loginSuccess = true;
while (true) {
if ((reader.getType() == XmlReader.END_TAG) && reader.getName().equals("success")) {
break;
}
reader.next();
}
}
}
if (loginSuccess == false) {
for (Enumeration e = listeners.elements(); e.hasMoreElements();) {
XmppListener xl = (XmppListener) e.nextElement();
xl.onAuthFailed(reader.getName() + ", failed authentication");
}
return false;
}
return loginSuccess;
}
public void getRosterVCard(String tojid) throws IOException {
this.writer.startTag("iq");
this.writer.attribute("id", "vc2");
this.writer.attribute("to", tojid);
this.writer.attribute("type", "get");
this.writer.startTag("vCard");
this.writer.attribute("xmlns", "vcard-temp");
this.writer.endTag(); // vCard
this.writer.endTag(); // iq
this.writer.flush();
}
/**
* Sends a roster query.
*
* #throws java.io.IOException is thrown if {#link XmlReader} or {#link XmlWriter}
* throw an IOException.
*/
public void getRoster() throws IOException {
this.writer.startTag("iq");
// this.writer.attribute("id", "roster");
this.writer.attribute("type", "get");
this.writer.startTag("query");
this.writer.attribute("xmlns", "jabber:iq:roster");
this.writer.endTag(); // query
this.writer.endTag(); // iq
this.writer.flush();
//<iq id="qxmpp7" from="919700424402#213.204.83.20/QXmpp" type="get"><query xmlns="jabber:iq:roster"/></iq>
}
/**
* Sends a message text to a known jid.
*
* #param to the JID of the recipient
* #param msg the message itself
*/
public void sendMessage(final String to, final String msg, final String id) {
try {
this.writer.startTag("message");
this.writer.attribute("type", "chat");
this.writer.attribute("to", to);
this.writer.startTag("body");
this.writer.text(msg);
this.writer.endTag();
this.writer.endTag();
this.writer.flush();
} catch (final IOException e) {
java.lang.System.out.println(e);
this.connectionFailed();
}
}
/**
* Requesting a subscription.
*
* #param to the jid you want to subscribe
*/
public void subscribe(final String to) {
this.sendPresence(to, "subscribe", null, null, 0);
}
/**
* Remove a subscription.
*
* #param to the jid you want to remove your subscription
*/
public void unsubscribe(final String to) {
this.sendPresence(to, "unsubscribe", null, null, 0);
}
/**
* Approve a subscription request.
*
* #param to the jid that sent you a subscription request
*/
public void subscribed(final String to) {
this.sendPresence(to, "subscribed", null, null, 0);
}
/**
* Refuse/Reject a subscription request.
*
* #param to the jid that sent you a subscription request
*/
public void unsubscribed(final String to) {
this.sendPresence(to, "unsubscribed", null, null, 0);
}
/**
* Sets your Jabber Status.
*
* #param show is one of the following: <code>null</code>, chat, away,
* dnd, xa, invisible
* #param status an extended text describing the actual status
* #param priority the priority number (5 should be default)
*/
public void setStatus(String show, String status, final int priority) {
if (show.equals("")) {
show = null;
}
if (status.equals("")) {
status = null;
}
if (show.equals("invisible")) {
this.sendPresence(null, "invisible", null, null, priority);
} else {
this.sendPresence(null, null, show, status, priority);
}
}
/**
* Sends a presence stanza to a jid. This method can do various task but
* it's private, please use setStatus to set your status or explicit
* subscription methods subscribe, unsubscribe, subscribed and
* unsubscribed to change subscriptions.
*/
public void sendPresence(final String to, final String type, final String show, final String status, final int priority) {
try {
this.writer.startTag("presence");
if (type != null) {
this.writer.attribute("type", type);
}
if (to != null) {
this.writer.attribute("to", to);
}
if (show != null) {
this.writer.startTag("show");
this.writer.text(show);
this.writer.endTag();
}
if (status != null) {
this.writer.startTag("status");
this.writer.text(status);
this.writer.endTag();
}
if (priority != 0) {
this.writer.startTag("priority");
this.writer.text(Integer.toString(priority));
this.writer.endTag();
}
this.writer.endTag(); // presence
this.writer.flush();
} catch (final IOException e) {
java.lang.System.out.println(e);
this.connectionFailed();
}
}
/**
* Closes the stream-tag and the {#link XmlWriter}.
*/
public void logoff() {
try {
this.writer.endTag();
this.writer.flush();
this.writer.close();
} catch (final IOException e) {
java.lang.System.out.println(e);
this.connectionFailed();
}
}
/**
* Save a contact to roster. This means, a message is send to jabber
* server (which hosts your roster) to update the roster.
*
* #param jid the jid of the contact
* #param name the nickname of the contact
* #param group the group of the contact
* #param subscription the subscription of the contact
*/
public void saveContact(final String jid, final String name, final Enumeration group, final String subscription) {
try {
this.writer.startTag("iq");
this.writer.attribute("type", "set");
this.writer.startTag("query");
this.writer.attribute("xmlns", "jabber:iq:roster");
this.writer.startTag("item");
this.writer.attribute("jid", jid);
if (name != null) {
this.writer.attribute("name", name);
}
if (subscription != null) {
this.writer.attribute("subscription", subscription);
}
if (group != null) {
while (group.hasMoreElements()) {
this.writer.startTag("group");
this.writer.text((String) group.nextElement());
this.writer.endTag(); // group
}
}
this.writer.endTag(); // item
this.writer.endTag(); // query
this.writer.endTag(); // iq
this.writer.flush();
} catch (final IOException e) {
java.lang.System.out.println(e);
this.connectionFailed();
}
}
/**
* This method is used to be called on a parser or a connection error.
* It tries to close the XML-Reader and XML-Writer one last time.
*
*/
private void connectionFailed() {
if (this.writer != null)
this.writer.close();
if (this.reader != null)
this.reader.close();
for (Enumeration e = listeners.elements(); e.hasMoreElements();) {
XmppListener xl = (XmppListener) e.nextElement();
xl.onConnFailed("");
}
}
private void connectionFailed(final String msg) {
if (this.writer != null)
this.writer.close();
if (this.reader != null)
this.reader.close();
for (Enumeration e = listeners.elements(); e.hasMoreElements();) {
XmppListener xl = (XmppListener) e.nextElement();
xl.onConnFailed(msg);
}
}
};
xml reader looks like this:
public class XmlReader {
private InputStream is;
public final static int START_DOCUMENT = 0;
public final static int END_DOCUMENT = 1;
public final static int START_TAG = 2;
public final static int END_TAG = 3;
public final static int TEXT = 4;
//private Stack tags;
private boolean inside_tag;
private boolean left_angle;
private String tagName;
private String text;
private final Hashtable attributes = new Hashtable();
private int c;
private int type = START_DOCUMENT;
//public XmlReader(final InputStream in) throws IOException, UnsupportedEncodingException {
public XmlReader(final InputStream in) throws IOException {
//reader = new InputStreamReader(in, "UTF-8");
this.is = in;
//this.tags = new Stack();
this.inside_tag = false;
this.left_angle = false;
}
//http://discussion.forum.nokia.com/forum/showthread.php?t=76814
//by abirr
private int getNextCharacter() throws IOException {
int a = is.read();
int t=a;
if((t|0xC0)==t){
int b = is.read();
if( b == 0xFF ){ // Check if legal
t=-1;
}else if( b < 0x80 ){ // Check for UTF8 compliancy
throw new IOException("Bad UTF-8 Encoding encountered");
}else if((t|0xE0)==t) {
int c = is.read();
if( c == 0xFF ){ // Check if legal
t=-1;
}else if( c < 0x80 ){ // Check for UTF8 compliancy
throw new IOException("Bad UTF-8 Encoding encountered");
}else
t=((a & 0x0F)<<12) | ((b & 0x3F)<<6) | (c & 0x3F);
}else
t=((a & 0x1F)<<6)|(b&0x3F);
}
return a;
}
public void close() {
if (is != null) {
try {
is.close();
is = null;
} catch (IOException e) {
e.printStackTrace();
}
/*try {
reader.close();
} catch (IOException e) {}*/
}
}
public int next() throws IOException {
/* while (!this.ready())
try {
java.lang.Thread.sleep(100);
} catch (InterruptedException e) {}*/
this.c = getNextCharacter();
if (this.c <= ' ') {
while (((this.c = getNextCharacter()) <= ' ') && (this.c != -1)) {
;
}
}
if (this.c == -1) {
this.type = END_DOCUMENT;
return this.type;
}
if (this.left_angle || (this.c == '<')) {
this.inside_tag = true;
// reset all
this.tagName = null;
this.text = null;
this.attributes.clear();
if (this.c == '<') {
this.left_angle = true;
this.c = getNextCharacter();
}
if (this.left_angle && this.c == '/') {
this.left_angle = false;
this.type = END_TAG;
this.c = getNextCharacter();
this.tagName = this.readName('>');
} else if (this.left_angle && ((this.c == '?') || (this.c == '!'))) {// ignore xml heading & // comments
this.left_angle = false;
while ((this.c = getNextCharacter()) != '>') {
;
}
this.next();
} else {
this.left_angle = false;
this.type = START_TAG;
this.tagName = this.readName(' ');
String attribute = "";
String value = "";
while (this.c == ' ') {
/*this.c = getNextCharacter();
attribute = this.readName('=');
int quote = getNextCharacter();//this.c = this.read(); // '''
BTalk.debugConsole.addDebugMsg("quote: " + quote);
this.c = getNextCharacter();
value = this.readText(quote); //change from value = this.readText(''');
this.c = getNextCharacter();
this.attributes.put(attribute, value);
BTalk.debugConsole.addDebugMsg("attributes: " + attributes);*/
this.c = getNextCharacter();
attribute = this.readName('=').trim();
int quote = getNextCharacter();//this.c = this.read(); // '''
if (quote == 32) {
while (quote == 32) {
quote = getNextCharacter();//this.c = this.read(); // '''
}
this.c = getNextCharacter();
value = this.readText(quote); //change from value = this.readText(''');
this.c = getNextCharacter();
this.attributes.put(attribute, value);
} else {
this.c = getNextCharacter();
value = this.readText(quote); //change from value = this.readText(''');
this.c = getNextCharacter();
this.attributes.put(attribute, value);
}
}
if (this.c != '/') {
this.inside_tag = false;
}
}
} else if ((this.c == '>') && this.inside_tag) // last tag ended
{
this.type = END_TAG;
this.inside_tag = false;
} else {
this.tagName = null;
this.attributes.clear();
this.type = TEXT;
this.text = this.readText('<');
// fix the < dismatching problem
this.left_angle = true;
}
return this.type;
}
// NOTICE: this is only for debug use
public void parseHtml() throws IOException {
while (true) {
char c;
c = (char) this.getNextCharacter();
System.out.print(c);
}
}
public int getType() {
return this.type;
}
public String getName() {
return this.tagName;
}
public String getAttribute(final String name) {
return (String) this.attributes.get(name);
}
public Enumeration getAttributes() {
return this.attributes.keys();
}
public String getText() {
return this.text;
}
private String readText(final int end) throws IOException {
final StringBuffer output = new StringBuffer("");
while (this.c != end) {
if (this.c == '&') {
this.c = getNextCharacter();
switch (this.c) {
case 'l':
output.append('<');
break;
case 'g':
output.append('>');
break;
case 'a':
if (getNextCharacter() == 'm') {
output.append('&');
} else {
output.append('\'');
}
break;
case 'q':
output.append('"');
break;
case 'n':
output.append(' ');
break;
default:
output.append('?');
}
while ((this.c = getNextCharacter()) != ';') {
;
}
// NOTICE: Comment out these mystical codes
// } else if (this.c == '\\') {
// // NOTICE: What this means?
// if ((this.c = getNextCharacter()) == '<') {
// output.append('\\');
// break;
// } else {
// output.append((char) this.c);
// }
} else {
output.append((char) this.c);
}
this.c = getNextCharacter();
}
// while((c = read()) != end);
System.out.println(output.toString()+"");
return output.toString();
}
private String readName(final int end) throws IOException {
final StringBuffer output = new StringBuffer("");
do {
output.append((char) this.c);
} while (((this.c = getNextCharacter()) != end) && (this.c != '>') && (this.c != '/'));
return output.toString();
}
};
the problem is with session we need to create session before roster
String msg = "<iq type=\"set\" id=\"session_1\"><session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/></iq>";
try {
os.write(msg.getBytes());
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
reader.next();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (reader.getName().equals("iq")) {
while (true) {
if((reader.getType() == XmlReader.END_TAG) && reader.getName().equals("iq"))
{
session=true;
break;
}
try {
reader.next();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//
now the problem is solved.thank you
For multiple image retrieval I am calling a PhotoHelperServlet with an anchor tag to get imageNames(multiple images) as follows
PhotoHelperServlet to get names of Images
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Getting userid from session
Image image = new Image();
image.setUserid(userid);
ImageDAO imageDAO = new ImageDAO();
try {
List<Image> imageId = imageDAO.listNames(image);
if (imageId == null) {
// check if imageId is retreived
}
request.setAttribute("imageId", imageId);
//Redirect it to home page
RequestDispatcher rd = request.getRequestDispatcher("/webplugin/jsp/profile/photos.jsp");
rd.forward(request, response);
catch (Exception e) {
e.printStackTrace();
}
In ImageDAO listNames() method :
public List<Image> listNames(Image image) throws IllegalArgumentException, SQLException, ClassNotFoundException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultset = null;
Database database = new Database();
List<Image> imageId = new ArrayList<Image>();
try {
connection = database.openConnection();
preparedStatement = connection.prepareStatement(SQL_GET_PHOTOID);
preparedStatement.setLong(1, image.getUserid());
resultset = preparedStatement.executeQuery();
while(resultset.next()) {
image.setPhotoid(resultset.getLong(1));
imageId.add(image);
}
} catch (SQLException e) {
throw new SQLException(e);
} finally {
close(connection, preparedStatement, resultset);
}
return imageId;
}
In JSP code:
<c:forEach items="${imageId}" var="imageid">
<img src="Photos/${imageid}">
</c:forEach>
In PhotoServlet doGet() method to get a photo:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String imageid = request.getPathInfo().substring(1);
if(imageid == null) {
// check for null and response.senderror
}
ImageDAO imageDAO = new ImageDAO();
try {
Image image = imageDAO.getPhotos(imageid);
if(image == null) {}
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(image.getPhoto(), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}
} catch(Exception e) {
e.printStackTrace();
}
In ImageDAO getPhotos() method
public Image getPhotos(String imageid) throws IllegalArgumentException, SQLException, ClassNotFoundException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultset = null;
Database database = new Database();
Image image = new Image();
try {
connection = database.openConnection();
preparedStatement = connection.prepareStatement(SQL_GET_PHOTO);
preparedStatement.setString(1, imageid);
resultset = preparedStatement.executeQuery();
while(resultset.next()) {
image.setPhoto(resultset.getBinaryStream(1));
}
} catch (SQLException e) {
throw new SQLException(e);
} finally {
close(connection, preparedStatement, resultset);
}
return image;
}
In web.xml
<!-- Getting each photo -->
<servlet>
<servlet-name>Photos Module</servlet-name>
<servlet-class>app.controllers.PhotoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Photos Module</servlet-name>
<url-pattern>/Photos/*</url-pattern>
</servlet-mapping>
<!-- Getting photo names -->
<servlet>
<servlet-name>Photo Module</servlet-name>
<servlet-class>app.controllers.PhotoHelperServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Photo Module</servlet-name>
<url-pattern>/Photo</url-pattern>
</servlet-mapping>
Question:
I am getting following Exception:
java.io.IOException: Stream closed
on this Line:
at app.controllers.PhotoServlet.doGet(PhotoServlet.java:94)
while ((length = input.read(buffer)) > 0) {
The full Exception:
java.io.IOException: Stream closed
at java.io.BufferedInputStream.getInIfOpen(BufferedInputStream.java:134)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:256)
at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
at java.io.FilterInputStream.read(FilterInputStream.java:90)
at app.controllers.PhotoServlet.doGet(PhotoServlet.java:94)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
I'd imagine that the basic code flow is laid out like follows:
try {
Get connection, statement, resultset
Use connection, statement, resultset
Get inputstream of resultset
} finally {
Close resultset, statement, connection
}
try {
Get outputstream
Use inputstream of resultset, outputstream
} finally {
Close outputstream, inputstream of resultset
}
And that the close of the ResultSet has implicitly closed the InputStream. It look like that your JDBC driver does not store the InputStream of the ResultSet fully in memory or on temp storage when the ResultSet is closed. Perhaps the JDBC driver is a bit simplistic, or not well thought designed, or the image is too large to be stored in memory. Who knows.
I'd first figure out what JDBC driver impl/version you're using and then consult its developer documentation to learn about settings which may be able to change/fix this behaviour. If you still can't figure it out, then you'd have to rearrange the basic code flow as follows:
try {
Get connection, statement, resultset
Use connection, statement, resultset
try {
Get inputstream of resultset, outputstream
Use inputstream of resultset, outputstream
} finally {
Close outputstream, inputstream of resultset
}
} finally {
Close resultset, statement, connection
}
Or
try {
Get connection, statement, resultset
Use connection, statement, resultset
Get inputstream of resultset
Copy inputstream of resultset
} finally {
Close resultset, statement, connection
}
try {
Get outputstream
Use copy of inputstream, outputstream
} finally {
Close outputstream, copy of inputstream
}
The first approach is the most efficient, only the code is clumsy. The second approach is memory inefficient when you're copying to ByteArrayOutputStream, or performance inefficient when you're copying to FileOutputStream. If the images are mostly small and do not exceed a megabyte or something, then I'd just copy it to ByteArrayOutputStream.
InputStream input = null;
OutputStream output = null;
try {
input = new BufferedInputStream(resultSet.getBinaryStream("columnName"), DEFAULT_BUFFER_SIZE);
output = new ByteArrayOutputStream();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
for (int length; ((length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
} finally {
if (output != null) try { output.close(); } catch (IOException ignore) {}
if (input != null) try { input.close(); } catch (IOException ignore) {}
}
Image image = new Image();
image.setPhoto(new ByteArrayInputStream(output.toByteArray()));
// ...
参考一下:
ImageLoad
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
/**
* 图片加载帮助类(自动异步加载、图片文件缓存、缓存文件管理)
*
* #author n.zhang
*
*/
public class ImageLoad {
private static final String TAG = "imageLoad";// 日志标签
private static final String TAG_REF = TAG + "Ref";
private Executor executor; // 线程池
private int defaultImageID;// 默认图片id
private Context context;// 你懂的
private HashMap<String, PathInfo> cache = new HashMap<String, PathInfo>();// URL
boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 路径信息对应表
private LinkedList<PathInfo> use = new LinkedList<PathInfo>();// 已在使用的路径信息队列
private LinkedList<PathInfo> lost = new LinkedList<PathInfo>();// 还未使用的路径信息队列
private LinkedList<PathInfo> original = new LinkedList<PathInfo>();// 初始图片路径信息队列
private int index = 0;// id下标
/**
* 图片加载工具,默认10线程下载,缓存80张图片
*
* #param context
*/
public ImageLoad(Context context) {
this(context, 10, 80, 0);
}
/**
* 图片加载工具
*
* #param context
* 你懂的
* #param threadSize
* 最大线程数
* #param maxCacheSize
* 最大缓存图片数量
* #param defaultImageID
* 默认图片id
*/
public ImageLoad(Context context, int threadSize, int maxCacheSize, int defaultImageID) {
this.context = context;
this.defaultImageID = defaultImageID;
executor = Executors.newFixedThreadPool(threadSize);
loadImagePathInfo();
// 图片信息数量不足不满最大值,以空白图片信息补足。
newImagePathInfo(maxCacheSize);
for (PathInfo pi : original) {
if (null == pi.url) {
lost.offer(pi);
} else {
use.offer(pi);
cache.put(pi.url, pi);
}
}
File dir = null;
if (sdCardExist) {
dir = new File(Environment.getExternalStorageDirectory() + "/t_image/");
} else {
dir = new File(context.getCacheDir() + "/t_image/");
}
// 如果文件存在并且不是目录,则删除
if (dir.exists() && !dir.isDirectory()) {
dir.delete();
}
// 如果目录不存在,则创建
if (!dir.exists()) {
dir.mkdir();
}
}
/**
* 路径信息
*
* #author n.zhang
*
*/
public static class PathInfo {
private int id;// 图片id 此id用于生成存储图片的文件名。
private String url;// 图片url
}
/**
* 获得图片存储路径
*
* #param url
* #return
*/
public PathInfo getPath(String url) {
PathInfo pc = cache.get(url);
if (null == pc) {
pc = lost.poll();
}
if (null == pc) {
pc = use.poll();
refresh(pc);
}
return pc;
}
/**
* #info 微博使用加载数据路径
* #author FFMobile-cuihe
* #date 2012-3-1 下午2:13:10
* #Title: getsPath
* #Description: TODO
* #param#param url
* #param#return 设定文件
* #return PathInfo 返回类型
* #throws
*/
public PathInfo getsPath(String url) {
PathInfo pc = cache.get(url);
if (null == pc) {
pc = lost.peek();
}
// if (null == pc) {
// pc = use.peek();
// refresh(pc);
// }
return pc;
}
public PathInfo getLocalPath(String url) {
PathInfo pc = cache.get(url);
if (null == pc) {
pc = lost.peek();
}
return pc;
}
/**
* 刷新路径信息(从索引中删除对应关系、删除对应的图片文件、获取一个新id)
*
* #param pc
*/
private void refresh(PathInfo pc) {
long start = System.currentTimeMillis();
File logFile = null;
try {
cache.remove(pc.url);
File file = toFile(pc);
file.delete();
logFile = file;
pc.id = index++;
pc.url = null;
} finally {
Log.d(TAG_REF, "ref time {" + (System.currentTimeMillis() - start) + "}; ref {" + logFile + "}");
}
}
/**
* 获得file对象
*
* #param pi
* 路径缓存
* #return
*/
public File toFile(PathInfo pi) {
if (sdCardExist) {
return new File(Environment.getExternalStorageDirectory() + "/t_image/" + pi.id + ".jpg");
} else {
return new File(context.getCacheDir() + "/t_image/" + pi.id + ".jpg");
}
}
/**
* 请求加载图片
*
* #param url
* #param ilCallback
*/
public void request(String url, final ILCallback ilCallback) {
final long start = System.currentTimeMillis();
final PathInfo pc = getPath(url);
File file = toFile(pc);
if (null != pc.url) {
ilCallback.seed(Uri.fromFile(file));
Log.d(TAG, "load time {" + (System.currentTimeMillis() - start) + "}; cache {" + pc.url + "} ");
} else {
pc.url = url;
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (null == msg.obj) {
ilCallback.seed(Uri.EMPTY);
Log.d(TAG, "load lost time {" + (System.currentTimeMillis() - start) + "}; network lost {"
+ pc.url + "}");
} else {
ilCallback.seed((Uri) msg.obj);
Log.d(TAG, "load time {" + (System.currentTimeMillis() - start) + "}; network {" + pc.url + "}");
}
};
};
executor.execute(new DownloadImageTask(pc, file, mHandler));
}
}
private void localRequest(String url, final ILCallback ilCallback) {
final long start = System.currentTimeMillis();
final PathInfo pc = getLocalPath(url);
File file = toFile(pc);
if (null != pc.url) {
ilCallback.seed(Uri.fromFile(file));
Log.d(TAG, "load time {" + (System.currentTimeMillis() - start) + "}; cache {" + pc.url + "} ");
}
}
public void localRequest(String url, ImageView iv) {
localRequest(url, new ImageViewCallback(iv));
}
/**
* 请求加载图片
*
* #param url
* #param iv
*/
public void request(String url, ImageView iv) {
request(url, new ImageViewCallback(iv));
}
/**
* 请求加载图片
*
* #param url
* #param iv
*/
// public void request(String url, ImageButton iv) {
// request(url, new ImageButtonCallbacks(iv));
// }
/**
* 请求加载图片
*
* #param url
* #param iv
*/
// public void request(String url, Button iv) {
// request(url, new ButtonCallbacks(iv));
// }
/**
* 请求加载图片
*
* #param url
* #param iv
*/
public void request(String url, ImageSwitcher iv) {
request(url, new ImageSwitcherCallbacks(iv));
}
/**
* 下载图片任务
*
* #author Administrator
*
*/
private class DownloadImageTask implements Runnable {
private Handler hc;
private PathInfo pi;
private File file;
public DownloadImageTask(PathInfo pi, File file, Handler hc) {
this.pi = pi;
this.file = file;
this.hc = hc;
}
public void run() {
try {
byte[] b = requestHttp(pi.url);
if (null == b) {
throw new IOException("数据为空");
}
writeFile(file, b);
use.offer(pi);
cache.put(pi.url, pi);
Message message = new Message();
message.obj = Uri.fromFile(file);
hc.sendMessage(message);
} catch (IOException e) {
Message message = hc.obtainMessage(0, Uri.EMPTY);
hc.sendMessage(message);
Log.i(TAG, "image download lost.", e);
} catch (RuntimeException e) {
Message message = hc.obtainMessage(0, Uri.EMPTY);
hc.sendMessage(message);
Log.i(TAG, "image download lost.", e);
}
}
}
private void writeFile(File file, byte[] data) throws IOException {
FileOutputStream out = new FileOutputStream(file);
try {
out.write(data);
} finally {
out.close();
}
}
private static byte[] requestHttp(String url) throws IOException {
DefaultHttpClient client = new DefaultHttpClient();
System.gc();
try {
HttpGet get = new HttpGet(url);
HttpResponse res = client.execute(get);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (200 == res.getStatusLine().getStatusCode()) {
res.getEntity().writeTo(baos);
return baos.toByteArray();
} else {
throw new IOException("httpStatusCode:" + res.getStatusLine().getStatusCode());
}
} finally {
client.getConnectionManager().shutdown();
}
}
/**
* 读取图片路径信息
*
* #return
*/
#SuppressWarnings("unchecked")
private void loadImagePathInfo() {
long start = System.currentTimeMillis();
File file = new File(context.getCacheDir() + "/imagePathCache.json");
try {
if (!file.isFile()) {
// 文件不存在。
Log.d(TAG, "path info file does not exist");
imageGc();
return;
}
StringWriter sw = new StringWriter();
char[] buf = new char[1024];
int len;
FileReader fr = new FileReader(file);
while (-1 != (len = fr.read(buf))) {
sw.write(buf, 0, len);
}
fr.close();
JSONObject json = new JSONObject(sw.toString());
Iterator<String> it = json.keys();
while (it.hasNext()) {
String key = it.next();
int id = json.getInt(key);
PathInfo pi = new PathInfo();
pi.url = key;
pi.id = id;
if (index < id) {
index = id;
}
original.add(pi);
}
// 打开文件文件缓存成功
Log.i(TAG, "load path info ok.");
} catch (IOException e) {
Log.i(TAG, "load path info lost - IOException.", e);
imageGc();
} catch (JSONException e) {
Log.i(TAG, "load path info lost - JSONException.", e);
imageGc();
} finally {
if (file.exists()) {
file.delete();
Log.d(TAG, "delete path info file");
}
Log.d(TAG, "load path info time {" + (System.currentTimeMillis() - start) + "}");
}
}
/**
* 如果路径信息加载失败,清理图片目录。
*/
private void imageGc() {
long start = System.currentTimeMillis();
try {
File dir;
if (sdCardExist) {
dir = new File(Environment.getExternalStorageDirectory() + "/t_image/");
} else {
dir = new File(context.getCacheDir() + "/t_image/");
}
if (dir.isDirectory()) {
for (File file : dir.listFiles()) {
file.delete();
// gc
Log.d(TAG_REF, "gc {" + file + "}");
}
}
} finally {
// gc 计时
Log.d(TAG_REF, "gc time {" + (System.currentTimeMillis() - start) + "}");
}
}
private void newImagePathInfo(int max_size) {
for (int i = original.size(); i < max_size; i++) {
PathInfo pc = new PathInfo();
pc.id = index++;
original.add(pc);
}
}
/**
* 保存图片路径信息(如记录,下次程序打开,可读取该记录已存图片继续可用)
*/
public void saveImagePathInfo() {
long start = System.currentTimeMillis();
try {
JSONObject json = new JSONObject();
for (PathInfo pi : use) {
try {
json.put(pi.url, pi.id);
} catch (JSONException e) {
e.printStackTrace();
}
}
File file = new File(context.getCacheDir() + "/imagePathCache.json");
try {
FileWriter fw = new FileWriter(file);
fw.write(json.toString());
fw.close();
Log.i(TAG, "image file info save ok.");
} catch (IOException e) {
e.printStackTrace();
Log.i(TAG, "image file info save lost.");
file.delete();
}
} finally {
Log.d(TAG, "save time {" + (System.currentTimeMillis() - start) + "}");
}
}
/**
* 图片加载回调
*
* #author n.zhang
*
*/
public static interface ILCallback {
public void seed(Uri uri);
}
private class ImageViewCallback implements ILCallback {
public ImageViewCallback(ImageView iv) {
if (defaultImageID > 0) {
iv.setImageResource(defaultImageID);
}
this.iv = iv;
}
private ImageView iv;
public void seed(Uri uri) {
File f = new File(uri.getPath());
iv.setImageURI(Uri.parse(f.toString()));
f = null;
}
}
// private class ImageButtonCallbacks implements ILCallback {
// public ImageButtonCallbacks(ImageButton iv) {
// if (defaultImageID > 0) {
// iv.setBackgroundResource(defaultImageID);
////iv.setImageResource(defaultImageID);
// }
// this.iv = iv;
// }
//
// private ImageButton iv;
//
// public void seed(Uri uri) {
// iv.setImageURI(uri);
// }
// }
// private class ButtonCallbacks implements ILCallback {
// public ButtonCallbacks(Button iv) {
// if (defaultImageID > 0) {
// iv.setBackgroundResource(defaultImageID);
////iv.setImageResource(defaultImageID);
// }
// this.iv = iv;
// }
//
// private Button iv;
//
// public void seed(Uri uri) {
// iv.setImageURI(uri);
// }
// }
private class ImageSwitcherCallbacks implements ILCallback {
public ImageSwitcherCallbacks(ImageSwitcher iv) {
if (defaultImageID > 0) {
iv.setImageResource(defaultImageID);
}
this.iv = iv;
}
private ImageSwitcher iv;
public void seed(Uri uri) {
iv.setImageURI(uri);
}
}
}
It looks as if the problem is actually not in the code you posted. For some reason the stream input is closed. So you are probably closing the stream in image.getPhoto()
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Running a .sql script using MySQL with JDBC
I have an SQL script file which contains 40-50 SQL statements. Is it possible to run this script file using JDBC?
This link might help you out: http://pastebin.com/f10584951.
Pasted below for posterity:
/*
* Slightly modified version of the com.ibatis.common.jdbc.ScriptRunner class
* from the iBATIS Apache project. Only removed dependency on Resource class
* and a constructor
*/
/*
* Copyright 2004 Clinton Begin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.sql.*;
/**
* Tool to run database scripts
*/
public class ScriptRunner {
private static final String DEFAULT_DELIMITER = ";";
private Connection connection;
private boolean stopOnError;
private boolean autoCommit;
private PrintWriter logWriter = new PrintWriter(System.out);
private PrintWriter errorLogWriter = new PrintWriter(System.err);
private String delimiter = DEFAULT_DELIMITER;
private boolean fullLineDelimiter = false;
/**
* Default constructor
*/
public ScriptRunner(Connection connection, boolean autoCommit,
boolean stopOnError) {
this.connection = connection;
this.autoCommit = autoCommit;
this.stopOnError = stopOnError;
}
public void setDelimiter(String delimiter, boolean fullLineDelimiter) {
this.delimiter = delimiter;
this.fullLineDelimiter = fullLineDelimiter;
}
/**
* Setter for logWriter property
*
* #param logWriter
* - the new value of the logWriter property
*/
public void setLogWriter(PrintWriter logWriter) {
this.logWriter = logWriter;
}
/**
* Setter for errorLogWriter property
*
* #param errorLogWriter
* - the new value of the errorLogWriter property
*/
public void setErrorLogWriter(PrintWriter errorLogWriter) {
this.errorLogWriter = errorLogWriter;
}
/**
* Runs an SQL script (read in using the Reader parameter)
*
* #param reader
* - the source of the script
*/
public void runScript(Reader reader) throws IOException, SQLException {
try {
boolean originalAutoCommit = connection.getAutoCommit();
try {
if (originalAutoCommit != this.autoCommit) {
connection.setAutoCommit(this.autoCommit);
}
runScript(connection, reader);
} finally {
connection.setAutoCommit(originalAutoCommit);
}
} catch (IOException e) {
throw e;
} catch (SQLException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Error running script. Cause: " + e, e);
}
}
/**
* Runs an SQL script (read in using the Reader parameter) using the
* connection passed in
*
* #param conn
* - the connection to use for the script
* #param reader
* - the source of the script
* #throws SQLException
* if any SQL errors occur
* #throws IOException
* if there is an error reading from the Reader
*/
private void runScript(Connection conn, Reader reader) throws IOException,
SQLException {
StringBuffer command = null;
try {
LineNumberReader lineReader = new LineNumberReader(reader);
String line = null;
while ((line = lineReader.readLine()) != null) {
if (command == null) {
command = new StringBuffer();
}
String trimmedLine = line.trim();
if (trimmedLine.startsWith("--")) {
println(trimmedLine);
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("//")) {
// Do nothing
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("--")) {
// Do nothing
} else if (!fullLineDelimiter
&& trimmedLine.endsWith(getDelimiter())
|| fullLineDelimiter
&& trimmedLine.equals(getDelimiter())) {
command.append(line.substring(0, line
.lastIndexOf(getDelimiter())));
command.append(" ");
Statement statement = conn.createStatement();
println(command);
boolean hasResults = false;
if (stopOnError) {
hasResults = statement.execute(command.toString());
} else {
try {
statement.execute(command.toString());
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
}
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
ResultSet rs = statement.getResultSet();
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 0; i < cols; i++) {
String name = md.getColumnLabel(i);
print(name + "\t");
}
println("");
while (rs.next()) {
for (int i = 0; i < cols; i++) {
String value = rs.getString(i);
print(value + "\t");
}
println("");
}
}
command = null;
try {
statement.close();
} catch (Exception e) {
// Ignore to workaround a bug in Jakarta DBCP
}
Thread.yield();
} else {
command.append(line);
command.append(" ");
}
}
if (!autoCommit) {
conn.commit();
}
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} catch (IOException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} finally {
conn.rollback();
flush();
}
}
private String getDelimiter() {
return delimiter;
}
private void print(Object o) {
if (logWriter != null) {
System.out.print(o);
}
}
private void println(Object o) {
if (logWriter != null) {
logWriter.println(o);
}
}
private void printlnError(Object o) {
if (errorLogWriter != null) {
errorLogWriter.println(o);
}
}
private void flush() {
if (logWriter != null) {
logWriter.flush();
}
if (errorLogWriter != null) {
errorLogWriter.flush();
}
}
}
I use this bit of code to import sql statements created by mysqldump:
public static void importSQL(Connection conn, InputStream in) throws SQLException
{
Scanner s = new Scanner(in);
s.useDelimiter("(;(\r)?\n)|(--\n)");
Statement st = null;
try
{
st = conn.createStatement();
while (s.hasNext())
{
String line = s.next();
if (line.startsWith("/*!") && line.endsWith("*/"))
{
int i = line.indexOf(' ');
line = line.substring(i + 1, line.length() - " */".length());
}
if (line.trim().length() > 0)
{
st.execute(line);
}
}
}
finally
{
if (st != null) st.close();
}
}
Another option, this DOESN'T support comments, very useful with AmaterasERD DDL export for Apache Derby:
public void executeSqlScript(Connection conn, File inputFile) {
// Delimiter
String delimiter = ";";
// Create scanner
Scanner scanner;
try {
scanner = new Scanner(inputFile).useDelimiter(delimiter);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return;
}
// Loop through the SQL file statements
Statement currentStatement = null;
while(scanner.hasNext()) {
// Get statement
String rawStatement = scanner.next() + delimiter;
try {
// Execute statement
currentStatement = conn.createStatement();
currentStatement.execute(rawStatement);
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Release resources
if (currentStatement != null) {
try {
currentStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
currentStatement = null;
}
}
scanner.close();
}
Just read it and then use the preparedstatement with the full sql-file in it.
(If I remember good)
ADD: You can also read and split on ";" and than execute them all in a loop.
Do not forget the comments and add again the ";"
You should be able to parse the SQL file into statements. And run a single statement a time. If you know that your file consists of simple insert/update/delete statements you can use a semicolon as statement delimiter. In common case you have a task to create your specific SQL-dialect parser.
I had the same problem trying to execute an SQL script that creates an SQL database. Googling here and there I found a Java class initially written by Clinton Begin which supports comments (see http://pastebin.com/P14HsYAG). I modified slightly the file to cater for triggers where one has to change the default DELIMITER to something different. I've used that version ScriptRunner (see http://pastebin.com/sb4bMbVv). Since an (open source and free) SQLScriptRunner class is an absolutely necessary utility, it would be good to have some more input from developers and hopefully we'll have soon a more stable version of it.
You can read the script line per line with a BufferedReader and append every line to a StringBuilder so that the script becomes one large string.
Then you can create a Statement object using JDBC and call statement.execute(stringBuilder.toString()).