• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

joeferner/node-java: Bridge API to connect with existing Java APIs.

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

joeferner/node-java

开源软件地址:

https://github.com/joeferner/node-java

开源编程语言:

C++ 48.1%

开源软件介绍:

Build Status

java

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

$ npm install java

Notes:

  • node-gyp requires python 2.x not python 3.x. See nodejs/node-gyp#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:

If you get ENOENT errors looking for <nodepath>\node_modules\node-gyp\.., ensure you have node-gyp installed as a global nodule:

npm 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:

npm install --global --production windows-build-tools

Installation ARM (Raspberry Pi)

GYP_DEFINES="armv7=0" CCFLAGS='-march=armv6' CXXFLAGS='-march=armv6' npm install java

Manual compile (Using node-gyp)

./compile-java-code.sh
node-gyp configure build
npm 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

npm 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

node test.js

Java 1.8 support

Manual compilation for Java 1.8 support requires additional steps:

./compile-java-code.sh
./compile-java8-code.sh
node-gyp configure build
npm 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

npm install -g nw-gyp
npm install java
cd node_modules/java
nw-gyp configure --target=0.10.5
nw-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:

"use strict";
var fs = require("fs");
var java = require("java");
var baseDir = "./target/dependency";
var dependencies = fs.readdirSync(baseDir);

dependencies.forEach(function(dependency){
    java.classpath.push(baseDir + "/" + dependency);
})

java.classpath.push("./target/classes");
java.classpath.push("./target/test-classes");

exports.getJavaInstance = function() {
    return java;
}

and then in the consuming class write:

var javaInit = require('./javaInit');
var java = javaInit.getJavaInstance();

//your code goes here

Quick Examples

var java = require("java");
java.classpath.push("commons-lang3-3.1.jar");
java.classpath.push("commons-io.jar");

var list1 = java.newInstanceSync("java.util.ArrayList");
console.log(list1.sizeSync()); // 0
list1.addSync('item1');
console.log(list1.sizeSync()); // 1

java.newInstance("java.util.ArrayList", function(err, list2) {
  list2.addSync("item1");
  list2.addSync("item2");
  console.log(list2.toStringSync()); // [item1, item2]
});

var ArrayList = java.import('java.util.ArrayList');
var list3 = new ArrayList();
list3.addSync('item1');
list3.equalsSync(list1); // true

Create a char array

var charArray = java.newArray("char", "hello world\n".split(''));

Create a byte array

var byteArray = java.newArray(
  "byte",
  "hello world\n"
    .split('')
    .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.

var javaLong = java.newInstanceSync("java.lang.Long", 5);
console.log('Possibly truncated long value: ' + javaLong);
console.log('Original long value (as a string): ' + javaLong.longValue);
java.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.

try {
  java.methodThatThrowsExceptionSync();
} catch(ex) {
  console.log(ex.cause.getMessageSync());
}

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:

var java = require("java");
java.asyncOptions = {
  asyncSuffix: undefined,     // Don't generate node-style methods taking callbacks
  syncSuffix: "",              // Sync methods use the base name(!!)
  promiseSuffix: "Promise",   // Generate methods returning promises, using the suffix Promise.
  promisify: require('util').promisify // Needs Node.js version 8 or greater, see comment below
};
java.classpath.push("commons-lang3-3.1.jar");
java.classpath.push("commons-io.jar");

java.import("java.util.ArrayList"); // see NOTE below

java.newInstancePromise("java.util.ArrayList")
    .then(function(list) { return list.addPromise("item1"); })
    .then(function(list) { return list.addPromise("item2"); })
    .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 set asyncOptions.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. See testHelpers.js for an example.
  • For promisify implementation, if you are using Node.js version 8.0.0 or newer then promisify: 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 for asyncOptions.promiseSuffix.
  • Either (but not both) asyncSuffix or syncSuffix can be the empty string. If you want the defacto standard behavior for no suffix on async methods, you must provide an empty string for asyncSuffix.
  • 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, and java.callStaticMethodPromise are not available until the JVM has been created. You may need to call some other java method such as java.import() to finalize java initialization, or even better, the function java.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

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

java.asyncOptions = {
  asyncSuffix: undefined,     // Don't generate node-style methods taking callbacks
  syncSuffix: "",              // Sync methods use the base name(!!)
  promiseSuffix: "Promise",   // Generate methods returning promises, using the suffix Promise.
  promisify: require('util').promisify // Needs Node.js version 8 or greater, see comment below
  ifReadOnlySuffix: "_alt"
};

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.someStaticF 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap