httpclient.execute error: java.lang.reflect.InvocationTargetException - apache-commons-httpclient

I am working on an SUP MBO project. I am trying to use a Result Set Filter to customize my MBO. In that class, I need http get something and customize the MBO rows based on the feedback. I use MobileSDK of SUP2.1.2 and try preview the resultset. I enabled the debugging and can see the output from the console.
The changed result set filter code piece looks like:
#Override
public ResultSet filter(ResultSet in, Map arg1)
throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("www.google.com");
HttpResponse response1 = httpclient.execute(httpGet);
httpGet.releaseConnection();
return in;
}
Each time when httpclient.execute(httpGet) gets called, an exception is thrown out as below:
00:06:42 [ERROR] [ExecuteSection]: Execution error
java.lang.reflect.InvocationTargetException
at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:421)
at org.eclipse.jface.dialogs.ProgressMonitorDialog.run(ProgressMonitorDialog.java:507)
at com.sybase.uep.tooling.ui.dialogs.preview.ExecuteSection.execute(ExecuteSection.java:227)
...
Caused by: java.lang.VerifyError: Cannot inherit from final class
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
...
at com.sybase.uep.tooling.ui.dialogs.preview.ExecuteSection$4.run(ExecuteSection.java:207)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121)
I tried different httpclient jar versions (including 3.0.1, 4.2) but always got the same failure.
Does anyone have any hint? Thanks.

Got the solution from here
Hi,
Normally "java.lang.reflect.InvocationTargetException" occurs when java compiler finds 2 different classes with same name in 2 different packages. when u r importing both classes at a time and when you r trying to create object of that class it throws "java.lang.reflect.InvocationTargetException" exception .
The solution is that when you are creating the object of the class use package name also along with class name so that compiler knows what class it has to use.

Related

Spring Boot #RequestScope and Hibernate schema based multi-tenancy

I'm working on a schema based multi-tenant app, in which I want to resolve the Tenant Identifier using a #RequestScope bean. My understanding is that #RequestScope uses/injects proxies for the request scoped beans, wherever they are referred (e.g. in other singleton beans). However, this is not working in the #Component that implements CurrentTenantIdentifierResolver and I get the following error when I start my service,
Caused by: org.springframework.beans.factory.support.ScopeNotActiveException: Error creating bean with name 'scopedTarget.userContext': Scope 'request' is not active for the current thread;
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
Following are the relevant pieces of code.
#Component
public class CurrentTenant implements CurrentTenantIdentifierResolver {
#Autowired
private UserContext userContext;
#Override
public String resolveCurrentTenantIdentifier() {
return Optional.of(userContext)
.map(u -> u.getDomain())
.get();
}
#Component
#RequestScope
public class UserContext {
private UUID id;
private String domain;
My questions,
Isn't the proxy for the #RequestScope injected (by default)? Do I need to do anything more?
Is Hibernate/Spring trying to establish a connection to the DB at startup (even when there is no tenant available)?
Hibernate properties:
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
properties.remove(AvailableSettings.DEFAULT_SCHEMA);
properties.put(AvailableSettings.MULTI_TENANT, MultiTenancyStrategy.SCHEMA);
properties.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, tenantResolver);
properties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, connectionProvider);
For the time being, I'm preventing the NullPointerException by checking if we are in the RequestContext. However, a connection still gets established to the master database (although I've explicitly specified the dialect and am not specifying hbm2ddl.auto). Since this connection is not associated with any schema, I'd like to avoid making it, so that it does not look for any tables that it won't find anyways.
What seems to be happenning is that when a HTTP request is received, hibernate is trying to resolve the current tenant identifier, even before my #RequestScope bean is created (and even before my #RestController method is called.) If a provide the default connection to the databse, I then get the following error. If I don't provide a connection, it throws an exception and aborts.
2021-09-26 11:55:44.882 WARN 19759 --- [nio-8082-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42P01
2021-09-26 11:55:44.882 ERROR 19759 --- [nio-8082-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: relation "employees" does not exist
Position: 301
2021-09-26 11:55:44.884 ERROR 19759 --- [nio-8082-exec-2] o.t.n.controller.EmployeeController : Exception: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

SpEL evaluation of path variable in WebsocketSecurityConfiguration

I am running a JHipster 6.1.2 Gateway with Websockets and am trying to restrict access to a messaging topic, so that users can only subscribe to topics of the institution they belong to. So basically I want to perform a check on the id from the subscription path.
My current solution is based on https://stackoverflow.com/a/44895369/4246074 and looks as follows:
WebsocketSecurityConfiguration.java:
#Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
//...
//User can only subscribe to own institution topic
.simpSubscribeDestMatchers("/topic/institution.{id}")
.access("#institutionIdGuard.checkInstitutionId(#id)")
//...
}
InstitutionIdGuard.java:
#Component
public class InstitutionIdGuard {
public boolean checkInstitutionId(Long institutionId) {
//validation logic for institutionId would go here
return true;
}
The problem:
Apparently the SpEL expression can't access {id} from the path because i get a nullpointer error with the following log:
2019-08-08 10:30:08.367 ERROR 31097 --- [ XNIO-1 I/O-1] o.s.w.s.m.StompSubProtocolHandler : Failed to send client message to application via MessageChannel in session j2a0jlos. Sending STOMP ERROR to client.
org.springframework.messaging.MessageDeliveryException: Failed to send message to ExecutorSubscribableChannel[clientInboundChannel]; nested exception is java.lang.IllegalArgumentException: Failed to evaluate expression '#institutionIdGuard.checkInstitutionId(#id)'
at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:146)
at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:122)
at org.springframework.web.socket.messaging.StompSubProtocolHandler.handleMessageFromClient(StompSubProtocolHandler.java:284)
at org.springframework.web.socket.messaging.SubProtocolWebSocketHandler.handleMessage(SubProtocolWebSocketHandler.java:324)
at org.springframework.web.socket.handler.WebSocketHandlerDecorator.handleMessage(WebSocketHandlerDecorator.java:75)
at org.springframework.web.socket.handler.LoggingWebSocketHandlerDecorator.handleMessage(LoggingWebSocketHandlerDecorator.java:56)
at org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator.handleMessage(ExceptionWebSocketHandlerDecorator.java:58)
at org.springframework.web.socket.sockjs.transport.session.AbstractSockJsSession.delegateMessages(AbstractSockJsSession.java:386)
at org.springframework.web.socket.sockjs.transport.session.WebSocketServerSockJsSession.handleMessage(WebSocketServerSockJsSession.java:195)
at org.springframework.web.socket.sockjs.transport.handler.SockJsWebSocketHandler.handleTextMessage(SockJsWebSocketHandler.java:93)
at org.springframework.web.socket.handler.AbstractWebSocketHandler.handleMessage(AbstractWebSocketHandler.java:43)
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.handleTextMessage(StandardWebSocketHandlerAdapter.java:113)
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.access$000(StandardWebSocketHandlerAdapter.java:42)
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$3.onMessage(StandardWebSocketHandlerAdapter.java:84)
at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter$3.onMessage(StandardWebSocketHandlerAdapter.java:81)
at io.undertow.websockets.jsr.FrameHandler$7.run(FrameHandler.java:286)
at io.undertow.websockets.jsr.ServerWebSocketContainer$1.call(ServerWebSocketContainer.java:170)
at io.undertow.websockets.jsr.ServerWebSocketContainer$1.call(ServerWebSocketContainer.java:167)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at io.undertow.websockets.jsr.ServerWebSocketContainer.invokeEndpointMethod(ServerWebSocketContainer.java:604)
at io.undertow.websockets.jsr.ServerWebSocketContainer.invokeEndpointMethod(ServerWebSocketContainer.java:594)
at io.undertow.websockets.jsr.FrameHandler.invokeTextHandler(FrameHandler.java:266)
at io.undertow.websockets.jsr.FrameHandler.onFullTextMessage(FrameHandler.java:317)
at io.undertow.websockets.core.AbstractReceiveListener$2.complete(AbstractReceiveListener.java:156)
at io.undertow.websockets.core.AbstractReceiveListener$2.complete(AbstractReceiveListener.java:152)
at io.undertow.websockets.core.BufferedTextMessage.read(BufferedTextMessage.java:105)
at io.undertow.websockets.core.AbstractReceiveListener.readBufferedText(AbstractReceiveListener.java:152)
at io.undertow.websockets.core.AbstractReceiveListener.bufferFullMessage(AbstractReceiveListener.java:90)
at io.undertow.websockets.jsr.FrameHandler.onText(FrameHandler.java:182)
at io.undertow.websockets.core.AbstractReceiveListener.handleEvent(AbstractReceiveListener.java:44)
at io.undertow.websockets.core.AbstractReceiveListener.handleEvent(AbstractReceiveListener.java:33)
at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
at io.undertow.server.protocol.framed.AbstractFramedChannel$FrameReadListener.handleEvent(AbstractFramedChannel.java:951)
at io.undertow.server.protocol.framed.AbstractFramedChannel$FrameReadListener.handleEvent(AbstractFramedChannel.java:932)
at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
at org.xnio.conduits.ReadReadyHandler$ChannelListenerHandler.readReady(ReadReadyHandler.java:66)
at org.xnio.nio.NioSocketConduit.handleReady(NioSocketConduit.java:88)
at org.xnio.nio.WorkerThread.run(WorkerThread.java:561)
Caused by: java.lang.IllegalArgumentException: Failed to evaluate expression '#institutionIdGuard.checkInstitutionId(#id)'
at org.springframework.security.access.expression.ExpressionUtils.evaluateAsBoolean(ExpressionUtils.java:30)
at org.springframework.security.messaging.access.expression.MessageExpressionVoter.vote(MessageExpressionVoter.java:57)
at org.springframework.security.messaging.access.expression.MessageExpressionVoter.vote(MessageExpressionVoter.java:39)
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:63)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233)
at org.springframework.security.messaging.access.intercept.ChannelSecurityInterceptor.preSend(ChannelSecurityInterceptor.java:69)
at org.springframework.messaging.support.AbstractMessageChannel$ChannelInterceptorChain.applyPreSend(AbstractMessageChannel.java:178)
at org.springframework.messaging.support.AbstractMessageChannel.send(AbstractMessageChannel.java:132)
... 37 common frames omitted
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1004E: Method call: Method checkInstitutionId(null) cannot be found on type com.mycompany.websocketgateway.security.InstitutionIdGuard
at org.springframework.expression.spel.ast.MethodReference.findAccessorForMethod(MethodReference.java:225)
at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:134)
at org.springframework.expression.spel.ast.MethodReference.access$000(MethodReference.java:54)
at org.springframework.expression.spel.ast.MethodReference$MethodValueRef.getValue(MethodReference.java:390)
at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:90)
at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:114)
at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:300)
at org.springframework.security.access.expression.ExpressionUtils.evaluateAsBoolean(ExpressionUtils.java:26)
... 44 common frames omitted
I would be grateful for any ideas how to make my solution work or other other ways of performing checks in the id.
I found the solution on the Spring Security issue tracker. Apparently before Spring Security 5.2 you can pass the implicit message variable to the SpEL expression
.simpSubscribeDestMatchers("/topic/institution.*")
.access("#institutionIdGuard.checkInstitutionId(authentication, message)")
Then in the verification method its possible to get the path from the message and do your own verification with it:
public boolean checkInstitutionId(Authentication authentication, Message<?> message) {
StompHeaderAccessor sha = StompHeaderAccessor.wrap(message);
String topic = sha.getDestination();
String id = topic.replace("/topic/institution/", "");
//validation logic for institutionId would go here
return true;
}
Spring Security 5.2 should have fixed the issue according to this pull request.

NullPointerException at (DefaultListableBeanFactory.java:104)

I'm getting the following stack trace when I try to run my code from main method.
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.koushik.javabrains.DrawingApp.main(DrawingApp.java:19)
Caused by: java.lang.NullPointerException
at org.springframework.beans.factory.support.DefaultListableBeanFactory.<clinit>(DefaultListableBeanFactory.java:104)
... 1 more
here is the code.
FileSystemResource newResource = new FileSystemResource("spring.xml");
BeanFactory factory = new XmlBeanFactory(newResource);
Triangle triangle = (Triangle) factory.getBean("triangle");
triangle.draw();
Can anyone please tell me why I get this exception and How do I resolve it?
error is thrown at first line (FileSystemResource newResource = new FileSyste....)
Thanks in advance :)
You should use ApplicationContext instead:
ApplicationContext ctx = new FileSystemXmlApplicationContext("spring.xml");
But, of course, you have to provide correct config file location: seems to me full path.

Spring 3.1 with hibernate 4 can't use stored procedure with OracleTypes

Recently we upgraded from hibernate 3.5 to 4.1.7 as well as spring from 3.0.5 to 3.1.3. Hibernate is configured via jpa in spring so no changes is made.
After the upgrade, most of the stuff works fine but one function that uses stored procedure is broken with the following exception:
java.lang.ClassCastException: $Proxy188 cannot be cast to oracle.jdbc.OracleConnection
at oracle.sql.TypeDescriptor.setPhysicalConnectionOf(TypeDescriptor.java:829)
at oracle.sql.TypeDescriptor.(TypeDescriptor.java:583)
at oracle.sql.ArrayDescriptor.(ArrayDescriptor.java:224)
at org.springframework.data.jdbc.support.oracle.SqlArrayValue.createTypeValue(SqlArrayValue.java:71)
at org.springframework.jdbc.core.support.AbstractSqlTypeValue.setTypeValue(AbstractSqlTypeValue.java:58)
at org.springframework.jdbc.core.StatementCreatorUtils.setValue(StatementCreatorUtils.java:281)
at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValueInternal(StatementCreatorUtils.java:217)
at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValue(StatementCreatorUtils.java:128)
at org.springframework.jdbc.core.CallableStatementCreatorFactory$CallableStatementCeatorImpl.createCallableStatement(CallableStatementCreatorFactory.java:212)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:1008)
at org.springframework.jdbc.core.JdbcTemplate.call(JdbcTemplate.java:1064)
at org.springframework.jdbc.object.StoredProcedure.execute(StoredProcedure.java:144)
In debug mode, I found the AbsructSqlTypeValue.setTypeValue() method has the following implementation:
public final void setTypeValue(PreparedStatement ps, int paramIndex, int sqlType, String typeName)
throws SQLException {
Object value = createTypeValue(ps.getConnection(), sqlType, typeName);
if (sqlType == TYPE_UNKNOWN) {
ps.setObject(paramIndex, value);
}
else {
ps.setObject(paramIndex, value, sqlType);
}
}
The ps.getConnection() method here actually returns a new Hibernate 4 LogicalConnectionImpl which wraps around the real OracleConnection. And that's why the it throws the ClassCastException in Oracle driver.
The reason why it calls to oracle.SqlArrayValue is because the stored procedure takes list of longs as input parameter. When the input parameter is defined, we uses OracleTypes.ARRAY then while binding the values, we create a new SqlArrayValue object to wrap around the Long[]. I tried to use the generic Types.Array and Long[] directly but it didn't work either with the following exception:
Caused by: java.sql.SQLException: Fail to convert to internal representation: [Ljava.lang.Long;#337f5afe
at oracle.sql.ARRAY.toARRAY(ARRAY.java:187)
at oracle.jdbc.driver.OraclePreparedStatement.setObjectCritical(OraclePreparedStatement.java:8782)
at oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:8278)
at oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:8877)
at oracle.jdbc.driver.OracleCallableStatement.setObject(OracleCallableStatement.java:4992)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.setObject(OraclePreparedStatementWrapper.java:240)
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 oracle.ucp.jdbc.proxy.StatementProxyFactory.invoke(StatementProxyFactory.java:230)
at oracle.ucp.jdbc.proxy.PreparedStatementProxyFactory.invoke(PreparedStatementProxyFactory.java:124)
at oracle.ucp.jdbc.proxy.CallableStatementProxyFactory.invoke(CallableStatementProxyFactory.java:101)
at $Proxy214.setObject(Unknown Source)
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 org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
I don't understand why the jdbcTemplate somehow uses the hibernate connection instead of the native OracleConnection, maybe there is some configuration somewhere can fix it magically?
Found the root cause of it. The class that extends StoredProcedure didn't define the jdbcTemplate property so the default one is used which doesn't have nativeJdbcExtractor defined. After adding the jdbcTemplate dependency to refer to the one defined with org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor as nativeJdbcExtractor resolve the issue. I guess hibernate 3.5 with spring 3.0 doesn't have this issue since at that time the returned jdbc connection is already the OracleConnection.

cannot initialize Quartz Scheduler in Spring

I'm trying to use Quartz 1.8.5 (and I also tried Quartz2.0 - same issue) with Spring 3.0.0.
However, I do not want to use Spring's utility wrappers for Quartz schedulers, triggers, jobs...
I would like to create all these objects programmatically from my application, just like in a
standalone Java app with no container - for many reasons, but mainly because i have requirements for
dynamic triggers and JobDetails...
So, I have my quartz.properties on the classpath, where I define a JobStoreTX:
org.quartz.scheduler.instanceName: NotificationsScheduler
org.quartz.scheduler.instanceId: AUTO
org.quartz.scheduler.skipUpdateCheck: true
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 3
org.quartz.threadPool.threadPriority: 5
org.quartz.jobStore.misfireThreshold: 60000
org.quartz.jobStore.class: org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.useProperties: false
org.quartz.jobStore.dataSource: qzDS
org.quartz.jobStore.tablePrefix: QRTZ_
org.quartz.jobStore.isClustered: false
org.quartz.dataSource.qzDS.driver: com.mysql.jdbc.Driver
org.quartz.dataSource.qzDS.URL: jdbc:mysql://localhost:3306/myschema
org.quartz.dataSource.qzDS.user: myuser
org.quartz.dataSource.qzDS.password: mypwd
org.quartz.dataSource.qzDS.maxConnections: 5
Then, I have a simple Initializer class, taken almost as is from example1 of Quartz distribution,
which is using an un-modified HelloJob from the same example:
public class NotificationInitializer {
public void init(){
try {
SchedulerFactory schdFact = new StdSchedulerFactory("quartz.properties");
Scheduler schd = schdFact.getScheduler();
schd.start();
JobDetail jd = new JobDetail("hellojob", Scheduler.DEFAULT_GROUP, HelloJob.class);
Trigger t = TriggerUtils.makeImmediateTrigger(2, 1000);
t.setStartTime(new Date());
schd.scheduleJob(jd, t);
// wait long enough so that the scheduler as an opportunity to run
..........
schd.shutdown(true);
} catch (SchedulerException e) {
.....
}
}
}
And I also have a simple unit test that calls this class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:spring/applicationContext.xml")
public class NotificationInitializerTest {
private final static Logger logger = LoggerFactory
.getLogger(NotificationInitializerTest.class);
#BeforeClass
public static void setupClass() {
PropertyConfigurator.configure(Loader
.getResource("spring/log4j.properties"));
PropertyConfigurator.configure(Loader
.getResource("spring/quartz.properties"));
}
#Test
public void testInit() {
NotificationInitializer ni = new NotificationInitializer();
ni.init();
logger.info("NotificationInitializer.init() finished OK");
}
}
And when I run this unit test I'm getting the following errors - see the full stack trace below:
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'org.springframework.jdbc.datasource.init.DataSour ceInitializer#0':
Invocation of init method failed; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
Query was empty
Any idea what went wrong?
Also, I am setting up JobStoreTX for now - just to make sure I can get it working,
but eventually I would like to use the JobStoreCMT toplug intoSpring's transaction management.
I could not find any good documentation/examples on how to do that, especially if I don't want to use
Spring's wrappers for schedulers and hardcode all trigger definitions...
Thanks!
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDeendencies (DependencyInjectionTestExecutionListener.java:109 )
at org.springframework.test.context.support.Dependenc yInjectionTestExecutionListener.prepareTestInstanc e(DependencyInjectionTestExecutionListener.java:75 )
at org.springframework.test.context.TestContextManage r.prepareTestInstance(TestContextManager.java:333)
at org.springframework.test.context.junit4.SpringJUni t4ClassRunner.createTest(SpringJUnit4ClassRunner.j ava:220)
at
.....
Caused by: org.springframework.beans.factory.BeanCreationExce ption: Error creating bean with name 'org.springframework.jdbc.datasource.init.DataSour ceInitializer#0': Invocation of init method failed; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorEx ception: Query was empty
at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.initializeBean(Abstract AutowireCapableBeanFactory.java:1401)
at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.doCreateBean(AbstractAu towireCapableBeanFactory.java:512)
at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.createBean(AbstractAuto wireCapableBeanFactory.java:450)
at org.springframework.beans.factory.support.Abstract BeanFactory$1.getObject(AbstractBeanFactory.java:2 90)
at org.springframework.beans.factory.support.DefaultS ingletonBeanRegistry.getSingleton(DefaultSingleton BeanRegistry.java:222)
at org.springframework.beans.factory.support.Abstract BeanFactory.doGetBean(AbstractBeanFactory.java:287 )
at org.springframework.beans.factory.support.Abstract BeanFactory.getBean(AbstractBeanFactory.java:189)
at org.springframework.beans.factory.support.DefaultL istableBeanFactory.preInstantiateSingletons(Defaul tListableBeanFactory.java:557)
at org.springframework.context.support.AbstractApplic ationContext.finishBeanFactoryInitialization(Abstr actApplicationContext.java:842)
at org.springframework.context.support.AbstractApplic ationContext.refresh(AbstractApplicationContext.ja va:416)
at org.springframework.test.context.support.AbstractG enericContextLoader.loadContext(AbstractGenericCon textLoader.java:84)
at org.springframework.test.context.support.AbstractG enericContextLoader.loadContext(AbstractGenericCon textLoader.java:1)
at org.springframework.test.context.TestContext.loadA pplicationContext(TestContext.java:280)
at org.springframework.test.context.TestContext.getAp plicationContext(TestContext.java:304)
... 25 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorEx ception: Query was empty
at sun.reflect.NativeConstructorAccessorImpl.newInsta nce0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInsta nce(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newI nstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:40 6)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLErro r.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLErro r.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.ja va:3491)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.ja va:3423)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:19 36)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java :2060)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionIm pl.java:2536)
at com.mysql.jdbc.StatementImpl.executeUpdate(Stateme ntImpl.java:1564)
at com.mysql.jdbc.StatementImpl.executeUpdate(Stateme ntImpl.java:1485)
at org.apache.commons.dbcp.DelegatingStatement.execut eUpdate(DelegatingStatement.java:228)
at org.springframework.jdbc.datasource.init.ResourceD atabasePopulator.executeSqlScript(ResourceDatabase Populator.java:157)
at org.springframework.jdbc.datasource.init.ResourceD atabasePopulator.populate(ResourceDatabasePopulato r.java:110)
at org.springframework.jdbc.datasource.init.DataSourc eInitializer.afterPropertiesSet(DataSourceInitiali zer.java:69)
at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.invokeInitMethods(Abstr actAutowireCapableBeanFactory.java:1460)
at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.initializeBean(Abstract AutowireCapableBeanFactory.java:1398)
...
I recently came across this issue too, (I was using Java7 under Mac OS X), the following worked for me:
first of all, test if the method java.net.InetAddress.getLocalHost() works, if it throws exception like:
Caused by: java.net.UnknownHostException: leo-mbp: nodename nor servname provided, or not known
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:901)
at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1293)
at java.net.InetAddress.getLocalHost(InetAddress.java:1469)
run the following to workaround it:
scutil --set HostName "localhost"
Hope it's helpful to you.
#blob : you were right on target. After spending hours trying to figure out why the NotificationInitializer was not initialized (as the error message suggested....) I finally tried to remove the Quartz DB initialization script from my Spring config - and everything worked like a charm!
<jdbc:initialize-database data-source="dataSource"
enabled="${database.initschema}">
<jdbc:script location="${database.schemaLoc}" />
<jdbc:script location="${database.seedLoc}" />
<!-- <jdbc:script location="classpath:db/tables_mysql_innodb_1.8.5.sql" /> -->
</jdbc:initialize-database>
I just wish Spring error messages were a bit more specific... :)
Now, I still don't understand why I cannot create the DB tables for Quartz this way - the same scripts works just fine when run directly on the DB. Maybe some weird sequence of startup actions in Spring?
thanks!
Only a guess: Check if you need to specify a connection validation query. Something like
validationQuery="select 1"
Changing "org.quartz.scheduler.instanceId" from AUTO to 10 in quartz.properties file worked for me.

Resources