Handling errors in ANTLR4 - java

The default behavior when the parser doesn't know what to do is to print messages to the terminal like:
line 1:23 missing DECIMAL at '}'
This is a good message, but in the wrong place. I'd rather receive this as an exception.
I've tried using the BailErrorStrategy, but this throws a ParseCancellationException without a message (caused by a InputMismatchException, also without a message).
Is there a way I can get it to report errors via exceptions while retaining the useful info in the message?
Here's what I'm really after--I typically use actions in rules to build up an object:
dataspec returns [DataExtractor extractor]
#init {
DataExtractorBuilder builder = new DataExtractorBuilder(layout);
}
#after {
$extractor = builder.create();
}
: first=expr { builder.addAll($first.values); } (COMMA next=expr { builder.addAll($next.values); })* EOF
;
expr returns [List<ValueExtractor> values]
: a=atom { $values = Arrays.asList($a.val); }
| fields=fieldrange { $values = values($fields.fields); }
| '%' { $values = null; }
| ASTERISK { $values = values(layout); }
;
Then when I invoke the parser I do something like this:
public static DataExtractor create(String dataspec) {
CharStream stream = new ANTLRInputStream(dataspec);
DataSpecificationLexer lexer = new DataSpecificationLexer(stream);
CommonTokenStream tokens = new CommonTokenStream(lexer);
DataSpecificationParser parser = new DataSpecificationParser(tokens);
return parser.dataspec().extractor;
}
All I really want is
for the dataspec() call to throw an exception (ideally a checked one) when the input can't be parsed
for that exception to have a useful message and provide access to the line number and position where the problem was found
Then I'll let that exception bubble up the callstack to whereever is best suited to present a useful message to the user--the same way I'd handle a dropped network connection, reading a corrupt file, etc.
I did see that actions are now considered "advanced" in ANTLR4, so maybe I'm going about things in a strange way, but I haven't looked into what the "non-advanced" way to do this would be since this way has been working well for our needs.

Since I've had a little bit of a struggle with the two existing answers, I'd like to share the solution I ended up with.
First of all I created my own version of an ErrorListener like Sam Harwell suggested:
public class ThrowingErrorListener extends BaseErrorListener {
public static final ThrowingErrorListener INSTANCE = new ThrowingErrorListener();
#Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e)
throws ParseCancellationException {
throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + msg);
}
}
Note the use of a ParseCancellationException instead of a RecognitionException since the DefaultErrorStrategy would catch the latter and it would never reach your own code.
Creating a whole new ErrorStrategy like Brad Mace suggested is not necessary since the DefaultErrorStrategy produces pretty good error messages by default.
I then use the custom ErrorListener in my parsing function:
public static String parse(String text) throws ParseCancellationException {
MyLexer lexer = new MyLexer(new ANTLRInputStream(text));
lexer.removeErrorListeners();
lexer.addErrorListener(ThrowingErrorListener.INSTANCE);
CommonTokenStream tokens = new CommonTokenStream(lexer);
MyParser parser = new MyParser(tokens);
parser.removeErrorListeners();
parser.addErrorListener(ThrowingErrorListener.INSTANCE);
ParserRuleContext tree = parser.expr();
MyParseRules extractor = new MyParseRules();
return extractor.visit(tree);
}
(For more information on what MyParseRules does, see here.)
This will give you the same error messages as would be printed to the console by default, only in the form of proper exceptions.

When you use the DefaultErrorStrategy or the BailErrorStrategy, the ParserRuleContext.exception field is set for any parse tree node in the resulting parse tree where an error occurred. The documentation for this field reads (for people that don't want to click an extra link):
The exception which forced this rule to return. If the rule successfully completed, this is null.
Edit: If you use DefaultErrorStrategy, the parse context exception will not be propagated all the way out to the calling code, so you'll be able to examine the exception field directly. If you use BailErrorStrategy, the ParseCancellationException thrown by it will include a RecognitionException if you call getCause().
if (pce.getCause() instanceof RecognitionException) {
RecognitionException re = (RecognitionException)pce.getCause();
ParserRuleContext context = (ParserRuleContext)re.getCtx();
}
Edit 2: Based on your other answer, it appears that you don't actually want an exception, but what you want is a different way to report the errors. In that case, you'll be more interested in the ANTLRErrorListener interface. You want to call parser.removeErrorListeners() to remove the default listener that writes to the console, and then call parser.addErrorListener(listener) for your own special listener. I often use the following listener as a starting point, as it includes the name of the source file with the messages.
public class DescriptiveErrorListener extends BaseErrorListener {
public static DescriptiveErrorListener INSTANCE = new DescriptiveErrorListener();
#Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
int line, int charPositionInLine,
String msg, RecognitionException e)
{
if (!REPORT_SYNTAX_ERRORS) {
return;
}
String sourceName = recognizer.getInputStream().getSourceName();
if (!sourceName.isEmpty()) {
sourceName = String.format("%s:%d:%d: ", sourceName, line, charPositionInLine);
}
System.err.println(sourceName+"line "+line+":"+charPositionInLine+" "+msg);
}
}
With this class available, you can use the following to use it.
lexer.removeErrorListeners();
lexer.addErrorListener(DescriptiveErrorListener.INSTANCE);
parser.removeErrorListeners();
parser.addErrorListener(DescriptiveErrorListener.INSTANCE);
A much more complicated example of an error listener that I use to identify ambiguities which render a grammar non-SLL is the SummarizingDiagnosticErrorListener class in TestPerformance.

What I've come up with so far is based on extending DefaultErrorStrategy and overriding it's reportXXX methods (though it's entirely possible I'm making things more complicated than necessary):
public class ExceptionErrorStrategy extends DefaultErrorStrategy {
#Override
public void recover(Parser recognizer, RecognitionException e) {
throw e;
}
#Override
public void reportInputMismatch(Parser recognizer, InputMismatchException e) throws RecognitionException {
String msg = "mismatched input " + getTokenErrorDisplay(e.getOffendingToken());
msg += " expecting one of "+e.getExpectedTokens().toString(recognizer.getTokenNames());
RecognitionException ex = new RecognitionException(msg, recognizer, recognizer.getInputStream(), recognizer.getContext());
ex.initCause(e);
throw ex;
}
#Override
public void reportMissingToken(Parser recognizer) {
beginErrorCondition(recognizer);
Token t = recognizer.getCurrentToken();
IntervalSet expecting = getExpectedTokens(recognizer);
String msg = "missing "+expecting.toString(recognizer.getTokenNames()) + " at " + getTokenErrorDisplay(t);
throw new RecognitionException(msg, recognizer, recognizer.getInputStream(), recognizer.getContext());
}
}
This throws exceptions with useful messages, and the line and position of the problem can be gotten from either the offending token, or if that's not set, from the current token by using ((Parser) re.getRecognizer()).getCurrentToken() on the RecognitionException.
I'm fairly happy with how this is working, though having six reportX methods to override makes me think there's a better way.

For anyone interested, here's the ANTLR4 C# equivalent of Sam Harwell's answer:
using System; using System.IO; using Antlr4.Runtime;
public class DescriptiveErrorListener : BaseErrorListener, IAntlrErrorListener<int>
{
public static DescriptiveErrorListener Instance { get; } = new DescriptiveErrorListener();
public void SyntaxError(TextWriter output, IRecognizer recognizer, int offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e) {
if (!REPORT_SYNTAX_ERRORS) return;
string sourceName = recognizer.InputStream.SourceName;
// never ""; might be "<unknown>" == IntStreamConstants.UnknownSourceName
sourceName = $"{sourceName}:{line}:{charPositionInLine}";
Console.Error.WriteLine($"{sourceName}: line {line}:{charPositionInLine} {msg}");
}
public override void SyntaxError(TextWriter output, IRecognizer recognizer, Token offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e) {
this.SyntaxError(output, recognizer, 0, line, charPositionInLine, msg, e);
}
static readonly bool REPORT_SYNTAX_ERRORS = true;
}
lexer.RemoveErrorListeners();
lexer.AddErrorListener(DescriptiveErrorListener.Instance);
parser.RemoveErrorListeners();
parser.AddErrorListener(DescriptiveErrorListener.Instance);

For people who use Python, here is the solution in Python 3 based on Mouagip's answer.
First, define a custom error listener:
from antlr4.error.ErrorListener import ErrorListener
from antlr4.error.Errors import ParseCancellationException
class ThrowingErrorListener(ErrorListener):
def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):
ex = ParseCancellationException(f'line {line}: {column} {msg}')
ex.line = line
ex.column = column
raise ex
Then set this to lexer and parser:
lexer = MyScriptLexer(script)
lexer.removeErrorListeners()
lexer.addErrorListener(ThrowingErrorListener())
token_stream = CommonTokenStream(lexer)
parser = MyScriptParser(token_stream)
parser.removeErrorListeners()
parser.addErrorListener(ThrowingErrorListener())
tree = parser.script()

Related

Stackoverflowerror while using distinct in apache spark

I use Spark 2.0.1.
I am trying to find distinct values in a JavaRDD as below
JavaRDD<String> distinct_installedApp_Ids = filteredInstalledApp_Ids.distinct();
I see that this line is throwing the below exception
Exception in thread "main" java.lang.StackOverflowError
at org.apache.spark.rdd.RDD.checkpointRDD(RDD.scala:226)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:246)
at org.apache.spark.rdd.UnionRDD$$anonfun$1.apply(UnionRDD.scala:84)
at org.apache.spark.rdd.UnionRDD$$anonfun$1.apply(UnionRDD.scala:84)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
at scala.collection.immutable.List.foreach(List.scala:318)
at scala.collection.TraversableLike$class.map(TraversableLike.scala:244)
at scala.collection.AbstractTraversable.map(Traversable.scala:105)
at org.apache.spark.rdd.UnionRDD.getPartitions(UnionRDD.scala:84)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:248)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:246)
at scala.Option.getOrElse(Option.scala:120)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:246)
at org.apache.spark.rdd.UnionRDD$$anonfun$1.apply(UnionRDD.scala:84)
at org.apache.spark.rdd.UnionRDD$$anonfun$1.apply(UnionRDD.scala:84)
..........
The same stacktrace is repeated again and again.
The input filteredInstalledApp_Ids has large input with millions of records.Will thh issue be the number of records or is there a efficient way to find distinct values in JavaRDD. Any help would be much appreciated. Thanks in advance. Cheers.
Edit 1:
Adding the filter method
JavaRDD<String> filteredInstalledApp_Ids = installedApp_Ids
.filter(new Function<String, Boolean>() {
#Override
public Boolean call(String v1) throws Exception {
return v1 != null;
}
}).cache();
Edit 2:
Added the method used to generate installedApp_Ids
public JavaRDD<String> getIdsWithInstalledApps(String inputPath, JavaSparkContext sc,
JavaRDD<String> installedApp_Ids) {
JavaRDD<String> appIdsRDD = sc.textFile(inputPath);
try {
JavaRDD<String> appIdsRDD1 = appIdsRDD.map(new Function<String, String>() {
#Override
public String call(String t) throws Exception {
String delimiter = "\t";
String[] id_Type = t.split(delimiter);
StringBuilder temp = new StringBuilder(id_Type[1]);
if ((temp.indexOf("\"")) != -1) {
String escaped = temp.toString().replace("\\", "");
escaped = escaped.replace("\"{", "{");
escaped = escaped.replace("}\"", "}");
temp = new StringBuilder(escaped);
}
// To remove empty character in the beginning of a
// string
JSONObject wholeventObj = new JSONObject(temp.toString());
JSONObject eventJsonObj = wholeventObj.getJSONObject("eventData");
int appType = eventJsonObj.getInt("appType");
if (appType == 1) {
try {
return (String.valueOf(appType));
} catch (JSONException e) {
return null;
}
}
return null;
}
}).cache();
if (installedApp_Ids != null)
return sc.union(installedApp_Ids, appIdsRDD1);
else
return appIdsRDD1;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I assume the main dataset is in inputPath. It appears that it's a comma-separated file with JSON-encoded values.
I think you could make your code a bit simpler by combination of Spark SQL's DataFrames and from_json function. I'm using Scala and leave converting the code to Java as a home exercise :)
The lines where you load a inputPath text file and the line parsing itself can be as simple as the following:
import org.apache.spark.sql.SparkSession
val spark: SparkSession = ...
val dataset = spark.read.csv(inputPath)
You can display the content using show operator.
dataset.show(truncate = false)
You should see the JSON-encoded lines.
It appears that the JSON lines contain eventData and appType fields.
val jsons = dataset.withColumn("asJson", from_json(...))
See functions object for reference.
With JSON lines, you can select the fields of your interest:
val apptypes = jsons.select("eventData.appType")
And then union it with installedApp_Ids.
I'm sure the code gets easier to read (and hopefully to write too). The migration will give you extra optimizations that you may or may not be able to write yourself using assembler-like RDD API.
And the best is that filtering out nulls is as simple as using na operator that gives DataFrameNaFunctions like drop. I'm sure you'll like them.
It does not necessarily answer your initial question, but this java.lang.StackOverflowError might get away just by doing the code migration and the code gets easier to maintain, too.

What is the idiomatic way for printing all the differences in XMLUnit?

I'm trying to override the default XMLUnit behavior of reporting only the first difference found between two inputs with a (text) report that includes all the differences found.
I've so far accomplished this:
private static void reportXhtmlDifferences(String expected, String actual) {
Diff ds = DiffBuilder.compare(Input.fromString(expected))
.withTest(Input.fromString(actual))
.checkForSimilar()
.normalizeWhitespace()
.ignoreComments()
.withDocumentBuilderFactory(dbf).build();
DefaultComparisonFormatter formatter = new DefaultComparisonFormatter();
if (ds.hasDifferences()) {
StringBuffer expectedBuffer = new StringBuffer();
StringBuffer actualBuffer = new StringBuffer();
for (Difference d: ds.getDifferences()) {
expectedBuffer.append(formatter.getDetails(d.getComparison().getControlDetails(), null, true));
expectedBuffer.append("\n----------\n");
actualBuffer.append(formatter.getDetails(d.getComparison().getTestDetails(), null, true));
actualBuffer.append("\n----------\n");
}
throw new ComparisonFailure("There are HTML differences", expectedBuffer.toString(), actualBuffer.toString());
}
}
But I don't like:
Having to iterate through the Differences in client code.
Reaching into the internals of DefaultComparisonFormatter and calling getDetails with that null ComparisonType.
Concating the differences with line dashes.
Maybe this is just coming from an unjustified bad gut feeling, but I'd like to know if anyone has some input on this use case.
XMLUnit suggests to simply print out the differences, see the section on "Old XMLUnit 1.x DetailedDiff": https://github.com/xmlunit/user-guide/wiki/Migrating-from-XMLUnit-1.x-to-2.x
Your code would look like this:
private static void reportXhtmlDifferences(String expected, String actual) {
Diff ds = DiffBuilder.compare(Input.fromString(expected))
.withTest(Input.fromString(actual))
.checkForSimilar()
.normalizeWhitespace()
.ignoreComments()
.withDocumentBuilderFactory(dbf).build();
if (ds.hasDifferences()) {
StringBuffer buffer = new StringBuffer();
for (Difference d: ds.getDifferences()) {
buffer.append(d.toString());
}
throw new RuntimeException("There are HTML differences\n" + buffer.toString());
}
}

StringIndexOutOfBoundsException Java Error

public void onStart() throws Exception
{
// start up code here
}enter code here
public void onExecute() throws Exception
{
// execute code (set executeOnChange flag on inputs)
String tmp = getInASCIIString().getValue();
setOutCSVString(new BStatusString(AsciiToBinary(tmp)));
}
public void onStop() throws Exception
{
// shutdown code here
}
public static String AsciiToBinary(String asciiString) throws Exception
{
String padding = "00000000";
StringBuffer dataString = new StringBuffer();
StringBuffer outCSV = new StringBuffer();
StringTokenizer Values = new StringTokenizer(asciiString,",");
while (Values.hasMoreTokens())
{
String bin = padding + Integer.toBinaryString(Integer.parseInt(Values.nextToken()));
String reversedString = new StringBuffer(bin.substring(bin.length() - 8, bin.length())).reverse().toString();
dataString.append(reversedString);
}
try
{
char[] charArray = dataString.toString().toCharArray();
for (int i = 1; i < charArray.length; i++)
{
if (charArray[i] == '1')
{
outCSV.append(i+"");
outCSV.append(',');
}
}
if (outCSV.toString().length() > 1)
{
return outCSV.toString().substring(0, outCSV.toString().length()-1);
}
else
{
return outCSV.toString();
}
}
catch(StringIndexOutOfBoundsException e)
{
return "";
}
}
We use a Tridium- which uses Java as the backend. This program seems to be randomly and occasionally throwing an error. I'm only limited to the packages that are pre-installed, including: java.util, java.baja.sys, javax.baja.status, javax.baja.util, com.tridium.program
Which is why some of the code is written using the logic/functions that it does. Anyway- I cannot figure out why this is throwing an error. Any thoughts?
java.lang.StringIndexOutOfBoundsException: String index out of range: 15 at java.lang.String.charAt(String.java:658)
Full stack trace:
java.lang.StringIndexOutOfBoundsException: String index out of range: 15
at java.lang.String.charAt(String.java:658)
at com.korsengineering.niagara.conversion.BStatusNumericToStatusBoolean.changed(BStatusNumericToStatusBoolean.java:38)
at com.tridium.sys.schema.ComponentSlotMap.fireComponentEvent(ComponentSlotMap.java:1000)
at com.tridium.sys.schema.ComponentSlotMap.modified(ComponentSlotMap.java:902)
at com.tridium.sys.schema.ComplexSlotMap.modified(ComplexSlotMap.java:1538)
at com.tridium.sys.schema.ComplexSlotMap.setDouble(ComplexSlotMap.java:1254)
at javax.baja.sys.BComplex.setDouble(BComplex.java:666)
at com.tridium.sys.schema.ComplexSlotMap.copyFrom(ComplexSlotMap.java:294)
at javax.baja.sys.BComplex.copyFrom(BComplex.java:246)
at javax.baja.sys.BLink.propagatePropertyToProperty(BLink.java:593)
at javax.baja.sys.BLink.propagate(BLink.java:523)
at com.tridium.sys.engine.SlotKnobs.propagate(SlotKnobs.java:56)
at com.tridium.sys.schema.ComponentSlotMap.modified(ComponentSlotMap.java:899)
at com.tridium.sys.schema.ComplexSlotMap.modified(ComplexSlotMap.java:1538)
at com.tridium.sys.schema.ComplexSlotMap.setDouble(ComplexSlotMap.java:1254)
at javax.baja.sys.BComplex.setDouble(BComplex.java:666)
at javax.baja.status.BStatusNumeric.setValue(BStatusNumeric.java:66)
at com.tridium.kitControl.conversion.BStatusStringToStatusNumeric.calculate(BStatusStringToStatusNumeric.java:161)
at com.tridium.kitControl.conversion.BStatusStringToStatusNumeric.changed(BStatusStringToStatusNumeric.java:155)
at com.tridium.sys.schema.ComponentSlotMap.fireComponentEvent(ComponentSlotMap.java:1000)
at com.tridium.sys.schema.ComponentSlotMap.modified(ComponentSlotMap.java:902)
at com.tridium.sys.schema.ComplexSlotMap.modified(ComplexSlotMap.java:1538)
at com.tridium.sys.schema.ComplexSlotMap.setString(ComplexSlotMap.java:1335)
at javax.baja.sys.BComplex.setString(BComplex.java:668)
at com.tridium.sys.schema.ComplexSlotMap.copyFrom(ComplexSlotMap.java:295)
at javax.baja.sys.BComplex.copyFrom(BComplex.java:246)
at javax.baja.sys.BLink.propagatePropertyToProperty(BLink.java:593)
at javax.baja.sys.BLink.propagate(BLink.java:523)
at com.tridium.sys.engine.SlotKnobs.propagate(SlotKnobs.java:56)
at com.tridium.sys.schema.ComponentSlotMap.modified(ComponentSlotMap.java:899)
at com.tridium.sys.schema.ComplexSlotMap.modified(ComplexSlotMap.java:1538)
at com.tridium.sys.schema.ComplexSlotMap.setString(ComplexSlotMap.java:1335)
at javax.baja.sys.BComplex.setString(BComplex.java:668)
at com.tridium.sys.schema.ComplexSlotMap.copyFrom(ComplexSlotMap.java:295)
at javax.baja.sys.BComplex.copyFrom(BComplex.java:238)
at javax.baja.control.BControlPoint.doExecute(BControlPoint.java:271)
at auto.javax_baja_control_BStringWritable.invoke(AutoGenerated)
at com.tridium.sys.schema.ComponentSlotMap.invoke(ComponentSlotMap.java:1599)
at com.tridium.sys.engine.EngineUtil.doInvoke(EngineUtil.java:49)
at com.tridium.sys.engine.EngineManager.checkAsyncActions(EngineManager.java:364)
at com.tridium.sys.engine.EngineManager.execute(EngineManager.java:209)
at com.tridium.sys.engine.EngineManager$EngineThread.run(EngineManager.java:691)
Something is happening outside your Program Object, once you wire your outCSVString to whatever other wire sheet logic you are linking it to. This is more than likely due to your AsciiToBinary method returning a null string output that the rest of your logic can't deal with.
Wire outCSVString to a StringWritable object that has a StringCov history extension on it, and look for what value the history records at the same timestamp where you see the exception, to make sure your ProgramObject is generating the output you expect.
Regarding your AsciiToBinary method, the Tridium framework is limited in the modules it provides and what you can import, however it does come packaged with Apache Oro Regular Expression Tools Version 2.0.8. Search for "oro" in the Niagara Help file for more information.
In my experience, you will be more assured that outCSVString will always follow a desired format if you use a regular expression with a substitution to build the string, rather than tokenizing and iterating through the string yourself.

Reporting progress of parser

I have a large file that I am trying to parse with Antlr in Java, and I would like to show the progress.
It looked like could do the following:
CommonTokenStream tokens = new CommonTokenStream(lexer);
int maxTokenIndex = tokens.size();
and then use maxTokenIndex in a ParseTreeListener as such:
public void exitMyRule(MyRuleContext context) {
int tokenIndex = context.start.getTokenIndex();
myReportProgress(tokenIndex, maxTokenIndex);
}
The second half of that appears to work. I get ever increasing values for tokenIndex. However, tokens.size() is returning 0. This makes it impossible to gauge how much progress I have made.
Is there a good way to get an estimate of how far along I am?
The following appears to work.
File file = getFile();
ANTLRInputStream input = new ANTLRInputStream(new FileReader(file));
ProgressMonitor progress = new ProgressMonitor(null,
"Loading " + file.getName(),
null,
0,
input.size());
Then extend MyGrammarBaseListener with
#Override
public void exitMyRule(MyRuleContext context) {
progress.setProgress(context.stop.getStopIndex());
}

Ignore whitespace while converting XML to JSON using XStream

I'm attempting to establish a reliable and fast way to transform XML to JSON using Java and I've started to use XStream to perform this task. However, when I run the code below the test fails due to whitespace (including newline), if I remove these characters then the test will pass.
#Test
public void testXmlWithWhitespaceBeforeStartElementCanBeConverted() throws Exception {
String xml =
"<root>\n" +
" <foo>bar</foo>\n" + // remove the newlines and white space to make the test pass
"</root>";
String expectedJson = "{\"root\": {\n" +
" \"foo\": bar\n" +
"}}";
String actualJSON = transformXmlToJson(xml);
Assert.assertEquals(expectedJson, actualJSON);
}
private String transformXmlToJson(String xml) throws XmlPullParserException {
XmlPullParser parser = XppFactory.createDefaultParser();
HierarchicalStreamReader reader = new XppReader(new StringReader(xml), parser, new NoNameCoder());
StringWriter write = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(write);
HierarchicalStreamCopier copier = new HierarchicalStreamCopier();
copier.copy(reader, jsonWriter);
jsonWriter.close();
return write.toString();
}
The test fails the exception:
com.thoughtworks.xstream.io.json.AbstractJsonWriter$IllegalWriterStateException: Cannot turn from state SET_VALUE into state START_OBJECT for property foo
at com.thoughtworks.xstream.io.json.AbstractJsonWriter.handleCheckedStateTransition(AbstractJsonWriter.java:265)
at com.thoughtworks.xstream.io.json.AbstractJsonWriter.startNode(AbstractJsonWriter.java:227)
at com.thoughtworks.xstream.io.json.AbstractJsonWriter.startNode(AbstractJsonWriter.java:232)
at com.thoughtworks.xstream.io.copy.HierarchicalStreamCopier.copy(HierarchicalStreamCopier.java:36)
at com.thoughtworks.xstream.io.copy.HierarchicalStreamCopier.copy(HierarchicalStreamCopier.java:47)
at testConvertXmlToJSON.transformXmlToJson(testConvertXmlToJSON.java:30)
Is there a way to to tell the copy process to ignore the ignorable white space. I cannot find any obvious way to enable this behaviour, but I think it should be there. I know I can pre-process the XML to remove the white space, or maybe just use another library.
update
I can work around the issue using a decorator of the HierarchicalStreamReader interface and suppressing the white space node manually, this still does not feel ideal though. This would look something like the code below, which will make the test pass.
public class IgnoreWhitespaceHierarchicalStreamReader implements HierarchicalStreamReader {
private HierarchicalStreamReader innerHierarchicalStreamReader;
public IgnoreWhitespaceHierarchicalStreamReader(HierarchicalStreamReader hierarchicalStreamReader) {
this.innerHierarchicalStreamReader = hierarchicalStreamReader;
}
public String getValue() {
String getValue = innerHierarchicalStreamReader.getValue();
System.out.printf("getValue = '%s'\n", getValue);
if(innerHierarchicalStreamReader.hasMoreChildren() && getValue.length() >0) {
if(getValue.matches("^\\s+$")) {
System.out.printf("*** White space value suppressed\n");
getValue = "";
}
}
return getValue;
}
// rest of interface ...
Any help is appreciated.
Comparing two XML's as String objects is not a good idea. How are you going to handle case when xml is same but nodes are not in the same order.
e.g.
<xml><node1>1</node1><node2>2</node2></xml>
is similar to
<xml><node2>2</node2><node1>1</node1></xml>
but when you do a String compare it will always return false.
Instead use tools like XMLUnit. Refer to following link for more details,
Best way to compare 2 XML documents in Java

Categories

Resources