How to identify the JAVACC parser unsuccessful programatically? - parsing

In javacc, how to check weather the input file is successfully passed the grammar or not? As an example, say I want to print "Filed parsed successfully" if the whole file is successfully parsed by the parser, and if not I want to print "File parsing faild!"
I'm pretty newbie to javacc. So please help

try {
parser.start() ;
System.out.println("File parsed successfully.") ;
} catch( ParseException ex ) {
// Syntax error
System.out.println( ex.getMessage() ) ; }
} catch( TokenManagerError ex ) {
// Lexical error
System.out.println( ex.getMessage() ) ; }
} catch( Throwable ex ) {
// Some other error
System.out.println( ex.getMessage() ) ; }

Related

I am not able to parse IOS driver page source

I got Page source using
String pageSource = driver.getPageSource();
Now i need to save this xml file to local in cache. So i need to get element attributes like x and y attribute value rather than every time get using element.getAttribute("x");. But I am not able to parse pageSource xml file to some special character. I cannot remove this character because at if i need element value/text it shows different text if i will remove special character. Appium is use same way to do this.
I was also facing same issue and i got resolution using below code which i have written and it works fine
public static void removeEscapeCharacter(File xmlFile) {
String pattern = "(\\\"([^=])*\\\")";
String contentBuilder = null;
try {
contentBuilder = Files.toString(xmlFile, Charsets.UTF_8);
} catch (IOException e1) {
e1.printStackTrace();
}
if (contentBuilder == null)
return;
Pattern pattern2 = Pattern.compile(pattern);
Matcher matcher = pattern2.matcher(contentBuilder);
StrBuilder sb = new StrBuilder(contentBuilder);
while (matcher.find()) {
String str = matcher.group(1).substring(1, matcher.group(1).length() - 1);
try {
sb = sb.replaceFirst(StrMatcher.stringMatcher(str),
StringEscapeUtils.escapeXml(str));
} catch (Exception e) {
e.printStackTrace();
}
}
try {
Writer output = null;
output = new BufferedWriter(new FileWriter(xmlFile, false));
output.write(sb.toString());
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if you will get that kind of problem then catch it with remove special character and parse again.
try {
doc = db.parse(fileContent);
} catch (Exception e) {
removeEscapeCharacter(file);
doc = db.parse(file);
}
It might works for you.
I can able to do same using SAXParser and add handler to do for this.
Refer SAX Parser

Tika--Extracting Distinct Items from a Compound Document

Question:
Assume an email message with an attachment (assume a JPEG attachment). How do I parse (not using the Tika facade classes) the email message and return the distinct pieces--a) the email text contents and b) the email attachment?
Configuration:
Tika 1.2
Java 1.7
Details:
I have been able to properly parse email messages in basic email message formats. However, after the parsing, I need to know a) the email's text contents and b) the the contents of any attachment to the email. I will store these items in my database as essentially parent email with child attachments.
What I cannot figure out is how I can "get back" the distinct parts and know that the parent email has attachments and be able to separately store those attachments referenced to the mail. This is, I believe, essentially similar to extracting ZipFile contents.
Code Example:
private Message processDocument(String fullfilepath) {
try {
File filename = new File(fullfilepath) ;
return this.processDocument(filename) ;
} catch (NullPointerException npe) {
Message error = new Message(false) ;
error.appendErrorMessage("The file name was null.") ;
return error ;
}
}
private Message processDocument(File filename) {
InputStream stream = null;
try {
stream = new FileInputStream(filename) ;
} catch (FileNotFoundException fnfe) {
// TODO Auto-generated catch block
fnfe.printStackTrace();
System.out.println("FileNotFoundException") ;
return diag ;
}
int writelimit = -1 ;
ContentHandler texthandler = new BodyContentHandler(writelimit);
this.safehandlerbodytext = new SafeContentHandler(texthandler);
this.meta = new Metadata() ;
ParseContext context = new ParseContext() ;
AutoDetectParser autodetectparser = new AutoDetectParser() ;
try {
autodetectparser.parse(
stream,
texthandler,
meta,
context) ;
this.documenttype = meta.get("Content-Type") ;
diag.setSuccessful(true);
} catch (IOException ioe) {
// if the document stream could not be read
System.out.println("TikaTextExtractorHelper IOException " + ioe.getMessage()) ;
//FIXME -- add real handling
} catch (SAXException se) {
// if the SAX events could not be processed
System.out.println("TikaTextExtractorHelper SAXException " + se.getMessage()) ;
//FIXME -- add real handling
} catch (TikaException te) {
// if the document could not be parsed
System.out.println("TikaTextExtractorHelper TikaException " + te.getMessage()) ;
System.out.println("Exception Filename = " + filename.getName()) ;
//FIXME -- add real handling
}
}
When Tika hits an embedded document, it goes to the ParseContext to see if you have supplied a recursing parser. If you have, it'll use that to process any embedded resources. If you haven't, it'll skip.
So, what you probably want to do is something like:
public static class HandleEmbeddedParser extends AbstractParser {
public List<File> found = new ArrayList<File>();
Set<MediaType> getSupportedTypes(ParseContext context) {
// Return what you want to handle
HashSet<MediaType> types = new HashSet<MediaType>();
types.put(MediaType.application("pdf"));
types.put(MediaType.application("zip"));
return types;
}
void parse(
InputStream stream, ContentHandler handler,
Metadata metadata, ParseContext context
) throws IOException {
// Do something with the child documents
// eg save to disk
File f = File.createTempFile("tika","tmp");
found.add(f);
FileOutputStream fout = new FileOutputStream(f);
IOUtils.copy(stream,fout);
fout.close();
}
}
ParseContext context = new ParseContext();
context.set(Parser.class, new HandleEmbeddedParser();
parser.parse(....);

How to store a Lua function into C++ with SLB ( Simple Lua Binder )?

I need to store a Lua function using the library "Simple Lua Binder"
typedef ? TLuaFunction;
class Foo
{
public:
void SetCallback( TLuaFunction f )
{
mCallback = f;
}
void ExecuteCallback()
{
f(); // Calls Lua function
}
private:
TLuaFunction mCallback;
};
// Manager initialization
SLB::Manager scriptManager;
// SetCallback registration into lua
SLB::Class<Foo>( "Foo", &scriptManager )
.constructor()
.set( "SetCallback", &Foo::SetCallback )
.set( "ExecuteCallback", &Foo::ExecuteCallback )
;
char* luaCode =
"SLB.using( SLB )\n"
"o = Foo()\n"
"o:SetCallback( function() \n"
" print( 'Callback executed' ) \n"
" end \n"
") \n"
"o:ExecuteCallback() \n";
SLB::Script script( &scriptManager );
script.doString( luaCode );
// The result is
> "Callback executed"
I don't know if there is a type in SLB library that I can put instead of ? ( see the first line of code ).
Or if I have to do the things different.

Blackberry InputStream Closes Prematurely

The following code is used to get an XML file from a web server, and today, for the last few runs, this throws an exception with an error message "stream close." I have not modified this code since yesterday, nor have I modified any methods that handle the parsing.
The idea is this builds a list of item from the XML file pulled from the fullurl. There should 20 items in the list (based on the XML file I am using right now). In the last few runs, the parsing operation has thrown the exception mentioned above, and only stores 5 items. The method public void endDocument() never gets called.
Any thoughts would be helpful, since this will have to be moved to a background task, and I would like to have solved before I do that.
public void getAndParseXML() {
HttpConnection xmlcon = null;
InputStream xmlinput = null;
SAXParserFactory spf = null;
String fullurl = this.getNewsUrl() + NewsListBuilderTask.CONNECTION_STRING; // URL of XML file along specification for connection type
if ( (TransportInfo.isTransportTypeAvailable(TransportInfo.TRANSPORT_TCP_WIFI)) && (TransportInfo.hasSufficientCoverage(TransportInfo.TRANSPORT_TCP_WIFI)) )
fullurl += NewsListBuilderTask.WIFI_STRING;
try {
xmlcon = (HttpConnection)Connector.open( fullurl, Connector.READ, false ); // open connection to XML source
spf = SAXParserFactory.newInstance(); // set up xml parsers
xmlinput = xmlcon.openInputStream(); // set up input stream
SAXParser saxparser = spf.newSAXParser(); // create a new parser object
saxparser.parse( xmlinput, this ); // parse operations start here
}
catch( IOException ex ) {
System.out.println( "IOException Caught:\t" + ex.getMessage() ); // set a default item if any exception occurs with retreiving or parsing XML file
this.createDefaultItem();
}
catch (SAXException ex) {
System.out.println( "SAXException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
this.createDefaultItem();
}
catch ( IllegalArgumentException ex ) {
System.out.println( "IllegalArgumentException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
this.createDefaultItem();
}
catch (ParserConfigurationException ex) {
System.out.println( "ParserConfigurationException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
this.createDefaultItem();
}
finally {
if ( xmlinput != null) {
try {
xmlinput.close(); // attempt to close all connections
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if ( xmlcon != null ) {
try {
xmlcon.close();
}
catch ( IOException ex ) {
ex.printStackTrace();
}
}
}
}
NOTE: The fullurl used ends up bieng "http://somexmlfile.com?type=photo;deviceside=true" with ";interface=wifi" appended if available.

Blackberry HttpConnection Timing Out

I am trying to grab an XML file for parsing with the following:
private void getAndParseXML( String _xmlurl ) {
HttpConnection xmlcon = null;
InputStream input = null;
SAXParserFactory spf = null;
try {
xmlcon = (HttpConnection)Connector.open( _xmlurl, Connector.READ ); // open connection to XML source
spf = SAXParserFactory.newInstance(); // set up xml parsers
input = xmlcon.openInputStream(); // set up input stream
SAXParser saxparser = spf.newSAXParser(); // create a new parser object
saxparser.parse( input, this ); // parse operations start here
}
catch( IOException ex ) {
System.out.println( "IOException Caught:\t" + ex.getMessage() ); // set a default item if any exception occurs with retreiving or parsing XML file
}
catch (SAXException ex) {
System.out.println( "SAXException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
}
catch ( IllegalArgumentException ex ) {
System.out.println( "IllegalArgumentException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
}
catch (ParserConfigurationException ex) {
System.out.println( "ParserConfigurationException Caught:\t" + ex.getMessage() );
ex.printStackTrace();
}
finally {
if ( input != null) {
try {
input.close(); // attempt to close all connections
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if ( xmlcon != null ) {
try {
xmlcon.close();
}
catch ( IOException ex ) {
ex.printStackTrace();
}
}
}
} // END ----------------------------------------------------------------------------
But the I get an exception thrown saying the connection timed out after 12 seconds. This after the line input = xmlcon.openInputStream(); is executed.
If this is relevant, it is the IOException that gets caught, and determining if there is an active network connection is done before this method is called. Did I miss something?
EDIT: Just for clarification, this would be the first instance of a network connection in the application. Before this block of code, a simple test:
private boolean isConnectedToNetwork() {
boolean isConnected = false;
if ( (TransportInfo.isTransportTypeAvailable(TransportInfo.TRANSPORT_TCP_CELLULAR)) || (TransportInfo.isTransportTypeAvailable(TransportInfo.TRANSPORT_TCP_WIFI)) )
if ( (TransportInfo.hasSufficientCoverage(TransportInfo.TRANSPORT_TCP_CELLULAR)) || (TransportInfo.hasSufficientCoverage(TransportInfo.TRANSPORT_TCP_WIFI)) )
isConnected = true;
return isConnected;
}
to make sure a connection would be possible, before attempting to retrieve an XML file.
Mike, everything looks OK.
However here are some ideas to think of:
Can you open the URL from your browser?
What BB Transport do you use to open the connection (for instance, maybe it fails on BES, but will work Ok on Direct TCP or Wi-Fi)?
By the moment of this call, have the code that "determins if there is an active network connection" closed all connections it might have opened (if any) during detection?
Found the issue. The url, in this case _xmlurl, needed to be appended with ";deviceside=true" to ensure a direct TCP/IP connection was established. This makes sure an HttpConnection is made through the cellular network. In other words, to make sure the connection was not made through the Blackberry MDS.
Also, a check was needed:
if ( (TransportInfo.isTransportTypeAvailable(TransportInfo.TRANSPORT_TCP_WIFI)) && (TransportInfo.hasSufficientCoverage(TransportInfo.TRANSPORT_TCP_WIFI)) )
the wi-fi antenna was on. If the above ervaluated to true, the url (again _xmlurl) needed to be further appended with ";interface=wifi" to avoid the cellular network , but still open a direct TCP/IP connection.

Resources