我正在尝试将XML数据插入MySQL数据库。我编写的SAX解析器在测试时自行工作。但是,每当我尝试将记录插入数据库时,即使我确保将值分配给null的工作流元素,也会出现NullPointerException。这是我的数据库表代码。 包数据库;
//STEP 1. Import required packages
import java.sql.*;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
public class Table {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://baldwin.isri.cmu.edu/SciSIP";
// Database credentials
static final String USER = "user";
static final String PASS = "pass";
public Table() {
}
public void createTable() {
Connection con = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
con = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = con.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS workflow" +
"(id INTEGER not NULL AUTO_INCREMENT, " +
" annotationBean VARCHAR(255), " +
" date VARCHAR(255), " +
" text VARCHAR(255), " +
" identification VARCHAR(255), " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if(stmt != null)
con.close();
} catch(SQLException se) {
}// do nothing
try {
if(con != null)
con.close();
} catch(SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
public void insertRecord(String annotationBean, String date, String text, String identification) {
Connection con = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver"); //Load the driver
con = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = con.createStatement();
String sql = "INSERT INTO `workflow` VALUES ('"+annotationBean+"', '"+date+"', '"+text+"', '"+identification+"')";
stmt.execute(sql); //Insert a row
System.out.println("Record Inserted into Database...");
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if(stmt != null)
con.close();
} catch(SQLException se) {
}// do nothing
try {
if(con != null)
con.close();
} catch(SQLException se) {
se.printStackTrace();
}//end finally try
}//end try
}
这是我的解析器代码,带有insert记录语句。
package parser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import database.Table;
public class XML_Parser_SAX extends DefaultHandler{
List aWorkflow;
private String tempVal;
//to maintain context
private Workflow tempWorkflow;
public XML_Parser_SAX(){
aWorkflow = new ArrayList();
}
public void runExample() {
parseDocument();
printData();
}
private void parseDocument() {
//get a factory
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
//get a new instance of parser
SAXParser sp = spf.newSAXParser();
//parse the file and also register this class for call backs
sp.parse("workflow.xml", this);
}catch(SAXException se) {
se.printStackTrace();
}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch (IOException ie) {
ie.printStackTrace();
}
}
/**
* Iterate through the list and print
* the contents
*/
private void printData(){
System.out.println("Number of Tasks in Workflow: '" + aWorkflow.size() + "'.");
Iterator it = aWorkflow.iterator();
while(it.hasNext()) {
System.out.println(it.next().toString());
}
}
//Event Handlers
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
//reset
tempVal = "";
if(qName.equalsIgnoreCase("annotationBean")) {
//create a new instance of employee
tempWorkflow = new Workflow();
tempWorkflow.setAnnotationBean(attributes.getValue("class"));
System.out.println("class");
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
tempVal = new String(ch,start,length);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equalsIgnoreCase("annotationBean")) {
//add it to the list
aWorkflow.add(tempWorkflow);
System.out.println("annotationBean");
} else if (qName.equalsIgnoreCase("date")) {
if (tempVal != null) {
tempWorkflow.setDate(tempVal);
}
else {
tempWorkflow.setDate("null");
}
System.out.println(tempWorkflow.getDate());
} else if (qName.equalsIgnoreCase("text")) {
if (tempVal != null) {
tempWorkflow.setText(tempVal);
}
else {
tempWorkflow.setText("null");
}
System.out.println(tempWorkflow.getText());
} else if (qName.equalsIgnoreCase("identification")) {
if (tempVal != null) {
tempWorkflow.setIdentification(tempVal);
}
else {
tempWorkflow.setIdentification("null");
}
System.out.println(tempWorkflow.getIdentification());
}
Table t = new Table();
//t.createTable();
t.insertRecord(tempWorkflow.getAnnotationBean(), tempWorkflow.getDate(), tempWorkflow.getText(), tempWorkflow.getIdentification());
}
public static void main(String[] args){
XML_Parser_SAX parse = new XML_Parser_SAX();
parse.runExample();
}
}
有人可以告诉我为什么这会给我NullPointerException吗?在此先感谢!!!
这是stacktrace:
Exception in thread "main" java.lang.NullPointerException
at parser.XML_Parser_SAX.endElement(XML_Parser_SAX.java:126)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(AbstractSAXParser.java:606)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XMLDocumentFragmentScannerImpl.java:1741)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2898)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(SAXParserImpl.java:302)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:274)
at parser.XML_Parser_SAX.parseDocument(XML_Parser_SAX.java:49)
at parser.XML_Parser_SAX.runExample(XML_Parser_SAX.java:35)
at parser.XML_Parser_SAX.main(XML_Parser_SAX.java:131)
是的,workflow.xml存在。以下是它的副本。
<workflow xmlns="http://taverna.sf.net/2008/xml/t2flow" version="1" producedBy="taverna- 2.4.0"><dataflow id="8781d5f4-d0ba-48a8-a1d1-14281bd8a917" role="top"><name>Hello_World</name> <inputPorts /><outputPorts><port><name>greeting</name><annotations /></port></outputPorts> <processors><processor><name>hello</name><inputPorts /><outputPorts><port><name>value</name> <depth>0</depth><granularDepth>0</granularDepth></port></outputPorts><annotations /> <activities><activity><raven><group>net.sf.taverna.t2.activities</group> <artifact>stringconstant-activity</artifact><version>1.4</version></raven> <class>net.sf.taverna.t2.activities.stringconstant.StringConstantActivity</class><inputMap /> <outputMap><map from="value" to="value" /></outputMap><configBean encoding="xstream"> <net.sf.taverna.t2.activities.stringconstant.StringConstantConfigurationBean xmlns="">
<value>Hello, World!</value>
</net.sf.taverna.t2.activities.stringconstant.StringConstantConfigurationBean></configBean> <annotations /></activity></activities><dispatchStack><dispatchLayer><raven> <group>net.sf.taverna.t2.core</group><artifact>workflowmodel-impl</artifact> <version>1.4</version></raven> <class>net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.Parallelize</class> <configBean encoding="xstream"> <net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.ParallelizeConfig xmlns="">
<maxJobs>1</maxJobs>
</net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.ParallelizeConfig> </configBean></dispatchLayer><dispatchLayer><raven><group>net.sf.taverna.t2.core</group> <artifact>workflowmodel-impl</artifact><version>1.4</version></raven> <class>net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.ErrorBounce</class> <configBean encoding="xstream"><null xmlns="" /></configBean></dispatchLayer><dispatchLayer> <raven><group>net.sf.taverna.t2.core</group><artifact>workflowmodel-impl</artifact> <version>1.4</version></raven> <class>net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.Failover</class><configBean encoding="xstream"><null xmlns="" /></configBean></dispatchLayer><dispatchLayer><raven> <group>net.sf.taverna.t2.core</group><artifact>workflowmodel-impl</artifact> <version>1.4</version></raven> <class>net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.Retry</class><configBean encoding="xstream"><net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.RetryConfig xmlns="">
<backoffFactor>1.0</backoffFactor>
<initialDelay>1000</initialDelay>
<maxDelay>5000</maxDelay>
<maxRetries>0</maxRetries>
</net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.RetryConfig></configBean> </dispatchLayer><dispatchLayer><raven><group>net.sf.taverna.t2.core</group> <artifact>workflowmodel-impl</artifact><version>1.4</version></raven> <class>net.sf.taverna.t2.workflowmodel.processor.dispatch.layers.Invoke</class><configBean encoding="xstream"><null xmlns="" /></configBean></dispatchLayer></dispatchStack> <iterationStrategyStack><iteration><strategy /></iteration></iterationStrategyStack> </processor></processors><conditions /><datalinks><datalink><sink type="dataflow"> <port>greeting</port></sink><source type="processor"><processor>hello</processor> <port>value</port></source></datalink></datalinks><annotations><annotation_chain encoding="xstream"><net.sf.taverna.t2.annotation.AnnotationChainImpl xmlns="">
<annotationAssertions>
<net.sf.taverna.t2.annotation.AnnotationAssertionImpl>
<annotationBean class="net.sf.taverna.t2.annotation.annotationbeans.Author">
<text>Stian Soiland-Reyes</text>
</annotationBean>
<date>2012-01-03 15:10:48.73 GMT</date>
<creators />
<curationEventList />
</net.sf.taverna.t2.annotation.AnnotationAssertionImpl>
</annotationAssertions>
</net.sf.taverna.t2.annotation.AnnotationChainImpl></annotation_chain><annotation_chain encoding="xstream"><net.sf.taverna.t2.annotation.AnnotationChainImpl xmlns="">
<annotationAssertions>
<net.sf.taverna.t2.annotation.AnnotationAssertionImpl>
<annotationBean class="net.sf.taverna.t2.annotation.annotationbeans.DescriptiveTitle">
<text>Hello World</text>
</annotationBean>
<date>2012-01-03 15:10:54.167 GMT</date>
<creators />
<curationEventList />
</net.sf.taverna.t2.annotation.AnnotationAssertionImpl>
</annotationAssertions>
</net.sf.taverna.t2.annotation.AnnotationChainImpl></annotation_chain> <annotation_chain_2_2 encoding="xstream"><net.sf.taverna.t2.annotation.AnnotationChainImpl xmlns="">
<annotationAssertions>
<net.sf.taverna.t2.annotation.AnnotationAssertionImpl>
<annotationBean class="net.sf.taverna.t2.annotation.annotationbeans.IdentificationAssertion">
<identification>8781d5f4-d0ba-48a8-a1d1-14281bd8a917</identification>
</annotationBean>
<date>2012-01-03 15:12:21.684 GMT</date>
<creators />
<curationEventList />
</net.sf.taverna.t2.annotation.AnnotationAssertionImpl>
<text>One of the simplest workflows possible. No workflow input ports, a single workflow output port "greeting", outputting "Hello, world!" as produced by the String Constant "hello".</text>
</annotationBean>
<date>2012-01-03 15:12:15.643 GMT</date>
<creators />
<curationEventList />
</net.sf.taverna.t2.annotation.AnnotationAssertionImpl>
</annotationAssertions>
</net.sf.taverna.t2.annotation.AnnotationChainImpl></annotation_chain></annotations >
</dataflow></workflow>
答案 0 :(得分:0)
您的tempWorkflow
设置为空。
startElement
只在获得annotationBean
startTag时构建临时工作流,但它会在任何结束标记上执行失败元素。所以当它</configBean>
时它会失败。
你需要有相应的开始和结束动作=你必须添加更多的开始动作。而且你还必须检查一切是否在正确的位置正确初始化。
如果您输入日志语句(例如log4J),例如:
,它会有很大帮助LOG.debug("start-tag tempWorkFlow");
这将使您能够准确计算出调用代码的时间。