I am trying to connect my service file to cloud sql instance. But I am geeting java.lang.NoClassDefFoundError: Could not initialize class com.blacklight.common.DBManager
Here is my class
package com.blacklight.common;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
#WebListener("Initialize db upon initialization of application context")
public class DBManager implements ServletContextListener {
private static final Logger LOGGER = LoggerFactory.getLogger(DBManager.class);
private static final Object dataSourceLock = new Object();
private static DataSource dataSource = null;
static {
dataSource = initDataSource();
}
private static DataSource initDataSource() {
synchronized (dataSourceLock) {
try {
String username = "aaaa";
String password = "bbbb";
String driverName = "com.mysql.jdbc.Driver";
String instance = "project-Id:location:database-name";
if (dataSource == null) {
HikariConfig config = new HikariConfig();
config.setUsername(username);
config.setPassword(password);
config.setJdbcUrl("jdbc:mysql:///Features");
config.setUsername(username);
config.setPassword(password);
config.setDriverClassName(driverName);
config.setConnectionInitSql("SET NAMES 'utf8mb4'");
config.addDataSourceProperty("socketFactory","com.google.cloud.sql.mysql.SocketFactory");
config.addDataSourceProperty("cloudSqlInstance", instance);
config.addDataSourceProperty("characterEncoding", "UTF-8");
config.addDataSourceProperty("useUnicode", "true");
// config.addDataSourceProperty("noAccessToProcedureBodies", "true");
config.addDataSourceProperty("useSSL", "true");
config.addDataSourceProperty("ipTypes", "PRIVATE,PUBLIC");
config.setMaximumPoolSize(50);
config.setMinimumIdle(5);
config.setConnectionTimeout(10000);
config.setIdleTimeout(600000);
config.setMaxLifetime(1800000);
dataSource = new HikariDataSource(config);
}
return dataSource;
} catch (Exception e) {
System.out.println("Error");
LOGGER.error(e.getMessage(), e);
}
throw new RuntimeException("Couldn't initialize datasource");
}
}
public static Connection getConnection() throws SQLException {
if (dataSource == null) {
dataSource = initDataSource();
}
return dataSource.getConnection();
}
#Override
public void contextInitialized(ServletContextEvent event) {
dataSource = initDataSource();
}
#Override
public void contextDestroyed(ServletContextEvent event) {
if (dataSource != null) {
((HikariDataSource) dataSource).close();
}
}
}
and my error logs are
com.blacklight.common.DBManager initDataSource: Failed to initialize pool: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
com.zaxxer.hikari.pool.HikariPool$PoolInitializationException: Failed to initialize pool: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at com.zaxxer.hikari.pool.HikariPool.throwPoolInitializationException(HikariPool.java:596)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:582)
at com.zaxxer.hikari.pool.HikariPool.(HikariPool.java:115)
at com.zaxxer.hikari.HikariDataSource.(HikariDataSource.java:81)
at com.blacklight.common.DBManager.initDataSource(DBManager.java:71)
at com.blacklight.common.DBManager.(DBManager.java:26)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.eclipse.jetty.server.handler.ContextHandler$StaticContext.createInstance(ContextHandler.java:2902)
at org.eclipse.jetty.servlet.ServletContextHandler$Context.createInstance(ServletContextHandler.java:1299)
at org.eclipse.jetty.server.handler.ContextHandler$StaticContext.createListener(ContextHandler.java:2913)
at org.eclipse.jetty.servlet.ListenerHolder.doStart(ListenerHolder.java:94)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:73)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:369)
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1449)
at com.google.apphosting.runtime.jetty94.AppEngineWebAppContext.startWebapp(AppEngineWebAppContext.java:274)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1414)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:916)
at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:288)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:524)
at com.google.apphosting.runtime.jetty94.AppEngineWebAppContext.doStart(AppEngineWebAppContext.java:218)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:73)
at com.google.apphosting.runtime.jetty94.AppVersionHandlerFactory.doCreateHandler(AppVersionHandlerFactory.java:207)
at com.google.apphosting.runtime.jetty94.AppVersionHandlerFactory.createHandler(AppVersionHandlerFactory.java:125)
at com.google.apphosting.runtime.jetty94.AppVersionHandlerMap.getHandler(AppVersionHandlerMap.java:82)
at com.google.apphosting.runtime.jetty94.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:176)
at com.google.apphosting.runtime.RequestRunner.dispatchServletRequest(RequestRunner.java:264)
at com.google.apphosting.runtime.RequestRunner.dispatchRequest(RequestRunner.java:229)
at com.google.apphosting.runtime.RequestRunner.run(RequestRunner.java:194)
at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:273)
at java.lang.Thread.run(Thread.java:750)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1117)
at com.mysql.jdbc.MysqlIO.(MysqlIO.java:350)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2416)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2450)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2235)
at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:818)
at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:46)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:404)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:307)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:364)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561)
... 31 more
Caused by: java.net.ConnectException: Connection timed out (Connection timed out)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:607)
at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:293)
at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:173)
at com.google.cloud.sql.core.CoreSocketFactory.createSslSocket(CoreSocketFactory.java:275)
at com.google.cloud.sql.core.CoreSocketFactory.connect(CoreSocketFactory.java:229)
at com.google.cloud.sql.core.CoreSocketFactory.connect(CoreSocketFactory.java:188)
at com.google.cloud.sql.mysql.SocketFactory.connect(SocketFactory.java:41)
at com.mysql.jdbc.MysqlIO.(MysqlIO.java:300)
This is caused when there exists a class file in your code which is present at compile-time but not found at run-time. Look for differences in your build time and runtime classpaths.
Here's a simple code to illustrate what your error actually is:
NoClassDefFoundErrorDemo.java
public class NoClassDefFoundErrorDemo {
public static void main(String[] args) {
try {
// The following line would throw ExceptionInInitializerError
SimpleCalculator calculator1 = new SimpleCalculator();
} catch (Throwable t) {
System.out.println(t);
}
// The following line would cause NoClassDefFoundError
SimpleCalculator calculator2 = new SimpleCalculator();
}
}
SimpleCalculator.java
public class SimpleCalculator {
static int undefined = 1 / 0;
}
So actually its happening in this manner :
This differentiates java.lang.ClassNotFoundException and java.lang.NoClassDefFoundError, wherein the ClassNotFoundException shows that the class was not found on the classpath, meaning thereby, that we were trying to load the class definition; and the class did not exist on our classpath.
However, in the latter, which is your case, is when the JVM looked in its internal class definition data structure for the definition of a class and did not find it.
This means that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying to use the class again (and thus need to load it, since it failed last time), but we're not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again).
Possible Solutions:-
The class is not available in Java Classpath.
If you are working in J2EE environment than the visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.
Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
Because NoClassDefFoundError is a subclass of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
Any start-up script is overriding Classpath environment variable.
You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
Resources
3 Ways To Solve NoClassDefFoundError
Problem Patterns - NoClassDefFoundError
Related
I am trying to make a extra class that would take care of connection and status of the user, but I am still getting some wierd error, that I don´t understand.
This is my ´FTPConnection class
I created private ftpClient using DI (I have #Bean annotation in main class) and I am trying to connect to the server using this method from another class
#Autowired
private FTPClient ftpClient;
public void connect() {
try {
ftpClient.connect("host");
ftpClient.login("username", "password");
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.err.println("FTP server refused connection.");
System.exit(1);
}
}
catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
And this is the class with the RequestMapping methods
#PostMapping("/uploadFile")
public void uploadFile(#RequestParam("file") MultipartFile file) {
var connection = new FTPConnection();
try {
connection.connect();
System.out.println(connection.isConnected());
FTPClient ftpClient = connection.getFtpClient();
ftpClient.changeWorkingDirectory("/usb");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
[...]
And the error that I am getting is
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root
java.lang.NullPointerException: null
at com.tenpetr.FTPFileUploader.FTPConnection.connect(FTPConnection.java:16) ~[main/:na]
at com.tenpetr.FTPFileUploader.FileTransfer.uploadFile(FileTransfer.java:29) ~[main/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ...
Dou you have any idea, why I am stuck here? Thanks for your advices.
My guess is (will update after having more data) that the FtpClient is not correctly initialized and thus the FtpConnection is not correctly initialized as well.
TO BE UPDATED
Defining a bean with singleton scope means the container creates a single instance of that bean
edited:
#Bean
#Scope("singleton")
public FTPClient ftpClient(){
return new FTPClient();
}
This won't work if you're trying to autowire an interface
I have a cucumber and selenium test which has always worked fine and suddenly stops running with the below error.
1 Scenarios (1 failed)
14 Steps (14 skipped)
0m0.004s
java.lang.ExceptionInInitializerError
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.picocontainer.injectors.AbstractInjector.newInstance(AbstractInjector.java:145)
at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:342)
at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:678)
at cucumber.runtime.java.picocontainer.PicoFactory.getInstance(PicoFactory.java:40)
at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:60)
at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:224)
at cucumber.runtime.Runtime.runHooks(Runtime.java:212)
at cucumber.runtime.Runtime.runBeforeHooks(Runtime.java:202)
at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:40)
at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
at cucumber.runtime.Runtime.run(Runtime.java:122)
at cucumber.api.cli.Main.run(Main.java:36)
at cucumber.api.cli.Main.main(Main.java:18)
Caused by: java.lang.NullPointerException
at com.optal.browsers.WebDriverFactory.createAndSetUpThreadedBrowser(WebDriverFactory.java:56)
at com.optal.browsers.WebDriverFactory.create(WebDriverFactory.java:37)
at com.optal.hooks.ScenarioHooks.<clinit>(ScenarioHooks.java:19)
... 24 more
java.lang.NoClassDefFoundError: Could not initialize class com.optal.hooks.ScenarioHooks
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.picocontainer.injectors.AbstractInjector.newInstance(AbstractInjector.java:145)
at org.picocontainer.injectors.ConstructorInjector$1.run(ConstructorInjector.java:342)
at org.picocontainer.injectors.AbstractInjector$ThreadLocalCyclicDependencyGuard.observe(AbstractInjector.java:270)
at org.picocontainer.injectors.ConstructorInjector.getComponentInstance(ConstructorInjector.java:364)
at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.getComponentInstance(AbstractInjectionFactory.java:56)
at org.picocontainer.behaviors.AbstractBehavior.getComponentInstance(AbstractBehavior.java:64)
at org.picocontainer.behaviors.Stored.getComponentInstance(Stored.java:91)
at org.picocontainer.DefaultPicoContainer.getInstance(DefaultPicoContainer.java:699)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:647)
at org.picocontainer.DefaultPicoContainer.getComponent(DefaultPicoContainer.java:678)
at cucumber.runtime.java.picocontainer.PicoFactory.getInstance(PicoFactory.java:40)
at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:60)
at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:224)
at cucumber.runtime.Runtime.runHooks(Runtime.java:212)
at cucumber.runtime.Runtime.runAfterHooks(Runtime.java:206)
at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:46)
at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
at cucumber.runtime.Runtime.run(Runtime.java:122)
at cucumber.api.cli.Main.run(Main.java:36)
at cucumber.api.cli.Main.main(Main.java:18)
Calling System.exit() ..................
Process finished with exit code 1
ExceptionInInitializerError
An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable.
The ExceptionInInitializerError is thrown when the JVM attempts to load a new class. During the class loading procedure, all static variables and static initializers are being evaluated. A static initializer is a block enclosed within curly braces without having any name and return type, except having the keyword static.
An example of a static initializer:
import java.util.UUID;
class Example {
private static String ID = null;
static {
ID = UUID.randomUUID().toString();
}
}
The static initializer is evaluated only once during the class loading procedure. Thus, a thrown exception in the evaluation of a static variable or initializer is wrapped into an ExceptionInInitializerError, in order for the JVM to indicate that the class could not be initialized and loaded.
An example that throws ExceptionInInitializerError error is as follows:
public class Example {
private static String message = null;
private static String subMessage = null;
public Example(String message) {
Example.message = message;
}
static {
/* Store the first 10 characters of the input message. */
subMessage = message.substring(0, 10);
}
public String getSubMessage() {
return subMessage;
}
public static void main(String[] args) {
Example exampleClass = new Example("Test");
System.out.println(exampleClass.getSubMessage());
}
}
Executing the above code snippet you will see the following error:
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at main.java.Example.<clinit>(Example.java:13)
You can use either of the following methods to extract more information about the underlying actual exception:
getException(): Returns the exception that occurred during a static initialization that caused this error to be created.
getCause(): Returns the exception that caused this error to be thrown.
Dealing with ExceptionInInitializerError
The ExceptionInInitializerError is used as a wrapper to indicate that an exception arises in the static initializer block or the evaluation of a static variable’s value. Thus, we have to ensure that the original exception is fixed, in order for the JVM to be able to load our class successfully.
Outro
You can throw unchecked / runtime exceptions from the block of a static initializer. However, you cannot allow a checked exception to propagate out of a static block, because is not possible to handle these exceptions in your source.
if you are using Mac M1 chip and room lib , try this : In project-level build.gradle, add the following configuration in allprojects :
allprojects {
repositories {
// ...
}
// ADD THE FOLLOWING
configurations.all {
resolutionStrategy {
force 'org.xerial:sqlite-jdbc:3.34.0'
}
}
}
Ref : https://stackoverflow.com/a/70232822/7048025
import java.util.*;
import javax.smartcardio.*;
public class Terminals{
public static void main (String [] args) throws Exception{
TerminalFactory factory = TerminalFactory.getDefault ();
System.out.println ("Default factory: "+factory);
dumpTerminals (factory);
factory = TerminalFactory.getInstance ("PC/SC", null);
System.out.println ("PC/SC factory: "+factory);
dumpTerminals (factory);
}
static void dumpTerminals (TerminalFactory factory) throws Exception{
List<CardTerminal> terminals = factory.terminals ().list ();
for (CardTerminal terminal: terminals)
System.out.println (terminal);
}
}
This code is not detecting COM port in WINDOWS 8.1 pro . It prints Default factory: TerminalFactory for type None from provider None and some errors
Exception in thread "main" java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: PC/SC, provider: SunPCSC, class: sun.security.smartcardio.SunPCSC$Factory)
at java.security.Provider$Service.newInstance(Provider.java:1259)
at sun.security.jca.GetInstance.getInstance(GetInstance.java:243)
at sun.security.jca.GetInstance.getInstance(GetInstance.java:190)
at javax.smartcardio.TerminalFactory.getInstance(TerminalFactory.java:243)
at Terminals.main(Terminals.java:10)
Caused by: sun.security.smartcardio.PCSCException: SCARD_E_NO_SERVICE
at sun.security.smartcardio.PCSC.SCardEstablishContext(Native Method)
at sun.security.smartcardio.PCSCTerminals.initContext(PCSCTerminals.java:56)
at sun.security.smartcardio.SunPCSC$Factory.<init>(SunPCSC.java:60)
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 java.security.Provider$Service.newInstance(Provider.java:1254)
... 4 more
even though MIFARE card reader is connected to laptop at COM port .
I tried multiple times by disconnecting and connecting never succeed .I had installed required driver for card reader device driver is working properly.
Why it's not recognising card reader?
I'm doing an app for my high school and I have the following situation:
I will use an embedded HSQL database for storing my application data. When I open the connection, I try to connect to the database only if exists, so it will not be created if it doesn't exist. Basically, if an HsqlException is thrown, functions to create the database, tables and constraints will be called.
The point is that this line:
Connection c = DriverManager.getConnection(url, user, pwd);
Throws an SQLException AND an HsqlException. But if I try to catch and control them, the output keeps being like this:
run:
2014-11-19T20:15:25.142+0100 SEVERE could not reopen database
Catched an Hsql or SQL Exception. //This is my 'control' over the Exceptions.
org.hsqldb.HsqlException: La base de datos no existe: C:/Databases/DB
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.persist.Logger.open(Unknown Source)
at org.hsqldb.Database.reopen(Unknown Source)
at org.hsqldb.Database.open(Unknown Source)
at org.hsqldb.DatabaseManager.getDatabase(Unknown Source)
at org.hsqldb.DatabaseManager.newSession(Unknown Source)
at org.hsqldb.jdbc.JDBCConnection.<init>(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.getConnection(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at DBManager.DBManager.main(DBManager.java:20)
BUILD SUCCESSFUL (total time: 0 seconds)
And finally this is my code. I hope someone call tell me why is this happening.
package DBManager;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DBManager {
static Connection c;
static Statement stm;
public static void main(String[] args){
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
c = DriverManager.getConnection("jdbc:hsqldb:file:C:/Databases/DB;create=false", "SA", "");
} catch (ClassNotFoundException ex) {
System.out.println("ClassNotFoundException has been catched.");
} catch (SQLException | org.hsqldb.HsqlException ex) {
System.out.println("Catched an Hsql or SQL Exception.");
//TODO call connection where the database is created.
//TODO create schema CreateSchema.run(c);
//TODO create constraints
} finally {
//TODO
}
}
private static class CreateSchema{
public static void run(Connection con){
//TODO: Create table queries.
}
}
}
Assuming you do not already have a HSQLDB database in C:/Databases/DB then this is behaving how I would expect. Your connection string tells it not to create the database if it does not exist, so it can't return an exception so it throws an exception which you are catching and logging.
Because the exception has been caught the run is considered successful because the main method did not throw an exception or call System.exit() with a non-zero value.
The exception you are catching is actually the SQLException and not the HsqlException (which is a RuntimeException) - the SQLException has a nested HsqlException. If you print the stack trace of the exception (ex.printStackTrace()) you can see this. So you should just catch SQLException.
The extra output you see is from within the HSQLDB driver class - if you look at the source for org.hsqldb.Database#reopen() you can see it calls logger.logSevereEvent("could not reopen database", e); and that's what responsible for the extra output you see. It tries to use a logging framework if one is available and defaults to the one in the JDK, which if not configured will print to System.err.
I have inherited some Java RMI client/server code, and while it runs fine on one machine, I haven't been able to get it to run in my dev environment.
The problem is when I run the server using the following java.exe -Djava.security.policy=conf\server.policy -SRC;. -Djava.library.path=. org.prog.rmi.RmiServer
I get the following error:
java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: org.prog.rmi.RmiServer_Stub (no security manager: RMI class loader disabled)
at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:396)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:250)
at sun.rmi.transport.Transport$1.run(Transport.java:159)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:155)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:535)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649)
...
My server.policy file is
grant {
permission java.security.AllPermission;
};
And my java code:
package org.prog.rmi;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.registry.*;
public class RmiServer extends UnicastRemoteObject
implements RmiServerIntf {
private BatchApi bapi;
private String iniFileLocation;
private String layoutOption;
private int addressCount = 0;
private RefInt apiHandle = new RefInt();
public RmiServer(String iniFileLocation,String layoutOption) throws RemoteException
{ super();
this.iniFileLocation = iniFileLocation;
this.layoutOption = layoutOption;
initAPI();
startupAPI();
openAPI();
}
public static void main(String args[])
{
System.out.println("RMI server started");
// Create and install a security manager
if (System.getSecurityManager() == null)
{
System.setSecurityManager(new RMISecurityManager());
System.out.println("Security manager installed.");
}
else
System.out.println("Security manager already exists.");
try //special exception handler for registry creation
{
LocateRegistry.createRegistry(1099);
System.out.println("java RMI registry created.");
}
catch (RemoteException e)
{
//do nothing, error means registry already exists
System.out.println("java RMI registry already exists.");
}
try
{
//Instantiate RmiServer
for (String arg: args){
System.out.println(arg);
}
RmiServer obj = new RmiServer(args[0],args[1]);
// Bind this object instance to the name "RmiServer"
Naming.rebind("//127.0.0.1/RmiServer", obj);
System.out.println("PeerServer bound in registry");
}
catch (Exception e)
{
System.err.println("RMI server exception:");
e.printStackTrace();
}
}
}
I've seen solutions relating to the java.rmi.server.codebase but didn't have any luck setting this either
You haven't regenerated the stub with rmic, or the Registry doesn't have access to it via its classpath.
After some further investigation and following RMI tutorials it appeared that there was a problem with the RMI registration server on port 1099.
When I stared the RMI registration server on another port (e.g. 2005) and changed these lines of code
LocateRegistry.createRegistry(2005);
and
Naming.rebind("//127.0.0.1:2055/RmiServer", obj);
This ran sucessfully without errors and my client was able to connect.
I hope this answer helps others with this error. Let me know if anyone needs any more detailed information.