ReferenceError: "alert" is not defined - java

I am trying to call a java script function from java code.
Here is my Java code
public static void main(String[] args) throws FileNotFoundException {
try {
/**
* To call a anonymous function from java script file
*/
ScriptEngine engine = new ScriptEngineManager()
.getEngineByName("javascript");
FileReader fr = new FileReader("src/js/MySpec.js");
engine.eval(fr);
} catch (ScriptException scrEx) {
scrEx.printStackTrace();
}
}
Here is my java script file:
(function() {
alert("Hello World !!!");
})();
But when I run main method of driver class it is giving me error as below:
Exception in thread "main" javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "alert" is not defined. (<Unknown source>#2) in <Unknown source> at line number 2
at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:110)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:232)
at Java6RhinoRunner.load(Java6RhinoRunner.java:42)
at Java6RhinoRunner.main(Java6RhinoRunner.java:12)
What I know is that it need some script engine to execute it.
For that I added rhino.jar file in to my class path.But this is not working.
I an not getting how to solve this error.
Please help.Thanks in advance.

alert is not part of JavaScript, it's part of the window object provided by web browsers. So it doesn't exist in the context you're trying to use it in. (This is also true of setInterval, setTimeout, and other timer-related stuff, FYI.)
If you just want to do simple console output, Rhino provides a print function to your script, so you could replace alert with print. Your script also has access to all of the Java classes and such, so for instance java.lang.System.out.println('Hello'); would work from your JavaScript script (although it's a bit redundant with the provided print function). You can also make Java variables available to your script easily via ScriptEngine.put, e.g:
engine.put("out", System.out);
...and then in your script:
out.println('Hello from JavaScript');
...so that's a third way to do output from the script. :-)
See the discussion in the javax.script package documentation, in particular ScriptEngine#put, or for more complex cases, Bindings (and SimpleBindings) and ScriptContext.

Related

Java program runs yet compilation fails

I wrote a Java program whose filename was (intentionally) different from the class I wrote inside the file. The javac command failed as expected on both CMD and WSL. The java command however worked and ran my print statement. I wrote the code intentionally this way so there is no way it was a previously compiled version of the code. The following code was written in a file called "explainJava.java" (notice the filename is different from the class name).
public class explain{
public static void main(String[] args) {
System.out.println("Java is weird");
}
}
I've had to google this myself, but I think I've found an explanation in this article.
According to that source as of Java 11 java is capable of compiling a single source file into memory.
What I conclude from that: When the file is compiled into memory and not written to disk it obviously cannot have a file name. If there is no filename there is no such thing as a wrong filename, therefore the code executes.
Please also note that the restriction of having to name a file like the public class within that file is more of a design decision to make work for the compiler easier/ faster. It is not a physical restriction so to speak. Have a look at the following thread for more details.
If you put this code:
public class explain {
public static void main(String[] args) {
System.out.println("Java is weird");
}
}
into a file named explainJava.java, and then compile it with this:
javac explainJava.java
you will get an error that correctly informs you that your filename ("explainJava") and the class defined inside that file ("explain") do not match:
explainJava.java:1: error: class explain is public, should be declared in a file named explain.java
public class explain{
^
1 error
If you run this command:
$ java explainJava.java
Java is weird
you see expected output, because you're skipping the explicit compilation step (that is, you aren't running javac first) and instead relying on behavior introduced in Java 11 that allows you to compile+run in a single step. Here's an explanation: Does the 'java' command compile Java programs?
So the answer is to either:
rename your file to match the class, so change the filename to "explain.java", or
rename the class to match the file, change public class explain to be public class explainJava

Is Jmeter Beanshell support invoke function from Kotlin jar file

I have Kotlin class:
class Ping {
fun ping(from: String): String{
return "Hello $from"
}
}
I've built jar file from this class. and included it to Jmeter and invoked it in BeanShell Sampler:
Ping ping = new Ping();
ping.ping("Jmeter");
it appear error Error invoking bsh method: eval Sourced file: inline evaluation of: ``Ping ping = new Ping(); ping.ping("Jmeter");'' : Method Invocation ping.ping
but I tried to change parameter of the method from string to int it work fine.
Any solution for this problem?
Thank you!
I cannot reproduce your issue using:
JMeter 5.4.1
Kotlin 1.5 (I copied the following .jars to JMeter Classpath just in case)
kotlin-reflect.jar
kotlin-reflect-sources.jar
kotlin-stdlib.jar
kotlin-stdlib-jdk7.jar
kotlin-stdlib-jdk7-sources.jar
kotlin-stdlib-jdk8.jar
kotlin-stdlib-jdk8-sources.jar
kotlin-stdlib-sources.jar
kotlin-test.jar
kotlin-test-sources.jar
The following sample code:
Ping ping = new Ping();
log.info(ping.ping("Jmeter"));
So double check your .jar file and JMeter Classpath. It also worth trying to put your code inside try block like
try {
Ping ping = new Ping();
log.info(ping.ping("Jmeter"));
}
catch (Exception ex) {
log.error("Beanshell failure", ex);
}
this way you will get the root cause of the problem in jmeter.log file
Also be aware that starting from JMeter 3.1 it's recommended to use JSR223 Test Elements and Groovy language for scripting so maybe it worth considering migrating to Groovy, see Apache Groovy - Why and How You Should Use It article for more details, it might be the case you won't need any Kotlin code.

Run matlab function in java class in absence of matlab environment

I want to use matlab function in java application. I create java package from my function by deploytool in matlab. Now, how can i use this package? Can only import the jar file created by deploytool in my java project and use its function?
After a lot of googling, I used this toturial but in the final step, i get error "could not load file".
Also i read about MatlabControl, but in this solution, we should have matlab environment in our system to java code running. But i will run my final app in systems that may not have matlab at all.
So i need a solution to run matlab function in java class even in absence of matlab environment.
Finally I solve my problem. the solution step by step is as follows:
write matlab function:
function y = makesqr(x)
y = magic(x);
Use deploytool in matlab and create java package.
3.create new java application in Eclipse and add main class. import javabuilde.jar and makesqr.jar:
import com.mathworks.toolbox.javabuilder.MWArray;
import com.mathworks.toolbox.javabuilder.MWClassID;
import com.mathworks.toolbox.javabuilder.MWNumericArray;
import makesqr.Class1;
and main.java:
public class main {
public static void main(String[] args) {
MWNumericArray n = null;
Object[] result = null;
Class1 theMagic = null;
try
{
n = new MWNumericArray(Double.valueOf(5),MWClassID.DOUBLE);
theMagic = new Class1();
result = theMagic.makesqr(1, n);
System.out.println(result[0]);
}
catch (Exception e)
{
System.out.println("Exception: " + e.toString());
}
finally
{
MWArray.disposeArray(n);
MWArray.disposeArray(result);
theMagic.dispose();
}
}
}
add javabuilder.jar and makesqr.jar to java build path of your project.
run it.
the Double.valueOf(3), define the input for our function and the output is as follows:
8 1 6
3 5 7
4 9 2
I didn't get properly your problem. Did you already compile the jar file from Matlab code and you are trying to use that, or you are at the last step of the tutorial?
If your answer is the latest case, most probably you forgot the "." before the class path.
From tutorial you linked:
You must be sure to place a dot (.) in the first position of the class path. If it not, you get a message stating that Java cannot load the class.
Also check if the matlab compiler path ("c:\Program Files\MATLAB\MATLAB Compiler Runtime\v82\toolbox\javabuilder\jar\javabuilder.jar" - in the tutorial) is correct for your system.

readFully not defined with Java Nashorn Javascript Engine

I am trying to run a javascript script with the new Java 8 Nashorn javascript engine but it fails with the following error:
<eval>:1 ReferenceError: "readFully" is not defined
The script uses the readFully function that should be defined in the global scope nashorn is run with the scripting mode enabled (wich is default when running through a ScriptEngine as seen here http://mail.openjdk.java.net/pipermail/nashorn-dev/2013-December/002562.html).
Here is a sample to reproduce the error:
import java.io.FileNotFoundException;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Test {
public static void main(String[] argv) throws FileNotFoundException, ScriptException {
ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("nashorn");
scriptEngine.eval("print('Hey!');print(print);print(readFully);");
}
}
This sample prints Hey ! and then the source code of the print function (another nashorn built-in function) and finally it should print the source code of the readFully method. But I have this Exception instead:
Exception in thread "main" javax.script.ScriptException: ReferenceError: "readFully" is not defined in <eval> at line number 1
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:586)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:570)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:525)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:521)
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:192)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
at com.github.bringking.maven.requirejs.Test.main(Test.java:14)
Caused by: <eval>:1 ReferenceError: "readFully" is not defined
at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:58)
at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:320)
at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:292)
at jdk.nashorn.api.scripting.NashornScriptEngine.__noSuchProperty__(NashornScriptEngine.java:272)
at jdk.nashorn.internal.scripts.Script$engine.L:35(nashorn:engine/resources/engine.js:37)
at jdk.nashorn.internal.scripts.Script$\^eval\_.runScript(<eval>:1)
at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:535)
at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:209)
at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:378)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:568)
... 5 more
When the sample script is run with the nashorn command line with the -scripting parameter (with the jjs tool of the jdk), all is fine. Here is the result of the same script:
Hey!
function print() { [native code] }
function readFully() { [native code] }
I could rewrite a readFully method and bind it with the script context, but I prefer to understand why it does not work and use already built-in functions.
Regards
Finally, I have implemented a readFully function that I use in my script (Only compatible with Nashorn):
function readFully(url) {
var result = "";
var imports = new JavaImporter(java.net, java.lang, java.io);
with (imports) {
var urlObj = null;
try {
urlObj = new URL(url);
} catch (e) {
// If the URL cannot be built, assume it is a file path.
urlObj = new URL(new File(url).toURI().toURL());
}
var reader = new BufferedReader(new InputStreamReader(urlObj.openStream()));
var line = reader.readLine();
while (line != null) {
result += line + "\n";
line = reader.readLine();
}
reader.close();
}
return result;
}
readFully is not a standard JavaScript function and it is likely not standard in Nashorn either.
There were similar issues when Rhino was chosen for inclusion in the Sun implementation of Java 6. The scripting tool may provide enhancements that are not present in the embedded API. readFully is not a documented function in the Java 8 Nashorn API.
In previous versions of Java the specification stated that provided scripting engines were an implementation detail of the JRE vendor. I am not aware if Java 8 makes anything about the engines provided mandatory or whether it makes any future compatibility guarantees. I would check JSR-337 thoroughly if this was likely to be an issue.
https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions
readFully (-scripting mode only)
This function reads the entire contents of a file passed in as a string argument and sends it to stdout, or you can assign the result to a variable.
readFully example:
jjs> readFully("text.txt")
This is the contents of the text.txt file located in the current working directory.
readFully is enabled only in scripting mode. Nashorn docs
try this:
>>jjs -scripting
jjs> readFully("your_file")
readFully() function is only available as built in function in nashorgn when you enable scripting in you application
There are two ways you can do this:-
pass -Dnashorn.args=-scripting when you run your application to enable nashorn
scripting
Enable it programmatically by creating Nashorn engine with scripting args
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine(new String[] { "-scripting" });

Getting "class does not have a static void main method accepting String[]" error even though main signature is correct

My DrJava was working fine, but now I keep getting the folowing error whenever I run anything:
Static Error: This class does not have a static void main method accepting String[].
So it will compile OK, but then it shoots out the error . This happens even though everything I test does indeed have a public static void main(String[] args) in it. It seems like a classpath/resources type of error. I appreciate any tips
EDIT: my class
public class Test{
public static void main(String[] args){
System.out.println(" hashmap ");
}
}
There's nothing wrong with the code, so the problem must be with the environment.
Check that you're actually executing that class. Find out where the class that's executed is specified and check it's correct
Check that you're compiling the class. Maybe the code you're looking at has not been compiled and you're trying to execute an old version that was compild before you coded a main()
Check your classpath. Is the compiled class accessible in the classpath of the java command
You don't need to reinstall java, nor is it a java version issue. It may be the way that your are running the program.
To check if it is a problem with your code, do the following:
Make a new folder and put Test.java in it.
Open up Command Line Or Terminal and change to that folder .
Type javac Test.java. Test.class should be in the folder now.
If you want, open up the class with a text editor. This is what I get:
˛∫æ2
<init>()VCodeLineNumberTablemain([Ljava/lang/String;)V
SourceFile Test.java hashmap Testjava/lang/Objectjava/lang/SystemoutLjava/io/PrintStream;java/io/PrintStreamprintln(Ljava/l ang/String;)V! *∑±
% ≤∂±
Back to the command line or terminal, type java Test.
If you get an error, which you shouldn't, I don't know what to say. It should produce the string " hashmap " on to the command line or terminal.
Why re-installing Dr. Java may not work is because you may be using the same working directory, causing same run settings to be used. Dr. Java may be running an external program, one without a main method.
I think that you should install the Eclipse IDE for Java. It is much easier to get around, it looks nicer, and it runs the file or project that you are looking at currently.
Sometimes this problem happens because may be mistake in saving file.you always your file using double quotes and with the .java extension which is main class means that class containing main method.
you should save your file by class name which is public .if there is two classes and both have main method then you should save your file by class name that is public and that class will be run.As like your compiler looking for main method in public static void main(String [] args) that is contract for jvm to run a programme
so it is not able to found that main method that is static and it looking for your Dr class.java
See this Example it have two main methods and practice these kinds of question.I also got this kind of problem in starting.
public class TestFirst
{
public static void main(String [] args){
System.out.println(" TestFirst ");
}
}
class Test{
public static void main(String [] args){
System.out.println(" hashmap ");
}
}
if you save pro-gramme by "TestFirst.java" then o/p will come TestFirst if you do some mistake in main method because we have saved our programme by TestFirst then you will get error like you got.
# 2nd mistake may be this
debian#debian:~/Geany_java$ javac Test1.java
debian#debian:~/Geany_java$ java Test1
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at Test1.main(Test1.java:11)
your classpath has not set properly See above Compiling successfully but running showing same kind of error you got.Which OS is using I can guide you properly.
Check that actually your file have the .java termination nor the .dj
There is nothing wrong with the code.
It is the executing environment which might have problem. Please share the details.
Check if program compiled correctly.
Check time-stamo of .class file.
Check permissions on folder/directory where class-files are getting generated.
Check if DrJAVA has appropriate permission on the directory.
Did you create a file, compiled it with out main?
Check class-path. Might be possible that previous class file is still being found by JDK in classpath.
Try compiling .java file from cmdLine instead of editor.
As others have mentioned, your code is fine. There must be a problem with your environment. I recently experienced a similar issue when investigating and answering this question.
Basically, in that question, the code Void.class instanceof Class resulted in a compiler error because a user-made Class.class existed in the classpath, so one Class (the Java built-in java.lang.Class) didn't match with the given Class (user-made).
Something similar may be at work here. It is possible that there is a user-made String.class in your classpath. Then in your main signature, String[] args would mean an array of your String, when Dr. Java must be looking for a main method taking an array of the Java built-in String, i.e. java.lang.String[]. If you have a custom String class in your classpath (or in your project?), then the Java compiler will choose it over the built-in String. If you were to compile and run your Test class from the command line, then you would get the runtime error: Exception in thread "main" java.lang.NoSuchMethodError: main.
Following #S0urceC0ded's suggestion, you may find this when looking at Test.class in a text editor:
main([LString;)V // A user-made String class
instead of what it's supposed to be:
main([Ljava/lang/String;)V // The built-in java.lang.String class
If so, remove your own String class (at least the .class file, but also the .java file so the .class file isn't re-created) from the classpath, and compile and run your Test class again.
Without a look at your environment, I can't tell for sure that this is the issue. But it can explain it.
If you are using Dr.Java as IDE, then you need to make sure that the main class containing 'public static void main' should be at the very top of your program. Otherwise Dr.Java throws this error during runtime.

Categories