Closing Connection from WildFly Datasource cause java.net.SocketException - jdbc

I'm using WildFly 10.0.0 and MySQL 5.5.17 and JDBC Driver 5.1.39
I first set a DataSouce in WildFly as a module
in the folder WILDFLY_HOME\modules\system\layers\base\com\mysql\main there is the driver and the file module.xml :
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="com.mysql">
<resources>
<resource-root path="mysql-connector-java-5.1.39-bin.jar"/>
</resources>
<dependencies>
<module name="javax.api"/>
<module name="javax.transaction.api"/>
</dependencies>
</module>
And the config file standalone-full.xml :
<subsystem xmlns="urn:jboss:domain:datasources:4.0">
<datasources>
<datasource jta="false" jndi-name="java:/jdbc/MyDS" pool-name="MyDS" enabled="true" use-ccm="false">
<connection-url>jdbc:mysql://www.my-url.com:3306/my_db</connection-url>
<driver>mysql</driver>
<pool>
<min-pool-size>5</min-pool-size>
<max-pool-size>20</max-pool-size>
<prefill>true</prefill>
</pool>
<security>
<user-name>login</user-name>
<password>password</password>
</security>
</datasource>
<drivers>
<driver name="mysql" module="com.mysql">
<driver-class>com.mysql.jdbc.Driver</driver-class>
<xa-datasource-class>com.mysql.jdbc.Driver</xa-datasource-class>
</driver>
</drivers>
</datasources>
</subsystem>
When I test the connection within the wildfly console I have the message : "Successfully created JDBC connection.
Successfully connected to database MyDS"
When I try to use this DataSource doing :
#Resource(mappedName = "java:/jdbc/MyDS")
private DataSource dataSource;
private Integer selectId(String mail) {
try (Connection connection = dataSource.getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(getQuery())) {
statement.setString(1, mail);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
Integer id = resultSet.getInt(1);
return id;
} else {
return null;
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
I have this Exception :
The last packet successfully received from the server was 2 621 144 milliseconds ago. The last packet sent successfully to the server was 2 621 171 milliseconds ago.
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:422)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:988)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3739)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2508)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2673)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2549)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1962)
at org.jboss.jca.adapters.jdbc.WrappedPreparedStatement.executeQuery(WrappedPreparedStatement.java:504)
at my.app.mail.service.MailService.selectId(LoginService.java:46)
... 129 more
Caused by: java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3721)
... 136 more
When I do :
#Resource(mappedName = "java:/jdbc/MyDS")
private DataSource dataSource;
private Integer selectId(String mail) {
try {
Connection connection = dataSource.getConnection();
try (PreparedStatement statement = connection.prepareStatement(getQuery())) {
statement.setString(1, mail);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
Integer id = resultSet.getInt(1);
return id;
} else {
return null;
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
It works...
How I have to handle DataSource? Do problems will occurs if I don't close Connection? Maybe it's a problem of DataSource config...

Related

How to propogate an exception from tcp outbound gateway to upstream SI components

I have been searching over the internet and have been trying different ways to make it work but I couldn't get it working.
Actually my system need to connect to multiple tcp server endpoints (which we call payers endpoint) as a tcp client application. The client components include the throttling and queuing components and they get initialized dynamically based on the payers configurations stored in DB as a separate application context. I have created a tcp outbound gateway for this purpose and which is being initialized in a dynamic context based on the ideas given in
https://github.com/spring-projects/spring-integration-samples/tree/master/advanced
What I want is to catch/get exceptions to the calling code at the time calling the payersGateway component in case of any error. But I am unable to receive the exceptions back.
My context file for tcp client connectivity is as follow:
dynamic-tcp-gateway-context file
<context:property-placeholder/>
<int-ip:tcp-connection-factory id="client"
type="client"
host="${host}"
port="${port}"
single-use="true"
so-timeout="${soTimeout}"
serializer="byteArrayLfSerializer"
deserializer="ediTcpSerializer"
/>
<bean id="ediTcpSerializer" class="com.abc.throttling.EdiTcpSerializer">
<property name="maxMessageSize" value="20480000"/>
</bean>
<bean id="byteArrayLfSerializer" class="org.springframework.integration.ip.tcp.serializer.ByteArrayLfSerializer">
<property name="maxMessageSize" value="20480000"/>
</bean>
<int:channel id="toPayerChannel">
<int:dispatcher task-executor="producerThreadExecutor"/>
</int:channel>
<task:executor id="producerThreadExecutor" pool-size="10" queue-capacity="50" rejection-policy="ABORT"/>
<int:channel id="throttlerChannel">
<int:priority-queue capacity="${queueSize:1000}"/> <!-- for example queue size, you can increase this capacity
based on your
requirement -->
</int:channel>
<int:bridge input-channel="toPayerChannel" output-channel="throttlerChannel" />
<int-ip:tcp-outbound-gateway id="outGateway"
request-channel="throttlerChannel"
connection-factory="client"
request-timeout="10000"
reply-timeout="${replyTimeout}">
<int:poller id="tcpPoller" error-channel="errorChannel" fixed-rate="1000" max-messages-per-poll="${messageRate:20}"/>
</int-ip:tcp-outbound-gateway>
<int:transformer input-channel="errorChannel"
ref="exceptionTransformer" method="createErrorResponse"/>
<bean id="exceptionTransformer" class="com.stella.healthenet.throttling.TcpGatewayExceptionTransformer"/>
<int:object-to-string-transformer input-channel="errorChannel"/>
application context for main payers connectivity is as follow:
main-payers-gateway-context file
<context:component-scan base-package="com.abc.throttling" />
class="com.abc.throttling.DynamicTcpChannelResolverTest" id="dynamicTcpChannelResolverTest"/>-->
<int:gateway id="payersGateway"
service-interface="com.abc.gateway.PayersGateway"
default-request-channel="toDynRouter"
default-request-timeout="1000000"
default-reply-timeout="${payersGateway.defaultReplyTimout}"
/>
<int:converter ref="converter"/>
<bean class="com.abc.manager.edi.core.core4.ByteArrayToStringConverter" id="converter"/>
<int:converter ref="converter2"/>
<bean class="com.abc.manager.edi.core.core2.Core2RealTimeResponseToString" id="converter2"/>
<int:converter ref="converter3"/>
<bean class="com.abc.manager.edi.core.core4.Core4RealTimeResponseToString" id="converter3"/>
<int:channel id="toDynRouter" />
<int:router resolution-required="true" input-channel="toDynRouter"
expression="#dynamicPayerChannelResolver.resolve(headers['payer'])" >
</int:router>
The code for dynamic channel resolver is as follow:
#Component("dynamicPayerChannelResolver")
public class DynamicPayerChannelResolver {
#Value("${throttling.payersChannelQueueSize}")
private String payersChannelQueueSize;
#Value("${throttling.tcpSoTimeout}")
private String tcpSoTimeout;
#Value("${tcpOutboundGateway.replyTimeout}")
private String tcpReplyTimeout;
#Autowired
private ApplicationContext applicationContext;
public static final int MAX_CACHE_SIZE = 30;
private static final org.apache.logging.log4j.Logger LOG = LogManager.getLogger();
#Autowired
PayerRepositoryService payerRepositoryService;
private final Map<UUID, MessageChannel> channels = Collections.synchronizedMap(new LinkedHashMap<UUID,
MessageChannel>(){
private static final long serialVersionUID = 1L;
#Override
protected boolean removeEldestEntry(
Entry<UUID, MessageChannel> eldest) {
//This returning true means the least recently used
//channel and its application context will be closed and removed
boolean remove = size() > MAX_CACHE_SIZE;
if(remove) {
MessageChannel channel = eldest.getValue();
ConfigurableApplicationContext ctx = contexts.get(channel);
if(ctx != null) { //shouldn't be null ideally
ctx.close();
contexts.remove(channel);
}
}
return remove;
}
});
private final Map<MessageChannel, ConfigurableApplicationContext> contexts =
new HashMap<MessageChannel, ConfigurableApplicationContext>();
/**
* Resolve a payer to a channel, where each payer gets a private
* application context and the channel is the inbound channel to that
* application context.
*
* #param payer
* #return a channel
*/
public MessageChannel resolve(UUID payer) {
MessageChannel channel = this.channels.get(payer);
if (channel == null) {
channel = createNewPayerChannel(payerRepositoryService.findPayerByPayerId(payer));
}
return channel;
}
private synchronized MessageChannel createNewPayerChannel(PayerEntity payer) {
MessageChannel channel = this.channels.get(payer.getPayerId());
if (channel == null) {
ConfigurableApplicationContext ctx;
if(TransportType.SOAP_WSDL.getValue().equals(payer.getConnTransportType())){
ctx = new ClassPathXmlApplicationContext(
new String[] { "dynamic-soap-gateway-context.xml" },
false,applicationContext);
}
else{
ctx = new ClassPathXmlApplicationContext(
new String[] { "dynamic-tcp-gateway-context.xml" },
false,applicationContext);
}
this.setEnvironmentForPayer(ctx, payer);
ctx.refresh();
channel = ctx.getBean("toPayerChannel", MessageChannel.class);
this.channels.put(payer.getPayerId(), channel);
//Will works as the same reference is presented always
this.contexts.put(channel, ctx);
}
return channel;
}
public void updatePollerConfigs() {
Iterator it = this.channels.entrySet().iterator();
while(it.hasNext()){
Map.Entry pair = (Map.Entry)it.next();
PayerEntity payer = this.payerRepositoryService.findPayerByPayerId((UUID)pair.getKey());
final String transportType = payer.getConnTransportType();
if(TransportType.SOAP_WSDL.getValue().equals(transportType)){
MessageChannel channel= this.channels.get(payer);
ConfigurableApplicationContext ctx;
ctx=this.contexts.get(channel);
PollingConsumer pc = ctx.getBean("soapPoller",PollingConsumer.class);
//TODO: this value need to be set from payer configs in db.
pc.setMaxMessagesPerPoll(10);
}
else if (TransportType.X12_SOCKET.getValue().equals(transportType)) {
MessageChannel channel= this.channels.get(payer);
ConfigurableApplicationContext ctx;
ctx=this.contexts.get(channel);
PollingConsumer pc = ctx.getBean("outGateway",PollingConsumer.class);
//TODO: this value need to be set from payer configs in db.
pc.setMaxMessagesPerPoll(10);
}
}
}
private void setEnvironmentForPayer(ConfigurableApplicationContext ctx,
PayerEntity payer) {
final String transportType = payer.getConnTransportType();
final String endPoint = payer.getConnEndPoint();
if(payer.getMessageRate()==null){
throw new NullPointerException("MessageRate value is NULL in DB. Please specify a MessageRate value in " +
"Payers DB for PayerID: " + payer.getPayerId());
}
final String messageRate = payer.getMessageRate();
StandardEnvironment env = new StandardEnvironment();
Properties props = new Properties();
// populate properties for payer
;
if(TransportType.SOAP_WSDL.getValue().equals(transportType)){
props.setProperty("endpoint", endPoint);
props.setProperty("messageRate",messageRate);
props.setProperty("queueSize",payersChannelQueueSize);
}
else if (TransportType.X12_SOCKET.getValue().equals(transportType)) {
if (!endPoint.contains(":")) {
throw new Exception(ErrorType.UNEXPECTED, "Payer X12 Socket endpoint must include a port.");
}
final String ip;
if (endPoint.contains("/")) {
ip = endPoint.substring(endPoint.lastIndexOf('/') + 1, endPoint.lastIndexOf(":"));
} else {
ip = endPoint.substring(0, endPoint.lastIndexOf(":"));
}
final String port = endPoint.substring(endPoint.lastIndexOf(':') + 1);
props.setProperty("host", ip);
props.setProperty("port", port);
props.setProperty("messageRate",messageRate);
props.setProperty("queueSize",payersChannelQueueSize);
props.setProperty("soTimeout", tcpSoTimeout);
props.setProperty("replyTimeout",tcpReplyTimeout);
}
PropertiesPropertySource pps = new PropertiesPropertySource("payerChannelProps", props);
env.getPropertySources().addLast(pps);
ctx.setEnvironment(env);
}
I want to get the exceptions generated at the downstream components to appear at the payersGateway interface send method call i.e., shown below:
String response = payersGateway.send(
MessageBuilder.withPayload(requestMessage)
.setHeader("endpointUrl", endPoint)
.setHeader("senderId", coreSenderId)
.setHeader("receiverId", payerIdCode)
.setHeader("username", username)
.setHeader("password", password)
.setHeader("payloadType", payloadType)
.setHeader("nginxUrl", nginxUrl)
.setHeader("payer", payerId)
.setHeader("transType", transType)
.setHeader("priority", 1)
.build());
where the payersGateway is simple interface pointing to Gateway component in main context file.
public interface PayersGateway {
public String send(Message<String> message);
}
Please see the stack trace of produced exception as below:
[task-scheduler-1] ERROR org.springframework.integration.ip.tcp.TcpOutboundGateway - Tcp Gateway exception
java.net.ConnectException: Connection refused (Connection refused)
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:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
at javax.net.DefaultSocketFactory.createSocket(SocketFactory.java:271)
at org.springframework.integration.ip.tcp.connection.TcpNetClientConnectionFactory.createSocket(TcpNetClientConnectionFactory.java:76)
at org.springframework.integration.ip.tcp.connection.TcpNetClientConnectionFactory.buildNewConnection(TcpNetClientConnectionFactory.java:49)
at org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory.obtainNewConnection(AbstractClientConnectionFactory.java:116)
at org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory.obtainConnection(AbstractClientConnectionFactory.java:79)
at org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory.getConnection(AbstractClientConnectionFactory.java:69)
at org.springframework.integration.ip.tcp.TcpOutboundGateway.handleRequestMessage(TcpOutboundGateway.java:130)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:109)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
at org.springframework.integration.endpoint.PollingConsumer.handleMessage(PollingConsumer.java:129)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.doPoll(AbstractPollingEndpoint.java:272)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.access$000(AbstractPollingEndpoint.java:58)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:190)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:186)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller$1.run(AbstractPollingEndpoint.java:353)
at org.springframework.integration.util.ErrorHandlingTaskExecutor$1.run(ErrorHandlingTaskExecutor.java:55)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
at org.springframework.integration.util.ErrorHandlingTaskExecutor.execute(ErrorHandlingTaskExecutor.java:51)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller.run(AbstractPollingEndpoint.java:344)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
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)
[task-scheduler-1] ERROR org.springframework.integration.handler.LoggingHandler - org.springframework.messaging.MessagingException: Failed to send or receive; nested exception is java.net.ConnectException: Connection refused (Connection refused)
at org.springframework.integration.ip.tcp.TcpOutboundGateway.handleRequestMessage(TcpOutboundGateway.java:158)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:109)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
at org.springframework.integration.endpoint.PollingConsumer.handleMessage(PollingConsumer.java:129)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.doPoll(AbstractPollingEndpoint.java:272)
at org.springframework.integration.endpoint.AbstractPollingEndpoint.access$000(AbstractPollingEndpoint.java:58)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:190)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:186)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller$1.run(AbstractPollingEndpoint.java:353)
at org.springframework.integration.util.ErrorHandlingTaskExecutor$1.run(ErrorHandlingTaskExecutor.java:55)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
at org.springframework.integration.util.ErrorHandlingTaskExecutor.execute(ErrorHandlingTaskExecutor.java:51)
at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller.run(AbstractPollingEndpoint.java:344)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
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: java.net.ConnectException: Connection refused (Connection refused)
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:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
at javax.net.DefaultSocketFactory.createSocket(SocketFactory.java:271)
at org.springframework.integration.ip.tcp.connection.TcpNetClientConnectionFactory.createSocket(TcpNetClientConnectionFactory.java:76)
at org.springframework.integration.ip.tcp.connection.TcpNetClientConnectionFactory.buildNewConnection(TcpNetClientConnectionFactory.java:49)
at org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory.obtainNewConnection(AbstractClientConnectionFactory.java:116)
at org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory.obtainConnection(AbstractClientConnectionFactory.java:79)
at org.springframework.integration.ip.tcp.connection.AbstractClientConnectionFactory.getConnection(AbstractClientConnectionFactory.java:69)
at org.springframework.integration.ip.tcp.TcpOutboundGateway.handleRequestMessage(TcpOutboundGateway.java:130)
... 21 more
It should work as you need; exceptions before the throttlerChannel will be thrown directly to the caller; exceptions after that channel will be sent to the gateway by the poller's error handler.
Perhaps your gateway timeout is too short?
Turning on DEBUG logging and following the message flow should help you debug it.
EDIT
You can fix the missing failedMessage by adding a bean of this type to the Tcp outbound gateway's <int-ip:request-handler-advice-chain />...
public class FailedMessagePopulator extends AbstractRequestHandlerAdvice {
#Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
try {
return callback.execute();
}
catch (MessagingException e) {
if (e.getFailedMessage() == null) {
throw new MessageHandlingException(message, e.getMessage(), e);
}
else {
throw e;
}
}
catch (Exception e) {
throw new MessageHandlingException(message, e.getMessage(), e);
}
}
}
Note that you will need to add the error channel to the <gateway/> since the poller will now see the failed message and send the exception back to the gateway for error handling.

JSR-352 with Liberty Profile - 'ORA-01002: fetch out of sequence'

I am experimenting with the JSR-352 implementation in the Liberty Profile and have been stumped by an 'ORA-01002: fetch out of sequence' error after my reader processes the first 10 items of my JDBC ResultSet. My chunk size is set to 100.
Here is my reader:
#Dependent
#Named("myItemReader")
public class MyItemReader extends AbstractItemReader {
#Resource(name="jdbc/somedb",shareable=false)
private DataSource lavDb;
private PreparedStatement stmt;
private ResultSet rs;
#Override
public void open(Serializable checkpoint) throws Exception {
Connection con = lavDb.getConnection();
con.setAutoCommit(false);
stmt = con.prepareStatement("select id from sometable",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery();
}
#Override
public MyInputRecord readItem() throws Exception{
if(rs.next()){
return new MyInputRecord(rs.getInt(1));
}
return null;
}
#Override
public void close(){
try{
rs.close();
stmt.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
If the ResultSet processing occurs in the open() method then I do not encounter any errors.
Here is my batchPersistence configuration from my server.xml:
<dataSource id="oracle-wasadmin" jdbcDriverRef="wasoracledriver" jndiName="jdbc/wasoracledb" type="javax.sql.XADataSource">
<properties.oracle URL="${wasadmin.jdbcurl}" password="xxxxxx" user="yyyyyy"/>
<conionManager agedTimeout="1m" maxIdleTime="15m" maxPoolSize="25" minPoolSize="0"/>
</dataSource>
<jdbcDriver id="wasoracledriver" javax.sql.XADataSource="oracle.jdbc.xa.client.OracleXADataSource">
<library>
<fileset dir="${shared.resource.dir}/oracle" includes="*.jar"/>
</library>
</jdbcDriver>
Here is the error in the joblog:
com.ibm.jbatch.container.exception.BatchContainerRuntimeException: Failure in Read-Process-Write Loop
at com.ibm.jbatch.container.controller.impl.ChunkStepControllerImpl.invokeChunk(ChunkStepControllerImpl.java:702)
at com.ibm.jbatch.container.controller.impl.ChunkStepControllerImpl.invokeCoreStep(ChunkStepControllerImpl.java:792)
at com.ibm.jbatch.container.controller.impl.BaseStepControllerImpl.execute(BaseStepControllerImpl.java:292)
at com.ibm.jbatch.container.controller.impl.ExecutionTransitioner.doExecutionLoop(ExecutionTransitioner.java:118)
at com.ibm.jbatch.container.controller.impl.WorkUnitThreadControllerImpl.executeCoreTransitionLoop(WorkUnitThreadControllerImpl.java:94)
at com.ibm.jbatch.container.controller.impl.WorkUnitThreadControllerImpl.executeWorkUnit(WorkUnitThreadControllerImpl.java:155)
at com.ibm.jbatch.container.controller.impl.WorkUnitThreadControllerImpl$AbstractControllerHelper.runExecutionOnThread(WorkUnitThreadControllerImpl.java:480)
at com.ibm.jbatch.container.controller.impl.WorkUnitThreadControllerImpl.runExecutionOnThread(WorkUnitThreadControllerImpl.java:90)
at com.ibm.jbatch.container.util.BatchWorkUnit.run(BatchWorkUnit.java:117)
at com.ibm.ws.context.service.serializable.ContextualRunnable.run(ContextualRunnable.java:80)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.ibm.jbatch.container.exception.BatchContainerRuntimeException: java.sql.SQLException: ORA-01002: fetch out of sequence
at com.ibm.jbatch.container.controller.impl.ChunkStepControllerImpl.readItem(ChunkStepControllerImpl.java:354)
at com.ibm.jbatch.container.controller.impl.ChunkStepControllerImpl.readAndProcess(ChunkStepControllerImpl.java:245)
at com.ibm.jbatch.container.controller.impl.ChunkStepControllerImpl.invokeChunk(ChunkStepControllerImpl.java:626)
... 14 more
Caused by: java.sql.SQLException: ORA-01002: fetch out of sequence
I have additional logs, etc, if they would be helpful. Thanks in advance.
Don't cache JDBC Statement or ResultSet instances across threads. The JDBC programming model does not support multi-threaded access, which is likely why you are running into this error. And also why it works fine from within the open method, which runs on a single thread. When using JDBC, it is okay to cache DataSource, but not Connection or anything beneath Connection. Let the application server manage pooling of Connections and Statements, which it does in a thread safe way.

Writing java based JMS Client for WildFly10

I writing java based JMS Client for WildFly10 and I had problem
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
props.put(Context.PROVIDER_URL, WILDFLY_REMOTING_URL); // NOTICE: "http- remoting" and port "8080"
props.put(Context.SECURITY_PRINCIPAL, JMS_USERNAME);
props.put(Context.SECURITY_CREDENTIALS, JMS_PASSWORD);
//props.put("jboss.naming.client.ejb.context", true);
context = new InitialContext(props);
i run your client code and i got this error:
Got initial Context: javax.naming.InitialContext#5442a311
Exception in thread “main” org.jboss.naming.remote.protocol.NamingIOException: Failed to lookup [Root exception is java.io.IOException: java.lang.ClassNotFoundException: org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory]
at org.jboss.naming.remote.client.ClientUtil.namingException(ClientUtil.java:49)
at org.jboss.naming.remote.protocol.v1.Protocol$1.execute(Protocol.java:104)
at org.jboss.naming.remote.protocol.v1.RemoteNamingStoreV1.lookup(RemoteNamingStoreV1.java:95)
at org.jboss.naming.remote.client.HaRemoteNamingStore$1.operation(HaRemoteNamingStore.java:276)
at org.jboss.naming.remote.client.HaRemoteNamingStore.namingOperation(HaRemoteNamingStore.java:137)
at org.jboss.naming.remote.client.HaRemoteNamingStore.lookup(HaRemoteNamingStore.java:272)
at org.jboss.naming.remote.client.RemoteContext.lookup(RemoteContext.java:87)
at org.jboss.naming.remote.client.RemoteContext.lookup(RemoteContext.java:129)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at com.almasprocess.model.bl.WildFlyJmsQueueSender.init(WildFlyJmsQueueSender.java:49)
at com.almasprocess.model.bl.WildFlyJmsQueueSender.main(WildFlyJmsQueueSender.java:43)
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:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.io.IOException: java.lang.ClassNotFoundException: org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory
at org.jboss.naming.remote.protocol.v1.Protocol$1$3.read(Protocol.java:159)
at org.jboss.naming.remote.protocol.v1.Protocol$1$3.read(Protocol.java:149)
at org.jboss.naming.remote.protocol.v1.BaseProtocolCommand.readResult(BaseProtocolCommand.java:59)
at org.jboss.naming.remote.protocol.v1.Protocol$1.handleClientMessage(Protocol.java:149)
at org.jboss.naming.remote.protocol.v1.RemoteNamingStoreV1$MessageReceiver$1.run(RemoteNamingStoreV1.java:232)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:340)
at org.jboss.marshalling.AbstractClassResolver.loadClass(AbstractClassResolver.java:131)
at org.jboss.marshalling.AbstractClassResolver.resolveClass(AbstractClassResolver.java:112)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadClassDescriptor(RiverUnmarshaller.java:1002)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadNewObject(RiverUnmarshaller.java:1256)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:276)
at org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:209)
at org.jboss.marshalling.AbstractObjectInput.readObject(AbstractObjectInput.java:41)
at org.jboss.naming.remote.protocol.v1.Protocol$1$3.read(Protocol.java:156)
… 7 more
Process finished with exit code 1
And I changed code like this and add activemq lib in my project:
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
props.put(Context.PROVIDER_URL, WILDFLY_REMOTING_URL); // NOTICE: "http-remoting" and port "8080"
props.put(Context.SECURITY_PRINCIPAL, JMS_USERNAME);
props.put(Context.SECURITY_CREDENTIALS, JMS_PASSWORD);
and i got this error :
Got initial Context: javax.naming.InitialContext#6842775d
Exception in thread "main" javax.naming.NameNotFoundException: jms/RemoteConnectionFactory
at org.apache.activemq.jndi.ReadOnlyContext.lookup(ReadOnlyContext.java:225)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at com.almasprocess.model.bl.WildFlyJmsQueueSender.init(WildFlyJmsQueueSender.java:49)
at com.almasprocess.model.bl.WildFlyJmsQueueSender.main(WildFlyJmsQueueSender.java:43)
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:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
and standalone-full.xml config file like this :
<subsystem xmlns="urn:jboss:domain:messaging-activemq:1.0">
<server name="default">
<security-setting name="#">
<role name="guest" send="true" consume="true" create-non-durable-queue="true" delete-non-durable-queue="true"/>
</security-setting>
<address-setting name="#" dead-letter-address="jms.queue.DLQ" expiry-address="jms.queue.ExpiryQueue" max-size-bytes="10485760" page-size-bytes="2097152" message-counter-history-day-limit="10"/>
<http-connector name="http-connector" socket-binding="http" endpoint="http-acceptor"/>
<http-connector name="http-connector-throughput" socket-binding="http" endpoint="http-acceptor-throughput">
<param name="batch-delay" value="50"/>
</http-connector>
<in-vm-connector name="in-vm" server-id="0"/>
<http-acceptor name="http-acceptor" http-listener="default"/>
<http-acceptor name="http-acceptor-throughput" http-listener="default">
<param name="batch-delay" value="50"/>
<param name="direct-deliver" value="false"/>
</http-acceptor>
<in-vm-acceptor name="in-vm" server-id="0"/>
<jms-queue name="ExpiryQueue" entries="java:/jms/queue/ExpiryQueue"/>
<jms-queue name="DLQ" entries="java:/jms/queue/DLQ"/>
<jms-queue name="clickQueue" entries="java:/jms/queue/clickQueue java:/jboss/exported/jms/queue/clickQueue"/>
<jms-queue name="emailQueue" entries="java:/jms/queue/EmailQueue java:/jboss/exported/jms/queue/EmailQueue"/>
<jms-queue name="emailSendQueue" entries="java:/jboss/exported/jms/queue/EmailSendQueue"/>
<connection-factory name="InVmConnectionFactory" entries="java:/ConnectionFactory" connectors="in-vm"/>
<connection-factory name="RemoteConnectionFactory" entries="java:jboss/exported/jms/RemoteConnectionFactory" connectors="http-connector"/>
<pooled-connection-factory name="activemq-ra" entries="java:/JmsXA java:jboss/DefaultJMSConnectionFactory" connectors="in-vm" transaction="xa"/>
</server>
</subsystem>
can you help me about error???
thanks.
Working example:
public class JMSClient {
private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
private static final String PROVIDER_URL = "http-remoting://127.0.0.1:8080";
private static final String CONNECTION_FACTORY = "jms/RemoteConnectionFactory";
private static final String DESTINATION = "topic/irisWebBroadcaster";
private static final String USERNAME = "jmsuser";
private static final String PASSWORD = "qqq";
public static void main(String[] args) {
Context namingContext = null;
JMSContext context = null;
try {
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, PROVIDER_URL);
env.put(Context.SECURITY_PRINCIPAL, USERNAME);
env.put(Context.SECURITY_CREDENTIALS, PASSWORD);
namingContext = new InitialContext(env);
ConnectionFactory connectionFactory = (ConnectionFactory) namingContext.lookup(CONNECTION_FACTORY);
Destination destination = (Destination) namingContext.lookup(DESTINATION);
context = connectionFactory.createContext(USERNAME, PASSWORD);
JMSProducer producer = context.createProducer();
producer.send(destination, "TEST");
} catch (Exception e) {
// print error messge
} finally {
if (namingContext != null) {
try {
namingContext.close();
} catch (NamingException e) {
// print error messge
}
}
if (context != null) {
context.close();
}
}
}
}
Corresponding classpath (maybe excessive):
[WILDFLY10_DIR]/modules/system/layers/base/javax/annotation/api/main/jboss-annotations-api_1.2_spec-1.0.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/servlet/api/main/jboss-servlet-api_3.1_spec-1.0.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/ejb/api/main/jboss-ejb-api_3.2_spec-1.0.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/enterprise/api/main/cdi-api-1.2.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/log4j/logmanager/main/log4j-jboss-logmanager-1.1.2.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/inject/api/main/javax.inject-1.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/ws/rs/api/main/jboss-jaxrs-api_2.0_spec-1.0.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/javax/jms/api/main/jboss-jms-api_2.0_spec-1.0.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/codehaus/jackson/jackson-core-asl/main/jackson-core-asl-1.9.13.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/codehaus/jackson/jackson-mapper-asl/main/jackson-mapper-asl-1.9.13.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/logging/main/jboss-logging-3.3.0.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/logmanager/main/jboss-logmanager-2.0.3.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/remote-naming/main/jboss-remote-naming-2.0.4.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/xnio/main/xnio-api-3.3.4.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/xnio/nio/main/xnio-nio-3.3.4.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/remoting/main/jboss-remoting-4.0.18.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/marshalling/main/jboss-marshalling-1.4.10.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/marshalling/river/main/jboss-marshalling-river-1.4.10.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/activemq/artemis/main/artemis-jms-client-1.1.0.wildfly-011.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/activemq/artemis/main/artemis-core-client-1.1.0.wildfly-011.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/activemq/artemis/main/artemis-commons-1.1.0.wildfly-011.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/activemq/artemis/main/artemis-selector-1.1.0.wildfly-011.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/commons/beanutils/main/commons-beanutils-1.9.2.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/apache/commons/collections/main/commons-collections-3.2.2.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/slf4j/jcl-over-slf4j/main/jcl-over-slf4j-1.7.7.jbossorg-1.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/slf4j/main/slf4j-api-1.7.7.jbossorg-1.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/slf4j/impl/main/slf4j-jboss-logmanager-1.0.3.GA.jar
[WILDFLY10_DIR]/modules/system/layers/base/org/jboss/ejb-client/main/jboss-ejb-client-2.1.4.Final.jar
[WILDFLY10_DIR]/modules/system/layers/base/io/netty/main/netty-all-4.0.32.Final.jar
You can add something like this if you have problems with logging:
InternalLoggerFactory.setDefaultFactory(new Log4JLoggerFactory());
PropertyConfigurator.configure("conf/log4j.properties");
I see that Answer given by Rudik is not yet accepted , hence posting my take on this problem.
Test case
#Test
public void sendMessagesToWildfly10() throws IOException, NamingException {
String Message = "Hello, World!";
String connectionFactoryJNDIName = "jms/RemoteConnectionFactory";
String queueName = "jms/queue/TestQueue";
Context namingContext = null;
JMSContext context = null;
try {
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY,"org.jboss.naming.remote.client.InitialContextFactory");
env.put(Context.PROVIDER_URL, "http-remoting://localhost:8470");
// Below May Not be needed if you have turned off the security for Messaging
env.put(Context.SECURITY_PRINCIPAL, "guest");
env.put(Context.SECURITY_CREDENTIALS, "guest");
namingContext = new InitialContext(env);
ConnectionFactory connectionFactory = (ConnectionFactory) namingContext.lookup(connectionFactoryJNDIName);
Destination destination = (Destination) namingContext.lookup(queueName);
context = connectionFactory.createContext("userName", "password");
JMSProducer producer = context.createProducer();
for (int i = 0; i < 10; i++) {
producer.send(destination, Message+" - "+i);
}
JMSConsumer consumer = context.createConsumer(destination);
for (int i = 0; i < 10; i++) {
String text = consumer.receiveBody(String.class, 5000);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (namingContext != null) {
namingContext.close();
}
if (context != null) {
context.close();
}
}
}
You will require below mentioned Jars/dependencies added to your classpath. Most of them you can find in Wildfly/modules
If a JMS client is running within a WildFly application then the org.apache.activemq.artemis module must be added as a dependency on your deployment to avoid the java.lang.ClassNotFoundException: org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory, e.g. as answered here.
Otherwise ( standalone java application) - the jboss-client.jar needs to be included into class-path.
Note: take the jboss-client.jar based on your target WildFly version because it differs between WildFLy 8 and 10.

com.mysql.jdbc.Driver not resolved in ApiFest

Here is what my pom.xml looks like :
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
Code where i am trying to get jdbc connection :
public static Connection getConnection() {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "dbname” ";
String userName = "userName";
String password = "password";
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url + dbName, userName, password);
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
} catch (Exception e) {
System.out.println("Inside exception");
e.printStackTrace();
}
System.out.println("Returning connection >>> " + connection);
return connection;
}
I am running ApiFest server using command :
java -Dproperties.file=apifest-oauth.properties -Dlog4j.configuration=file:log4j.xml -jar target/apifest-oauth20-0.2.0-SNAPSHOT-jar-with-dependencies.jar
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:789)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:191)
Also tried downloading com.mysql.jdbc_5.1.5.jar and added it to class path but no help.

can't use two bundles with ehcache in karaf container

I'm using the Karaf (actually Aetos) OSGi container. I want to have two bundles that use ehcache. Apparently, when the second bundle starts its cache, the cache of the first bundle is stopped.
When the first one is installed, there is no problem. It runs fine.
When I install the second one I get a stack trace like this:
2014-03-25 20:38:18,758 | ERROR | rint Extender: 2 | BlueprintContainerImpl | 9 - org.apache.aries.blueprint - 0.3.2 | Unable to start blueprint container for bundle DataProviderLoadFX
org.osgi.service.blueprint.container.ComponentDefinitionException: Unable to instantiate components
at org.apache.aries.blueprint.container.BlueprintContainerImpl.instantiateEagerComponents(BlueprintContainerImpl.java:635)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BlueprintContainerImpl.doRun(BlueprintContainerImpl.java:337)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BlueprintContainerImpl.run(BlueprintContainerImpl.java:230)[9:org.apache.aries.blueprint:0.3.2]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)[:1.6.0_41]
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)[:1.6.0_41]
at java.util.concurrent.FutureTask.run(FutureTask.java:138)[:1.6.0_41]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)[:1.6.0_41]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:206)[:1.6.0_41]
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)[:1.6.0_41]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)[:1.6.0_41]
at java.lang.Thread.run(Thread.java:662)[:1.6.0_41]
Caused by: java.lang.NullPointerException
at org.apache.aries.blueprint.container.BeanRecipe.setProperties(BeanRecipe.java:768)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BeanRecipe.internalCreate(BeanRecipe.java:722)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.di.AbstractRecipe.create(AbstractRecipe.java:64)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BeanRecipe.setProperty(BeanRecipe.java:813)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BeanRecipe.setProperties(BeanRecipe.java:787)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BeanRecipe.setProperties(BeanRecipe.java:768)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BeanRecipe.internalCreate(BeanRecipe.java:722)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.di.AbstractRecipe.create(AbstractRecipe.java:64)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BlueprintRepository.createInstances(BlueprintRepository.java:219)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BlueprintRepository.createAll(BlueprintRepository.java:147)[9:org.apache.aries.blueprint:0.3.2]
at org.apache.aries.blueprint.container.BlueprintContainerImpl.instantiateEagerComponents(BlueprintContainerImpl.java:631)[9:org.apache.aries.blueprint:0.3.2]
... 10 more
Then I update that second bundle and it starts up just fine. However, when I then exercise the cache on the first bundle, the cache begins to fail with this stack trace:
Caused by: org.apache.camel.language.bean.RuntimeBeanExpressionException: Failed to invoke method: handleFTPDeliveryRequest(${property.requestId},${property.duplicate}) on null due to: java.lang.IllegalStateException: The DRS_RequestServiceLoadSensitivity_jdbcOneHourToLiveCache Cache is not alive (STATUS_SHUTDOWN)
at org.apache.camel.language.bean.BeanExpression$OgnlInvokeProcessor.process(BeanExpression.java:285)
at org.apache.camel.language.bean.BeanExpression.evaluate(BeanExpression.java:114)
... 92 more
Caused by: java.lang.IllegalStateException: The DRS_RequestServiceLoadSensitivity_jdbcOneHourToLiveCache Cache is not alive (STATUS_SHUTDOWN)
at net.sf.ehcache.Cache$CacheStatus.checkAlive(Cache.java:4290)
at net.sf.ehcache.Cache.checkStatus(Cache.java:2731)
at net.sf.ehcache.Cache.get(Cache.java:1610)
at net.sf.ehcache.Cache.get(Cache.java:1591)
at com.windlogics.tsunami.drs.requestservice.LdfxDAO.checkDuplicaeFTPRequest(LdfxDAO.java:843)
at com.windlogics.tsunami.drs.requestservice.RequestProcessor.handleFTPDeliveryRequest(RequestProcessor.java:284)
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.apache.camel.component.bean.MethodInfo.invoke(MethodInfo.java:341)
at org.apache.camel.component.bean.MethodInfo$1.proceed(MethodInfo.java:238)
at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:166)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:99)
at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:73)
at org.apache.camel.language.bean.BeanExpression$InvokeProcessor.process(BeanExpression.java:189)
at org.apache.camel.language.bean.BeanExpression$OgnlInvokeProcessor.process(BeanExpression.java:281)
... 93 more
The ehcache config files are in the bundles. They are identical except for the names of the ehcache and caches and the names of the files themselves are even different.
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
name="DRS_RequestServiceLoadSensitivity" monitoring="autodetect" dynamicConfig="true">
<diskStore path="java.io.tmpdir" />
<transactionManagerLookup class="net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup" properties="jndiName=java:/TransactionManager"
propertySeparator=";" />
<cacheManagerEventListenerFactory class="" properties="" />
<defaultCache maxEntriesLocalHeap="0" eternal="false" timeToIdleSeconds="1200" timeToLiveSeconds="1200">
</defaultCache>
<cache name="DRS_RequestServiceLoadSensitivity_jdbcOneHourToLiveCache" maxBytesLocalHeap="100M" maxBytesLocalDisk="200M" eternal="false"
diskSpoolBufferSizeMB="20" timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LFU" transactionalMode="off">
</ehcache>
I'm using the following bean as a factory:
public class CacheManagerFactory {
private static Logger logger = Logger.getLogger(CacheManagerFactory.class);
private CacheManager cacheManager;
private String configFilename = "ehcache.xml";
private Bundle bundle;
public void afterPropertiesSet() {
InputStream in = null;
try {
URL url = bundle.getEntry(configFilename);
in = url.openStream();
cacheManager = CacheManager.create(in);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
logger.warn("", e);
}
}
}
}
public void dispose() {
cacheManager.shutdown();
}
public Cache getCache(String name) {
return cacheManager.getCache(name);
}
public CacheManager getCacheManager() {
return cacheManager;
}
public void setBundle(Bundle bundle) {
this.bundle = bundle;
}
public void setConfigFilename(String configFilename) {
this.configFilename = configFilename;
}
}
Here is the excerpt from the blueprint.xml files where I use the factory:
<bean id="cacheManagerFactory" class="com.windlogics.tsunami.drs.dataprovider.CacheManagerFactory" init-method="afterPropertiesSet" destroy-method="dispose">
<property name="bundle" ref="blueprintBundle" />
<property name="configFilename" value="DRS_RequestServiceLoadSensitivity_ehcache.xml" />
</bean>
<bean id="dao" class="com.windlogics.tsunami.drs.dataprovider.LdfxDAO">
<property name="dataSource" ref="loadFXDataSource" />
<property name="cache">
<bean factory-ref="cacheManagerFactory" factory-method="getCache">
<argument value="DRS_RequestServiceLoadSensitivity_jdbcOneHourToLiveCache" />
</bean>
</property>
</bean>
I have this in the pom.xml files:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-cache</artifactId>
</dependency>

Resources