Installations
npm install java
Score
59.8
Supply Chain
96.7
Quality
75
Maintenance
100
Vulnerability
97.6
License
Releases
Unable to fetch releases
Developer
joeferner
Developer Guide
Module System
CommonJS
Min. Node Version
>=7.0.0
Typescript Support
No
Node Version
20.10.0
NPM Version
10.2.3
Statistics
1,876 Stars
617 Commits
282 Forks
70 Watching
6 Branches
55 Contributors
Updated on 27 Nov 2024
Languages
C++ (48.27%)
JavaScript (42.33%)
Java (6.19%)
Shell (1.41%)
Python (1.37%)
Dockerfile (0.33%)
HTML (0.1%)
Total Downloads
Cumulative downloads
Total Downloads
6,624,588
Last day
-4.5%
3,086
Compared to previous day
Last week
5%
17,789
Compared to previous week
Last month
4.5%
75,188
Compared to previous month
Last year
20.9%
917,298
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Bridge API to connect with existing Java APIs.
Google Groups Discussion Forum
Other projects that might be helpful
- node-java-maven - manages your node-java classpath by using maven dependency management.
Installation
1$ npm install java
Notes:
- node-gyp requires python 2.x not python 3.x. See https://github.com/TooTallNate/node-gyp/issues/155 for more details.
- If you see an error such as "Call to 'node findJavaHome.js' returned exit status 1"
Try running
node findJavaHome.js
in the node-java directory to see the full failure message. - If you are having problems finding 'jni.h'. Make sure you have the JDK installed not just the JRE. If you are using OpenJDK you want the openjdk-7-jdk package, not openjdk-7-jre. Mavericks users see Issue #86 if you run into this.
Installation Ubuntu
sudo apt install make g++
- If u've error (on global installation):
EACCES user nobody does not have permission to access the dev dir /root/.cache/node-gyp/10.16.0
, then just run:npm i -g java --unsafe-perm
Installation OSX
- If you run into strange runtime issues, it could be because the Oracle JDK does not advertise itself as available for JNI. See Issue 90 for more details and manual workarounds. If this does occur for you, please update the issue.
Installation Windows
For 64 bit installs with 32 bit node:
- you need the 32 bit JDK, with the 64 bit JDK you will see LNK2001 errormessages (http://stackoverflow.com/questions/10309304/what-library-to-link-to-on-windows-7-for-jni-createjavavm).
- when using the windows SDK 7.1 command prompt (64 bits) be sure to setenv.cmd /Release /x86
If you get ENOENT
errors looking for <nodepath>\node_modules\node-gyp\..
, ensure you have node-gyp installed as a global nodule:
1npm install -g node-gyp
If you get D9025
warnings and C1083
errors when looking for .sln
or .h
files, be sure you've got the node-gyp
's dependencies, as explained here.
Alternatively, Windows users can easily install all required tools by running the following command in PowerShell as administrator. For more information see windows-build-tools project page:
1npm install --global --production windows-build-tools
Installation ARM (Raspberry Pi)
1GYP_DEFINES="armv7=0" CCFLAGS='-march=armv6' CXXFLAGS='-march=armv6' npm install java
Manual compile (Using node-gyp)
1./compile-java-code.sh 2node-gyp configure build 3npm test
NOTE: You will need node-gyp installed using "npm install -g node-gyp"
On Raspian you might need a:
- sudo ln -s /usr/lib/jvm/jdk-7-oracle-arm-vfp-hflt /opt/jdk
Some issues with the OpenSDK7 so take the Oracle version for compiling.
Docker
If you want to play with node-java but don't want to setup the build environment you can run it in docker.
docker run -it joeferner/node-java bash
Then inside the docker container create a directory and run
1npm install --unsafe-perm java
Then create a file called test.js
with the following contents
var java = require('java');
var javaLangSystem = java.import('java.lang.System');
javaLangSystem.out.printlnSync('Hello World');
Then run
1node test.js
Java 1.8 support
Manual compilation for Java 1.8 support requires additional steps:
1./compile-java-code.sh 2./compile-java8-code.sh 3node-gyp configure build 4npm test
Java 1.8 language features can be used in Java classes only if a Java 1.8 JRE is available. The script compile-java8-code.sh is used only to compile java classes used in the 'test8' unit tests, but these classes are checked into the test8/ directory. Note that unit tests in the test8/ directory will pass (by design) if run against a Java 1.7 JRE, provided that a java.lang.UnsupportedClassVersionError is caught with the message 'Unsupported major.minor version 52.0' (the expected behavior when Java 1.8 language features are used in an older JRE).
Installation node-webkit
1npm install -g nw-gyp 2npm install java 3cd node_modules/java 4nw-gyp configure --target=0.10.5 5nw-gyp build
See testIntegration/webkit for a working example
Using node-java in existing maven projects
When using node-java in existing maven projects, all the dependencies and the class files of the project have to be pushed to the classpath.
One possible solution would be:
Issue the command:
mvn dependency:copy-dependencies
Then create the following module javaInit:
1"use strict"; 2var fs = require("fs"); 3var java = require("java"); 4var baseDir = "./target/dependency"; 5var dependencies = fs.readdirSync(baseDir); 6 7dependencies.forEach(function(dependency){ 8 java.classpath.push(baseDir + "/" + dependency); 9}) 10 11java.classpath.push("./target/classes"); 12java.classpath.push("./target/test-classes"); 13 14exports.getJavaInstance = function() { 15 return java; 16}
and then in the consuming class write:
1 2var javaInit = require('./javaInit'); 3var java = javaInit.getJavaInstance(); 4 5//your code goes here
Quick Examples
1var java = require("java"); 2java.classpath.push("commons-lang3-3.1.jar"); 3java.classpath.push("commons-io.jar"); 4 5var list1 = java.newInstanceSync("java.util.ArrayList"); 6console.log(list1.sizeSync()); // 0 7list1.addSync('item1'); 8console.log(list1.sizeSync()); // 1 9 10java.newInstance("java.util.ArrayList", function(err, list2) { 11 list2.addSync("item1"); 12 list2.addSync("item2"); 13 console.log(list2.toStringSync()); // [item1, item2] 14}); 15 16var ArrayList = java.import('java.util.ArrayList'); 17var list3 = new ArrayList(); 18list3.addSync('item1'); 19list3.equalsSync(list1); // true
Create a char array
1var charArray = java.newArray("char", "hello world\n".split(''));
Create a byte array
1var byteArray = java.newArray( 2 "byte", 3 "hello world\n" 4 .split('') 5 .map(function(c) { return java.newByte(String.prototype.charCodeAt(c)); }));
Using java.lang.Long and long
JavaScript only supports 32-bit integers. Because of this java longs must be treated specially. When getting a long result the value may be truncated. If you need the original value there is a property off of the result called "longValue" which contains the un-truncated value as a string. If you are calling a method that takes a long you must create it using java.newInstance.
1var javaLong = java.newInstanceSync("java.lang.Long", 5); 2console.log('Possibly truncated long value: ' + javaLong); 3console.log('Original long value (as a string): ' + javaLong.longValue); 4java.callStaticMethodSync("Test", "staticMethodThatTakesALong", javaLong);
Exceptions
Exceptions from calling methods either caught using JavaScript try/catch block or passed to a callback as the first parameter may have a property named "cause" which has a reference to the Java Exception object which caused the error.
1try { 2 java.methodThatThrowsExceptionSync(); 3} catch(ex) { 4 console.log(ex.cause.getMessageSync()); 5}
AsyncOptions: control over the generation of sync, async & promise method variants.
As of release 0.4.5 it became possible to create async methods that return promises by setting the asyncOptions
property of the java object. With release 0.4.7 this feature is extended to allow changing the suffix assigned for sync and async method variants, and to further configure this module to optionally omit generation of any of these variants.
Example:
1var java = require("java"); 2java.asyncOptions = { 3 asyncSuffix: undefined, // Don't generate node-style methods taking callbacks 4 syncSuffix: "", // Sync methods use the base name(!!) 5 promiseSuffix: "Promise", // Generate methods returning promises, using the suffix Promise. 6 promisify: require('util').promisify // Needs Node.js version 8 or greater, see comment below 7}; 8java.classpath.push("commons-lang3-3.1.jar"); 9java.classpath.push("commons-io.jar"); 10 11java.import("java.util.ArrayList"); // see NOTE below 12 13java.newInstancePromise("java.util.ArrayList") 14 .then(function(list) { return list.addPromise("item1"); }) 15 .then(function(list) { return list.addPromise("item2"); }) 16 .catch(function(err) { /* handle error */ });
NOTES:
- If you want the defacto standard behavior, simply don't set java.asyncOptions.
- If you do provide asyncOptions, be aware that this module will not generate method variants of a given flavor if you don't provide a string value for the corresponding suffix (
asyncSuffix
,syncSuffix
,promiseSuffix
). In the example above, the application is configured to omit the method variants using node-style async callback functions. - If you provide
asyncOptions.promiseSuffix
then you must also setasyncOptions.promisify
to a function that promisifies a node-style async function. I.e. the provided function must take as input a function whose last argument is a node callback function, and it must return an equivalent promise-returning function. Several Promises/A+ libraries provide such functions, but it may be necessary to provide a wrapper function. SeetestHelpers.js
for an example. - For
promisify
implementation, if you are using Node.js version 8.0.0 or newer thenpromisify: require('util').promisify
will work out of the box. If you need to support and older Node.js version then an implementation needs to be provided, for example,promisify: require("when/node").lift
- If you provide
asyncOptions.promisify
then you must provide a non-empty string forasyncOptions.promiseSuffix
. - Either (but not both)
asyncSuffix
orsyncSuffix
can be the empty string. If you want the defacto standard behavior for no suffix on async methods, you must provide an empty string forasyncSuffix
. - We've tested promises with five Promises/A+ implementations. See
testHelpers.js
for more information. - NOTE: Due to specifics of initialization order, the methods
java.newInstancePromise
,java.callMethodPromise
, andjava.callStaticMethodPromise
are not available until the JVM has been created. You may need to call some other java method such asjava.import()
to finalize java initialization, or even better, the functionjava.ensureJvm()
.
Special note about the exported module functions newInstance
, callMethod
, and callStaticMethod
.
These methods come in both async and sync variants. If you provide the promisify
and promiseSuffix
attributes in asyncOptions then you'll also get the Promises/A+ variant for these three functions. However, if you change the defacto conventions for the syncSuffix
(i.e. 'Sync') and/or asyncSuffix
(i.e. '') it will not affect the naming for these three functions. I.e. no matter what you specify in asyncOptions, the async variants are named newInstance
, callMethod
, and callStaticMethod
, and the sync variants are named newInstanceSync
, callMethodSync
, and callStaticMethodSync
.
Varargs support
With v0.5.0 node-java now supports methods with variadic arguments (varargs). Prior to v0.5.0, a JavaScript call to a Java varargs method had to construct an array of the variadic arguments using java.newArray()
. With v0.5.0 JavaScript applications can simply use the variadic style.
In most cases it is still acceptable to use java.newArray()
. But it is now possible to pass a plain JavaScript array, or use the variadic style. For example, consider these snippets from the unit test file test/varargs-test.js
:
test.equal(Test.staticVarargsSync(5, 'a', 'b', 'c'), '5abc');
test.equal(Test.staticVarargsSync(5, ['a', 'b', 'c']), '5abc');
test.equal(Test.staticVarargsSync(5, java.newArray('java.lang.String', ['a', 'b', 'c'])), '5abc');
Note that when passing a JavaScript array (e.g. ['a', 'b', 'c']
) for a varargs parameter, node-java must infer the Java type of the array. If all of the elements are of the same JavaScript primitive type (string
in this example) then node-java will create a Java array of the corresponding type (e.g. java.lang.String
). The Java types that node-java can infer are: java.lang.String
, java.lang.Boolean
, java.lang.Integer
, java.lang.Long
, and java.lang.Double
. If an array has a mix of Integer
, Long
, and Double
, then the inferred type will be java.lang.Number
. Any other mix will result in an inferred type of java.lang.Object
.
Methods accepting varargs of a generic type are also problematic. You will need to fall back to using java.newArray()
. See Issue #285.
JVM Creation
With v0.5.1 a new API is available to make it easier for a complex application to have full control over JVM creation. In particular, it is now easier to compose an application from several modules, each of which must add to the Java classpath and possibly do other operations just before or just after the JVM has been created. See the methods ensureJvm and registerClient. See also several of the tests in the testAsyncOptions directory.
Release Notes
v0.5.0
- Support for varargs. This change is not 100% backwards compatible, but the fix is generally easy and results in more natural code.
v0.2.0
Index
java
- classpath
- options
- asyncOptions
- import
- newInstance
- instanceOf
- callStaticMethod
- callMethod
- getStaticFieldValue
- setStaticFieldValue
- newArray
- newByte
- newShort
- newLong
- newChar
- newDouble
- newFloat
- newProxy
- isJvmCreated
- registerClient
- registerClientP
- ensureJvm
java objects
API Documentation
java
classpath
java.classpath*
Array of paths or jars to pass to the creation of the JVM.
All items must be added to the classpath before calling any other node-java methods.
Example
java.classpath.push('commons.io.jar');
java.classpath.push('src');
options
java.options*
Array of options to pass to the creation of the JVM.
All items must be added to the options before calling any other node-java methods.
Example
java.options.push('-Djava.awt.headless=true');
java.options.push('-Xmx1024m');
asyncOptions
1java.asyncOptions = { 2 asyncSuffix: undefined, // Don't generate node-style methods taking callbacks 3 syncSuffix: "", // Sync methods use the base name(!!) 4 promiseSuffix: "Promise", // Generate methods returning promises, using the suffix Promise. 5 promisify: require('util').promisify // Needs Node.js version 8 or greater, see comment below 6 ifReadOnlySuffix: "_alt" 7};
asyncSuffix
Suffix for callback-based async method call signatures.syncSuffix
Suffix for synchronous method call signatures.promiseSuffix
Suffix for promise-based async method call signaturespromisify
Callback-to-promise transform implementation. From Node.js version 8 one can just use Node.js implementation:promisify: require('util').promisify
.ifReadOnlySuffix
See Static Member Name Conflicts.
See Async Options for details.
import
java.import(className)*
Loads the class given by className such that it acts and feels like a JavaScript object.
Arguments
- className - The name of the class to create. Separate nested classes using
'$'
(eg.com.nearinfinty.MyClass$NestedClass
).
Example
var Test = java.import('Test');
Test.someStaticMethodSync(5);
console.log(Test.someStaticField);
var value1 = Test.NestedEnum.Value1;
var test = new Test();
list.instanceMethodSync('item1');
newInstance
java.newInstance(className, [args...], callback)*
java.newInstanceSync(className, [args...]) : result
Creates an instance of the specified class. If you are using the sync method an exception will be throw if an error occurs, otherwise it will be the first argument in the callback.
Arguments
- className - The name of the class to create. Separate nested classes using
'$'
(eg.com.nearinfinty.MyClass$NestedClass
). - callback(err, item) - Callback to be called when the class is created.
Example
var list = java.newInstanceSync("java.util.ArrayList");
java.newInstance("java.util.ArrayList", function(err, list) {
if(err) { console.error(err); return; }
// new list
});
instanceOf
java.instanceOf(javaObject, className)*
Determines of a javaObject is an instance of a class.
Arguments
- javaObject - Instance of a java object returned from a method or from newInstance.
- className - A string class name.
Example
var obj = java.newInstanceSync("my.package.SubClass");
if(java.instanceOf(obj, "my.package.SuperClass")) {
console.log("obj is an instance of SuperClass");
}
callStaticMethod
java.callStaticMethod(className, methodName, [args...], callback)*
java.callStaticMethodSync(className, methodName, [args...]) : result
Calls a static method on the specified class. If you are using the sync method an exception will be throw if an error occurs, otherwise it will be the first argument in the callback.
Arguments
- className - The name of the class to call the method on. Separate nested classes using
'$'
(eg.com.nearinfinty.MyClass$NestedClass
). - methodName - The name of the method to call. The method name can include the full signature (see Getting the full method signature).
- callback(err, item) - Callback to be called when the class is created.
Example
var result = java.callStaticMethodSync("com.nearinfinty.MyClass", "doSomething", 42, "test");
java.callStaticMethod("com.nearinfinty.MyClass", "doSomething", 42, "test", function(err, results) {
if(err) { console.error(err); return; }
// results from doSomething
});
callMethod
java.callMethod(instance, methodName, [args...], callback)*
java.callMethodSync(instance, methodName, [args...]) : result
Calls a method on the specified instance. If you are using the sync method an exception will be throw if an error occurs, otherwise it will be the first argument in the callback.
Arguments
- instance - An instance of the class from newInstance.
- methodName - The name of the method to call. The method name can include the full signature (see Getting the full method signature).
- callback(err, item) - Callback to be called when the class is created.
Example
var instance = java.newInstanceSync("com.nearinfinty.MyClass");
var result = java.callMethodSync("com.nearinfinty.MyClass", "doSomething", 42, "test");
java.callMethodSync(instance, "doSomething", 42, "test", function(err, results) {
if(err) { console.error(err); return; }
// results from doSomething
});
getStaticFieldValue
java.getStaticFieldValue(className, fieldName)*
Gets a static field value from the specified class.
Arguments
- className - The name of the class to get the value from. Separate nested classes using
'$'
(eg.com.nearinfinty.MyClass$NestedClass
). - fieldName - The name of the field to get the value from.
Example
var data = java.getStaticFieldValue("com.nearinfinty.MyClass", "data");
setStaticFieldValue
java.setStaticFieldValue(className, fieldName, newValue)*
Sets a static field value on the specified class.
Arguments
- className - The name of the class to set the value on. Separate nested classes using
'$'
(eg.com.nearinfinty.MyClass$NestedClass
). - fieldName - The name of the field to set the value on.
- newValue - The new value to assign to the field.
Example
java.setStaticFieldValue("com.nearinfinty.MyClass", "data", "Hello World");
newArray
java.newArray(className, values[])*
Creates a new java array of given glass type. To create array of primitive types like char
, byte
, etc, pass the primitive type name (eg. java.newArray("char", "hello world\n".split(''))
).
Arguments
- className - The name of the type of array elements. Separate nested classes using
'$'
(eg.com.nearinfinty.MyClass$NestedClass
). - values - A JavaScript array of values to assign to the java array.
Example
var newArray = java.newArray("java.lang.String", ["item1", "item2", "item3"]);
newByte
java.newByte(val)*
Creates a new java byte. This is needed because JavaScript does not have the concept of a byte.
Arguments
- val - The value of the java byte.
Example
var b = java.newByte(12);
newShort
java.newShort(val)*
Creates a new java short. This is needed because JavaScript does not have the concept of a short.
Arguments
- val - The value of the java short.
Example
var s = java.newShort(12);
newLong
java.newLong(val)*
Creates a new java long. This is needed because JavaScript does not have the concept of a long.
Arguments
- val - The value of the java long.
Example
var s = java.newLong(12);
newChar
java.newChar(val)*
Creates a new java char. This is needed because JavaScript does not have the concept of a char.
Arguments
- val - The value of the java char.
Example
var ch = java.newChar('a');
newDouble
java.newDouble(val)*
Creates a new java double. This is needed to force JavaScript's number to a double to call some methods.
Arguments
- val - The value of the java double.
Example
var d = java.newDouble(3.14);
newFloat
java.newFloat(val)*
Creates a new java float. This is needed to force JavaScript's number to a float to call some methods.
Arguments
- val - The value of the java float.
Example
var f = java.newFloat(3.14);
newProxy
java.newProxy(interfaceName, functions)*
Creates a new java Proxy for the given interface. Functions passed in will run on the v8 main thread and not a new thread.
The returned object has a method unref() which you can use to free the object for garbage collection.
Arguments
- interfaceName - The name of the interface to proxy. Separate nested classes using
'$'
(eg.com.nearinfinty.MyClass$NestedClass
). - functions - A hash of functions matching the function in the interface.
Example
var myProxy = java.newProxy('java.lang.Runnable', {
run: function () {
// This is actually run on the v8 thread and not the new java thread
console.log("hello from thread");
}
});
var thread = java.newInstanceSync("java.lang.Thread", myProxy);
thread.start();
isJvmCreated
java.isJvmCreated()*
Returns true if the JVM has been created. The JVM can only be created once.
registerClient
java.registerClient(before, after)*
Register that a client wants to be called back immediately before and/or immediately after the JVM is created. If used, this function must be called before the JVM has been created. The before function is typically used to add to the classpath. The function may execute asynchronous operations (such as a async glob function). The after function is sometimes useful for doing one-time initialization that requires the JVM to first be initialized. If either function is unnecessary, use null
or undefined
. See also registerClientP
and ensureJvm
. See the unit tests in testAsyncOptions
for examples.
registerClientP
java.registerClientP(before, after)*
Like java.registerClient, but before and after are assumed to be functions returning promises.
ensureJvm
java.ensureJvm(callback)*
If the JVM has not yet been created, execute the full JVM initialization process, then call callback function when initialization is complete. If the JVM has been created, just call the callback. Note that the full initialization process includes: 1) executing all registered client before hooks, 2) creating the JVM, then 3) executing all registered client after hooks.
java
object
Call Method
obj.methodName([args...], callback)*
obj.methodNameSync([args...]) : result
Once you have a java object either by creating a new instance or as a result of a method call you can then call methods on that object. All public, non-static methods are exposed in synchronous and asynchronous flavors.
Arguments
- args - The arguments to pass to the method.
- callback(err, item) - Callback to be called when the method has completed.
Example
var list = java.newInstanceSync("java.util.ArrayList");
list.addSync("item1");
list.add("item2", function(err, result) {
if(err) { console.error(err); return; }
});
Field Access
obj.fieldName = val*
val = obj.fieldName
Once you have a java object either by creating a new instance or as a result of a method call you can get instance field values.
Example
var list = java.newInstanceSync("com.nearinfinty.MyClass");
list.data = "test";
var data = list.data;
Getting the Full Method Signature
Run javap -s -classpath <your-class-path> <your-class-name>
. Find the method name you are looking for. For example:
public int methodAmbiguous(java.lang.Double);
Signature: (Ljava/lang/Double;)I
The full method signature would be methodAmbiguous(Ljava/lang/Double;)I
.
If you have grep, a shortcut is javap -s -classpath . my.company.MyClass | grep -A1 myMethodName
.
Signal Handling
The JVM intercepts signals (Ctrl+C, etc.) before node/v8 gets to handle them. To fix this there are a couple options.
Signal Handling Option 1
One option to capture these events is to add the following flag:
1java.options.push('-Xrs');
As man java
says, the -Xrs
flag will “reduce usage of operating-system signals by [the] Java virtual machine (JVM)”, to avoid issues when developing “applications that embed the JVM”.
Signal Handling Option 2
Hook into the runtime shutdown hook.
First create a java wrapper around the Runtime.addShutdownHook method to allow using a proxy object.
1public class ShutdownHookHelper { 2 public static void setShutdownHook(final Runnable r) { 3 Runtime.getRuntime().addShutdownHook(new Thread() { 4 @Override 5 public void run() { 6 r.run(); 7 } 8 }); 9 } 10}
Compile ShutdownHookHelper and then use it as follows.
1var java = require('./'); 2java.classpath.push('.'); 3var ShutdownHookHelper = java.import('ShutdownHookHelper'); 4 5ShutdownHookHelper.setShutdownHookSync(java.newProxy('java.lang.Runnable', { 6 run: function () { 7 console.log("do shutdown stuff here instead."); 8 } 9}));
Object lifetime
When you call a Java method through node-java, any arguments (V8/JavaScript objects) will be converted to Java objects on the v8 main thread via a call to v8ToJava (found in utils.cpp). The JavaScript object is not held on to and can be garbage collected by v8. If this is an async call, the reference count on the Java objects will be incremented. The Java method will be invoked in a node.js async thread (see uv_queue_work). When the method returns, the resulting object will be returned to the main v8 thread and converted to JavaScript objects via a call to javaToV8 and the Java object's reference count will then be decremented to allow for garbage collection. The resulting v8 object will then be returned to the callers callback function.
Static member name conflicts ('name', 'arguments', 'caller')
The JavaScript object returned by java.import(classname)
is a JavaScript constructor Function, implemented such that you can create instances of the Java class. For example:
1var Test = java.import('Test'); 2var test = new Test(); 3 4Test.someStaticMethod(function(err, result) { ... }); 5 6var value1 = Test.NestedEnum.Value1;
But JavaScript reserves a few property names of Function objects: name
, arguments
, and caller
. If your class has public static members (either methods or fields) with these names, node-java is unable to create the necessary property to implement the class's API. For example, suppose your class Test
implements a static method named caller
, or has a NestedEnum
with a value name
:
1public class Test { 2 ... 3 public static String caller() { return "something"; } 4 public enum NestedEnum { foo, name }; 5}
In JavaScript, you would expect to be able to use those static members like this:
1var Test = java.import('Test'); 2Test.caller(function(err, result) { ... }); // ERROR 3var value = Test.NestedEnum.name; // ERROR
Node-java can't create those properties, so the above code won't work. Instead, node-java appends a suffix to the name. The default suffix is simply an underscore _
, but you can change the suffix using asyncOptions
:
1var java = require('java'); 2 3java.asyncOptions = { 4 asyncSuffix: "", 5 syncSuffix: "Sync", 6 ifReadOnlySuffix: "_alt" 7}; 8 9var Test = java.import('Test'); 10Test.caller_alt(function(err, result) { ... }); // OK 11var value = Test.NestedEnum.name_alt; // OK
Troubleshooting
Error: Cannot find module '../build/jvm_dll_path.json'
Either postInstall.js
didn't run or there was a problem detecting java. Try running postInstall.js
manually.
Debugging
npm install
node-gyp build --debug
gdb --args `which node` ./node_modules/.bin/nodeunit test
License
(The MIT License)
Copyright (c) 2012 Near Infinity Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
Found 4/9 approved changesets -- score normalized to 4
Reason
dependency not pinned by hash detected -- score normalized to 2
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/master.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/joeferner/node-java/master.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/master.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/joeferner/node-java/master.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/pull-requests.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/joeferner/node-java/pull-requests.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/pull-requests.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/joeferner/node-java/pull-requests.yml/master?enable=pin
- Warn: containerImage not pinned by hash: docker/Dockerfile:1: pin your Docker image by updating ubuntu:16.04 to ubuntu:16.04@sha256:1f1a2d56de1d604801a9671f301190704c25d604a416f59e03c04f5c6ffee0d6
- Info: 0 out of 4 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 containerImage dependencies pinned
- Info: 2 out of 2 npmCommand dependencies pinned
Reason
9 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-h6ch-v84p-w6p9
- Warn: Project is vulnerable to: GHSA-phwq-j96m-2c2q
- Warn: Project is vulnerable to: GHSA-ghr5-ch3p-vcr6
- Warn: Project is vulnerable to: GHSA-78xj-cgh5-2h22
- Warn: Project is vulnerable to: GHSA-2p57-rm9w-gvfp
- Warn: Project is vulnerable to: GHSA-p8p7-x288-28g6
- Warn: Project is vulnerable to: GHSA-f5x3-32g6-xq36
- Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/master.yml:1
- Warn: no topLevel permission defined: .github/workflows/pull-requests.yml:1
- Info: no jobLevel write permissions found
Reason
binaries present in source code
Details
- Warn: binary detected: commons-lang3-node-java.jar:1
- Warn: binary detected: examples/lucene/lucene-analyzers-common-7.4.0.jar:1
- Warn: binary detected: examples/lucene/lucene-core-7.4.0.jar:1
- Warn: binary detected: examples/lucene/lucene-queryparser-7.4.0.jar:1
- Warn: binary detected: examples/mixJavaAndNode/src/com/nearinfinity/nodeJava/MyClass.class:1
- Warn: binary detected: jarjar-1.4.jar:1
- Warn: binary detected: src-java/node/CastingUtils.class:1
- Warn: binary detected: src-java/node/MethodCallBaton.class:1
- Warn: binary detected: src-java/node/NodeDynamicProxyClass.class:1
- Warn: binary detected: src-java/node/NodeJsException.class:1
- Warn: binary detected: src-java/node/VarArgs.class:1
- Warn: binary detected: test/ListenerInterface.class:1
- Warn: binary detected: test/ListenerTester.class:1
- Warn: binary detected: test/RunInterface$1.class:1
- Warn: binary detected: test/RunInterface$Interface0Arg.class:1
- Warn: binary detected: test/RunInterface$Interface1Arg.class:1
- Warn: binary detected: test/RunInterface$InterfaceWithReturn.class:1
- Warn: binary detected: test/RunInterface.class:1
- Warn: binary detected: test/Test$Enum.class:1
- Warn: binary detected: test/Test$StaticEnum.class:1
- Warn: binary detected: test/Test$SubClass.class:1
- Warn: binary detected: test/Test$SuperClass.class:1
- Warn: binary detected: test/Test.class:1
- Warn: binary detected: test/TestExceptions.class:1
- Warn: binary detected: test/commons-lang3-3.1.jar:1
- Warn: binary detected: test8/TestLambda$IntegerMath.class:1
- Warn: binary detected: test8/TestLambda.class:1
- Warn: binary detected: testIntegration/jdbc/mysql-connector-java-5.1.22-bin.jar:1
- Warn: binary detected: testIntegration/jdbc/sqljdbc.jar:1
- Warn: binary detected: testIntegration/jdbc/sqljdbc4.jar:1
- Warn: binary detected: testIntegration/poi/poi-3.9-20121203.jar:1
- Warn: binary detected: testIntegration/poi/poi-scratchpad-3.9-20121203.jar:1
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 26 are checked with a SAST tool
Score
2.2
/10
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More