Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Expected “"” but found unknown token

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.

like image 846
Jakir00 Avatar asked Jul 14 '10 20:07

Jakir00


2 Answers

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...

like image 66
Andreas Dolk Avatar answered Oct 19 '22 09:10

Andreas Dolk


You need to 'double-escape' the space in the path:

        vvvv
...\Menu\\\\ Extras\...
like image 33
martin clayton Avatar answered Oct 19 '22 09:10

martin clayton