Giter Site home page Giter Site logo

node-java's Introduction

master

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());
}

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*

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');
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"
};
  • asyncSuffix Suffix for callback-based async method call signatures.
  • syncSuffix Suffix for synchronous method call signatures.
  • promiseSuffix Suffix for promise-based async method call signatures
  • promisify 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');

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
});

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");
}

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");

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");

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"]);

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);

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);

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);

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');

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);

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);

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();

java.isJvmCreated()*

Returns true if the JVM has been created. The JVM can only be created once.

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.

java.registerClientP(before, after)*

Like java.registerClient, but before and after are assumed to be functions returning promises.

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.

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; }
});

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;

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.

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:

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

public class ShutdownHookHelper {
  public static void setShutdownHook(final Runnable r) {
    Runtime.getRuntime().addShutdownHook(new Thread() {
      @Override
      public void run() {
        r.run();
      }
    });
  }
}

Compile ShutdownHookHelper and then use it as follows.

var java = require('./');
java.classpath.push('.');
var ShutdownHookHelper = java.import('ShutdownHookHelper');

ShutdownHookHelper.setShutdownHookSync(java.newProxy('java.lang.Runnable', {
  run: function () {
    console.log("do shutdown stuff here instead.");
  }
}));

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.

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:

var Test = java.import('Test');
var test = new Test();

Test.someStaticMethod(function(err, result) { ... });

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

public class Test {
    ...
    public static String caller() { return "something"; }
    public enum NestedEnum { foo, name };
}

In JavaScript, you would expect to be able to use those static members like this:

var Test = java.import('Test');
Test.caller(function(err, result) { ... });  // ERROR
var 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:

var java = require('java');

java.asyncOptions = {
  asyncSuffix: "",
  syncSuffix: "Sync",
  ifReadOnlySuffix: "_alt"
};

var Test = java.import('Test');
Test.caller_alt(function(err, result) { ... });  // OK
var 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.

node-java's People

Contributors

andyf0x avatar cancerberosgx avatar david-gang avatar dependabot[bot] avatar egandro avatar facboy avatar frosas avatar gabylb avatar graykode avatar informatic avatar inolen avatar jimlloyd avatar jkstrick avatar joeferner avatar jsdevel avatar leviticusmb avatar marshallofsound avatar matthiasg avatar mscdex avatar paulwcy avatar pdulapalli avatar perlun avatar ramr avatar rochal avatar rossj avatar shine-on avatar siren avatar stuws avatar wickedest avatar wsw0108 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-java's Issues

Unable to install node-java on Windows

Hi,
I'm trying to install node-java on windows. I have installed python3.3.0, node v0.8.14 and also latest node-gyp. And also set the environment variables PYTHONPATH AND JAVA_HOME.
I also visual studio 2012. Still i am getting this error while installing. Can anyone help me in this?
(I am using Git Bash in windows to install)

$ npm install -g java
npm http GET https://registry.npmjs.org/java
npm http 304 https://registry.npmjs.org/java

[email protected] install C:\Users\siva_mac\AppData\Roaming\npm\node_modules\java
node-gyp rebuild

C:\Users\siva_mac\AppData\Roaming\npm\node_modules\java>node "c:\Program Files\n
odejs\node_modules\npm\bin\node-gyp-bin....\node_modules\node-gyp\bin\node-gy
p.js" rebuild
gyp ERR! configure error
gyp ERR! stack Error: Command failed: File "", line 1
gyp ERR! stack import platform; print platform.python_version();
gyp ERR! stack ^
gyp ERR! stack SyntaxError: invalid syntax
gyp ERR! stack
gyp ERR! stack at ChildProcess.exithandler (child_process.js:540:15)
gyp ERR! stack at ChildProcess.EventEmitter.emit (events.js:99:17)
gyp ERR! stack at maybeClose (child_process.js:638:16)
gyp ERR! stack at Process._handle.onexit (child_process.js:680:5)
gyp ERR! System Windows_NT 6.1.7600
gyp ERR! command "node" "c:\Program Files\nodejs\node_modules\npm\node_modu
les\node-gyp\bin\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\siva_mac\AppData\Roaming\npm\node_modules\java
gyp ERR! node -v v0.8.14
gyp ERR! node-gyp -v v0.7.1
gyp ERR! not ok
npm ERR! [email protected] install: node-gyp rebuild
npm ERR! cmd "/c" "node-gyp rebuild" failed with 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is most likely a problem with the java package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-gyp rebuild
npm ERR! You can get their info via:
npm ERR! npm owner ls java
npm ERR! There is likely additional logging output above.

npm ERR! System Windows_NT 6.1.7600
npm ERR! command "c:\Program Files\nodejs\node.exe" "c:\Program Files\nodej
s\node_modules\npm\bin\npm-cli.js" "install" "-g" "java"
npm ERR! cwd c:\work
npm ERR! node -v v0.8.14
npm ERR! npm -v 1.1.65
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! c:\work\npm-debug.log
npm ERR! not ok code 0

install fails on windows 8

I am attempting to npm install java, but the install fails with:

c:\users\nicholas\dropbox\geo599\javanodetest\node_modules\java\src\javaScope.h(5): fatal error C1083: Cannot open incl
ude file: 'jni.h': No such file or directory [C:\Users\Nicholas\Dropbox\GEO599\javanodetest\node_modules\java\build\bin
ding.sln]
C:\Users\Nicholas\.node-gyp\0.8.17\deps\uv\include\uv.h(55): fatal error C1083: Cannot open include file: 'stdint.h': N
o such file or directory [C:\Users\Nicholas\Dropbox\GEO599\javanodetest\node_modules\java\build\binding.sln]
c:\users\nicholas\dropbox\geo599\javanodetest\node_modules\java\src\utils.h(7): fatal error C1083: Cannot open include
file: 'jni.h': No such file or directory [C:\Users\Nicholas\Dropbox\GEO599\javanodetest\node_modules\java\build\binding
.sln]
C:\Users\Nicholas\.node-gyp\0.8.17\deps\uv\include\uv.h(55): fatal error C1083: Cannot open include file: 'stdint.h': N
o such file or directory [C:\Users\Nicholas\Dropbox\GEO599\javanodetest\node_modules\java\build\binding.sln]
c:\users\nicholas\dropbox\geo599\javanodetest\node_modules\java\src\utils.h(7): fatal error C1083: Cannot open include
file: 'jni.h': No such file or directory [C:\Users\Nicholas\Dropbox\GEO599\javanodetest\node_modules\java\build\binding
.sln]
C:\Users\Nicholas\.node-gyp\0.8.17\deps\uv\include\uv.h(55): fatal error C1083: Cannot open include file: 'stdint.h': N
o such file or directory [C:\Users\Nicholas\Dropbox\GEO599\javanodetest\node_modules\java\build\binding.sln]
Project : warning PRJ0018: The following environment variables were not found: [C:\Users\Nicholas\Dropbox\GEO599\javano
detest\node_modules\java\build\binding.sln]

I have added python, jdk, and VCBuild.exe to the path. I installed the .NET 3.5 Framework so I can get VCBuild.exe compiler.

These guys are added to my windows path:

C:\Python27\ArcGIS10.1
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\amd64
C:\Program Files\Java\jdk1.7.0_13\include

It is complaining it can't find jni.h which I have indeed included in the path. Does VCBuild.exe get it's environment variables from a special place?

newProxy doesn't seem to work

  1. Copy the following code into a file called test.js
  2. Run it by "node test.js"
  3. Observe crash with something like this:
    Invalid memory access of location 0xa rip=0x102fc9462

Platform tested: Mac OS 10.7.4

// ================================
var java = require("java");

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");
}
});
myProxy.ref();

var thread = java.newInstanceSync("java.lang.Thread", myProxy);
thread.start();

setTimeout(function() {
console.log("Timed out!");
}, 3000);

Fatal error C1083: Cannot open include file: 'v8.h'

I've now tried to get node and node-java to work on my system without any luck. II don't know how many times I've tried building and installing and uninstalling. I think I've seen every error message there is... So, I'm quite frustrated...

OS: Windows 7 64 bit (I've tried both 32 bit and 64 bit node and java - latest try with 32 bit)
Installed:
Microsoft Visual Studio C++ Express
Python 2.7
Java 1.7.0_07 (JAVA_HOME=C:\Java\jdk1.7.0_07)
Path=%java_home%\bin;%java_home%\jre\bin\client;%path%

  1. Uncompressed node-v0.8.15 to C:\nodejs
  2. From within a Visual Studio Command Prompt, I “cd” to C:\nodejs\node-v0.8.15
  3. Then I ran ‘vcbuild release’ and waited for it to finish
  4. Copied the files from C:\nodejs\node-v0.8.15\Release to C:\nodejs
  5. Downloaded npm-1.1.9.zip and uncompressed its content directlry in to: C:\nodejs
  6. Set NODE_HOME=C:\nodejs
  7. Set path=C:\nodejs;%path%
  8. Now I tried to install node-java: npm install java
  9. Error log:
    C:\nodejs>npm install java
    npm http GET https://registry.npmjs.org/java
    npm http 304 https://registry.npmjs.org/java
    npm http GET https://registry.npmjs.org/mnm
    npm http 304 https://registry.npmjs.org/mnm

[email protected] install C:\nodejs\node_modules\java
node mnm.js build

[1/6] cxx: src\java.cpp -> build\Release\src\java.obj
java.cpp
c:\nodejs\node_modules\java\src\java.h(5) : fatal error C1083: Cannot open include file: 'v8.h': No such file or directory
[2/6] cxx: src\javaObject.cpp -> build\Release\src\javaObject.obj
javaObject.cpp
c:\nodejs\node_modules\java\src\javaObject.h(5) : fatal error C1083: Cannot open include file: 'v8.h': No such file or directory
[3/6] cxx: src\methodCallBaton.cpp -> build\Release\src\methodCallBaton.obj
methodCallBaton.cpp
c:\nodejs\node_modules\java\src\utils.h(6) : fatal error C1083: Cannot open include file: 'v8.h': No such file or directory
[4/6] cxx: src\nodeJavaBridge.cpp -> build\Release\src\nodeJavaBridge.obj
nodeJavaBridge.cpp
c:\nodejs\node_modules\java\src\java.h(5) : fatal error C1083: Cannot open include file: 'v8.h': No such file or directory
[5/6] cxx: src\utils.cpp -> build\Release\src\utils.obj
utils.cpp
c:\nodejs\node_modules\java\src\utils.h(6) : fatal error C1083: Cannot open include file: 'v8.h': No such file or directory
ERROR: [Error: At least one file failed to compile.]

npm ERR! [email protected] install: node mnm.js build
npm ERR! cmd "/c" "node mnm.js build" failed with 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is most likely a problem with the java package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node mnm.js build
npm ERR! You can get their info via:
npm ERR! npm owner ls java
npm ERR! There is likely additional logging output above.
npm ERR!
npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\nodejs\node.exe" "C:\nodejs\node_modules\npm\bin\n
pm-cli.js" "install" "java"
npm ERR! cwd C:\nodejs
npm ERR! node -v v0.8.15
npm ERR! npm -v 1.1.9
npm ERR! code ELIFECYCLE
npm ERR! message [email protected] install: node mnm.js build
npm ERR! message cmd "/c" "node mnm.js build" failed with 1
npm ERR! errno {}
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! C:\nodejs\npm-debug.log
npm not ok

So, it has a problem finding v8.h. I searched for it and found under: C:\nodejs\node-v0.8.15\deps\v8\include

What am I doing wrong here?

UPDATE: I read #22 and tried with JDK 1.6.0_30
Now I get another error and a couple of warnings:

"fatal error C1083: Cannot open include file: 'unistd.h': No such file or directory"
Looks like it's missing something from msysgit?

"warning C4506: no definitionfor inline function 'v8::Persistent v8::Persistent::New(v8::Handle)'..."

can't install node-java on Mac OS X 10.8 DP2

Xxx-MacBook-Air:rar xxx$ sudo npm install java
Password:
npm http GET https://registry.npmjs.org/java
npm http 304 https://registry.npmjs.org/java

[email protected] install /Users/xxx/Downloads/rar/node_modules/java
node build.js

[1/6] cxx: src/java.cpp -> build/Release/src/java.o
execvp(): No such file or directory
[2/6] cxx: src/javaObject.cpp -> build/Release/src/javaObject.o
execvp(): No such file or directory
[3/6] cxx: src/methodCallBaton.cpp -> build/Release/src/methodCallBaton.o
execvp(): No such file or directory
[4/6] cxx: src/nodeJavaBridge.cpp -> build/Release/src/nodeJavaBridge.o
execvp(): No such file or directory
[5/6] cxx: src/utils.cpp -> build/Release/src/utils.o
execvp(): No such file or directory
ERROR: At least one file failed to compile.

npm ERR! [email protected] install: node build.js
npm ERR! sh "-c" "node build.js" failed with 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is most likely a problem with the java package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node build.js
npm ERR! You can get their info via:
npm ERR! npm owner ls java
npm ERR! There is likely additional logging output above.
npm ERR!
npm ERR! System Darwin 12.0.0
npm ERR! command "node" "/usr/local/bin/npm" "install" "java"
npm ERR! cwd /Users/xxx/Downloads/rar
npm ERR! node -v v0.6.14
npm ERR! npm -v 1.1.12
npm ERR! code ELIFECYCLE
npm ERR! message [email protected] install: node build.js
npm ERR! message sh "-c" "node build.js" failed with 1
npm ERR! errno {}
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /Users/xxx/Downloads/rar/npm-debug.log
npm not ok

java.lang.reflect.Method leaking

First let me say, this npm module is awesome, so thanks!

So I noticed my node instance/JVM hitting ALLOCATION_AND_RETRY error and investigated using visualvm. This problem manifests on a RedHat Enterprise Linux server release 6.2 (2.6.32-220.9.1.el6.x86_64) on an x86_64 compiled node and JVM (1.6.0_31) binary.

In visualvm I noticed the heap jumping up in size very quickly and GCing soon after, and the predominant Class in the memory sample before the GC is int[] at something of the order of 2Gb. After GC it jumps back to around 100Mb but slowly this number increases. In the memory sample you can also see the java.lang.reflect.Method instances increasing, and not going down at all suggesting that they are not being released. My naive assumption is that these are held by the NodeDynamicProxyClass bridge but I could be way off base.

Below is a test case that highlights the problem. Note that if you change the line

var out = java.import('java.lang.System').out;

to

var System = java.import('java.lang.System');

and then call System.out.println(...) in the loop, then the number of Method instances jumps up an order of magnitude faster.

var async = require('async');
var java = require('java');

var out = java.import('java.lang.System').out;

var arr = new Array();
for (var i=0;i<10000000;i++) {
    arr.push(i+'');
}

async.forEachSeries(arr, function(item, callback) {
    out.println(item, function() {
        // Give some time for GC in case that helps
        setTimeout(callback, 1);
    });
});

As a side note, this is using the async npm module.

Cheers,
-Paul

Long-Number conversion accuracy

Hi,

Some of my Java methods return a long, whose accuracy is not maintained when converted to a JavaScript Number. The number is an ID (arithmetic operations aren't required), but I eventually need to pass it through to other Java methods.

Is there a way to accurately get the String value of this long (for display and reference in JS land) and then convert back to a long to pass to Java methods?

Thanks!

Add Java extensions to require.extensions

Great project. I'm loving the idea behind it. Anyway, it would be great if you could add Java extensions such as .class and .jar to require.extensions, so that a simple require("foo.class") would return the whole API of the file.

Support for .java would be a nice-to-have, even when importing it will be pretty slow due to the compilation overhead.

Writing node apps that rely on Java libs would become much easier, and it wouldn't feel as if you try to write Java code in JS. I just want to use the helpers I wrote half a lifetime ago in Java with node, without remembering how Java worked.

Run Quick Example code : occured this error

I had executed "npm install java" in my project folder.
then I had run quick example source as below.


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

var list = java.newInstanceSync("java.util.ArrayList");

java.newInstance("java.util.ArrayList", function(err, list) {
list.addSync("item1");
list.addSync("item2");
});

var ArrayList = java.import('java.util.ArrayList');
var list = new ArrayList();
list.addSync('item1');


But, error occured as below


node test

node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Object # has no method 'import'
at Object. (E:\Javascript_dev\JS_workspace\NodeJava\test.js:12:22
)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:31)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
at EventEmitter._tickCallback (node.js:192:40)


I can't use 'import' method...

Getting Error while executing "npm install java"

verbose fetch to /tmp/npm-1337445371181/1337445394831-0.5816605573054403/tmp.tgz
http GET https://registry.npmjs.org/mnm/-/mnm-0.0.3.tgz
ERR! failed to fetch https://registry.npmjs.org/mnm/-/mnm-0.0.3.tgz
verbose about to build /mnt/prashant/software/node_modules/java
ERR! error installing [email protected]
info unbuild /mnt/prashant/software/node_modules/java
verbose from cache /mnt/prashant/software/node_modules/java/package.json
info preuninstall [email protected]
info uninstall [email protected]
verbose unbuild [email protected] [ true,
verbose unbuild [email protected] '/mnt/prashant/software/node_modules',
verbose unbuild [email protected] '/mnt/prashant/software/node_modules' ]
info postuninstall [email protected]
verbose installOne cb [email protected]
ERR! Error: getaddrinfo EADDRINFO
ERR! at errnoException (dns.js:31:11)
ERR! at Object.onanswer as oncomplete
ERR! You may report this log at:
ERR! http://github.com/isaacs/npm/issues
ERR! or email it to:
ERR! [email protected]
ERR!
ERR! System Linux 2.6.18-274.17.1.el5
ERR! command "node" "/usr/local/bin/npm" "install" "java"

Window7 + VS2010 Express : Can't npm install java

I tried with the Visual Studio 2010 Express command Prompt.
I did add the path to the environment variables PATH, NODE_ROOT and JAVA_HOME manually.

Then while trying to "npm install java", I got the following error.

npm http GET https://registry.npmjs.org/java
npm http 304 https://registry.npmjs.org/java

[email protected] install E:\node-v0.6.15\node_modules\java
node build.js

[1/6] cxx: src\java.cpp -> build\Release\src\java.o
java.cpp
[2/6] cxx: src\javaObject.cpp -> build\Release\src\javaObject.o
javaObject.cpp
[3/6] cxx: src\methodCallBaton.cpp -> build\Release\src\methodCallBaton.o
methodCallBaton.cpp
[4/6] cxx: src\nodeJavaBridge.cpp -> build\Release\src\nodeJavaBridge.o
nodeJavaBridge.cpp
[5/6] cxx: src\utils.cpp -> build\Release\src\utils.o
utils.cpp
[6/6] cxx_link: build\Release\src\java.o build\Release\src\javaObject.o build\Release\src\methodCallBaton.o build\Release\src\nodeJavaBridge.o build\Release\src\utils.o -> build\Release\nodejavabridge_bindings.node
LINK : fatal error LNK1181: 'node.lib' ; 4 .
ERROR: Failed to link.
npm ERR! error installing [email protected]

npm ERR! [email protected] install: node build.js
npm ERR! cmd "/c" "node build.js" failed with 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is most likely a problem with the java package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node build.js
npm ERR! You can get their info via:
npm ERR! npm owner ls java
npm ERR! There is likely additional logging output above.
npm ERR!
npm ERR! System Windows_NT 6.1.7601
npm ERR! command "node" "C:\nodejs\node_modules\npm\bin\npm-cli.js" "install" "java"
npm ERR! cwd E:\node-v0.6.15
npm ERR! node -v v0.6.15
npm ERR! npm -v 1.1.2
npm ERR! code ELIFECYCLE
npm ERR! message [email protected] install: node build.js
npm ERR! message cmd "/c" "node build.js" failed with 1
npm ERR! errno {}
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! E:\node-v0.6.15\npm-debug.log
npm not ok

Setting and getting system properties appears to break the class path

For some reason after accessing System properties results in "NoClassDefFoundError" errors when subsequent attempts to load new jars and instantiate classes from them are made.

I've tried different jars, reloading properties etc, but it seems dead after the first static call.

This is a problem when incorporating different jars, etc in different locations/modules in your applicaiton.

The following works:
_java.classpath.push('ojdbc6-11.2.0.3.0.jar');
var driver = _java.newInstanceSync('oracle.jdbc.OracleDriver');
_java.callStaticMethodSync('java.sql.DriverManager','registerDriver',driver);

The following throws an exception:

var props = _java.callStaticMethodSync('java.lang.System','getProperty','java.class.path');
_java.classpath.push('ojdbc6-11.2.0.3.0.jar');
var driver = _java.newInstanceSync('oracle.jdbc.OracleDriver');
_java.callStaticMethodSync('java.sql.DriverManager','registerDriver',driver);

Exception:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Could not create class oracle.jdbc.OracleDriver
java.lang.NoClassDefFoundError: oracle/jdbc/OracleDriver
Caused by: java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)

at Object.<anonymous> (/usr/local/varolii/dev/sqlConnect/lib/query.js:12:20)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:31)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
at EventEmitter._tickCallback (node.js:192:40)

Can't execute methods for objects in java.lang package

node-java seems to be installed properly and lucene example works when I run it under project's directory.
But when I try to execute such code:

var java = require("java");
var str = java.newInstanceSync("java.lang.String", "Hello");
console.log(str.getBytesSync());

I got
TypeError: Object Hello has no method 'getBytesSync'
Similar error occur for other methods and also for example for Integer class instance.

I need to call getBytes to pass it to stream and actually I'm trying to implement code which will deserialize object:
new ObjectInputStream(new ByteArrayInputStream(serialized)).readObject()
Just wondering maybe there is some other way to do this.

"npm install java" do not work on java "1.7.0_04" ?

Hi,

My java is jdk1.7.0_04. When I run "npm install java",it did failed.

hyjy@hyjy-Latitude-E6400:~/workspace/testnodejava$ java -version
java version "1.7.0_04"
Java(TM) SE Runtime Environment (build 1.7.0_04-b20)
Java HotSpot(TM) Server VM (build 23.0-b21, mixed mode)

hyjy@hyjy-Latitude-E6400:/workspace/testnodejava$ npm install mnm
npm http GET https://registry.npmjs.org/mnm
npm http 304 https://registry.npmjs.org/mnm
[email protected] ./node_modules/mnm
hyjy@hyjy-Latitude-E6400:
/workspace/testnodejava$ npm install java
npm http GET https://registry.npmjs.org/java
npm http 304 https://registry.npmjs.org/java

[email protected] install /home/hyjy/workspace/testnodejava/node_modules/java
node mnm.js build

[1/6] cxx: src/nodeJavaBridge.cpp -> build/Release/src/nodeJavaBridge.o
In file included from /home/hyjy/workspace/testnodejava/node_modules/java/src/nodeJavaBridge.cpp:2:0:
/home/hyjy/workspace/testnodejava/node_modules/java/src/java.h:6:18: fatal error: node.h: No such file or directory
compilation terminated.
[2/6] cxx: src/java.cpp -> build/Release/src/java.o
In file included from /home/hyjy/workspace/testnodejava/node_modules/java/src/java.cpp:2:0:
/home/hyjy/workspace/testnodejava/node_modules/java/src/java.h:6:18: fatal error: node.h: No such file or directory
compilation terminated.
[3/6] cxx: src/utils.cpp -> build/Release/src/utils.o
In file included from /home/hyjy/workspace/testnodejava/node_modules/java/src/utils.cpp:2:0:
/home/hyjy/workspace/testnodejava/node_modules/java/src/utils.h:11:16: fatal error: uv.h: No such file or directory
compilation terminated.
[4/6] cxx: src/javaObject.cpp -> build/Release/src/javaObject.o
In file included from /home/hyjy/workspace/testnodejava/node_modules/java/src/javaObject.cpp:2:0:
/home/hyjy/workspace/testnodejava/node_modules/java/src/javaObject.h:6:18: fatal error: node.h: No such file or directory
compilation terminated.
[5/6] cxx: src/methodCallBaton.cpp -> build/Release/src/methodCallBaton.o
In file included from /home/hyjy/workspace/testnodejava/node_modules/java/src/methodCallBaton.h:5:0,
from /home/hyjy/workspace/testnodejava/node_modules/java/src/methodCallBaton.cpp:2:
/home/hyjy/workspace/testnodejava/node_modules/java/src/utils.h:11:16: fatal error: uv.h: No such file or directory
compilation terminated.
ERROR: [Error: At least one file failed to compile.]
npm ERR! error installing [email protected]

npm ERR! [email protected] install: node mnm.js build
npm ERR! sh "-c" "node mnm.js build" failed with 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is most likely a problem with the java package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node mnm.js build
npm ERR! You can get their info via:
npm ERR! npm owner ls java
npm ERR! There is likely additional logging output above.
npm ERR!
npm ERR! System Linux 3.2.0-25-generic-pae
npm ERR! command "node" "/usr/bin/npm" "install" "java"
npm ERR! cwd /home/hyjy/workspace/testnodejava
npm ERR! node -v v0.6.12
npm ERR! npm -v 1.1.4
npm ERR! code ELIFECYCLE
npm ERR! message [email protected] install: node mnm.js build
npm ERR! message sh "-c" "node mnm.js build" failed with 1
npm ERR! errno {}
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /home/hyjy/workspace/testnodejava/npm-debug.log
npm not ok

Please advice

Chen Zhao

callStaticMethod memory leak

Thanks for the module, but I'm encountering with memory leaks while calling static method.

Java class implementing static method returning some string:

package com.socialbakers.hbase.helpers;

public class TableTmp {
    public static String getDataFromTable() {
        String tmp = "";
        for (int i = 0; i < 1000; i++) {
            tmp += "0123456789";
        }
        return tmp;
    }
}

Coffeescript calling static method from mentioned class:

java = require 'java'
util = require 'util'

java.classpath.push "#{__dirname}/target/api-hbase-utils-0.0.1-SNAPSHOT.jar"

i = 0
callQuery = () ->
    java.callStaticMethod 'com.socialbakers.hbase.helpers.TableTmp', 'getDataFromTable', (err, result) ->
        util.log err if err
#       util.log result
        result = null

        if i % 10 is 0
            util.log "#{i}: #{util.inspect process.memoryUsage()}"

        if i == 10000
            process.abort()

        i++

setInterval(callQuery,10)

After running the script memwatch shows something like:

before: {
    nodes: 59693,
    time: Thu Jul 04 2013 15:09:33 GMT+0200 (CEST),
    size_bytes: 5480664,
    size: '5.23 mb'
},
after: {
    nodes: 55104,
    time: Thu Jul 04 2013 15:11:15 GMT+0200 (CEST),
    size_bytes: 105442160,
    size: '100.56 mb' 
}
.
.
    {
        what: 'String',
        size_bytes: 100249240,
        size: '95.61 mb',
        '+': 10067,
        '-': 108
    }

I wasn't really able to track down what exactly is causing this, maybe you could help me?

Cheers,
Martin

Apple AWT Issue

Hi,

I have some issues when running a library (Sikuli) on Mac:

2012-10-13 22:17:40.469 node[34314:707] Apple AWT Java VM was loaded on first thread -- can't start AWT.

node_modules/java/lib/nodeJavaBridge.js:16
  var clazz = java.findClassSync(name); // TODO: change to Class.forName when 
                   ^
Error: Could not create class org.sikuli.script.Screen
java.lang.InternalError: Can't start the AWT because Java was started on the first thread.  Make sure StartOnFirstThread is not specified in your application's Info.plist or on the command line
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1827)
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1724)
    at java.lang.Runtime.loadLibrary0(Runtime.java:823)
    at java.lang.System.loadLibrary(System.java:1045)
    at sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:50)
    at java.security.AccessController.doPrivileged(Native Method)
    at apple.awt.CGraphicsEnvironment.<clinit>(CGraphicsEnvironment.java:23)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:169)
    at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:68)
    at org.sikuli.script.Screen.<clinit>(Screen.java:25)

    at Java.java.import (node_modules/java/lib/nodeJavaBridge.js:16:20)
    at Object.<anonymous> (sikuli.js:15:35)
    at Object.<anonymous> (sikuli.js:18:4)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:362:17)
    at require (module.js:378:17)

I tried to do:

  var java = require("java");
  java.options.push("-XstartOnFirstThread");

but it didn't work:

Unrecognized option: -XstartOnFirstThread
Segmentation fault: 11

I also tried -Djava.awt.headless=true, without much success:

node_modules/java/lib/nodeJavaBridge.js:16
  var clazz = java.findClassSync(name); // TODO: change to Class.forName when 
                   ^
Error: Could not create class org.sikuli.script.Screen
java.lang.ExceptionInInitializerError
Caused by: java.awt.HeadlessException
    at sun.java2d.HeadlessGraphicsEnvironment.getScreenDevices(HeadlessGraphicsEnvironment.java:59)
    at org.sikuli.script.Screen.<clinit>(Screen.java:26)

    at Java.java.import (node_modules/java/lib/nodeJavaBridge.js:16:20)
    at Object.<anonymous> (sikuli.js:17:35)
    at Object.<anonymous> (sikuli.js:20:4)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:362:17)
    at require (module.js:378:17)

Any ideas?

thanks!

Issues with JDK 1.7.0_09 - Fatal error

While trying to call a custom java method we get a fatal error (see messages below). This is when node-java has been compiled using JDK 1.7 and the JRE is 1.7 as well.

The process works without any issues when invoked using node-java compiled using JDK 1.6 and the JRE is 1.6...

A fatal error has been detected by the Java Runtime Environment:

SIGSEGV (0xb) at pc=0x00007f0cff62050c, pid=21678, tid=139693879064352

JRE version: 7.0_09-b05

Java VM: Java HotSpot(TM) 64-Bit Server VM (23.5-b02 mixed mode linux-amd64 compressed oops)

Problematic frame:

V [libjvm.so+0x56850c] jni_IsInstanceOf+0xbc

--- or ---

A fatal error has been detected by the Java Runtime Environment:

SIGSEGV (0xb) at pc=0x00007f534dfd9427, pid=21630, tid=139995778197280

JRE version: 7.0_09-b05

Java VM: Java HotSpot(TM) 64-Bit Server VM (23.5-b02 mixed mode linux-amd64 compressed oops)

Problematic frame:

V [libjvm.so+0x5a2427] JNIHandleBlock::allocate_handle(oopDesc*)+0x247

Cloud9 IDE + node-java = Error

Hi there!

I have problem when running simple node-java example in the Cloud9 IDE https://github.com/ajaxorg/cloud9.

I get the following error:
dyld: lazy symbol binding failed: Symbol not found: __ZN2v82V815MarkIndependentEPPNS_8internal6ObjectE
Referenced from:
/Users/Milan/Documents/Programming/NodeJS_Projects/node_modules/java/build/Release/nodejavabridge_bindings.node
Expected in: flat namespace
dyld: Symbol not found: __ZN2v82V815MarkIndependentEPPNS_8internal6ObjectE
Referenced from: /Users/Milan/Documents/Programming/NodeJS_Projects/node_modules/java/build/Release/nodejavabridge_bindings.node
Expected in: flat namespace

However, the example is executed without any problem through the terminal.
BTW, I am running Java v1.6 on Mac OS X 10.7.3.

Do you have an idea why I get this error in Cloud9 IDE?

Synchronous method invocations do not throw java exceptions

Is this intentional? It returns the exception as a string instead unles you make the change below.

methodCallBaton.cpp:70
v8::Handle<v8::Value> MethodCallBaton::resultsToV8(JNIEnv *env) {
  v8::HandleScope scope;

  if(m_error) {
--    v8::Handle<v8::Value> err = javaExceptionToV8(env, m_error, m_errorString);
++    v8::Handle<v8::Value> err = ThrowException(javaExceptionToV8(env, m_error, m_errorString));
    env->DeleteGlobalRef(m_error);
    return scope.Close(err);
  }

  return scope.Close(javaToV8(m_java, env, m_result));
}

For example I get the following output from the code below..
HERE1
HERE2
[Error: Error running instance method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
Caused by: java.lang.Exception: eh?
at s.except(s.java:5)
... 4 more
]
HERE3

s.java:

class s {
    public s(){}
    public int except() throws Exception {
        throw new Exception("eh?");
    }
}

s.js:

var java = require("java");
java.classpath.push(".");
var s = java.newInstanceSync("s");
console.log("HERE1");
s.exceptSync();
console.log("HERE2");
console.log(s.exceptSync());
console.log("HERE3");

build error in linux

running npm install java fails with:

make: *** No rule to make target /opt/java/jdk1.6.0_37jre/lib/amd64/server/libjvm.so', needed bybuild/depsVerified'. Stop.

the issue is that it is callinf $JAVA_HOMEjre where it should be $JAVA_HOME/jre

Internal fatal error while unwrapping variable

I get this fatal error when I run the following code:

node: /home/crodas/.node-gyp/0.8.14/src/node_object_wrap.h:61: static T* node::ObjectWrap::Unwrap(v8::Handle<v8::Object>) [with T = JavaObject]: Assertion `handle->InternalFieldCount() > 0' failed.
Aborted

Sample code:

var java = require('java');
java.classpath.push("poi.jar");
java.classpath.push("poi-scratchpad.jar");

var stream = java.newInstanceSync("java.io.FileInputStream", 'presentation.ppt');
var ppt    = java.newInstanceSync('org.apache.poi.hslf.usermodel.SlideShow', stream); 
stream.close();

var pgsize = ppt.getPageSizeSync();

var slides = ppt.getSlides();

var TYPE_INT_RGB = java.getStaticFieldValue("java.awt.image.BufferedImage", "TYPE_INT_RGB");

var img, graphics;
for (i = 0; i < slides.length; i++) {
    img = java.newInstanceSync('java.awt.image.BufferedImage', pgsize.width, pgsize.height, TYPE_INT_RGB);
    graphics = img.createGraphicsSync();
}

Only ASCII String is supported.

Here is a small patch for allowing UTF-8 String. Hope this helps.

diff --git a/node_modules/java/src/utils.cpp b/node_modules/java/src/utils.cpp
index ded1bc4..b55c2d5 100644
--- a/node_modules/java/src/utils.cpp
+++ b/node_modules/java/src/utils.cpp
@@ -176,7 +176,7 @@ jobject v8ToJava(JNIEnv* env, v8::Local<v8::Value> arg) {
   }

   if(arg->IsString()) {
-    v8::String::AsciiValue val(arg->ToString());
+    v8::String::Utf8Value val(arg->ToString());
     return env->NewStringUTF(*val);
   }

unable to install when using node 0.10.0

I am attempting to install node-java on node v0.10.0 and am getting the following error.

Could you please point me to a solution?

module.js:356
Module._extensions[extension](this, filename);
^
Error: Module version mismatch. Expected 11, got 1.
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object. (/usr/local/lib/node_modules/java/lib/nodeJavaBridge.js:5:16)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)

Could not install on Win7

ERROR: You appear to not be running in a Visual Studio prompt.
npm ERR! error installing [email protected]

npm ERR! [email protected] install: node build.js
npm ERR! cmd "/c" "node build.js" failed with 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is most likely a problem with the java package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node build.js
npm ERR! You can get their info via:
npm ERR! npm owner ls java
npm ERR! There is likely additional logging output above.
npm ERR!
npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\Program Files (x86)\nodejs\node.exe" "C:\Program Files (x86)\nodejs\node_modules\npm\bin
\npm-cli.js" "install" "java"
npm ERR! cwd E:\EclipseSVN\node
npm ERR! node -v v0.6.12
npm ERR! npm -v 1.1.4
npm ERR! code ELIFECYCLE
npm ERR! message [email protected] install: node build.js
npm ERR! message cmd "/c" "node build.js" failed with 1
npm ERR! errno {}
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! E:\ApplicationFolder\npm-debug.log
npm not ok

Error: %1 is not a valid Win32 application.

Hello!

Not working win7x64.

c:\Naima\worker\node\backoffice\node_modules\java>node testHelpers.js

module.js:485
process.dlopen(filename, module.exports);
Error: %1 is not a valid Win32 application.
c:\Naima\worker\node\backoffice\node_modules\java\build\Release\nodejavabridge_bindings.node
at Object.Module._extensions..node (module.js:485:11)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at Object. (c:\Naima\worker\node\backoffice\node_modules\java\lib\nodeJavaBridge.js:5:16)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)

core dumps using double callback with JDBC (+ workaround)

Hi,

excellent piece of work! I've been getting frequent core dumps however with a particular jdbc snippet with the "npm" version of node-java. In the end I found that a small change (below) to remove the second callback within a callback seems to make the problem go away. Anyway, building from the github source directly the problem is resolved.

// Load the http module to create an http server.
var http = require('http');
var util = require("util");
var java = require("java");
java.options.push("-Djava.awt.headless=true"); // running on OS X 10.8
java.classpath.push("../jtds-1.2.7-dist/jtds-1.2.7.jar");

var cl = java.callStaticMethodSync("java.lang.ClassLoader","getSystemClassLoader")
cl.loadClassSync( "net.sourceforge.jtds.jdbc.Driver" ).newInstanceSync();

var i = 0;

function fetch(sql,cb) {
    var cn = java.callStaticMethodSync("java.sql.DriverManager","getConnection",
    "jdbc:jtds:sybase://172.16.54.129:5000;charset=iso_1;", "sa", "" );
    var s = cn.createStatementSync();

    s.execute( sql, function(err,ok) {
        if ( err )
            console.error(err);
        else
            s.getResultSet( function(err,rs) {
                var md = rs.getMetaDataSync();
                var cc = md.getColumnCountSync();
                var rows = [[]];

                for (var c=0 ; c<cc ; c++)
                    rows[0].push(md.getColumnLabelSync(c+1))

                while( rs.nextSync() ) {
                    var row = [];
                    for (var c=0 ; c<cc ; c++)
                        row.push(rs.getStringSync(c+1));
                    rows.push(row);
                }

                cn.closeSync();
                cb(rows);
            } )
    } );
}

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/html"});
  response.write("Hello World "+i+++'<pre>'+util.inspect(request.headers)+"\n");
  fetch( "waitfor delay '00:00:05' select * from pubs2..titles",
    function(rows) {
        var html = '<table>';
        for ( var r=0 ; r<rows.length ; r++ ) {
            html += '\n<tr>';
            for ( var c=0 ; c<rows[r].length ; c++ )
                html += (r==0?'<th>':'<td>')+rows[r][c];
        }
        response.write(html+'\n</table>');
        response.end();
    }
  );
} );

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");

Server running at http://127.0.0.1:8000/
Reading symbols for shared libraries . done
Invalid memory access of location 0x1 rip=0x104c9ead3

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000001
0x0000000104c9ead3 in JVM_FindPrimitiveClass ()
(gdb) where
#0  0x0000000104c9ead3 in JVM_FindPrimitiveClass ()
#1  0x0000000104cabbc4 in JVM_InternString ()
#2  0x0000000104cabb4f in JVM_InternString ()
#3  0x0000000100bca66a in JNIEnv_::NewGlobalRef (this=0x1060011d0, lobj=0x10db06350) at jni.h:836
#4  0x0000000100bd1a04 in MethodCallBaton::MethodCallBaton (this=0x101818cc0, java=0x101a010f0, method=0x10db06350, args=0x10db06308, callback=@0x7fff5fbfeea8) at methodCallBaton.cpp:12
#5  0x0000000100bd327d in InstanceMethodCallBaton::InstanceMethodCallBaton (this=0x101818cc0, java=0x101a010f0, obj=0x100a12e20, method=0x10db06350, args=0x10db06308, callback=@0x7fff5fbfeea8) at methodCallBaton.cpp:188
#6  0x0000000100bcd83e in JavaObject::methodCallSync (args=@0x7fff5fbff070) at javaObject.cpp:163
#7  0x0000000100145918 in HandleApiCallHelper [inlined] () at :1145
#8  0x0000000100145918 in Builtin_HandleApiCall (isolate=0x101010400) at ../deps/v8/src/builtins.cc:1162
#9  0x0000092097b0618e in ?? ()
#10 0x0000092097b8d1c8 in ?? ()
#11 0x0000092097b248c7 in ?? ()
#12 0x0000092097b11317 in ?? ()
#13 0x000000010017106d in Invoke (is_construct=, argc=2, args=0x7fff5fbff360, has_pending_exception=0x7fff5fbff317) at ../deps/v8/src/execution.cc:118
#14 0x000000010012108c in v8::Function::Call (this=0x1020041a0, argc=2, argv=0x7fff5fbff360) at ../deps/v8/src/api.cc:3644
#15 0x0000000100bd2367 in MethodCallBaton::after (this=0x100e08290, env=0x1060011d0) at methodCallBaton.cpp:62
#16 0x0000000100bd1ae8 in MethodCallBaton::EIO_AfterMethodCall (req=0x100e082e0) at methodCallBaton.cpp:46
#17 0x000000010004e5ff in uv__after_work (eio=) at ../deps/uv/src/unix/fs.c:669
#18 0x0000000100046a21 in eio_finish (req=0x100e09ae0) at ../deps/uv/src/unix/eio/eio.c:860
#19 0x0000000100044df3 in etp_poll [inlined] () at :698
#20 0x0000000100044df3 in eio_poll (channel=) at ../deps/uv/src/unix/eio/eio.c:966
#21 0x0000000100053a1f in uv_eio_want_poll_notifier_cb (watcher=, status=100667856) at ../deps/uv/src/unix/uv-eio.c:46
#22 0x0000000100043e1a in uv__async_io (loop=, handle=0x1060011d0, events=2) at ../deps/uv/src/unix/async.c:117
#23 0x000000010004974c in ev_invoke_pending (loop=0x100639af8) at ../deps/uv/src/unix/ev/ev.c:2145
#24 0x0000000100044110 in uv__run (loop=0x1006391b0) at ../deps/uv/src/unix/core.c:248
#25 0x000000010004403f in uv_run (loop=0x1006391b0) at ../deps/uv/src/unix/core.c:265
#26 0x0000000100009191 in node::Start (argc=, argv=0x7fff5fbffa98) at ../src/node.cc:2974
#27 0x0000000100001174 in start ()
(gdb) 

If I change the fetch code to only have a single callback it is perfectly reliable:

function fetch(sql,cb) {
    var cn = java.callStaticMethodSync("java.sql.DriverManager","getConnection",
    "jdbc:jtds:sybase://172.16.54.129:5000;charset=iso_1;", "sa", "" );
    var s = cn.createStatementSync();

    s.execute( sql, function(err,ok) {
        if ( err )
            console.error(err);
        else {
            var rs = s.getResultSetSync()
            var md = rs.getMetaDataSync();
            var cc = md.getColumnCountSync();
            var rows = [[]];

            for (var c=0 ; c<cc ; c++)
                rows[0].push(md.getColumnLabelSync(c+1))

            while( rs.nextSync() ) {
                var row = [];
                for (var c=0 ; c<cc ; c++)
                    row.push(rs.getStringSync(c+1));
                rows.push(row);
            }

            cn.closeSync();
            cb(rows);
        }
    } );
}

Hope this helps track something down.

John

install issue: node.h missing? manual copy fixed it

Hi,

I had an issue installing the package via npm: v8.h was missing.
So I cloned the git source repo, and copied the /usr/lib/nodejs/ files into the src folder => compile errors were gone

So is it a bug in the installer or is there perhaps something wrong with my include settings or so?

Thanks!

JRE detects fatal error running the example

A fatal error has been detected by the Java Runtime Environment:

SIGSEGV (0xb) at pc=0x00007f262a422e1a, pid=17852, tid=139801925064512

JRE version: 6.0_32-b05

Java VM: Java HotSpot(TM) 64-Bit Server VM (20.7-b02 mixed mode linux-amd64 compressed oops)

Problematic frame:

V [libjvm.so+0x4f3e1a] unsigned+0xfa

An error report file with more information is saved as:

/home/jochen/dev/code/git/node-java/examples/lucene/hs_err_pid17852.log

If you would like to submit a bug report, please visit:

http://java.sun.com/webapps/bugreport/crash.jsp

Aborted (core dumped)

Can't install node-java (Ubuntu) against java 1.7

plever@ubuntuOffice1:~$ java -version
java version "1.7.0_03"
Java(TM) SE Runtime Environment (build 1.7.0_03-b04)
Java HotSpot(TM) Client VM (build 22.1-b02, mixed mode)

plever@ubuntuOffice1:~$ javac -version
javac 1.7.0_03

plever@ubuntuOffice1:~$ sudo npm install java
npm ERR! Error: No compatible version found: java
npm ERR! No valid targets found.
npm ERR! Perhaps not compatible with your version of node?
npm ERR! at installTargetsError (/usr/local/lib/node_modules/npm/lib/cache.js:424:10)
npm ERR! at /usr/local/lib/node_modules/npm/lib/cache.js:406:17
npm ERR! at saved (/usr/local/lib/node_modules/npm/lib/utils/npm-registry-client/get.js:136:7)
npm ERR! at Object.cb as oncomplete
npm ERR! Report this entire log at:
npm ERR! http://github.com/isaacs/npm/issues
npm ERR! or email it to:
npm ERR! [email protected]
npm ERR!
npm ERR! System Linux 2.6.32-40-generic-pae
npm ERR! command "node" "/usr/local/bin/npm" "install" "java"
npm ERR! cwd /home/plever
npm ERR! node -v v0.5.11-pre
npm ERR! npm -v 1.0.106
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /home/plever/npm-debug.log
npm not ok

plever@ubuntuOffice1:~$ node --version
v0.5.11-pre

plever@ubuntuOffice1:~$ echo $JAVA_HOME
/usr/local/java/jdk1.7.0_03

Could it be an issue with my node version? I'm guessing it's an issue with java 1.7.

toCharArray

First, thanks for your job.

I face a blocking problem :

I'm unable to call a java method like "login(String user, char [] passwd)" because of "char []" type.

The way to convert java string do char [] is to use String#toCharArray() method but with node-java we can't access this method.

Do you have a solution ?

Many thanks.

Eric.

Example code apache.lucene does not work

It loads the first modules, but gets stuck on this one:

var writerConfig = java.newInstanceSync("org.apache.lucene.index.IndexWriterCo
^
Error: Could not find constructor for class org.apache.lucene.index.IndexWriterConfig
at Object. (/Users/jazz/WebstormProjects/node-java/lucene.js:15:25)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)

ok: var idx = java.newInstanceSync("org.apache.lucene.store.RAMDirectory");
ok: var version = java.getStaticFieldValue("org.apache.lucene.util.Version", "LUCENE_CURRENT");
ok: var analyzer = java.newInstanceSync("org.apache.lucene.analysis.standard.StandardAnalyzer", version);
NOK: var writerConfig = java.newInstanceSync("org.apache.lucene.index.IndexWriterConfig", version, analyzer);

Can't install node-java

ERROR: You must set JAVA_HOME or JDK_INCLUDE_DIR environment variable

My environment:
ubuntu 12.04 x86
node v0.6.18

~$ node

process.env["JAVA_HOME"]
'/usr/lib/jvm/jdk1.7.0_04'

What reason?

Thanks for your help. :)

Type java.lang.Long mapping

Take a class Test like this :

public class Test {
public static void test(java.lang.Long a){
System.out.println("test1");
}
}

Try this :

var java=require('java')
java.classpath.push('./test.jar');
var Test = java.import('Test');
Test.testSync(java.newInstanceSync("java.lang.Long", 1));

Gives :

Error: Could not find method "test(java.lang.Integer)" on class "class Test".
Possible matches:
public static void Test.test(java.lang.Long)

done it with last build.

Regards.

Using with fibers

Hi,
great work. But I have problems creating Java objects inside a fiber. In this case the Java process crashes. Do you know this issue? Do you need more information?
Thanks Andreas

node-java low throughput

Hi, I'm was testing node-java to know if it is a good choice for a project I'm doing. But after running some tests I figured out that it is having a good throughput. I construct my test creating a Java class that has a method that sleeps for a while and then returns. Then I created an object of that class using node-java inside a REST handler and called the method from it. To test my app I used JMeter, but when I have more than 4 clients, the throughput get stuck in 20.0/sec, otherwise it runs smoothly. Any ideas about what is causing this?

Error: Could not create class com.nearinfinity.nodeJava.MyClass

I am getting errors when I try to run to run the example code:

nodeJavaBridge.js:16
var clazz = java.findClassSync(name); // TODO: change to Class.forName when
^
Error: Could not create class com.nearinfinity.nodeJava.MyClass
java.lang.UnsupportedClassVersionError: com/nearinfinity/nodeJava/MyClass : Unsupported major.minor version 51.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)

at Java.java.import (.../node-java-master/lib/nodeJavaBridge.js:16:20)
at Object.<anonymous> (.../node-java-master/examples/mixJavaAndNode/runMyClass.js:6:26)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)

I am using java version "1.7.0_11."

Any ideas?

Crash with array of ints.

In Java class I have following method:
public int[] getArr()
{
int arr[] = new int[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
return arr;
}

Node crashes (due to JVM crash) on following JS statement:
var myArr = myObject.getArrSync();

With all three debuggers attached (js, java, C++), I've verified, that on Java side getArr completed. It looks like You're trying to get array 'int' element as Object and then check its class. And JVM doesn't like this.

install fails on ubuntu

I have tried all the combo possible, but I still get the No rule to make target `jre/lib/amd64/server/libjvm.so' error

export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk-amd64/
or
export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk-amd64/
or
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64

my python is 2.7 , node gyp 0.7,1 and node is 0.8.14

/usr/lib/jvm/java-7-openjdk-amd64/jre/lib/amd64/server/libjvm.so is present so I'm not sure what the error is.
java home is working of for my other stuff I'd appreciate some help thanks

failing to get complex return objects from Java

Java classes that are composed entirely of primitive types
e.g.
public static class ProfileCondition {
int id;
String type;
String value;
}

can be accessed without a problem through node-java.

Lists of primitives are handled if you wrap a method with JSON.parse()

For example if you return from a myMethod a List
var jsObject = JSON.parse(java.newInstanceSync("com....myMethod"));

When I expanded to try to handle a more complex object that has a List of non-primitives I get an empty object within node.

e.g. something of the following style
public static class ProfileInfo {
int id;
String name;
boolean is_default;
List conditions;
public ProfileInfo() {
this.conditions = new ArrayList();
}
}
public static class ProfileCondition {
int id;
String type;
String value;
}

var ProfileInfo = java.import("com.....ProfileInfo");
var jsObect = new ProfileInfo();
jsObject = javaClient.get_my_profile_info_method();

Should we expect a complex object or List type of object to be handled successfully? Similarly walking down the object should the node-java library handled objects like the ProfileInfo class above correctly?

cannot find module

I use the example lucene
but it throws an error:
limaoubuntu@limaoubuntu-VirtualBox:~/node_modules/java/examples/lucene$ node example.js

node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Cannot find module '/home/limaoubuntu/node_modules/java/build/Release/nodejavabridge_bindings.node'
at Function._resolveFilename (module.js:332:11)
at Function._load (module.js:279:25)
at Module.require (module.js:354:17)
at require (module.js:370:17)
at Object. (/home/limaoubuntu/node_modules/java/lib/nodeJavaBridge.js:5:16)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:32)
at Function._load (module.js:308:12)
at Module.require (module.js:354:17)

Apple JWT Java VM Issue

Hello,

First off, thank you very much for authoring this package. Tremendous job.

I'm working on a particularly tricky piece of code that involves using the java AWT. I'm currently getting an error while trying to read a file using the javax.imageio.ImageIO class. Here's the offending code:

var file = java.newInstanceSync("java.io.File", path);
var image = java.callStaticMethodSync("javax.imageio.ImageIO", "read", file);

The error thrown is:

Error: Error running static method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
Caused by: java.lang.InternalError: Can't start the AWT because Java was started on the first thread. Make sure StartOnFirstThread is not specified in your application's Info.plist or on the command line
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1827)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1724)
at java.lang.Runtime.loadLibrary0(Runtime.java:823)
at java.lang.System.loadLibrary(System.java:1045)
at sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:50)
at java.security.AccessController.doPrivileged(Native Method)
at sun.java2d.Disposer.(Disposer.java:41)
at javax.imageio.stream.FileImageInputStream.(FileImageInputStream.java:82)
at javax.imageio.stream.FileImageInputStream.(FileImageInputStream.java:57)
at com.sun.imageio.spi.FileImageInputStreamSpi.createInputStreamInstance(FileImageInputStreamSpi.java:37)
at javax.imageio.ImageIO.createImageInputStream(ImageIO.java:331)
at javax.imageio.ImageIO.read(ImageIO.java:1278)
... 4 more

Any idea how I might be able to get around this?

Thanks in advance!

install node-java on windows 64bit error node-gyp successed

gyp ERR! build error
gyp ERR! stack Error: ENOENT, open 'C:\Users\swj.node-gyp\0.8.16\x64\node.lib'
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Program Files\nod
ejs\node_modules\node-gyp\bin\node-gyp.js" "rebuild"
gyp ERR! cwd F:\workspace\shomopcrm_dev\node_modules\java
gyp ERR! node -v v0.8.16
gyp ERR! node-gyp -v v0.9.5
gyp ERR! not ok
npm ERR! [email protected] install: node-gyp rebuild
npm ERR! cmd "/c" "node-gyp rebuild" failed with 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is most likely a problem with the java package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-gyp rebuild
npm ERR! You can get their info via:
npm ERR! npm owner ls java
npm ERR! There is likely additional logging output above.

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\Program Files\nodejs\node.exe" "C:\Program Files\nod
ejs\node_modules\npm\bin\npm-cli.js" "install" "java"
npm ERR! cwd F:\workspace\shomopcrm_dev
npm ERR! node -v v0.8.16
npm ERR! npm -v 1.1.70
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! F:\workspace\shomopcrm_dev\npm-debug.log
npm ERR! not ok code 0

Casting

Unable to use objects that are created in a particular type. We know that JavaScript don't keep type and type is automatically resolved by the compiler. However this throws an error for classes in Java that require the utilization of a particular class.

Can we have an option to cast data as a parameter.

java classpath question

Can I specify directories in the node-java classpath? I'm looking to integrate node with a Java backend that I've already written, but will need to tweak the code, and it would be nice to not have to rebuild a jar file for every 3 lines of change in the code.

Thanks

The specified module could not be found

Hi,

I was using windows xp 32bit. First, when I tried to "npm install java", I got several warnings:

C:\Program Files\Microsoft Visual Studio 10.0\VC\include\xlocale(323): warning
C4530: C++ exception handler used, but unwind semantics are not enabled. Specif
y /EHsc [xxxxxx\node_modules\java\build\nodejavabridge_bindings
.vcxproj]
C:\Program Files\Microsoft Visual Studio 10.0\VC\include\xlocale(323): warning
C4530: C++ exception handler used, but unwind semantics are not enabled. Specif
y /EHsc [xxxxxx\node_modules\java\build\nodejavabridge_bindings
.vcxproj]
C:\Documents and Settings\lenovo.node-gyp\0.8.15\deps\v8\include\v8.h(183): wa
rning C4506: no definition for inline function 'v8::Persistent v8::Persisten
t::New(v8::Handle)' [xxxxxx\node_modules\java\build\nodej
avabridge_bindings.vcxproj]
with
[
T=v8::Object
]
nodeJavaBridge.cpp
java.cpp
......

but without errors.

So I then tried to launch my application by: "node client.js"

and got:

module.js:485
process.dlopen(filename, module.exports);
^
Error: The specified module could not be found.
xxxxxx\node_modules\java\build\Release\nodejavabridge_bindings.n
ode
at Object.Module._extensions..node (module.js:485:11)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at Object. (xxxxxx\node_modules\java\lib\nodeJava
Bridge.js:6:16)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)

however I checked the path xxxxxx\node_modules\java\build\Release\nodejavabridge_bindings.node, and it was there.

I feel it might related to issue #29, so I tried the method in the comment, still had the same result.

The same things works well on both Mac and Linux.

Could anyone point me a solution? Thanks :)

JAVA_HOME install issue

npm install java
fails with the following JAVA_HOME:
export JAVA_HOME=/usr/lib/jvm/jdk1.7.0
but succeeds with:
export JAVA_HOME=/usr/lib/jvm/jdk1.7.0/

It seems a forward slash is necessary... could the documentation be updated to help others? Thx

Unable to install with node v0.10.0 on linux

I'm trying to install node-java using npm but it is failing to compile (output is below).

I have managed to find out this much: libuv's uv_after_work_cb has gained an addition int argument (see joyent/libuv@92fb84b).

Unfortunately I know nothing about libuv and very little about node.js, but I would love to use your library.

Any chance this is a quick fix?

Thanks

This is the output of 'npm instal java':

[email protected] install /home/victor/node_modules/java
node-gyp rebuild

make: Entering directory /home/victor/node_modules/java/build' ACTION Verify Deps build/depsVerified CXX(target) Release/obj.target/nodejavabridge_bindings/src/java.o ../src/java.cpp: In function ‘_jobject* Java_node_NodeDynamicProxyClass_callJs(JNIEnv*, _jobject*, jlong, _jobject*, _jobjectArray*)’: ../src/java.cpp:731: error: invalid conversion from ‘void (*)(uv_work_t*)’ to ‘void (*)(uv_work_t*, int)’ ../src/java.cpp:731: error: initializing argument 4 of ‘int uv_queue_work(uv_loop_t*, uv_work_t*, void (*)(uv_work_t*), void (*)(uv_work_t*, int))’ make: *** [Release/obj.target/nodejavabridge_bindings/src/java.o] Error 1 make: Leaving directory/home/victor/node_modules/java/build'
gyp ERR! build error
gyp ERR! stack Error: make failed with exit code: 2
gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:256:23)
gyp ERR! stack at ChildProcess.EventEmitter.emit (events.js:98:17)
gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:754:12)
gyp ERR! System Linux 2.6.32-279.22.1.el6.x86_64
gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/victor/node_modules/java
gyp ERR! node -v v0.10.0
gyp ERR! node-gyp -v v0.8.5
gyp ERR! not ok
npm ERR! [email protected] install: node-gyp rebuild
npm ERR! sh "-c" "node-gyp rebuild" failed with 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is most likely a problem with the java package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-gyp rebuild
npm ERR! You can get their info via:
npm ERR! npm owner ls java
npm ERR! There is likely additional logging output above.

npm ERR! System Linux 2.6.32-279.22.1.el6.x86_64
npm ERR! command "/usr/local/bin/node" "/usr/local/bin/npm" "install" "java"
npm ERR! cwd /home/victor
npm ERR! node -v v0.10.0
npm ERR! npm -v 1.2.14
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /home/victor/npm-debug.log
npm ERR! not ok code 0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.