How to compile/run the java code via javac/java? - java

I have a code below. I can compile and run it normally in NetBeans. But with javac/java, I cannot run it normally. What do I miss?
The code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/* the original code is from link: http://edu.qudong.com/safe/base/Javascript/shilidaima/20080514/12527.html */
package gendemo;
/**
*
* #author tomxue
*/
class Gen2 {
private Object ob; //定义一个通用类型成员
public Gen2(Object ob) {
this.ob = ob;
}
public Object getOb() {
return ob;
}
public void setOb(Object ob) {
this.ob = ob;
}
public void showTyep() {
System.out.println("T的实际类型是: " + ob.getClass().getName());
}
}
public class GenDemo2 {
public static void main(String[] args) {
//定义类Gen2的一个Integer版本
Gen2 intOb = new Gen2(new Integer(88));
intOb.showTyep();
int i = (Integer) intOb.getOb();
System.out.println("value= " + i);
System.out.println("----------------------------------");
//定义类Gen2的一个String版本
Gen2 strOb = new Gen2("Hello Gen!");
strOb.showTyep();
String s = (String) strOb.getOb();
System.out.println("value= " + s);
}
}
By javac, after compiling, I got below result.
tomxue#ubuntu:~/test$ javac GenDemo2.java
tomxue#ubuntu:~/test$ ls
Gen2.class GenDemo2.class GenDemo2.java
And then, if I run it like this:
tomxue#ubuntu:~/test$ java Gen2
Exception in thread "main" java.lang.NoClassDefFoundError: Gen2
Caused by: java.lang.ClassNotFoundException: Gen2
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
tomxue#ubuntu:~/test$ java GenDemo2
Exception in thread "main" java.lang.NoClassDefFoundError: GenDemo2
Caused by: java.lang.ClassNotFoundException: GenDemo2
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
What is wrong with it?

The problem is that java expects the directory structure to match the package name ("gendemo"), so it can't find your classes. move your java file into a sub-directory named gendemo, then compile it from the top directory using javac gendemo/GenDemo2.java and run it using java -cp . gendemo.GenDemo2.

When you run java SomeClass JVM load SomeClass and trying to run SomeClass.main method.
So you should run:
java GenDemo2
or add:
public static void main(String[] args) to Gen2.java

Related

Including Python Script in Spring Boot Application with Jython fails - module not found

I am trying to get used to python+java interaction and so I wrote a little python-script that I wanted to execute that script from my Spring Boot Application. That script is located in the (relative from the .java-file) path /scripts_py/getStockPrice.py that contains the getStockPrice-method (see code below). So I integrated jython and tried to execute the following CronJob:
#Component
public class CronService {
private PythonScriptSingleton pss = PythonScriptSingleton.getInstance();
private final Logger logger = LoggerFactory.getLogger(CronService.class);
//call every 5 sec
#Scheduled(fixedRate = 5000)
public void initStockPriceAPICall() {
this.getStockPrice("NFLX");
}
public void getStockPrice(String ticker) {
String result = (String) (Object) this.pss.getFunc_getPriceForTicker().__call__(new PyString(ticker));
try {
logger.info("Price is " + result);
} catch (NullPointerException e) {
logger.info("Catched NPE");
}
}
}
The PythongScriptSingleton (the idea was, that I probably need to execute that script a lot of times - so I tried to go for a singleton instance of this class that holds the script so I do not need to recompile it every time:
public class PythonScriptSingleton {
private static PythonScriptSingleton ps;
public static PythonScriptSingleton getInstance() {
if (ps == null) {
ps = new PythonScriptSingleton();
ps.initScript();
}
return ps;
}
private PyObject func_getPriceForTicker;
private PythonScriptSingleton() {
}
private void initScript() {
PythonInterpreter interpreter = new PythonInterpreter();
String fileUrlPath = "/scripts_py";
String scriptName = "getStockPrice.py";
interpreter.exec("import sys\n" + "import os \n" + "sys.path.append('" + fileUrlPath + "')\n" + "from "
+ scriptName + " import * \n");
String funcName = "getStockPrice";
PyObject someFunc = interpreter.get(funcName);
this.func_getPriceForTicker = someFunc;
interpreter.close();
}
public PyObject getFunc_getPriceForTicker() {
return func_getPriceForTicker;
}
}
The Python Script:
from yahoo_fin import stock_info as si
def getStockPrice(ticker):
price = si.get_live_price(ticker)
return price
I am using the embedded tomcat with Spring Boot (executable JAR-File) and jython-standalone 2.7.2:
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.2</version>
</dependency>
The error i keep running into says, that the script is not defined - I tried defining it with and without the file ending (.py), both did not change anything:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [de.fr.stockticker.pythoninteraction.CronService]: Constructor threw exception; nested exception is Traceback (most recent call last):
File "<string>", line 4, in <module>
ImportError: No module named getStockPrice
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:217) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1312) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
... 81 common frames omitted
Caused by: org.python.core.PyException: ImportError: No module named getStockPrice
at org.python.core.Py.ImportError(Py.java:329) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.imp.import_first(imp.java:1230) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.imp.import_module_level(imp.java:1361) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.imp.importName(imp.java:1528) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.ImportFunction.__call__(__builtin__.java:1285) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.PyObject.__call__(PyObject.java:433) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.__builtin__.__import__(__builtin__.java:1232) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.imp.importAll(imp.java:1647) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.pycode._pyx0.f$0(<string>:4) ~[na:na]
at org.python.pycode._pyx0.call_function(<string>) ~[na:na]
at org.python.core.PyTableCode.call(PyTableCode.java:173) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.PyCode.call(PyCode.java:18) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.Py.runCode(Py.java:1687) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.Py.exec(Py.java:1731) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.util.PythonInterpreter.exec(PythonInterpreter.java:268) ~[jython-standalone-2.7.2.jar:2.7.2]
at de.fr.stockticker.pythoninteraction.PythonScriptSingleton.initScript(PythonScriptSingleton.java:28) ~[classes/:na]
at de.fr.stockticker.pythoninteraction.PythonScriptSingleton.getInstance(PythonScriptSingleton.java:13) ~[classes/:na]
at de.fr.stockticker.pythoninteraction.CronService.<init>(CronService.java:12) ~[classes/:na]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_251]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_251]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_251]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_251]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:204) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
... 83 common frames omitted
I was able to run your program partially using Jython - I couldn't get the stock process from yahoo which is internally depends on numpy and looks like Jython doesn't support numpy as it being cpython library.
private void initScript() {
PythonInterpreter interpreter = new PythonInterpreter();
String fileUrlPath = "/users/sagar/demo/src/main/resources/python";
interpreter.exec("import sys");
interpreter.exec("sys.path.append('" + fileUrlPath + "')");
interpreter.exec("from getStockPrice import *"); this.func_getPriceForTicker =
interpreter.get("getStockPrice", PyFunction.class);
interpreter.close();
}
You will be able to get past your error but you will see error
Missing required dependencies ['numpy']
So I tried using another java python library jep and made changes as follow
#SpringBootApplication
#EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
private final Logger logger = LoggerFactory.getLogger(DemoApplication.class);
//call every 5 sec
#Scheduled(fixedRate = 5000)
public void initStockPriceAPICall() throws JepException {
this.getStockPrice("NFLX");
}
private void getStockPrice(String ticker) throws JepException {
try (Interpreter interp = new SharedInterpreter()) {
String fileUrlPath = "/users/sagar/demo/src/main/resources/python";
interp.exec("import sys");
interp.exec("sys.path.append('" + fileUrlPath + "')");
interp.exec("from getStockPrice import *");
interp.set("ticker", ticker);
interp.exec("price = getStockPrice(ticker)");
Object result = interp.getValue("price");
logger.info("Price is " + result);
}
}
}
pom.xml
<dependency>
<groupId>black.ninia</groupId>
<artifactId>jep</artifactId>
<version>3.9.0</version>
</dependency>
Make sure to install jep module - it has native library
pip install jeb
Add java library path to load native library
-Djava.library.path=/usr/local/lib/python2.7/site-packages/jep
Reference - https://github.com/ninia/jep/wiki/Getting-Started

Java library (GSON) : NoClassDefFoundError

For a project, I need to import the GSON library, despite of these steps found on different topics, I still have the error NoClassDefFoundError...
Step 1 : in the BuildPath, I add the library as an external JARs
Step 2 : in Order and Export, I check the library
So, if anyone has the solution, thank you in advance for your answers ! ;)
More Informations :
package ummisco.gama.webgl;
import com.google.gson.Gson;
public class SceneReceiver {
private final static SceneReceiver instance = new SceneReceiver();
private boolean canReceive = true;
public static SceneReceiver getInstance() {
return instance;
}
private SceneReceiver() {
}
public void receive(final SimpleScene scene) {
reception(false);
try {
Gson gson = new Gson();
String sceneSend = gson.toJson(scene);
System.out.println(sceneSend);
} catch (Exception e) {
System.out.println(e.getMessage());
}
reception(true);
}
private void reception(boolean canReceive) {
this.canReceive = canReceive;
}
public boolean canReceive() {
return canReceive;
}
}
Here the stacktrace :
Exception in thread "Thread-14" java.lang.NoClassDefFoundError: com/google/gson/Gson
at ummisco.gama.webgl.SceneReceiver.receive(SceneReceiver.java:28)
at ummisco.gama.opengl.scene.ModelScene.endDrawingLayers(ModelScene.java:232)
at ummisco.gama.opengl.scene.SceneBuffer.endUpdatingScene(SceneBuffer.java:74)
at ummisco.gama.opengl.JOGLRenderer.endDrawingLayers(JOGLRenderer.java:713)
at msi.gama.outputs.display.LayerManager.drawLayersOn(LayerManager.java:182)
at ummisco.gama.opengl.SWTOpenGLDisplaySurface.updateDisplay(SWTOpenGLDisplaySurface.java:168)
at ummisco.gama.ui.views.displays.LayeredDisplayView$11.run(LayeredDisplayView.java:673)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: com.google.gson.Gson cannot be found by ummisco.gama.opengl_1.7.0.qualifier
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:439)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:352)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:344)
at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:160)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 8 more

Eclipse Birt ClassNotFoundException

I created scripted dataset in Birt (4.4.0) along with a Event Handler:
public class ActionsPerDateDataSet extends ScriptedDataSetEventAdapter {
#Override
public boolean fetch( IDataSetInstance dataSet, IUpdatableDataSetRow row ) throws ScriptException {
}
#Override
public void open(IDataSetInstance dataSet) {
}
}
I generate the report using the following code:
public File actionPdf() throws EngineException, IOException {
IReportEngine engine = getEngine();
IReportRunnable design = engine.openReportDesign("c:\\...\\scripted.rptdesign");
IRunAndRenderTask task = engine.createRunAndRenderTask(design);
// Set parent classloader for engine
task.getAppContext().put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY, ReportingService.class.getClassLoader());
File f = new File(System.nanoTime() + "res.pdf");
final IRenderOption options = new RenderOption();
options.setOutputFormat("pdf");
OutputStream os = new FileOutputStream(f);
options.setOutputStream(os);
task.setRenderOption(options);
task.run();
task.close();
os.close();
return f;
}
However Birt can't find the class:
Caused by: java.lang.ClassNotFoundException: com.foo.aip.ejb.reporting.action.ActionsPerDateDataSet
at org.eclipse.birt.core.framework.URLClassLoader.findClass1(URLClassLoader.java:188)
at org.eclipse.birt.core.framework.URLClassLoader$1.run(URLClassLoader.java:156)
at org.eclipse.birt.core.framework.URLClassLoader$1.run(URLClassLoader.java:1)
at java.security.AccessController.doPrivileged(Native Method)
at org.eclipse.birt.core.framework.URLClassLoader.findClass(URLClassLoader.java:151)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at org.eclipse.birt.report.engine.executor.ApplicationClassLoader.loadClass(ApplicationClassLoader.java:79)
at org.eclipse.birt.report.engine.executor.EventHandlerManager.loadClass(EventHandlerManager.java:99)
... 85 more
I am out of ideas :(
Do you have any hints for me?
The classloader should be set when the engine is initialized, use an object of type org.eclipse.birt.report.engine.api.EngineConfig
EngineConfig config = new EngineConfig();
config.getAppContext().put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY,ReportingService.class.getClassLoader());
Of course this will work only if "ReportingService" class is in the same classloader than "ActionsPerDateDataSet" but you don't provide informations about that. If it is not the case, set a further classloader to the BIRT engine with
config.setProperty( EngineConstants.WEBAPP_CLASSPATH_KEY,"c:/your-jar-location/actionperdataset.jar;c:/your-class-location" );

hazelcast mapper class not found

I`m trying to run map/reduce task on hazelcast 3.4, but I keep getting classs not found exception
I created several players and store them to IMap
this.conf = new ClientConfig();
HazelcastInstance cluster = HazelcastClient.newHazelcastClient(this.conf);
Map<String, Player> mapPlayers = cluster.getMap("players");
for (int playerID = 0; playerID < 10000; playerID++) {
Player p = new Player();
mapPlayers.put(Integer.toString(playerID), p);
System.out.println("inserted player nuber " + Integer.toString(playerID));
}
after that I created map reduce class MRCount
public class MRCount {
private ClientConfig conf;
public MRCount() {
this.conf = new ClientConfig();
this.conf.getNetworkConfig();
}
public void getCount() throws ExecutionException, InterruptedException {
HazelcastInstance cluster = HazelcastClient.newHazelcastClient(this.conf);
IMap<String, Player> mapPlayers = cluster.getMap("players");
KeyValueSource<String, Player> source = KeyValueSource.fromMap(mapPlayers);
JobTracker jobTracker = cluster.getJobTracker("default");
Job<String, Player> job = jobTracker.newJob(source);
ICompletableFuture<Map<String, Integer>> future = job.mapper(new MyMapper())
.reducer(new MyReducerFactory()).submit();
// future.andThen(buildCallback());
Map<String, Integer> result = future.get();
for (Map.Entry<String, Integer> e: result.entrySet()) {
System.out.println(e.getKey() + ": " + Integer.toString(e.getValue()) );
}
cluster.shutdown();
}
}
mapper class:
public class MyMapper implements Mapper<String, Player, String, Integer> {
#Override
public void map(String key, Player value, Context<String, Integer> context) {
context.emit("total", 1);
}
}
public class MyReducerFactory implements ReducerFactory<String, Integer, Integer>{
#Override
public Reducer<Integer, Integer> newReducer(String key) {
return new MyReducer();
}
private class MyReducer extends Reducer<Integer, Integer> {
private volatile Integer result = 0;
#Override
public void reduce(Integer value) {
result += value;
}
#Override
public Integer finalizeReduce() {
return result;
}
}
}
I builded my project with maven. when I start the import functions everything goes well and I`ve got players stored in HZ cluster, but when i start the MRCount.getCount() function I keep getting HazelcastSerializationException
Exception in thread "main" java.util.concurrent.ExecutionException: com.hazelcast.nio.serialization.HazelcastSerializationException: java.lang.ClassNotFoundException: com.test.queries.models.MyMapper
at com.hazelcast.client.spi.impl.ClientCallFuture.resolveResponse(ClientCallFuture.java:214)
at com.hazelcast.client.spi.impl.ClientCallFuture.access$000(ClientCallFuture.java:53)
at com.hazelcast.client.spi.impl.ClientCallFuture$1.run(ClientCallFuture.java:286)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
at com.hazelcast.util.executor.HazelcastManagedThread.executeRun(HazelcastManagedThread.java:76)
at com.hazelcast.util.executor.HazelcastManagedThread.run(HazelcastManagedThread.java:92)
Caused by: com.hazelcast.nio.serialization.HazelcastSerializationException: java.lang.ClassNotFoundException: com.test.queries.models.MyMapper
at com.hazelcast.nio.serialization.DefaultSerializers$ObjectSerializer.read(DefaultSerializers.java:201)
at com.hazelcast.nio.serialization.StreamSerializerAdapter.read(StreamSerializerAdapter.java:44)
at com.hazelcast.nio.serialization.SerializationServiceImpl.readObject(SerializationServiceImpl.java:309)
at com.hazelcast.nio.serialization.ByteArrayObjectDataInput.readObject(ByteArrayObjectDataInput.java:439)
at com.hazelcast.mapreduce.impl.client.ClientMapReduceRequest.readData(ClientMapReduceRequest.java:226)
at com.hazelcast.mapreduce.impl.client.ClientMapReduceRequest.read(ClientMapReduceRequest.java:181)
at com.hazelcast.client.impl.client.ClientRequest.readPortable(ClientRequest.java:116)
at com.hazelcast.nio.serialization.PortableSerializer.read(PortableSerializer.java:88)
at com.hazelcast.nio.serialization.PortableSerializer.read(PortableSerializer.java:30)
at com.hazelcast.nio.serialization.StreamSerializerAdapter.toObject(StreamSerializerAdapter.java:65)
at com.hazelcast.nio.serialization.SerializationServiceImpl.toObject(SerializationServiceImpl.java:260)
at com.hazelcast.client.impl.ClientEngineImpl$ClientPacketProcessor.loadRequest(ClientEngineImpl.java:364)
at com.hazelcast.client.impl.ClientEngineImpl$ClientPacketProcessor.run(ClientEngineImpl.java:340)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
at com.hazelcast.util.executor.HazelcastManagedThread.executeRun(HazelcastManagedThread.java:76)
at com.hazelcast.util.executor.HazelcastManagedThread.run(HazelcastManagedThread.java:92)
at ------ End remote and begin local stack-trace ------.(Unknown Source)
at com.hazelcast.client.spi.impl.ClientCallFuture.resolveResponse(ClientCallFuture.java:201)
... 7 more
Caused by: java.lang.ClassNotFoundException: com.test.queries.models.MyMapper
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at com.hazelcast.nio.ClassLoaderUtil.tryLoadClass(ClassLoaderUtil.java:124)
at com.hazelcast.nio.ClassLoaderUtil.loadClass(ClassLoaderUtil.java:113)
at com.hazelcast.nio.IOUtil$1.resolveClass(IOUtil.java:113)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1612)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1517)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1771)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at com.hazelcast.nio.serialization.DefaultSerializers$ObjectSerializer.read(DefaultSerializers.java:196)
at com.hazelcast.nio.serialization.StreamSerializerAdapter.read(StreamSerializerAdapter.java:44)
at com.hazelcast.nio.serialization.SerializationServiceImpl.readObject(SerializationServiceImpl.java:309)
at com.hazelcast.nio.serialization.ByteArrayObjectDataInput.readObject(ByteArrayObjectDataInput.java:439)
at com.hazelcast.mapreduce.impl.client.ClientMapReduceRequest.readData(ClientMapReduceRequest.java:226)
at com.hazelcast.mapreduce.impl.client.ClientMapReduceRequest.read(ClientMapReduceRequest.java:181)
at com.hazelcast.client.impl.client.ClientRequest.readPortable(ClientRequest.java:116)
at com.hazelcast.nio.serialization.PortableSerializer.read(PortableSerializer.java:88)
at com.hazelcast.nio.serialization.PortableSerializer.read(PortableSerializer.java:30)
at com.hazelcast.nio.serialization.StreamSerializerAdapter.toObject(StreamSerializerAdapter.java:65)
at com.hazelcast.nio.serialization.SerializationServiceImpl.toObject(SerializationServiceImpl.java:260)
at com.hazelcast.client.impl.ClientEngineImpl$ClientPacketProcessor.loadRequest(ClientEngineImpl.java:364)
at com.hazelcast.client.impl.ClientEngineImpl$ClientPacketProcessor.run(ClientEngineImpl.java:340)
... 5 more
You have to deploy all the classes on the server side as well.
First, create custom Jar file with com.test.queries.models.MyMapper class and place it Hazelcast lib folder. Then, add the following classpath entry in server .bat file and restart.
set CLASSPATH=%~dp0..\lib\hazelcast-all-3.5.2.jar
set CLASSPATH=%CLASSPATH%;..\lib\Custom-0.0.1-SNAPSHOT.jar

Luaj / Java: org.luaj.vm2.LuaError: loop or previous error loading module

I am learning the Luaj library and I am trying to implement the hyperbolic example in a unit test:
#Test
public void testHyperbolicLuaScriptExample() throws Exception {
URL luaScriptUrl = Thread.currentThread().getContextClassLoader().getResource("hyperbolic.lua");
Assert.assertNotNull(luaScriptUrl);
String luaScriptUrlPath = luaScriptUrl.getPath();
File luaScriptFile = new File(luaScriptUrlPath);
FileInputStream luaScriptFileInputStream = new FileInputStream(luaScriptFile);
Prototype luaScriptPrototype = LuaC.instance.compile(luaScriptFileInputStream, "");
Globals luaScriptStandardGlobals = JsePlatform.standardGlobals();
LuaClosure luaClosure = new LuaClosure(luaScriptPrototype, luaScriptStandardGlobals);
LuaValue luaValue = luaClosure.call();
}
hyperbolic.java is constructed as per the example
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.*;
public class hyperbolic extends TwoArgFunction {
public hyperbolic() {}
public LuaValue call(LuaValue moduleName, LuaValue environment) {
LuaValue library = tableOf();
library.set("sinh", new sinh());
library.set("cosh", new cosh());
environment.set("com.apple.aide.lua.hyperbolic", library);
return library;
}
static class sinh extends OneArgFunction {
public LuaValue call(LuaValue x) {
return LuaValue.valueOf(Math.sinh(x.checkdouble()));
}
}
static class cosh extends OneArgFunction {
public LuaValue call(LuaValue x) {
return LuaValue.valueOf(Math.cosh(x.checkdouble()));
}
}
}
And the in hyberbolic.lua
require 'hyperbolic'
return {"x", hyperbolic.sinh(0.5), "y", hyperbolic.cosh(0.5)}
However the test produces the following error
org.luaj.vm2.LuaError: #hyperbolic.lua:3 loop or previous error loading module 'hyperbolic'
at org.luaj.vm2.LuaValue.error(Unknown Source)
at org.luaj.vm2.lib.PackageLib$require.call(Unknown Source)
at org.luaj.vm2.LuaClosure.execute(Unknown Source)
at org.luaj.vm2.LuaClosure.call(Unknown Source)
at org.luaj.vm2.lib.PackageLib$require.call(Unknown Source)
at org.luaj.vm2.LuaClosure.execute(Unknown Source)
at org.luaj.vm2.LuaClosure.call(Unknown Source)
at com.example.LuaScriptExecutionTest.testHyperbolicLuaScriptExample(LuaScriptExecutionTest.java:52)
What does this error mean and how do I fix it?
And the in hyberbolic.lua (sic, should be hyperbolic)
require 'hyperbolic'
You require a module with the same name as the file in which require happens, which leads to a loop (that's what the error message is about). Simply rename the current file (hyperbolic.lua) and the error should go away.

Categories