Hmm, the formatting of the offered fix was mangled (had used a format which was 
obviously not o.k.).
So here another attempt to present the code in a way that makes it hopefully 
easy to copy and paste
(in a fixed pitch the ".replace(...)" invocations are aligned to the same 
column):

----- code ----
@Override   // enquote string in double-quotes and escape the characters '\', 
'\n', '"' in the string
    public String getOutputStatement(final String toDisplay)
    {
        return "print(\"" + toDisplay.replace("\\", "\\\\")
                                     .replace("\n", "\\n" )
                                     .replace("\"", "\\\"")
                          + "\")";
    }
----- code ----

---rony


On 05.11.2019 12:09, Rony G. Flatscher wrote:
> Almost two years ago I brought up a bug in 
> NashornScriptEngineFactory.getOutputStatement(String).
> Further attention obviously stopped with the question where an appropriate 
> place would be to file a
> bug.
>
> The bug is caused by not quoting and escaping the passed string such that a 
> proper JavaScript
> statement gets created, if the string contains e.g. comma or wrong characters 
> because they do not
> get escaped. Currently
>
>     nashornFractory.getOutputStatement("'hello world', this is \"Nashorn"\ 
> speaking! ")
>
> will yield
>
>       print('hello world', this is "Nashorn" speaking! )
>
> which is syntactically wrong and causes a ScriptException if executed by 
> Nashorn.
>
> Rather the returned statement in this case should be
>
>     print("'hello world', this is \"Nashorn"\ speaking! ")
>
> ---
>
> Although I signed the OCA I have no rights to open a bug, so I kindly ask 
> someone with the power to
> do so.
>
> Also, a possible, simple fix for getOutputStatement() in
> jdk.nashorn.api.scripting.NashornScriptEngineFactory would be:
>
>     @Override // enquote string in double-quotes and escape the characters 
> '\', '\n', '"' in the
>     string public String getOutputStatement(final String toDisplay) { return 
> "print(\"" +
>     toDisplay.replace("\\", "\\\\") .replace("\n", "\\n" ) .replace("\"", 
> "\\\"") + "\")"; }
>
> Again, having signed the OCA it should be o.k. to use this code directly to 
> fix the bug.
>
> If you prefer a patch, then please point me to the exact mercurial repository 
> I should check out in
> order to produce the patch. (The original code is merely a one-liner: return 
> "print(" + toDisplay +
> ")";  so it should be easy and safe to apply the above code directly.)
>
> ---rony
... cut ...

Reply via email to