I am migrating an old web app. It was written with old web.xml-style, now we want to programmatically build the servlet.
This is a Spring MVC app, deployed as a WAR module in an EAR under Wildfly 10.0.0.Final.
I wrote my implementation of Spring's WebApplicationInitializer (still using Spring XML config at the moment, to preceed step by step - next step will be to migrate to JavaConfig). Though I'm stuck here because the servlet is initialized twice, and the second time the initilization fails due to a filter's name conflict - NullPointerException after filter creation.
This is my initilizer:
public class MyWebApplicationInitializer implements WebApplicationInitializer {
private static final Logger log = LoggerFactory.getLogger(MyWebApplicationInitializer.class);
/**
* #see org.springframework.web.WebApplicationInitializer#onStartup(javax.servlet.ServletContext)
*/
#Override
public void onStartup(ServletContext container) throws ServletException {
log.debug("******* Initializing Web App *******");
XmlWebApplicationContext rootContext = new XmlWebApplicationContext();
rootContext.setConfigLocation("classpath:META-INF/spring/application-context.xml");
XmlWebApplicationContext webContext = new XmlWebApplicationContext();
webContext.setConfigLocation("classpath:META-INF/spring/mvc-context.xml");
container.addListener(new ContextLoaderListener(rootContext));
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(webContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
container.addFilter("log4jEnhancementFilter", Log4jEnhancementFilter.class);
log.info("******* Web App correctly initialized *******");
}
}
A bit of log below:
[ServerService Thread Pool -- 74]:[INFO] # 2016-04-19 07:19:27,725: io.undertow.servlet.spec.ServletContextImpl.log:313: Spring WebApplicationInitializers detected on classpath: [com.xyz.web.servlet.MyWebApplicationInitializer#6356dd91]
[ServerService Thread Pool -- 74]:[DEBUG] # 2016-04-19 07:19:27,725: com.xyz.web.servlet.MyWebApplicationInitializer.onStartup:44: ******* Initializing Web App *******
...
[ServerService Thread Pool -- 74]:[INFO] # 2016-04-19 07:19:27,796: com.xyz.web.servlet.MyWebApplicationInitializer.onStartup:59: ******* Web App correctly initialized *******
...
[ServerService Thread Pool -- 74]:[INFO] # 2016-04-19 07:19:27,797: io.undertow.servlet.spec.ServletContextImpl.log:313: Spring WebApplicationInitializers detected on classpath: [com.xyz.web.servlet.MyWebApplicationInitializer#427d3c64]
[ServerService Thread Pool -- 74]:[DEBUG] # 2016-04-19 07:19:27,797: com.xyz.web.servlet.MyWebApplicationInitializer.onStartup:44: ******* Initializing Web App *******
07:19:27,800 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 74) MSC000001: Failed to start service jboss.undertow.deployment.default-server.default-host./www: org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host./www: java.lang.RuntimeException: java.lang.NullPointerException
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:85)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
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)
at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: java.lang.RuntimeException: java.lang.NullPointerException
at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:231)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:100)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:82)
... 6 more
Caused by: java.lang.NullPointerException
at com.xyz.web.servlet.MyWebApplicationInitializer.onStartup(MyWebApplicationInitializer.java:54)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)
at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:184)
... 8 more
As you can see there is a double servlet's initilization; the first succeeds, the second fails due to the NPE.
What am I doing wrong and how can I fix it?
Related
how to list wildfly (version 16) deployed http servlets ? either from web console port 8080 or the cli ?
I have deployed a working example :
2021-04-07 19:10:28,579 INFO [org.jboss.as.server.deployment] (MSC service thread 1-2) WFLYSRV0027: Starting deployment of "h2-console.war" (runtime-name: "h2-console.war")
2021-04-07 19:10:28,719 INFO [org.wildfly.extension.undertow] (ServerService Thread Pool -- 124) WFLYUT0021: Registered web context: '/h2-console' for server 'default-server'
this works : http://172.21.93.102:8080/h2-console/console/login.jsp?jsessionid=bf0d51b655f42eb956ba4f2bf98a1de9
is it possible to list the deployed http servlets, similar to the list of deployed EJB ?
could it be that EJB are necessarily deployed, whereas http servlets could be say switched off at startup in web.xml "load-on-startup" :
<servlet>
<servlet-name>H2Console</servlet-name>
<servlet-class>org.h2.server.web.WebServlet</servlet-class>
<init-param>
<param-name>webAllowOthers</param-name>
<param-value></param-value>
</init-param>
<init-param>
<param-name>trace</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
in the configuration/runtime tabs of the web console there is something for "undertow" http server sessions, but I can't find a list of servlets
configuration tab :
runtime tab:
list of deployed EJBs (it displays which jar/war additionally):
update :
Runtime -> Server -> Web -> Deployment -> deployment -> view does indeed show the deployed servlet, as in the correct answer, further to that, I'd need to call an EJB 3.0 bean from the servlet, but I have this error :
javax.naming.NameNotFoundException: MFProLoginBean/remote -- service jboss.naming.context.java.MFProLoginBean.remote
this EJB is listed in the web console of wildfly 16, and is fetchable with wget at : http://wildfly:8080//TServerXmlRpc/login/PreLoginServlet
the EJB (it seems EJB 3.0 ?) :
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.jboss.annotation.ejb.Clustered;
import org.jboss.annotation.ejb.RemoteBinding;
import org.jboss.annotation.ejb.RemoteBindings;
#Clustered
#Stateless
#RemoteBindings({
#RemoteBinding(jndiBinding = "MFProLoginBean/remote"),
#RemoteBinding(jndiBinding = "MFProLoginBean/httpremote", clientBindUrl = "servlet://${tserver.ejb3.client.address}${tserver.ejb3.client.port}${tserver.ejb3.client.url}", factory = it.company.tserver.ejb3.StatelessClusterProxyFactory.class) })
public class MFProLoginBean implements MFProLogin, MFProLoginLocal {
the invocation that fails in the servlet :
public class LoginServlet extends HttpServlet {
private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
javax.naming.Context ctx = InitialContextFactory.create();
MFProLogin loginBean = (MFProLogin) ctx.lookup("MFProLoginBean/remote");
TUserSession userSession = loginBean.loginUser(authReq, new TInfoRequest(launcherVersion, descriptorVersion, environmentPath));
those variables are set in the wildfly start script :
JBoss Bootstrap Environment
JBOSS_HOME: /opt/wildfly
JAVA: /usr/bin/java
JAVA_OPTS: -server -Xms64m -Xmx512m -XX:MetaspaceSize=96M -XX:MaxMetaspaceSize=256m -Djava.net.preferIPv4Stack=true -Djboss.modules.system.pkgs=org.jboss.byteman
-Djava.awt.headless=true -agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=n -Dtserver.ejb3.client.address=jbosscollaudomfpro.classlocale.it
-Dtserver.ejb3.client.port=:8080 -Dtserver.ejb3.client.url=//unified-invoker/Ejb3ServerInvokerServlet?return-exception=true
-Dtserver.http.client.address=jbosscollaudomfpro.classlocale.it -Dtserver.http.client.port=8080 -Dtserver.jms.http.client.url=/jmsmessaging/connector
-Dorg.jboss.logging.Log4jService.catchSystemOut=false -Dlogmanager.log4jimpl.properties=tserver-log4j.properties -DpropsDomain=
that "unified-invoker.sar" is no longer used since AS 7 ?
this seems to substitute java variables ? :
package it.company.tserver.ejb3;
import org.jboss.annotation.ejb.RemoteBinding;
import org.jboss.annotation.ejb.RemoteBindingImpl;
public class StatelessClusterProxyFactory extends org.jboss.ejb3.stateless.StatelessClusterProxyFactory
{
#Override
public void setRemoteBinding(RemoteBinding binding) {
String uri = binding.clientBindUrl();
if (uri!=null && uri.indexOf("${")>=0) {
uri = ReplacePropertiesUtil.replace(uri);
RemoteBindingImpl b = new RemoteBindingImpl(binding.jndiBinding(), binding.interceptorStack(), uri, binding.factory());
super.setRemoteBinding(b);
}
else
super.setRemoteBinding(binding);
}
}
In the web console go to Runtime -> Server -> Web -> Deployment then select the deployment you want and click "View". From there you can see the servlets from the Servlet tab on the left.
In CLI you can execute something like the following to list the names.
/deployment=YOUR.war/subsystem=undertow:read-children-names(child-type=servlet)
Or something like the following to list more details:
/deployment=helloworld-html5.war/subsystem=undertow:read-children-resources(child-type=servlet, include-runtime=true)
In my Spring Boot project, there are REST and MVC controllers. Where the MVC part should have session. This part goes fine, but when you come from a MVC page with session and start using Swagger from the browser to the API I start to see these messages on the REST API endpoints:
org.springframework.dao.DuplicateKeyException: PreparedStatementCallback; SQL [INSERT INTO SPRING_SESSION_ATTRIBUTES(SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) VALUES (?, ?, ?)Duplicate entry '7a69e3fe-dd7f-4a1d-85bb-2dcd617225dd-SPRING_SECURITY_SAVED_REQUE' for key 'PRIMARY'; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '7a69e3fe-dd7f-4a1d-85bb-2dcd617225dd-SPRING_SECURITY_SAVED_REQUE' for key 'PRIMARY'
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:242)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1402)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:620)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:850)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:905)
at org.springframework.session.jdbc.JdbcOperationsSessionRepository.insertSessionAttributes(JdbcOperationsSessionRepository.java:515)
at org.springframework.session.jdbc.JdbcOperationsSessionRepository.access$300(JdbcOperationsSessionRepository.java:131)
at org.springframework.session.jdbc.JdbcOperationsSessionRepository$2.doInTransactionWithoutResult(JdbcOperationsSessionRepository.java:413)
at org.springframework.transaction.support.TransactionCallbackWithoutResult.doInTransaction(TransactionCallbackWithoutResult.java:36)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140)
at org.springframework.session.jdbc.JdbcOperationsSessionRepository.save(JdbcOperationsSessionRepository.java:393)
at org.springframework.session.jdbc.JdbcOperationsSessionRepository.save(JdbcOperationsSessionRepository.java:131)
at org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper.saveSession(SessionRepositoryFilter.java:377)
at org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper.commitSession(SessionRepositoryFilter.java:233)
at org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper.access$100(SessionRepositoryFilter.java:197)
at org.springframework.session.web.http.SessionRepositoryFilter.doFilterInternal(SessionRepositoryFilter.java:150)
at org.springframework.session.web.http.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:81)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:472)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:395)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:316)
at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:395)
at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:254)
at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:349)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:175)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '7a69e3fe-dd7f-4a1d-85bb-2dcd617225dd-SPRING_SECURITY_SAVED_REQUE' for key 'PRIMARY'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3976)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3912)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2530)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2683)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2486)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
at org.springframework.jdbc.core.JdbcTemplate.lambda$update$0(JdbcTemplate.java:855)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:605)
... 36 common frames omitted
My security configuration looks like this:
#Configuration
#EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.cors().and()
.authorizeRequests()
.antMatchers(
"/",
"/index.html",
"/oauth2-redirect.html",
"/favicon-*.png",
"/swagger-*",
"/swagger.json"
).permitAll()
.anyRequest().authenticated();
}
}
Appereantly there is a bug in delta session handling: https://github.com/spring-projects/spring-session/pull/1070
This should be fixed in version Spring Session 2.0.4.RELEASE, I worked on version Spring Session 2.0.3.RELEASE and have now downgraded to Spring Session 1.3.2.RELEASE which resolved my issues (which is in spring boot 1.5.13.RELEASE).
Will try again when version 2.0.4.RELEASE is out.
UPDATE: I tested the SNAPSHOT version, suggested here
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-jdbc</artifactId>
<version>2.0.4.BUILD-SNAPSHOT</version>
</dependency>
This is resolving my issue.
Need to use sql query that will ignore duplicate. Spring already have the correct one, you just need to enable it:
#Configuration
class DatabaseConfig {
#Bean
public MySqlJdbcIndexedSessionRepositoryCustomizer sessionRepositoryCustomizer() {
return new MySqlJdbcIndexedSessionRepositoryCustomizer();
// or PostgreSqlJdbcIndexedSessionRepositoryCustomizer
}
}
I am using grpc to communicate between a Java server and node client. When either of them die/crash the other dies to.
Here is the exception thrown on Java server when node client dies -
Nov 08, 2016 11:28:03 AM io.grpc.netty.NettyServerHandler onConnectionError
WARNING: Connection Error
java.io.IOException: An existing connection was forcibly closed by the remote host
at sun.nio.ch.SocketDispatcher.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:43)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
at sun.nio.ch.IOUtil.read(IOUtil.java:192)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
at io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:288)
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1100)
at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:349)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:112)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:571)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:512)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:426)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:398)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:877)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
at java.lang.Thread.run(Thread.java:745)
Here is the exception thrown on node when java dies:
events.js:141
throw er; // Unhandled 'error' event
^
Error: {"created":"#1478623914.082000000","description":"An existing connection was forcibly closed by the remote host.\r\n","file":"..\src\core\lib\iomgr\tcp_windows.c","file_line":171,"grpc_status":14}
at ClientReadableStream._emitStatusIfDone ( C:\HarshalDev\Live_TDFX\TDSL0007-TDFXPlatfo rmsDesignandBuild\tdfxlive\node_modules\grpc\src\node\src\client.js:189:19)
at ClientReadableStream._receiveStatus (C:\ HarshalDev\Live_TDFX\TDSL0007-TDFXPlatformsDesignandBuild\tdfxlive\node_modules\grpc\src\node\src\client.js:169:8)
at C:\HarshalDev\Live_TDFX\TDSL0007-TDFXPlatformsDesignandBuild\tdfxlive\node_modules\grpc\src\node\src\client.js:577:14
[nodemon] app crashed - waiting for file changes before starting...
QUESTION - How do I handle those exceptions?
I tried without any success adding try/catch and adding a uncaught exception handlers for threads.
Java code to initialize -
ServerBuilder<?> serverBuilder = ServerBuilder.forPort(getPort());
server = serverBuilder
.addService(createBwayStreamingService())
.addService(ServerInterceptors.intercept(createBwayOrderService(), authServerInterceptor))
.addService(createBwayInstrumentService())
.addService(createBwaySettlementService())
.addService(createBwayDateTimeService())
.addService(ServerInterceptors.intercept(createBwayConfService(), authServerInterceptor))
.addService(ServerInterceptors.intercept(createBwayTradeService(), authServerInterceptor))
.addService(ServerInterceptors.intercept(createBwayAuthService(), authServerInterceptor))
.build();
Preconditions.checkNotNull(server);
server.start();
System.out.println("Server started, listening on " + getPort());
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
System.out.println("Shutting down gRPC server");
TocGateway.this.stop();
System.out.println("Server shut down");
}
});
server.awaitTermination();
Node client handler (one of the services, all other services use the same pattern) -
let protoDescriptorStreaming = grpc.load((process.env.FX_LIVE_PROTO_DIR || '../tocGateway/src/main/proto') + '/streaming.proto');
let streamingService = new protoDescriptorStreaming.tds.fxlive.bway.BwayStreamService(process.env.TOC_GATEWAY_ADDRESS || 'localhost:8087', grpc.credentials.createInsecure());
The Java warning is harmless. Your application should continue running normally after the exception. It would be nice to reduce the log level to have less logspam, but it also shouldn't impact the correctness of your application.
I have the Following CouchBase Template Bean:
#PostConstruct
public void initIt() throws Exception {
if(couchbaseDisabled)
return;
couchbaseClient= new CouchbaseClient(
bootstrapUris(Arrays.asList(hosts.split(","))),
CouchbaseConstants.BUCKET,
""
);
couchbaseTemplate();
}
public void couchbaseTemplate() throws Exception {
logger.info("Enabling CouchBase Template");
couchbaseTemplate= new CouchbaseTemplate(couchbaseClient);
//couchbaseTemplate.
}
and
#PreDestroy
public void cleanup() throws Exception {
logger.info("Closing couchbase connection.");
if (couchbaseClient != null) {
couchbaseClient.shutdown();
couchbaseTemplate=null;
couchbaseClient=null;
}
}
While the Server is being Shut Down i am geting the Following Logs:
SEVERE: The web application [] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
Jan 8, 2016 4:57:24 PM org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
SEVERE: The web application [] created a ThreadLocal with key of type [java.lang.ThreadLocal] (value [java.lang.ThreadLocal#40c94525]) and a value of type [com.couchbase.client.deps.io.netty.util.internal.InternalThreadLocalMap] (value [com.couchbase.client.deps.io.netty.util.internal.InternalThreadLocalMap#5ddaa15d]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak.
Jan 8, 2016 4:57:24 PM org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
SEVERE: The web application [] created a ThreadLocal with key of type [java.lang.ThreadLocal] (value [java.lang.ThreadLocal#40c94525]) and a value of type [com.couchbase.client.deps.io.netty.util.internal.InternalThreadLocalMap] (value [com.couchbase.client.deps.io.netty.util.internal.InternalThreadLocalMap#3c9810ce]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak.
Jan 8, 2016 4:57:24 PM org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
SEVERE: The web application [] created a ThreadLocal with key of type [java.lang.ThreadLocal] (value [java.lang.ThreadLocal#40c94525]) and a value of type [com.couchbase.client.deps.io.netty.util.internal.InternalThreadLocalMap] (value [com.couchbase.client.deps.io.netty.util.internal.InternalThreadLocalMap#23776376]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak.
Jan 8, 2016 4:57:24 PM org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
SEVERE: The web application [] created a ThreadLocal with key of type [java.lang.ThreadLocal] (value [java.lang.ThreadLocal#40c94525]) and a value of type [com.couchbase.client.deps.io.netty.util.internal.InternalThreadLocalMap] (value [com.couchbase.client.deps.io.netty.util.internal.InternalThreadLocalMap#7322ea2a]) but failed to remove it when the web application was stopped. This is very likely to create a memory leak.
Jan 8, 2016 4:57:32 PM org.apache.coyote.http11.Http11Protocol destroy
INFO: Stopping Coyote HTTP/1.1 on http-8099
What can be Done Here?
Ok so you have both SDK 1.4.x and 2.x running in your application (since you have com.couchbase.client:java-client in your pom).
The thread leak message comes from the later. You must have instantiated a Cluster somewhere (as in com.couchbase.client.java.Cluster).
Make sure to also clean it up at the end of the application's lifecycle by calling cluster.disconnect() (I guess from a #PreDestroy method, as you did for the CouchbaseClient).
If you also created a custom CouchbaseEnvironment, you have to also properly shut it down (in the same method as the Cluster cleanup) by calling environment.shutdownAsync().toBlocking().single().
Make sure to use the latest version of the 2.x SDK as some older versions had bugs relative to proper thread cleanup on shutdown (see JCBC-773 and JVMCBC-251 issues).
I have got a problem with ejb remote method invocation. For testing I created a ejb project with a statless bean and a simple method, declared in a remote interface. I deployed this project in a JBoss 7.1.
Now I want to call the business method hello in my bean from another class, which is not part of the project and not deployed in that jboss server. So if I understand it correct, this is a normal remote method call from a client.
I wrote my HelloWorldClient, declared the properties for the InitialContext(). But when I run this client, I got a NameNotFoundException. For me it seems like the exception is because of a false jndi-name, but I tried a lot to get the correct one.
On the console I got jndi names from my server for the project, but it doesn't work. Could someone help me solve this problem?
Client with context:
Properties jndiProps = new Properties();
jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
jndiProps.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
jndiProps.put(Context.PROVIDER_URL,"remote://localhost:4447");
jndiProps.put(Context.SECURITY_PRINCIPAL, "testuser");
jndiProps.put(Context.SECURITY_CREDENTIALS, "testpasswort");
Context ctx = new InitialContext(jndiProps);
HelloWorldRemote hello = (HelloWorldRemote) ctx.lookup("java:global[/ejbproject1]/ejbproject1/HelloWorldBean[/HelloWorldRemote]");
My Bean:
#Stateless(name="hello")
public class HelloWorldBean implements HelloWorldRemote{
#Override
public String hello(String value) {
System.out.println("Say hello to "+value);
return "Hello " + value;
}
the jndi names from the jboss
18:19:07,464 INFO [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-6) JNDI bindings for session bean named hello in deployment unit deployment "ejbproject1.jar" are as follows:
java:global/ejbproject1/hello!interfaces.HelloWorldRemote
java:app/ejbproject1/hello!interfaces.HelloWorldRemote
java:module/hello!interfaces.HelloWorldRemote
java:jboss/exported/ejbproject1/hello!interfaces.HelloWorldRemote
java:global/ejbproject1/hello
java:app/ejbproject1/hello
java:module/hello
and the exception:
javax.naming.NameNotFoundException: global[/ejbproject1]/ejbproject1/HelloWorldBean[/HelloWorldRemote] -- service jboss.naming.context.java.jboss.exported.global[.ejbproject1].ejbproject1.HelloWorldBean[.HelloWorldRemote]
Change from
java:global/ejbproject1/hello!interfaces.HelloWorldRemote
to
java:/ejbproject1/hello!interfaces.HelloWorldRemote
That will work.