Java serializable object to a file - java

I have a Swing Program. I am having trouble to save entire main class to a file.
public class GreenHouseMain extends JFrame implements ActionListener,
MouseListener, Runnable, WindowListener, KeyListener, Serializable
{
//.....other components
static GreenHouseMain ghMain;
}
public static void main(String[] args)
{
ghMain = new GreenHouseMain();
}
public void startEvents()
{
suspended = false;
terminate = false;
jbStart.setEnabled(false);
worker = new Thread(new Runnable()
{
public void run()
{
try
{
//Other Code
} catch (ControllerException e)
{
try
{
Date now = new Date();
String log = "";
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("error.log")));
if (e.getMessage() == "Unknown Windows Malfuction")
{
log = "ErrorCode=1, WindowMalfunction," + now;
} else
{
log = "ErrorCode=2, PowerOut," + now;
}
out.println(log);
jTextArea.append(log + "\n");
out.close();
out.flush();
ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream("dump.out"));
//It failed in here, says "java.lang.NullPointerException
output.writeObject(GreenHouseMain.ghMain);
output.flush();
} catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
}
});
worker.start();
}
Few things you should know:
1. All classes have been implements Serializable interface
2. There several threads in the program (don't know if it is reason for exception
3. I have had Serialized a object to file before with about the same code but in a console app. Don't know why it fails here.
at javax.swing.plaf.basic.BasicScrollPaneUI.paint(Unknown Source)
at javax.swing.plaf.ComponentUI.update(Unknown Source)
at javax.swing.JComponent.paintComponent(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent._paintImmediately(Unknown Source)
at javax.swing.JComponent.paintImmediately(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.seqPaintDirtyRegions(Unknown Source)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

This
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
should be:
} catch (IOException ex) {
ex.printStackTrace();
}
This will give you much better information, most importantly the exact line where the NullPointerException occurs and from where that line is reached. If that doesn't make the cause of the problem obvious, start the program in a debugger and put a breakpoint on that line.

Related

No method named getClip was found in type "javax.sound.sampled.AudioSystem"

Trying to play and audio clip in java, but this error pops up every time. I imported everything I need to so I'm not sure what the issue is.
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream (this.getClass ().getResource ("hopes_and_dreams.wav"));
Clip clip = AudioSystem.getClip ();
clip.open (audioInputStream);
clip.start ();
javax.sound.sampled.LineUnavailableException: Failed to allocate clip data: Requested buffer too large.
at com.sun.media.sound.MixerClip.implOpen(Unknown Source)
at com.sun.media.sound.MixerClip.open(Unknown Source)
at com.sun.media.sound.MixerClip.open(Unknown Source)
at CA_PeterLang.paint(CA_PeterLang.java:828)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JLayeredPane.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paintWithOffscreenBuffer(Unknown Source)
at javax.swing.JComponent.paintDoubleBuffered(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at java.awt.GraphicsCallback$PaintCallback.run(Unknown Source)
at sun.awt.SunGraphicsCallback.runOneComponent(Unknown Source)
at sun.awt.SunGraphicsCallback.runComponents(Unknown Source)
at java.awt.Container.paint(Unknown Source)
at sun.awt.RepaintArea.paint(Unknown Source)
at sun.awt.windows.WComponentPeer.handleEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
The issue of the OP and not being able to find the method is related to the Ready to Program IDE which is apparently running Java 1.4. The .getClip() method in the question was added in Java 1.5 according to the JavaDocs for AudioSystem
However, I have, in the past, had issues where the system would not find my specific speakers, so the following approach has worked for me. Note that I use a URL, but it should be adaptable to a getResource() approach.
private Mixer.Info getSpeakers()
{
Mixer.Info speakers = null;
Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
for (Mixer.Info mi : mixerInfo) {
// System.out.println(mi.getName() + "\t" +
// mi.getDescription());
if (mi.getName().startsWith("Speakers")) {
speakers = mi;
}
}
System.out.println(
(speakers != null ? speakers.getName() : "<no speakers>"));
return speakers;
}
public void playSound(String soundFile)
{
AudioInputStream ais = null;
try {
URL url = new File(soundFile).toURI().toURL();
ais = AudioSystem.getAudioInputStream(url);
Mixer mixer = AudioSystem.getMixer(getSpeakers());
DataLine.Info dataInfo = new DataLine.Info(Clip.class, null);
Clip clip = (Clip)mixer.getLine(dataInfo);
clip.open(ais);
clip.start();
do {
try {
Thread.sleep(50);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
while (clip.isActive());
}
catch (UnsupportedAudioFileException | IOException |
LineUnavailableException e)
{
e.printStackTrace();
}
}
When called with playSound("Alarm01.wav"), it properly executes. I think this approach uses slightly older methods.
Edit: please do not follow my names here -- they are hacked for testing.
Edit 2: the foreach loop may be changed to:
for (int i = 0; i < mixerInfo.length; ++i) {
Mixer.Info mi = mixerInfo[i];
...
Edit 3: to use as an InputStream rather than a URL, use
InputStream is = this.getClass().getClassLoader().getResourceAsStream(soundName);
// add a check for null
ais = AudioSystem.getAudioInputStream(is);
Edit 4: This method works with Java 1.4 (to the best of my knowledge). I had to hack around on my local machine settings to get the sound, but that is a different issue.
public void playSoundOldJava(String soundFile)
{
try {
InputStream is = this.getClass().getClassLoader().getResourceAsStream(soundFile);
// TODO: add check for null inputsteam
if (is == null) {
throw new IOException("did not find " + soundFile);
}
AudioInputStream ais = AudioSystem.getAudioInputStream(is);
DataLine.Info dataInfo = new DataLine.Info(Clip.class, ais.getFormat());
if (AudioSystem.isLineSupported(dataInfo)) {
Clip clip = (Clip)AudioSystem.getLine(dataInfo);
System.out.println("open");
clip.open(ais);
clip.start();
do {
try {
Thread.sleep(50);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
while (clip.isActive());
}
}
catch (Exception e) {
e.printStackTrace();
}
}
I've never used it but, it seems like you have to do this :
Clip clip = new Clip(); // Think that you can pass the stream as parameter for the builder
clip.open(audioInputStream);
Ref here : https://docs.oracle.com/javase/7/docs/api/javax/sound/sampled/Clip.html#open(javax.sound.sampled.AudioInputStream)

Java SQL expected 6 bytes and received 0 error

I am getting this error: "Insufficient data while reading from the network - expected a minimum of 6 bytes and received only 0 bytes. The connection has been terminated." When I try to connect to my data base. I can not seem to find any solution that works. Could you guys give me a hand?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class RetrieveData
{
private String zone;
private String date;
private String userName = "User";
private String password = "Password";
private String serverAdress= "jdbc:derby://Server:1010/Database";
private Connection con = null;
private Statement stmt = null;
private ResultSet rs = null;
RetrieveData(String zoneToPull, String dayToPull)
{
zone = zoneToPull;
date = dayToPull;
}
public int HistoryActual()
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection(serverAdress, userName, password);
String sql = "SELECT TOP 10 " +
"*" +
"FROM" +
"walks" +
"WHERE"+
"company_id = 'TMS3'";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next())
{
System.out.println(rs.getString(4) + " " + rs.getString(6));
}
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
finally
{
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
return 0;
}
}
Here is the stack trace:
java.sql.SQLNonTransientConnectionException: Insufficient data while reading from the network - expected a minimum of 6 bytes and received only 0 bytes. The connection has been terminated.
at org.apache.derby.client.am.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.jdbc.ClientDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at RetrieveData.HistoryActual(RetrieveData.java:27)
at BookToGoals.(BookToGoals.java:34)
at Console.Console(Console.java:96)
at Console.access$0(Console.java:47)
at Console$1.run(Console.java:43)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: ERROR 08006: Insufficient data while reading from the network - expected a minimum of 6 bytes and received only 0 bytes. The connection has been terminated.
at org.apache.derby.client.net.Reply.fill(Unknown Source)
at org.apache.derby.client.net.Reply.ensureALayerDataInBuffer(Unknown Source)
at org.apache.derby.client.net.Reply.readDssHeader(Unknown Source)
at org.apache.derby.client.net.Reply.startSameIdChainParse(Unknown Source)
at org.apache.derby.client.net.NetConnectionReply.readExchangeServerAttributes(Unknown Source)
at org.apache.derby.client.net.NetConnection.readServerAttributesAndKeyExchange(Unknown Source)
at org.apache.derby.client.net.NetConnection.flowServerAttributesAndKeyExchange(Unknown Source)
at org.apache.derby.client.net.NetConnection.flowUSRIDPWDconnect(Unknown Source)
at org.apache.derby.client.net.NetConnection.flowConnect(Unknown Source)
at org.apache.derby.client.net.NetConnection.(Unknown Source)
at org.apache.derby.client.net.ClientJDBCObjectFactoryImpl.newNetConnection(Unknown Source)
... 22 more
It looks like I found out what is going on. It is due to my own confusion. I am trying to connect to a Microsoft SQL database. Thus I need the sqljdbc driver not derby. This has resolve my issue. Thanks for the help guys.

AES encryption attempt fails - Given final block not properly padded maybe

I know that this question has been asked a couple of times before and I have reviewed the answers to no avail, but what I did get from the answers is that my problem maybe a 'wrong key' issue. This is my first time attempting encryption I put this AES class together from a couple of tutorials I found online. My guess is I have either left something out or have something in the wrong order. Below is my code and the StackTrace. Any help that would point me in the right direction would be much appreciated.
public class AES {
private static ArrayList<String> uncryptedArrayList = new ArrayList<>();
private static String pinString;
private SecretKeyFactory factory;
private KeySpec spec;
private SecretKey tmp;
private Cipher dcipher;
private byte[] salt, iv, decodedData, decryptedData, pin, pass, encryptedData, encodedData;
private int iterationCount = 1024;
private int keyStrength = 128;
private SecretKey key;
private String magic;
private AlgorithmParameters params;
public AES() {
try {
salt = new String("TheBestSaltEvers").getBytes();
magic = new String("ABCDEFGHIJKLMNOP");
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
spec = new PBEKeySpec(magic.toCharArray(), salt, iterationCount, keyStrength);
tmp = factory.generateSecret(spec);
key = new SecretKeySpec(tmp.getEncoded(), "AES");
dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
params = dcipher.getParameters();
iv = params.getParameterSpec(IvParameterSpec.class).getIV();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidParameterSpecException e) {
e.printStackTrace();
}
}
public byte[] encrypt(String data) {
try {
dcipher.init(Cipher.ENCRYPT_MODE, key);
encryptedData = dcipher.doFinal(data.getBytes("UTF8"));
encodedData = new Base64().encode(encryptedData);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return encodedData;
}
public String decrypt(byte[] data) {
String result = null;
try {
dcipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
decodedData = new Base64().decode(data);
decryptedData = dcipher.doFinal(decodedData);
result = new String(decryptedData, "UTF8");
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
StackTrace
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:966)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
at security.AES.decrypt(AES.java:108)
at security.AES.decryptedPinPass(AES.java:187)
at gui.UserLogin.<init>(UserLogin.java:95)
at gui.Login.lambda$2(Login.java:191)
at gui.Login$$Lambda$19/1960756374.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:966)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)
at javax.crypto.Cipher.doFinal(Cipher.java:2165)
at security.AES.decrypt(AES.java:108)
at security.AES.decryptedPinPass(AES.java:188)
at gui.UserLogin.<init>(UserLogin.java:95)
at gui.Login.lambda$2(Login.java:191)
at gui.Login$$Lambda$19/1960756374.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
You are forgetting to include the IV in the Cipher.init during encryption. The IV will therefore differ, giving you this error for smaller ciphertext. Usually the IV is prefixed to the ciphertext.
Note that putting everything in fields is really not the way to go. In the end the encrypt and decrypt methods should work independently of each other.

MYSQL - Communications link failure; timeout

The class below creates a connection to my MYSQL user, it then submits some data into a table.. I've checked and double checked the username and password, it's definitely 100% correct, but why does it keep throwing this memory leak? I am having trouble figuring this out myself, I've been reading all the related topics, but none really seems to be the same issue as mine.
package com.rs.MYSQL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import com.rs.Settings;
import com.rs.utils.Lottery;
public class LotteryMYSQL {
private static Connection connection;
private static long lastConnection = System.currentTimeMillis();
public static void createConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://runerebellion.com:3306/database",
"user", "pass");//fake user&pass
} catch (Exception e) {
e.printStackTrace();
}
}
public static void destroyConnection() {
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void init() {
createConnection();
}
public static boolean updateInfo() {
try {
if (Settings.DisableMYSQL == true)
return false;
createConnection();
Statement stmt = connection.createStatement();
if (Lottery.getCurrentLotteryWinner() != null)
stmt.executeUpdate("UPDATE info SET moneyEarned = '"
+ Lottery.options.size() + "', lastWinner = '"
+ Lottery.getCurrentLotteryWinner() + "'");
else
stmt.executeUpdate("UPDATE info SET moneyEarned = '"
+ Lottery.options.size() + "', lastWinner = '"
+ Lottery.getLastLotteryWinner() + "'");
destroyConnection();
} catch (Throwable e) {
if (System.currentTimeMillis() - lastConnection > 10000) {
destroyConnection();
createConnection();
lastConnection = System.currentTimeMillis();
}
}
return false;
}
}
The memory leak is below
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
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 com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1137)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:356)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2504)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2541)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2323)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:832)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
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 com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:417)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:344)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.rs.MYSQL.LotteryMYSQL.createConnection(LotteryMYSQL.java:19)
at com.rs.Launcher.main(Launcher.java:103)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:258)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:306)
... 16 more
Used this:
and it worked fine
Class.forName("com.mysql.jdbc.Driver").newInstance();
String IP = "";
String DB = "";
String User = "";
String Pass = "";
connection = DriverManager.getConnection("jdbc:mysql://" + IP + "/"
+ DB, User, Pass);

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.

Categories