How do I use jGrasp's libraries? - import

I have a folder full of classes from a class I took. With a fresh install of jGrasp old projects that used to run fine are now full of "symbol not found" errors.
I still have the libraries, but I don't know how to import them. The way our class was set up, you didn't need import statements for anything that was in the library.
/* Turtle Drawing Program Lab 6, Part B */
/* Started by Celine Latulipe , modified by Bruce Long*/
public class Lab6PartB {
public static void main(String [] args)
{
/* Create the world */
World w = new World();
/* Create the turtle, call him Tom */
Turtle tom = new Turtle(w);
/* test the getDistance2() method */
int dist = tom.getDistance2();
System.out.println("This should print out the value 400. Value is: " + dist);
tom.moveTo(500, 400);
dist = tom.getDistance2();
System.out.println("This should print out the value 640. Value is: " + dist);
// TODO: Add a third test case that you make up
}
}
Error:
----jGRASP exec: java Lab6PartB
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: ModelDisplay
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: ModelDisplay
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.

You can add the directory containing the class files to the classpath, either at the OS level, or using "Settings" > "PATH / CLASSPATH" > "Workspace" in jGRASP.
Also, you could copy all the class files/directories to the folder containing your new project classes.

Related

JyNI Eclipse setup

I have the following Java file in Eclipse.
package java_python_tutorial;
import org.python.core.PyInstance;
import org.python.util.PythonInterpreter;
public class MainJython {
public static void main(String[] args) {
PythonInterpreter python = new PythonInterpreter();
python.execfile("pytest/test_np.py");
// PyInstance test = (PyInstance) python.eval("Test()");
// test.invoke("printArr");
python.close();
}
}
If I include just the Jython JAR, running the file will result in an ImportError: no module named numpy from Python. I tried fixing this problem by also including the JyNI JAR in my project build path, but now running the file gives this error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/python/modules/_weakref/ReferenceBackendFactory
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
at java.lang.Class.getConstructor0(Class.java:3075)
at java.lang.Class.newInstance(Class.java:412)
at org.python.core.PySystemState.initialize(PySystemState.java:1015)
at org.python.core.PySystemState.initialize(PySystemState.java:947)
at org.python.core.PySystemState.initialize(PySystemState.java:930)
at org.python.core.PySystemState.initialize(PySystemState.java:925)
at org.python.core.PySystemState.initialize(PySystemState.java:920)
at org.python.core.PySystemState.initialize(PySystemState.java:916)
at org.python.core.ThreadStateMapping.getThreadState(ThreadStateMapping.java:32)
at org.python.core.Py.getThreadState(Py.java:1440)
at org.python.core.Py.getThreadState(Py.java:1436)
at org.python.core.Py.getSystemState(Py.java:1456)
at org.python.util.PythonInterpreter.<init>(PythonInterpreter.java:105)
at org.python.util.PythonInterpreter.<init>(PythonInterpreter.java:94)
at org.python.util.PythonInterpreter.<init>(PythonInterpreter.java:71)
at java_python_tutorial.MainJython.main(MainJython.java:7)
Caused by: java.lang.ClassNotFoundException: org.python.modules._weakref.ReferenceBackendFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 18 more
For reference, the contents of the Python script I'm calling is:
import numpy as np
class TestNP(object):
def __init__(self):
self.arr = np.array([[1,2,3],[4,5,6]])
def printArr(self):
print(self.arr)

integrate an ant project

I want to run a following project:
https://gforge.inria.fr/plugins/mediawiki/wiki/melinda/index.php/RDF_keys
In the project page, they resume the steps as the following:
1-git clone https://gforge.inria.fr/git/melinda/melinda.git
2-cd melinda/trunk/rdfifd/
3-ant jar
4- java -jar pseudo-keys.jar -t -i /path/to/rdf_file -o /path/to/output/file
So how can i integrate and run this project in an eclipse project?
I already following these setp on a linux command line and it is work well and pseudo-keys.jar is generated. I take this .jar and In my laptop i write the following code:
public class TestDriver {
/** Executes a command */
public static void execute(String cmd, File folder) throws Exception {
Process p = Runtime.getRuntime().exec(cmd, null, folder);
BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader bre = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String s1, s2 = null;
while (null != (s1 = bri.readLine()) || null != (s2 = bre.readLine())) {
if (s1 != null) System.out.println(s1);
if (s2 != null) System.err.println(s2);
}
p.waitFor();
}
public static void main(String[]args) throws Exception{
String cmd = "java -jar C:/Users/user/Desktop/pseudo-keys.jar -t -i C:/Users/user/Desktop/randomLocation/datasetLocation/restaurant1.rdf -o C:/Users/user/Desktop/randomLocation/key.xml";
execute(cmd, null);
}
The execution give the following error:
java.lang.NoClassDefFoundError: org/apache/commons/cli/ParseException
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.cli.ParseException
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main"
Any help please to run the code? Where is my mistake?
Thank you
Copy the URI https://gforge.inria.fr/git/melinda/melinda.git to the clipboard
In the Git Repositories click the Clone a Git Repository button and follow the wizard (if the dialog is not prefilled, enter the URI manually)
Right-click the node melinda [master] > Working Tree > trunk > rdfifd and choose Import Projects... and follow the import wizard
In the Package Explorer or Project Explorer open the file rdfifd/build.xml via double-click
In the Outline view right-click the target jar and choose Run As > Ant Build
On the command line run java -jar pseudo-keys.jar -t -i /path/to/rdf_file -o /path/to/output/file. Alternatively, you can skip step 4 and 5 and run fr.inrialpes.exmo.rdfkeys.KeyExtraction as Java application with the necessary arguments (Run > Run Configurations..., in tab Arguments field Program arguments).

Talend - The import org.apache cannot be resolved

I've created a custom Talend component, which at certain step connects to an external Http service. For that, I'm using org.apache.commons.httpclient through javajet imports. I've seen the modules already exist in the Modules view. Nevertheless, when running a job the console outputs:
Execution failed : Failed to generate code.
[----------
1. ERROR in /Users/frb/Downloads/TOS_DI-20160510_1709-V6.2.0/workspace/.JETEmitters/src/org/talend/designer/codegen/translators/ngsi/orion/TOrionAppendBeginJava.java (at line 14)
import org.apache.commons.httpclient.*;
^^^^^^^^^^
The import org.apache cannot be resolved
----------
2. ERROR in /Users/frb/Downloads/TOS_DI-20160510_1709-V6.2.0/workspace/.JETEmitters/src/org/talend/designer/codegen/translators/ngsi/orion/TOrionAppendBeginJava.java (at line 15)
import org.apache.commons.httpclient.methods.*;
^^^^^^^^^^
The import org.apache cannot be resolved
----------
3. ERROR in /Users/frb/Downloads/TOS_DI-20160510_1709-V6.2.0/workspace/.JETEmitters/src/org/talend/designer/codegen/translators/ngsi/orion/TOrionAppendBeginJava.java (at line 16)
import org.apache.commons.httpclient.params.HttpMethodParams;;
^^^^^^^^^^
The import org.apache cannot be resolved
----------
3 problems (3 errors)
]
Any hints about how to fix this issue? My Talend version is 6.2.0.
EDIT 1
This is my begin code:
<%# jet
imports="
org.talend.core.model.process.INode
org.talend.core.model.process.ElementParameterParser
org.talend.core.model.metadata.IMetadataTable
org.talend.core.model.metadata.IMetadataColumn
org.talend.core.model.process.IConnection
org.talend.core.model.process.IConnectionCategory
org.talend.designer.codegen.config.CodeGeneratorArgument
org.talend.core.model.metadata.types.JavaTypesManager
org.talend.core.model.metadata.types.JavaType
java.util.List
java.util.Map
org.apache.commons.httpclient.*
org.apache.commons.httpclient.methods.*
org.apache.commons.httpclient.params.HttpMethodParams
"
%>
<%
// Get the CID
CodeGeneratorArgument codeGenArgument = (CodeGeneratorArgument) argument;
INode node = (INode)codeGenArgument.getArgument();
String cid = node.getUniqueName();
// Get the component parameters
String orionEndpoint = ElementParameterParser.getValue(node, "__ORION_ENDPOINT__");
String authEndpoint = ElementParameterParser.getValue(node, "__AUTH_ENDPOINT__");
String authUsername = ElementParameterParser.getValue(node, "__AUTH_USERNAME__");
String authPassword = ElementParameterParser.getValue(node, "__AUTH_PASSWORD__");
String entityIdField = ElementParameterParser.getValue(node, "__ENTITY_ID_FIELD__");
String entityTypeField = ElementParameterParser.getValue(node, "__ENTITY_TYPE_FIELD__");
String defaultEntityType = ElementParameterParser.getValue(node, "__DEFAULT_ENTITY_TYPE__");
String ignoredFilds = ElementParameterParser.getValue(node, "__IGNORED_FIELDS__");
%>
System.out.println("I am the begin section");
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(<%=authEndpoint%>);
method.setRequestHeader(new Header("Content-Type", "application/json"));
method.setRequestBody("{\"username\":\"" + <%=authUsername%> + "\",\"password\":\"" + <%=authPassword%> + "\"}");
try {
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
} // if
byte[] responseBody = method.getResponseBody();
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
method.releaseConnection();
} // try
EDIT 2
I've added the following to my Component Descriptor file:
<IMPORTS>
<IMPORT
NAME="commons-httpclient"
MODULE="commons-httpclient-3.1.jar"
REQUIRED="true"
/>
</IMPORTS>
Now, in the modules view I'm able to see the following:
Sadly, the component outputs the same errors.
EDIT 3
After removing the imports and using fully qualified names, as suggested by #Balazs Gunics, the code seems to be generated. Nevertheless, some other errors related to commons-httpclient arise at running time:
Starting job job_tOrionAppend at 08:20 21/06/2016.
[statistics] connecting to socket on port 3916
[statistics] connected
I am the begin section
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.apache.commons.httpclient.HttpClient.<clinit>(HttpClient.java:66)
at iotp_talend_connectors.job_torionappend_0_1.job_tOrionAppend.tMysqlInput_1Process(job_tOrionAppend.java:854)
at iotp_talend_connectors.job_torionappend_0_1.job_tOrionAppend.tMysqlConnection_1Process(job_tOrionAppend.java:422)
at iotp_talend_connectors.job_torionappend_0_1.job_tOrionAppend.runJobInTOS(job_tOrionAppend.java:1355)
at iotp_talend_connectors.job_torionappend_0_1.job_tOrionAppend.main(job_tOrionAppend.java:1212)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
[statistics] disconnected
[statistics] disconnected
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 5 more
Job job_tOrionAppend ended at 08:20 21/06/2016. [exit code=1]
So in the begin.javajet code of yours the following code will only import these libraries for the code generation itself. But you need them to the generated code.
Generating java using java makes it hard to oversee this.
<%# jet
imports="
org.apache.commons.httpclient.*
org.apache.commons.httpclient.methods.*
org.apache.commons.httpclient.params.HttpMethodParams
So what you need is to have these imports added to the generated code. Well that is not really possible :( https://www.talendforge.org/forum/viewtopic.php?id=3670 To do that you need to modify the xml descriptor for your component.
So your imports are right. All you have to do is make sure you use the fully qualified names. I.e.: This piece of code:
System.out.println("I am the begin section");
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(<%=authEndpoint%>);
Have to be rewritten to look like this:
System.out.println("I am the begin section");
org.apache.commons.httpclient.HttpClient client =
new org.apache.commons.httpclient.HttpClient();
org.apache.commons.httpclient.methods.PostMethod method =
new org.apache.commons.httpclient.methods.PostMethod(<%=authEndpoint%>);
Yes, it would be way more elegant if we could import the classes and use them.

LuaJava Eclipse

I finally managed to get LuaJava to build on OSX and now I am running into trouble using it in Eclipse. I put the jnilib in my system path and when I go to the directory where I built it I can run the Console like this:
$ java -cp "luajava-1.1.jar" org.keplerproject.luajava.Console
API Lua Java - console mode.
> print("Hello World!")
Hello World!
> exit
$
So I'm guessing that means that it is built and installed correctly. I added the jar to my project using the "Add External Jar" in the Java Build Path property window. But when I try to use it I get this error:
Exception in thread "main" java.lang.NoClassDefFoundError: ScriptEngineSample
Caused by: java.lang.ClassNotFoundException: ScriptEngineSample
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:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Here is all of my code:
LuaWarrior.java
public class LuaWarrior
{
public static void main(String[] args)
{
new Game().start();
}
}
Game.java
import org.keplerproject.luajava.LuaState;
import org.keplerproject.luajava.LuaStateFactory;
public class Game
{
private LuaState _lua;
public Game()
{
_lua = LuaStateFactory.newLuaState();
_lua.openLibs();
}
public void start()
{
_lua.LdoFile("scripts/hello.lua");
}
}
It turns out that it doesn't need to be in the system path, but is needs to be in the JVM Library folder.
/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Libraries/

Java dynamic class loading fails on windows, but working fine on linux

I am trying to load a class dynamically from a jar file. It worked fine on a Ubuntu linux box ( Sun Java Version 1.6.0_24 (b07).
When I tried to run the same thing on Windows (Windows 7, Java version "1.6.0_14") it fails with Class Not Found exception.
Following is code :
try {
String jarFile = "/sqljdbc4.jar";
File newf = new File(jarFile);
System.out.println(newf.getAbsolutePath());
System.out.println("File exists ? :" + newf.exists());
String urlPath = "jar:file://" + newf.getAbsolutePath() + "!/";
System.out.println(urlPath);
ClassLoader cur = Thread.currentThread().getContextClassLoader();
URL[] jarUrlArray = { new URL(urlPath) };
URLClassLoader cl = URLClassLoader.newInstance(jarUrlArray, cur);
Class c = Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver", true, cl);
Method m[] = c.getMethods();
for (Method mm : m) {
System.out.println(mm.getName());
}
} catch (Exception e) {
e.printStackTrace();
}
While running on Linux, jar is placed at root and for Windows its at c:\ (source and binaries are in some folder on C:\ so "/sqljdbc4.jar" resolves to c:\sqljdbc4.jar on windows, I have made sure that correct jar location in passed to classloader for both the platforms.
Following is the stack trace i get on windows
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
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 java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:594)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at DemoClass.loadAClass(DemoClass.java:31)
at DemoClass.main(DemoClass.java:14)
NOTE : You can use any jar that u have to try this out. I was playing with MS SQL Server JDBC Driver jar.
Thanks !
-Abhijeet.
Try using this to create the URL rather than manually building the string:
URL[] jarUrlArray = { newf.toURI().toURL() };