So, I don't know why the Client part of my project give me this type of error
Exception in thread "main" java.lang.ClassNotFoundException: Mining.FrequentPatternMiner
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 java.io.ObjectInputStream.resolveClass(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at JabberClient.main(JabberClient.java:81)
In the Server part, I cast the FrequentPatternMiner variable and then i give it to the ObjectOutputStream
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
FrequentPatternMiner fpMiner=new FrequentPatternMiner(dataTarget, minsup);
fpMiner.salva("FP_"+nameFile+"_minSup"+minsup+".dat");
System.out.println("Frequent Patterns \n"+fpMiner);
out.flush();
out.writeObject((Object)fpMiner);
In the Client part, i do this
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
Object fpMiner=in.readObject();
(((ObjectInput)in).readObject());
System.out.println(fpMiner);
How would I fix my code? Can you help me?
The code is correct, but your premise isn't. You've said, that the class "FrequentPatternMiner must be unknown for the client". With that premise you can't serialize the class as you did, because serialization only transfers the data of the object and not it's implementation.
You might want to look into DataTransferObjects (which has to be known on both client and server) or use a simple array to transfer the object.
Example using a simple array as "DTO"
Server:
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
// The following line assumes that dataTarget and minsup are types
// that are serializable and known to the client
Object[] objArray = new Object[] { dataTarget, minsup };
out.flush();
out.writeObject(objArray);
Client:
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
Object[] objArray = (Object[])in.readObject();
System.out.println(objArray);
// FrequentPatternMiner must still known to the client, if you need more than
// the constructor arguments (like methods of the FrequentPatternMiner) Object.
FrequentPatternMiner fpMiner=new FrequentPatternMiner(objArray[0], objArray[1]);
Further Idea
If you don't want that FrequentPatternMiner implementation/class is known to the client, you can try "Remoting" or "Remote Procedure Calls" (RPC). This is an advanced subject and there are a lot of libraries out there (and platforms) that provide this functionallity. They do basically this:
You need an Interface for the Class on the client (like interface IPatternMiner { void doMine() }
You connect server and client (depends on the library on how to do this) and obtain an instance of IPatternMiner
You call a method on the interface and the implementation gets executed on the server (with the parameters pased in from the client). Note that file operations write on the file system on the server
The problem you have is that FrequentPatternMiner is not on your classpath.
What you can do is ctrl+t on Eclipse and look for FrequentPatternMiner to know what is the jar containing this class. Then ensure that your project is referencing this class.
If you are using maven you can use mvm dependency:tree goal to know if your project contain this jar.
Casting to Object doesn't have any magical properties. Everything can be cast to Object. It doesn't change the fact that what is written to the object stream is a FrequentPatternMiner, and if that class isn't available at the receiver, this exception will result.
Solution: deploy the class.
Similarly, casting an ObjectInputStream to ObjectInput accomplishes precisely nothing.
You need to tyecast.
System.out.println((FrequentPatternMiner )fpMiner);
Else how would the client know class of the Object that is being deserialized. Note it is not necessary to typecast just for using it in sysout. It will print using Objects toString() method.
Though your Exception says
Exception in thread "main" java.lang.ClassNotFoundException
You need to add this class on the client side too. Lastly check that serialVersionUID is same for the class in server and client.
Related
I would like to get the state machine from .uml file created by papyrus. I am parsing the model.uml file using the code below.
ResourceSet set = new ResourceSetImpl();
set.getResourceFactoryRegistry().getExtensionToFactoryMap()
.put(UMLResource.FILE_EXTENSION, UMLResource.Factory.INSTANCE);
set.getResourceFactoryRegistry().getExtensionToFactoryMap()
.put(UMLResource.FILE_EXTENSION, UMLResource.Factory.INSTANCE);
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap()
.put(UMLResource.FILE_EXTENSION, UMLResource.Factory.INSTANCE);
Resource res = set.getResource(URI.createFileURI("resources/model.uml"), true);
EcoreUtil.resolveAll(res);
System.out.println(res.getContents().get(0));
This code works fine and prints the content. But when I try to cast it to Model class using the code below
Model model = (Model) EcoreUtil.getObjectByType(res.getContents(),UMLPackage.Literals.MODEL);
It throws this exception,
Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/uml2/types/TypesPackage
at org.eclipse.uml2.uml.internal.impl.UMLPackageImpl.init(UMLPackageImpl.java:1907)
at org.eclipse.uml2.uml.UMLPackage.<clinit>(UMLPackage.java:83)
at org.eclipse.uml2.uml.UMLPackage$Literals.<clinit>(UMLPackage.java:28779)
at mp.m2bt.BTGenerator.main(BTGenerator.java:49)
Caused by: java.lang.ClassNotFoundException: org.eclipse.uml2.types.TypesPackage
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)
I am not sure if I am missing anything. I think the problem is in UMLPackage.Literals.MODEL. So, Can anybody help me to fix this issue and get the state machines from the model.
You need the jar org.eclipse.uml2.types in your classpath. This is why the type org.eclipse.uml2.types.TypesPackage cannot be found.
I was experimenting on command pattern and one use of it in wikipedia goes like this:
Networking
It is possible to send whole command objects across the network to be executed on the other machines, for example player actions in computer games.
I assume here sending objects means sending data within the fields of the object, right? And not the code within the execute() method?
I was experimenting through serialization & found a behaviour I couldn't explain. Here's the program:
public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("Commands"))) {
Command command = () -> {
System.out.println("MUHAHA!");
};
outputStream.writeObject(command);
}
try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("Commands"))) {
Command command = (Command) inputStream.readObject();
command.execute();
}
}
}
interface Command extends Serializable {
void execute();
}
Upon execution, I get the string MUHAHA!. So, the implementation of the execute() method is being saved in the file. However, if I comment out the first try{} block & then execute, it fails. The Commands file remains from the previous execution, but it fails to read & parse.
I get the following stack trace:
Exception in thread "main" java.io.IOException: unexpected exception type
at java.io.ObjectStreamClass.throwMiscException(Unknown Source)
at java.io.ObjectStreamClass.invokeReadResolve(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at random.Test.main(Test.java:18)
Caused by: java.lang.NoSuchMethodException: random.Test.$deserializeLambda$(java.lang.invoke.SerializedLambda)
at java.lang.Class.getDeclaredMethod(Unknown Source)
at java.lang.invoke.SerializedLambda$1.run(Unknown Source)
at java.lang.invoke.SerializedLambda$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.lang.invoke.SerializedLambda.readResolve(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
... 5 more
The NoSuchMethodException makes some sense to me, but why didn't it come the first time? Is it storing the first class created through lambda in some cache (or the Metaspace)?
In the end, is it possible to send an implementation across? I was hoping in the other end the code of the execute method will be written into some dynamically created Command implementation.
It is not storing the implementation in the file. To show that, separate your code into two classes: one that serializes and one that deserializes, and execute them in different environments where neither has the .class files of the other.
I'm trying to make an online drawing game. For that I'm using the Path class in Android and I need to send it to my Java server. To do that, I had tried to extend the Path class, as follows:
public class SerializedPath extends Path implements Serializable {
private static final long serialVersionUID = -5974912367682897467L;
}
To simplify things and to narrow down the problem, all I did was to send it with outputStream.writeObject(new SerializedPath) and then outputStream.flush() where outputStream is an instance of ObjectOutputStream. Over the server I simply read it using inputStream.readObject() where inputStream is an instance of ObjectInputStream. The exception I'm getting is:
java.io.InvalidClassException: com.droplay.drawingonline.path.SerializedPath; unable to create instance
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at com.droplay.drawingonline.Session.run(Session.java:71)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.GeneratedSerializationConstructorAccessor1.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.io.ObjectStreamClass.newInstance(Unknown Source)
... 5 more
Caused by: java.lang.RuntimeException: Stub!
at android.graphics.Path.(Path.java:24)
... 8 more
Now, to isolate the problem, I had tried creating a new class that doesn't have any members and doesn't extend anything and it did work. The server didn't throw any exception and it worked like a charm. I made sure the packages names are the same, the names of the classes are the same, the server uses the same SDK files as my Android project and the files' code in both the Android app and the Java server are EXACTLY the same, but I keep getting this exception. The app doesn't throw any exception. It sends the object just fine. Please, what's wrong with my code? Thank you for helping! :)
Well I managed to solve it by sending the position of each click to the server, instead of a path class. But why didn't it work when I serialized it?
I followed the example given in this post: How to send data from Matlab to Rails, but am receiving an error message that I cannot find any information on. My script looks like this:
javaaddpath('./httpcomponents/httpclient-4.2.2.jar')
javaaddpath('./httpcomponents/httpcore-4.2.2.jar')
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
httpclient = DefaultHttpClient();
httppost = HttpPost('http://localhost:3000/signin');
httppost.addHeader('Content-Type','application/json');
httppost.addHeader('Accept','application/json');
tokenRequest = StringEntity('{"session", "{email_address:""email#aol.com,""password:""password""}"}');
httppost.setEntity(tokenRequest);
response = httpclient.execute(httppost);
On the last line, I get the error:
Java exception occurred: java.lang.VerifyError: Cannot inherit from final class
From searches online, I gather that this is a software version issue. I tried using the 4.2 builds of those files (the same ones used in the other post), but I received the same error. Does anyone have an idea what could be wrong? Or know a way to do what I am trying to do without using these external libraries?
EDIT:
originally I tried using this code:
tokenRequest = {'session', '{''email_address'':''email#aol.com'',''password'':''password''}'};
token = urlread('http://localhost:3000/signin','POST',tokenRequest);
but I received the NoMethodError that led me to that other post:
NoMethodError (undefined method `each' for "{'email_address':'email#aol.com','password':'password'}":String):
app/models/session.rb:14:in `initialize'
I think the reason it throws this error is because the server thinks it is receiving a String object, which doesn't have an each method. I assume I would fix this by using the 'Content-Type' argument to specify that its json. Is there a way to do this using urlread?
EDIT: full stack trace for java libs issue
Java exception occurred:
java.lang.VerifyError: Cannot inherit from final class
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(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 com.mathworks.jmi.CustomURLClassLoader.findClass(ClassLoaderManager.java:760)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
at org.apache.http.impl.client.DefaultHttpClient.createHttpParams(DefaultHttpClient.java:157)
at org.apache.http.impl.client.AbstractHttpClient.getParams(AbstractHttpClient.java:448)
at org.apache.http.impl.client.AbstractHttpClient.createClientConnectionManager(AbstractHttpClient.java:309)
at org.apache.http.impl.client.AbstractHttpClient.getConnectionManager(AbstractHttpClient.java:466)
at org.apache.http.impl.client.AbstractHttpClient.createHttpContext(AbstractHttpClient.java:286)
at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:851)
at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
Looks like the data being sent is not properly quoted. End result should be
{'email_address':'email#aol.com','password':'password'}
Try changing the code to
tokenRequest = StringEntity('{"session", {"email_address":"email#aol.com","password":"password"}}');
urlread2 turned out to be a much better solution. This code does the job:
tokenRequest = '{ "session" : { "email_address": "email#aol.com", "password": "password" } }';
header = http_createHeader('Content-Type','application/json');
token = urlread2('http://localhost:3000/signin.json','POST',tokenRequest,header);
I am sending an object encased in a Message object encase in a SignedObject over a TCP connection using an ObjectInputStream. Here's the basic code:
Send
Object data = someObject;
ObjectOutputStream = new ObjectOutputStream(socket.getOutputStream());
Message newMsg = new Message(data);
out.writeObject(security.signObject(newMsg,privKey));
Receive
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
Object line = in.readObject();
SignedObject messageIn = (SignedObject) line;
Message msg = (Message) messageIn.getObject();
The Message class is a basic class with only fields and no methods. One of the fields is Object Message.data, which in this case contains either siena.Filter or siena.Notification. When I call SignedObject.getObject(), I get an InvalidObjectException. The stack trace is below.
java.io.InvalidObjectException: siena.SENPInvalidFormat
at siena.Filter.readObject(Filter.java:127)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at java.security.SignedObject.getObject(Unknown Source)
The code for the message transfer is correct. It works for numerous other cases with other classes, and even with other versions of the same class. It is not working for a specific version of siena.Filter and siena.Notification.
I can see that the readObject() method of the class being sent (siena.Filter or siena.Notification) is being called, but I don't know if this is supposed to be happening or not. I know that an exception is being thrown within the siena method, which I'm guessing is causing the InvalidObjectException.
So the question is, is the problem that siena.class.readObject() is throwing an exception and is not written properly, or is the problem that siena.class.readObject() is being called at all? If the latter, how would I go about fixing that?
Thanks,
David
Why do you just type cast what you are getting from your InputObjectStream to the type of object that you are passing ? Once you get readObject, just typecast it to your SingledObject, should work ? Sorry again I am unable to completely understand. Its better you put in some code here.