Lasse this was part of the assignment.My output through this code comes as
<order>
<record>
<other elements which i have fetched from the database.....?
(Count of rejected records)
</record>
</order>
I want the output to be
<order>
<record>(Count of rejected records)
</record>
<other elements which i have fetched from the database.....?
</order>
Don't go through the whole code.I have commented out the areas which gives me this output(Commented as /** lasse)
import org.w3c.dom.*;
import java.io.*;
import java.util.*;
import java.text.*;
import javax.mail.*;
import javax.servlet.*;
import javax.activation.*;
import javax.servlet.http.*;
import javax.mail.internet.*;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.sql.*;
//xalan stuff
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.dom.DOMResult;
class SaxErrors implements ErrorHandler
{
public StringBuffer errors = new StringBuffer();
public void warning(SAXParseException ex)
{
}
public void error(SAXParseException ex)
{
}
public void fatalError(SAXParseException ex) throws SAXException
{
errors.append("Error ---\n");
errors.append("Line number : " + ex.getLineNumber() + "\n");
errors.append("Column number : " + ex.getColumnNumber() + "\n");
errors.append("Message : " + ex.getMessage() + "\n");
}
public String ErrorMessages()
{
if (errors.length() == 0)
{
return null;
}
else
{
return errors.toString();
}
}
}
public class JdbcInsertServlet extends HttpServlet {
static String colName;
static int results,rec_load,rec_rej,numCols;
Document agentsDoc = null;
Connection con = null;
Statement stmt = null;
ResultSet resultset = null;
ResultSetMetaData resultmetadata = null;
int agid;
String str1;
//New document
public static Document createDomDocument() {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
return doc;
} catch (Exception e) {
}
return null;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
str1=request.getParameter("thefile");
System.out.println("str1 : "+str1);
//for parsing the xml file
ErrorHandler demo=new SaxErrors();
SaxErrors s = new SaxErrors();
try
{
//Instantiate the parser and parse the file
DocumentBuilderFactory docbuilderfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docbuilder = docbuilderfactory.newDocumentBuilder();
agentsDoc = docbuilder.parse(str1);
XMLReader reader=XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
reader.setErrorHandler(demo);
reader.setFeature("http://xml.org/sax/features/validation",true);
}
catch(SAXException e){
System.out.println("error reading" + e.getMessage());
}
catch(Exception ex)
{
System.out.println("Error : " + ex.getMessage());
}
if (s.ErrorMessages() != null)
{
sendEmail(str1);
}
/**lasse
Document doc = createDomDocument();
Element dataroot=doc.createElement("order);
Element dataroot1 = doc.createElement("record");
dataroot.appendChild(dataroot1);
order element i.e the root and record being appended to it.
*/
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc

dbc:xjdbc");
stmt=con.createStatement();
resultset = stmt.executeQuery("select * from agents");
resultmetadata = resultset.getMetaData();
numCols = resultmetadata.getColumnCount();
/**Lasse
for (int i=1;i<=numCols;i++) {
colName = resultmetadata.getColumnName(i);
Element dataEl = doc.createElement(colName);
dataEl.appendChild(doc.createTextNode(colVal));
dataroot.appendChild(dataEl);
}
elements are added fetched from the database
*/
//Get the root element and all agents elements
Element agentsRoot = agentsDoc.getDocumentElement();
NodeList agents = agentsRoot.getElementsByTagName("agent");
for (int i = 0; i < agents.getLength(); i++) {
//For each agents, get the agent element
Element thisAgent = (Element)agents.item(i);
//Get iatano information
String thisAgentid = thisAgent.getAttribute("iatanumber");
System.out.println("Ino: " + thisAgentid);
agid = Integer.parseInt(thisAgentid);
out.println("Iata No is : " +agid);
//Get name information
String thisAgentname = thisAgent.getAttribute("name");
System.out.println("Name: "+thisAgentname);
//Loop through each trading address
NodeList traddress = thisAgent.getElementsByTagName("tradingaddress");
for (int j=0; j < traddress.getLength(); j++) {
Element thisAddress = (Element)traddress.item(j);
System.out.println("j" + j+ " "+"i "+ i);
//Get trading adress information from child
//elements
String l1 = thisAddress.getElementsByTagName("line1")
.item(0)
.getFirstChild().getNodeValue();
String l2 = thisAddress.getElementsByTagName("line2")
.item(0)
.getFirstChild().getNodeValue();
String pcode = thisAddress.getElementsByTagName("postcode")
.item(0)
.getFirstChild().getNodeValue();
String reg =thisAddress.getElementsByTagName("region")
.item(0)
.getFirstChild().getNodeValue();
String cty =thisAddress.getElementsByTagName("country")
.item(0)
.getFirstChild().getNodeValue();
//Loop through each legal address for the name and iatano
NodeList lgaddress = thisAgent.getElementsByTagName("legaladdress");
for (int k=0; k < lgaddress.getLength(); k++) {
Element thislgAddress = (Element)lgaddress.item(k);
System.out.println("k" + k+ " "+"i "+ i);
//Get trading adress information from child
//elements
String ll1 = thislgAddress.getElementsByTagName("line1")
.item(0)
.getFirstChild().getNodeValue();
String ll2 = thislgAddress.getElementsByTagName("line2")
.item(0)
.getFirstChild().getNodeValue();
String lpcode = thislgAddress.getElementsByTagName("postcode")
.item(0)
.getFirstChild().getNodeValue();
String lreg =thislgAddress.getElementsByTagName("region")
.item(0)
.getFirstChild().getNodeValue();
String lcty =thislgAddress.getElementsByTagName("country")
.item(0)
.getFirstChild().getNodeValue();
try
{
results = stmt.executeUpdate("insert into agents(iatano,trpostcode,lgregion) values("+agid+",'"+pcode+"','"+lreg+"')");
if(results>0)
{
++rec_load;
out.println("insert");
}
else
{
// ++rec_rej;
}
}catch(Exception e){++rec_rej;out.println("Reject");}
}
}
System.out.println("agid is : "+agid);
}
System.out.println("Total No of records inserted : "+rec_load);
System.out.println("Total No of records rejected : "+rec_rej);
stmt.close();
con.close();
System.out.println("Over");
} catch (Exception e) {
System.out.println("Error " + e.toString());
}
//For printing the new xml file in case of error
/**lasse
if(rec_rej > 0)
{
dataroot.appendChild(doc.createTextNode(Integer.toString(rec_rej)));
doc.appendChild(dataroot);
writeXmlFile(doc, "c:/inrej.xml");
}
here i get the value of rec_rej.
*/
}//doPost() closing
public void sendEmail( String filename){
boolean debug = false;
try {
Properties prop = new Properties();
prop.put("mail.host", "your_stmp_goes_here"); //SMTP goes here
Session mailConnection = Session.getDefaultInstance(prop, null);
mailConnection.setDebug(debug);
Message msg = new MimeMessage(mailConnection);
InternetAddress myaddress = new InternetAddress("zotesterror@zeroocta.net", "YourName");
InternetAddress sendingTo = new InternetAddress("zotesterror@tplusplus.net", "OtherPersonsName");
msg.setContent(msg, "text/plain");
msg.setFrom(myaddress);
msg.setRecipient(Message.RecipientType.TO, sendingTo);
msg.setSubject("Error details: ");
// Create the msg part
BodyPart msgBodyPart = new MimeBodyPart();
// Fill the msg
msgBodyPart.setText("XML Error File");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(msgBodyPart);
// Conversion of String errorMesage to byte arrray
// attachment
msgBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource("c:/inrej.xml");
msgBodyPart.setDataHandler(new DataHandler(source));
msgBodyPart.setFileName("Error Messages");
multipart.addBodyPart(msgBodyPart);
// Put parts in msg
msg.setContent(multipart);
// Send the msg
Transport.send(msg);
}
catch (Exception e) {
e.printStackTrace();
}
}
//For getting values from database incase of reject and writing it to a file
public static void writeXmlFile(Document doc, String filename) {
try {
// Prepare the DOM document for writing
Source source = new DOMSource(doc);
// Prepare the output file
File file = new File(filename);
Result result = new StreamResult(file);
// Write the DOM document to the file
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);
} catch (Exception e) {
} }
}