Java - Expected “"” but found unknown token - java

I am receiving this error when trying to execute applescript from my java application. The code is as follows:
String script = "tell application \"Terminal\" to do shell script \"/System/Library/CoreServices/Menu\\ Extras/user.menu/Contents/Resources/CGSession -suspend\" ";
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("AppleScript");
engine.eval(script);
I get the following error:
Exception in thread "main" javax.script.ScriptException: Expected “"” but found unknown token.
at apple.applescript.AppleScriptEngine.evalScript(Native Method)
at apple.applescript.AppleScriptEngine.eval(AppleScriptEngine.java:342)
at apple.applescript.AppleScriptEngine.eval(AppleScriptEngine.java:313)
at myTestApp.Main.main(Main.java:25)
Thanks for your consideration.

A guess based on experience... Maybe the escaped space in the pathname is your show stopper.
Try to call a script from a location where the path has no spaces or try to 'double-escape' the escaped space, like so:
"tell application \"Terminal\" to do shell script \"/System/Library/CoreServices/Menu\\\\ Extras/user.menu/Contents/Resources/CGSession -suspend\" "
A common reason for strange errors are those whitespaces in pathnames. So it was my first guess, that this causes trouble in your script. Then I remembered that sometimes we have to 'escape escaped backslashes'. This article doesn't explain, why it solved exactly your problem, but it shows how many backslashes may be needed...

You need to 'double-escape' the space in the path:
vvvv
...\Menu\\\\ Extras\...

Related

Why is ANTLR not printing set of tokens correctly?

I am testing to see if ANTLR-4.7.1 is working properly by using a sample, provided by my professor, to match these results for the same printed set of tokens:
% java -jar ./antlr-4.7.1-complete.jar HelloExample.g4
% javac -cp antlr-4.7.1-complete.jar HelloExample*.java
% java -cp .:antlr-4.7.1-complete.jar org.antlr.v4.gui.TestRig HelloExample greeting helloworld.greeting -tokens
[#0,0:4='Hello',<1>,1:0]
[#1,6:10='World',<3>,1:6]
[#2,12:12='!',<2>,1:12]
[#3,14:13='<EOF>',<-1>,2:0]
(greeting Hello World !)
However, after getting to the 3rd command, my output was instead:
[#0,0:4='Hello',<'Hello'>,1:0]
[#1,6:10='World',<Name>,1:6]
[#2,12:12='!',<'!'>,1:12]
[#3,13:12='<EOF>',<EOF>,1:13]
In my output, there are no numbers inside < >, which I believe should be defined from the HelloExample.tokens file that contain:
Hello=1
Bang=2
Name=3
WS=4
'Hello'=1
'!'=2
I get no error information and antlr seemed to have generated all the files I needed, so I don't know where I should be looking to resolve this, please help. And I'm not sure if it'll be of use, but my working directory started with helloworld.greeting and HelloExample.g4 and final directory now contains
helloworld.greeting
HelloExample.g4
HelloExample.interp
HelloExample.tokens
HelloExampleBaseListener.class
HelloExampleBaseListener.java
HelloExampleLexer.class
HelloExampleLexer.inerp
HelloExampleLexer.java
HelloExampleLexer.tokens
HelloExampleListener.class
HelloExampleListener.java
HelloExampleParser$GreetingContext.class
HelloExampleParser.class
HelloExampleParser.java
As rici already pointed out in the comments, getting the actual rule names instead of their numbers in the token output is a feature and shouldn't worry you.
In order to get the (greeting Hello World !) output at the end, you'll want to add the -tree flag after -tokens.

Regex Expression working in Notepad++ but not Java

Okay, so i'm working on a problem I'd rather solve with regex, I test most of my regex expressions in Notepad++, This has worked fine after a few tweaks such as double escaping some things for java, However this regex expression throws an exception when run in java, however it runs in Notepad++ just fine, the idea if this code is to be able to mention a different player in the game with a highlighted name.
tldr; I'm trying to replace the first occurrence of a specific name in a message
I've tried looking around for a while but i haven't found a solution, so i thought i might as well ask here.
p.getName() simply returns a string (the players name)
String newmessage = message.replaceFirst("(?i)" + Pattern.quote(p.getName()) + "((?(?=\\s)|('|,|!))|$)", color + p.getName() + Color.toString(Color.getLastColorOf(message)));
However executing the code throws this exception
...at java.lang.Thread.run(Unknown Source) [?:1.8.0_202]
Caused by: java.util.regex.PatternSyntaxException: Unknown inline modifier near index 15
(?i)\QTauCubed\E((?(?=\s)|('|,))|$)
^
at java.util.regex.Pattern.error(Unknown Source) ~[?:1.8.0_202]...
And I'm not sure what it wants me to do, I don't see how this is not valid regex
This is the regex for Notepad++
(?i)Name((?(?=\s)|('|,|!))|$)
The above will match
Name's r
Name
Name test
Name,
Name!
But will not match
Nametest
That is what I intended it to do.
I vote for just using the pattern \bName\b along with String#replaceFirst:
String input = "Rename here is a Name and here is the same Name again.";
input = input.replaceFirst("\\bName\\b", "blah");
System.out.println(input);
This prints:
Rename here is a blah and here is the same Name again.

synonyms() error in wordnet

I want to use synonyms () described in 'Intro to the tm package' for R. It uses the wordnet package. The wordnet package downloaded from CRAN does not have Dict (dictionary) in its directory. I downloaded it from the Princeton site and copied it over to the directory. After using sys.setenv() and setDict() for setting paths, I still get this error:
Error in sort(unique(unlist(lapply(synsets, getWord))))
error in evaluating the argument 'x' in selecting a method for function 'sort': Error in unique(unlist(lapply(synsets, getWord))) :
error in evaluating the argument 'x' in selecting a method for function 'unique': Error in .jcall(synset, "Ljava/util/List;", "getWord") :
java.lang.NumberFormatException: For input string: "t"
when I try synonyms("company", pos = "NOUN") or another English word in place of 'company'. The problem is in getSynonyms() called from synonyms(). Any idea on how to fix this problem?
Different combinations lead to different input string NumberFormatException. My Java is version 1.8. I tried all the online resources. I added two paths to PATH for R's bin and RJava's jri. Discussion on the exception indicates it is a string to numeric conversion issue. I have made sure that Java to R linkage (via rJava) works (URL: https://www.rforge.net/rJava/ ).

Undefined objects in JavaScript engine in Java

Executing the following code in Java7
ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("js");
Bindings b = scriptEngine.createBindings();
b.put("x", true);
scriptEngine.eval("x&y", b);
I get the error
sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "b" is not defined. (<Unknown Source>#1) in <Unknown Source> at line number 1
Is there an option to evaluate to null/false for undefined objects, like in JavaScript?
I know that an option will be to do something like "this.x&this.y" instead of "x&y", but I don't have control over that string (user entered).
I browsed a little bit through the Rhino code and it seems that there's no such option.
In the end I will append "this." in front of each variable. This is not by far a desirable solution (I will not even accept my own answer :) ), but for the time being I have no other.

Regular expression to parse a log file and find stacktraces

I'm working with a legacy Java app that has no logging and just prints all information to the console. Most exceptions are also "handled" by just doing a printStackTrace() call.
In a nutshell, I've just redirected the System.out and System.error streams to a log file, and now I need to parse that log file. So far all good, but I'm having problems trying to parse the log file for stack traces.
Some of the code is obscufated as well, so I need to run the stacktraces through a utility app to de-obscufate them. I'm trying to automate all of this.
The closest I've come so far is to get the initial Exception line using this:
.+Exception[^\n]+
And finding the "at ..(..)" lines using:
(\t+\Qat \E.+\s+)+
But I can't figure out how to put them together to get the full stacktrace.
Basically, the log files looks something like the following. There is no fixed structure and the lines before and after stack traces are completely random:
Modem ERROR (AT
Owner: CoreTalk
) - TIMEOUT
IN []
Try Open: COM3
javax.comm.PortInUseException: Port currently owned by CoreTalk
at javax.comm.CommPortIdentifier.open(CommPortIdentifier.java:337)
...
at UniPort.modemService.run(modemService.java:103)
Handling file: C:\Program Files\BackBone Technologies\CoreTalk 2006\InputXML\notify
java.io.FileNotFoundException: C:\Program Files\BackBone Technologies\CoreTalk 2006\InputXML\notify (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
...
at com.gobackbone.Store.a.a.handle(Unknown Source)
at com.jniwrapper.win32.io.FileSystemWatcher.fireFileSystemEvent(FileSystemWatcher.java:223)
...
at java.lang.Thread.run(Unknown Source)
Load Additional Ports
... Lots of random stuff
IN []
[Fatal Error] .xml:6:114: The entity name must immediately follow the '&' in the entity reference.
org.xml.sax.SAXParseException: The entity name must immediately follow the '&' in the entity reference.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
...
at com.gobackbone.Store.a.a.run(Unknown Source)
Looks like you just need to paste them together (and use a newline as glue):
.+Exception[^\n]+\n(\t+\Qat \E.+\s+)+
But I would change your regex a bit:
^.+Exception[^\n]++(\s+at .++)+
This combines the whitespace between the at... lines and uses possessive quantifiers to avoid backtracking.
We have been using ANTLR to tackle the parsing of logfiles (in a different application area). It's not trivial but if this is a critical task for you it will be better than using regexes.
I get good results using
perl -n -e 'm/(Exception)|(\tat )/ && print' /var/log/jboss4.2/debian/server.log
It dumps all lines which have Exception or \tat in them. Since the match is in the same time the order is kept.

Categories

Resources