Calling external javascript function from java - javascript

I have tried to call javascript function from java code, but I am getting the following error while using javascript API:
Caused by: sun.org.mozilla.javascript.internal.EcmaError:
ReferenceError: "File" is not defined. (#8) at
sun.org.mozilla.javascript.internal.ScriptRuntime.constructError(ScriptRuntime.java:3770)
at
sun.org.mozilla.javascript.internal.ScriptRuntime.constructError(ScriptRuntime.java:3748)
at
sun.org.mozilla.javascript.internal.ScriptRuntime.notFoundError(ScriptRuntime.java:3833)
at
sun.org.mozilla.javascript.internal.ScriptRuntime.name(ScriptRuntime.java:1760)
at
sun.org.mozilla.javascript.internal.Interpreter.interpretLoop(Interpreter.java:1785)
at
sun.org.mozilla.javascript.internal.Interpreter.interpret(Interpreter.java:849)
java code:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
engine.eval(Files.newBufferedReader(Paths.get("D:/test/test.js"), StandardCharsets.UTF_8));
Invocable inv = (Invocable) engine;
inv.invokeFunction("display", "test");
inv.invokeFunction("writeTextFile", "D:\\test\\file.txt", "test");
test.js:
var display = function(name) {
print("Hello, I am a Javascript display function "+name);
return "display function return"
}
function writeTextFile(afilename, output) {
var txtFile = new File(afilename);
txtFile.writeln(output);
txtFile.close();
}
display function working fine, the error appear while executing writeTextFile function.

in your test.js, try:
var txtFile = new File([""], afilename);

Related

How to use Paths(java.nio.file.Paths) in nashorn javascript

I have a path (eg: "C:/Users/aaa/bbb/ccc/"), my aim to get the parent path (i.e. "C:/Users/aaa/bbb/")
For this I tried using java.nio.file.Paths, which worked in java and I tried converting the same into nashorn js:
import java.nio.file.Paths;
public class ReadPropertiesFile {
public static void main(String[] args) {
String myPath = "C:/Users/aaa/bbb/ccc/";
System.out.println(Paths.get(myPath).getParent());
}
}
Nashorn script:
var testPath = "C:/Users/aaa/bbb/ccc/";
var Paths = java.import("java.nio.file.Paths");
try{
var test = Paths.get(testPath).getParent();
console.log("++++++MyFINALPATH+++++"+test);
}catch (e){ console.log("++++++MyFINALPATH+++++"+e);
}
Expected output: C:/Users/aaa/bbb/
Error-
TypeError: Paths.get(...).getParent is not a function
You need to use this instead:
var Paths = Java.type("java.nio.file.Paths");
https://docs.oracle.com/javase/9/scripting/using-java-scripts.htm#JSJSG117

Read data from a website using Nashorn

I want to retrieve data from a website using Nashorn script engine
I have the java code where I can retrieve data from a sample website template.
Now I want to call that java file from java script file.
following is the code:
JAVA CODE(Nsample.java):
package sample;
import java.net.*;
import java.io.*;
public class Nsample
{
public static void main(String[] args)
{
String output = getUrlContents("https://freewebsitetemplates.com/");
System.out.println(output);
}
public static String getUrlContents(String theUrl)
{
StringBuilder content = new StringBuilder();
try
{
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return content.toString();
}
}
JAVASCRIPT code:(sample.js)
var n = Java.type('C.JavaFolder.sample.Nsample');
var result = n.getUrlContents("https://freewebsitetemplates.com/");
print(result);
I'm trying to compile javascript code using command prompt but it is showing CLASSNOTFOUNDEXCEPTION.
The command was jjs sample.js.Im assuming I did some mistake in Java.type() function.
Can anyone solve this?
This line is the problematic line:
var n = Java.type('C.JavaFolder.sample.Nsample');
Java.type accepts fully qualified java type name. Based on your Java code, your package seems to be "sample" and class name is "Nsample". So the fully qualified class name would be "sample.Nsample".
You should compile your Java classes and specify the directory in -classpath option (of jjs tool or your java application if you use javax.script API with nashorn).
Instead of calling Java from JavaScript , I tried to call JavaScript from java and worked well.
I created some functions in JavaScript and invoked those functions from Java code.
Following is the code.Hope this helps.
Test.java:
import javax.script.*;
import java.io.*;
import java.util.*;
public class Test{
public static void main(String[] args) throws Exception{
ScriptEngine engine = new ScriptEngineManager().getEngineByName("Nashorn");
engine.eval(new FileReader("test.js"));
Invocable invoke = (Invocable)engine;
Object res = invoke.invokeFunction("httpGet","https://www.javaworld.com");
System.out.println(res);
}
}
test.js:
var httpGet = function(theUrl){
var con = new java.net.URL(theUrl).openConnection();
con.requestMethod = "GET";
return asResponse(con);
}
function asResponse(con){
var d = read(con.inputStream);
return d;
}
function read(inputStream){
var inReader = new java.io.BufferedReader(new
java.io.InputStreamReader(inputStream));
var inputLine;
var response = new java.lang.StringBuffer();
while ((inputLine = inReader.readLine()) != null) {
response.append(inputLine);
}
inReader.close();
return response.toString();
}

How to find my javascript function in Jint in C#?

I wrote code below
static void Main(string[] args)
{
var engine = new Engine();
var file = File.ReadAllText(#"...\Desktop\beautify.js");
var final = file + Environment.NewLine + "(function () {return js_beautify('var a = 2;');})();";
var exec = engine.Execute(final);
var r = exec.GetCompletionValue().ToString();
Console.WriteLine(r);
Console.Read();
}
but the Jint show error
Jint.Runtime.JavaScriptException: 'js_beautify is not defined'
Can anyone help me how to register external js libraries like beautify.js and then call functions of them in Jint ?
It should be
var engine = new Engine().Execute("var global = {};").Execute(content);
var js_beautify = engine.Execute("global.js_beautify").GetCompletionValue();
var result = engine.Invoke(js_beautify, "var a = 2;").AsString();

JavaScript in Java code throwing exception

I'm trying to call a JavaScript function from Java code. My code is as follows:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
String script = baseUrl + "UIConfigurator/includes/js/DataCaptureFramework.js";
try {
LOGGER.info("evaluating engine");
LOGGER.info(script);
URL url1 = new URL(script);
LOGGER.info("url1 "+url1.getPath()+url1);
BufferedReader in = new BufferedReader(
new InputStreamReader(url1.openStream()));
String inputLine = null;
StringBuffer buffer = new StringBuffer();
while ((inputLine = in.readLine()) != null)
buffer.append(inputLine);
LOGGER.info(buffer.toString());
engine.eval(buffer.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
LOGGER.error(e.toString());
LOGGER.error("Throwing error in the catch part");
}
Invocable inv = (Invocable) engine;
try {
LOGGER.info("invoking function");
inv.invokeFunction("displayDataCapturePopUp("+user.getOrgId()+","+user.getId()+","+session.getLoginType()+");");
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ScriptException e) {
// TODO Auto-generated catch block
LOGGER.error("throwing error in catch block of invoking engine and function");
}
When I run this code it gives me the following error:
11:53:50,847 ERROR [Login] javax.script.ScriptException:
sun.org.mozilla.javascript.internal.EcmaError: ReferenceError:
"jQuery" is not defined. (#1) in at
line number 1 11:53:50,847 ERROR [Login] Throwing error in the catch
part 11:53:50,848 INFO [Login] invoking function 11:53:50,848 ERROR
[STDERR] java.lang.NoSuchMethodException: no such method:
displayDataCapturePopUp(301,1373864,0);
I tried a lot of things but still cannot get rid of this. Please tell me what I'm doing wrong. I'm trying to call the below function from JavaScript.
function displayDataCapturePopUp(orgId,userId,loginTypeId){ jQuery(" <link/>", {rel: "stylesheet",type: "text/css",href:
"/UIConfigurator/includes/css/librarycss/jquery-ui.min.css"}).appendTo("head"); jQuery("<link/>", {rel: "stylesheet",type: "text/css",href:
"/UIConfigurator/includes/css/DataCaptureFramework.css"}).appendTo("head"); jQuery("<link/>", {rel: "stylesheet",type: "text/css",href:
"/UIConfigurator/includes/css/librarycss/tooltipster.css"}).appendTo("head"); jQuery("<link/>", {rel: "stylesheet",type: "text/css",href:
"/UIConfigurator/includes/css/librarycss/jquery.alerts.css"}).appendTo("head");
jQuery.getScript('/UIConfigurator/includes/js/UiAjaxInteraction.js',function() {
jQuery.getScript('/iONjsLib/js/jquery-ui-1.10.4.min.js',function() {
jQuery.getScript('/iONjsLib/js/jquery.tooltipster.min.js',function() {
jQuery.getScript('/UIConfigurator/includes/js/libraryjs/jquery.alerts.js',function() {
jQuery.getScript('/iONjsLib/js/jquery.blockUI.js',function() {
getDataCapturePopUpDetails(orgId,userId,loginTypeId); }
);
}
);
}
);
}
);
}
);
}
ScriptEngine runs JavaScript in an entirely separate environment, with no access to your browser. It looks like you're trying to use it to show some kind of popup in your browser; this will not work. If you need to control your browser remotely, you need to use a different API, not ScriptEngine.

Call internal javascript function from java code

I have to call a javascript function named function startPolling() and created into hill.js file (/Demo MM/src/main/webapp/static/assets/js/hill.js) from java code. How can i do?Thanks
I'm using this code but receive exception
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
if (!(engine instanceof Invocable)) {
System.out.println("Invoking methods is not supported.");
return "500";
}
Invocable inv = (Invocable) engine;
String scriptPath = "/Demo MM/src/main/webapp/static/assets/js/hill.js";
try {
engine.eval("load('" + scriptPath + "')");
} catch (ScriptException e) {
return "500";
}
Make sure you are in the correct working directory to begin with. I get your code working.
To output working directory:
System.out.println("Working Directory = " +
System.getProperty("user.dir"));

Categories