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
Related
when using a solution provided in the below post : Browse, read, and remove a message from a queue using IBM MQ classes
i am getting below error
Caused by: com.ibm.mq.jmqi.JmqiException: CC=2;RC=2495;AMQ8568: The native JNI library 'mqjbnd64' was not found. For a client installation this is expected. [3=mqjbnd64]
I am new to IBM MQ , but i think it is trying to fing MQ library on my local machine but i want to connect on remote server as MQ is not installed on my machine
Here is a Java/MQ program that will connect to either (1) a remote queue manager (client mode) or (2) local queue manager (bindings mode), open queue, loop to retrieve all messages from a queue then close and disconnect.
import java.io.EOFException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import com.ibm.mq.MQException;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import com.ibm.mq.constants.CMQC;
/**
* Program Name
* MQTest12L
*
* Description
* This java class will connect to a remote queue manager with the
* MQ setting stored in a HashTable, loop to retrieve all messages from a queue
* then close and disconnect.
*
* Sample Command Line Parameters
* bindings mode
* -m MQA1 -q TEST.Q1
* client mode
* -m MQA1 -q TEST.Q1 -h 127.0.0.1 -p 1414 -c TEST.CHL -u UserID -x Password
*
* #author Roger Lacroix
*/
public class MQTest12L
{
private static final SimpleDateFormat LOGGER_TIMESTAMP = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
private Hashtable<String,String> params;
private Hashtable<String,Object> mqht;
/**
* The constructor
*/
public MQTest12L()
{
super();
params = new Hashtable<String,String>();
mqht = new Hashtable<String,Object>();
}
/**
* Make sure the required parameters are present.
* #return true/false
*/
private boolean allParamsPresent()
{
boolean b = params.containsKey("-m") && params.containsKey("-q");
if (params.containsKey("-c"))
{
b = b && params.containsKey("-c") && params.containsKey("-h") && params.containsKey("-p");
}
if (b)
{
try
{
if (params.containsKey("-p"))
Integer.parseInt((String) params.get("-p"));
}
catch (NumberFormatException e)
{
b = false;
}
}
return b;
}
/**
* Extract the command-line parameters and initialize the MQ HashTable.
* #param args
* #throws IllegalArgumentException
*/
private void init(String[] args) throws IllegalArgumentException
{
int port = 1414;
if (args.length > 0 && (args.length % 2) == 0)
{
for (int i = 0; i < args.length; i += 2)
{
params.put(args[i], args[i + 1]);
}
}
else
{
throw new IllegalArgumentException();
}
if (allParamsPresent())
{
if (params.containsKey("-c"))
{
try
{
port = Integer.parseInt((String) params.get("-p"));
}
catch (NumberFormatException e)
{
port = 1414;
}
mqht.put(CMQC.CHANNEL_PROPERTY, params.get("-c"));
mqht.put(CMQC.HOST_NAME_PROPERTY, params.get("-h"));
mqht.put(CMQC.PORT_PROPERTY, new Integer(port));
if (params.containsKey("-u"))
mqht.put(CMQC.USER_ID_PROPERTY, params.get("-u"));
if (params.containsKey("-x"))
mqht.put(CMQC.PASSWORD_PROPERTY, params.get("-x"));
}
// I don't want to see MQ exceptions at the console.
MQException.log = null;
}
else
{
throw new IllegalArgumentException();
}
}
/**
* Connect, open queue, loop and get all messages then close queue and disconnect.
*
*/
private void testReceive()
{
String qMgrName = (String) params.get("-m");
String inputQName = (String) params.get("-q");
MQQueueManager qMgr = null;
MQQueue queue = null;
int openOptions = CMQC.MQOO_INPUT_AS_Q_DEF + CMQC.MQOO_INQUIRE + CMQC.MQOO_FAIL_IF_QUIESCING;
MQGetMessageOptions gmo = new MQGetMessageOptions();
gmo.options = CMQC.MQGMO_WAIT + CMQC.MQGMO_FAIL_IF_QUIESCING;
gmo.waitInterval = 5000; // wait up to 5 seconds for a message.
MQMessage receiveMsg = null;
int msgCount = 0;
boolean getMore = true;
try
{
if (params.containsKey("-c"))
qMgr = new MQQueueManager(qMgrName, mqht);
else
qMgr = new MQQueueManager(qMgrName);
MQTest12L.logger("successfully connected to "+ qMgrName);
queue = qMgr.accessQueue(inputQName, openOptions);
MQTest12L.logger("successfully opened "+ inputQName);
while(getMore)
{
receiveMsg = new MQMessage();
try
{
// get the message on the queue
queue.get(receiveMsg, gmo);
msgCount++;
if (CMQC.MQFMT_STRING.equals(receiveMsg.format))
{
String msgStr = receiveMsg.readStringOfByteLength(receiveMsg.getMessageLength());
// MQTest12L.logger("["+msgCount+"] " + msgStr);
}
else
{
byte[] b = new byte[receiveMsg.getMessageLength()];
receiveMsg.readFully(b);
// MQTest12L.logger("["+msgCount+"] " + new String(b));
}
}
catch (MQException e)
{
if ( (e.completionCode == CMQC.MQCC_FAILED) &&
(e.reasonCode == CMQC.MQRC_NO_MSG_AVAILABLE) )
{
// All messages read.
getMore = false;
break;
}
else
{
MQTest12L.logger("MQException: " + e.getLocalizedMessage());
MQTest12L.logger("CC=" + e.completionCode + " : RC=" + e.reasonCode);
getMore = false;
break;
}
}
catch (IOException e)
{
MQTest12L.logger("IOException:" +e.getLocalizedMessage());
}
}
}
catch (MQException e)
{
MQTest12L.logger("CC=" +e.completionCode + " : RC=" + e.reasonCode);
}
finally
{
MQTest12L.logger("read " + msgCount + " messages");
try
{
if (queue != null)
{
queue.close();
MQTest12L.logger("closed: "+ inputQName);
}
}
catch (MQException e)
{
MQTest12L.logger("CC=" +e.completionCode + " : RC=" + e.reasonCode);
}
try
{
if (qMgr != null)
{
qMgr.disconnect();
MQTest12L.logger("disconnected from "+ qMgrName);
}
}
catch (MQException e)
{
MQTest12L.logger("CC=" +e.completionCode + " : RC=" + e.reasonCode);
}
}
}
/**
* A simple logger method
* #param data
*/
public static void logger(String data)
{
String className = Thread.currentThread().getStackTrace()[2].getClassName();
// Remove the package info.
if ( (className != null) && (className.lastIndexOf('.') != -1) )
className = className.substring(className.lastIndexOf('.')+1);
System.out.println(LOGGER_TIMESTAMP.format(new Date())+" "+className+": "+Thread.currentThread().getStackTrace()[2].getMethodName()+": "+data);
}
/**
* main line
* #param args
*/
public static void main(String[] args)
{
MQTest12L write = new MQTest12L();
try
{
write.init(args);
write.testReceive();
}
catch (IllegalArgumentException e)
{
System.err.println("Usage: java MQTest12L -m QueueManagerName -q QueueName [-h host -p port -c channel] [-u UserID] [-x Password]");
System.exit(1);
}
System.exit(0);
}
}
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
I am developping J2EE application with appfuse , i have a webform called easyVolAction that contain a method search() I need to save the result of search method in database but and an excpetion is generated when clicking in the action search :NullPointerException in object trajet .I created TrajetDaoHibernate:
public TrajetDaoHibernate() {
super(TrajetModel.class);
}
/**
* {#inheritDoc}
*/
#SuppressWarnings("unchecked")
public List<TrajetModel> getTrajet() {
Session session = getSessionFactory().getCurrentSession();
Query qry = session.createQuery("from TrajetModel u order by upper(u.id)");
return qry.list();
}
/**
* {#inheritDoc}
*/
public TrajetModel saveTrajet(TrajetModel trajet) {
if (log.isDebugEnabled()) {
log.debug("user's id: " + trajet.getId());
}
Session session = getSessionFactory().getCurrentSession();
session.saveOrUpdate(trajet);
// necessary to throw a DataIntegrityViolation and catch it in UserManager
session.flush();
return trajet;
}
#Override
public TrajetModel save(TrajetModel trajet) {
return this.saveTrajet(trajet);
}
and TrajetDao:
public interface TrajetDao extends GenericDao {
List<TrajetModel> getTrajet();
TrajetModel saveTrajet(TrajetModel trajet);
}
and trajetManager:
#Service("trajetManager")
public class TrajetModelImpl extends GenericManagerImpl<TrajetModel, Long> implements TrajetManager {
private TrajetDao trajetDao;
#Autowired
public void setTrajetModelDao(TrajetDao trajetDao) {
this.dao = trajetDao;
this.trajetDao = trajetDao;
}
/**
* {#inheritDoc}
*/
public TrajetModel getTrajet(String trajetId) {
return trajetDao.get(new Long(trajetId));
}
/**
* {#inheritDoc}
*/
public List<TrajetModel> getTrajet() {
return trajetDao.getAllDistinct();
}
/**
* {#inheritDoc}
*/
public TrajetModel saveTrajet(TrajetModel trajet) throws TrajetExistsException {
try {
return trajetDao.saveTrajet(trajet);
} catch (DataIntegrityViolationException e) {
//e.printStackTrace();
log.warn(e.getMessage());
throw new TrajetExistsException("Trajet '" + trajet.getNom() + "' already exists!");
} catch (JpaSystemException e) { // needed for JPA
//e.printStackTrace();
log.warn(e.getMessage());
throw new TrajetExistsException("Trajet '" + trajet.getNom() + "' already exists!");
}
}
}
finnaly the action where i declare the search method:
public String recherche() throws IOException, TrajetExistsException {
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
// String url1 =
// FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("hidden");
String departAller = request.getParameter("easyVolRobot:villeDepart");
String arriveeAller = request.getParameter("easyVolRobot:villeArrivee");
String jourAller = request.getParameter("easyVolRobot:jourDep");
String moisAller = request.getParameter("easyVolRobot:dateDep");
String jourRetour = request.getParameter("easyVolRobot:jourDep");
String moisRetour = request.getParameter("easyVolRobot:dateArr");
String jourAllerPlus1 = jourAller + 1;
parametre = "departAller=" + departAller + "&arriveeAller="
+ arriveeAller + "&jourAller=" + jourAller + "&moisAller="
+ moisAller + "&jourRetour=" + jourRetour + "&moisRetour="
+ moisRetour;
parametre1 = "departAller=" + departAller + "&arriveeAller="
+ arriveeAller + "&jourAller=" + jourAllerPlus1 + "&moisAller="
+ moisAller + "&jourRetour=" + jourRetour + "&moisRetour="
+ moisRetour;
String response = sendGetRequest(url, parametre);
// insert();
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream(
"/data/crawl/root/siteSNCF.html"));
out.print(response);
} finally {
if (out != null)
out.close();
}
// tableau de resultats des trajets
List<TrajetModel> listTrajets = new ArrayList<TrajetModel>();
// trajet
//TrajetModel trajet = new TrajetModel();
File input = new File("/data/crawl/root/siteSNCF.html");
Document doc = Jsoup.parse(input, "UTF-8",
"http://www.easyvols.org/france-voyage");
for (Element vol : doc.select("div.vols")) {
//trajet = new TrajetModel();
for (Element allerRetour : vol.select("div.aller-retour")) {
Elements aeroport = allerRetour.select("div.aeroport");
System.out.println(aeroport.text());
Elements depart = allerRetour.select("div.depart");
Elements arrive = allerRetour.select("div.arrivee");
Elements date = allerRetour.select("div.date");
trajet.setNom(aeroport.text());
trajet.setVilleDepart(depart.text());
trajet.setVilleArrive(arrive.text());
trajet.sethArrive(12);
trajet.sethDepart(11);
trajet.sethReqt(14);
}
Elements prix2 = vol.select("div.tarif");
trajet.setPrice(prix2.text());
trajet = trajetManager.saveTrajet(trajet);
System.out.println(trajet);}
return"mainMenu";
}
why you comment this line out?
//TrajetModel trajet = new TrajetModel();
I see no other line where you create the TrajetModel.
If that object is not initiated you get the NPE here:
trajet.setNom(aeroport.text());
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()).