Can someone help me here with my little Java/MySQL Database tool?
Part of the code is as follows, but when clicking on the createCustomerButton the DBMS tells me, that my syntax is somehow wrong.
protected static JTextField nachnameField = new JTextField();
protected static JTextField vornameField = new JTextField();
protected static JTextField postleitzahlField = new JTextField();
protected static JTextField strasseField = new JTextField();
protected static JTextField emailField = new JTextField();
protected static JTextField telefonField = new JTextField();
protected static JTextField zusatzinfoField = new JTextField();
static JButton createCustomerButton = new JButton("Kunde anlegen");
...
public static void passStatement(String statementString)
throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement preparedStmt = conn.prepareStatement(statementString);
preparedStmt.executeUpdate();
}
...
public class Listener extends Main implements ActionListener, MouseListener {
public void actionPerformed(ActionEvent ae) {
#Override
public void mouseClicked(MouseEvent me) {
if (me.getSource() == createCustomerButton) {
nachnameField.getText();
vornameField.getText();
strasseField.getText();
postleitzahlField.getText();
telefonField.getText();
emailField.getText();
zusatzinfoField.getText();
String statement = "INSERT INTO kunde (nachname, vorname, strasse,
postleitzahl, telefon, email, zusatzinfo) VALUES("+nachnameField+","
+vornameField+","+strasseField+","+postleitzahlField+","+telefonField+","
+emailField+","+zusatzinfoField+")";
try {
passStatement(statement);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
createLowerPanel();
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Full error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your
SQL syntax; check the manual that corresponds to your MySQL server version for the right
syntax to use near'
[,322,4,461x19,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,
alignment' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at
sun.reflect.NativeConstructorAccessorImpl.newInstance
(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance
(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
at com.mysql.jdbc.Util.getInstance(Util.java:383)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1062)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4226)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4158)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2615)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2776)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2840)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2082)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2334)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2262)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2246)
at Main.passStatement(Main.java:66)
at Listener.mouseClicked(Listener.java:46)
at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:270)
at java.awt.Component.processMouseEvent(Component.java:6508)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3311)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4501)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Any help is greatly appreciated!!
If it is a string value that you are inputting to a SQL database then you need to put single quotes before and after each element e.g..
tring statement = "INSERT INTO kunde (nachname, vorname, strasse,
postleitzahl, telefon, email, zusatzinfo) VALUES('" + nachname + "','" // use variable here
+ vorname + "')"; // ...... etc...
Hope this is clear.
You're calling getText() on your JTextFields and just ignoring the String returned. Instead your passing the actual JTextField's toString result and not its text into your SQL statement. Don't do that.
So instead, get the text Strings from your fields, and put them into String variables. Then use those variables to build your SQL statement. i.e.,
String foo = fooTextField.getText();
// now use foo, not fooTextField to create your SQL statements.
i.e.,
if (me.getSource() == createCustomerButton) {
String nachname = nachnameField.getText(); // get text put into variable
String vorname = vornameField.getText();
// .... etc
String statement = "INSERT INTO kunde (nachname, vorname, strasse,
postleitzahl, telefon, email, zusatzinfo) VALUES(" + nachname + "," // use variable here
+ vorname + "," ...... etc...
Also:
Learn and then use PreparedStatements as these are safer to use.
Don't add MouseListeners to JButtons as this will lead to bad button behavior (i.e., disabled buttons that still work, buttons that don't respond to space bar presses...)
Use ActionListeners instead.
Don't overuse static modifier as you're doing. Using them in this way suggests that your code needs to be improved greatly.
Don't post bad snippets as you're doing as that will only confuse us.
Related
I work on a small educational project - easy java app with database and gui. I work in NetBeans IDE.
For graphical interface I use JavaFX, and as I've testet this part work perfectly fine, but I have some problem with JDBC part (I use JDBC driver for sqlite database, created with DB browser for sqlite). My main application class looks like this:
public class BazaLyoko extends Application {
#Override
public void start(Stage stage) throws Exception {
Database baza = new Database();
String tytul = baza.getEpisodeName(1);
stage.setTitle(tytul);
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
And when I change those lines:
Database baza = new Database();
String tytul = baza.getEpisodeName(1);
To this (to replace value retrieved from database to a placeholder - I did this to ensure if the error is rather connected with JavaFX or JDBC part)
String tytul = "";
Program start without problem, but when I try to use my database application don't start. There isn't any compilation error or anything like that (or maybe I just don't see them, as I'm quite new to this IDE, though I think such things are usually blatantly visible) just no application window appear.
Here's the code for my database class(they both share the same package):
public class Database {
public static Connection conn;
public Database()
{
connect();
}
public static void connect()
{
String connectionString = "jdbc:sqlite:BazaLyoko.db";
try
{
conn = DriverManager.getConnection(connectionString);
if (conn != null)
{
DatabaseMetaData meta = conn.getMetaData();
//System.out.println("Nazwa sterownika to " + meta.getDriverName());
//System.out.println("Stworzono baze danych.");
}
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
}
private ResultSet doQuery(String query) throws SQLException
{
Statement stmt = null;
try
{
stmt = this.conn.createStatement();
ResultSet result = stmt.executeQuery(query);
return result;
}
catch (SQLException e )
{
throw new Error("Problem", e);
}
finally
{
if (stmt != null) { stmt.close(); }
}
}
public String getEpisodeName(int nr) throws SQLException
{
ResultSet result = doQuery("SELECT tytul FROM Odcinki WHERE numer="+String.valueOf(nr));
result.next();
return result.getString("tytul");
}
}
Database of that name is located inside my project directory (i also tried to copy it to package directory but nothing changed), the names of the table and column are correct to and exist a row with value 1 in column numer.
What I'm missing or doing wrong?
Edit:
I manage to get the following Stack Trace:
No suitable driver found for jdbc:sqlite:BazaLyoko.db
at com.sun.corba.se.impl.util.Utility.printStackTrace(Utility.java:933)
at bazalyoko.Database.connect(Database.java:46)
at bazalyoko.Database.<init>(Database.java:26)
at bazalyoko.BazaLyoko.start(BazaLyoko.java:23)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
at java.lang.Thread.run(Thread.java:748)
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$1(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
at bazalyoko.Database.doQuery(Database.java:57)
at bazalyoko.Database.getEpisodeName(Database.java:75)
at bazalyoko.BazaLyoko.start(BazaLyoko.java:24)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
... 1 more
Exception running application bazalyoko.BazaLyoko
Java Result: 1
This question already has answers here:
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
(13 answers)
Closed 6 years ago.
Below is the code that works perfectly fine when it is executed from main (ie in eclipse RunAs java application). However if I call Statement getStatement from outside ( meaning a servlet calling it via a put ) in the same package I get java.lang.ClassNotFoundException: com.mysql.jdbc.Driver. Any pointers to why ?
public class DBConnectivity {
private static Statement getStatement(String username, String password) throws SQLException, ClassNotFoundException {
Properties prop = new Properties();
prop.put("user", "root");
prop.put("password", "password");
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/keeptrack", prop);
Statement stmt = conn.createStatement();
return stmt;
}
public void put(String username, String password, String table,
String name, String exercise, String wsj, String food)
throws SQLException, ClassNotFoundException {
Statement stmt = getStatement(username, password);
// checkIfTableExists(stmt, table);
stmt.executeUpdate(
"insert into " + table +
" " +
"values(\'" + name + "\', \'" + exercise + "\', \'" + wsj + "\', \'" + food + "\')");
}
public List<String> get(String username, String password, String table)
throws SQLException, ClassNotFoundException {
Statement stmt = getStatement(username, password);
//checkIfTableExists(stmt, table);
ResultSet rs = stmt.executeQuery("select FOOD from " + table);
List<String> foodData = new ArrayList<String>();
while(rs.next()) {
String output = rs.getString("FOOD");
foodData.add(output);
// System.out.println("wohoo: " + output);
}
return foodData;
}
public static void main(String[] args) throws SQLException, ClassNotFoundException {
DBConnectivity conn = new DBConnectivity();
conn.put("root", "password", "trackTable", "D", "B", "C", "D");
conn.get("root", "password", "trackTable");
}
}
Here is the servlet which calls the database:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("firstname");
String password = request.getParameter("lastname");
String firstname = username;
String exercise = request.getParameter("exerise");
String wsj = request.getParameter("wsj");
String food = request.getParameter("food");
try {
new DBConnectivity().put(username, password, "trackTable", firstname, exercise, wsj, food);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The new DBConnectivity().put call results in ClassNotFoundException.
Stack trace is :
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1295)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1147)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at org.ameya.dynasty.DBConnectivity.getStatement(DBConnectivity.java:27)
at org.ameya.dynasty.DBConnectivity.get(DBConnectivity.java:63)
at org.ameya.dynasty.ServletIndex.doGet(ServletIndex.java:39)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:744)
Your error:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
If it works running from Eclipse, that means you have the MySql jdbc dirver jar in the classpath of your project, but it is not available to your web application.
The project class path (build path) is not the same as the class path of your web application when deployed. Not all jars being on your project class path get exported automatically.
Usually jars in the WEB-INF/lib will be available for the web application, but jars outside of that will not.
You should either place the MySql jdbc driver jar in WEB-INF/lib, or add it to the lib folder of your Servlet container (Tomcat in your case judging by the exception stack trace).
You have to include mysql-connector-java-5.1.24-bin.jar library file into your project.
Then it will not give the error class not found.
this file located inside C:\Program Files\MySQL\Connector J 5.1.20.0 folder.
Add mysql-conneter jar in your project library. You can download it from below link
Download Connector Jar file
make sure that the packager you are using for creating war file (it could just as well be eclipse), is putting the mysql driver jar file in the war's web-inf lib.
typically, in eclipse you ensure above by going to project properties->deployment assembly and making sure your driver jar is included
If you execute the same method (main) in other class inside the project, must be executed perfectly.
The classloader is the same, but you can't access to the method getStatement outside the class DBConnectivity because the method is private.
You could execute this method by reflection.
i'm implementing a client/server app with java RMI, client and server are in different packages in the same project (and of course they run on the same machine) and interfaces are defined in a "common" package.When i try to get one of the two remote object i get the aforementioned excepition. I've read some SO answers where people sugget to add a static reference to remote object so they can be never collected, but this doesn't work!
here is the code of the client and server
NotificheServiceProxy
public class NotificheServiceProxy implements INotificheService
{
#Override
public ArrayList <NotificaDTO> generaNotifiche(String autostrada, Date data, Date oraInizio, Date oraFine)
{
try
{
RMIClient client = new RMIClient ("localhost" , 1099);
INotificheService service = (INotificheService) client.getService(INotificheService.class);
return service.generaNotifiche(autostrada, data, oraInizio, oraFine);
}
catch (RemoteException ex)
{
Logger.getLogger(TrattaServiceProxy.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
catch (NotBoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
RMIClient
public class RMIClient
{
private Registry reg;
public RMIClient (String url , int port) throws RemoteException
{
reg = LocateRegistry.getRegistry(url, port);
}
public Remote getService(Class service) throws NotBoundException, RemoteException
{
RMIMapping RMIMappingAnn = (RMIMapping) service.getAnnotation(RMIMapping.class);
return reg.lookup(RMIMappingAnn.name());
}
}
NotificheService (server side)
public class NotificheService implements INotificheService
{
private static NotificheService instance;
#Override
public ArrayList<NotificaDTO> generaNotifiche(String autostrada, Date data, Date oraInizio, Date oraFine) throws RemoteException
{
instance = this;
return new NotificheBusinessLogic().generaNotifiche(autostrada, data, oraInizio, oraFine);
}
}
scServerConfig (server main)
public class SCServerConfig
{
public static RMIServer server;
public static void main (String[] args)
{
server = new RMIServer(1099);
//avvia il server ed esporta oggetti remoti
server.start().export(TrattaService.class).export(NotificheService.class);
//Other stuff
RMIServer (starts server and provide method for remote objects exporting
public class RMIServer
{
private Registry reg;
private int regPort;
public RMIServer (int regPort)
{
this.regPort = regPort;
}
public RMIServer start()
{
try
{
reg = LocateRegistry.createRegistry(regPort);
System.out.println("SERVER OK");
}
catch (RemoteException ex)
{
Logger.getLogger(RMIServer.class.getName()).log(Level.SEVERE, null, ex);
}
return this;
}
public RMIServer export (Class object)
{
try
{
RMIMapping RMIMappingAnn = (RMIMapping) object.getInterfaces()[0].getAnnotation(RMIMapping.class);
Remote tmp = UnicastRemoteObject.exportObject((Remote)object.newInstance(), 0);
reg.rebind( RMIMappingAnn.name() , tmp );
System.out.println("oggetto remoto esportato " + object);
}
catch (InstantiationException ex)
{
System.err.println("InstantiationExeception!!\ncause:\n 1. il costruttore dell' oggetto remoto non deve avere argomenti");
}
catch (IllegalAccessException ex)
{
Logger.getLogger(RMIServer.class.getName()).log(Level.SEVERE, null, ex);
}
catch (RemoteException ex)
{
Logger.getLogger(RMIServer.class.getName()).log(Level.SEVERE, null, ex);
}
return this;
}
}
Each interface is annotated with #RMIMapping annotation that provides the object binding name. But i'm sure that the problem doesn'come from this
This is for me a real mistery, this is the stacktrace......many thanks for help!
ott 03, 2014 5:13:17 PM it.csbeng.speedcontrolsystem.addettoApp.proxy.NotificheServiceProxy generaNotifiche
SEVERE: null
java.rmi.NoSuchObjectException: no such object in table
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:273)
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:251)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:160)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:194)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:148)
at $Proxy3.generaNotifiche(Unknown Source)
at it.csbeng.speedcontrolsystem.addettoApp.proxy.NotificheServiceProxy.generaNotifiche(NotificheServiceProxy.java:25)
at it.csbeng.speedcontrolsystem.addettoApp.coordinator.AddettoAppCoordinator.generaNotifiche(AddettoAppCoordinator.java:17)
at it.csbeng.speedcontrolsystem.addettoApp.boundary.AddettoInteraction.generaNotificheEvent(AddettoInteraction.java:179)
at it.csbeng.speedcontrolsystem.addettoApp.boundary.AddettoInteraction.access$000(AddettoInteraction.java:15)
at it.csbeng.speedcontrolsystem.addettoApp.boundary.AddettoInteraction$1.mousePressed(AddettoInteraction.java:78)
at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:280)
at java.awt.Component.processMouseEvent(Component.java:6502)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4489)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:723)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:682)
at java.awt.EventQueue$3.run(EventQueue.java:680)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:696)
at java.awt.EventQueue$4.run(EventQueue.java:694)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:693)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at it.csbeng.speedcontrolsystem.addettoApp.coordinator.AddettoAppCoordinator.generaNotifiche(AddettoAppCoordinator.java:20)
at it.csbeng.speedcontrolsystem.addettoApp.boundary.AddettoInteraction.generaNotificheEvent(AddettoInteraction.java:179)
at it.csbeng.speedcontrolsystem.addettoApp.boundary.AddettoInteraction.access$000(AddettoInteraction.java:15)
at it.csbeng.speedcontrolsystem.addettoApp.boundary.AddettoInteraction$1.mousePressed(AddettoInteraction.java:78)
at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:280)
at java.awt.Component.processMouseEvent(Component.java:6502)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4489)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:723)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:682)
at java.awt.EventQueue$3.run(EventQueue.java:680)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:696)
at java.awt.EventQueue$4.run(EventQueue.java:694)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:693)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
EDIT: #EJP before that, i've done something like
public class RemoteObject implements IRemoteObject
{
private static RemoteObject instance;
public RemoteObject ()
{
instance = this;
}
public someType someMethod (...)
}
but it throwed the same exception. Furthermore, as you can see, in scServerConfig there is a
public static RMIServer server;
which encapsulates a Registry reference. if these thing i've done are correct, i think that adding static references may not be enough, even tough "suddendly" started to work for me. Am I wrong?
java.rmi.NoSuchObjectException but static reference added
It isn't added. You're trying to call the remote method that adds it. You're failing at that, so it hasn't hapoened yet.
You need to set the static instance in the constructor of your remote object. Doing it in the remote method may already be too late.
I suggest you also keep the Registry in a static variable server side. In fact strictly speaking that's the only reference you need to keep static.
I'm trying to costumize a Synthetica theme in netbeans as this article shows :
http://www.jyloo.com/news/?pubId=1335947397000
So, I created the costum.xml file and I added it to my project folder as : /home/aimad/NetBeansProjects/GestionStock/costum.xml
and I create this code in my Form constructor :
public PersonelMainForm() {
try {
try {
UIManager.setLookAndFeel(new SyntheticaStandardLookAndFeel() {
#Override
protected void loadCustomXML() throws ParseException {
loadXMLConfig("custom.xml");
}
});
setName("MainFrame");
getRootPane().updateUI();
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(PersonelMainForm.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (ParseException ex) {
Logger.getLogger(PersonelMainForm.class.getName()).log(Level.SEVERE, null, ex);
}
initComponents();
}
but when I run the program I get this error message :
Exception in thread "AWT-EventQueue-0"
java.lang.IllegalArgumentException: You must supply an InputStream,
StyleFactory and Class or URL at
javax.swing.plaf.synth.SynthParser.parse(SynthParser.java:227) at
javax.swing.plaf.synth.SynthLookAndFeel.load(SynthLookAndFeel.java:573)
at
de.javasoft.plaf.synthetica.SyntheticaLookAndFeel.loadXMLConfig(SyntheticaLookAndFeel.java:428)
at
Personel.PersonelMainForm$1.loadCustomXML(PersonelMainForm.java:34)
at
de.javasoft.plaf.synthetica.SyntheticaLookAndFeel.(SyntheticaLookAndFeel.java:364)
at
de.javasoft.plaf.synthetica.SyntheticaStandardLookAndFeel.(SyntheticaStandardLookAndFeel.java:30)
at Personel.PersonelMainForm$1.(PersonelMainForm.java:30) at
Personel.PersonelMainForm.(PersonelMainForm.java:30) at
Personel.PersonelMainForm$3.run(PersonelMainForm.java:159) at
java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251) at
java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727) at
java.awt.EventQueue.access$200(EventQueue.java:103) at
java.awt.EventQueue$3.run(EventQueue.java:688) at
java.awt.EventQueue$3.run(EventQueue.java:686) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:697) at
java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at
java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at
java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
I've just tried running the sample java files that I got with the epson tm-t20 printer that I bought. These classes should run but they keep giving me errors. I've been looking at this for over 8 hours now I'm really getting frustrated. This is the exception it's throwing at me:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/apache/xerces/parsers/DOMParser
at jpos.config.simple.xml.AbstractXercesRegPopulator.<init>(Unknown Source)
at jpos.config.simple.xml.XercesRegPopulator.<init>(Unknown Source)
at jpos.config.simple.xml.SimpleXmlRegPopulator.<init>(Unknown Source)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at java.lang.Class.newInstance0(Class.java:372)
at java.lang.Class.newInstance(Class.java:325)
at jpos.loader.simple.SimpleServiceManager.initRegPopulator(Unknown Source)
at jpos.loader.simple.SimpleServiceManager.initEntryRegistry(Unknown Source)
at jpos.loader.simple.SimpleServiceManager.init(Unknown Source)
at jpos.loader.simple.SimpleServiceManager.<init>(Unknown Source)
at jpos.loader.JposServiceLoader.<clinit>(Unknown Source)
at jpos.BaseJposControl.open(Unknown Source)
at postest.Step1Frame.processWindowEvent(Step1Frame.java:83)
at java.awt.Window.processEvent(Window.java:2003)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Window.dispatchEventImpl(Window.java:2713)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:680)
at java.awt.EventQueue$4.run(EventQueue.java:678)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Here's the sample code I've been looking at:
POSPrinterControl19 ptr = (POSPrinterControl19)new POSPrinter();
JPanel contentPane;
JPanel jPanel_reciept = new JPanel();
TitledBorder titledBorder1;
GridBagLayout gridBagLayout1 = new GridBagLayout();
GridBagLayout gridBagLayout2 = new GridBagLayout();
JButton jButton_Print = new JButton();
/**Construct "Frame"*/
public Step1Frame() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
/**Form the component*/
private void jbInit() throws Exception {
//setIconImage(Toolkit.getDefaultToolkit().createImage(Step1Frame.class.getResource("[Your Icon]")));
contentPane = (JPanel) this.getContentPane();
titledBorder1 = new TitledBorder(BorderFactory.createEtchedBorder(Color.white,new Color(134, 134, 134)),"Receipt");
contentPane.setLayout(gridBagLayout1);
this.setSize(new Dimension(300, 180));
this.setTitle("Step 1 Print \"Hello JavaPOS\"");
jPanel_reciept.setLayout(gridBagLayout2);
jPanel_reciept.setBorder(titledBorder1);
jButton_Print.setText("Print");
jButton_Print.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton_Print_actionPerformed(e);
}
});
contentPane.add(jPanel_reciept, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(15, 0, 0, 0), 20, 20));
jPanel_reciept.add(jButton_Print, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 10, 5, 10), 130, 0));
}
/**
* Outline The processing code required in order to enable
* or to disable use of service is written here.
* #exception JposException This exception is fired toward the failure of
* the method which JavaPOS defines.
*/
/**When the window was closed*/
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
this.closing();
}
/**When the window open*/
else if (e.getID() == WindowEvent.WINDOW_OPENED) {
// JavaPOS's code for Step1
try {
//Open the device.
//Use the name of the device that connected with your computer.
//ptr.clearPrintArea();
ptr.open("POSPrinter");
//Get the exclusive control right for the opened device.
//Then the device is disable from other application.
ptr.claim(1000);
//Enable the device.
ptr.setDeviceEnabled(true);
}
catch(JposException ex) {
}
}
// JavaPOS's code for Step1--END
}
//***********************Button*************************************************
/**
* Outline The code for using the most standard method "PrintNormal"
* to print is described.
*/
void jButton_Print_actionPerformed(ActionEvent e) {
// JavaPOS's code for Step1
try{
//printNormal(int station, String data)
//A string is sent by using the method "printNormal", and it is printed.
// "\n" is the standard code for starting a new line.
// When the end of the line have no "\n",printing by
// using the method "printNormal" doesn't start, may be.
ptr.printNormal(POSPrinterConst.PTR_S_RECEIPT,"Hello JavaPOS\n");
}
catch(JposException ex){
}
// JavaPOS's code for Step1--END
}
//***********************Method*************************************************
/**
* Outline The code to finish a service.
*/
void closing(){
// JavaPOS's code for Step1
try{
//Cancel the device.
ptr.setDeviceEnabled(false);
//Release the device exclusive control right.
ptr.release();
//Finish using the device.
ptr.close();
}
catch(JposException ex){
}
// JavaPOS's code for Step1--END
System.exit(0);
}
You have to put some additionally dependency library to the project classpath, one of them seems to be the apache xerces XML parser, so basically you have to add that jar library to the classpath .
you can find the apache xerces XML parser here .
For me class org/apache/xerces/parsers/DOMParser is missing. You can download it from maven repository xercesImpl.jar