HTTP 500 error when sending XML to server - java

I am trying to send an XML file to my RESTful web server, and receive a XML file in return, however, I am getting a 500 error.
java.io.IOException: Server returned HTTP response code: 500 for URL:
http://sps-psa-240:8080/NMCJWS/rest/jmsmon2/pub at
sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
at SendXML.send(SendXML.java:151)
at SendXML.main(SendXML.java:39)
Line 151 is InputStream response = uc.getInputStream();
If I uncomment System.out.println(((HttpURLConnection) uc).getResponseCode());,
then I get the same error on OutputStreamWriter out = new OutputStreamWriter(uc.getOutputStream());
I know the server works because a coworker has this working in Obj-C.
Here is my code:
public class SendXML
{
public static void main(String[] args) throws SAXException, XPathExpressionException, ParserConfigurationException,
IOException, TransformerException
{
String xml = generateXML("AC24", "/fa/gdscc/dss24-apc");
send("localhost", xml);
}
public static String generateXML(String conn, String funcAddr) throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException, TransformerException
{
/*
* <?xml version="1.0" encoding="UTF-8"?>
<JMSMON2Req>
<SubItem UID="iPAD-2031e616-de74-44a7-9292-3745d2b1ba21">
<FuncAddr>/fa/gdscc/con1-ac25</FuncAddr>
<ItemName>AZANG</ItemName>
<ItemName>ELANG</ItemName>
<Metadata key="UID">iPAD-2031e616-de74-44a7-9292-3745d2b1ba21</Metadata>
<Metadata key="CONN">1</Metadata>
</SubItem>
</JMSMON2Req>
*/
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("http://sps-psa-240:8080/NMCWS/rest/conn/subsys/prof?ss=" + conn + "&pt=IPAD_DASHBOARD");
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/SubscrProf/DataItem/DataItemName");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
//build xml
Document output = builder.newDocument();
//create root
org.w3c.dom.Element root = output.createElement("JMSMON2Req");
output.appendChild(root);
//create subitem
org.w3c.dom.Element subItemNode = output.createElement("SubItem");
subItemNode.setAttribute("UID", "IPAD-CN1-DSS26-SC151-PN230-AC26");
root.appendChild(subItemNode);
//create funcAddr
org.w3c.dom.Element funcAddrNode = output.createElement("FuncAddr");
Text text = output.createTextNode(funcAddr);
funcAddrNode.appendChild(text);
subItemNode.appendChild(funcAddrNode);
//create itemname
for (int i = 0; i < nodes.getLength(); i++)
{
org.w3c.dom.Element itemNameNode = output.createElement("SubItem");
text = output.createTextNode(nodes.item(i).getTextContent());
itemNameNode.appendChild(text);
subItemNode.appendChild(itemNameNode);
}
//create metadata uid
org.w3c.dom.Element metaDataNode = output.createElement("Metadata");
metaDataNode.setAttribute("key", "UID");
text = output.createTextNode("IPAD-CN1-DSS26-SC151-PN230-AC26");
metaDataNode.appendChild(text);
subItemNode.appendChild(metaDataNode);
//create metadata conn
org.w3c.dom.Element metaDataNode2 = output.createElement("Metadata");
metaDataNode2.setAttribute("key", "CONN");
text = output.createTextNode("4");
metaDataNode2.appendChild(text);
subItemNode.appendChild(metaDataNode2);
/////////////////
//Output the XML
//set up a transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult out = new StreamResult(sw);
DOMSource source = new DOMSource(output);
trans.transform(source, out);
String xmlString = sw.toString();
//print xml
System.out.println("Here's the xml:\n" + xmlString);
return xmlString;
}
public static void send(String urladdress, String file) throws MalformedURLException, IOException
{
String charset = "UTF-8";
String s = URLEncoder.encode(file, charset);
// Open the connection and prepare to POST
URLConnection uc = new URL(urladdress).openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("Accept-Charset", charset);
uc.setRequestProperty("Content-Type","text/xml");
try
{
//System.out.println(((HttpURLConnection) uc).getResponseCode());
OutputStreamWriter out = new OutputStreamWriter(uc.getOutputStream());
out.write(s);
out.flush();
InputStream response = uc.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(response));
String line;
while ((line = r.readLine()) != null)
System.out.println(line);
out.close();
response.close();
}
catch (IOException e)
{
e.printStackTrace(); // should do real exception handling
}
}
}

I figured out my problem. I had to encode xmlString in UTF-8

Look at the logs on the server. What is causing the 500 error?
Is this a RESTful web service, or a SOAP web service you're submitting to?
Consider using some sort of XML<->Object framework like JAXB or XStream.
Consider using some sort of RESTful web service framework like Jersey or RestEasy.
Consider using some sort of SOAP framework like JAX-WS or Apache Axis

Make sure you are using the right encoding.
URLEncoder.encode is making the content safe for transfer as 'application/x-www-form-urlencoded', but you probably want to use UTF-8.
Also, new OutputStreamWriter(...) should specify the desired encoding. You are currently using the standard platform encoding which is probably iso-8859-1.
Third, don't try to mess around with URLConnection yourself, if there are plenty of libs around there, that can make you life easier.
Here is the send method done in Resty (Disclaimer: I'm the author of it). HTTPClient is another choice to consider as are other client-side libraries.
import us.monoid.web.Resty;
import static us.monoid.web.Resty.*;
Resty r = new Resty();
String result = r.text(urladdress, new Content("text/xml", file.getBytes("UTF-8"))).toString();

Related

Modified XML file not saving java

I am making a web application, and I need to make a log. I am storing this log as an xml file.
These are my paths:
log.xml -> org.codealizer.quizme.resources
Servlet -> org.codealizer.quizme.servlets
When my application runs, it gives me a success result, but the xml file is not modified.
This is my code to modify the xml file:
private void createLog(HttpServletRequest request,
HttpServletResponse response, PrintWriter out) {
String ipAddress = request.getRemoteAddr();
int port = request.getRemotePort();
String clientInformation = request.getHeader("user-agent");
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = factory.newDocumentBuilder();
Document doc = dBuilder.parse(getClass().getResourceAsStream(
"/org/codealizer/quizme/resources/log.xml"));
doc.getDocumentElement().normalize();
Node log = doc.getFirstChild();
Element item = doc.createElement("item");
Element time = doc.createElement("time");
time.appendChild(doc.createTextNode("" + System.currentTimeMillis()));
item.appendChild(time);
Element access = doc.createElement("access");
access.appendChild(doc.createTextNode(getClass().getName()));
item.appendChild(access);
Element address = doc.createElement("address");
address.appendChild(doc.createTextNode(ipAddress + ":" + port));
item.appendChild(address);
Element client = doc.createElement("client");
client.appendChild(doc.createTextNode(clientInformation));
item.appendChild(client);
log.appendChild(item);
// Update
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(getClass().getResource(
"/org/codealizer/quizme/resources/log.xml").getFile());
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
} catch (SAXException | IOException | ParserConfigurationException
| TransformerException e) {
out.println(e.getMessage());
}
This is my current log.xml file
<?xml version="1.0" encoding="UTF-8"?>
<log></log>
Could someone please help me fix this issue? Thx a lot :)

How to read XML server response in JavaScript?

I work on a web project and at this point I need to pass a hard-coded xml from Java to JavaScript to parse that xml; the problem is that I don't know exactly how to do this. As shown below, my xml is stored in a String variable, so I need to pass this variable to JavaScript.
I'm using tomcat as a server.
Java Code - that creates xml:
#Path("/getXml")
#GET
#Produces(MediaType.TEXT_XML)
#Consumes(MediaType.TEXT_PLAIN)
public String getXml(#Context HttpServletRequest request) throws TransformerConfigurationException, TransformerException{
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document document = docBuilder.newDocument();
Element rootElement = document.createElement("news-counts");
document.appendChild(rootElement);
int j=12;
for(int i=1; i<10; i++) {
Element item = document.createElement("item");
rootElement.appendChild(item);
item.setAttribute("count", "" + j);
item.setAttribute("date", "201408" + "0" + i);
j=j+2;
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
String xmlOutput = writer.getBuffer().toString().replaceAll("\n|\r", "");
// return Response.status(Status.NOT_ACCEPTABLE).entity("xmlOutput").build();
//System.out.println(xmlOutput);
return xmlOutput;
} catch (ParserConfigurationException ex) {
Logger.getLogger(Searcher.class.getName()).log(Level.SEVERE, null, ex);
} finally {
return null;
}
}
JavaScript code - how I tried to acces the xmlOutput variable
function test() {
var r=new XMLHttpRequest();
r.open("GET", "http://localhost:8080/WebApplication6/tavi/searcher/getXml" , false);
r.send();
var responseText = r.responseText;
alert(responseText);
}
You can easily use Jquery for parsing xml. Heres another one Easy XML Consumption using jQuery. If you prefer pure javascript look at this thread.
Using Jquery:
var xml = $.parseXML("<news-counts><item count=\"1\" date=\"2014-08-13 00:00:00\">Stuff</item><item count=\"2\" date=\"2014-08-13 01:01:01\">Bar</item></news-counts>");
var x = xml.getElementsByTagName('item');
for(i=0;i<x.length;i++)
{
console.log(x.item(i).textContent); //Stuff Bar
console.log(x.item(i).getAttribute('count')); //1 2
console.log(x.item(i).getAttribute('date')); //2014-08-13 00:00:00 2014-08-13 01:01:01
}
Using javascript:
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
var xml = parseXml("<news-counts><item count=\"1\" date='2014-08-13 00:00:00'>Stuff</item><item count=\"2\" date='2014-08-13 00:00:00'>Bar</item></news-counts>");//get attributes or contents after this line
You can parse your xml in javascript by this way -
var content = xml_string;//your xml string variable
if (typeof content == 'string') {
content = ( new window.DOMParser() ).parseFromString(content, "text/xml");
}
You can parse xml by jQuery. Ref: http://www.jquerybyexample.net/2012/04/read-and-process-xml-using-jquery-ajax.html

null pointer exception on getNodeValue() when parsing XML web page - android

I looked over several of the answers posted here, but I can't find the answer I need. It may have to do with the web site itself, but I don't think it is.
I'm trying to parse an XML on a web site and I'm getting a null pointer exception error.
I run the parsing is a separate thread following Google demand when reading from the web.
please see my code and try to help.
class BackgroundTask1 extends AsyncTask<String, Void, String[]> {
protected String[] doInBackground(String... url) {
new HttpGet();
new StringBuffer();
InputStream is = null;
HttpURLConnection con = null;
try {
//Log.d("eyal", "URL: " + boiUrl);
URL url1 = new URL("http://www.boi.org.il/currency.xml");
con = (HttpURLConnection)url1.openConnection();
con.setRequestMethod("GET");
con.connect();
is = con.getInputStream();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(is);
NodeList lastVld = doc.getElementsByTagName("LAST_UPDATE");
String lastV = lastVld.item(0).getFirstChild().getNodeValue();
}
catch (Exception e) {
e.printStackTrace();
}
I get the error on the last line.
Thanks for your help.
This code worked for me
InputStream is = null;
HttpURLConnection con = null;
try {
URL url1 = new URL("http://www.boi.org.il/currency.xml");
con = (HttpURLConnection)url1.openConnection();
con.setRequestMethod("GET");
con.connect();
is = con.getInputStream();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(is);
NodeList lastVld = doc.getElementsByTagName("LAST_UPDATE");
Element elem = (Element) lastVld.item(0);
String lastV = elem.getTextContent();
System.out.println(lastV);
} catch (Exception e) {
e.printStackTrace();
}
I verified I was getting good content by adding a transformer to print out the results to the console.
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer xform = tFactory.newTransformer();
xform.transform(new DOMSource(doc), new StreamResult(System.out));
There was a couple times I tried running where elem came out null, which I think had something to do with some bad content being retrieved from the URL. This was the content that was printed by the transformer.
<html>
<body>
<script>document.cookie='iiiiiii=11a887d6iiiiiii_11a887d6; path=/';window.location.href=window.location.href;</script>
</body>
</html>
I noticed that if I had this file open in my browser, the code would all of a sudden quit working until I refreshed the page, then it started giving me the right output.
I suspect there's an issue with something at this URL, because when it works properly, this code works fine.
Good luck...
You only have one LAST_UPDATE tag in your xml and it has an inner value, so try just using the node value from the Node Class you get from item(0)
String lastV = lastVld.item(0).getNodeValue();
HTHs
There is no node returned for that tag name. You may want to first check the size of the lastVld and then try to access the items in there.

Not able to write files from one xml to another xml using java

Actually i need to replace some of the tags in source xml and write the files as new one. Here my code works fine but now am not able to open the output xml. In the output xml i have some tamil words. Is it the reason for file not opening
public class dxml {
public static StringBuffer sb = new StringBuffer() ;
public static void main(String [] args) throws Exception {
File xmlFile = new File("/home/dev702/Desktop/axl/Data Entry.xml");
BufferedReader br = new BufferedReader(
new FileReader("/home/dev702/Desktop/axl/Data Entry.xml"));
String line = null;
int linecount = 1;
FileWriter fw;
BufferedWriter bw = null;
fw = new FileWriter("/home/dev702/Desktop/axl/Data_Entry_OPT.xml") ;
bw = new BufferedWriter(fw);
while((line = br.readLine())!= null)
{
if(linecount > 2)
{
line = line.replaceAll("Data_x0020_Entry_x0020_Date",
"DataEntryDate");
//bw.write(line);
}
bw.write(line);
linecount++;
System.out.println(line);
}
bw.close();
fw.close();
}
}
If you want to transform XML to another form of XML you should be using XSLT's to achieve this. Java has support for transforming two documents...below is a code snippet of how to acheive this.
The premise really is you get your original XML into a document, set up the XSLT to use and transform it into another document.
The scope of using XSLT is outside of this reply. I recommend using Altova's excellent XMLSpy for testing your XSLT's.
public class Mapper {
public Document convert(Document originalDocument, Resource xsltResource) throws TransformerException, ParserConfigurationException,
JAXBException, IOException, SAXException {
/**
* You'll need to create your documentBuilder to build the new document.
*/
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
/**
* Set up your transformer factory, you'll need to pass your XSLT file in as an inputstream
* I've passed it in here as a method arg and it's a Spring Resource but you can do it however you like.
*/
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory
.newTransformer(new StreamSource(xsltResource.getInputStream()));
/**
* Set the encoding to avoid headaches.
*/
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
/**
* Create a BAoS to hold your original document.
*/
ByteArrayOutputStream os = new ByteArrayOutputStream();
transformer.transform(new DOMSource(originalDocument), new StreamResult(os));
/**
* Do the transformation.
*/
return documentBuilder.parse(new InputSource(new StringReader(os.toString("UTF-8"))));
}
}

Bad Characters when parsing GML in Java

I'm using the org.w3c.dom package to parse the gml schemas (http://schemas.opengis.net/gml/3.1.0/base/).
When I parse the gmlBase.xsd schema and then save it back out, the quote characters around GeometryCollections in the BagType complex type come out converted to bad characters (See code below).
Is there something wrong with how I'm parsing or saving the xml, or is there something in the schema that is off?
Thanks,
Curtis
public static void main(String[] args) throws IOException
{
File schemaFile = File.createTempFile("gml_", ".xsd");
FileUtils.writeStringToFile(schemaFile, getSchema(new URL("http://schemas.opengis.net/gml/3.1.0/base/gmlBase.xsd")));
System.out.println("wrote file: " + schemaFile.getAbsolutePath());
}
public static String getSchema(URL schemaURL)
{
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(IOUtils.toString(schemaURL.openStream()))));
Element rootElem = doc.getDocumentElement();
rootElem.normalize();
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
ByteArrayOutputStream xmlOutStream = new ByteArrayOutputStream();
StreamResult result = new StreamResult(xmlOutStream);
transformer.transform(source, result);
return xmlOutStream.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
I'm suspicious of this line:
Document doc = db.parse(new InputSource(
new StringReader(IOUtils.toString(schemaURL.openStream()))));
I don't know what IOUtils.toString does here but presumably it's assuming a particular encoding, without taking account of the XML declaration.
Why not just use:
Document doc = db.parse(schemaURL.openStream());
Likewise your FileUtils.writeStringToFile doesn't appear to specify a character encoding... which encoding does it use, and why encoding is in the StreamResult?

Categories