I'm writing a program for homework and running into an issue I can't seem to resolve. The problem involves simulating the probabilities of a randomwalk ending on any given node (just background, not really relevant to the problem). I've written my own class that uses a hash map to hold node objects (UndirectedGraph and NodeEntry respectively). I've also written a test harness.
Originally all these were in one file but I decided to move the UndirectedGraph and NodeEntry to a separate package...cause that seems like the right thing to do. I've gotten everything fixed up so that testHarness will compile but at runtime I get the following:
Exception in thread "main" java.lang.NoClassDefFoundError: GraphWalker/NodeEntry
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2531)
at java.lang.Class.getMethod0(Class.java:2774)
at java.lang.Class.getMethod(Class.java:1663)
at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486)
Caused by: java.lang.ClassNotFoundException: GraphWalker.NodeEntry
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)
... 6 more
from looking around I find a few answers for this, primarily that the classes aren't on the classpath. Thing is I have all these files in the same folder, and my understanding is the current folder is always on the classpath.
here's abbreviated copies of the code:
testHarness:
import java.util.*;
import GraphWalker.*;
public class testHarness {
public static void main (String args[]) {
new testHarness();
}
public testHarness() {
GraphWalker.UndirectedGraph graph = new GraphWalker.UndirectedGraph(3);
// System.out.println(graph.containsNode(1));
graph.addNode(1);
graph.addNode(2);
graph.addNode(3);
UndirectedGraph:
package GraphWalker;
import java.util.*;
public class UndirectedGraph {
/*
* Based in part on UndirectedGraph.java by Keith Schwarz (htiek#cs.stanford.edu)
*/
public HashMap graphMap;
public UndirectedGraph(int numNodes) {
this.graphMap = new HashMap(numNodes);
}
public void addNode (Integer nodeNum) {
graphMap.put(nodeNum, new NodeEntry(1.0f,0.0f));
}
NodeEntry:
package GraphWalker;
import java.util.*;
public class NodeEntry {
// four inherent values
// credit is the current credit of the node
// nextCredit holds the credit for the next step
// adjList holds a list of adjacent node IDs
// degree holds the number of neighbors
public Float credit;
public Float nextCredit;
public ArrayList adjList;
public Integer degree;
public NodeEntry(Float credit, Float nextCredit) {
this.credit = credit;
this.nextCredit = nextCredit;
this.adjList = new ArrayList();
this.degree = 0;
}
public void addEdge(Integer neighbor) {
this.adjList.add(neighbor);
this.degree += 1;
}
each class has quite a bit more code but I don't think it's relevant to the issue. I'm working on Ubuntu 12.04 and trying to compile and run from both command line and using Geany (simple IDE) same behavior either way.
Any help?
Alrighty,
The issue was that the package files needed to be in a separate folder (named for the package, in my case GraphWalker). I'm not entirely clear on why it compiled fine but at runtime when it went to look for the package it seems to have expected/required them to be in their own folder.
I wouldn't consider that a class path issue, per se, since the files being looked for were in a folder that was on the classpath, just not the folder they needed to be in.
Related
My goal: Running Processing.org (version 3.5.4) from Max (cycling74) version 8 on Windows 10 64 through writing an MXJ external (Max Java support). I want to open a processing test sketch within window from MAX by sending a bang message to the MXJ external. For this I have
class MaxJavaTest3 extends MaxObject which calls
class TestProcessing extends PApplet.
public class MaxJavaTest3 extends MaxObject {
public void bang() {
String[] args = {};
TestProcessing.main(args);
}
}
public class TestProcessing extends PApplet {
public static void main(String args[] ) {
PApplet.main("TestProcessing", args);
}
public void settings() {
size(920, 780);
}
public void setup() {
background(0);
fill(255, 0, 0);
circle(width/2, height/2, 80);
}
}
In IntelliJ, I set the dependencies for Max and Java. The bang message is received in Java e.g. triggering some text messages to the console. If I execute PApplet.main via the entry point TestProcessing.main, the processing window opens. So far so good, but trying to invoke PApplet.main via MaxJavaTest3.bang() method I get the error:
java.lang.RuntimeException: java.lang.ClassNotFoundException: TestProcessing
at processing.core.PApplet.runSketch(PApplet.java:10852)
at processing.core.PApplet.main(PApplet.java:10657)
at TestProcessing.main(TestProcessing.java:11)
at MaxJavaTest3.bang(MaxJavaTest3.java:19)
Caused by: java.lang.ClassNotFoundException: TestProcessing
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at processing.core.PApplet.runSketch(PApplet.java:10845)
... 3 more
```JAVA
I found a post which suggests that there is a problem with Max using ProcessingĀ“s OpenGL related capacities: "since OpenGL uses also native libraries (*.dll files) and not only *.jar files. I don't know if its possible in MaxMSP - that depends on how they set up their JVM."
https://forum.processing.org/one/topic/use-processing-from-within-max-msp-or-from-matlab.html
Good day, Everyone!
This is my first time posting here, so I apologize in advance for the newbie mistakes in posting.
I am supposed to call a C# method in Java program. I am using RGiesecke.DllExport(1.2.7) to export my C# static method and com.sun.jna(4.2.2) to load the DLL in Java.
However, it always results to
Invalid memory access
java.lang.Error: Invalid memory access
at com.sun.jna.Native.invokePointer(Native Method)
at com.sun.jna.Function.invokePointer(Function.java:477)
at com.sun.jna.Function.invokeString(Function.java:658)
at com.sun.jna.Function.invoke(Function.java:402)
at com.sun.jna.Function.invoke(Function.java:323)
at com.sun.jna.Library$Handler.invoke(Library.java:236)
at com.sun.proxy.$Proxy13.Parse(Unknown Source)
I figured that it is caused by creating new C# objects in the called method because I have not yet allocated memory for the function.
I would like to confirm/ask if there is a way I can allocate memory for function in com.sun.jna.Library (loaded C# DLL).
Shown are the codes below:
Java (Interface for class):
package com.example.mydllclass
import com.sun.jna.Library;
public interface IMyDllClass extends Library {
String Parse(String path);
}
Java (Loading dll and invoking method)
public class MyClassProcess {
private final String DLL_PATH = ".\\MyClass.dll"
public String processFile(String path){
IMyDllClass INSTANCE =(IMyDllClass)Native.loadLibrary(DLL_PATH,IMyDllClass.class);
return INSTANCE.Parse(path);
}
}
C# Method
public class MyDllClass{
[DllExport("Parse", CallingConvention = CallingConvention.Cdecl)]
public static string Parse(string path)
{
String result = "";
ProcessResultCalculator processResultCalculator = new ProcessResultCalculator(); // I need to create this
result = processResultCalculator.execute(path);
return result;
}
}
Thank you!
While I have seen this happen with the main class and fixed it, I am now getting an error in which my main class cannot find another class I've created to make an object. The classes are within the same Eclipse project file, which is using sinbad to read xml. The classes are
public class RiverRunner {
public static void main(String[] args) {
String code1="abag1";
DataSource ds1= DataSource.connectAs("xml","https://water.weather.gov/ahps2/rss/obs/"+code1+".rss");
ds1.setCacheTimeout(100);
ds1.load();
//ds1.printUsageString();'
System.out.printf("");
//Rivers ob1 = new Rivers();
Rivers ob1 = ds1.fetch("Rivers", "title", "geo:lat", "geo:long");
System.out.println(code1 + ": " + ob1);
}
}
public class Rivers {
private String name;
private float lat;
private float lon;
public Rivers(String name, float lat, float lon) {
this.name=name;
this.lat=lat;
this.lon=lon;
}
//as of yet unwritten methods
}
and the precise error is
Exception in thread "main" core.ops.SignatureUnificationException: could not find a class named: Rivers (ds:no-class)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at core.log.Errors.exception(Errors.java:57)
at core.sig.SigUtils.classFor(SigUtils.java:32)
at core.data.DataSource.fetch(DataSource.java:705)
at RequiredPackage.RiverRunner.main(RiverRunner.java:20)
I've heard it has something to do with .classpath, but I do not know how to open or edit that, nor what it should look like. Other .java files within the project display the same issue. Copy pasting a functional .classpath did not work. Finally, RiverRunner recognizes that Rivers is real to some extent, because if I misspell Rivers when creating ob1, it gives a "cannot be resolved to a type" error, which does not occur if called correctly.
Somewhat of a followup to How to use public class frome .java file in other processing tabs?; using the example from Usage class from .java file - is there a full doc for that? - Processing 2.x and 3.x Forum, I have this:
/tmp/Sketch/Sketch.pde
// forum.processing.org/two/discussion/3677/
// usage-class-from-java-file-is-there-a-full-doc-for-that
Foo tester;
void setup() {
size(600, 400, JAVA2D);
smooth(4);
noLoop();
clear();
rectMode(Foo.MODE);
fill(#0080FF);
stroke(#FF0000);
strokeWeight(3);
tester = new Foo(this);
tester.drawBox();
}
/tmp/Sketch/Foo.java
import java.io.Serializable;
//import peasy.org.apache.commons.math.geometry.Rotation;
//import peasy.org.apache.commons.math.geometry.Vector3D;
import processing.core.PApplet;
import processing.core.PGraphics;
public class Foo implements Serializable {
static final int GAP = 15;
static final int MODE = PApplet.CORNER;
final PApplet p;
Foo(PApplet pa) {
p = pa;
}
void drawBox() {
p.rect(GAP, GAP, p.width - GAP*2, p.height - GAP*2);
}
}
The example runs fine as is - but if I uncomment the import peasy.org... lines, then compilation fails with:
The package "peasy" does not exist. You might be missing a library.
Libraries must be installed in a folder named 'libraries' inside the 'sketchbook' folder.
Of course, I do have PeasyCam installed, under /path/to/processing-2.1.1/modes/java/libraries/peasycam/ - and it works fine, if I do a import peasy.*; from a .pde sketch.
I guess, this has something to do with paths - apparently pure Java files in a sketch, do not refer to the same library paths as .pde files in a sketch.
Is it possible to get this sketch to compile with the import peasy.org... lines (other than, I guess, copying/symlinking the peasycam library in the sketch folder, here /tmp/Sketch/ <--- EDIT: just tried symlinking as described, it doesn't work; the same error is reported)?
This is where you learn that Processing isn't actually Java, it just has a similar(ish) syntax and can run its code in the JVM by aggregating all .pde files into a single class that can be compiled for running on the JVM. Processing has its own rules for dealing with imports and the like.
Why not just do this entirely in Processing instead?
class Foo {
static int MODE = ...;
static int GAP = ...;
PApplet sketch;
public Foo(PApplet _sketch) {
sketch = _sketch;
...
}
void drawBox() {
sketch.rect(GAP, GAP, p.width - GAP*2, p.height - GAP*2);
}
...
}
and then make sure to have that in a file Foo.pde or something in the same dir as your sketch, with your sketch loading in the peasy library through the regular Processing import mechanism?
Ok, thanks to #MikePomaxKamermans answer, especially "by aggregating all .pde files into a single class", I simply tried importing peasy in the .pde file before the first reference to foo; that is, in /tmp/Sketch/Sketch.pde I now have:
// forum.processing.org/two/discussion/3677/
// usage-class-from-java-file-is-there-a-full-doc-for-that
import peasy.*; // add this
Foo tester;
...
... and then the sketch compiles without a problem (but note: while this approach works for this example, it somehow didn't work in the original problem that drove me to post the question).
I am new to reflection and to practice, I downloaded a random Java project from a website. I decided to find out which class has the main method so I wrote the following code:
package reflection;
import java.io.IOException;
import java.lang.reflect.*;
import java.nio.file.*;
public class FindMethods {
public static void main(String[] args) throws IOException{
if(args.length==0){
System.out.println("Exiting");
System.exit(1);
}else{
Path p = Paths.get(args[0]);
DirectoryStream<Path> allClassFiles = Files.newDirectoryStream(p, "*.class");
for(Path each : allClassFiles){
// System.out.println(each.getFileName());
try {
findMethods(each.getFileName().toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
public static void findMethods(String file) throws ClassNotFoundException{
System.out.println(file);
Class c = Class.forName(file);
Method[] m = c.getDeclaredMethods();
for(Method each : m){
System.out.println(each.toString());
}
}
}
System.out.println(each.getFileName()); properly returns the .class files in the folder however, it is interspersed with stack trace of ClassNotFoundException
The classes are as follows:
Addwindow$1.class
Addwindow$2.class
Addwindow.class
Authorwindow.class
clsConnection.class
clsSettings$1.class
clsSettings.class
Deletewindow$1.class
Deletewindow$2.class
Deletewindow.class
Editwindow$1.class
Editwindow$2.class
Editwindow.class
Emprptwindow$PrintCommand.class
Emprptwindow.class
Helpwindow.class
LoginFrame$1.class
LoginFrame.class
MainMenu$1.class
MainMenu$2.class
MainMenu.class
Payrptwindow.class
printwindow$1.class
printwindow.class
Settingswindow$1.class
Settingswindow.class
What changes do I need to make to the code to get the methods from each class ?
Stack trace:
java.lang.ClassNotFoundException: Settingswindow
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at reflection.FindMethods.findMethods(FindMethods.java:33)
at reflection.FindMethods.main(FindMethods.java:22)
Random project being talked about:
http://projectseminar.org/java-projects/payroll-accounting-system/98/
.class is part of the filename, but it isn't part of the class name. You need to strip it before passing it to Class.forName.
Another issue is that forName expects packages to be separated using periods, rather than than slashes or whatever directory separator your filesystem uses. If everything is in the default package, this shouldn't be an issue though.
If it's still not working, you should double check the classpath.
Class names that contain a $ are anonymous classes within the outer class (determined by the name to the left of the $). You can safely ignore those in your search for main. Just test for the presence of a $ in the class names in your main loop and skip the processing.
Without knowing more about what app you are looking at, I can't say why your code can't find some of the other classes (like clsConnection).
There is a problem in this approach - you load all project's classes. It is better to analize classes without loading them. There are tools for that. Here's what we can do with http://www.jboss.org/javassist
public static void findMethods(String file) throws Exception {
ClassPool cp = ClassPool.getDefault();
try (InputStream is = new FileInputStream(file)) {
CtClass cc = cp.makeClass(is);
for (CtMethod m : cc.getMethods()) {
System.out.println(m);
}
}
}