This error is produced by launching the jar file in cmd with "G:\Orchid\OrchidFX.jar". When launching the application through IntelliJ everything runs just fine. Also, in File->ProjectStructure we have added sqljdbc4.jar to the library.
The Error:
javafx.fxml.LoadException:
file:/G:/Orchid/OrchidFX.jar!/DatabaseSettingsForm.fxml
at javafx.fxml.FXMLLoader.constructLoadException(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.load(Unknown Source)
at fxproject.ApplicationSplashScreen.loadDatabaseScreen(ApplicationSplashScreen.java:35)
at fxproject.ApplicationSplashScreen.start(ApplicationSplashScreen.java:26)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.Trampoline.invoke(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
... 19 more
Caused by: java.lang.NoClassDefFoundError: com/microsoft/sqlserver/jdbc/SQLServerDataSource
at fxproject.OrchidDataSource.setDataSourceSettings(OrchidDataSource.java:56)
at fxproject.OrchidDataSource.<init>(OrchidDataSource.java:50)
at DataSettingsController.initialize(DataSettingsController.java:34)
... 28 more
Caused by: java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDataSource
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)
... 31 more
OrchidDataSource.java:
package fxproject;
import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
public class OrchidDataSource
{
private final String driverType = "jdbc";
private final String dbmsType = "sqlserver";
private String hostname = "192.168.1.173";
private int portNumber = 1433;
private String databaseName = "OrchidDB";
private final String propertyValue = "user=Blah;password=blahblah";
private String username = "blah"; //andrew
private String password = "password";
public String getHostname()
{
return hostname;
}
public int getPortNumber()
{
return portNumber;
}
public String getUsername()
{
return username;
}
public String getPassword()
{
return password;
}
public String getDatabaseName()
{
return databaseName;
}
private SQLServerDataSource dataSource;
private static OrchidDataSource orchidDataSource;
public OrchidDataSource()
{
setDataSourceSettings();
setCurrentDataSource(this);
}
private void setDataSourceSettings()
{
dataSource = new SQLServerDataSource();
dataSource.setUser(username);
dataSource.setPassword(password);
dataSource.setServerName(hostname);
dataSource.setPortNumber(portNumber);
dataSource.setDatabaseName(databaseName);
}
public void setDataSourceSettings(String username, String password, String hostname, int portNumber, String databaseName)
{
this.username = username;
this.password = password;
this.hostname = hostname;
this.portNumber = portNumber;
this.databaseName = databaseName;
setDataSourceSettings();
}
public void setCurrentDataSource(OrchidDataSource orchidDataSource)
{
this.orchidDataSource = orchidDataSource;
}
public static OrchidDataSource getCurrentDataSource()
{
return orchidDataSource;
}
public Connection getConnection() throws SQLException
{
return dataSource.getConnection();
}
}
DataSettingsController:
package fxproject;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import java.sql.Connection;
public class DataSettingsController
{
public static final String VIEWCONTROLLER_TITLE= "DataSettings";
#FXML
TextField fieldhostname;
#FXML
TextField fieldportnumber;
#FXML
TextField fielddatabasename;
#FXML
TextField fieldusername;
#FXML
PasswordField fieldpassword;
public DataSettingsController()
{
}
#FXML
public void initialize()
{
OrchidDataSource dataSource = new OrchidDataSource();
fieldhostname.setText(dataSource.getHostname());
fieldportnumber.setText(String.valueOf(dataSource.getPortNumber()));
fielddatabasename.setText(dataSource.getDatabaseName());
fieldusername.setText(dataSource.getUsername());
fieldpassword.setText(dataSource.getPassword());
}
#FXML
protected void handleButtonSubmit(ActionEvent e)
{
try
{
OrchidDataSource dataSource = new OrchidDataSource();
dataSource.setDataSourceSettings(fieldusername.getText(),
fieldpassword.getText(),
fieldhostname.getText(),
Integer.parseInt(fieldportnumber.getText()),
fielddatabasename.getText());
Connection connection = OrchidDataSource.getCurrentDataSource().getConnection();
connection.prepareStatement("{call SelectClientStatus()}").executeQuery(); ///low data query to test connection
new MainSystem();
Node source = (Node) e.getSource();
Stage stage = (Stage) source.getScene().getWindow();
stage.close();
}
catch(Exception ae)
{
new OrchidAlertBox("Error", "Database cannot be reached.");
}
}
}
Related
I want to use JAAS authentication for my Web application. I can't figure out where the error lies. I don't get any error messages but the login part is not working.
I have a Html page (index.html) as front page. When logging in it get username and password and takes it to the servlet.
index.html
<html>
<head>
<title>Login
</title>
</head>
<body>
<br><br>
<center>
<h1>Railway Reservation</h1>
<br><br>
<form action="Authentication" method="post">
User Name:<input type="text" name="user"><br><br>
Password:<input type="password" name="pass"><br><br>
<input type="submit" value="Login">
</form>
</center>
</body>
</html>
Authentication.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import javax.security.auth.login.*;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
public class Authentication extends HttpServlet
{
public Authentication()
{
super();
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("hiii");
String user = request.getParameter("user");
String password = request.getParameter("pass");
pw.println(user + " " + password );
if((user!=null)&&(password!=null))
{
pw.println("if");
CBHandler cbhandler = new CBHandler(user,password);
boolean authFlag = true;
try
{
HttpSession session = request.getSession();
session.setAttribute("username",user);
pw.println("inside try block");
System.setProperty("java.security.auth.login.config","jaas.config");
LoginContext loginContext = new LoginContext("Railway",cbhandler);
loginContext.login();
pw.println("try ");
}
catch(LoginException e)
{
pw.println(e);
e.printStackTrace();
authFlag = false;
pw.println("hello");
}
if(authFlag)
{
pw.println(user + " " + password);
pw.println("Authentication success...");
Connection con = DB.getDBconnection();
if(con!=null)
{
String sql = "select role from login where uname=?";
try
{
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1,user);
ResultSet rs = pst.executeQuery();
rs.next();
String role = rs.getString("role");
if(role.equals("user"))
response.sendRedirect("user.jsp");
else
response.sendRedirect("admin.jsp");
}
catch(Exception e)
{
pw.println(e);
}
}
}
else
pw.println("Authentication failed...");
}
else
{
pw.println("Invalid authentication...");
}
}
}
CBHandler.java
import java.io.*;
import javax.security.auth.callback.*;
public class CBHandler implements CallbackHandler
{
private String user = null;
private String password = null;
public CBHandler(String user,String password)
{
this.user = user;
this.password = password;
}
#Override
public void handle(Callback[] callbackArray) throws IOException,UnsupportedCallbackException
{
int counter = 0;
while(counter < callbackArray.length)
{
if(callbackArray[counter] instanceof NameCallback)
{
NameCallback nameCallback = (NameCallback)callbackArray[counter++];
nameCallback.setName(user);
}
else if(callbackArray[counter] instanceof PasswordCallback)
{
PasswordCallback passwordCallback = (PasswordCallback)callbackArray[counter++];
passwordCallback.setPassword(password.toCharArray());
}
}
}
}
LoginMod.java
import java.util.*;
import java.sql.*;
import java.io.*;
import javax.security.auth.Subject;
import javax.security.auth.callback.*;
import javax.security.auth.login.* ;
import javax.security.auth.spi.LoginModule;
public class LoginMod implements LoginModule
{
private CallbackHandler callbackHandler = null;
private boolean successFlag = false;
#Override
public void initialize(Subject subject, CallbackHandler callbackHandler,Map<String,?> sharedState,Map<String,?> options)
{
this.callbackHandler = callbackHandler;
}
#Override
public boolean login() throws LoginException
{
Callback[] callbackArray = new Callback[2];
callbackArray[0] = new NameCallback("User Name: ");
callbackArray[1] = new PasswordCallback("Password : ",false);
try
{
callbackHandler.handle(callbackArray);
}
catch(IOException e)
{
e.printStackTrace();
}
catch(UnsupportedCallbackException e)
{
e.printStackTrace();
}
String name = ((NameCallback) callbackArray[0]).getName();
String password = new String(((PasswordCallback) callbackArray[1]).getPassword());
if((name.equals("root"))&&(password.equals("root")))
{
System.out.println("auth success");
successFlag = true;
}
else
{
successFlag = false;
throw new FailedLoginException ("auth failed");
}
return successFlag;
}
#Override
public boolean commit() throws LoginException
{
return successFlag;
}
#Override
public boolean abort() throws LoginException
{
return false;
}
#Override
public boolean logout() throws LoginException
{
return false;
}
}
jaas.config
Railway
{
LoginMod required debug=true;
};
When I run this code I get this as Output
hiii root root if inside try block
This is the error I get
HTTP Status 500 – Internal Server Error
Type Exception Report
Message java.io.IOException: jaas.config (No such file or directory)
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
java.lang.SecurityException: java.io.IOException: jaas.config (No such file or directory)
sun.security.provider.ConfigFile$Spi.<init>(Unknown Source)
sun.security.provider.ConfigFile.<init>(Unknown Source)
sun.reflect.GeneratedConstructorAccessor23.newInstance(Unknown Source)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
java.lang.reflect.Constructor.newInstance(Unknown Source)
java.lang.Class.newInstance(Unknown Source)
javax.security.auth.login.Configuration$2.run(Unknown Source)
javax.security.auth.login.Configuration$2.run(Unknown Source)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.login.Configuration.getConfiguration(Unknown Source)
javax.security.auth.login.LoginContext$1.run(Unknown Source)
javax.security.auth.login.LoginContext$1.run(Unknown Source)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.login.LoginContext.init(Unknown Source)
javax.security.auth.login.LoginContext.<init>(Unknown Source)
Authentication.doPost(Authentication.java:37)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.io.IOException: jaas.config (No such file or directory)
sun.security.provider.ConfigFile$Spi.ioException(Unknown Source)
sun.security.provider.ConfigFile$Spi.init(Unknown Source)
sun.security.provider.ConfigFile$Spi.<init>(Unknown Source)
sun.security.provider.ConfigFile.<init>(Unknown Source)
sun.reflect.GeneratedConstructorAccessor23.newInstance(Unknown Source)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
java.lang.reflect.Constructor.newInstance(Unknown Source)
java.lang.Class.newInstance(Unknown Source)
javax.security.auth.login.Configuration$2.run(Unknown Source)
javax.security.auth.login.Configuration$2.run(Unknown Source)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.login.Configuration.getConfiguration(Unknown Source)
javax.security.auth.login.LoginContext$1.run(Unknown Source)
javax.security.auth.login.LoginContext$1.run(Unknown Source)
java.security.AccessController.doPrivileged(Native Method)
javax.security.auth.login.LoginContext.init(Unknown Source)
javax.security.auth.login.LoginContext.<init>(Unknown Source)
Authentication.doPost(Authentication.java:37)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
The place I was going wrong was giving the location of the configuration file in java.security file, which is present in C:\Program Files\Java\jre1.8.0_77\lib\security\java.security.
When copying the path of the jaas.config file in Windows the path is given with backward slashes( / ), which should be replaced with forward slashes( \ ).
For example, it should be like login.config.url.1=file:D:/mani/java/sample_jaas.config and not as login.config.url.1=file:D:\mani\java\sample_jaas.config
I guess it will be helpful for someone.
I wrote a code which gives a Java null pointer exception in JavaFX8. There are two classes: one that does a processing to an image Mat and another one that shows the image processed, in a different window. The code is:
public class ImagineComprimata
{
public Mat imComp;
#FXML
private ImageView imagineCompresata;
#FXML
private Button bSalveaza;
#FXML
private TextArea campRC;
#FXML
private TextArea campEMP;
#FXML
public void salveaza(ActionEvent eveniment)
{
//this will be edited later
}
public void arata() throws IOException
{
Stage scena = new Stage();
FXMLLoader fl = new FXMLLoader(getClass().getResource("/fxml/ImagineComprimata.fxml"));
AnchorPane p = (AnchorPane) fl.load();
Scene s = new Scene(p, 742, 495);
scena.setScene(s);
scena.showAndWait();
}
public void setMat(Mat imagine)
{
this.imComp = imagine;
}
public void setImagineCompresata(Image imagine)
{
this.imagineCompresata.setImage(imagine);
}
}
Now in the main window from which i make a call of this class to be displayed on screen:
public class Compresia
{
private Mat imagine;
private int parametru;
#FXML
public Button bSelecteaza;
#FXML
public Button bComprima;
#FXML
public Button bIntrodu;
#FXML
private ImageView foto;
#FXML
private TextField valoarea;
private String denumireFotografie;
private Matrix[] desc;
#FXML
public TextArea campRang;
private int rang;
#FXML
public void comprima(ActionEvent eveniment) throws InterruptedException, IOException
{
if (imagine == null)
{
Notificare.informeaza("Notificare", "Nu ai selectat o imagine!");
}
else
{
double[][] mc = AlgoritmDeCompresie.comprimaImaginea(desc, Util.extragereValori(imagine), parametru);
Mat im = Util.construiesteImagine(mc);
ImagineComprimata ic = new ImagineComprimata();
ic.setMat(im);
ic.setImagineCompresata(Util.conversieMat2Image(im));
ic.arata();
}
}
#FXML
public void cautaFisier(ActionEvent eveniment) throws InterruptedException
{
Matrix[] desc;
Mat im;
String denumire;
FileChooser f = new FileChooser();
File fotoSelectat = f.showOpenDialog(null);
if (fotoSelectat != null)
{
denumire = fotoSelectat.getPath();
im = Highgui.imread(denumire);
Imgproc.cvtColor(im, im, Imgproc.COLOR_BGR2GRAY);
this.desc = AlgoritmDeCompresie.descompune(Util.extragereValori(im));//////
rang = Util.returneazaRangul(Util.extragereValori(im));
imagine = im;
campRang.setText(Integer.toString(rang));
foto.setImage(Util.conversieMat2Image(im));
}
}
#FXML
public void seteazaParametru(ActionEvent eveniment)
{
int p = Integer.parseInt(this.valoarea.getText());
if (p >= this.rang)
{
Notificare.informeaza("Notificare", "Introdu un parametru mai mic decat rangul!");
this.valoarea.setText(null);
}
else
{
this.parametru = p;
Notificare.informeaza("Notificare", "parametru setat :" + p);
}
///////////////
}
public void start() throws Exception
{
Stage scena = new Stage();
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Compresia.fxml"));
AnchorPane b = (AnchorPane) loader.load();
Scene s = new Scene(b, 955, 586);
scena.setScene(s);
scena.setTitle("Compresie");
scena.setResizable(false);
scena.show();
}
public Matrix[] getDescompunere()
{
return this.desc;
}
public void setDescompunere(Matrix[] descompunere)
{
this.desc = descompunere;
}
}
It gives me an error at setImageCompressed(im) which traces to the setImageCompressed(Mat im). ImageCompressed is the JavaFX controller which shows the image proccessed. Where did I do wrong? The error report looks like this:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(Unknown Source)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Node.fireEvent(Unknown Source)
at javafx.scene.control.Button.fire(Unknown Source)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1500(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$355(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$149(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.Trampoline.invoke(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
... 49 more
Caused by: java.lang.NullPointerException
at interfata.ImagineComprimata.setImagineCompresata(ImagineComprimata.java:56)
at interfata.Compresia.comprima(Compresia.java:66)
... 58 more
It may be the case that "private ImageView imagineCompresata" instance of ImagineComprimata class is not getting initialized and remains pointing to a null , as a result of which when you are calling this.imagineCompresata.setImage(imagine) a NullPointerException is being raised.
Fixed, per Engineer Dollery's answer, solution at bottom.
The goal is to serialize the network field of class Network. Sorry for the naming.
I had this, which compiled, and serialized properly.
public class Network {
private HashMap<String, HashMap<String, Number>> network;
...
public void load(String networkFile) throws Exception{
network = (HashMap<String, HashMap<String, Number>>)Utility.deserialize(Utility.load(networkFile));
}
public void save(String networkFile) throws Exception{
Utility.save(networkFile, Utility.serialize(network));
}
}
class Number implements Serializable {
...
}
I changed it to this generic version, which compiles, but no longer serializes. I need someway to specify that HashMap of T and Number is serializable.
public class Network<T extends Serializable> {
private HashMap<T, HashMap<T, Number>> network;
...
public void load(String networkFile) throws Exception{
network = (HashMap<T, HashMap<T, Number>>)Utility.deserialize(Utility.load(networkFile));
}
public void save(String networkFile) throws Exception{
Utility.save(networkFile, Utility.serialize(network));
}
}
class Number implements Serializable {
...
}
And this is the code for serialization
package Bullib;
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class Utility{
public static Pattern phrasePattern = Pattern.compile("[^;:!.?]+");
public static Pattern wordPattern = Pattern.compile("['A-Za-z]+");
public static Object deserialize(byte[] serialized) throws Exception {
ByteArrayInputStream bi = new ByteArrayInputStream(serialized);
ObjectInputStream si = new ObjectInputStream(bi);
return si.readObject();
}
public static byte[] serialize(Object target) throws Exception {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream so = new ObjectOutputStream(bo);
so.writeObject(target);
so.flush();
return bo.toByteArray();
}
public static byte[] load(String filename) throws Exception {
RandomAccessFile file = new RandomAccessFile(new File(filename), "r");
byte[] b = new byte[(int)file.length()];
file.read(b);
file.close();
return b;
}
public static void save(String filename, byte[] value) throws Exception {
RandomAccessFile file = new RandomAccessFile(new File(filename), "rw");
file.write(value);
file.close();
}
public static Collection<String> executeRegex(Pattern pattern, String text){
LinkedList<String> matches = new LinkedList<String>();
Matcher m = pattern.matcher(text);
while (m.find()) {
matches.add(m.group(0));
}
return matches;
}
}
This is the error I get back when trying to serialize with T as either String or Double
Exception in thread "main" java.io.NotSerializableException: Bullib.Network.Netw
ork
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at Bullib.Utility.serialize(Utility.java:21)
at Bullib.Network.Network.save(Network.java:88)
at Engine.save(Engine.java:63)
at Engine.main(Engine.java:88)
Per requests, an example test and error. As you can see, it produces the same exception as above. I've updated the test to show that it passes if nothing is added to the map, and fails otherwise.
public static void main(String[] args) throws Exception{
Network<String> stringtest = new Network<String>("","","");
stringtest.save("testempty");
stringtest.load("testempty");
System.out.println("passed empty");
stringtest.placeAndMove("fill",0.0);
stringtest.save("testfilled");
stringtest.load("testfilled");
System.out.println("passed filled");
}
java: Bullib/Network/Network
passed empty
Exception in thread "main" java.io.NotSerializableException: Bullib.Network.Netw
ork
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at java.util.HashMap.writeObject(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at Bullib.Utility.serialize(Utility.java:21)
at Bullib.Network.Network.save(Network.java:88)
at Bullib.Network.Network.main(Network.java:108)
The solution is to change
public class Network<T extends Serializable> {
private HashMap<T, HashMap<T, Number>> network;
...
public void load(String networkFile) throws Exception{
network = (HashMap<T, HashMap<T, Number>>)Utility.deserialize(Utility.load(networkFile));
}
public void save(String networkFile) throws Exception{
Utility.save(networkFile, Utility.serialize(network));
}
}
class Number implements Serializable {
...
}
to
public class Network<T extends Serializable> implements Serializable {
private HashMap<T, HashMap<T, Number>> network;
...
public void load(String networkFile) throws Exception{
network = (HashMap<T, HashMap<T, Number>>)Utility.deserialize(Utility.load(networkFile));
}
public void save(String networkFile) throws Exception{
Utility.save(networkFile, Utility.serialize(network));
}
}
class Number implements Serializable {
...
}
Try this:
public class Network implements Serializable
I'm using Rhino 1.7 R4 with envjs 1.2 on Mac OSX with JDK 1.6.0_33
If I run:
java -jar rhino-1.7R4.jar -opt -1
And then:
load('env.rhino-1.2.js')
Then the script is loaded successfully.
When I load the same JS script from Java via RhinoTest.java:
import org.apache.commons.io.IOUtils;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextAction;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.tools.shell.Main;
import org.mozilla.javascript.tools.shell.ShellContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class RhinoTest {
static final Logger LOGGER = LoggerFactory.getLogger(RhinoTest.class);
static private Scriptable SCRIPTABLE;
static private List<Script> scripts;
public static void main(String[] args) {
ShellContextFactory cxFactory = Main.shellContextFactory;
cxFactory.call(new ContextAction() {
#Override
public Object run(Context cx) {
final Initiator initiator = new Initiator(cx).init();
LOGGER.trace("Run script");
try {
return initiator.execute();
} finally {
}
}
class Initiator {
Initiator(Context context) {
this.cx = context;
}
Initiator init() {
if (SCRIPTABLE == null)
createScriptable();
initContext();
return this;
}
Object execute() {
return null;
}
void createScriptable() {
LOGGER.trace("init standard objects");
SCRIPTABLE = cx.initStandardObjects();
LOGGER.trace("set optimization level to -1");
cx.setOptimizationLevel(-1);// bypass the 64k limit // interpretive mode
attachJs("env.rhino-1.2.js");
LOGGER.trace("set optimization level to 9");
cx.setOptimizationLevel(9);
}
#SuppressWarnings("deprecation")
private void attachJs(String jsFileName) {
InputStream in = null;
InputStreamReader reader = null;
if (LOGGER.isDebugEnabled()) LOGGER.debug("loading " + jsFileName);
try {
in = RhinoTest.class.getResourceAsStream(jsFileName);
if (in == null)
throw new RuntimeException("cannot find js file : " + jsFileName);
reader = new InputStreamReader(in);
if (scripts == null)
scripts = new ArrayList<Script>();
scripts.add(cx.compileReader(SCRIPTABLE, reader, jsFileName, 1, null));
if (LOGGER.isDebugEnabled()) LOGGER.debug("loaded " + jsFileName);
} catch (IOException e) {
throw new RuntimeException("cannot load js file : " + jsFileName, e);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(reader);
}
}
void initContext() {
LOGGER.trace("set optimization level to -1");
cx.setOptimizationLevel(-1);// bypass the 64k limit // interpretive mode
for (Script s : scripts) {
s.exec(cx, SCRIPTABLE);
}
}
private final Context cx;
}
});
}
}
I get:
Exception in thread "main" org.mozilla.javascript.EvaluatorException: missing : after property id (env.rhino-1.2.js#2121)
at org.mozilla.javascript.DefaultErrorReporter.runtimeError(Unknown Source)
at org.mozilla.javascript.DefaultErrorReporter.error(Unknown Source)
at org.mozilla.javascript.Parser.addError(Unknown Source)
at org.mozilla.javascript.Parser.reportError(Unknown Source)
at org.mozilla.javascript.Parser.mustMatchToken(Unknown Source)
at org.mozilla.javascript.Parser.primaryExpr(Unknown Source)
at org.mozilla.javascript.Parser.memberExpr(Unknown Source)
at org.mozilla.javascript.Parser.unaryExpr(Unknown Source)
at org.mozilla.javascript.Parser.mulExpr(Unknown Source)
at org.mozilla.javascript.Parser.addExpr(Unknown Source)
at org.mozilla.javascript.Parser.shiftExpr(Unknown Source)
at org.mozilla.javascript.Parser.relExpr(Unknown Source)
at org.mozilla.javascript.Parser.eqExpr(Unknown Source)
at org.mozilla.javascript.Parser.bitAndExpr(Unknown Source)
at org.mozilla.javascript.Parser.bitXorExpr(Unknown Source)
at org.mozilla.javascript.Parser.bitOrExpr(Unknown Source)
at org.mozilla.javascript.Parser.andExpr(Unknown Source)
at org.mozilla.javascript.Parser.orExpr(Unknown Source)
at org.mozilla.javascript.Parser.condExpr(Unknown Source)
at org.mozilla.javascript.Parser.assignExpr(Unknown Source)
at org.mozilla.javascript.Parser.argumentList(Unknown Source)
at org.mozilla.javascript.Parser.memberExprTail(Unknown Source)
at org.mozilla.javascript.Parser.memberExpr(Unknown Source)
at org.mozilla.javascript.Parser.unaryExpr(Unknown Source)
at org.mozilla.javascript.Parser.mulExpr(Unknown Source)
at org.mozilla.javascript.Parser.addExpr(Unknown Source)
at org.mozilla.javascript.Parser.shiftExpr(Unknown Source)
at org.mozilla.javascript.Parser.relExpr(Unknown Source)
at org.mozilla.javascript.Parser.eqExpr(Unknown Source)
at org.mozilla.javascript.Parser.bitAndExpr(Unknown Source)
at org.mozilla.javascript.Parser.bitXorExpr(Unknown Source)
at org.mozilla.javascript.Parser.bitOrExpr(Unknown Source)
at org.mozilla.javascript.Parser.andExpr(Unknown Source)
at org.mozilla.javascript.Parser.orExpr(Unknown Source)
at org.mozilla.javascript.Parser.condExpr(Unknown Source)
at org.mozilla.javascript.Parser.assignExpr(Unknown Source)
at org.mozilla.javascript.Parser.expr(Unknown Source)
at org.mozilla.javascript.Parser.statementHelper(Unknown Source)
at org.mozilla.javascript.Parser.statement(Unknown Source)
at org.mozilla.javascript.Parser.parseFunctionBody(Unknown Source)
at org.mozilla.javascript.Parser.function(Unknown Source)
at org.mozilla.javascript.Parser.primaryExpr(Unknown Source)
at org.mozilla.javascript.Parser.memberExpr(Unknown Source)
at org.mozilla.javascript.Parser.unaryExpr(Unknown Source)
at org.mozilla.javascript.Parser.mulExpr(Unknown Source)
at org.mozilla.javascript.Parser.addExpr(Unknown Source)
at org.mozilla.javascript.Parser.shiftExpr(Unknown Source)
at org.mozilla.javascript.Parser.relExpr(Unknown Source)
at org.mozilla.javascript.Parser.eqExpr(Unknown Source)
at org.mozilla.javascript.Parser.bitAndExpr(Unknown Source)
at org.mozilla.javascript.Parser.bitXorExpr(Unknown Source)
at org.mozilla.javascript.Parser.bitOrExpr(Unknown Source)
at org.mozilla.javascript.Parser.andExpr(Unknown Source)
at org.mozilla.javascript.Parser.orExpr(Unknown Source)
at org.mozilla.javascript.Parser.condExpr(Unknown Source)
at org.mozilla.javascript.Parser.assignExpr(Unknown Source)
at org.mozilla.javascript.Parser.expr(Unknown Source)
at org.mozilla.javascript.Parser.primaryExpr(Unknown Source)
at org.mozilla.javascript.Parser.memberExpr(Unknown Source)
at org.mozilla.javascript.Parser.unaryExpr(Unknown Source)
at org.mozilla.javascript.Parser.mulExpr(Unknown Source)
at org.mozilla.javascript.Parser.addExpr(Unknown Source)
at org.mozilla.javascript.Parser.shiftExpr(Unknown Source)
at org.mozilla.javascript.Parser.relExpr(Unknown Source)
at org.mozilla.javascript.Parser.eqExpr(Unknown Source)
at org.mozilla.javascript.Parser.bitAndExpr(Unknown Source)
at org.mozilla.javascript.Parser.bitXorExpr(Unknown Source)
at org.mozilla.javascript.Parser.bitOrExpr(Unknown Source)
at org.mozilla.javascript.Parser.andExpr(Unknown Source)
at org.mozilla.javascript.Parser.orExpr(Unknown Source)
at org.mozilla.javascript.Parser.condExpr(Unknown Source)
at org.mozilla.javascript.Parser.assignExpr(Unknown Source)
at org.mozilla.javascript.Parser.expr(Unknown Source)
at org.mozilla.javascript.Parser.statementHelper(Unknown Source)
at org.mozilla.javascript.Parser.statement(Unknown Source)
at org.mozilla.javascript.Parser.parse(Unknown Source)
at org.mozilla.javascript.Parser.parse(Unknown Source)
at org.mozilla.javascript.Context.compileImpl(Unknown Source)
at org.mozilla.javascript.Context.compileReader(Unknown Source)
at org.mozilla.javascript.Context.compileReader(Unknown Source)
at RhinoTest$1$Initiator.attachJs(RhinoTest.java:85)
at RhinoTest$1$Initiator.createScriptable(RhinoTest.java:63)
at RhinoTest$1$Initiator.init(RhinoTest.java:44)
at RhinoTest$1.run(RhinoTest.java:28)
at org.mozilla.javascript.Context.call(Unknown Source)
at org.mozilla.javascript.ContextFactory.call(Unknown Source)
at RhinoTest.main(RhinoTest.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Please help
Wladimir,
You were right it was a version thing.
It turns out that the batik libs I imported included another version of rhino.
By excluding batik-js from my project for each batik dependency this issue went away.
This how I deserialize my arrayList which contains objects of identification
public void deserializeArrayList(){
String path = "./qbank/IdentificationHARD.quiz";
try{
FileInputStream fileIn = new FileInputStream(path);
ObjectInputStream in = new ObjectInputStream(fileIn);
ArrayList<Identification> list = (ArrayList<Identification>) in.readObject();
System.out.println(list);
}catch(Exception e){
e.printStackTrace();
}
}
This is how I serialize it
public void saveItemIdentification(ArrayList<Identification> identification,File file){
try{
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream(file));
out.writeObject(identification);
}catch(Exception e){
e.printStackTrace();
}
}
But when I deserialize it it gives me this errors
java.io.InvalidClassException: quizmaker.management.Identification; quizmaker.management.Identification; no valid constructor
at java.io.ObjectStreamClass.checkDeserialize(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at java.util.ArrayList.readObject(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at quizmaker.management.Manage.deserializeArrayList(Manage.java:92)
This is line 92
ArrayList<Identification> list = (ArrayList<Identification>) in.readObject();
Why is this happening?
This is the code of Identification Object.
package quizmaker.management;
import java.io.Serializable;
import quizmaker.Accounts.Rights.IAnswerable;
public class Identification extends Question implements Serializable{
private static final long serialVersionUID = 2L;
private String question;
private String answer;
public Identification(String q , String a){
super(q,a);
}
public String toString(){
return String.format("Question: %s\n Answer %s", getQuestion(),getAnswer());
}
}