JMS Producer is closed - ejb

Using Wildfly and JMS via Hornetq I got this exception
javax.ejb.EJBTransactionRolledbackException: Producer is closed
It occurs once or twice every few hours.
Caused by: javax.jms.IllegalStateRuntimeException: Producer is closed
at org.hornetq.jms.client.JmsExceptionUtils.convertToRuntimeException(JmsExceptionUtils.java:60) [hornetq-jms-client-2.4.1.Final.jar:]
at org.hornetq.jms.client.HornetQJMSProducer.send(HornetQJMSProducer.java:112) [hornetq-jms-client-2.4.1.Final.jar:]
at org.hornetq.jms.client.HornetQJMSProducer.send(HornetQJMSProducer.java:230) [hornetq-jms-client-2.4.1.Final.jar:]
at com.turbineam.tradeagent.message.MessageSender.sendMessage(MessageSender.java:26) [classes:]
at com.turbineam.tradeagent.agent.TradeAgent.sendMessage(TradeAgent.java:36) [classes:]
at com.turbineam.tradeagent.agent.TradeAgent.handleMessage(TradeAgent.java:82) [classes:]
at sun.reflect.GeneratedMethodAccessor273.invoke(Unknown Source) [:1.8.0_05]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.8.0_05]
at java.lang.reflect.Method.invoke(Method.java:483) [rt.jar:1.8.0_05]
at org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptor.java:52)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.invocation.WeavedInterceptor.processInvocation(WeavedInterceptor.java:53)
at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:407)
at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.doMethodInterception(Jsr299BindingsInterceptor.java:82) [wildfly-weld-8.2.0.Final.jar:8.2.0.Final]
at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.processInvocation(Jsr299BindingsInterceptor.java:93) [wildfly-weld-8.2.0.Final.jar:8.2.0.Final]
at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.invocation.WeavedInterceptor.processInvocation(WeavedInterceptor.java:53)
at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.as.ejb3.component.invocationmetrics.ExecutionTimeInterceptor.processInvocation(ExecutionTimeInterceptor.java:43) [wildfly-ejb3-8.2.0.Final.jar:8.2.0.Final]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:407)
at org.jboss.as.ejb3.concurrency.ContainerManagedConcurrencyInterceptor.processInvocation(ContainerManagedConcurrencyInterceptor.java:104) [wildfly-ejb3-8.2.0.Final.jar:8.2.0.Final]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:407)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46) [weld-core-impl-2.2.6.Final.jar:2014-10-03 10:05]
at org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor.processInvocation(EjbRequestScopeActivationInterceptor.java:83) [wildfly-weld-8.2.0.Final.jar:8.2.0.Final]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.as.ee.concurrent.ConcurrentContextInterceptor.processInvocation(ConcurrentContextInterceptor.java:45) [wildfly-ee-8.2.0.Final.jar:8.2.0.Final]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.invocation.InitialInterceptor.processInvocation(InitialInterceptor.java:21)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
at org.jboss.as.ee.component.interceptors.ComponentDispatcherInterceptor.processInvocation(ComponentDispatcherInterceptor.java:53)
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.as.ejb3.component.singleton.SingletonComponentInstanceAssociationInterceptor.processInvocation(SingletonComponentInstanceAssociationInterceptor.java:52) [wildfly-ejb3-8.2.0.Final.jar:8.2.0.Final]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:251) [wildfly-ejb3-8.2.0.Final.jar:8.2.0.Final]
... 201 more
Caused by: javax.jms.IllegalStateException: Producer is closed
at org.hornetq.jms.client.HornetQMessageProducer.checkClosed(HornetQMessageProducer.java:537) [hornetq-jms-client-2.4.1.Final.jar:]
at org.hornetq.jms.client.HornetQMessageProducer.send(HornetQMessageProducer.java:206) [hornetq-jms-client-2.4.1.Final.jar:]
at org.hornetq.jms.client.HornetQMessageProducer.send(HornetQMessageProducer.java:200) [hornetq-jms-client-2.4.1.Final.jar:]
at org.hornetq.ra.HornetQRAMessageProducer.send(HornetQRAMessageProducer.java:145)
at org.hornetq.jms.client.HornetQJMSProducer.send(HornetQJMSProducer.java:107) [hornetq-jms-client-2.4.1.Final.jar:]
... 240 more
Sender is created as follows:
#Slf4j
public class MessageSender {
#Inject
#JMSConnectionFactory("java:jboss/DefaultJMSConnectionFactory")
private JMSContext context;
public void sendMessage(Destination destination, String messageId, Serializable serializable) throws NamingException, JMSException {
log.debug("Sending a message: " + serializable.toString());
context.createProducer().setJMSCorrelationID(messageId).send(destination, serializable);
}
}
Maybe I'm missing something but I don't understand why it happens. How to handle it properly? I definitely need this message to be sent no matters what. Thanks in advance.
EDITED:
The most important part I guess that lead me to resolve this issue is that from time to time I got (in addition to closed Producer):
WARN [org.hornetq.core.client] (ejb) HQ214021: Invalid concurrent session usage. Sessions are not supposed to be used by more than one thread concurrently.
Bean which I injected MessageSender to was annotated with #Stateless.

Ok, after many, many attempts I managed to solve this issue. What was wrong with this setup was that if no annotion determining scope was provided on MessageSender then it was #Dependent. And it means that it was of the scope of the bean that it was injected to. In that case #Stateless. There was only one session created. Method from #Stateless bean can be run concurrently and that was the main reason of the problem. sendMeasge used the same JMS session. The simplest solution to this problem is to either ensure that there is always one thred in sendMessage or to create multiple sessions. One of the solution I found is to use #RequestScope in the following way:
#Slf4j
#RequestScope
public class MessageSender {
#Inject
#JMSConnectionFactory("java:jboss/DefaultJMSConnectionFactory")
private JMSContext context;
public void sendMessage(Destination destination, String messageId, Serializable serializable) throws NamingException, JMSException {
log.debug("Sending a message: " + serializable.toString());
context.createProducer().setJMSCorrelationID(messageId).send(destination, serializable);
}
}
In the above example we create session each time we send message - so there is no longer a problem of concurrent session usage and it the problem with closed producer also disappeared.
If someone would be interested I recommend futher reading from:
http://www.mastertheboss.com/jboss-server/jboss-jms/jms-20-tutorial-on-wildfly-as

Related

Error creating bean with name 'springSecurityFilterChain' defined in class path resource

I am new to Spring Security. I am using okta OIDC application to secure my Resource Server.
I have the following application.yml
okta:
oauth2:
client-id: {client-id}
issuer: https://{okta-domain}.okta.com
I have the following security configuration :
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http) throws Exception{
http.authorizeRequests().antMatchers("/").permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("user_pwd").roles("USER").and()
.withUser("admin").password("admin_pwd").roles("USER", "ADMIN");
}
}
I am getting the following error after adding the above piece of code:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalStateException: Can't configure anyRequest after itself
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:655) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:483) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1336) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1176) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:311) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:897) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
at com.symbiose.OAuthResourceServerApplication.main(OAuthResourceServerApplication.java:13) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_241]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_241]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_241]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_241]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.3.4.RELEASE.jar:2.3.4.RELEASE]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.IllegalStateException: Can't configure anyRequest after itself
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:650) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
... 27 common frames omitted
Caused by: java.lang.IllegalStateException: Can't configure anyRequest after itself
at org.springframework.util.Assert.state(Assert.java:76) ~[spring-core-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.security.config.annotation.web.AbstractRequestMatcherRegistry.anyRequest(AbstractRequestMatcherRegistry.java:74) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter.configure(ResourceServerConfigurerAdapter.java:30) ~[spring-security-oauth2-2.3.4.RELEASE.jar:na]
at org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration.configure(ResourceServerConfiguration.java:154) ~[spring-security-oauth2-2.3.4.RELEASE.jar:na]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:231) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:322) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:94) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration$$EnhancerBySpringCGLIB$$4941180f.init(<generated>) ~[spring-security-oauth2-2.3.4.RELEASE.jar:na]
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:370) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:324) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104) ~[spring-security-config-5.3.4.RELEASE.jar:5.3.4.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_241]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_241]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_241]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_241]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
... 28 common frames omitted
Also, how do I validate the user and password dynamically without hard coding the values as above in the "InMemoryAuthentication". For ex: I have created few people and added them in User and Admin groups as per my requirement in Okta, added the user and admin groups to my OIDC SPA App.
In that case, the users with specific user or admin role will be logging in which I need to capture and restrict access to few APIs in case of user ROLE. How do I configure the above code to dynamically verify the logged in user?
There are a few questions in here, so I'll attempt to answer them.
First, you are configuring both Basic Auth and an OAuth resource server.
My suggestion is to keep it simple and JUST use OAuth. You can configure them both, but you will need to explicitly do so in your WebSecurityConfigurerAdapter
i.e. in configure() add:
// require authentication for ALL endpoints
http.authorizeRequests().anyRequest().authenticated();
// enable resource server to process JWTs
http.oauth2ResourceServer().jwt();
One issue you have is you have this line:
http.authorizeRequests().antMatchers("/").permitAll();
This allows ALL unauthenticated requests.
If you do NOT define a WebSecurityConfigurerAdapter at all, the default is the first code block I posted.
I usually recommend to start with the defaults. The default is a secure application :)
Once you have that working, you can add a custom WebSecurityConfigurerAdapter. but start with a similar default configuration.
Next, start allowing any unauthenticated paths, something like:
http.authorizeRequests()
// Allow anon access to the root application
.antMatchers("/", "/index.html").permitAll()
// Require authentication for ALL other requests
.anyRequest().authenticated();
// enable resource server, process JWTs
http.oauth2ResourceServer().jwt();
Finally, add other authentication sources (in your case basic auth if needed).
For role-based security you have a couple of options too, you can either add them via annotations or in your WebSecurityConfigurerAdapter.
This post should walk you through everything in a bit more detail: https://developer.okta.com/blog/2019/06/20/spring-preauthorize

when to use RecoveryCallback vs KafkaListenerErrorHandler

I'm trying to understand when should i use org.springframework.retry.RecoveryCallback and org.springframework.kafka.listener.KafkaListenerErrorHandler?
As of today, I'm using a class (implements org.springframework.retry.RecoveryCallback) to log error message and send the message to DLT and it's working. For sending a message to DLT, I'm using Spring KafkaTemplate and then I came across KafkaListenerErrorHandler and DeadLetterPublishingRecoverer. Now, can you please suggest me, how should i use KafkaListenerErrorHandler and DeadLetterPublishingRecoverer? Can this replace the RecoveryCallback?
Here is my current kafkaListenerContainerFactory code
#Bean
public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(primaryConsumerFactory());
factory.setRetryTemplate(retryTemplate());
factory.setRecoveryCallback(recoveryCallback);
factory.getContainerProperties().setAckMode(AckMode.RECORD);
factory.setConcurrency(1);
factory.getContainerProperties().setMissingTopicsFatal(false);
return factory; }
If it's working as you want now, why change it?
There are several layers and you can choose which one to do the error handling, depending on your needs.
KafkaListenerErrorHandler would be invoked for each delivery attempt within the retry, so you typically won't use it with retry.
Retry RecoveryCallback is invoked after retries are exhausted (or immmediately if you have classified an exception as not retryable).
ErrorHandler - is in the container and is invoked if any listener throws an exception, not just #KafkaListeners.
With recent versions of the framework you can completely replace listener level retry with a SeekToCurrentErrorHandler configured with a DeadLetterPublishingRecoverer and a BackOff.
The DeadLetterPublishingRecoverer is intended for use in a container error handler since it needs the raw ConsumerRecord<?, ?>.
The KafkaListenerErrorHandler only has access to the spring-messaging Message<?> that is converted from the ConsumerRecord<?, ?>.
To add on to the excellent context from #GaryRussell, this is what i am currently using:
I am handling any errors(a.k.a exception) like this:
factory.setErrorHandler(new SeekToCurrentErrorHandler(
new DeadLetterPublishingRecoverer(kafkaTemplate), new FixedBackOff(0L, 0L)));
And to print this error, i have a listener on the .DLT and i am printing the exception stack trace that is stored in the header like so:
#KafkaListener(id = "MY_ID", topics = MY_TOPIC + ".DLT")
public void listenDlt(ConsumerRecord<String, SomeClassName> consumerRecord,
#Header(KafkaHeaders.DLT_EXCEPTION_STACKTRACE) String exceptionStackTrace) {
logger.error(exceptionStackTrace);
}
Note: I am using logger.error, because i am redirecting all error messages to an error log file that is being monitored.
BONUS:
If you set the following:
logging.level.org.springframework.kafka=DEBUG
You will see this in your console/log:
xxx [org.springframework.kafka.KafkaListenerEndpointContainer#7-2-C-1] DEBUG o.s.k.listener.SeekToCurrentErrorHandler - Skipping seek of: ConsumerRecord xxx
xxx [kafka-producer-network-thread | producer-3] DEBUG o.s.k.l.DeadLetterPublishingRecoverer - Successful dead-letter publication: SendResult xxx
If you have a better way to log, i would appreciate your comment.
Thanks!
Cheers

Calling multiple DAO from a single servlet

does anyone know how to create object from mulitple data access object and call their method. When i create object from only one DAO and call their method then it works perfect but with multiple it throws null pointer exception,
and here's the error i am getting
java.lang.NullPointerException at front.Home.processRequest(Home.java:70) at front.Home.doGet(Home.java:97) at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188) at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191) at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189) at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114) at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544) at java.lang.Thread.run(Thread.java:744)
Annotations are only applied to a single field, class or method, so you should annotate all your dependencies separately:
#EJB private CategoryDAO categoryDAO;
#EJB private GoldDAO goldDAO;
#EJB private ForexDAO forexDAO;

sending mail using thymeleaf in Spring Schedular

I am trying to send email using thymeleaf template. But I am getting an error message as
org.thymeleaf.exceptions.TemplateProcessingException: Resource resolution by ServletContext with org.thymeleaf.resourceresolver.ServletContextResourceResolver can only be performed when context implements org.thymeleaf.context.IWebContext [current context: org.thymeleaf.context.Context]
at org.thymeleaf.resourceresolver.ServletContextResourceResolver.getResourceAsStream(ServletContextResourceResolver.java:74)
at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:221)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1192)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1148)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1095)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1008)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:982)
at in.coep.vlabteam.leap.implementations.ScheduleNotificationImpl.sendNotification(ScheduleNotificationImpl.java:205)
at in.coep.vlabteam.leap.implementations.ScheduleNotificationImpl.sendScheduleNotificationMail(ScheduleNotificationImpl.java:105)
at in.coep.vlabteam.leap.services.ScheduleNotificationService.sendScheduleNotificationByMail(ScheduleNotificationService.java:47)
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.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:64)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:53)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:206)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
10936 [taskScheduler-1] ERROR org.thymeleaf.TemplateEngine - [THYMELEAF][taskScheduler-1] Exception processing template "scheduleMail.html": Resource resolution by ServletContext with org.thymeleaf.resourceresolver.ServletContextResourceResolver can only be performed when context implements org.thymeleaf.context.IWebContext [current context: org.thymeleaf.context.Context]
I cant used WebContext() instead of Context(). Because for webContext I need HttpServletRequest object that I can't get here, because it is not in scope of request.
I am trying to send mail using context(), but I am getting an error.
Please anyone have solution on this. Thanks in advance
Here is my code,
final Context ctx = new Context();
ctx.setVariable("eagletId", user.getEagletId());
ctx.setVariable("name", user.getFirstName());
ctx.setVariable("setSentDate", new Date());
ctx.setVariable("department", user.getDepartment());
ctx.setVariable("batch", user.getBatch());
// ctx.setVariable("month" Constants.LeapConstants.UserType);
// Prepare message using a Spring helper
final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
final MimeMessageHelper message =
new MimeMessageHelper(mimeMessage, true /* multipart */, "UTF-8");
message.setSubject("Create your report for month");
message.setFrom("leap#gmail.com");
message.setTo("vlab#gmail.com");
// Create the HTML body using Thymeleaf
final String htmlContent = this.templateEngine.process("scheduleMail.html", ctx);
message.setText(htmlContent, true /* isHtml */);
// Send mail
this.mailSender.send(mimeMessage);
Your template engine is configured with ServletContextTemplateResolver instead of either FileTemplateResolver or ClassLoaderTemplateResolver. This will be defined most likely in a spring config file somewhere. If configured in code, see the Thymeleaf user's guide on configuring the template engine and configuration of the templateResolver. It's good doc.
Via xml configuration, it should look something like this:
<beans:bean id="templateResolver"
class="org.thymeleaf.templateresolver.ClassLoaderTemplateResolver">
</beans:bean>

how to save a base64 as image in java server faces project

I am doing a project for school. Subject of project is tshirt design. I am using jsf and primefaces. But I don't know well jsf and primefaces. I wanted save a base64 from html as image in jsf project. But when I had tried to following functions, NullPointerException. This function is called in a Servlet. A base64 is grabbed by this Servlet.
public static void save(String dataURL){
line85: ExternalContext external = FacesContext.getCurrentInstance().getExternalContext();
ServletContext servletContext = (ServletContext) external.getContext();
String filename = servletContext.getRealPath("cloud.png");
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes;
try {
decodedBytes = decoder.decodeBuffer(dataURL.split("data:image/(png|jpg);base64,")[1]);
BufferedImage imag=ImageIO.read(new ByteArrayInputStream(decodedBytes));
ImageIO.write(imag, "png", new File(filename));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
23.Ara.2012 17:48:20 org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [org.soft.tshirt.servlets.DesignServlet] in context with path [/Tshirt] threw exception
java.lang.NullPointerException
at org.soft.tshirt.beans.ImageBean.save(ImageBean.java:85)
at org.soft.tshirt.servlets.DesignServlet.processRequest(DesignServlet.java:102)
at org.soft.tshirt.servlets.DesignServlet.doPost(DesignServlet.java:76)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
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:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
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:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
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:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
The current instance of the FacesContext is only available in the HTTP request thread which is been served through the FacesServlet who is the one responsible for creating the FacesContext. In other words, only when the request URL matches the URL pattern of the FacesServlet. In other words, only JSF pages, JSF managed beans (and thus not backing beans which you instantiate yourself like as is happening here!) and all other JSF artifacts like event/phase listeners, UI components, etc have the current instance of the FacesContext available to them.
In an arbitrary homegrown HTTP servlet, the FacesContext isn't available at all, for the simple reason that the FacesServlet is not been invoked beforehand. So the getCurrentInstance() method on it would return null. You know, trying to access/invoke any fields/method on null will cause NullPointerException. See also its javadoc.
In order to achieve the sole goal of obtaining the ServletContext, just invoke the inherited GenericServlet#getServletContext() method inside the servlet.
protected void doPost(...) {
String filename = getServletContext().getRealPath("cloud.png");
// ...
}
Pass that information instead to the method responsible for creating the file. You might want to extract that code into a different class which is reused between your servlet and backing bean.
Unrelated to the concrete problem, writing files to the expanded WAR folder is really a bad practice for the reasons mentioned in among others this answer: Uploaded image only available after refreshing the page.

Resources