Lots of code fixes and refactoring. Serializer does now work with InputStream and OutputStream instead of directly accessing files. All depending classes have been refactored as well.
This commit is contained in:
Fabian Becker 2012-04-26 14:17:23 +00:00
parent 20c0c21c02
commit 693d5f8e9d
16 changed files with 512 additions and 427 deletions

View File

@ -26,20 +26,16 @@ import eva2.tools.*;
import eva2.tools.jproxy.RemoteStateListener;
import java.awt.*;
import java.awt.event.*;
import java.io.Serializable;
import java.io.*;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Set;
import java.util.Vector;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.plaf.basic.BasicBorders;
/**
@ -71,7 +67,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
// LogPanel
private LoggingPanel logPanel;
private static final Logger logger = Logger.getLogger(EvAInfo.defaultLogger);
private static final Logger LOGGER = Logger.getLogger(EvAInfo.defaultLogger);
// Module:
private ExtAction actModuleLoad;
@ -395,7 +391,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
evaFrame.getContentPane().add(progressBar, BorderLayout.NORTH);
evaFrame.getContentPane().setLayout(new BorderLayout());
logPanel = new LoggingPanel(logger);
logPanel = new LoggingPanel(LOGGER);
evaFrame.getContentPane().add(logPanel, BorderLayout.SOUTH);
@ -430,12 +426,12 @@ public class EvAClient implements RemoteStateListener, Serializable {
selectHost(hostName);
}
comAdapter.setLogPanel(logPanel);
logger.log(Level.INFO, "Selected Host: {0}", comAdapter.getHostName());
LOGGER.log(Level.INFO, "Selected Host: {0}", comAdapter.getHostName());
}
if (withGUI) {
logger.log(Level.INFO, "Working directory is: {0}", System.getProperty("user.dir"));
logger.log(Level.INFO, "Class path is: {0}", System.getProperty("java.class.path", "."));
LOGGER.log(Level.INFO, "Working directory is: {0}", System.getProperty("user.dir"));
LOGGER.log(Level.INFO, "Class path is: {0}", System.getProperty("java.class.path", "."));
if (!(evaFrame.isVisible())) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
@ -445,7 +441,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
}
// if this message is omitted, the stupid scroll pane runs to
// the end of the last line which is ugly for a long class path
logger.info("EvA2 ready");
LOGGER.info("EvA2 ready");
}
}
@ -454,11 +450,11 @@ public class EvAClient implements RemoteStateListener, Serializable {
* the MATLAB environment variable has been set.
*/
public void close() {
logger.info("Closing EvA2 Client. Bye!");
LOGGER.info("Closing EvA2 Client. Bye!");
evaFrame.dispose();
Set<String> keys = System.getenv().keySet();
if (keys.contains("MATLAB")) {
logger.info("EvA2 workbench has been started from Matlab: not killing JVM");
LOGGER.info("EvA2 workbench has been started from Matlab: not killing JVM");
} else {
if (parentWindow == null) {
System.exit(1);
@ -601,7 +597,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {
logger.info(e.getActionCommand());
LOGGER.info(e.getActionCommand());
showAboutDialog();
}
};
@ -612,7 +608,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {
logger.info(e.getActionCommand());
LOGGER.info(e.getActionCommand());
showLicense();
}
};
@ -623,7 +619,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {
logger.info(e.getActionCommand());
LOGGER.info(e.getActionCommand());
selectAvailableHost(comAdapter.getHostNameList());
}
};
@ -634,7 +630,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {
logger.info(e.getActionCommand());
LOGGER.info(e.getActionCommand());
showPleaseWaitDialog();
Thread xx = new Thread() {
@ -653,7 +649,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {
logger.info(e.getActionCommand());
LOGGER.info(e.getActionCommand());
showPleaseWaitDialog();
Thread xx = new Thread() {
@ -671,7 +667,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {
logger.info(e.getActionCommand());
LOGGER.info(e.getActionCommand());
showPleaseWaitDialog();
Thread xx = new Thread() {
@ -820,10 +816,10 @@ public class EvAClient implements RemoteStateListener, Serializable {
if (useLocalRMI) {
EvAServer Server = new EvAServer(true, false);
comAdapter.setLocalRMIServer(Server.getRMIServer());
logger.info("Local EvAServer started");
LOGGER.info("Local EvAServer started");
comAdapter.setRunLocally(false); // this is not quite true but should have the desired effect
} else {
logger.info("Working locally");
LOGGER.info("Working locally");
comAdapter.setLocalRMIServer(null);
comAdapter.setRunLocally(true);
}
@ -836,22 +832,41 @@ public class EvAClient implements RemoteStateListener, Serializable {
if (ModuleNameList == null) {
JOptionPane.showMessageDialog(evaFrame.getContentPane(), "No modules available on " + comAdapter.getHostName(), EvAInfo.infoTitle, 1);
} else {
String LastModuleName = Serializer.loadString("lastmodule.ser");
if (LastModuleName == null) {
LastModuleName = ModuleNameList[0];
String lastModule = null;
try {
FileInputStream inputStream = new FileInputStream("lastmodule.ser");
lastModule = Serializer.loadString(inputStream);
inputStream.close();
} catch (Exception ex) {
LOGGER.log(Level.WARNING, "Could not load last loaded module.", ex);
}
if (lastModule == null) {
lastModule = ModuleNameList[0];
LOGGER.log(Level.INFO, "Defaulting to module: {0}", lastModule);
}
selectedModule = (String) JOptionPane.showInputDialog(evaFrame.getContentPane(),
"Which module do you want \n to load on host: " + comAdapter.getHostName() + " ?", "Load optimization module on host",
JOptionPane.QUESTION_MESSAGE,
null,
ModuleNameList,
LastModuleName);
lastModule);
}
}
if (selectedModule == null) {
System.err.println("not loading any module");
} else {
Serializer.storeString("lastmodule.ser", selectedModule);
try {
FileOutputStream outStream = new FileOutputStream("lastmodule.ser");
Serializer.storeString(outStream, selectedModule);
outStream.close();
} catch (FileNotFoundException ex) {
LOGGER.log(Level.WARNING, "Could not store selected module.", ex);
} catch (IOException ex) {
LOGGER.log(Level.WARNING, "Could not close file stream.", ex);
}
loadSpecificModule(selectedModule, goParams);
@ -859,8 +874,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
actHost.setEnabled(true);
actAvailableHost.setEnabled(true);
}
logger.info("Selected Module: " + selectedModule);
// m_LogPanel.statusMessage("Selected Module: " + selectedModule);
LOGGER.info("Selected Module: " + selectedModule);
}
}
@ -906,7 +920,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
try {
newModuleAdapter = comAdapter.getModuleAdapter(selectedModule, goParams, withGUI ? null : "EvA2");
} catch (Exception e) {
logger.log(Level.SEVERE, "Error loading module.", e);
LOGGER.log(Level.SEVERE, "Error loading module.", e);
EVAERROR.EXIT("Error while m_ComAdapter.GetModuleAdapter Host: " + e.getMessage());
}
if (newModuleAdapter == null) {
@ -915,9 +929,9 @@ public class EvAClient implements RemoteStateListener, Serializable {
String cp = System.getProperty("java.class.path", ".");
String dir = (baseDir == null) ? System.getProperty("user.dir") : baseDir.getPath();
// System.err.println("Working dir: " + dir);
if (baseDir == null) {
/*if (baseDir == null) {
throw new RuntimeException("Cannot launch EvA2 due to an access restriction. If you are using Java Web Start, please download the application and try again.");
}
}*/
if (!cp.contains(dir)) {
// this was added due to matlab not adding base dir to base path...
System.err.println("classpath does not contain base directory!");
@ -971,7 +985,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
// m_ModulGUIContainer.add(Temp);
} catch (Exception e) {
currentModule = null;
logger.log(Level.SEVERE, "Error while newModulAdapter.getModulFrame(): " + e.getMessage(), e);
LOGGER.log(Level.SEVERE, "Error while newModulAdapter.getModulFrame(): " + e.getMessage(), e);
EVAERROR.EXIT("Error while newModulAdapter.getModulFrame(): " + e.getMessage());
}
// try { TODO whats this?
@ -1028,9 +1042,9 @@ public class EvAClient implements RemoteStateListener, Serializable {
private void selectHost(String hostName) {
comAdapter.setHostName(hostName);
logger.info("Selected Host: " + hostName);
LOGGER.info("Selected Host: " + hostName);
if (currentModule != null) {
logger.info("Reloading module from server...");
LOGGER.info("Reloading module from server...");
loadModuleFromServer(currentModule, null);
}
}
@ -1078,7 +1092,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
if (HostName == null) {
return;
}
logger.info("Kill host process on = " + HostName);
LOGGER.info("Kill host process on = " + HostName);
comAdapter.killServer(HostName);
// m_LogPanel.statusMessage("");
}
@ -1098,7 +1112,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
l.performedRestart(infoString);
}
}
logger.log(Level.INFO, "Restarted processing {0}", infoString);
LOGGER.log(Level.INFO, "Restarted processing {0}", infoString);
startTime = System.currentTimeMillis();
}
@ -1108,7 +1122,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
l.performedStart(infoString);
}
}
logger.log(Level.INFO, "Started processing {0}", infoString);
LOGGER.log(Level.INFO, "Started processing {0}", infoString);
startTime = System.currentTimeMillis();
}
@ -1119,7 +1133,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
}
}
long t = (System.currentTimeMillis() - startTime);
logger.info(String.format("Stopped after %1$d.%2$tL s", (t / 1000), (t % 1000)));
LOGGER.info(String.format("Stopped after %1$d.%2$tL s", (t / 1000), (t % 1000)));
if (!withGUI) {
System.exit(0);
}
@ -1137,7 +1151,7 @@ public class EvAClient implements RemoteStateListener, Serializable {
}
}
if (msg != null) {
logger.info(msg);
LOGGER.info(msg);
}
if (this.progressBar != null) {
Runnable doSetProgressBarValue = new Runnable() {

View File

@ -14,11 +14,17 @@ import eva2.server.go.operators.postprocess.PostProcessParams;
import eva2.server.go.problems.InterfaceAdditionalPopulationInformer;
import eva2.server.go.problems.InterfaceOptimizationProblem;
import eva2.server.go.strategies.InterfaceOptimizer;
import eva2.tools.Serializer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class AbstractGOParameters implements InterfaceGOParameters, Serializable {
public static boolean TRACE = false;
protected long m_Seed = (long)0.0;
public abstract class AbstractGOParameters implements InterfaceGOParameters, Serializable {
protected static final Logger LOGGER = Logger.getLogger(eva2.EvAInfo.defaultLogger);
protected long randomSeed = (long)0.0;
// Opt. Algorithms and Parameters
protected InterfaceOptimizer m_Optimizer;
@ -31,14 +37,14 @@ public abstract class AbstractGOParameters implements InterfaceGOParameters, Ser
protected AbstractGOParameters() {
}
protected AbstractGOParameters(AbstractGOParameters Source) {
protected AbstractGOParameters(AbstractGOParameters goParameters) {
this();
this.m_Optimizer = Source.m_Optimizer;
this.m_Problem = Source.m_Problem;
this.m_Terminator = Source.m_Terminator;
this.m_Optimizer = goParameters.m_Optimizer;
this.m_Problem = goParameters.m_Problem;
this.m_Terminator = goParameters.m_Terminator;
this.m_Optimizer.SetProblem(this.m_Problem);
this.m_Seed = Source.m_Seed;
this.m_PostProc = Source.m_PostProc;
this.randomSeed = goParameters.randomSeed;
this.m_PostProc = goParameters.m_PostProc;
}
public AbstractGOParameters(InterfaceOptimizer opt, InterfaceOptimizationProblem prob, InterfaceTerminator term) {
@ -60,7 +66,7 @@ public abstract class AbstractGOParameters implements InterfaceGOParameters, Ser
setProblem(src.m_Problem);
setTerminator(src.m_Terminator);
this.m_Optimizer.SetProblem(this.m_Problem);
setSeed(src.m_Seed);
setSeed(src.randomSeed);
setPostProcessParams(src.m_PostProc);
}
@ -81,20 +87,37 @@ public abstract class AbstractGOParameters implements InterfaceGOParameters, Ser
return true;
} else return false;
}
/**
*
*/
public void saveInstance(String fileName) {
try {
FileOutputStream fileStream = new FileOutputStream(fileName);
Serializer.storeObject(fileStream, this);
} catch (FileNotFoundException ex) {
LOGGER.log(Level.WARNING, "Could not store instance object.", ex);
}
}
public void saveInstance() {
String fileName = this.getClass().getSimpleName() + ".ser";
saveInstance(fileName);
}
public String toString() {
StringBuffer sb = new StringBuffer(getName());
sb.append("\n");
sb.append("seed=");
sb.append(m_Seed);
sb.append("\nProblem: ");
sb.append(BeanInspector.toString(m_Problem));
sb.append("\nOptimizer: ");
sb.append(BeanInspector.toString(m_Optimizer));
sb.append("\nTerminator: ");
sb.append(BeanInspector.toString(m_Terminator));
sb.append("\n");
return sb.toString();
StringBuilder sBuilder = new StringBuilder(getName());
sBuilder.append("\n");
sBuilder.append("seed=");
sBuilder.append(randomSeed);
sBuilder.append("\nProblem: ");
sBuilder.append(BeanInspector.toString(m_Problem));
sBuilder.append("\nOptimizer: ");
sBuilder.append(BeanInspector.toString(m_Optimizer));
sBuilder.append("\nTerminator: ");
sBuilder.append(BeanInspector.toString(m_Terminator));
sBuilder.append("\n");
return sBuilder.toString();
}
public void addInformableInstance(InterfaceNotifyOnInformers o) {
@ -160,11 +183,18 @@ public abstract class AbstractGOParameters implements InterfaceGOParameters, Ser
* @param x Long seed.
*/
public void setSeed(long x) {
m_Seed = x;
randomSeed = x;
}
/**
* Returns the current seed for the random number generator.
*
* @return The current seed for the random number generator.
*/
public long getSeed() {
return m_Seed;
return randomSeed;
}
public String seedTipText() {
return "Random number seed, set to zero to use current system time.";
}

View File

@ -11,6 +11,11 @@ import eva2.server.go.problems.F1Problem;
import eva2.server.go.strategies.DifferentialEvolution;
import eva2.server.go.strategies.InterfaceOptimizer;
import eva2.tools.Serializer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/** The class gives access to all DE parameters for the EvA
* top level GUI.
@ -22,25 +27,27 @@ import eva2.tools.Serializer;
*/
public class DEParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable {
public static boolean TRACE = false;
/**
*
* Load or create a new instance of the class.
*
* @return A loaded (from file) or new instance of the class.
*/
public static DEParameters getInstance() {
if (TRACE) System.out.println("DEParameters getInstance 1");
DEParameters Instance = (DEParameters) Serializer.loadObject("DEParameters.ser");
if (TRACE) System.out.println("DEParameters getInstance 2");
if (Instance == null) Instance = new DEParameters();
return Instance;
DEParameters instance = null;
try {
FileInputStream fileStream = new FileInputStream("DEParameters.ser");
instance = (DEParameters) Serializer.loadObject(fileStream);
} catch (FileNotFoundException ex) {
LOGGER.log(Level.WARNING, "Could not load instance object.", ex);
}
if (instance == null) {
instance = new DEParameters();
}
return instance;
}
/**
*
*/
public void saveInstance() {
Serializer.storeObject("DEParameters.ser",this);
}
/**
*
*/
@ -76,23 +83,25 @@ public class DEParameters extends AbstractGOParameters implements InterfaceGOPar
* @return The population of current solutions to a given problem.
*/
public Population getPopulation() {
return ((DifferentialEvolution)this.m_Optimizer).getPopulation();
return ((DifferentialEvolution) this.m_Optimizer).getPopulation();
}
public void setPopulation(Population pop){
((DifferentialEvolution)this.m_Optimizer).setPopulation(pop);
((DifferentialEvolution) this.m_Optimizer).setPopulation(pop);
}
public String populationTipText() {
return "Edit the properties of the population used.";
}
/** This method will set the amplication factor f
/** This method will set the amplication factor f.
* @param f
*/
public void setF (double f) {
((DifferentialEvolution)this.m_Optimizer).setF(f);
((DifferentialEvolution) this.m_Optimizer).setF(f);
}
public double getF() {
return ((DifferentialEvolution)this.m_Optimizer).getF();
return ((DifferentialEvolution) this.m_Optimizer).getF();
}
public String fTipText() {
return "F is a real and constant factor which controlls the ampllification of the differential variation.";
@ -102,10 +111,10 @@ public class DEParameters extends AbstractGOParameters implements InterfaceGOPar
* @param k
*/
public void setK(double k) {
((DifferentialEvolution)this.m_Optimizer).setK(k);
((DifferentialEvolution) this.m_Optimizer).setK(k);
}
public double getK() {
return ((DifferentialEvolution)this.m_Optimizer).getK();
return ((DifferentialEvolution) this.m_Optimizer).getK();
}
public String kTipText() {
return "Probability of alteration through DE1.";
@ -115,10 +124,10 @@ public class DEParameters extends AbstractGOParameters implements InterfaceGOPar
* @param l
*/
public void setLambda (double l) {
((DifferentialEvolution)this.m_Optimizer).setLambda(l);
((DifferentialEvolution) this.m_Optimizer).setLambda(l);
}
public double getLambda() {
return ((DifferentialEvolution)this.m_Optimizer).getLambda();
return ((DifferentialEvolution) this.m_Optimizer).getLambda();
}
public String lambdaTipText() {
return "Enhance greediness through amplification of the differential vector to the best individual for DE2.";
@ -128,10 +137,10 @@ public class DEParameters extends AbstractGOParameters implements InterfaceGOPar
* @param s The type.
*/
public void setDEType(DETypeEnum s) {
((DifferentialEvolution)this.m_Optimizer).setDEType(s);
((DifferentialEvolution) this.m_Optimizer).setDEType(s);
}
public DETypeEnum getDEType() {
return ((DifferentialEvolution)this.m_Optimizer).getDEType();
return ((DifferentialEvolution) this.m_Optimizer).getDEType();
}
public String dETypeTipText() {
return "Choose the type of Differential Evolution.";

View File

@ -9,7 +9,11 @@ import eva2.server.go.problems.F1Problem;
import eva2.server.go.strategies.EvolutionaryProgramming;
import eva2.server.go.strategies.InterfaceOptimizer;
import eva2.tools.Serializer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
/** The class gives access to all EP parameters for the EvA
* top level GUI.
@ -21,31 +25,34 @@ import java.io.Serializable;
*/
public class EPParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable {
public static boolean TRACE = false;
private static final Logger LOGGER = Logger.getLogger(eva2.EvAInfo.defaultLogger);
/**
*
* Load or create a new instance of the class.
*
* @return A loaded (from file) or new instance of the class.
*/
public static EPParameters getInstance() {
if (TRACE) System.out.println("EPParameters getInstance 1");
EPParameters Instance = (EPParameters) Serializer.loadObject("EPParameters.ser");
if (TRACE) System.out.println("EPParameters getInstance 2");
if (Instance == null) Instance = new EPParameters();
return Instance;
EPParameters instance = null;
try {
FileInputStream fileStream = new FileInputStream("EPParameters.ser");
instance = (EPParameters) Serializer.loadObject(fileStream);
} catch (FileNotFoundException ex) {
LOGGER.log(Level.WARNING, "Could not load instance object.", ex);
}
if (instance == null) {
instance = new EPParameters();
}
return instance;
}
/**
*
*/
public void saveInstance() {
Serializer.storeObject("EPParameters.ser",this);
}
/**
*
*/
public EPParameters() {
super(new EvolutionaryProgramming(), new F1Problem(), new EvaluationTerminator());
if (TRACE) System.out.println("EPParameters Constructor start");
}
/**

View File

@ -8,7 +8,11 @@ import eva2.server.go.problems.B1Problem;
import eva2.server.go.strategies.GeneticAlgorithm;
import eva2.server.go.strategies.InterfaceOptimizer;
import eva2.tools.Serializer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
/** The class gives access to all GA parameters for the EvA
* top level GUI.
@ -19,23 +23,29 @@ import java.io.Serializable;
* To change this template use File | Settings | File Templates.
*/
public class GAParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable {
public static boolean TRACE = false;
public static GAParameters getInstance() {
if (TRACE) System.out.println("GAParameters getInstance 1");
GAParameters Instance = (GAParameters) Serializer.loadObject("GAParameters.ser");
if (TRACE) System.out.println("GAParameters getInstance 2");
if (Instance == null) Instance = new GAParameters();
return Instance;
}
private static final Logger LOGGER = Logger.getLogger(eva2.EvAInfo.defaultLogger);
/**
*
* Load or create a new instance of the class.
*
* @return A loaded (from file) or new instance of the class.
*/
public void saveInstance() {
Serializer.storeObject("GAParameters.ser",this);
public static GAParameters getInstance() {
GAParameters instance = null;
try {
FileInputStream fileStream = new FileInputStream("GAParameters.ser");
instance = (GAParameters) Serializer.loadObject(fileStream);
} catch (FileNotFoundException ex) {
LOGGER.log(Level.WARNING, "Could not load instance object.", ex);
}
if (instance == null) {
instance = new GAParameters();
}
return instance;
}
/**
*
*/

View File

@ -10,6 +10,9 @@ import eva2.server.go.problems.InterfaceOptimizationProblem;
import eva2.server.go.strategies.GeneticAlgorithm;
import eva2.server.go.strategies.InterfaceOptimizer;
import eva2.tools.Serializer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.logging.Level;
/**
@ -23,10 +26,8 @@ import eva2.tools.Serializer;
*/
public class GOParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable {
public static boolean TRACE = false;
public static GOParameters getInstance() {
return getInstance("GOParameters.ser", true);
return getInstance("GOParameters.ser", true);
}
/**
@ -36,35 +37,23 @@ public class GOParameters extends AbstractGOParameters implements InterfaceGOPar
* @param casually if true, standard parameters are used quietly if the params cannot be loaded
* @return a GOParameters instance
*/
public static GOParameters getInstance(String serParamFile, boolean casually) {
if (TRACE) System.out.println("GOParameters getInstance 1 - " + serParamFile + " , " + casually);
GOParameters Instance = null;
if (serParamFile!=null) {
try {
Instance = (GOParameters) Serializer.loadObject(serParamFile, casually);
if (TRACE) System.out.println("Loading succeded.");
} catch(Exception e) {
System.err.println("Error loading GOParameters from " + serParamFile);
Instance = null;
}
} else if (!casually) System.err.println("Error: null argument for noncasual param file loading! (GOParameters)");
if (TRACE) System.out.println("GOParameters getInstance 2");
if (Instance == null) Instance = new GOParameters();
return Instance;
}
public void saveInstance(String serParamFile) {
if (TRACE) System.out.println("GOParameters: saveInstance to " + serParamFile);
Serializer.storeObject(serParamFile,this);
}
public void saveInstance() {
saveInstance("GOParameters.ser");
public static GOParameters getInstance(String serParamFile, final boolean casually) {
GOParameters instance = null;
try {
FileInputStream fileStream = new FileInputStream(serParamFile);
instance = (GOParameters) Serializer.loadObject(fileStream, casually);
} catch (FileNotFoundException ex) {
LOGGER.log(Level.WARNING, "Could not load instance object.", ex);
}
if (instance == null) {
instance = new GOParameters();
}
return instance;
}
public GOParameters() {
super(new GeneticAlgorithm(), new F1Problem(), new EvaluationTerminator(1000));
// ((F1Problem)m_Problem).setEAIndividual(new GAIndividualDoubleData());
}
public GOParameters(InterfaceOptimizer opt, InterfaceOptimizationProblem prob, InterfaceTerminator term) {
@ -89,7 +78,8 @@ public class GOParameters extends AbstractGOParameters implements InterfaceGOPar
public Object clone() {
return new GOParameters(this);
}
/** This method returns a global info string
/** This method returns a global info string.
* @return description
*/
public static String globalInfo() {

View File

@ -7,7 +7,11 @@ import eva2.server.go.problems.B1Problem;
import eva2.server.go.strategies.HillClimbing;
import eva2.server.go.strategies.InterfaceOptimizer;
import eva2.tools.Serializer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
/** The class gives access to all HC parameters for the EvA
@ -19,23 +23,27 @@ import java.io.Serializable;
* To change this template use File | Settings | File Templates.
*/
public class HCParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable {
/**
*
*/
public static HCParameters getInstance() {
if (TRACE) System.out.println("HCParameters getInstance 1");
HCParameters Instance = (HCParameters) Serializer.loadObject("HCParameters.ser");
if (TRACE) System.out.println("HCParameters getInstance 2");
if (Instance == null) Instance = new HCParameters();
return Instance;
}
/**
*
* Load or create a new instance of the class.
*
* @return A loaded (from file) or new instance of the class.
*/
public void saveInstance() {
Serializer.storeObject("HCParameters.ser",this);
public static HCParameters getInstance() {
HCParameters instance = null;
try {
FileInputStream fileStream = new FileInputStream("HCParameters.ser");
instance = (HCParameters) Serializer.loadObject(fileStream);
} catch (FileNotFoundException ex) {
LOGGER.log(Level.WARNING, "Could not load instance object.", ex);
}
if (instance == null) {
instance = new HCParameters();
}
return instance;
}
/**
*
*/
@ -73,10 +81,10 @@ public class HCParameters extends AbstractGOParameters implements InterfaceGOPar
* @return The population of current solutions to a given problem.
*/
public Population getPopulation() {
return ((HillClimbing)this.m_Optimizer).getPopulation();
return ((HillClimbing) this.m_Optimizer).getPopulation();
}
public void setPopulation(Population pop){
((HillClimbing)this.m_Optimizer).setPopulation(pop);
((HillClimbing) this.m_Optimizer).setPopulation(pop);
}
public String populationTipText() {
return "Edit the properties of the population used.";

View File

@ -7,7 +7,10 @@ import eva2.server.go.problems.B1Problem;
import eva2.server.go.strategies.InterfaceOptimizer;
import eva2.server.go.strategies.MonteCarloSearch;
import eva2.tools.Serializer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.logging.Level;
/** The class gives access to all HC parameters for the EvA
* top level GUI.
@ -18,25 +21,27 @@ import java.io.Serializable;
* To change this template use File | Settings | File Templates.
*/
public class MCParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable {
public static boolean TRACE = false;
/**
*
* Load or create a new instance of the class.
*
* @return A loaded (from file) or new instance of the class.
*/
public static MCParameters getInstance() {
if (TRACE) System.out.println("MCParameters getInstance 1");
MCParameters Instance = (MCParameters) Serializer.loadObject("MCParameters.ser");
if (TRACE) System.out.println("MCParameters getInstance 2");
if (Instance == null) Instance = new MCParameters();
return Instance;
}
MCParameters instance = null;
try {
FileInputStream fileStream = new FileInputStream("MCParameters.ser");
instance = (MCParameters) Serializer.loadObject(fileStream);
} catch (FileNotFoundException ex) {
LOGGER.log(Level.WARNING, "Could not load instance object.", ex);
}
/**
*
*/
public void saveInstance() {
Serializer.storeObject("MCParameters.ser",this);
if (instance == null) {
instance = new MCParameters();
}
return instance;
}
/**
*
*/

View File

@ -9,7 +9,10 @@ import eva2.server.go.problems.TF1Problem;
import eva2.server.go.strategies.InterfaceOptimizer;
import eva2.server.go.strategies.MultiObjectiveEA;
import eva2.tools.Serializer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.logging.Level;
/** The class gives access to all MOEA parameters for the EvA
* top level GUI.
@ -21,18 +24,24 @@ import java.io.Serializable;
*/
public class MOEAParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable {
public static boolean TRACE = false;
/**
* Load or create a new instance of the class.
*
* @return A loaded (from file) or new instance of the class.
*/
public static MOEAParameters getInstance() {
if (TRACE) System.out.println("MOEAParameters getInstance 1");
MOEAParameters Instance = (MOEAParameters) Serializer.loadObject("MOEAParameters.ser");
if (TRACE) System.out.println("MOEAParameters getInstance 2");
if (Instance == null) Instance = new MOEAParameters();
return Instance;
}
MOEAParameters instance = null;
try {
FileInputStream fileStream = new FileInputStream("MOEAParameters.ser");
instance = (MOEAParameters) Serializer.loadObject(fileStream);
} catch (FileNotFoundException ex) {
LOGGER.log(Level.WARNING, "Could not load instance object.", ex);
}
public void saveInstance() {
Serializer.storeObject("MOEAParameters.ser",this);
if (instance == null) {
instance = new MOEAParameters();
}
return instance;
}
public MOEAParameters() {

View File

@ -8,7 +8,10 @@ import eva2.server.go.problems.B1Problem;
import eva2.server.go.strategies.InterfaceOptimizer;
import eva2.server.go.strategies.PopulationBasedIncrementalLearning;
import eva2.tools.Serializer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.logging.Level;
/** The class gives access to all PBIL parameters for the EvA
@ -21,18 +24,24 @@ import java.io.Serializable;
*/
public class PBILParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable {
public static boolean TRACE = false;
/**
* Load or create a new instance of the class.
*
* @return A loaded (from file) or new instance of the class.
*/
public static PBILParameters getInstance() {
if (TRACE) System.out.println("PBILParameters getInstance 1");
PBILParameters Instance = (PBILParameters) Serializer.loadObject("PBILParameters.ser");
if (TRACE) System.out.println("PBILParameters getInstance 2");
if (Instance == null) Instance = new PBILParameters();
return Instance;
}
PBILParameters instance = null;
try {
FileInputStream fileStream = new FileInputStream("PBILParameters.ser");
instance = (PBILParameters) Serializer.loadObject(fileStream);
} catch (FileNotFoundException ex) {
LOGGER.log(Level.WARNING, "Could not load instance object.", ex);
}
public void saveInstance() {
Serializer.storeObject("PBILParameters.ser",this);
if (instance == null) {
instance = new PBILParameters();
}
return instance;
}
public PBILParameters() {

View File

@ -13,6 +13,9 @@ import eva2.server.go.strategies.InterfaceOptimizer;
import eva2.server.go.strategies.ParticleSwarmOptimization;
import eva2.tools.SelectedTag;
import eva2.tools.Serializer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.logging.Level;
/** The class gives access to all PSO parameters for the EvA
* top level GUI.
@ -24,25 +27,26 @@ import eva2.tools.Serializer;
*/
public class PSOParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable {
public static boolean TRACE = false;
/**
*
/**
* Load or create a new instance of the class.
*
* @return A loaded (from file) or new instance of the class.
*/
public static PSOParameters getInstance() {
if (TRACE) System.out.println("PSOParameters getInstance 1");
PSOParameters Instance = (PSOParameters) Serializer.loadObject("PSOParameters.ser");
if (TRACE) System.out.println("PSOParameters getInstance 2");
if (Instance == null) Instance = new PSOParameters();
return Instance;
}
PSOParameters instance = null;
try {
FileInputStream fileStream = new FileInputStream("PSOParameters.ser");
instance = (PSOParameters) Serializer.loadObject(fileStream);
} catch (FileNotFoundException ex) {
LOGGER.log(Level.WARNING, "Could not load instance object.", ex);
}
/**
*
*/
public void saveInstance() {
Serializer.storeObject("PSOParameters.ser",this);
if (instance == null) {
instance = new PSOParameters();
}
return instance;
}
/**
*
*/

View File

@ -10,7 +10,10 @@ import eva2.server.go.problems.InterfaceOptimizationProblem;
import eva2.server.go.strategies.InterfaceOptimizer;
import eva2.server.go.strategies.SimulatedAnnealing;
import eva2.tools.Serializer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.logging.Level;
/** The class gives access to all SA parameters for the EvA
* top level GUI.
@ -21,9 +24,6 @@ import java.io.Serializable;
* To change this template use File | Settings | File Templates.
*/
public class SAParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable {
public static boolean TRACE = false;
// Opt. Algorithms and Parameters
private InterfaceOptimizer m_Optimizer = new SimulatedAnnealing();
private InterfaceOptimizationProblem m_Problem = new B1Problem();
@ -33,22 +33,25 @@ public class SAParameters extends AbstractGOParameters implements InterfaceGOPar
transient private InterfacePopulationChangedEventListener m_Listener;
/**
*
* Load or create a new instance of the class.
*
* @return A loaded (from file) or new instance of the class.
*/
public static SAParameters getInstance() {
if (TRACE) System.out.println("SAParameters getInstance 1");
SAParameters Instance = (SAParameters) Serializer.loadObject("SAParameters.ser");
if (TRACE) System.out.println("SAParameters getInstance 2");
if (Instance == null) Instance = new SAParameters();
return Instance;
}
SAParameters instance = null;
try {
FileInputStream fileStream = new FileInputStream("SAParameters.ser");
instance = (SAParameters) Serializer.loadObject(fileStream);
} catch (FileNotFoundException ex) {
LOGGER.log(Level.WARNING, "Could not load instance object.", ex);
}
/**
*
*/
public void saveInstance() {
Serializer.storeObject("SAParameters.ser",this);
if (instance == null) {
instance = new SAParameters();
}
return instance;
}
/**
*
*/

View File

@ -9,7 +9,10 @@ import eva2.server.go.problems.B1Problem;
import eva2.server.go.strategies.InterfaceOptimizer;
import eva2.server.go.strategies.SteadyStateGA;
import eva2.tools.Serializer;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.logging.Level;
/** The class gives access to all SSGA parameters for the EvA
* top level GUI.
@ -21,31 +24,33 @@ import java.io.Serializable;
*/
public class SSGAParameters extends AbstractGOParameters implements InterfaceGOParameters, Serializable {
public static boolean TRACE = false;
/**
*
* Load or create a new instance of the class.
*
* @return A loaded (from file) or new instance of the class.
*/
public static SSGAParameters getInstance() {
if (TRACE) System.out.println("SSGAParameters getInstance 1");
SSGAParameters Instance = (SSGAParameters) Serializer.loadObject("SSGAParameters.ser");
if (TRACE) System.out.println("SSGAParameters getInstance 2");
if (Instance == null) Instance = new SSGAParameters();
return Instance;
}
SSGAParameters instance = null;
try {
FileInputStream fileStream = new FileInputStream("SSGAParameters.ser");
instance = (SSGAParameters) Serializer.loadObject(fileStream);
} catch (FileNotFoundException ex) {
LOGGER.log(Level.WARNING, "Could not load instance object.", ex);
}
/**
*
*/
public void saveInstance() {
Serializer.storeObject("SSGAParameters.ser",this);
if (instance == null) {
instance = new SSGAParameters();
}
return instance;
}
/**
*
*/
public SSGAParameters() {
super(new SteadyStateGA(), new B1Problem(), new EvaluationTerminator());
}
private SSGAParameters(SSGAParameters Source) {
super(Source);
}
@ -54,7 +59,8 @@ public class SSGAParameters extends AbstractGOParameters implements InterfaceGOP
return new SSGAParameters(this);
}
/** This method returns a global info string
/**
* This method returns a global info string.
* @return description
*/
public static String globalInfo() {
@ -65,17 +71,19 @@ public class SSGAParameters extends AbstractGOParameters implements InterfaceGOP
// *pff* i'll ignore that!
}
/** Assuming that all optimizer will store thier data in a population
* we will allow acess to this population to query to current state
/** Assuming that all optimizer will store their data in a population
* we will allow access to this population to query to current state
* of the optimizer.
* @return The population of current solutions to a given problem.
*/
public Population getPopulation() {
return ((SteadyStateGA)this.m_Optimizer).getPopulation();
return ((SteadyStateGA) this.m_Optimizer).getPopulation();
}
public void setPopulation(Population pop){
((SteadyStateGA)this.m_Optimizer).setPopulation(pop);
((SteadyStateGA) this.m_Optimizer).setPopulation(pop);
}
public String populationTipText() {
return "Edit the properties of the population used.";
}
@ -97,25 +105,32 @@ public class SSGAParameters extends AbstractGOParameters implements InterfaceGOP
* @param selection
*/
public void setParentSelection(InterfaceSelection selection) {
((SteadyStateGA)this.m_Optimizer).setParentSelection(selection);
((SteadyStateGA) this.m_Optimizer).setParentSelection(selection);
}
public InterfaceSelection getParentSelection() {
return ((SteadyStateGA)this.m_Optimizer).getParentSelection();
return ((SteadyStateGA) this.m_Optimizer).getParentSelection();
}
public String parentSelectionTipText() {
return "Choose a parent selection method.";
}
/** This method will set the number of partners that are needed to create
* offsprings by mating
* @param partners
/**
* This method will set the number of partners that are needed to create
* offsprings by mating.
*
* @param partners Number of partners needed for mating
*/
public void setNumberOfPartners(int partners) {
if (partners < 0) partners = 0;
((SteadyStateGA)this.m_Optimizer).setNumberOfPartners(partners);
if (partners < 0) {
partners = 0;
}
((SteadyStateGA) this.m_Optimizer).setNumberOfPartners(partners);
}
public int getNumberOfPartners() {
return ((SteadyStateGA)this.m_Optimizer).getNumberOfPartners();
return ((SteadyStateGA) this.m_Optimizer).getNumberOfPartners();
}
public String numberOfPartnersTipText() {
return "The number of mating partners needed to create offsprings.";

View File

@ -13,6 +13,11 @@ import eva2.tools.EVAERROR;
import eva2.tools.SelectedTag;
import eva2.tools.Serializer;
import eva2.tools.StringSelection;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A set of parameters for statistics in EvA2. Several data entries are provided by the AbstractStatistics class,
@ -29,6 +34,7 @@ public class StatsParameter implements InterfaceStatisticsParameter, InterfaceNo
private static final long serialVersionUID = -8681061379203108390L;
private static boolean TRACE = false;
private static final Logger LOGGER = Logger.getLogger(eva2.EvAInfo.defaultLogger);
public final static int VERBOSITY_NONE = 0;
public final static int VERBOSITY_FINAL = 1;
@ -59,23 +65,33 @@ public class StatsParameter implements InterfaceStatisticsParameter, InterfaceNo
*
*/
public static StatsParameter getInstance(boolean loadDefaultSerFile) {
if (loadDefaultSerFile) return getInstance("Statistics.ser");
else return new StatsParameter();
}
/**
* Try to load instance from serialized file. If impossible, instantiate a new one.
*/
public static StatsParameter getInstance(String serFileName) {
if (TRACE ) System.out.println("Loading serialized stats..");
StatsParameter Instance = (StatsParameter) Serializer.loadObject(serFileName);
if (Instance == null) {
Instance = new StatsParameter();
if (TRACE) System.out.println("Loading failed!");
}
return Instance;
if (loadDefaultSerFile) {
return getInstance("Statistics.ser");
} else {
return new StatsParameter();
}
}
/**
* Load or create a new instance of the class.
*
* @return A loaded (from file) or new instance of the class.
*/
public static StatsParameter getInstance(String serFileName) {
StatsParameter instance = null;
try {
FileInputStream fileStream = new FileInputStream(serFileName);
instance = (StatsParameter) Serializer.loadObject(fileStream);
} catch (FileNotFoundException ex) {
LOGGER.log(Level.WARNING, "Could not store instance object.", ex);
}
if (instance == null) {
instance = new StatsParameter();
}
return instance;
}
/**
*
*/
@ -98,28 +114,17 @@ public class StatsParameter implements InterfaceStatisticsParameter, InterfaceNo
return ret;
}
// /**
// * Return a list of String arrays describing the selected plot options, e.g. {"Best"} or {"Best", "Worst"}.
// * For now, only one array is returned.
// *
// * @return a list of String arrays describing the selected plot options
// */
// public ArrayList<String[]> getPlotDescriptions() {
// ArrayList<String> desc = new ArrayList<String>();
// for (int i=0; i<graphSel.getLength(); i++) {
// if (graphSel.isSelected(i)) desc.add(graphSel.getElement(i));
// }
// ArrayList<String[]> alist = new ArrayList<String[]>();
// alist.add(desc.toArray(new String[desc.size()]));
// return alist;
// }
/**
*
*/
public void saveInstance() {
Serializer.storeObject("Statistics.ser", this);
}
try {
FileOutputStream fileStream = new FileOutputStream("Statistics.ser");
Serializer.storeObject(fileStream, this);
} catch (FileNotFoundException ex) {
LOGGER.log(Level.WARNING, "Could not store instance object.", ex);
}
}
/**
*

View File

@ -1,15 +1,8 @@
package eva2.tools;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This class defines utility routines that use Java serialization. Any
@ -19,6 +12,16 @@ import java.io.Serializable;
* @author Holger Ulmer, Felix Streichert, Hannes Planatscher, Marcel Kronfeld
**/
public class Serializer {
/**
* The logging instance for this class.
*/
private static final Logger LOGGER = Logger.getLogger(eva2.EvAInfo.defaultLogger);
/**
* Private constructor to prevent instantiating module class.
*/
private Serializer() { }
/**
* Serialize the object o (and any Serializable objects it refers to) and
* store its serialized state in File f. If serializeInMem is true, the object
@ -26,49 +29,41 @@ public class Serializer {
* writing a nested object directly to a file.
*
* @param o the object to write
* @param f the file to write to
* @param outStream The stream to write to
* @param serializeInMem flag whether to wrap the object in a SerializedObject
* @throws IOException
**/
static public void store(Serializable o, File f, boolean serializeInMem) throws IOException {
FileOutputStream file = new FileOutputStream(f);
ObjectOutputStream out = new ObjectOutputStream(file);
private static void store(Serializable o, OutputStream outStream, boolean serializeInMem) throws IOException {
ObjectOutputStream out = new ObjectOutputStream(outStream);
try {
Object objToStore = o;
if (serializeInMem) objToStore = new SerializedObject((Object)o);
// System.out.println("Writing " + o.getClass());
if (serializeInMem) {
objToStore = new SerializedObject((Object) o);
}
out.writeObject(objToStore);
} catch (java.io.NotSerializableException e) {
System.err.println("Error: Object " + o.getClass() + " is not serializable - run settings cannot be stored.");
e.printStackTrace();
} catch (java.io.NotSerializableException ex) {
LOGGER.log(Level.SEVERE, "Object is not serializable!", ex);
}
out.flush();
out.close();
file.close();
}
// try {
// FileOutputStream OutStream = new FileOutputStream("ESPara.ser");
// ObjectOutputStream OutObjectStream = new ObjectOutputStream (OutStream);
// OutObjectStream.writeObject(this);
// OutObjectStream.flush();
// OutStream.close();
// } catch (Exception e) {
// System.out.println ("ERROR ESPara.ser"+e.getMessage());
// }
/**
* Deserialize the contents of File f and return the resulting object.
* A SerializedObject is unwrapped once.
*
* @param inputStream The Input stream to read from
* @throws ClassNotFoundException
* @throws IOException
* @return The deserialized Object from the file
**/
static public Object load(File f) throws IOException, ClassNotFoundException {
FileInputStream file = new FileInputStream(f);
ObjectInputStream in = new ObjectInputStream(file);
Object ret = in.readObject();
private static Object load(final InputStream inputStream) throws IOException, ClassNotFoundException {
ObjectInputStream objInputStream = new ObjectInputStream(inputStream);
Object ret = objInputStream.readObject();
if (ret instanceof SerializedObject) {
ret = ((SerializedObject)ret).getObject();
ret = ((SerializedObject) ret).getObject();
}
in.close();
file.close();
objInputStream.close();
return ret;
}
@ -92,98 +87,59 @@ public class Serializer {
// Make an input stream from the byte array and read
// a copy of the object back in.
ObjectInputStream in = new ObjectInputStream(
ObjectInputStream inputStream = new ObjectInputStream(
new ByteArrayInputStream(bos.toByteArray()));
obj = in.readObject();
}
catch(IOException e) {
e.printStackTrace();
}
catch(ClassNotFoundException cnfe) {
cnfe.printStackTrace();
obj = inputStream.readObject();
} catch (IOException ex) {
LOGGER.log(Level.WARNING, "Error while cloning object.", ex);
} catch (ClassNotFoundException ex) {
LOGGER.log(Level.WARNING, "Object class was not found.", ex);
}
return obj;
}
/**
* This is a simple serializable data structure that we use below for
* testing the methods above
**/
static class ExampleDataStruct implements Serializable {
String message;
int[] data;
ExampleDataStruct other;
public String toString() {
String s = message;
for(int i = 0; i < data.length; i++)
s += " " + data[i];
if (other != null) s += "\n\t" + other.toString();
return s;
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
// Create a simple object graph
ExampleDataStruct ds = new ExampleDataStruct();
ds.message = "hello world";
ds.data = new int[] { 1, 2, 3, 4 };
ds.other = new ExampleDataStruct();
ds.other.message = "nested structure";
ds.other.data = new int[] { 9, 8, 7 };
// Display the original object graph
System.out.println("Original data structure: " + ds);
// Output it to a file
File f = new File("datastructure.ser");
System.out.println("Storing to a file...");
Serializer.store(ds, f, true);
// Read it back from the file, and display it again
ds = (ExampleDataStruct) Serializer.load(f);
System.out.println("Read from the file: " + ds);
// Create a deep clone and display that. After making the copy
// modify the original to prove that the clone is "deep".
ExampleDataStruct ds2 = (ExampleDataStruct) Serializer.deepClone(ds);
ds.other.message = null; ds.other.data = null; // Change original
System.out.println("Deep clone: " + ds2);
}
/**
* Serialize the string s and
* store its serialized state in File with name Filename.
*
* @param filename The file
* @param data The string data
**/
public static void storeString (String Filename,String s) {
public static void storeString(final OutputStream outStream, final String data) {
try {
store(s, new File(Filename), false);
} catch (Exception e) {
System.out.println("ERROR writing string File "+Filename+ " String "+s);
store(data, outStream, false);
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, "Could not write string to stream", ex);
}
}
/**
* Deserialize the contents of File f containing
* Deserialize the contents of File filename containing
* a string and return the resulting string.
*
* @param filename The file
* @return The deserialized data from the file
**/
public static String loadString (String Filename) {
String s = null;
public static String loadString(final InputStream inputStream) {
String data = null;
try {
s=(String)load(new File(Filename));
} catch (Exception e) {
// System.out.println("WARNING: Loading string File "+Filename+ " not possible !!");
data = (String) load(inputStream);
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, "Could not load string from file!", ex);
}
return s;
return data;
}
/**
* Serialize the string s and
* store its serialized state in File with name Filename.
**/
public static File storeObject (String Filename,Serializable s) {
File ret = new File(Filename);
public static void storeObject(OutputStream outStream, Serializable s) {
try {
store(s, ret, true);
} catch (Exception e) {
System.err.println("ERROR writing Object File "+Filename+ " String "+s);
System.err.println(e.getMessage());
e.printStackTrace();
store(s, outStream, true);
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, "Could not write object to stream.", ex);
}
return ret;
}
/**
@ -191,8 +147,8 @@ public class Serializer {
* a string and return the resulting string. If the indicated file
* doesnt exist or an error occurs, null is returned.
**/
public static Object loadObject (String Filename) {
return loadObject(Filename, true);
public static Object loadObject (InputStream inputStream) {
return loadObject(inputStream, true);
}
/**
@ -202,27 +158,23 @@ public class Serializer {
* If casually is false, an error message is printed and an exception
* is raised if the file was not found or an error occured on loading.
**/
public static Object loadObject (String Filename, boolean casually) {
Object s = null;
File f = new File(Filename);
if (f.exists()) {
try {
s=(Object)load(f);
} catch (InvalidClassException e) {
System.err.println("WARNING: loading object File "+Filename+ " not possible, this may happen on source code changes.");
System.err.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.err.println("ClassNotFoundException on loading object File " + Filename + ". This may happen on refactorings.");
System.err.println(e.getMessage());
} catch (Exception e) {
if (!casually) throw new RuntimeException("WARNING: loading object File "+Filename+ " not possible! ("+e.getMessage()+")");
else return null;
}
return s;
} else {
if (!casually) System.err.println("Error in Serializer: file " + Filename + " not found!");
return null;
}
public static Object loadObject (InputStream inputStream, boolean casually) {
Object serializedObject = null;
try {
serializedObject = (Object) load(inputStream);
} catch (InvalidClassException ex) {
LOGGER.log(Level.WARNING, "Could not load object file.", ex);
} catch (ClassNotFoundException ex) {
LOGGER.log(Level.WARNING, "Matching object class could not be found.", ex);
} catch (Exception ex) {
if (!casually) {
throw new RuntimeException("WARNING: loading object is not possible! (" + ex.getMessage() + ")");
} else {
return null;
}
}
return serializedObject;
}
}

View File

@ -22,6 +22,9 @@ import java.util.Properties;
import java.util.StringTokenizer;
import eva2.tools.Serializer;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.AccessControlException;
import java.util.logging.Level;
import java.util.logging.Logger;
@ -31,7 +34,7 @@ import java.util.logging.Logger;
*
*/
public class ComAdapter {
private static final Logger logger = Logger.getLogger(eva2.EvAInfo.defaultLogger);
private static final Logger LOGGER = Logger.getLogger(eva2.EvAInfo.defaultLogger);
public static final int PORT = 1099;
public static final String SEP = "_";
static protected ComAdapter m_instance = null;
@ -68,7 +71,7 @@ public class ComAdapter {
/* This exception is expected to happen when
* we are using Java WebStart.
*/
logger.log(Level.INFO, "Username set to: WebStart", ex);
LOGGER.log(Level.INFO, "Username set to: WebStart", ex);
userName = "Webstart";
}
hostName = "localhost"; //"192.168.0.1";
@ -100,7 +103,7 @@ public class ComAdapter {
if (!m_HostNameList.contains(current)) {
m_HostNameList.add(current);
} else {
logger.log(Level.FINER, "Server " + current + " was already in list");
LOGGER.log(Level.FINER, "Server " + current + " was already in list");
}
}
}
@ -172,7 +175,7 @@ public class ComAdapter {
cnt++;
ret = getConnection(hostName).getRMIThreadHandler(c);
if (ret == null) {
logger.log(Level.WARNING, "Error in getRMIThreadHandler");
LOGGER.log(Level.WARNING, "Error in getRMIThreadHandler");
}
}
return ret;
@ -206,7 +209,7 @@ public class ComAdapter {
while (m_AvailableHostNameList.size() == 0) {
evalAvailableHostNameList();
if (m_AvailableHostNameList.size() == 0) {
logger.log(Level.WARNING, "No host availabe waiting..");
LOGGER.log(Level.WARNING, "No host availabe waiting..");
}
m_ownHostIndex = 0;
}
@ -267,7 +270,7 @@ public class ComAdapter {
String testurl = (String) m_HostNameList.get(i);
for (int j = 1; j < 3; j++) {
if (rmiPing(testurl + "_" + j) == true) {
logger.log(Level.INFO, "Found EvAServer on: " + testurl);
LOGGER.log(Level.INFO, "Found EvAServer on: " + testurl);
m_AvailableHostNameList.add(testurl + "_" + j);
}
}
@ -297,18 +300,30 @@ public class ComAdapter {
}
/**
*
* Returns the current hostName set for the adapter.
*
* @return The current hostName.
*/
public String getHostName() {
return hostName;
}
/**
*
* Sets hostName and writes it to a file.
*
* @param newHost The new hostName.
*/
public void setHostName(String newHost) {
public void setHostName(final String newHost) {
hostName = newHost;
Serializer.storeString("hostname.ser", hostName);
try {
FileOutputStream fileStream = new FileOutputStream("hostname.ser");
Serializer.storeString(fileStream, hostName);
fileStream.close();
} catch (FileNotFoundException ex) {
LOGGER.log(Level.WARNING, "Could not write hostname to file.", ex);
} catch (IOException ex) {
LOGGER.log(Level.WARNING, "Error writing hostname to file.", ex);
}
}
@ -327,7 +342,7 @@ public class ComAdapter {
}
String MainAdapterName = userName + MainAdapterImpl.MAIN_ADAPTER_NAME + Number; // attention
logger.info("RMIConnect to " + HostToConnect);
LOGGER.info("RMIConnect to " + HostToConnect);
MainAdapter MainRemoteObject = null;
try {
RMIInvocationHandler invocHandler = (RMIInvocationHandler) Naming.lookup(
@ -336,13 +351,13 @@ public class ComAdapter {
MainRemoteObject = getMainAdapter(invocHandler);
MainRemoteObject.setBuf("Ok.");
logger.info("RMIConnect " + MainRemoteObject.getBuf());
LOGGER.info("RMIConnect " + MainRemoteObject.getBuf());
} catch (MalformedURLException ex) {
logger.log(Level.WARNING, "MalformedURLException: Error while looking up " + ex.getMessage(), ex);
LOGGER.log(Level.WARNING, "MalformedURLException: Error while looking up " + ex.getMessage(), ex);
} catch (NotBoundException ex) {
logger.log(Level.WARNING, "NotBoundException: Error while looking up " + ex.getMessage(), ex);
LOGGER.log(Level.WARNING, "NotBoundException: Error while looking up " + ex.getMessage(), ex);
} catch (RemoteException ex) {
logger.log(Level.WARNING, "Error while connecting Host: " + HostToConnect, ex);
LOGGER.log(Level.WARNING, "Error while connecting Host: " + HostToConnect, ex);
return null;
}
return MainRemoteObject;
@ -394,7 +409,7 @@ public class ComAdapter {
Host + ":" + MainAdapterImpl.PORT + "/" + mainAdapterName); // attention !!
Test = (MainAdapter) x.getWrapper();
} catch (Exception ex) {
logger.log(Level.INFO, "No connection to : " + testurl, ex);
LOGGER.log(Level.INFO, "No connection to : " + testurl, ex);
return false;
}
return true;