java.lang.NullPointerException :at com.mysql.jdbc.ResultSet.buildIndexMapping - java

I am getting the below exception in my code :
frequent i am getting this error.
java.lang.NullPointerException
at com.mysql.jdbc.ResultSet.buildIndexMapping(ResultSet.java:616)
at com.mysql.jdbc.ResultSet.findColumn(ResultSet.java:946)
at com.mysql.jdbc.ResultSet.getString(ResultSet.java:5613)
at com.sfmfm.database.DB_DashBoard.doGet(DB_DashBoard.java:275)
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:305)
for this jsp Data not loading properly. browser :firefox latest
if i am running this in eclipse its working fine.
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sfmfm.properties.efmfm;
#WebServlet("/DB_DashBoard")
public class DB_DashBoard extends DB_Conn {
/**
*
*/
private static final long serialVersionUID = -5639866791158510975L;
static Statement st,st1;
public DB_DashBoard() throws Exception {
super();
st=con.createStatement();
st1=con.createStatement();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
out=response.getWriter();
String query=request.getParameter("query");
// create a java calendar instance
//Calendar calendar = Calendar.getInstance();
// get a java.util.Date from the calendar instance.
// this date will represent the current instant, or "now".
Date now = new Date();
if(query != null && query.contains("~"))
{
System.out.println("Web Browser Request--"+query);
/*System.out.println("Today Date" +now); */
String browser_req[]=query.split("~");
if(browser_req[0].equals("Fetch_Pending_Fee"))
{
StringBuffer AllList = new StringBuffer();
try {
ResultSet rs=st1.executeQuery("SELECT sm.first_name, sm.last_name, " +
"cs.section_name, cs.class_name, sp.balance_amount, tm.first_name as tfname,tm.last_name as tlname, " +
"sm.contact_no, ft.due_date FROM teacher_master tm,student_master sm," +
" student_payment sp, class_section cs, fee_type ft, student_class sc WHERE" +
" sp.balance_amount!=0 AND sp.student_id = sm.student_id AND" +
" sm.student_id = sc.student_id AND sc.class_id = cs.class_id AND " +
"cs.class_name = ft.class_name AND tm.teacher_id = cs.teacher_id AND ft.fee_type_id=sp.payment_id AND " +
"TO_DAYS(ft.due_date) < TO_DAYS(NOW())");
if (rs != null)
{
while(rs.next())
{
AllList.append("<PENDING>");
AllList.append("<FIRSTNAME>" + rs.getString("first_name") + "</FIRSTNAME>");
AllList.append("<LASTNAME>" + rs.getString("last_name") + "</LASTNAME>");
AllList.append("<CONTACT>" + rs.getString("contact_no") + "</CONTACT>");
AllList.append("<BALANCE>" + rs.getString("balance_amount") + "</BALANCE>");
AllList.append("<DUE>" + rs.getString("due_date") + "</DUE>");
AllList.append("<SECTION>" + rs.getString("section_name") + "</SECTION>");
AllList.append("<CLASS>" + rs.getString("class_name") + "</CLASS>");
AllList.append("<TFNAME>" + rs.getString("tfname") + "</TFNAME>");
AllList.append("<TLNAME>" + rs.getString("tlname") + "</TLNAME>");
AllList.append("<SECTION>" + rs.getString("section_name") + "</SECTION>");
AllList.append("</PENDING>");
}
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Access-Control-Allow-Origin", "*");
response.getWriter().println("<CATALOG>" + AllList.toString() +"</CATALOG>");
System.out.println("Response sent="+"<CATALOG>" + AllList.toString()+ "</CATALOG>");
}
}
catch (Exception e)
{
System.out.println("S: Errorhai2");
e.printStackTrace();
}
}
else if(browser_req[0].equals("alert_past_info"))
{
StringBuffer AllList = new StringBuffer();
try {
ResultSet rs=st.executeQuery("SELECT DAY(date_time) AS aday, MONTHNAME(date_time) AS amonth,TIME(date_time) AS atime,title,category,sub_category,details FROM post_alert ");
if (rs != null)
{
while(rs.next())
{
AllList.append("<PASTALERT>");
AllList.append("<ADAY>" + rs.getInt("aday") + "</ADAY>");
AllList.append("<AMONTH>" + rs.getString("amonth") + "</AMONTH>");
AllList.append("<ATIME>" + rs.getInt("atime") + "</ATIME>");
AllList.append("<ATITLE>" + rs.getString("title") + "</ATITLE>");
AllList.append("<ACATA>" + rs.getString("category") + "</ACATA>");
AllList.append("<ASUB>" + rs.getString("sub_category") + "</ASUB>");
AllList.append("<ADESC>" + rs.getString("details") + "</ADESC>");
AllList.append("</PASTALERT>");
}
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Access-Control-Allow-Origin", "*");
response.getWriter().println("<CATALOG>" + AllList.toString() +"</CATALOG>");
System.out.println("Response sent="+"<CATALOG>" + AllList.toString()+ "</CATALOG>");
}
}
catch (Exception e)
{
System.out.println("Error On Past Alert Viewing");
e.printStackTrace();
}
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
pls provide the suggestions to clear this error.

The error you get is coming from mysql driver. Your classpath in eclipse may use a different driver version that the one you are using once your app is deployed. It probably explain why you never get this error when running in eclipse.
So I suggest you to check the driver version your are using (and probably upgrading the one you use when the app is deployed).

Related

How can i make the content of a webpage downloadable for the client

Im working on a project and i cant find a way to make the content of a page that prints out a table from my database downloadable. I want there to be a button that gives the client the opportunity to download the content of the table in form of either pdf or csv.
this is the servlet fo
package bacit.web.bacit_web;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.sql.*;
#WebServlet(name = "BookingHistorikk", value = "/BookingHistorikk")
public class GetBookingHistorikk extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
{
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("<html><body>");
try
{
Class.forName("org.mariadb.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mariadb:**********", "root", "pass");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from BOOKING");
out.println("<table style=text-align:center border=1 width=50% height=10% >");
out.println("<tr><th>Start Dato</th><th>Slutt Dato</th><th>Kommentar</th><th>Levert</th><th>Total Pris</th></tr>");
while (rs.next())
{
Date startDate = rs.getDate("StartDate");
Date endDate = rs.getDate("EndDate");
String cmnt = rs.getString("Cmnt");
Boolean isDelivered = rs.getBoolean("IsDelivered");
int totalPrice = rs.getInt("TotalPrice");
out.println("<tr><td>" + startDate + "</td><td>" + endDate + "</td><td>" + cmnt + "</td><td>" + isDelivered + "</td><td>" + totalPrice + "</td></tr>");
}
out.println("</table>");
out.println("</html></body>");
con.close();
}
catch (Exception e)
{
out.println("error");
}
}
}
There are 2 things you need to do here ...
Create CSV file.
Send it to the user with the help of HttpServletResponse.
You can create a CSV file contents like this:
String getMyCsvFileAsString() {
StringBuilder sb = new StringBuilder();
sb.append("id");
sb.append(',');
sb.append("Name");
sb.append('\n');
sb.append("1");
sb.append(',');
sb.append("Prashant Ghimire");
sb.append('\n');
writer.write(sb.toString());
}
And then you can attach it to the request like this:
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment; filename=\"myCsvFile.csv\"");
try
{
OutputStream outputStream = response.getOutputStream();
// Get CSV file as string
String outputResult = getMyCsvFileAsString();
outputStream.write(outputResult.getBytes());
outputStream.flush();
outputStream.close();
}
catch(Exception e)
{
System.out.println(e.toString());
}
}

Java crawler to get all first and third party cookies

i would like to build a crawler in Java that give me all cookies from a website. This crawler is believed to crawl a list of websites (and obviously the undersides) automatic.
I have used jSoup and Selenium for my plan.
package com.mycompany.app;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
public class BasicWebCrawler {
private static Set<String> uniqueURL = new HashSet<String>();
private static List<String> link_list = new ArrayList<String>();
private static Set<String> uniqueCookies = new HashSet<String>();
private static void get_links(String url) {
Connection connection = null;
Connection.Response response = null;
String this_link = null;
try {
connection = Jsoup.connect(url);
response = connection.execute();
//cookies_http = response.cookies();
// fetch the document over HTTP
Document doc = response.parse();
// get all links in page
Elements links = doc.select("a[href]");
if(links.isEmpty()) {
return;
}
for (Element link : links) {
this_link = link.attr("href");
boolean add = uniqueURL.add(this_link);
System.out.println("\n" + this_link + "\n" + "title: " + doc.title());
if (add && (this_link.contains(url))) {
System.out.println("\n" + this_link + "\n" + "title: " + doc.title());
link_list.add(this_link);
get_links(this_link);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
get_links("https://de.wikipedia.org/wiki/Wikipedia");
/**
* Hier kommt Selenium ins Spiel
*/
WebDriver driver;
System.setProperty("webdriver.chrome.driver", "D:\\crawler\\driver\\chromedriver.exe");
driver = new ChromeDriver();
// create file named Cookies to store Login Information
File file = new File("Cookies.data");
FileWriter fileWrite = null;
BufferedWriter Bwrite = null;
try {
// Delete old file if exists
file.delete();
file.createNewFile();
fileWrite = new FileWriter(file);
Bwrite = new BufferedWriter(fileWrite);
// loop for getting the cookie information
} catch (Exception ex) {
ex.printStackTrace();
}
for(String link : link_list) {
System.out.println("Open Link: " + link);
driver.get(link);
try {
// loop for getting the cookie information
for (Cookie ck : driver.manage().getCookies()) {
String tmp = (ck.getName() + ";" + ck.getValue() + ";" + ck.getDomain() + ";" + ck.getPath() + ";" + ck.getExpiry() + ";" + ck.isSecure());
if(uniqueCookies.add(tmp)) {
Bwrite.write("Link: " + link + "\n" + (ck.getName() + ";" + ck.getValue() + ";" + ck.getDomain() + ";" + ck.getPath() + ";" + ck.getExpiry() + ";" + ck.isSecure())+ "\n\n");
Bwrite.newLine();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
try {
Bwrite.close();
fileWrite.close();
driver.close();
driver.quit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I test this code on a wikipedia page and compare the result with a cookie scanner call CookieMetrix.
My code shows only four cookies:
Link: https://de.wikipedia.org/wiki/Wikipedia:Lizenzbestimmungen_Commons_Attribution-ShareAlike_3.0_Unported
GeoIP;DE:NW:M__nster:51.95:7.54:v4;.wikipedia.org;/;null;true
Link: https://de.wikipedia.org/wiki/Wikipedia:Lizenzbestimmungen_Commons_Attribution-ShareAlike_3.0_Unported
WMF-Last-Access-Global;13-May-2019;.wikipedia.org;/;Mon Jan 19 02:28:33 CET 1970;true
Link: https://de.wikipedia.org/wiki/Wikipedia:Lizenzbestimmungen_Commons_Attribution-ShareAlike_3.0_Unported
WMF-Last-Access;13-May-2019;de.wikipedia.org;/;Mon Jan 19 02:28:33 CET 1970;true
Link: https://de.wikipedia.org/wiki/Wikipedia:Lizenzbestimmungen_Commons_Attribution-ShareAlike_3.0_Unported
mwPhp7Seed;55e;de.wikipedia.org;/;Mon Jan 19 03:09:08 CET 1970;false
But the cookie scanner shows seven. I don't know why my code shows lesser than the CookieMetrix. Can you help me?
JavaDoc for java.util.Set<Cookie> getCookies():
Get all the cookies for the current domain. This is the equivalent of calling "document.cookie" and parsing the result
document.cookie will not return HttpOnly cookies, simply because JavaScript does not allow it.
Also notice that the “CookieMetrix” seems to list cookies from different domains.
Solutions:
To get a listing such as “CookieMetrix” (1+2) you could add a proxy after your browser and sniff the requests.
In case you want to get all cookies for the current domain, including HttpOnly (1), you could try accessing Chrome’s DevTools API directly (afair, it’ll also return HttpOnly cookies)

Exporting MySQL as Excel File through Java Servlet, coming up with 404 Error

I'm running a page trying to export an Excel file through a Java Servlet. A rundown of the structure:
downloadreports.jsp is where the button is that is supposed to call the file. The button calls ReportsServlet.java, which is just the download and that in turn calls ExcelCreatorBanned.java, which calls the database and creates the Excel file.
The problem is that 1) when I try to click on downloadreports.jsp when running the full site, it automatically goes to the ReportsServlet instead of displaying the page (turning up a 404 error for /Reports) and 2) I've been messing with this for days and it's just not working. Not sure what I'm doing wrong, but any help would be very appreciated!
downloadreports.jsp
<div align="center">
<form id="downloadBanned" action="../Reports" method="post">`
<input class="btn btn-lg btn-red" type="submit" value="Download Banned Student List"><br> `
</form>`
ReportsServlet.java
package controllers;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import helpers.ExcelCreatorBanned;
/**
* Servlet implementation class ReportsServlet
*/
#WebServlet({ "/ReportsServlet", "/Reports" })
public class ReportsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private HttpSession session;
private String url;
/**
* #see HttpServlet#HttpServlet()
*/
public ReportsServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.session = request.getSession(false);
ExcelCreatorBanned ecb = new ExcelCreatorBanned();
ecb.downloadExcel();
url = "admin/downloadreports.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
private Object getOutputStream() {
// TODO Auto-generated method stub
return null;
}
}
ExcelCreatorBanned.java (The reference to DbConnect.java is the credentials to the server, and it definitely works because it works on the other pages)
package helpers;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.servlet.ServletOutputStream;
import model.DbConnect;
import java.sql.Statement;
public class ExcelCreatorBanned {
public String downloadExcel( ) { //ServletOutputStream out){
String outFileName = "BannedStudents.csv";
int nRow = 1;
String strQuery = null;
Connection con = null;
try {
// Getting connection here for mySQL database
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DbConnect.devCredentials();
System.out.println(con);
if(con==null)
return "Connection Failed";
// Database Query
strQuery = "select * from banned";
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(strQuery);
File file = new File(outFileName);
FileWriter fstream = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fstream);
//Get Titles
String titleLine = "BannedID" + "," + "UserID" + "," + "AdminID"
+ "," + "Ban Start Date" + "," +
"Ban End Date" + "," + "Penalty Count" + "," +
"Description" + "," + "Status" + "\n";
out.write(titleLine);
//stmt = conn.createStatement();
while (rs.next()) {
int BannedId = rs.getInt(1);
int UserID = rs.getInt(2);
int AdminID = rs.getInt(3);
String BanStartDate = rs.getString(4);
String BanEndDate = rs.getString(5);
int PenaltyCount = rs.getInt(6);
String Description = rs.getString(7);
String Status = rs.getString(8);
String outline = BannedId + "," + UserID + "," + AdminID +
"," + BanStartDate + "," +
BanEndDate + "," + PenaltyCount + "," + Description +
"," + Status + "\n";
out.write(outline);
} //end of while
out.close();
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
return outFileName;
}
}
I don't like the look of the action="../Reports" attribute in the line
<form id="downloadBanned" action="../Reports" method="post">
Try the following instead:
<form id="downloadBanned" action="${pageContext.request.contextPath}/Reports" method="post">
See this question for a discussion about what ${pageContext.request.contextPath} is.

Servlets and JSP blank

hi all I've typed out a page that queries the database then inputs something into the database but when I go to load the servlet/jsp page its comes back blank and am unsure what is happening or why? I'm coding in eclipse and after looking at the console and not getting anything printing out I figured there was something wrong with my code but I cannot see the problem.
Here is my servlet
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class TutorAssign
*/
#WebServlet("/TutorAssign")
public class TutorAssign extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TutorAssign() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
private void sendBack(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
//Set data you want to send back to the request (will be forwarded to the page)
//Can set string, int, list, array etc.
String sql = "SELECT l.id,s.name,l.day,l.time,l.room" +
" FROM subject s, lab l " +
" WHERE s.user_id="+(Integer)session.getAttribute("id");
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got boobs");
System.out.println(session.getAttribute("id"));
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery(sql);
System.out.println(res);
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
if (res.next()){
do{
list1.add(res.getString(1));
list2.add(res.getString(2)+" "+res.getString(3)+" "+res.getString(4)+" "+res.getString(5));
}while(res.next());
System.out.println("Outside");
String[] arr1 = list1.toArray(new String[list1.size()]);
String[] arr2 = list2.toArray(new String[list2.size()]);
System.out.println(list1);
request.setAttribute("res1", arr1);
request.setAttribute("res2", arr2);
}
}catch (SQLException e) {
}
catch (Exception e) {
}
//Decides what page to send the request data to
RequestDispatcher view = request.getRequestDispatcher("TutorAssign.jsp");
//Forward to the page and pass the request and response information
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int user_id = Integer.parseInt(request.getParameter("id"));
int lab_id = 0;
String message = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got connection");
System.out.println(user_id);
Statement s = con.createStatement();
String sql = "INSERT INTO user_lab" +
" (user_id, lab_id)" +
" VALUES" +
" ('" + user_id + "'," +
" '" + lab_id + "')";
System.out.println(sql);
int i = s.executeUpdate(sql);
if (i==1) {
message = "Successfully assigned a tutor.";
response.sendRedirect("Lecturer_labs");
}
s.close();
con.close();
}
catch (SQLException e) {
message = "Error." + e.toString();
boolean error = true;
}
catch (Exception e) {
message = "Error." + e.toString();
boolean error = true;
}
if (message!=null) {
PrintWriter out = response.getWriter();
out.println("<B>" + message + "</B><BR>");
out.println("<HR><BR>");
}
}
// TODO Auto-generated method stub
}
I noticed that your doGet method has not been implemented.
I would assume that your sendBack code is not being called
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
sendBack(request,response);
}
You have several empty catch blocks. This means that if the program encounters some problem the error will be silently swallowed and you don't know what code got executed and what code was skipped, so the outcome is unknown. At least log the error in the catch block, like this (very basic example, using java.util.logging
} catch (SQLException e) {
logger.log(Level.INFO,"SQL Error encountered",e);
} catch (Exception e) {
logger.log(Level.INFO,"Other error encountered",e);
}
Start by getting your error handling right, and study the errors the program encounters.
Aside from that problem, as the others point out your doGet isn't implemented - so if you call the page with GET it won't do anything because doGet is empty. It should do something on POST though.

SAXParseException returns null for getSystemId()

Why SAXParseException returns null for getSystemId()? What is System Identifier?
import java.io.StringReader;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
public class MainClass {
static public void main(String[] arg) throws Exception{
boolean validate = false;
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setValidating(validate);
XMLReader reader = null;
SAXParser parser = spf.newSAXParser();
reader = parser.getXMLReader();
reader.setErrorHandler(new MyErrorHandler());
reader.parse(new InputSource(new StringReader(xmlString)));
}
static String xmlString = "<PHONEBOOK>" +
" <PERSON>" +
" <NAME>Joe Wang</NAME>" +
" <EMAIL>joe#yourserver.com</EMAIL>" +
" <TELEPHONE>202-999-9999</TELEPHONE>" +
" <WEB>www.java2s.com</WEB>" +
" </PERSON>" +
" <PERSON> " +
"<NAME>Karol</NAE>" + // error here
" <EMAIL>karol#yourserver.com</EMAIL>" +
" <TELEPHONE>306-999-9999</TELEPHONE>" +
" <WEB>www.java2s.com</WEB>" +
" </PERSON>" +
" <PERSON>" +
" <NAME>Green</NAME>" +
" <EMAIL>green#yourserver.com</EMAIL>" +
" <TELEPHONE>202-414-9999</TELEPHONE>" +
" <WEB>www.java2s.com</WEB>" +
" </PERSON>" +
" </PHONEBOOK>";
}
class MyErrorHandler implements ErrorHandler {
public void warning(SAXParseException e) throws SAXException {
show("Warning", e);
throw (e);
}
public void error(SAXParseException e) throws SAXException {
show("Error", e);
throw (e);
}
public void fatalError(SAXParseException e) throws SAXException {
show("Fatal Error", e);
throw (e);
}
private void show(String type, SAXParseException e) {
System.out.println(type + ": " + e.getMessage());
System.out.println("Line " + e.getLineNumber() + " Column "
+ e.getColumnNumber());
System.out.println("System ID: " + e.getSystemId());
System.out.println(e);
}
}
The 'system identifier' in XML is the physical location you got something from. When you just parse a string in memory, it has no system identifier at all unless you make an extra call to give it one.
You can, in this case, call InputSource.setSystemId.
The System Identifier is a URI you can specify, it's there so it can be used by the EntityResolver to decide how relative paths get resolved during xml parsing. Whether it is a physical location or just a label is up to you. Of course, in your example you don't have anything to resolve so it's not needed.

Categories