I checked SO for the xmlpullparser exception but it's giving me others questions with Android and SOUP. I am using J2me and normal HTTPrequest to get my XML and I am using kXMl to parser the xml text. Below is the code that I am working on. And above it is more parsing code and they work perfectly.
if (parser.getName().equals("comments")) {
event = parser.next();
boolean flag = false;
if (parser.getName().equals("comment")) {
flag = true;
System.out.println("Flag is true");
}
while (flag) {
event = parser.next();
Questioncomments.addComponent(new Label(parser.nextText()));
event = parser.next();
System.out.println("Inside the While");
if (!parser.getName().equals("comment")) {
flag = false;
System.out.println("Flag is false");
}
}
Questioncomments.repaint();
}
XML I am sending this side - <comments><comment>Awesome Question #dulitha<idComment></idComment></comment></comments>
The error is -
org.xmlpull.v1.XmlPullParserException: precondition: START_TAG
(position:TEXT Awesome Question...#1:399 in
java.io.InputStreamReader#f828ed68)
at org.kxml2.io.KXmlParser.exception(+47)
at org.kxml2.io.KXmlParser.nextText(+14)
at
com.petmill.mobile.view.qanda.QuestionCanvas.setData(QuestionCanvas.java:189)
at
com.petmill.mobile.view.qanda.QuestionsList$5$1$1.actionPerformed(QuestionsList.java:119)
The error comes up at the line where I am trying to get the text - parser.nextText(). How can I parse the xml to get the data required... Thanks in advance.
It looks like you are not on the START_TAG event when you call parser.nextText(). Check that you are on a START_TAG event when you call parser.nextText() with the parser.getEventType(). I suspect that you have some whitespace between <comments> and <comment> tag and therefore your parser is not at the event that you expect it to be.
Perhaps you should also consider a safer approach for parsing this xml.
<comments>
<comment>Awesome Question #dulitha
<idComment></idComment>
</comment>
</comments>
this is not valid xml
Related
I would like to send a binary file via an appended MVCResourceCommand I coded for the native journal portlet. But the program is unable to use the OutputStream provided by the resource request.
IOUtils.copy( input, response.getPortletOutputStream() );
Considering:
The code works perfectly on StrutsActions
In custom portlets, it also works
In StrutsActions:
IOUtils.copy( input, response.getOutputStream() );
However, the code throws an IllegalStateException, saying that the writer is being used when I call response.getOutputStream().
I know we can not mix these two
The code is not attempting to do so
I wonder if Liferay is doing something with that request before it reaches my extension of BaseMVCResourceCommand, this is specifically for that native portlet.
I checked the preview feature for a webcontect item, but its URL is for the view mode.
The URL is created from a portlet:resourceURL tag inserted through a JSP fragment and the command is in its own OSGi module.
For sure, the URL is correct and the command logs that it was hit, but the exception is thrown afterwards.
The portlet I am trying to change is the:
"com_liferay_journal_web_portlet_JournalPortlet"
Any thoughts?
PS: I know about the Servlet and Portlet ResponseUtils. but they also eventually try getting the stream, leadin to the same exception.
#Component( immediate = true,
property = {
"javax.portlet.name=" + JOURNAL, "mvc.command.name=/command"
},
service = MVCResourceCommand.class )
public class Resource extends BaseMVCResourceCommand {
#Override
public void doServeResource( ResourceRequest request, ResourceResponse response ) throws PortletException {
try {
response.getPortletOutputStream();
}
catch ( Exception e ) {
throw new PortletException( e );
}
}
}
Caused by: java.lang.IllegalStateException: Unable to obtain OutputStream because Writer is already in use
at com.liferay.portlet.MimeResponseImpl.getPortletOutputStream(MimeResponseImpl.java:75)
Update:
It seems this is the source of my issues (PortletURLImpl), still looking for a solution though:
if (lifecycle.equals(PortletRequest.RESOURCE_PHASE)) {
_copyCurrentRenderParameters = true;
}
When the URL is created it comes with all sources of garbage from the render phase. Including an MVCPath
Really what I am after is a way to check if the control exists without throwing an error.
The code should look something like this:
Control myControl = UIMap.MyMainWindow;
if (!myControl.Exists)
{
//Do something here
}
The problem is that the control throws an error because it is invalid if it doesn't exist, essentially making the exists property useless.
What is the solution?
In this case I am using the tryfind method.
Like this:
HtmlDiv list = new HtmlDiv(Window.GetWebtop());
list.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
list.SearchProperties.Add(HtmlDiv.PropertyNames.InnerText, "Processing search", PropertyExpressionOperator.Contains);
if (list.TryFind())
{
//DO Something
}
I am re-posting the comment kida gave as a answer, because I think its the best solution.
Control myControl = UIMap.MyMainWindow;
if (!myControl.FindMatchingControls().Count == 0)
{
//Do something here
}
The FindMatchingControls().Count is much faster then the Try Catch or the TryFind. Since it does not wait for SearchTimeoutto check if the element is now there. Default it waits 30 seconds for the element to not be there, but I like my tests to fail fast.
Alternatively its possible to lower the Playback.PlaybackSettings.SearchTimeout before the Catch or TryFind and restore it afterwards, but this is unnecessary code if you ask me.
You can do one of two things: Wrap your code in a try-catch block so the exception will be swallowed:
try
{
if (!myControl.Exists)
{
// Do something here.
}
}
catch (System.Exception ex)
{
}
Or, you could add more conditions:
if (!myControl.Exists)
{
// Do something here.
}
else if (myControlExists)
{
// Do something else.
}
else
{
// If the others don't qualify
// (for example, if the object is null), this will be executed.
}
Personally, I like the catch block, because if I expect the control to be there as part of my test, I can Assert.Fail(ex.ToString()); to stop the test right there and log the error message for use in bug reporting.
If you are sure that control will exist or enabled after some time you can use WaitForControlExist() or WaitForControlEnabled() methods with a default timeout or specified timeout.
I have a situation like this and I am looping until the control is available :
bool isSaveButtonExist = uISaveButton.WaitForControlEnabled();
while (!isSaveButtonExist )
{
try
{
uISaveButton.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
uISaveButton.SetFocus(); // setting focus for the save button if found
isSaveButtonExist = uISaveButton.WaitForControlExist(100);
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message); // exception for every set focus message if the control not exist
}
}
// do something with found save button
// Click 'Save' button
Mouse.Click(uISaveButton, new Point(31, 37));
please refer to this link for more about these Methods:
Make playback wait methods
How can I get rid of the default ANTLR recognition error?
I want to write another message using my own error class instead of ANTLR's error.
I mean is there any possibility that some ANTLR error classes can be extended in order to display my own message?
More clearly, I do not want to see the following error message in my console :
token recognition error at:
If you simply want to suppress the messages, you can call lexer.removeErrorListeners(). However, a better approach is writing your lexer rules such that all possible input is tokenized, with the following rule at the end of the lexer. This will cause all error reporting to go through the parser instead of both the parser and lexer.
// handle characters which failed to match any other token
ErrorCharacter : . ;
In order to create a custom error handler you can extend the BaseErrorListener class and override the syntaxError method, e.g.:
public class MyErrorListener extends BaseErrorListener {
#Override
public void syntaxError( Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine,
String msg, RecognitionException e ) {
// method arguments should be used for more detailed report
throw new RuntimeException("syntax error occurred");
}
}
Now when you create a lexer and a parser you should remove the default error listeners and attach your custom one:
MyErrorListener errorListener = new MyErrorListener();
Lexer lexer = new MyLexer( ... );
lexer.removeErrorListeners();
lexer.addErrorListener( errorListener );
CommonTokenStream tokens = new CommonTokenStream( lexer );
Parser parser = new MyParser( tokens );
parser.removeErrorListeners();
parser.addErrorListener( errorListener );
The default message "line x:x token recognition error at: 'xxx'" comes from the default ConsoleErrorListener class. If you don't remove it using lexer/parser.removeErrorListeners() and only add your custom one it will still be triggered.
The error handling strategies are thoroughly described in a dedicated chapter of The Definitive ANTLR4 Reference book (mentioned on the ANTLR4 Documentation page). I currently have no access to the book itself, so would be grateful if someone edits this answer with a concrete page number of the book. Also, I couldn't find a related guide on the ANTLR4 doc page, so if it exists - a link would be helpful, too.
Another question on migrating code from v3 to v4:
For v3, I had a customized error reporting, using code like this (in the grammar file):
#members {
public void displayRecognitionError(String[] tokenNames,
RecognitionException e) {
String hdr = getErrorHeader(e);
String msg = getErrorMessage(e, tokenNames);
System.out.println("ERR:"+hdr+":"+msg);
errCount += 1;
}
}
In v4, when compiling the generated java files, I am getting the error:
MyParser.java:163: cannot find symbol
symbol : method getErrorMessage(org.antlr.v4.runtime.RecognitionException,java.lang.String[])
location: class MyParser
String msg = getErrorMessage(e, tokenNames);
^
Is this function replaced by some other function in v4? (I saw some questions and answers on ANTLRErrorListener, but I could not get how to use it for my situation.)
The displayRecognitionError method was removed in ANTLR 4, so even if you correct the body of that method it will not do anything. You need to remove the method from your grammar entirely, and implement ANTLRErrorListener instead. The documentation includes a list of classes that implement the interface, so you can reference those and/or extend one of them to produce the desired functionality.
Once you have an instance of an ANTLRErrorListener, you can use the following code to attach it to a Parser instance.
// remove the default error listener
parser.removeErrorListeners();
// add your custom error listener
parser.addErrorListener(listener);
I was trying to read a C# source file and parse it using Resharper. I wanted to get the list of namespaces used in the file but I had an exception in this line.
ICSharpFile file = CSharpParserUtil.Parse(sCode);
Exception Details:
A first chance exception of type 'System.InvalidOperationException' occurred in
JetBrains.Platform.ReSharper.Shell.dll
The thread 0x1020 has exited with code 0 (0x0).
The thread 0x14c0 has exited with code 0 (0x0).
static void Main()
{
String sCode = File.ReadAllText(#"D:\ResharperTries\TestFile.cs");
try
{
ICSharpFile file = CSharpParserUtil.Parse(sCode);
IList<ICSharpNamespaceDeclaration> x = file.NamespaceDeclarations;
foreach (ICSharpNamespaceDeclaration value in x)
{
Console.WriteLine(value.ContainingNamespace.ShortName);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Need some help regarding this issue.
Thanks
It is possible to do this with the parsers that are part of DXCore and CodeRush.
In version 10.2 we released stand-alone parser libraries for C# and VB (part of the freely downloadable DXCore), so referencing the parser libraries will make it very easy to do what you’re looking for.
If you need help with this, simply email support#devexpress.com with any questions.
Here is sample of code, which can be used to fill ListBox with namespaces, used in some file:
string filePath = #"InsertFilePathHere";
CSharp30Parser parser = new CSharp30Parser();
SourceFile fileNode = parser.ParseFile(filePath) as SourceFile;
if (fileNode == null || fileNode.UsingList == null)
return;
lbUsedNamespaces.Items.Clear();
for (int i = 0; i < fileNode.UsingList.Count; i++)
{
string strUsing = fileNode.UsingList.GetKey(i) as String;
if (String.IsNullOrEmpty(strUsing))
continue;
lbUsedNamespaces.Items.Add(strUsing);
}
Currently, it's impossible to use ReSharper API without Visual Stdio as in your example with console app.
You need to write R# plugin and it will be loaded into R# in Visual Studio.
Take a look at http://resharperpowertoys.codeplex.com/