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"));
Related
I have a springboot app that calls a .jsx script. It is a simple script, just read a JSON file and print some values on console.
My problem is when I try to get the output and log on my springboot app.
When I run the script using ExtendToolkit Script, I get the follow info on console:
Id: 6989996500
Result: undefined
But, when I run through Springboot, the output is:
Exit status: 0
Output: [TypeQuest] Timestamp=2023-02-01T05:00:19.434 ThreadId=6304 Type=TQ_WARN Component=TQFontManager Description="Not using user-specific cache directory; using: C:\Users\lnrei\AppData\Roaming\Adobe\typequest.2"
Here is my spring code:
`
try {
String[] command = {"C:\\Program Files\\Adobe\\Adobe Photoshop 2022\\Photoshop.exe",
"-r",
"C:\\Users\\lnrei\\OneDrive\\Documentos\\Projeto\\Photoshop Scripts\\scriptPSthumbnail.jsx"};
//Process process = new ProcessBuilder(command).start();
Process process = Runtime.getRuntime().exec(command);
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while((line = reader.readLine()) != null)
output.append(line + "\n");
int exit = process.waitFor();
System.out.println("Exit status: " + exit);
System.out.println("Output: " + output);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}`
As you can see, I trying to use process.getInputStream() to catch the output and sendo to a string.
Here is my .jsx file:
`
#include "json2.js";
var contentPath = "C:/Users/lnrei/OneDrive/Documentos/Projeto/content/content.json";
var contentFile = new File(contentPath);
if(contentFile.exists) {
contentFile.open("r");
var jsonStr = contentFile.read ();
contentFile.close ();
var content = JSON.parse(jsonStr);
$.writeln ("Id: " + content.matchId)
} else {
$.writeln ("Error handling the file!");
}
$.writeln();
photoshop.quit();`
Am working on protractor framework and I need to upload files to the application using a script.I know how to do it in java but no idea in javascript. Can someone please help me on this:
Java code :
public static void fileUpload(String script, String filePath) {
try {
Process proc = Runtime.getRuntime().exec("script " + script + " " + filePath);
BufferedReader read = new BufferedReader(new InputStreamReader(proc.getInputStream()));
try {
proc.waitFor();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}catch (IOException e) {
System.out.println(e.getMessage());
}
}
Thanks !
Not sure what you meant by script here. Using sendkeys with upload input element should work in protractor.
like :
var path = require('path');
var fileToUpload = '../test-resources/filetoupload'; //(the example relative path of the file )
var absolutePath = path.resolve(__dirname, fileToUpload);
element(by.css('input[type="file"]')).sendKeys(absolutePath);
uploadButton().click();
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);
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();
}
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.