SAX startElement is never called - java

I'm trying to use SAX to parse an XML but it happens that the Handler's startElement() is never called. I do not have any clues why it doesnt work.
This is my code
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.InputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class ChangePasswordXMLParser {
public static void parseXML(InputStream xml) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
ChangePasswordHandler handler = new ChangePasswordHandler();
saxParser.parse(xml, handler);
} catch (Exception e) {
e.printStackTrace();
}
}
private static class ChangePasswordHandler extends DefaultHandler {
boolean bfReturn;
public ChangePasswordHandler() {
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("return")) {
bfReturn = true;
}
}
#Override
public void characters(char ch[], int start, int length) throws SAXException {
if (bfReturn) {
AuthenticateUserResult user = SessionManager.getInstance().getUser();
String value = new String(ch, start, length);
EventBus.getDefault().post(new AlterarSenhaEvent(value));
bfReturn = false;
}
}
}
}
and this is and XML Input example:
<?xml version="1.0"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body SOAP-ENC:encodingStyle="http://schemas.xmlsoap.org/soap/envelope/">
<NS1:ChangePasswordResponse xmlns:NS1="urn:exemple">
<return xsi:type="xsd:string">03351-0</return>
</NS1:ChangePasswordResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
I did see in other topic here in stackoverflow that may be the imports, but my imports seems fine to me.
Any ideas? Thanks!

You set AlterarSenhaHandler instead of PasswordHandler.
So PasswordHandler is never called.
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("return")) {
System.out.println("inside return");
}
}
proofs that your code is valid

Related

File Not Found Exception while parsing large XML File in Java

I'm using SAX (Simple API for XML) to parse an XML document. The document is a huge XML file (dblp.xml - 1.46 GB), i wrote a few lines of parser and tested it on small files and it works.
Sample.XML and Student.XML are small files having few lines of XML, my parser parses them but when i change the path to dblp.XML it generates the file not found exception (file is still there with other sample files, but its huge in size)
here is the Exception i get:
java.io.FileNotFoundException: E:\Workspaces\Java\SaxParser\xml\dblp.dtd (The system cannot find the file specified)
here is my code:
package com.teamincredibles.sax;
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;
public class Parser extends DefaultHandler {
public void getXml() {
try {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxParserFactory.newSAXParser();
final MySet openingTagList = new MySet();
final MySet closingTagList = new MySet();
DefaultHandler defaultHandler = new DefaultHandler() {
public void startDocument() throws SAXException {
System.out.println("Starting Parsing...\n");
}
public void endDocument() throws SAXException {
System.out.print("\n\nDone Parsing!");
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (!openingTagList.contains(qName)) {
openingTagList.add(qName);
System.out.print("<" + qName + ">\n");
}
}
public void characters(char ch[], int start, int length)
throws SAXException {
/*for(int i=start; i<(start+length);i++){
System.out.print(ch[i]);
}*/
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (!closingTagList.contains(qName)) {
closingTagList.add(qName);
System.out.print("</" + qName + ">");
}
}
};
saxParser.parse("xml/dblp.xml", defaultHandler);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
Parser readXml = new Parser();
readXml.getXml();
}
}
What is the matter i can't figure out.
Is your XML file referencing a DTD, in this case "dblp.dtd".
If yes check if its in the location "E:\Workspaces\Java\SaxParser\xml\". If not place it in the location and run your code.

how to extract element from cxf soap message

I have below soap message.I want to extract Id and chargeBoxIdentity element.
ID: 2
Address: http://localhost:8080/ocppserver/services/CentralSystemService
Encoding: UTF-8
Http-Method: POST
Content-Type: application/soap+xml;charset=UTF-8;action="/Authorize"
Headers: {accept-encoding=[gzip,deflate], connection=[Keep-Alive], Content-Length= [852], content-type=[application/soap+xml;charset=UTF-8;action="/Authorize"], host=[localhost:8080], user-agent=[Apache-HttpClient/4.1.1 (java 1.5)]}
Payload: <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<h:chargeBoxIdentity xmlns:h="urn://Ocpp/Cs/2012/06/" xmlns="urn://Ocpp/Cs/2012/06/">REE001</h:chargeBoxIdentity>
<a:From>
<a:Address>http://127.0.0.1:8081/ChargeBox/Ocpp</a:Address>
</a:From>
<a:MessageID>urn:uuid:2ae9d933-4f92-4628-84fe-35024a858450</a:MessageID>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
<a:Action>/Authorize</a:Action></s:Header>
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<authorizeRequest xmlns="urn://Ocpp/Cs/2012/06/">
<idTag>EF1234</idTag>
</authorizeRequest>
</s:Body>
</s:Envelope>
I wrote below interceptor .Below interceptor print the Header and payload field.How to extract the Id ? How to extract chargeboxIdentity from the payload ? I am using the log4j framework.
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.helpers.CastUtils;
import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.Phase;
public class InBoundMessage extends AbstractSoapInterceptor {
public InBoundMessage() {
super(Phase.RECEIVE);
}
public void handleMessage(SoapMessage message) throws Fault {
Map<String, List<String>> headers = CastUtils.cast((Map)message.get(Message.PROTOCOL_HEADERS));
if (headers != null) {
Set<Entry<String,List<String>>> hashSet=headers.entrySet();
for(Entry<String,List<String>> entry:hashSet ) {
System.out.println("Key="+entry.getKey()+", Value="+entry.getValue());
}
}
System.out.println("Message id = "+message.getId());
try{
InputStream is = message.getContent ( InputStream.class );
CachedOutputStream os = new CachedOutputStream ( );
IOUtils.copy ( is, os );
os.flush();
message.setContent ( InputStream.class, os.getInputStream ( ) );
is.close();
String payload=IOUtils.toString ( os.getInputStream ( ) );
System.out.println ("The request is: " + payload);
}catch(Exception e){
e.printStackTrace();
}
}
}
I parsed the soap message by using SAX parser.
import java.io.StringReader;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ParseInBoundSoapMessage {
private static InBoundSoapMessage inBoundSoapMessage=null;
public static InBoundSoapMessage getInBoundSoapMessage(String xml) {
try {
inBoundSoapMessage=new InBoundSoapMessage();
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean ischargeBoxIdentityPresent = false;
boolean isAddressPresent = false;
boolean isFromPresent=false;
boolean isActionPresent=false;
boolean isMessageID=false;
boolean isRelatesTo=false;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (localName.equals("chargeBoxIdentity")) {
ischargeBoxIdentityPresent = true;
}
if (localName.equals("From")) {
isFromPresent = true;
}
if (localName.equals("Address")) {
isAddressPresent = true;
}
if(localName.equals("Action")){
isActionPresent=true;
}
if(localName.equals("MessageID")){
isMessageID=true;
}
if(localName.equals("RelatesTo")){
isRelatesTo=true;
}
}
public void characters(char ch[], int start, int length) throws SAXException {
if (ischargeBoxIdentityPresent) {
inBoundSoapMessage.setChargeBoxIdentity(new String(ch, start, length));
ischargeBoxIdentityPresent = false;
}
if(isAddressPresent && isFromPresent){
inBoundSoapMessage.setAddressInFrom(new String(ch, start, length));
isAddressPresent = false;
isFromPresent=false;
}
if(isActionPresent){
inBoundSoapMessage.setAction(new String(ch, start, length));
isActionPresent=false;
}
if(isMessageID){
inBoundSoapMessage.setMessageId(new String(ch, start, length));
isMessageID=false;
}
if(isRelatesTo){
inBoundSoapMessage.setRelatesTo(new String(ch, start, length));
isRelatesTo=false;
}
}
};
saxParser.parse(new InputSource(new StringReader(xml)), handler);
} catch (Exception e) {
e.printStackTrace();
}
return inBoundSoapMessage;
}
}

SAXParser Android, ArrayList repeating elements

I am currently just trying to process the elements within the item nodes. I am just focusing on the title at this point for simplicity, but I am finding that when it parses, I am just getting the same element three times.
http://open.live.bbc.co.uk/weather/feeds/en/2643123/3dayforecast.rss
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XMLHelper extends DefaultHandler {
private String URL_Main="http://open.live.bbc.co.uk/weather/feeds/en/2643123/3dayforecast.rss";
String TAG = "XMLHelper";
Boolean currTag = false;
String currTagVal = "";
public ItemData item = null;
public ArrayList<ItemData> items = new ArrayList<ItemData>();
public void get() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(this);
InputStream inputStream = new URL(URL_Main).openStream();
reader.parse(new InputSource(inputStream));
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
// Receives notification of the start of an element
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
Log.i(TAG, "TAG: " + localName);
currTag = true;
currTagVal = "";
if (localName.equals("channel")) {
item = new ItemData();
}
}
// Receives notification of end of element
public void endElement(String uri, String localName, String qName)
throws SAXException {
currTag = false;
if (localName.equalsIgnoreCase("title"))
item.setTitle(currTagVal);
else if (localName.equalsIgnoreCase("item"))
items.add(item);
}
// Receives notification of character data inside an element
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currTag) {
currTagVal = currTagVal + new String(ch, start, length);
currTag = false;
}
}
}
The reason you are getting the same value thrice is because you are creating the object when there is a channel tag in startElement method.
if (localName.equals("channel")) {
item = new ItemData();
}
I guess you should initiate the object whenever there is a item tag as below
if (localName.equals("item")) { // check for item tag
item = new ItemData();
}
Remodify your whole project, you need 3 classes :
1.ItemList
2.XMLHandler extends Default handler
3.SAXParsing activity
Make your code organized first
In your XMLHandler class extend default handler your code should look like
public class MyXMLHandler extends DefaultHandler
{
public static ItemList itemList;
public boolean current = false;
public String currentValue = null;
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
current = true;
if (localName.equals("channel"))
{
/** Start */
itemList = new ItemList();
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
current = false;
if(localName.equals("item"))
{
itemList.setItem(currentValue);
}
else if(localName.equals("title"))
{
itemList.setManufacturer(currentValue);
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
if(current)
{
currentValue = new String(ch, start, length);
current=false;
}
}
}
ItemList class is used to set , setter and getter methods to pass in values of arraylist and retrieve those array lists in the SAXParsing activity.
I hope this solution helps. :D

Why is my variable is null?

I do this
package file;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.LocatorImpl;
import org.xml.sax.helpers.XMLReaderFactory;
public class GetNatureSax implements ContentHandler {
private final static Logger _logger = Logger.getLogger(GetNatureSax.class.getName());
private boolean isCurrentElement = false;
private Locator locator;
private String _parameterValue = null;
public GetNatureSax() {
super();
locator = new LocatorImpl();
}
public String getValeurParametre() {
return _parameterValue;
}
public void setDocumentLocator(Locator value) {
locator = value;
}
public void startDocument() throws SAXException {}
public void endDocument() throws SAXException {}
public void startPrefixMapping(String prefix, String URI) throws SAXException {
}
public void endPrefixMapping(String prefix) throws SAXException {}
public void startElement(String nameSpaceURI, String localName, String rawName, Attributes attributs)
throws SAXException {
if (localName.equals("Nature")) {
isCurrentElement = true;
}
}
public void endElement(String nameSpaceURI, String localName, String rawName) throws SAXException {
if (localName.equals("Nature")) {
isCurrentElement = false;
}
}
public void characters(char[] ch, int start, int end) throws SAXException {
if (isCurrentElement) {
_parameterValue = new String(ch, start, end);
}
}
public void ignorableWhitespace(char[] ch, int start, int end) throws SAXException {
System.out.println("espaces inutiles rencontres : ..." + new String(ch, start, end) + "...");
}
public void processingInstruction(String target, String data) throws SAXException {
System.out.println("Instruction de fonctionnement : " + target);
System.out.println(" dont les arguments sont : " + data);
}
public void skippedEntity(String arg0) throws SAXException {}
public void parseFichier(String i_fichierATraiter) {
XMLReader saxReader;
try {
saxReader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
saxReader.setContentHandler(new GetNatureSax());
saxReader.parse(i_fichierATraiter);
System.out.println(_parameterValue);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
My XML:
...
<Reference>
<Nature>ACHAT</Nature>
<Statut>2</Statut>
<Type-Gest>RE</Type-Gest>
<Gest>RE_ELECTRA</Gest>
<Type-Res>D</Type-Res>
<Nb-h>24</Nb-h>
</Reference>
...
why when it execute this line
System.out.println(_parameterValue);
my variable is null and before when i debug my variable is not null
Because you instantiate a new GetNatureSax and give it to the SaxReader has a Content Handler.
So when the parsing has ended, it is the new GetNatureSax instance that have been modified and which have the field _parameterValue set, not the current instance (this).
Just modify your parseFichier method like this:
saxReader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
saxReader.setContentHandler(this); // here
saxReader.parse(i_fichierATraiter);
System.out.println("Found: " + getValeurParametre());
Using my debugger I can see you are using two GetNatureSax
saxReader.setContentHandler(new GetNatureSax());
This creates a second GetNatureSax object where is where the value is being set.
Changing it to
saxReader.setContentHandler(this);
fixed the problem.

Java Sax XML Parser, parsing custom "values" within XML tags?

I haven't worked much with XML before so maybe my ignorance on proper terminology is hurting me in my searches on how to do this. I have the code snippet below which I am using to parse an XML file like the one below. The problem is that it only picks up XML values within <Tag>Value</Tag> but not for the one below where I need to get the value of TagValue, which in this case would be "Russell Diamond".
I would appreciate if anyone can offer assistance as to how to get custom values like this. Thanks.
<Tag TagName="#Subject" TagDataType="Text" TagValue="Russell Diamond"/>
The snippet I am using:
public void printElementNames(String fileName) throws IOException {
//test write to file
FileWriter fstream = new FileWriter("/home/user/Desktop/readEDRMtest.txt");
final BufferedWriter out = new BufferedWriter(fstream);
//
try {
SAXParserFactory parserFact = SAXParserFactory.newInstance();
SAXParser parser = parserFact.newSAXParser();
System.out.println("XML Elements: ");
DefaultHandler handler = new DefaultHandler() {
public void startElement(String uri, String lName, String ele,
Attributes attributes) throws SAXException {
// print elements of xml
System.out.println(ele);
try {
out.write(ele);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void characters(char ch[], int start, int length)
throws SAXException {
System.out.println("Value : "
+ new String(ch, start, length));
try {
out.write("Value : "
+ new String(ch, start, length));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
You want to look into extracting attributes. Search on that and you'll find your answer.
The DefaultHandler class's startElement(...) method passes a parameter called attributes that refers to an Attribute object. The API for the Attribute interface will describe how to extract the information you need from this object.
For example:
out.write(attributes.getValue("TagValue"));
This is a stripped down and working version of your code snippet:
import java.io.File;
import java.io.IOException;
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;
public class SAX
{
public static void main(String[] args) throws IOException {
new SAX().printElementNames("Delete.xml");
}
public void printElementNames(String fileName) throws IOException
{
try {
SAXParserFactory parserFact = SAXParserFactory.newInstance();
SAXParser parser = parserFact.newSAXParser();
DefaultHandler handler = new DefaultHandler()
{
public void startElement(String uri, String lName, String ele, Attributes attributes) throws SAXException {
System.out.println(ele);
System.out.println(attributes.getValue("TagValue"));
}
public void characters(char ch[], int start, int length) throws SAXException {
System.out.println("Value : " + new String(ch, start, length));
}
};
parser.parse(new File(fileName), handler);
}catch(Exception e){
e.printStackTrace();
}
}
}
Content of Delete.xml
<Tag TagName="#Subject" TagDataType="Text" TagValue="Russell Diamond"/>
Further reading:
http://www.java-samples.com/showtutorial.php?tutorialid=152

Categories

Resources