Nodejs: Spawn jar (non executable) - java

I have a Java jar file, which is not executable(does not have a main method).
However I would like to invoke a particular class and its methods from my node.js application. I am currently using the below:
var child = require('child_process').spawn(
'java', ['-cp', "abc.jar", com.abc.ABCClass]
);
How now can I invoke the method in the ABCClass with appropriate arguments?
I currently get an exception such as below:
A JNI error has occurred, please check your installation and try again
Exception in thread "main"
Error: java.lang.NoClassDefFoundError:
org/apache/kafka/clients/consumer/KafkaConsumer
Thanks in advance. I am looking for a solution to call the method in that class.

Related

How to provide the -Dlogback.configurationFile=./logback.xml option in nodejs spawn method

I have angular2-node.js application. I am executing a jar file through the node server.
Jar execution is happening fine but it's using the logback.xml present in the jar file.
Node js code:
app.get('/report/:parameter1/:parameter2', function(req, res) {
var fileName = path.join(__dirname, '..', 'javaFile', 'xyz.jar');
spawn('/usr/bin/java', ['-jar ', fileName, parameter1 , parameter2, '&'],{
stdio : ['ignore', out, err],
detached : true }).unref();
data = '{response: Success}';
res.status(200).json(data);
res.end();
});
I want to refer the different logback.xml file for jar execution while running the jar from UI. So, i tried the below code:
spawn('/usr/bin/java', ['-jar -Dlogback.configurationFile=./logback.xml', fileName, cacheName , cacheType, '&'],{
stdio : ['ignore', out, err],
detached : true }).unref();
But, it also didn't work and throw the below error:
Unrecognized option: -jar -Dlogback.configurationFile=./logback.xml
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
I am new to node js. I searched the web but couldn't get an answer.
Is there any way to provide the logback.xml file dynamically in node.js code something like we do in shell script like below:
nohup java -jar -Dlogback.configurationFile=./logback.xml xyz.jar
Can anyone provide any solution for this.
The args arguments is <string[]>, so you should split the multiple args into multiple elements of the array, like you've done for the other arguments. You can check the signature of the method here.
Try,
spawn('/usr/bin/java', ['-jar', '-Dlogback.configurationFile=./logback.xml'], ....

java.lang.NoSuchMethodError - Ljava/lang/String;)Ljava/lang/String;

My code is giving an error below;
Exception in thread "main" java.lang.NoSuchMethodError:
com/myApp/Client.cypherCBC(Ljava/lang/String;)Ljava/lang/String;
But it's working fine in an another local environment. My code so far is below;
try {
System.out.println("Encrypted CBC passwd : "
+ Client.cypherCBC("CypherThePassword"));
} catch (Exception e) {
e.printStackTrace();
}
This is due to a run-time JAR or class mismatch. the "Client" class which was there at the time you compile your application has a static method "cypherCBC" which gets String parameter, but at run-time class loader has loaded the "Client" class which doesn't have that kind of method (same name with same signature).
if you can debug the application at runtime, put a break-point at the line which exception was thrown, then try to evaluate following expression,
Client.class.getResource("Client.class")
, then you can find where the class has been leaded from, then you can decompile and try to troubleshoot the issue.
I got the same error while running a web application in Weblogic.
The reason for this error is there are two versions of classes are in the environment.To fix this you have to figure out which .class is using at the run time.
I used following to identify which class is loaded at run time.
-verbose:class
There is a duplicate class on your classpath.
So, That is why JVM is getting confused that which one needs to pick because both classes have a same method with a different signature that you are trying to call.

java.lang.NoSuchMethodError when sending mail using Apache James 3

I just downloaded and setup the Apache James 3 latest beta release on Windows and so far i haven't been able to send a simple message. It looks like there is an issue with the build. The error is -
ERROR 22:45:01,666 | james.mailspooler | Exception processing mail while spooling Unable to process mail Mail1442234701295-757cd62b-eeed-4671-828c-2a7c715acfaa (org.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange: Exchange[Message: org.apache.james.core.MailImpl#4262d5d7])
javax.mail.MessagingException: Unable to process mail Mail1442234701295-757cd62b-eeed-4671-828c-2a7c715acfaa (org.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange: Exchange[Message: org.apache.james.core.MailImpl#4262d5d7])
.
.
Caused by: javax.mail.MessagingException: Unable to process mail Mail1442234701295-757cd62b-eeed-4671-828c-2a7c715acfaa (org.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange: Exchange[Message: org.apache.james.core.MailImpl#4262d5d7])
.
.
Caused by: org.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange: Exchange[Message: org.apache.james.core.MailImpl#4262d5d7]
.
.
Caused by: java.lang.NoSuchMethodError: org.apache.james.mime4j.stream.MimeConfig: method <init>()V not found
The relevant class in the JAR shows the supposedly missing constructor so i am at a complete loss. Can anyone guide me in the right direction please?
Thanks in advance!
Edit: Decompiled code snippet from the MimeConfig class shows the constructor
public final class MimeConfig {
/* member class not found */
class Builder {}
.
.
MimeConfig(boolean strictParsing, int maxLineLen, int maxHeaderCount, int maxHeaderLen, long maxContentLen, boolean countLineNumbers,
String headlessParsing, boolean malformedHeaderStartsBody) {
/* 53*/ this.strictParsing = strictParsing;
/* 54*/ this.countLineNumbers = countLineNumbers;
/* 55*/ this.malformedHeaderStartsBody = malformedHeaderStartsBody;
/* 56*/ this.maxLineLen = maxLineLen;
/* 57*/ this.maxHeaderCount = maxHeaderCount;
/* 58*/ this.maxHeaderLen = maxHeaderLen;
/* 59*/ this.maxContentLen = maxContentLen;
/* 60*/ this.headlessParsing = headlessParsing;
}
I got the same error and was searching for an answer. The error is because MimeConfig doesn't have a default constructor. I could get the mail successfully delivered locally by doing to following.
Dowloaded apache-mime4j-core-0.8.0-20150617.024907-738-sources
Created a default public constructor for MimeConfig
Initialized all the variables with values shown in the static class Builder constructor
Added setters for all the variables (Because I was getting NoSuchMethodError for setMaxLineLen)
Created a jar called apache-mime4j-0.8.0-fix.jar and pushed into the lib folder
I use run.sh, so replaced the mime4j core jar name with the above one.
I am sure there is some mismatch between spooler and mime4j. I think the calling code should use the Builder instead of directly trying to instantiate the MimeConfig.
Try these and let me know if it works. It worked for me. I am not sure if this is a permanent fix, but I can go ahead with exploring the V3 features till we get a permanent solution.
The solution is to use the : apache-mime4j-core-0.7.2.jar and apache-mime4j-dom-0.7.2.jar
download the two jars and put them in : james-server-app-3.0.0-beta5-SNAPSHOT\lib.
You can download james-server-app-3.0.0-beta5 from : https://repository.apache.org/content/repositories/snapshots/org/apache/james/james-server-app/3.0.0-beta5-SNAPSHOT/.

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.

ReferenceError: "alert" is not defined

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.

Categories