how to extract element from cxf soap message - java

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;
}
}

Related

Not having a response when I call my web service GET request

I'm a student who needs help with a homework problem. The thing is that I wrote a rest web service using SAX parser in order to display a xml file that I have stored on the same folder of the project. The problem is that when I use the path I provided to it, it's not happening anything. I'm probably doing something wrong on my code. Here it is:
package com.crunchify.restjersey;
import java.io.IOException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
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;
#Path("/saxbooksxml")
public class SaxBooksXml {
public SaxBooksXml(){}
#GET
#Produces(MediaType.APPLICATION_XML)
public void gofindsaxbooks(){
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = null;
try {
saxParser = factory.newSAXParser();
} catch (ParserConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SAXException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DefaultHandler handler = new DefaultHandler(){
boolean bauthor = false;
boolean btitle = false;
boolean bgenre = false;
boolean bprice = false;
boolean bpublish_date = false;
boolean bdescription = false;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException{
if(qName.equalsIgnoreCase("author")){
bauthor = true;
}
if(qName.equalsIgnoreCase("title")){
btitle = true;
}
if(qName.equalsIgnoreCase("genre")){
bgenre = true;
}
if(qName.equalsIgnoreCase("price")){
bprice = true;
}
if(qName.equalsIgnoreCase("publish_date")){
bpublish_date = true;
}
if(qName.equalsIgnoreCase("description")){
bdescription = true;
}
}
public void endElement(String uri, String localName, String qName) throws SAXException{
}
public void characters(char ch[], int start, int lenght) throws SAXException{
if(bauthor){
System.out.println("author: "+new String(ch, start, lenght));
bauthor = false;
}
if(btitle){
System.out.println("title: "+new String(ch, start, lenght));
btitle = false;
}
if(bgenre){
System.out.println("genre: "+new String(ch, start, lenght));
bgenre = false;
}
if(bprice){
System.out.println("price: "+new String(ch, start, lenght));
bprice = false;
}
if(bpublish_date){
System.out.println("publish_date: "+new String(ch, start, lenght));
bpublish_date = false;
}
if(bdescription){
System.out.println("description: "+new String(ch, start, lenght)+"\n");
bdescription = false;
}
}
};
try {
saxParser.parse("Books.xml", handler);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is a print of part of the file I'm trying to parse. The idea is to display it on the browser exactly the same.
enter image description here
Your method gofindsaxbooks returns void
Change it like below:
#GET
#Produces(MediaType.APPLICATION_XML)
public Response gofindsaxbooks()
{
return Response.status(200).entity("Test XML created").build();
}

SOAPHandler: How to remove automatically added namespace/attribute from child element

I'm trying to setup a SOAPHandler on my server to convert this incoming request
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<getMachine xmlns="http://machine.soap.webservices.product.company.at/">
<machineId>92623-15853588</machineId>
</getMachine>
</S:Body>
</S:Envelope>
to this request.
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<enns1:getMachine xmlns:enns1="http://machine.soap.webservices.product.company.at/">
<machineId>92623-15853588</machineId>
</enns1:getMachine>
</S:Body>
</S:Envelope>
My SOAPHandler looks like this.
package at.company.product.webservices.soap;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
public class SOAPValidationHandler implements SOAPHandler<SOAPMessageContext> {
private static final String PREFIX = "enns1";
#Override
public boolean handleMessage(SOAPMessageContext context) {
System.out.println("Server : handleMessage()......");
Boolean isRequest = (Boolean) context
.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
// inbound
if (!isRequest) {
try {
SOAPMessage soapMsg = context.getMessage();
SOAPBody body = soapMsg.getSOAPBody();
Iterator<SOAPElement> it = body.getChildElements();
// Look for all body elements who have a "xmlns" attribute and
// add a namespace prefix to it
while (it.hasNext()) {
SOAPElement elem = it.next();
addNamespacePrefix(elem);
Iterator itChildren = elem.getChildElements();
while (itChildren.hasNext()) {
Object child = itChildren.next();
if (child instanceof SOAPElement) {
SOAPElement cElem = ((SOAPElement) child);
// TODO: Remove the namespace from the child
// cElem.removeNamespaceDeclaration(""); => Does not
// work
}
}
}
// tracking
soapMsg.writeTo(System.out);
} catch (SOAPException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
}
return true;
}
private void addNamespacePrefix(SOAPElement elem) throws SOAPException {
Iterator<Object> it = elem.getAllAttributes();
QName name = new QName("xmlns");
String value = elem.getAttributeValue(name);
if (value != null) {
elem.addNamespaceDeclaration(PREFIX, elem.getNamespaceURI());
elem.removeNamespaceDeclaration("");
elem.setPrefix(PREFIX);
}
}
#Override
public boolean handleFault(SOAPMessageContext context) {
System.out.println("Server : handleFault()......");
return true;
}
#Override
public void close(MessageContext context) {
System.out.println("Server : close()......");
}
#Override
public Set<QName> getHeaders() {
System.out.println("Server : getHeaders()......");
return null;
}
}
After the processing of the request with the SOAPHandler the request looks like this:
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<enns1:getMachine xmlns:enns1="http://machine.soap.webservices.product.company.at/">
<machineId xmlns="http://machine.soap.webservices.product.company.at/">92623-15853588</machineId>
</enns1:getMachine>
</S:Body>
</S:Envelope>
As you can see I'm able to add the namespace prefix to the <getMachine> tag but then it automatically adds the xmlns attribute to the child element <machineId>. How can I avoid or fix this?
After toying around with the API I came up with this solution. This solves the described case.
package at.company.product.webservices.soap;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import javax.xml.ws.soap.SOAPFaultException;
public class SOAPValidationHandler implements SOAPHandler<SOAPMessageContext> {
private static final String PREFIX = "enns1";
#Override
public boolean handleMessage(SOAPMessageContext context) {
Boolean isRequest = (Boolean) context
.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
// for response message only, true for outbound messages, false for
// inbound
if (!isRequest) {
try {
SOAPMessage soapMsg = context.getMessage();
SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope();
SOAPHeader soapHeader = soapEnv.getHeader();
// if no header, add one
if (soapHeader == null) {
soapHeader = soapEnv.addHeader();
// throw exception
generateSOAPErrMessage(soapMsg, "No SOAP header.");
}
SOAPBody body = soapMsg.getSOAPBody();
Iterator<SOAPElement> it = body.getChildElements();
while (it.hasNext()) {
SOAPElement elem = it.next();
addNamespacePrefix(elem);
Iterator itChildChildren = elem.getChildElements();
while (itChildChildren.hasNext()) {
Object obj = itChildChildren.next();
if ((obj instanceof SOAPElement)) {
SOAPElement soapElem = (SOAPElement) obj;
String name = soapElem.getElementName().getLocalName();
QName qName = new QName(name);
((SOAPElement) obj).setElementQName(qName);
}
}
}
// tracking
soapMsg.writeTo(System.out);
} catch (SOAPException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
}
}
// continue other handler chain
return true;
}
private void addNamespacePrefix(SOAPElement elem) throws SOAPException {
Iterator<Object> it = elem.getAllAttributes();
QName name = new QName("xmlns");
String value = elem.getAttributeValue(name);
if (value != null) {
elem.addNamespaceDeclaration(PREFIX, elem.getNamespaceURI());
elem.removeNamespaceDeclaration("");
elem.setPrefix(PREFIX);
}
}
#Override
public boolean handleFault(SOAPMessageContext context) {
return true;
}
#Override
public void close(MessageContext context) {
}
#Override
public Set<QName> getHeaders() {
return null;
}
private void generateSOAPErrMessage(SOAPMessage msg, String reason) {
try {
SOAPBody soapBody = msg.getSOAPPart().getEnvelope().getBody();
SOAPFault soapFault = soapBody.addFault();
soapFault.setFaultString(reason);
throw new SOAPFaultException(soapFault);
} catch (SOAPException e) {
}
}
}

Unable to retrieve complete text from an element using JAXB

I am trying to retrieve text in using unmarshalling example of JAXB but unable to retrieve the within ... tag. This is my first question and hence quite unsure on indenting my code, but here it goes :
LangFlag.java
package IDJAXBParser;
import java.util.List;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlType( propOrder = { "name", "description", "match", "context" } )
#XmlRootElement( name = "langFlag" )
public class LangFlag
{
String name;
public String getName()
{
return name;
}
#XmlAttribute( name = "name" )
public void setName( String name )
{
this.name = name;
}
String description;
public String getDescription()
{
return description;
}
#XmlElement( name = "description" )
public void setDescription( String description )
{
this.description = description;
}
String context;
#XmlAnyElement(BioHandler.class)
public String getContext()
{
return context;
}
public void setContext( String context )
{
this.context = context;
}
List<String> match;
public List<String> getMatch()
{
return match;
}
#XmlElement( name = "match" )
public void setMatch( List<String> match )
{
this.match = match;
}
#Override
public String toString()
{
StringBuffer str = new StringBuffer( "Name: " + getName() + "\n" );
str.append("Description:" + getDescription() + "\n");
str.append("Context:" + getContext() + "\n");
str.append("Match:" + getMatch() + "\n");
str.append("\n");
return str.toString();
}
}
ListOfLangFlags.java
package IDJAXBParser;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement( name = "listOfLangFlags" )
public class ListOfLangFlags
{
List<LangFlag> listOfLangFlags;
public List<LangFlag> getLangFlags()
{
return listOfLangFlags;
}
/**
* element that is going to be marshaled in the xml
*/
#XmlElement( name = "langFlag" )
public void setLangFlags( List<LangFlag> listOfLangFlags )
{
this.listOfLangFlags = listOfLangFlags;
}
public void add( LangFlag langFlag )
{
if( this.listOfLangFlags == null )
{
this.listOfLangFlags = new ArrayList<LangFlag>();
}
this.listOfLangFlags.add( langFlag );
}
#Override
public String toString()
{
StringBuffer str = new StringBuffer();
for( LangFlag langFlag : this.listOfLangFlags )
{
str.append( langFlag.toString() );
}
return str.toString();
}
}
UnMarshalJAXVBComplete.java
package IDJAXBParser;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import IDJAXBParser.ListOfLangFlags;
public class UnMarshalJAXVBComplete
{
public static void main( String[] args )
{
try
{
File file = new File( "testv1.xml" );
JAXBContext jaxbContext = JAXBContext.newInstance( ListOfLangFlags.class );
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
ListOfLangFlags langFlags = (ListOfLangFlags)jaxbUnmarshaller.unmarshal( file );
System.out.println( langFlags );
}
catch( JAXBException e )
{
e.printStackTrace();
}
}
}
This is my XML document :
<listOfLangFlags>
<langFlag name="Lang Flag Name">
<description>Lang Flag Description</description>
<context begin="0" end="100">I am so <span class="locality">blue </span>
I'm greener than purple. </context>
<suggestions/>
<match>I am so</match>
<match>blue</match>
</langFlag>
</listOfLangFlags>
BioHandler.java
package IDJAXBParser;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.annotation.DomHandler;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class BioHandler implements DomHandler<String, StreamResult> {
private static final String BIO_START_TAG = "<context>";
private static final String BIO_END_TAG = "</context>";
private StringWriter xmlWriter = new StringWriter();
public StreamResult createUnmarshaller(ValidationEventHandler errorHandler) {
xmlWriter.getBuffer().setLength(0);
return new StreamResult(xmlWriter);
}
public String getElement(StreamResult rt) {
String xml = rt.getWriter().toString();
int beginIndex = xml.indexOf(BIO_START_TAG) + BIO_START_TAG.length();
int endIndex = xml.indexOf(BIO_END_TAG);
return xml.substring(beginIndex, endIndex);
}
public Source marshal(String n, ValidationEventHandler errorHandler) {
try {
String xml = BIO_START_TAG + n.trim() + BIO_END_TAG;
StringReader xmlReader = new StringReader(xml);
return new StreamSource(xmlReader);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
Any help would be appreciated! Thanks in advance
Here is a DomHandler implementation which convert between DOM object and String.
import java.io.StringReader;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.annotation.DomHandler;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class BioHandler implements DomHandler<String, DOMResult> {
private StringBuilder buffer = new StringBuilder();
public DOMResult createUnmarshaller(ValidationEventHandler errorHandler) {
return new DOMResult();
}
public String getElement(DOMResult rt) {
Node n = rt.getNode();
Element ele = null;
if (n instanceof Document) {
ele = ((Document)n).getDocumentElement();
} else if (n instanceof DocumentFragment) {
ele = (Element)n.getChildNodes().item(0);
}
//StringBuilder sb = new StringBuilder(); //only capture the text under current node.
if (ele != null && "context".equals(ele.getLocalName())) {
try {
NodeList nl = (NodeList)XPathFactory.newInstance().newXPath()
.compile("descendant::text()").evaluate(ele, XPathConstants.NODESET);
int length = nl.getLength();
for (int i = 0; i < length; i++) {
buffer.append(nl.item(i).getTextContent());
}
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
}
//for problem tracing
//System.err.println("BioHandler.getElement(), ele="+ele.getLocalName() +", result=["+result+"]");
return buffer.toString();
}
public Source marshal(String n, ValidationEventHandler errorHandler) {
try {
String xml = "<context>" + n.trim() + "</context>";
StringReader xmlReader = new StringReader(xml);
return new StreamSource(xmlReader);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
During my testing, the unknown <suggestions/> element is handled by the same object. So I declare buffer as class variable and output captured content every time.

Problems connecting with Dbpedia Lookup web service

I'm trying to use the Lookup web service from DBpedia, but I'm finding difficulties because there's very little information on the web. I found a code example, but when I execute it, I get errors:
java.lang.NullPointerException
at tutorial.DBpediaLookupClient.containsSearchTerms(DBpediaLookupClient.java:111)
at tutorial.DBpediaLookupClient.endElement(DBpediaLookupClient.java:87)
at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:195)
at tutorial.DBpediaLookupClient.<init>(DBpediaLookupClient.java:56)
at tutorial.DBpediaLookupClient.main(DBpediaLookupClient.java:126)
HERE IS THE CODE:
package tutorial;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import com.sun.org.apache.bcel.internal.classfile.Attribute;
public class DBpediaLookupClient extends DefaultHandler {
/**
* #param args
*/
private List<Map<String, String>> variableBindings = new ArrayList<Map<String, String>>();
private Map<String, String> tempBinding = null;
private String lastElementName = null;
private String query = "";
public DBpediaLookupClient( String query ) throws Exception {
this.query = query;
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryClass=place&QueryString="+query);
try{
client.executeMethod(method);
System.out.println(method);
InputStream ins = method.getResponseBodyAsStream();
SAXParserFactory factory = SAXParserFactory.newInstance();
javax.xml.parsers.SAXParser sax = factory.newSAXParser();
sax.parse(ins, this);
}catch (HttpException he) {
System.err.println("Http error connecting to lookup.dbpedia.org");
}catch (IOException ioe) {
System.err.println("Unable to connect to lookup.dbpedia.org");
}catch (ParserConfigurationException e) {
System.out.println("O parser não foi configurado corretamente.");
e.printStackTrace();
}catch (SAXException e) {
System.out.println("Problema ao fazer o parse do arquivo.");
e.printStackTrace();
}
method.releaseConnection();
}
public void startElement(String uri, String localName, String qName, Attribute attributes) throws SAXException {
if (qName.equalsIgnoreCase("result")) {
tempBinding = new HashMap<String, String>();
}
lastElementName = qName;
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("result")) {
System.out.println("Qname:" + qName);
if (!variableBindings.contains(tempBinding) && containsSearchTerms(tempBinding))
variableBindings.add(tempBinding);
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
String s = new String(ch, start, length).trim();
if (s.length() > 0) {
if ("Description".equals(lastElementName)) tempBinding.put("Description", s);
if ("URI".equals(lastElementName)) tempBinding.put("URI", s);
if ("Label".equals(lastElementName)) tempBinding.put("Label", s);
}
}
public List<Map<String, String>> variableBindings() {
return variableBindings;
}
private boolean containsSearchTerms(Map<String, String> bindings) {
StringBuilder sb = new StringBuilder();
for (String value : bindings.values()){
sb.append(value); // do not need white space
}
String text = sb.toString().toLowerCase();
StringTokenizer st = new StringTokenizer(this.query);
while (st.hasMoreTokens()) {
if (text.indexOf(st.nextToken().toLowerCase()) == -1) {
return false;
}
}
return true;
}
public static void main(String[] args) {
try {
DBpediaLookupClient client = new DBpediaLookupClient("berlin");
} catch (Exception e) {
e.printStackTrace();
}
}
}
If anybody has any idea of what's wrong please help me. Or if any of you has any other code example it will help a lot too.
I talked to the author of the code and he corrected some minor bugs.
Here is the code:
Here is the link to the corrected code: https://github.com/mark-watson/java_practical_semantic_web/blob/master/src/com/knowledgebooks/info_spiders/DBpediaLookupClient.java
Thats a really good example of the use of the Dbpedia Lookup Service with Jena.
It works perfectly!
Just be careful about the SAX paserhandler which maybe gives you wrong length in characters method
so re structure the linked java code like following:
private StringBuffer fechaiBuffer;
public void startElement(...) {
fechaiBuffer = new StringBuffer();
}
public void characters(char ch[], int start, int length) {
fechaiBuffer.append(ch, start, length);
}
public void endElement(...) {
s = fechaiBuffer.toString();
// and so on
}

How to parse GPX files with SAXReader?

I'm trying to parse a GPX file. I tried it with JDOM, but it does not work very well.
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(filename);
Element root = document.getRootElement();
System.out.println("Root:\t" + root.getName());
List<Element> listTrks = root.getChildren("trk");
System.out.println("Count trk:\t" + listTrks.size());
for (Element tmpTrk : listTrks) {
List<Element> listTrkpts = tmpTrk.getChildren("trkpt");
System.out.println("Count pts:\t" + listTrkpts.size());
for (Element tmpTrkpt : listTrkpts) {
System.out.println(tmpTrkpt.getAttributeValue("lat") + ":" + tmpTrkpt.getAttributeValue("lat"));
}
}
I opened the example file (CC-BY-SA OpenStreetMap) and the output is just:
Root: gpx
Count trk: 0
What can I do? Should I us a SAXParserFactory (javax.xml.parsers.SAXParserFactory) and implement a Handler class?
Here is my gpx reader. It ignores some of the tags but I hope it will help.
package ch.perry.rando.geocode;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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;
/**
*
* #author perrym
*/
public class GpxReader extends DefaultHandler {
private static final DateFormat TIME_FORMAT
= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
private List<Trackpoint> track = new ArrayList<Trackpoint>();
private StringBuffer buf = new StringBuffer();
private double lat;
private double lon;
private double ele;
private Date time;
public static Trackpoint[] readTrack(InputStream in) throws IOException {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
SAXParser parser = factory.newSAXParser();
GpxReader reader = new GpxReader();
parser.parse(in, reader);
return reader.getTrack();
} catch (ParserConfigurationException e) {
throw new IOException(e.getMessage());
} catch (SAXException e) {
throw new IOException(e.getMessage());
}
}
public static Trackpoint[] readTrack(File file) throws IOException {
InputStream in = new FileInputStream(file);
try {
return readTrack(in);
} finally {
in.close();
}
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
buf.setLength(0);
if (qName.equals("trkpt")) {
lat = Double.parseDouble(attributes.getValue("lat"));
lon = Double.parseDouble(attributes.getValue("lon"));
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("trkpt")) {
track.add(Trackpoint.fromWGS84(lat, lon, ele, time));
} else if (qName.equals("ele")) {
ele = Double.parseDouble(buf.toString());
} else if (qName.equals("")) {
try {
time = TIME_FORMAT.parse(buf.toString());
} catch (ParseException e) {
throw new SAXException("Invalid time " + buf.toString());
}
}
}
#Override
public void characters(char[] chars, int start, int length)
throws SAXException {
buf.append(chars, start, length);
}
private Trackpoint[] getTrack() {
return track.toArray(new Trackpoint[track.size()]);
}
}
To read GPX files easily in Java see: http://sourceforge.net/p/gpsanalysis/wiki/Home/
example:
//gets points from a GPX file
final List points= GpxFileDataAccess.getPoints(new File("/path/toGpxFile.gpx"));
Ready to use, open source, and fully functional java GpxParser (and much more) here
https://sourceforge.net/projects/geokarambola/
Details here
https://plus.google.com/u/0/communities/110606810455751902142
With the above library parsing a GPX file is a one liner:
Gpx gpx = GpxFileIo.parseIn( "SomeGeoCollection.gpx" ) ;
Getting its points, routes or tracks trivial too:
for(Point pt: gpx.getPoints( ))
Location loc = new Location( pt.getLatitude( ), pt.getLongitude( ) ) ;

Categories

Resources