How can I use Akka Actors in a Java application? - java

I would like to use Akka actors in Java.
I downloaded the akka-1.0.zip and added akka-actor-1.0.jar to my "Build Path" in Eclipse.
Then I wrote this Actor class:
package com.example;
import akka.actor.UntypedActor;
public class MyActor extends UntypedActor {
public void onReceive(Object message) throws IllegalArgumentException {
if (message instanceof String) {
System.out.println("Received: " + message);
} else throw new IllegalArgumentException("Unknown message: " + message);
}
}
But I get errors in Eclipse:
The type scala.Option cannot be resolved.
The type scala.Some cannot be resolved.
The type scala.PartialFunction cannot be resolved.
The type scala.ScalaObject cannot be resoled.
Do I need to add any more files to my "Build Path" or what am I doing wrong? I don't find the documentation beeing that helpful.
Update: I added scala-library.jar to my Build Path and the above erros disappeared. But I get an error when I compile and run the application:
Exception in thread "main" java.lang.NoClassDefFoundError: net/lag/configgy/ConfigMap
at akka.actor.Actors.actorOf(Actors.java:70)
at com.example.ActorTest.main(ActorTest.java:9)
Caused by: java.lang.ClassNotFoundException: net.lag.configgy.ConfigMap
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)
... 2 more
Here is the main class where I use my actor:
package com.example;
import akka.actor.ActorRef;
import akka.actor.Actors;
public class ActorTest {
public static void main(String[] args) {
ActorRef myActor = Actors.actorOf(MyActor.class);
myActor.start();
System.out.println("My Actor started");
}
}

In your akka-1.0.zip file there is scala-library.jar. Try adding it to the build path.
Also, there is a lib_managed directory inside the zip, which contains further library files. Possibly aslo some of them will be needed.
To avoid this kind of situations you should try maven. There is a Akka repository: http://scalablesolutions.se/akka/repository/se/scalablesolutions/akka/

You can find a complete, working example here; it's a Maven project, so it will get the dependencies for you automatically.

I see this problem using Akka in a Java project in Eclipse with the Scala IDE installed. The problem goes away when using an Eclipse instance without the Scala IDE installed. Eclipse is perhaps confused by two Scala libraries around?

I don't know Akka actors but it seems you need some scala support (libs on the build path) as well.

Related

java.lang.NoClassDefFoundError when trying to load class from JAR

I am working on a project that is supposed to parse texts from PDF files.
Having multiple dependencies I have decided to build a combined JAR with all the dependencies and the classes.
However, when I build JAR including dependencies via Intellij IDEA even though the JAR file is added properly and I can import the class the program throws NoClassDefFoundError (Please refer to the screenshot).
Firstly, I thought the jar wasn't in the classpath. However, even if I add -cp TessaractPDF.jar through VM Options the class still get undetected.
I think it is worth to mention that, everything works smoothly if I build JAR without dependencies and add the dependencies manually.
What should I do?
Exception in thread "main" java.lang.NoClassDefFoundError: me/afifaniks/parsers/TessPDFParser
at Test.main(Test.java:20)
Caused by: java.lang.ClassNotFoundException: me.afifaniks.parsers.TessPDFParser
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
... 1 more
Code Snippet:
import me.afifaniks.parsers.TessPDFParser;
import java.io.IOException;
import java.util.HashMap;
public class Test {
public static void main(String[] args) throws IOException {
System.out.println(System.getProperty("java.classpath"));
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("imageMode", "binary");
arguments.put("toFile", false);
arguments.put("tessDataPath", "/home/afif/Desktop/PDFParser/tessdata");
TessPDFParser pdfParser = new TessPDFParser("hiers15.pdf", arguments);
String text = (String) pdfParser.convert();
System.out.println(text);
}
}

java.lang.NoClassDefFoundError when Translating

I am using the Apertium Translator and using the sample code they provide. My code is like this.
import com.robtheis.aptr.language.Language;
import com.robtheis.aptr.translate.Translate;
public class Test {
public static void main(String[] args) throws Exception {
// Set the Apertium API Key - Get yours at http://api.apertium.org/register.jsp
Translate.setKey("BNSCFhEL8DoTApc2I1+aa3UYkVg");
String translatedText = Translate.execute("Hola, mundo!", Language.SPANISH, Language.ENGLISH);
System.out.println(translatedText);
}
}
I have no errors or warnings and when I run the program I get the following errors.
Exception in thread "main" java.lang.NoClassDefFoundError: org/json/simple/JSONValue
at com.robtheis.aptr.ApertiumTranslatorAPI.jsonSubObjToString(ApertiumTranslatorAPI.java:195)
at com.robtheis.aptr.ApertiumTranslatorAPI.retrieveSubObjString(ApertiumTranslatorAPI.java:140)
at com.robtheis.aptr.translate.Translate.execute(Translate.java:56)
at maple.Test.main(Test.java:11)
Caused by: java.lang.ClassNotFoundException: org.json.simple.JSONValue
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)
... 4 more
The .jar I'm using is the second one from https://github.com/rmtheis/apertium-translator-java-api/downloads
You have to download the first one. The first jar file (apertium-translator-java-api-0.2-jar-with-dependencies.jar) contains the all dependencies needed..
Or you add a json library to your project path..
Well JVM is not able to find some class at Runtime which was available at compile time. That is the reason of NoClassDefFoundError
Below you also have ClassNotFoundException for this class org.json.simple.JSONValue
which means you are trying to load the particular class at run-time by name.
Both of them related to Java Class Path.
I don't know alot about jSON stuff. But you are missing this file org.json.simple.JSONValue you can take it from here http://code.google.com/p/json-simple/
add the above jar file in your class path . And the code will definitely run. Guaranteed.!!!
Thanks

java.lang.NoClassDefFoundError in Hadoop Basics' MapReduce Program

I'm trying Hadoop's Basic MapReduce Program whose tutorial is on http://java.dzone.com/articles/hadoop-basics-creating
The Full code of the class is(the code is present on net on above url)
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
public class Dictionary {
public static class WordMapper extends Mapper<Text, Text, Text, Text> {
private Text word = new Text();
public void map(Text key, Text value, Context context) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString(), ",");
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(key, word);
}
}
}
public static class AllTranslationsReducer extends Reducer<Text, Text, Text, Text> {
private Text result = new Text();
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
String translations = "";
for (Text val : values) {
translations += "|" + val.toString();
}
result.set(translations);
context.write(key, result);
}
}
public static void main(String[] args) throws Exception {
System.out.println("welcome to Java 1");
Configuration conf = new Configuration();
System.out.println("welcome to Java 2");
Job job = new Job(conf, "dictionary");
job.setJarByClass(Dictionary.class);
job.setMapperClass(WordMapper.class);
job.setReducerClass(AllTranslationsReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.setInputFormatClass(KeyValueTextInputFormat.class);
FileInputFormat.addInputPath(job, new Path("/tmp/hadoop-cscarioni/dfs/name/file"));
FileOutputFormat.setOutputPath(job, new Path("output"));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
But after running in eclipse; I'm getting the error,
welcome to Java 1
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.apache.hadoop.conf.Configuration.<clinit>(Configuration.java:73)
at Dictionary.main(Dictionary.java:43)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
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)
... 2 more
Please note that the exception is NoClassDefFoundError instead of ClassNotFoundException.
Note : NoClassDefFoundError is thrown when a class is not visible at run time but was visible at compile time. This may be something that can happen in the distribution or production of JAR files, where not all the required class files were included.
To fix : Please check for differences in your build time and runtime classpaths.
NoClassDefFoundError and ClassNotFoundException are different.
one is an Error and the other is an Exception.
NoClassDefFoundError: arises from the JVM having problems finding a class it expected to find. A program that was working at compile-time can't run because of class files not being found.
ClassNotFoundException: This exception indicates that the class was not found on the classpath i.e we are trying to load the class definition and class/jar containing the class does not exist in the classpath.
NoClassDefFoundError comes when a class is not visible at run time but was at compile time. Which may be related to JAR files, because all the required class files were not included.
So try adding in your class path commons-logging-1.1.1 jar which you can get from http://commons.apache.org/logging/download_logging.cgi
NoClassDefFoundError occurs when the named class is successfully located in the classpath, but for some reason cannot be loaded and verified. Most often the problem is that another class needed for the verification of the named class is either missing or is the wrong version.
Generally speaking, this error means "double-check that you have all the right JAR files (of the right version) in your classpath".
It's a very common error when you run a Hadoop Map/Reduce program in local IDE (Eclipse).
You should already added hadoop-core.jar in your build path, so no compile error detected in your program. But you get the error when you run it, because hadoop-core is dependent on commons-logging.jar (as well as some other jars). You may need to add the jars under /lib to your build path.
I recommend you to use Maven or other dependency management tool to manage the dependency.
Please read an article: http://kishorer.in/2014/10/22/running-a-wordcount-mapreduce-example-in-hadoop-2-4-1-single-node-cluster-in-ubuntu-14-04-64-bit/. It explains how to reference dependencies in Eclipse without Marven. However, Marven is preferred way, from what I understood.

NoClassDefFoundError running java from the console

When I tried to run Java on Linux on the terminal this is what happens:
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorldApp/class
Caused by: java.lang.ClassNotFoundException: HelloWorldApp.class
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)
Can anyone help me with this?
EDIT: I was in the folder of the bytecode file and ran this on the terminal:
bash-4.1$ java class HelloWorldApp
Source file:
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
You are executing
java HelloWorldApp.class
but it must be
java HelloWorldApp
You may not append class to your call but name plain the classname.
Also, as others has remarked, it is better to use packages as classes in the default package do not work fine.
You also should note that if you have the package declaration in the code it will screw it up even if you try all the fancy fixes like setting CLASSPATH. For example if you have:
package blah;
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello world");
}
}
The line: package blah;
will cause java HelloWorld to fail after compiling. So remove this line and you should be able to run the src via cmd line.

Strange class files appearing in my bin folder

I am using Eclipse + Window Builder + few third party libraries to build a gui application,
Entry point for my application resides in MainWindow.java file, which also contains the gui of the application, other than that I have few helper classes.
My application works fine, but when I checked into bin folder I find four more class files there namely:
1. MainWindow$1.class
2. MainWindow$2.class
3. MainWindow$3.class
4. MainWindow$4.class.
Now I don't understand why these files are here, When I deleted these files, Eclipse throws an exception
Exception in thread "main" java.lang.NoClassDefFoundError: gui/MainWindow$1
at gui.MainWindow.main(MainWindow.java:71)
Caused by: java.lang.ClassNotFoundException: gui.MainWindow$1
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)
the code that throws the exception is:
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frmMailExtractor.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
I am not able to find out why these files are there and who put them? any ideas?
OK so these are the anonymous classes, but why the Exception then?...and why can't I see them in my eclipse..becasue when I export it as a runnable jar, the jar throws the same exception
These are class files generated for anonymous inner classes inside MainWindow. It probably contains a bunch of event listeners implemented as such.
Anonymous inner classes get compiled into separate class files with the name <OuterClass>$<nnn>.class, where <nnn> is a compiler-generated number.
Those are what anonymous classes get compiled into. The number in the filename is the ordinal of the related anonymous class in the respective Java compilation unit.

Categories