Open/Save SWT Text Object with ObjectOutput/InputStream - java

I'm trying to open/save a Text Object from SWT with the ObjectOutputStream. But it doesn't work. Have anybody an idea, why?
public static void read(String fileName, Text textField) {
int c=0;
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
c= in.readInt();
textField = (Text) in.readObject();
in.close();
}
catch(IOException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void write(String fileName, Text textField) {
int c = 1;
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fileName));
out.writeInt(c);
out.writeObject((Text)textField);
out.close();
}
catch(IOException e){
e.printStackTrace();
}
}
The Error which appears on the console when i save:
java.io.NotSerializableException: org.eclipse.swt.widgets.Text
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at FileIO.write(FileIO.java:42)
at SelectionAdapterSave.widgetSelected(SelectionAdapterSave.java:29)
at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:248)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1057)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4170)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3759)
at Editor.open(Editor.java:230)
at EditorMain.main(EditorMain.java:6)
and this when i try to open the file, what i saved before:
Caused by: java.io.NotSerializableException: org.eclipse.swt.widgets.Text
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at FileIO.write(FileIO.java:42)
at SelectionAdapterSave.widgetSelected(SelectionAdapterSave.java:29)
... 7 more

You can only use ObjectOutputStream on objects which implement Serializable. The SWT Text class does not implement this.
A SWT Text class contains all sorts of objects which depend on the native UI code, there is no way this can be saved and loaded again.

Related

Text to Speech in Java using Google

I have used the following code to convert text to speech, but I am getting the following errors:
errors
Caused by: java.io.IOException: Server returned HTTP response code: 503 for URL: http://ipv4.google.com/sorry/IndexRedirect?continue=http://translate.google.com/translate_tts%3Fie%3DUTF-8%26q%3DHello%2BWorld%26tl%3Dde%26prev%3Dinput&q=CGMSBCmIeyUYvpnkrwUiGQDxp4NLHAGq2VYVjoplnZ0vwMrZvShTrYA
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at us.monoid.web.AbstractResource.fill(AbstractResource.java:30)
... 5 more
Java Codes
public class TextToSpeech {
private static final String BASE_URL = "http://translate.google.com/translate_tts?ie=UTF-8&q={0}&tl={1}&prev=input";
public static void main(String[] args) {
say("Hello World");
}
public static void say(String text) {
try {
File f = new File("translate.mp3");
String sentence = URLEncoder.encode(text, "UTF-8");
String urlString = MessageFormat.format(BASE_URL, sentence, "de");
BinaryResource res = new Resty().bytes(new URI(urlString));
res.save(f);
FileInputStream in = new FileInputStream(f);
Player p = new Player(in);
p.play();
p.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (JavaLayerException e) {
e.printStackTrace();
}
Note that I have already included the jar files JLayer & Resty.. Please help ! Thanks

Java SerialIzation: 'ClassNotFoundException' when deserializing an Object

The error:
java.lang.ClassNotFoundException: testprocedure.tp$3
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.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 core.ProcedureSetup.load(ProcedureSetup.java:57)
at core.Engine.main(Engine.java:25)
I instantiate the object and call the "ProcedureSetup"'s "save" method from Class "tp".
ProcedureSetup ps=new ProcedureSetup(new Procedure(){ public void doStuff(){ System.out.println("Stuff is being done"); }});
ps.save();
however I load from a different collection of programs that has -ALL- required code but "tp"
ProcedureSetup ps=new ProcedureSetup();
ps.load();
Object saving and loading within class:
public void load(){
String path=Operator.persistentGetFile();//gets the file path
ObjectInputStream ois=null;
FileInputStream fin=null;
ProcedureSetup temp=null;
try {
fin = new FileInputStream(path);
ois = new ObjectInputStream(fin);
temp=(ProcedureSetup) ois.readObject();
ois.close();
fin.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if(ois!=null){
try {
ois.close();
} catch (IOException e) {}
}
if(fin!=null){
try {
fin.close();
} catch (IOException e) {}
}
if(temp!=null){
a=temp.a;
}else{
load();//If a load is failed, restart process.
}
}
public void save(){
String path=Operator.persistentGetDirectory();//get directory to save to
String input = JOptionPane.showInputDialog(this, "Enter the File name:");
ObjectOutputStream oos=null;
FileOutputStream fon=null;
try {
fon = new FileOutputStream(path+input+".obj");
oos = new ObjectOutputStream(fon);
try {
oos.writeObject(this);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
oos.close();
fon.close();
} catch (IOException e) {
e.printStackTrace();
}
if(oos!=null){
try {
oos.close();
} catch (IOException e) {}
}
if(fon!=null){
try {
fon.close();
} catch (IOException e) {}
}
}
My questions are:
Why are these errors happening?
Why (if necessary) do I need to have "tp" in my classpath?
If there is in fact a way to save the object in its current state with out the necessity of "tp" in the classpath how would I go about doing that? (Links would be lovely)
When you read in a serialized object, Java "reconstitutes" it by using the information in the serialized stream to build a live copy of the object. It can't do this unless it has the .class file for the object's class; it needs a blank copy to "fill out" with the information from the stream.
The best option is usually to make sure that the class is on the class path. If you have some particular reason why this won't work, Java serialization isn't for you; JSON may be a suitable option instead.
new Procedure(){ public void doStuff(){ System.out.println("Stuff is being done"); }}
The above is an anonymous inner class of your tp class. So, to be deserialized, this anonymous inner class, and its enclosing class tp, must be present in the classpath: the stream of bytes contains the name of the class and the fields of the object, but it doesn't contain the byte-code of the class itself.
You should make it a top-level class, or at least a static inner class.
You should also respect the Java naming conventions: classes are CamelCased.
Why are these errors happening?
There is only one error here: java.lang.ClassNotFoundException: testprocedure.tp$3. It means you haven't deployed testprocedure/tp$3.class to the peer.
Why (if necessary) do I need to have "tp" in my classpath?
So that deserialization can succeed. You can't do anything with a class you don't have the .class file for, let alone deserialize instances of it.

Socket programming, multithreaded game, getting an End Of File Exception

I'm trying to implement a little game, where multiple clients have to connect to a server, and play together. Every one has a different GUI and they communicate through the class ClientConnect, which is a Runnable started from the GUI class. The problem is that i'm getting an EOFException at the first lines of code, when i'm trying to intanciate the inputstream. The server is of course started at the beginning and sending an object.
Here is a cut of the implementation where i get the exception.
What should i do?
public ClientConnect(InetAddress address, int port) throws IOException {
clientSock = new Socket(address, port);
}
#Override
public void run() {
ArrayList<Object> receivedObject = null;
try (ObjectInputStream fromServer = new ObjectInputStream(clientSock.getInputStream());
ObjectOutputStream toServer = new ObjectOutputStream(clientSock.getOutputStream()))
{
while(!move) {
receivedObject = (ArrayList<Object>) fromServer.readObject();
move = !(receivedObject.get(0).equals("you have to wait!!"));
}
actualPlayer = (String) receivedObject.get(0);
scoreCard = (List<String>) receivedObject.get(1);
highScore = (HashMap<String, Integer>) receivedObject.get(2);
numberOfPlayers = (int) receivedObject.get(3);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here is the exception:
CShellExt::CShelljava.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at edu.hm.se2.kniffel.ClientConnect.run(ClientConnect.java:41)
at java.lang.Thread.run(Unknown Source)
Ext()
The line 41 is the line with the try
I'm starting the ClientConnect thread in the GUI like that:
public void actionPerformed(ActionEvent arg0) {
//Online-Spiel starten
if(game.listLength()>0){
try {
client = new ClientConnect(InetAddress.getByName(null), 2000);
new Thread(client).start();
while (!client.getMove()) {
lblActualUser.setText("WAITING.... " + client.getActualPlayer() + " ist an der Reihe");
}
Got it!
I Got something blocking the serversocket to be opened!
On this evidence, the peer isn't creating an ObjectOutputStream at all, it's just connecting and then closing the socket.
You should construct the ObjectOutputStream before the ObjectInputStream, at both ends.

Connection reset, java

I am getting a lot of connection reset errors, trough debugging i found out that the code is found within these lines:
//set up output stream for objects
output = new ObjectOutputStream(socket.getOutputStream());
output.flush(); //flush the output buffer to send header information
// Read a message sent by client application
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
The error occurs at this line:
String message = (String) ois.readObject();
The error message:
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at java.io.ObjectInputStream$PeekInputStream.peek(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.peek(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at org.bitbucket.c4d3r.ConnectionListener.listen(ConnectionListener.java:47)
at org.bitbucket.c4d3r.ConnectionListener.<init>(ConnectionListener.java:27)
at org.bitbucket.c4d3r.ConnectionHandler.connectionServer(ConnectionHandler.java:46)
at org.bitbucket.c4d3r.ConnectionHandler.run(ConnectionHandler.java:24)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I know that the connection reset is caused by a socket that's closed unexpectedly, however i am quite new to sockets and i am unable to find what i am doing wrong. Therefore i was hoping that someone could help me out with this. For a better vision of everything i have copied a bigger block of code beneath
private DomainController dc;
private Socket socket;
private boolean changed;
private ObjectOutputStream output;
private ObjectInputStream ois;
private Map json;
public ConnectionListener(DomainController dc, Socket socket) {
this.dc = dc;
this.socket = socket;
listen();
}
#Override
public void run() {
listen();
return;
}
#SuppressWarnings("finally")
public void listen() {
try
{
//set up output stream for objects
output = new ObjectOutputStream(socket.getOutputStream());
output.flush(); //flush the output buffer to send header information
// Read a message sent by client application
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
boolean inProgress;
//CHECK IF THERE ARE GIVEN COMMANDS
if(message.substring(0, 8).equalsIgnoreCase("COMMAND="))
{
switch(message.substring(8))
{
case "askMinigames":
//System.out.println("Sending minigames list");
output.writeObject(new String(dc.getProp().getProperty("minigames")));
output.flush(); //flush output to client
break;
}
}
} catch (SocketException ex) {
System.out.printf("Connection reset\n");
ex.printStackTrace();
} catch (IOException e) {
System.out.println("Input exception");
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try
{
if(ois != null) {
ois.close();
}
if(output != null) {
output.close();
}
if(socket != null) {
socket.close();
}
}
catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
}
You need to use the same object input and output streams for the life of the socket, at both ends. As you are just sending strings, I don't really see why you're using object streams at all: you could use e.g. DataOutputStream.writeUTF() and DataInputStream.readUTF().

Parsing Ofx file with java

I am currently trying to read an ofx file with java.
But I get the following error: Unhandled exception type FileNotFoundException (for the 2nd line). I am using OFx4j. Could you please give me some tips on that one?
Here is the code I have written so far:
String filename=new String("C:\\file.ofx");
FileInputStream file = new FileInputStream(filename);
NanoXMLOFXReader nano = new NanoXMLOFXReader();
try
{
nano.parse(stream);
System.out.println("woooo It workssss!!!!");
}
catch (OFXParseException e)
{
}
Thanks for your comments, I made some changes:
String FILE_TO_READ = "C:\\file.ofx";
try
{
FileInputStream file = new FileInputStream(FILE_TO_READ);
NanoXMLOFXReader nano = new NanoXMLOFXReader();
nano.parse(file);
System.out.println("woooo It workssss!!!!");
}
catch (OFXParseException e)
{
System.out.println("Message : "+e.getMessage());
}
catch (Exception e1)
{
System.out.println("Other Message : "+e1.getMessage());
}
But now I am getting this:
Exception in thread "main" java.lang.NoClassDefFoundError: net/n3/nanoxml/XMLParseException
at OfxTest.afficherFichier(OfxTest.java:31)
at OfxTest.main(OfxTest.java:20)
Caused by: java.lang.ClassNotFoundException: net.n3.nanoxml.XMLParseException
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
I am trying to figure it out. I believe it can't find the XMLParseException. But I am not sure.
The second problem that you're encountering: "Exception in thread "main" java.lang.NoClassDefFoundError: net/n3/nanoxml/XMLParseException" means that you haven't included the NanoXML library from here: http://devkix.com/nanoxml.php
You will also need the Apache Commons Logging library, as NanoXML appears to be dependent on this. Available here: http://commons.apache.org/logging/download_logging.cgi
This means that you are not catching FileNotFoundException. Also although this is not relevant to your error message but as best practice you should always close you file stream in the finally block like I have below. There is also no need to do to new String() on the file name either.
Add this catch block for the FileNotFoundException:-
String filename = "C:\\file.ofx";
FileInputStream file = null;
NanoXMLOFXReader nano = null;
try
{
file = new FileInputStream(filename);
nano = new NanoXMLOFXReader();
nano.parse(stream);
System.out.println("woooo It workssss!!!!");
}
catch (OFXParseException e)
{
e.printStackTrace();
throw e;
}catch (FileNotFoundException e){
e.printStackTrace();
throw e;
}finally{
if(file!=null){
file.close();
}
}

Categories