Exception Caught Too Early - java

Background: Hibernate connects to a database using a username and password entered into a GUI. Upon failure, instead of propagating the error up as an exception, it comes out as a stack trace in the logger. I don't know where the exception is being caught at. Also a tiny bit troubling is the following block:
if (reason != null) {
println("getConnection failed: " + reason);
throw reason;
}
My breakpoint is set at the throw line (and successfully triggers), but the println statement never generates output (MySQL is using some sort of logger setup I can't find an open file hand for). Any sort of trick for locating where an exception is caught?
EDIT 1:
I call
sessionFactory = /*AnnotationConfiguration*/ ac.buildSessionFactory();
The exception is caught by Hibernate somewhere between the java.sql.DriverManager class and my HibernateUtil class. I presume we can blame Hibernate deciding that I don't really want to see the exception. I want to convince hibernate to let me see the exception.
EDIT 2:
My stack is this:
java.sql.SQLException: Access denied for user 'user'#'machine' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:910)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3923)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1273)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2031)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:718)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282)
/* Exception is thrown on the next line (1st code block in original post). */
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:154)
/* Begin hidden source calls */
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:84)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2009)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1292)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
/* End hidden source calls */
at com.****.****.util.HibernateUtil.initialize(HibernateUtil.java:34)
I can't get the debugger to look at any point above the stack beyond DriverManager.java:582. Everything in the stack beyond that is not visible in the debugger.

First of all, as you mention that there is a logger, you should replace all println statements with log calls.
You can also add further log messages to identify what happens inside the app. Alternatively (or in combination with the above), you can step through the critical code part in the debugger to see where the exception actually happens.

Here's the end result: Line 116 of org.hibernate.cfg.SettingsFactory catches the sql exception and forces it to a log. No configuration is available to change this. It appears I'll be unable to tell my end-user why their connection fails unless I make use of the logs.
Netbeans, for some annoying reason after I gave it the source for Hibernate still wanted to call all of this "hidden source calls." Some time with VIM and reading the line numbers later, I've got it cleared up.

Set a breakpoint for the exception thrown, and when the debugger starts single step to see what happens. You Will probably only need a few steps before the print happens.

Related

How do deal with h2 databases inability to deal with interrupts

How do deal with h2 database inability to deal with interrupts, I was occasionally seeing that my embedded h2 database appeared to get corrupted, in particular I had amended an ExecutorService so that if a task took too long it would cancel the task. The task would be cancelled okay but then subsequent database access failed with exceptions such as
23/07/2019 14.23.31:BST:DeleteDuplicatesController:start:SEVERE: commit failed
org.hibernate.TransactionException: commit failed
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:187)
at com.jthink.songkong.db.ReportCache.save(ReportCache.java:46)
at com.jthink.songkong.reports.AbstractReport.setReportDatabaseObject(AbstractReport.java:365)
at com.jthink.songkong.reports.DeleteDuplicatesReport.setReportDatabaseObject(DeleteDuplicatesReport.java:333)
at com.jthink.songkong.reports.DeleteDuplicatesReport.closeReport(DeleteDuplicatesReport.java:377)
at com.jthink.songkong.analyse.toplevelanalyzer.DeleteDuplicatesController.deleteAnyDups(DeleteDuplicatesController.java:606)
at com.jthink.songkong.analyse.toplevelanalyzer.DeleteDuplicatesController.start(DeleteDuplicatesController.java:665)
at com.jthink.songkong.ui.swingworker.DeleteDuplicates.doInBackground(DeleteDuplicates.java:43)
at com.jthink.songkong.ui.swingworker.DeleteDuplicates.doInBackground(DeleteDuplicates.java:20)
at javax.swing.SwingWorker$1.call(SwingWorker.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at javax.swing.SwingWorker.run(SwingWorker.java:334)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.hibernate.TransactionException: unable to commit against JDBC connection
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doCommit(JdbcTransaction.java:116)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:180)
... 14 more
Caused by: org.h2.jdbc.JdbcSQLNonTransientException: General error: "java.lang.IllegalStateException: Reading from nio:C:/Users/Paul/AppData/Roaming/SongKong/Database/Database.mv.db failed; file length -1 read length 4096 at 1541494 [1.4.199/1]"; SQL statement:
COMMIT [50000-199]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:502)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:427)
at org.h2.message.DbException.get(DbException.java:194)
at org.h2.message.DbException.convert(DbException.java:347)
at org.h2.command.Command.executeUpdate(Command.java:280)
at org.h2.jdbc.JdbcConnection.commit(JdbcConnection.java:542)
at com.mchange.v2.c3p0.impl.NewProxyConnection.commit(NewProxyConnection.java:1284)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.doCommit(JdbcTransaction.java:112)
... 15 more
Caused by: java.lang.IllegalStateException: Reading from nio:C:/Users/Paul/AppData/Roaming/SongKong/Database/Database.mv.db failed; file length -1 read length 4096 at 1541494 [1.4.199/1]
at org.h2.mvstore.DataUtils.newIllegalStateException(DataUtils.java:883)
at org.h2.mvstore.DataUtils.readFully(DataUtils.java:420)
at org.h2.mvstore.FileStore.readFully(FileStore.java:98)
at org.h2.mvstore.MVStore.readBufferForPage(MVStore.java:1048)
at org.h2.mvstore.MVStore.readPage(MVStore.java:2186)
at org.h2.mvstore.MVMap.readPage(MVMap.java:554)
at org.h2.mvstore.Page$NonLeaf.getChildPage(Page.java:1086)
at org.h2.mvstore.Page.get(Page.java:221)
at org.h2.mvstore.MVMap.get(MVMap.java:402)
at org.h2.mvstore.MVMap.get(MVMap.java:389)
at org.h2.mvstore.MVStore.getMapName(MVStore.java:2737)
at org.h2.mvstore.MVStore.renameMap(MVStore.java:2650)
at org.h2.mvstore.tx.TransactionStore.commit(TransactionStore.java:453)
at org.h2.mvstore.tx.Transaction.commit(Transaction.java:389)
at org.h2.engine.Session.commit(Session.java:691)
at org.h2.command.dml.TransactionCommand.update(TransactionCommand.java:46)
at org.h2.command.CommandContainer.update(CommandContainer.java:133)
at org.h2.command.Command.executeUpdate(Command.java:267)
... 18 more
Caused by: java.nio.channels.ClosedChannelException
at sun.nio.ch.FileChannelImpl.ensureOpen(FileChannelImpl.java:110)
at sun.nio.ch.FileChannelImpl.read(FileChannelImpl.java:721)
at org.h2.store.fs.FileNio.read(FilePathNio.java:74)
at org.h2.mvstore.DataUtils.readFully(DataUtils.java:406)
... 34 more
23/07/2019 14.23.31:BST:Errors:addError:SEVERE: Adding Error:commit failed
I have since found this issue
Basically if using H2 in embedded mode, and it receives an interrupt then all subsequent access fails until the thread pool is close and reopened. In the example I give of a process having to be cancelled because it appears to be stuck there is no solution except for interrupting
I also have another case whereby usually the controller thread that doesn't directly do a database work itself so I was struggling to see why when an interrupt occurred why this would cause database errors since this is handled by controller thread. I have now worked out the issue is that Im using an ExecutorService with a fixed size BlockingQueue (so that we dont have a big queue build up in memory), but if the queue gets full then new task is actually executed by the controller thread (because of CallerRunsPolicy), so the controller thread can be making calls to database after all.
Im using H2 with hibernate and in both cases calling the following immediately after the interrupt
HibernateUtil.closeFactory();
seems to solve the issue, however I guess this means that any other threads with hibernate sessions will be broken, but at least newly opened sessins will be okay. So im not particularly happy with this workaround, any other ideas ?
Using H2 as a server is not a solution since the whole point of H2 was an embedded db self contained within application.
Although not properly documented using the async protocol allows a connection to be interrupted without breaking all other connections.

Find a particular exception and corresponding message

My web application runs on Spring (MVC) 4.2.9.RELEASE, Hibernate 5.1.3.Final, Spring Data 1.8.2.RELEASE, and MS SQL Server (2014).
In the Spring context, I have the following exceptioin hanlder:
<bean id="simpleMappingExceptionResolver" class="myproject.CustomMappingExceptionResolver">
...
</bean>
to catch and save stack trace. I am able to see the following deep in a long stack trace printed in the logs:
......
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 113 more
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Transaction (Process ID 73) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:258)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1535)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:467)
How can I find the following exception class in the above exceptioin hanlder (and given an Exception instance) :
com.microsoft.sqlserver.jdbc.SQLServerException
AND the corresponding message:
Transaction (Process ID 73) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
If I understood you correctly you need to catch a nested exception. That's a bit tricky, but doable. You need to have a try-catch block for the top level exception that you expect. In the catch clause, you can use exception.getCause() to step down one nesting level at a time, and see if that level is an instanceof your SQL exception class. You can also check the message if necessary by using getMessage(). If the exception fits your criteria, congratulations you caught it. If not, simply throw it again.
Two things to keep in mind:
this approach may lead to poor performance if many exceptions occur, and only a small fraction of those actually matches your criteria.
if an exception has no cause, then e.getCause() will return e itself. Watch out for infinite recursion here.

Log4J2 Factory Error when attempting to use SMTP Appender

Good afternoon,
When I attempt to use the SMTP Appender, I get an odd error in the console. The error appears to occur when the XML file is loaded, as it isn't logged via any output stream except stdout. The contents of the appender are as follows (and I have confirmed that the error is in this block of XML). I've removed our server information.
<SMTP name="Mailer">
<Subject>[ERROR] (software name) on ${hostName} has thrown a fatal error</Subject>
<To>(a valid email in the form of a#a.com)</To>
<From>(a valid email in the form of a#a.com)</From>
<SMTPHost>(The Internal IP address of a server in the form of 192.168.0.1)</SMTPHost>
<SMTPPort>587</SMTPPort>
<BufferSize>512</BufferSize>
</SMTP>
Whether or not it is referenced in a logger, I receive the following error immediately upon running the program and running getLogger from the log manager. I've removed a couple of the file names and replaced them with a rough description of what the file is doing at that point.
2015-05-19 19:08:18,812 ERROR Unable to invoke factory method in class class org.apache.logging.log4j.core.appender.SmtpAppender for element SMTP. 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 org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.build(PluginBuilder.java:137)
at org.apache.logging.log4j.core.config.AbstractConfiguration.createPluginObject(AbstractConfiguration.java:766)
at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:706)
at org.apache.logging.log4j.core.config.AbstractConfiguration.createConfiguration(AbstractConfiguration.java:698)
at org.apache.logging.log4j.core.config.AbstractConfiguration.doConfigure(AbstractConfiguration.java:358)
at org.apache.logging.log4j.core.config.AbstractConfiguration.start(AbstractConfiguration.java:161)
at org.apache.logging.log4j.core.LoggerContext.setConfiguration(LoggerContext.java:361)
at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:426)
at org.apache.logging.log4j.core.LoggerContext.reconfigure(LoggerContext.java:442)
at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:138)
at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:147)
at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:41)
at org.apache.logging.log4j.LogManager.getContext(LogManager.java:175)
at org.apache.logging.log4j.LogManager.getLogger(LogManager.java:426)
at (Our Log Interface Class, which essentially just returns the log passed by the Apache log manager)
at (The global variable definition file, the first method to use getLogger)
at (The main method for our software, where the globals are loaded)
Caused by: java.lang.NoSuchMethodError: javax.mail.Session.setProtocolForAddress(Ljava/lang/String;Ljava/lang/String;)V
at org.apache.logging.log4j.core.net.SmtpManager$SMTPManagerFactory.createManager(SmtpManager.java:325)
at org.apache.logging.log4j.core.net.SmtpManager$SMTPManagerFactory.createManager(SmtpManager.java:299)
at org.apache.logging.log4j.core.appender.AbstractManager.getManager(AbstractManager.java:71)
at org.apache.logging.log4j.core.net.SmtpManager.getSMTPManager(SmtpManager.java:124)
at org.apache.logging.log4j.core.appender.SmtpAppender.createAppender(SmtpAppender.java:142)
... 21 more
2015-05-19 19:08:18,814 ERROR Null object returned for SMTP in Appenders.
2015-05-19 19:08:18,819 ERROR Unable to locate appender Mailer for logger fatalerror
The details of the configuration are correct (I know it's a valid IP, etc) - they worked in log4j 1. The error log tells me virtually nothing about the error, so I am hoping someone has heard of this before. Thanks everyone!
This is the important line from your stacktrace:
Caused by: java.lang.NoSuchMethodError: javax.mail.Session.setProtocolForAddress(Ljava/lang/String;Ljava/lang/String;)V
The setProtocolForAddress method has been part of JavaMail since version 1.4, so this suggests to me that you are using an old version of that JAR. If you are, try upgrading to a later version.
Note that log4j2 has many lookups, not just system properties. So you need to convert ${hostName} to ${sys:hostName}, and if you are using a lookup for the IP address, this may be the cause of the issue. (Try hardcoding all lookup values to exclude this possibility.)

Fitnesse : "could not detect death of command line test runner"

Each time we launch a fitnesse test, it ends by saying
Testing was interrupted and results are incomplete
And we have an exception :
Could not detect death of command line test runner.
java.lang.IllegalThreadStateException: process has not exited
at fitnesse.components.CommandRunner.join(CommandRunner.java:79)
at fitnesse.responders.run.slimResponder.SlimTestSystem.bye(SlimTestSystem.java:208)
at fitnesse.responders.run.MultipleTestsRunner.startTestSystemAndExecutePages(MultipleTestsRunner.java:118)
at fitnesse.responders.run.MultipleTestsRunner.internalExecuteTestPages(MultipleTestsRunner.java:88)
at fitnesse.responders.run.MultipleTestsRunner.executeTestPages(MultipleTestsRunner.java:60)
at fitnesse.responders.run.TestResponder.performExecution(TestResponder.java:190)
at fitnesse.responders.run.TestResponder.doExecuteTests(TestResponder.java:72)
at fitnesse.responders.run.TestResponder$TestExecutor.execute(TestResponder.java:106)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:600)
at org.apache.velocity.util.introspection.UberspectImpl$VelMethodImpl.doInvoke(UberspectImpl.java:395)
at org.apache.velocity.util.introspection.UberspectImpl$VelMethodImpl.invoke(UberspectImpl.java:384)
at org.apache.velocity.runtime.parser.node.ASTMethod.execute(ASTMethod.java:173)
at org.apache.velocity.runtime.parser.node.ASTReference.execute(ASTReference.java:280)
at org.apache.velocity.runtime.parser.node.ASTReference.render(ASTReference.java:369)
at org.apache.velocity.runtime.parser.node.SimpleNode.render(SimpleNode.java:342)
at org.apache.velocity.runtime.directive.Parse.render(Parse.java:260)
at org.apache.velocity.runtime.parser.node.ASTDirective.render(ASTDirective.java:207)
at org.apache.velocity.runtime.parser.node.SimpleNode.render(SimpleNode.java:342)
at org.apache.velocity.Template.merge(Template.java:356)
at org.apache.velocity.Template.merge(Template.java:260)
at fitnesse.responders.templateUtilities.HtmlPage.render(HtmlPage.java:80)
at fitnesse.responders.run.TestResponder.doSending(TestResponder.java:61)
at fitnesse.responders.ChunkingResponder.startSending(ChunkingResponder.java:66)
at fitnesse.http.ChunkedResponse.sendTo(ChunkedResponse.java:26)
at fitnesse.FitNesseExpediter.sendResponse(FitNesseExpediter.java:96)
at fitnesse.FitNesseExpediter.start(FitNesseExpediter.java:48)
at fitnesse.FitNesseServer.serve(FitNesseServer.java:24)
at fitnesse.FitNesseServer.serve(FitNesseServer.java:17)
at fitnesse.socketservice.SocketService$ServerRunner.run(SocketService.java:109)
at java.lang.Thread.run(Thread.java:736)
Have you encountered the same problem ? How did you solved it ?
fitnesse version : 20121220
It's quite possible that you have a class reference that is hanging out there and that FitNesse cannot close. Or something is calling System.exit().
An example of the first is Selenium WebDriver. You must close() the browserDriver to get a clean end to a test.
The second is something that we unintentionally allowed in the past and has been changed in more recent releases. It's possible that updating to the latest EDGE might solve it.
However, more context is really required, as this is quite likely an issue in your configuration or your fixture.

JNDI with Active Directory PartialResultException

I am basically walking the LDAP tree in Active Directory.
At each level I query for "(objectClass=*)". When I do this on the root eg "dc=example,dc=com" I get the exception below. This works fine on our other LDAP instances. For some reason only on our Active Directory server I get this exception. I also get the same exception when using JXplorer on our Active Directory server.
From reading around online I found people saying you should turn on following, not sure what that means... So on my controls object (javax.naming.directory.SearchControls) that I pass with the query I call searchControls.setDerefLinkFlag(true). I also have tried setting it to false with the same result. Any a suggestions on what else could cause this? Maybe how I could fix it?
Note: In this post I changed the baseDn from dc=<my company domain> to example for my companies privacy.
javax.naming.PartialResultException: Unprocessed Continuation Reference(s); remaining name 'dc=example,dc=com'
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2820)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2794)
at com.sun.jndi.ldap.LdapCtx.searchAux(LdapCtx.java:1826)
at com.sun.jndi.ldap.LdapCtx.c_search(LdapCtx.java:1749)
at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_search(ComponentDirContext.java:368)
at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeDirContext.java:338)
at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCompositeDirContext.java:321)
at javax.naming.directory.InitialDirContext.search(InitialDirContext.java:248)
at com.motio.pi.gui.panels.useraccess.ldap.LDAPConnector.query(LDAPConnector.java:262)
at com.motio.pi.gui.selector.directory.CognosDirectoryBrowserController.expandCognosTreeNode(CognosDirectoryBrowserController.java:99)
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.motio.pi.utils.PIThreadDelegate$1.run(PIThreadDelegate.java:54)
at java.lang.Thread.run(Thread.java:662)
So when I was creating my naming context with the method:
javax.naming.ldap.InitialLdapContext.InitialLdapContext(
Hashtable<?, ?> environment, Control[] connCtls)
In the argument environment there is a property with the name Context.REFERRAL and its value should be set to: follow. This was the setting that I needed.
If you get an exception while referral usage in follow (for example: connection timed out) you can use referral ignore but you dont want to get partial exception you can use 3268 port number instead of 389 this port is using global catalog for ldap. You can find info from following link;
https://technet.microsoft.com/en-us/library/how-global-catalog-servers-work(v=ws.10).aspx

Categories

Resources