infinispan cache.put() throws null pointer exception even when values put are not null - caching

trying to add content to infinispan cache and I get null pointer exception when i use the put method. Mine is a JSF web application. We are trying to achieve session replication using wildfly 13.
import org.infinispan.Cache;
public class index extends AbstractPageBean implements java.io.Serializable {
#Resource(lookup = "java:jboss/infinispan/cache/web/web_repl")
Cache<String, String> ilsCache;
public Cache<String, String> getCache() {
return ilsCache;
}
public void prerender() {
ilsCache.put("Message", "Hello");
logger.info("CACHE " + getCache());
}
Log file
2018-08-21 14:21:57,134 ERROR [biz.autoscan.ils.index] (default task-1) index.java::Exception occured : java.lang.NullPointerException
at biz.autoscan.ils.index.btnLogin_action(index.java:930)
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:498)
at com.sun.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:181)
at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1985)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1487)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1378)
at java.lang.Thread.run(Thread.java:745)
Any idea why I still get null pointer exception fro cache.put()?
Edit: We are using WildFly 13 in domain mode and Infinispan in replication mode. My aim is to store the session object in the infinispan cache and share it between all the nodes.
Infinispan subsystem in domain.xml: This is how I have configured infinispan. We are using only two servers at the moment hence we have gone with replication mode.
<subsystem xmlns="urn:jboss:domain:infinispan:6.0">
<cache-container name="web" aliases="ilsee" default-cache="web_repl" module="org.wildfly.clustering.web.infinispan">
<transport channel="ee" lock-timeout="60000"/>
<local-cache name="Username"/>
<replicated-cache name="web_repl">
<transaction mode="BATCH"/>
</replicated-cache>
<distributed-cache name="dist">
<transaction mode="NON_XA"/>
<file-store/>
</distributed-cache>
</cache-container>
</subsystem>

The answer depends on how you configure your server.
I will provide a generic example.
First, you need to configure your standalone.xml file
<subsystem xmlns="urn:infinispan:server:core:9.2">
<cache-container module="org.infinispan.extension:ispn-9.2" name="infinispan_container" default-cache="default">
<transport/>
<global-state/>
<distributed-cache name="default"/>
<distributed-cache name="myCache"/>
</cache-container>
</subsystem>
Then in your Java application, you need to inject the resource using
#Resource(lookup = "java:jboss/datagrid-infinispan/container/infinispan_container/cache/myCache")
Cache cache;
As you can see infinispan_container and myCache are values that you provided in the XML configuration file.
There are two possible ways for your application to utilize Infinispan within Wildfly: embedded mode and server mode.
You can find more information http://infinispan.org/docs/stable/user_guide/user_guide.html#usage_3

Related

Problems using Springboot autoconfiguration to connect to SQL-Server in a FUSE EAP environment

This is likely to be a misconception on my part when it comes to working with SpringBoot on FUSE EAP environments. I've been trying to deploy a service, which I've developed following the RedHat documentation and the archetypes/examples I've found online that mix Camel and SpringBoot, but to no avail.
From what I understand, when creating a connection to a JNDI datasource, which has been configured and tested in the EAP Fuse server, I can use the application.properties, or application.yml, to have the spring application autoconfigure the connection. In my case, it's required that I use #PersistenceContext to invoke the EntityManager, since the CRUD operations that the extending JpaRepository don't really cover the needs.
As per RedHat's documentation, FUSE 7.2 has been installed in EAP 7.1 and the POM is using the org.jboss.redhat-fuse.fuse-springboot-bom version 7.2.0.fuse-720020-redhat-00001.
I've tried using spring's autoconfiguration, a manual configuration declaring a #Configuration class, a manual configuration by declaring the database connection in the camel-context.xml file, and some other minor tests.
The errors vary depending on whether I try delpying the .jar or .jar.original, generated by having the spring-boot-maven-plugin with the repackage execution goal, errors obtained up to this point are:
NullPointer because EntityManager em is null (.jar.original)
java.lang.NoClassDefFoundError: org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder (.jar.original, when there's a manual configuration of the datasource, be it in a #Configuration annotated java class, or in the camel-context.xml using Spring DSL)
java.lang.ClassNotFoundException: com.example.dao.genericDAOImpl (.jar with all dependencies packaged)
Here are snippets of my program, which include the POM, Application.java and the component which is trying to get the EntityManager, will be happy to provide more snippets if it's not enough/unclear.
POM.xml
...
<properties>
<fuse.version>7.2.0.fuse-720020-redhat-00001</fuse.version>
...
</properties>
<dependencies>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
</dependencies>
...
<build>
<defaultGoal>spring-boot:run</defaultGoal>
<plugins>
...
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.5.16.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
...
</plugins>
</build>
...
application.properties
spring.datasource.jndi-name=jdbc:sqlserver://ip:1433;DatabaseName=dbname
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.SQLServer2012Dialect
spring.jpa.generate-ddl=false
Application.java
#ImportResource({"classpath:spring/camel-context.xml"})
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
camel-context.xml
<beans ...>
...
<camelContext id="identidades_financieras" xmlns="http://camel.apache.org/schema/spring">
<onException>
<exception>java.lang.Exception</exception>
<handled>
<constant>true</constant>
</handled>
<setHeader headerName="Exchange.HTTP_RESPONSE_CODE">
<constant>500</constant>
</setHeader>
<setBody>
<simple>${exception.message}</simple>
</setBody>
</onException>
<restConfiguration apiContextPath="/openapi.json"
bindingMode="json" component="undertow"
contextPath="/restservice/api_v1" enableCORS="true">
<dataFormatProperty key="prettyPrint" value="true"/>
</restConfiguration>
<rest enableCORS="true" id="rest-for-openapi-document" path="/openapi">
<get id="openapi.json" produces="application/json" uri="openapi.json">
<description>Gets the OpenAPI document for this service</description>
<route id="route-for-openapi-document">
<setHeader headerName="Exchange.CONTENT_TYPE" id="setHeader-for-openapi-document">
<constant>application/vnd.oai.openapi+json</constant>
</setHeader>
<setBody id="setBody-for-openapi-document">
<constant>resource:classpath:openapi.json</constant>
</setBody>
</route>
</get>
</rest>
<rest bindingMode="auto" enableCORS="true"
id="rest-b5d099c1-1996-458b-b5db-34aadc57a548" path="/">
<get id="customPaginatexxxVO" produces="application/json" uri="/xxx">
<to uri="direct:customPaginatexxxVO"/>
</get>
...
<route id="route-28f4489d-b354-401b-b774-6425bec1c120">
<from id="from-17c4205f-8d28-4d3d-a265-cb1c38c9bc32" uri="direct:customPaginatexxxVO"/>
<log id="customPaginatexxxVO-log-1" message="headers ====> pageSize: ${header.pageSize} - pageNumber: ${header.pageNumber}"/>
<bean id="to-ee6565efaf-de46-4941-b119-be7aaa07d892"
method="paginate" ref="genericService"/>
<log id="customPaginatexxxVO-log-2" message="${body}"/>
</route>
<beans/>
genericService.java
#Service
public class genericServiceImpl implements genericService {
#Autowired
private genericDAO dao;
...
#Override
public xxxVO paginate(Map<String, Object> reqHeaders) {
... pageProps are defined using reqHeaders ...
xxxVO paginated = dao.customPagination(pageProps);
return paginated;
}
...
}
genericDAOImpl.java, which errors out when anything regarding em is invoked.
#Repository
public class genericDAOImpl implements genericDAO {
#PersistenceContext //when manually configured, I've added the (unitName="") in reference to the persistence unit, from my understanding, since only one datasource was created, this should pick up by default
private EntityManager em;
...
#Override
public xxxVO customPagination(paginateProps pageProps) {
xxxVO result = null;
try {
CriteriaBuilder paginationBuilder = em.getCriteriaBuilder();
CriteriaQuery<T> paginationQuery = paginationBuilder.createQuery(entity.class);
Root<T> entityClass = paginationQuery.from(entity.class);
paginationQuery.select(entityClass);
... some settings with pageProps ...
TypedQuery<T> query = em.createQuery(paginationQuery);
entityList = query.getResultList();
... entityList is transformed to xxxVO ...
} catch (Exception e) {
LOG.error("caught something");
e.printStackTrace();
}
return result;
}
...
As stated before, I've been getting numerous different errors depending on the options I've tried, and most of them clearly come down to misconfiguration, or not deploying correctly, I'm still somewhat inexperienced when it comes to SpringBoot and Camel, and different things I've read on the internet have created some confusion. Just to make sure, the pagination method, while very snipped out, should be working, if it had a not nulled EntityManager.
Here are a couple of the logs:
When deplying .jar (fat jar with all dependencies), which from the tests I've made, deploys correctly using java -jar, but not in the fuse eap service
09:16:01,937 WARN [org.springframework.context.support.GenericApplicationContext] (MSC service thread 1-3) Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.example.dao.genericDAOImpl] for bean with name 'genericDAO' defined in URL [vfs:/content/identidades_financieras-1.0-SNAPSHOT.jar/BOOT-INF/classes/spring/camel-context.xml]; nested exception is java.lang.ClassNotFoundException: com.example.dao.genericDAOImpl from [Module "deployment.identidades_financieras-1.0-SNAPSHOT.jar" from Service Module Loader]
09:16:01,940 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-3) MSC000001: Failed to start service jboss.deployment.unit."identidades_financieras-1.0-SNAPSHOT.jar".CamelContextActivationService."identidades_financieras-1.0-SNAPSHOT.jar": org.jboss.msc.service.StartException in service jboss.deployment.unit."identidades_financieras-1.0-SNAPSHOT.jar".CamelContextActivationService."identidades_financieras-1.0-SNAPSHOT.jar": Cannot create camel context: identidades_financieras-1.0-SNAPSHOT.jar
at org.wildfly.extension.camel.service.CamelContextActivationService.start(CamelContextActivationService.java:71)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:2032)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1955)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.example.dao.genericDAOImpl] for bean with name 'genericDAO' defined in URL [vfs:/content/identidades_financieras-1.0-SNAPSHOT.jar/BOOT-INF/classes/spring/camel-context.xml]; nested exception is java.lang.ClassNotFoundException: com.example.dao.genericDAO from [Module "deployment.identidades_financieras-1.0-SNAPSHOT.jar" from Service Module Loader]
...
When deploying .jar.original (basically, just the java) with a manually configured DataSource and EntityManagerFactory. From what I understand, the service is expecting org.springframework.boot dependencies to exist on the server. After checking the modules, there is no org.springframework.boot module in the fuse layer. Is this intended?
09:50:17,265 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-8) MSC000001: Failed to start service jboss.deployment.unit."identidades_financieras-1.0-SNAPSHOT.jar".CamelContextActivationService."identidades_financieras-1.0-SNAPSHOT.jar": org.jboss.msc.service.StartException in service jboss.deployment.unit."identidades_financieras-1.0-SNAPSHOT.jar".CamelContextActivationService."identidades_financieras-1.0-SNAPSHOT.jar": Failed to start service
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1978)
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.lang.NoClassDefFoundError: org/springframework/boot/orm/jpa/EntityManagerFactoryBuilder
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.getDeclaredMethods(Class.java:1975)
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:613)
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:524)
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:510)
at org.springframework.util.ReflectionUtils.getUniqueDeclaredMethods(ReflectionUtils.java:570)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod(AbstractAutowireCapableBeanFactory.java:697)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:640)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:609)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1490)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:425)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:395)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:96)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:687)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:525)
at org.wildfly.extension.camel.SpringCamelContextBootstrap$1.run(SpringCamelContextBootstrap.java:90)
at org.wildfly.extension.camel.proxy.ProxyUtils$1.invoke(ProxyUtils.java:51)
at com.sun.proxy.$Proxy68.run(Unknown Source)
at org.wildfly.extension.camel.proxy.ProxyUtils.invokeProxied(ProxyUtils.java:55)
at org.wildfly.extension.camel.SpringCamelContextBootstrap.createSpringCamelContexts(SpringCamelContextBootstrap.java:87)
at org.wildfly.extension.camel.service.CamelContextActivationService.start(CamelContextActivationService.java:58)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:2032)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1955)
... 3 more
Caused by: java.lang.ClassNotFoundException: org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder from [Module "deployment.identidades_financieras-1.0-SNAPSHOT.jar" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:412)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:400)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:116)
... 27 more
Finally, when uploading the .jar.original using only the Spring autoconfigure, the EM is null, using Postman I get a status 500 and "No response available" when I consume the REST
java.lang.NullPointerException
at com.example.dao.genericDAOImpl.customPagination(GenericDAOImpl.java:252)
The line makes reference to CriteriaBuilder paginationBuilder = em.getCriteriaBuilder(), or any other place where a EM method is invoked.
Thank you for your time! Any comment is appreciated...
There is no support for Spring Boot with Fuse EAP and the Camel subsystem. Hence why you do not see any org.springframework.boot dependencies in the Fuse module layer.
If you are going to deploy Camel Spring Boot applications into EAP, it's best you either disable the Camel subsystem for your deployment or avoid installing the subsystem entirely.
This is by no means a solution to the issue I was having, I believe this to be but a temporary patch on my code since the 7.4 version of Fuse will supposedly support SpringBoot 2.1.x or something of the like, but doing the following allowed me to create the database connection and move on with my life. I will not mark this as the acceptable answer, unless I'm told that this is the only way.
In the Application.java, I straight up disabled the SpringBootServletInitializer. Full disclosure, I straight up have no idea of the impact that doing this could have in an application, but the dependency was troubling while I was trying to deploy.
#ImportResource({"classpath:spring/camel-context.xml"})
#SpringBootApplication
public class Application {//extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
I created a persistence.xml file where I configured the name of persistence unit and selected the package containing the entities (or listed them, both worked).
In the camel-context.xml I declared the following before the tag
<bean class="org.apache.camel.component.jpa.JpaComponent" id="jpa">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="transactionManager" ref="jpaTxManager"/>
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="jpaTxManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="PERSISTENCE UNIT NAME IN PERSISTENCE.XML"/>
</bean>
<bean class="org.apache.camel.spring.spi.SpringTransactionPolicy" id="requiredPolicy">
<property name="transactionManager" ref="jpaTxManager"/>
<property name="propagationBehaviorName" value="PROPAGATION_REQUIRED"/>
</bean>
I created a java class responsible for the creation of the EntityManager, it is very important that the class is #Stateless (EJB), and that the connection to the persistence unit is made static.
#Stateless
public class persistenceUnitEntityManagerImpl implements IfEntityManager{
private static EntityManager em;
static {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("PERSISTENCE UNIT NAME");
em = entityManagerFactory.createEntityManager();
}
public void setEntityManager( EntityManager em ) {
persistenceUnitEntityManagerImpl.em = em;
}
public EntityManager getEntityManager() {
return persistenceUnitEntityManagerImpl.em;
}
}
In the beans where the database connection was needed, in my case, an #Component (should work just as well in a #Repository), I added the following:
private IfEntityManagerImpl IfEntityManager;
#PostConstruct
public void init() {
this.persistenceUnitEntityManagerImpl = new persistenceUnitEntityManagerImpl();
}
And whenever the EntityManager needs to be called, I can use persistenceUnitEntityManagerImpl.getEntityManager()
Just to make sure that the component isn't creating a new connection/entity manager/whatever, you can add a LOG to the #PostConstruct init, if your bean is a singleton (should be by default, I believe) you will never get that LOG or printline.

Caused by: java.lang.ClassNotFoundException: org.infinispan.commons.CacheException

i am trying to upgrade jboss 4 to jboss 7 and using wildfly 10 for research purpose.
now i got error saying
Caused by: java.lang.ClassNotFoundException:
org.infinispan.commons.CacheException from [Module
"deployment.mes-webservices.ear:main" from Service Module Loader]
at
org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
at
org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
at
org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
at
org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
... 299 more
when i debug i see that error initiated here.
cachedBom = (BillOfMaterials) **CacheManager**.fetchObjectFromCache(bomFqn, bomKey);
where cacheManager refers here.
private static final String CACHENAME = "ClusteredTreeCache";
protected static final Log log = LogFactory.getLog(CacheManager.class);
private static EmbeddedCacheManager myCacheManager;
private static Cache cache = myCacheManager.getCache();
private static TreeCache mCache;
private static void findCache() throws MalformedObjectNameException
{
// Find the shared cache service in JMX and create a proxy to it
ObjectName cacheServiceName_ = new ObjectName("java:jboss/infinispan/replicated_cache/customer");
// Create Proxy-Object for this service
myCacheManager = new DefaultCacheManager();
mCache = new TreeCacheFactory().createTreeCache(cache);
// Log that medtronicCache Proxy saved
log.info("mCache Proxy Object has been set. Should only happen once.");
}
Standalone :
<cache-container name="replicated_cache" default-cache="default" module="org.wildfly.clustering.server" jndi-name="infinispan/replicated_cache">
<transport lock-timeout="60000"/>
<replicated-cache name="customer" jndi-name="infinispan/replicated_cache/customer" mode="SYNC">
<transaction locking="OPTIMISTIC" mode="NON_XA"/>
<eviction strategy="NONE"/>
</replicated-cache>
</cache-container>
The problem seems to be that org.infinispan.commons.CacheException is not in your runtime classpath. Please check that:
infinispan-commons.jar is part of your deployment
or that you have jboss-deployment-structure.xml which declares a dependency to the org.infinispan.commons module
or that you have a manifest dependency to the org.infinispan.commons module
You could check my demo project at Github.

How to configure Hazelcast host port in Spring Boot?

I'm using hazelcast in my project and want to move hazelcast host:port information into environment variables. Before that I had default configuration that is:
<hazelcast-client xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.hazelcast.com/schema/client-config
http://www.hazelcast.com/schema/client-config/hazelcast-client-config-3.8.xsd"
xmlns="http://www.hazelcast.com/schema/client-config">
<network>
<connection-timeout>3000</connection-timeout>
<connection-attempt-period>1000</connection-attempt-period>
<connection-attempt-limit>259200</connection-attempt-limit>
</network>
</hazelcast-client>
and I've found that there is possibility to add <cluster-members> tag inside <network> to provide custom <address> for hazelcast instances. I've modified my hazelcast.xml file into:
<network>
<cluster-members>
<address>${HAZELCAST_URL}</address>
</cluster-members>
...
But whenever I'm starting my app it shows:
2017-11-10 17:55:45 [service,,,] WARN c.h.c.s.i.ClusterListenerSupport hz.client_0 [dev] [3.8.5] Exception during initial connection to ${HAZELCAST_URL}:5701, exception java.lang.IllegalArgumentException: Can't resolve address: ${HAZELCAST_URL}:5701
2017-11-10 17:55:45 [service,,,] WARN c.h.c.s.i.ClusterListenerSupport hz.client_0 [dev] [3.8.5] Exception during initial connection to ${HAZELCAST_URL}:5702, exception java.lang.IllegalArgumentException: Can't resolve address: ${HAZELCAST_URL}:5702
It means it still tries to connect to default port and variable is not resolved. Is there a way to configure it?
You can pass java.util.Properties into the client config builder. All you need do is build it from Spring's environment.
#Bean
public ClientConfig clientConfig(Environment environment) throws Exception {
Properties properties = new Properties();
String HAZELCAST_URL = "HAZELCAST_URL";
properties.put(HAZELCAST_URL, environment.getProperty(HAZELCAST_URL));
XmlClientConfigBuilder xmlClientConfigBuilder = new XmlClientConfigBuilder("hazelcast-client.xml");
xmlClientConfigBuilder.setProperties(properties);
return xmlClientConfigBuilder.build();
}
#Bean
public HazelcastInstance hazelcastInstance(ClientConfig clientConfig) {
return HazelcastClient.newHazelcastClient(clientConfig);
}
Note, there are more elegant ways to do this, the above is just one solution keeping it as simple as possible

How do I print exception stack traces in my log while suppressing other Spring DEBUG messages?

I’m using Spring 3.2.11.RELEASE and JBoss 7.1.3.Final. In my JBoss standalone.xml file, I have the following setting
<subsystem xmlns="urn:jboss:domain:logging:1.1">
<console-handler name="CONSOLE">
<level name="DEBUG"/>
<formatter>
<pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
</formatter>
</console-handler>
<periodic-rotating-file-handler name="FILE">
<formatter>
<pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
</formatter>
<file relative-to="jboss.server.log.dir" path="server.log"/>
<suffix value=".yyyy-MM-dd"/>
<append value="true"/>
</periodic-rotating-file-handler>
…
<logger category="org.springframework">
<level name="DEBUG"/>
</logger>
The problem is the DEBUG level prints out too much stuff that I don’t want, like
15:27:03,753 DEBUG [org.springframework.orm.jpa.JpaTransactionManager] (http-/0.0.0.0:8080-1) Closing JPA EntityManager [org.hibernate.jpa.internal.EntityManagerImpl#5d4c14] after transaction
However, if I upgrade the level o ERROR, I don’t see stack traces from Exceptions thrown iny web app, like
15:27:03,696 DEBUG [org.springframework.web.servlet.DispatcherServlet] (http-/0.0.0.0:8080-1) Handler execution resulted in exception - forwarding to resolved error view: ModelAndView: reference to view with name 'activity/response/file'; model is {error={"status":"failure","exception":"NullPointerException"}}: java.lang.NullPointerException
at org.mainco.subco.registration.mvc.RegistrationController.getInitRegPage(RegistrationController.java:369) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [classes.jar:1.6.0_65]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [classes.jar:1.6.0_65]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [classes.jar:1.6.0_65]
at java.lang.reflect.Method.invoke(Method.java:597) [classes.jar:1.6.0_65]
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) [spring-web-3.2.11.RELEASE.jar:3.2.11.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) [spring-web-3.2.11.RELEASE.jar:3.2.11.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) [spring-webmvc-3.2.11.RELEASE.jar:3.2.11.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) [spring-webmvc-3.2.11.RELEASE.jar:3.2.11.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:685) [spring-webmvc-3.2.11.RELEASE.jar:3.2.11.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) [spring-webmvc-3.2.11.RELEASE.jar:3.2.11.RELEASE]
Notice how the first line of the stack trace is Spring’s handler (“org.springframework.web.servlet.DispatcherServlet”), but the actual exception originates from my code (the line with “org.mainco.subco.registration.mvc.RegistrationController”). How can I get the exception stack traces to appear in my log while suppressing all the other non-essential Spring debugging messages?
I know this is too late, but I have encountered this issue myself and found a solution, so I thought why not share it here, maybe it helps other people out in the future.
In my case, while using Spring Boot 1.4.1.RELEASE and Spring Web 4.3.3.RELEASE and log4j, the exceptions were thrown by the default AbstractHandlerExceptionResolver under the DEBUG log level. So just create your own custom ExceptionResolver, in which you throw the exception with your own custom log level and map it for the entire web application.
ApplicationConfiguration.java:
#Configuration
#EnableAutoConfiguration
#ComponentScan(basePackages = "com.example.app") // in order for the app to scan all components, as well as our custom ExceptionResolver
public class ApplicationConfiguration
{
// database configs & other stuff
}
AppExceptionResolver.java:
#Component
public class AppExceptionResolver extends AbstractHandlerExceptionResolver
{
private static final Logger logger = LoggerFactory.getLogger(AppExceptionResolver.class.getSimpleName());
#Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
{
logger.error("Application error in: [" + ex.getClass().getName() + "]", ex);
return null;
}
}

Setting up JNDI Datasource with oracle in Tomcat

I can't make it work to get connection from DataSource obtained from JNDI in tomcat 7.0, resulting in error like this:
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of cla
ss '' for connect URL 'null'
I have done in many ways following the doc and other people suggestions, but still not able to fix it. Here are my settings:
In web.xml:
<resource-ref>
<description>MyDataSource</description>
<res-ref-name>jdbc/MyDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
In context.xml:
<Context>
<Resource name="jdbc/MyDataSource" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="abc" password="abc" driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:#123.123.123.123:1521:xe"/>
<!-- // tried both driver class names but all not work driverClassName="oracle.jdbc.driver.OracleDriver" -->
</Context>
Also, I tried to put that in server.xml, also not work
<Resource name="jdbc/MyDataSource" auth="Container" type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:#123.123.123.123:1521:xe"
servicename="MyDataSource" username="abc" password="abc"
maxActive="20" maxIdle="10" maxWait="20000"/>
<ResourceParams name="jdbc/MyDataSource">
<parameter>
<name>user</name>
<value>abc</value>
</parameter>
<parameter>
<name>password</name>
<value>abc</value>
</parameter>
<parameter>
<name>driverClassName</name>
<value>oracle.jdbc.driver.OracleDriver</value>
</parameter>
</ResourceParams>
Put classes12.jar as well as ojdbc14.jar in Tomcat 7.0\lib
Can anyone point me the right way?
I wasted so much time on that configuration but still cannot make it work. Thanks in advance!
John
Stack Trace as below:
DS: org.apache.tomcat.dbcp.dbcp.BasicDataSource#497062
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1452)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at DBTest.doGet(DBTest.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:928)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:539)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:298)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.knownURL(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(Unknown Source)
at java.sql.DriverManager.getDriver(Unknown Source)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1437)
... 21 more
And here is the code, exception at ds.getConnection. (It is not typical way to get DS, bcoz need to match WebSphere way...)
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
initCtx = new InitialContext(env);
DataSource ds = (DataSource) initCtx.lookup("java:comp/env/jdbc/MyDataSource");
System.err.println("DS: " + ds.toString());
Connection conn = ds.getConnection();
I realized that I defined the resource twice, once in my TOMCAT_HOME/conf/context.xml and in my applicationPath/META-INF/context.xml. Once I removed the resource from TOMCAT_HOME/conf/context.xml everything worked great.

Resources