SAXBuilder build throws java.lang.StringIndexOutOfBoundsException - java

I am parsing this xml
<Root><Status>1</Status><Message>Get call Successful</Message><StatusCode></StatusCode><Item type = 'all' subtype = '0' ><subItem><rank>0</rank><name>humywe12</name><value>4500</value></subItem></Item></Root>
I am parsing it using this code
SAXBuilder builder = new SAXBuilder();
Document doc = null;
xml = xml.replaceAll("\t", "");
StringReader r = new StringReader(xml);
try {
doc = builder.build(r); <-----here it throws error
} catch (IOException e) {
// e.printStackTrace();
throw e;
} catch (Exception e) {
// e.printStackTrace();
throw e;
}
return doc;
}
builder.build(r) it throws exception StringIndexOutOfBoundsException.
Am I doing something wrong?
updated
ok I have removed only these tags "type = 'all' subtype = '0'" and now it is not giving java.lang.StringIndexOutOfBoundsException. Is there any problem with SAXBUILDER ??

I believe this was a know JDom bug. See http://www.jdom.org/pipermail/jdom-interest/2000-August/001227.html
You may want to check out one of the latest versions of jdom (as fits within your application).

Someone can try and identify the error for you, but what I would do is to start with very small xml, say
<Root></Root>
and keep adding to it till I get the error and then see what in the data caused the error.

Spaces are not allowed between the attribute name and the "=", or between the "=" and the attribute value.
See the spec.

Related

Jsoup is not Correctly Working

Hello guys i have an problem by Jsoup it is not working and i have no idea to figured it out here is the Code
private void getWebsite() {
Document doc = null;
try {
doc = Jsoup.connect("http://www.jean-clermont-schule.de/seite/90384/vertretungsplan.html").get();
Elements newsHeadlines = doc.select("content");
} catch (IOException e) {
e.printStackTrace();
}
}
And here is an Picture
Your code you provided is valid and compiles so the error is likely outside of what you've shown us. Looking at your picture, I guess you've imported the wrong Document class. Check your imports.
I am unable to add comment above.
I think that the code line Elements newsHeadlines = doc.select("content"); is wrong because content isn't tag for this link.
You must provide tag name with attribute and value being optional while using .select("");
You may try Elements newsHeadlines = doc.select("div[id=content]");

How to handle XML-related exceptions in Java?

I'm working on an appliation that needs to read, manipulate and write XML documents. While working with the XML API, I had to catch several exceptions, and I'm not sure how to handle them.
Consider the following code:
public static void removeWhitespace(Document document)
{
XPath xPath = getXPath();
NodeList emptyTextNodes;
try
{
XPathExpression expression = xPath.compile("//text()[normalize-space(.) = '']");
emptyTextNodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
}
catch (XPathExpressionException e)
{
// How to handle this?
return;
}
int nEmptyTextNodes = emptyTextNodes.getLength();
for (int i = 0; i < nEmptyTextNodes; ++i)
{
Node node = emptyTextNodes.item(i);
node.getParentNode().removeChild(node);
}
}
The documentation for XPath#compile says that XPathExpressionException will be thrown "If expression cannot be compiled". However, in this case, the expression is hardcoded and (presumably) valid, so this shouldn't happen. Since this is a checked exception, I have to handle it - but what should I do in the catch block?
Similarly, the documentation for XPathExpression#evaluate says that XPathExpressionException will be thrown "If the expression cannot be evaluated". Since I believe the expression is valid, the only way I think this could happen is if the caller passes an invalid Document. How should I handle that?
Consider this method:
public static String documentToString(Document document)
{
StringWriter writer = new StringWriter();
try
{
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(document), new StreamResult(writer));
}
catch (TransformerException e)
{
// What happens now?
return null;
}
String xml = writer.getBuffer().toString();
// No need to close the StringWriter
return xml;
}
TransformerFactory#newTransformer will throw a TransformerConfigurationException (would have linked the docs but SO won't let me) "When it is not possible to create a Transformer instance". How can this ever happen? How do I deal with it?
I could declare these exceptions to be thrown, but that would just move the problem somewhere else.
Under which circumstance will these exceptions be thrown, and how should I handle them?
Under which circumstance will these exceptions be thrown
These are possible causes for XML / XPath / XSLT related exceptions in the javax.xml packages:
invalid arguments passed to API methods
use of configurations which are optional and not supported by implementations
IO and encoding errors when reading a Source or writing a Result
Syntax errors when parsing a XML document, a XSLT stylesheet, a XPath expression
errors caused by executing an invalid operation (e.g. in XPath: calling a node-set function on a string or a number)
any other runtime error, most likely caused by a bug in the implementation
how should I handle them?
Like you treat all exceptions:
If can handle an exception, i.e. fix its cause or take some other action, then catch it and run the exception handler code in the catch block.
If you can't handle an exception let the caller handle it. For checked exceptions the simplest way is just to declare it in your methods throw clause.
You could also catch an exception to convert it to another type (another checked exception, a RuntimeException or even an Error). Converting to a RuntimeException (e.g. a IllegalStateException) can be used if you don't want to have a checked exception in the method signature.
To your examples:
There is probably no possibility that your methods will fail (No disk IO operations, no syntax errors, all arguments ok, etc.).
Still you can't handle the exception so you need to pass it to the caller.
In the case of the two methods it could be irritating (but still justifiable) if the methods would declare XPathExpressionException and TransformerException.
If you ask me I would catch the XPathExpressionException and TransformerException and rethrow them wrapped into a IllegalStateException.
This shouldn't happen [but], I have to handle it[, so] what should I do in the catch block?
If you really believe that it can not happen, If you are counting on it not to happen, and it turns out that you were wrong and the exception actually does happen, then that means your program is defective.
Here's the simplest handler for an exception that means the program is defective:
catch (TheException ex) {
assert false;
}
Here's a better one:
import org.apache.log4j.Logger;
...
static final Logger LOGGER = ...;
...
catch (TheException ex) {
LOGGER.fatal("Unexpected exception", ex);
myApplication.makeSafeToShutdown(...);
System.exit(1);
}

Verbose Rexster output/logging on error `null`

I use Titan in a small Ubuntu server cloud with size 3 and deployed a Rexster extension to to $TITAN_HOME/ext. However, if I try to call an endpoint of the extension I get
{"message":"An error occurred while generating the response object","error":null}
which is not very helpful. How can I get more verbose output to see what is going wrong here? In addition, error null seems strange to me. Any ideas what can cause it?
edit:
I wrapped the whole execution of the extension that causes the errors in a try-catch-everything block:
#ExtensionNaming(
namespace = GraphityExtension.EXT_NAMESPACE,
name = "unfollow")
public class RemoveFollowshipExtension extends GraphityExtension {
#ExtensionDefinition(
extensionPoint = ExtensionPoint.GRAPH)
#ExtensionDescriptor(
description = "Removes a followship between two users.")
public
ExtensionResponse
unfollow(
#RexsterContext RexsterResourceContext content,
#RexsterContext Graph graph,
#ExtensionRequestParameter(
name = "following",
description = "identifier of the user following") String idFollowing,
#ExtensionRequestParameter(
name = "followed",
description = "identifier of the user followed") String idFollowed) {
try {
Graphity graphity = getGraphityInstance((TitanGraph) graph);
Map<String, String> map = new HashMap<String, String>();
try {
map.put(KEY_RESPONSE_VALUE, String.valueOf(graphity
.removeFollowship(idFollowing, idFollowed)));
return ExtensionResponse.ok(new JSONObject(map));
} catch (UnknownFollowingIdException | UnknownFollowedIdException e) {
return ExtensionResponse.error(e);
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return ExtensionResponse.error(sw.toString());
}
}
but keep getting
{"message":"","error":null}
on client side. The rexstitan.log contains warnings concerning these errors:
com.tinkerpop.rexster.GraphResource - The [graphity:unfollow+*] extension raised an error response.
which is nice to know but not very detailed.
You usually get that error if there is some failure during invocation of your extension. Usually, the console where Rexster is running should provide some log messages that explain the cause and have a stack trace.
In the event that you are not seeing those for some reason, I would try to do your own logging in your extension and possibly trap exceptions in your code more generally (and logging in the catch clause) until you can see the error.

No return value after moving XSLT transformation to other project

I have the following piece of code to transform an xml document to a html page. It's nothing special, just that I use the saxon factory for transforming as I need a function from XSLT 2.0.
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult output = new StreamResult(bos);
StreamSource input = new StreamSource(new FileReader(TransformationTest.class.getResource(sourceFileName).getFile()));
StreamSource stylesheet = new StreamSource(TransformationTest.class.getResourceAsStream(STYLESHEET));
Transformer tr = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", null).newTransformer(stylesheet);
tr.transform(input, output);
return bos.toString();
} catch (TransformerException e) {
throw new RuntimeException("XSL-Transform: Error while transforming the document.");
} catch (FileNotFoundException e) {
throw new RuntimeException("XSL-Transform: Error while reading the source file.");
}
The code is working fine in a seperate project with saxon added as a dependency. I tried it with different inputs and everytime I got the right output.
Now I tried adding it to a bigger project which has many many other libraries in the classpath and suddenly the code stops working. The output is just blank, no exceptions, no error messages, just a blank string that will be returned. I'm not an expert of what is happening in the transformer, so I need a bit of help here. What exactly could be reason for this behaviour and how can I fix it?

How to get data from an URL xml-file?

I'm making an android app - where I need to have weather-information. I've found this from yahoo weather. It's an XML and I want information such as: "day", "low" and "high".
Refer: http://weather.yahooapis.com/forecastrss?w=12718298&u=c
<yweather:forecast day="Sun" date="19 Feb 2012" low="-2" high="3" text="Clear" code="31"/>
(Line can be found in the bottom of the link)
I have no idea how to do this - please help. Source codes, examples and clues will be appreciated.
Here's the solution for future users:
InputStream inputXml = null;
try
{
inputXml = new URL("http://weather.yahooapis.com/forecastrss?w=12718298&u=c").openConnection().getInputStream();
DocumentBuilderFactory factory = DocumentBuilderFactory.
newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(inputXml);
NodeList nodi = doc.getElementsByTagName("yweather:forecast");
if (nodi.getLength() > 0)
{
Element nodo = (Element)nodi.item(0);
String strLow = nodo.getAttribute("low");
Element nodo1 = (Element)nodi.item(0);
String strHigh = nodo1.getAttribute("high");
System.out.println("Temperature low: " + strLow);
System.out.println("Temperature high: " + strHigh);
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
finally
{
try
{
if (inputXml != null)
inputXml.close();
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
}
It's been a couple of years since I used XML in Android, but this was quite helpful to me when I started out: anddev.org
The link seems to be a feed. (which is XML, obviously). There are many feed-reader APIs in Java. So, here you go
Read feed documentation, http://developer.yahoo.com/weather/
Read how to parse/read the feed, Rome Library to read feeds Java
Pull out your desired fields.
I guess this is already done. (easily found on Google) http://www.javahouse.altervista.org/gambino/Articolo_lettura_feed_da_java_en.html

Categories