In my JavaFx project I inject my controllers like so, which works fine:
#Configuration
public class AppFactory {
#Bean
public HomeController homeController() throws IOException {
return (HomeController) loadController("/wakiliproject/Home.fxml");
}
FXMLLoader loader = null;
protected Object loadController(String url) throws IOException {
loader = new FXMLLoader(getClass().getResource(url));
loader.load();
return loader.getController();
}
}
However, for non-controller classes, I get a null pointer exception, probably because the class never gets injected. Say, for example, I try to call a method in a non-controller class from another non-controller class like so:
Sending email via Spring, for example:
public class HomeController extends Application {
#Autowired
MailMail mailMail;
// Send email here
public void sendEmailMethod() {
System.out.println("Here ----------------------------------------------------------------");
mailMail.sendMail("olireylikesyou#gmail.com", "tryrevilo#yahoo.com", "Hello", "Subjecto");
}
// The other class methods
The other classes:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="username" value="mygmailusername#gmail.com" />
<property name="password" value="gmailpassword" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
<bean id="mailMail" class="wakiliproject.ServerSide.EMail.MailMail">
<property name="mailSender" ref="mailSender" />
</bean>
--
public class MailMail {
private MailSender mailSender;
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail(String from, String to, String subject, String msg) {
//creating message
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(msg);
//sending message
mailSender.send(message);
}
}
The stacktrace:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:367)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:305)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:894)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:56)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:158)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.mail.MailSendException: Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. k10sm2188955lae.42 - gsmtp
; message exceptions (1) are:
Failed message 1: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. k10sm2188955lae.42 - gsmtp
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:448)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:308)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:297)
at wakiliproject.ServerSide.EMail.MailMail.sendMail(MailMail.java:22)
at wakiliproject.HomeController$HomeInit.homeInit(HomeController.java:618)
at wakiliproject.HomeController$HomeInit.access$100(HomeController.java:613)
at wakiliproject.HomeController.initHomeController(HomeController.java:319)
at wakiliproject.WakiliProject.start(WakiliProject.java:34)
at com.sun.javafx.application.LauncherImpl$8.run(LauncherImpl.java:837)
at com.sun.javafx.application.PlatformImpl$7.run(PlatformImpl.java:335)
at com.sun.javafx.application.PlatformImpl$6$1.run(PlatformImpl.java:301)
at com.sun.javafx.application.PlatformImpl$6$1.run(PlatformImpl.java:298)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$6.run(PlatformImpl.java:298)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$300(WinApplication.java:39)
at com.sun.glass.ui.win.WinApplication$4$1.run(WinApplication.java:112)
... 1 more
Exception running application wakiliproject.WakiliProject
Java Result: 1
had a similar problem... got me some attempts to configure it right in my application.properties (I'm injecting JavaMailSender using spring)
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.auth = true;
spring.mail.properties.mail.socketFactory.port=587
spring.mail.properties.mail.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.socketFactory.fallback=false
later i was required to enable looser security to my account during the test:
"change your settings at https://www.google.com/settings/security/lesssecureapps so that your account is no longer protected by modern security standards"
or i got an authentication error.
I hope that helps
According to Mladen Uzelac You need to set some properties for your SMTP connection.
Link related:
http://forum.spring.io/forum/spring-projects/web/68425-javax-mail-messagingexception-530-5-7-0-must-issue-a-starttls-command-first-5sm505
Related
I have already defined a datasource in Spring configuration.
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/db" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
For LOG4J2 JDBCAppender, I know we need to obtain the datasource:
<JDBC name="databaseAppender" tableName="error_log">
<ConnectionFactory class="net.example.db"
method="getDatabaseConnection" />
<Column name="EVENT_DATE" isEventTimestamp="true" />
<Column name="LEVEL" pattern="%level" />
<Column name="LOGGER" pattern="%logger" />
<Column name="MESSAGE" pattern="%message" />
<Column name="THROWABLE" pattern="%ex{full}" />
</JDBC>
I have already added the package into the component-scan:
<context:component-scan base-package="com.test,net.example.db" />
And add annotation at the class ConnectionFactory as a Component
import java.sql.Connection;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class ConnectionFactory {
#Autowired
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Connection getDatabaseConnection() throws Exception {
return dataSource.getConnection();
}
}
However, I am getting null when call getDatabaseConnection()
2017-01-14 14:17:24,579 localhost-startStop-1 ERROR JdbcDatabaseManager jdbcManager{ description=databaseAppender, bufferSize=0, connectionSource=factory{ public static java.sql.Connection net.example.db.ConnectionFactory.getDatabaseConnection() }, tableName=error_log, columns=[ { name=EVENT_DATE, layout=null, literal=null, timestamp=true }, { name=LEVEL, layout=%level, literal=null, timestamp=false }, { name=LOGGER, layout=%logger, literal=null, timestamp=false }, { name=MESSAGE, layout=%message, literal=null, timestamp=false }, { name=THROWABLE, layout=%ex{full}, literal=null, timestamp=false } ] } Could not perform database startup operations: java.sql.SQLException: Failed to obtain connection from factory method. java.sql.SQLException: Failed to obtain connection from factory method.
at org.apache.logging.log4j.core.appender.db.jdbc.FactoryMethodConnectionSource$1.getConnection(FactoryMethodConnectionSource.java:107)
at org.apache.logging.log4j.core.appender.db.jdbc.FactoryMethodConnectionSource.getConnection(FactoryMethodConnectionSource.java:53)
at org.apache.logging.log4j.core.appender.db.jdbc.JdbcDatabaseManager.startupInternal(JdbcDatabaseManager.java:60)
at org.apache.logging.log4j.core.appender.db.AbstractDatabaseManager.startup(AbstractDatabaseManager.java:65)
at org.apache.logging.log4j.core.appender.db.AbstractDatabaseAppender.start(AbstractDatabaseAppender.java:89)
at org.apache.logging.log4j.core.config.AbstractConfiguration.start(AbstractConfiguration.java:255)
at org.apache.logging.log4j.core.LoggerContext.setConfiguration(LoggerContext.java:530)
at org.apache.logging.log4j.core.LoggerContext.start(LoggerContext.java:258)
at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:239)
at org.apache.logging.log4j.core.config.Configurator.initialize(Configurator.java:158)
at org.apache.logging.log4j.web.Log4jWebInitializerImpl.initializeNonJndi(Log4jWebInitializerImpl.java:168)
at org.apache.logging.log4j.web.Log4jWebInitializerImpl.start(Log4jWebInitializerImpl.java:110)
at org.apache.logging.log4j.web.Log4jServletContainerInitializer.onStartup(Log4jServletContainerInitializer.java:57)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5604)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1571)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1561)
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)
Caused by: java.lang.NullPointerException
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:497)
at org.apache.logging.log4j.core.appender.db.jdbc.FactoryMethodConnectionSource$1.getConnection(FactoryMethodConnectionSource.java:105)
... 20 more
I am skeptical that whether the bean dataSource has not yet created when LOGJ2 calls getDatabaseConnection(). Please let me know what would be the reason and solution.
Please go through this tutorial [ Log4j2 JDBC ] (http://self-learning-java-tutorial.blogspot.in/2015/10/log4j2-jdbcappender-write-log-messages.html)
As mentioned : please see this part
Following are the ConnectionFactory Parameters.
Class : Name of the class, that contains a static factory method for obtaining JDBC connections.
method : The name of a static factory method for obtaining JDBC connections. Method return type must be either java.sql.Connection or DataSource.
Please note that it requires a static factory method. thats why invocation of reflection fails.
Finally I found one solution to my answer. LOG4J is initialized before Spring, therefore the bean Datasource will return null.
I followed the instructions from below URL:
How to use Spring BoneCPDataSource bean as data source for Log4j 2 JDBC appender?
And everything is fine now.
<int:poller fixed-delay="${fixedDelay}" default="true">
<int:advice-chain>
<ref bean="pollAdvise"/>
</int:advice-chain>
</int:poller>
<bean id="pollAdvise" class="org.springframework.integration.scheduling.PollSkipAdvice">
<constructor-arg ref="healthCheckStrategy"/>
</bean>
<bean id="healthCheckStrategy" class="test.main.ServiceHealthCheckPollSkipStrategy">
<property name="url" value="${url}"/>
<property name="doHealthCheck" value="${doHealthCheck}"/>
<property name="restTemplate" ref="restTemplate"/>
</bean>
<bean id="restTemplate"
class="org.springframework.web.client.RestTemplate">
<constructor-arg ref="requestFactory"/>
</bean>
<bean id="requestFactory"
class="test.BatchClientHttpRequestFactory">
<constructor-arg ref="verifier"/>
</bean>
and my health check strategy looks like below
#ManagedResource
public class ServiceHealthCheckPollSkipStrategy implements PollSkipStrategy {
private volatile boolean skip=false;
private String url;
private static String doHealthCheck;
private RestTemplate restTemplate;
public RestTemplate getRestTemplate() {
return restTemplate;
}
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDoHealthCheck() {
return doHealthCheck;
}
public void setDoHealthCheck(String doHealthCheck) {
ServiceHealthCheckPollSkipStrategy.doHealthCheck= doHealthCheck;
}
#Override
public boolean skipPoll() {
if(doHealthCheck.equals("false")){
return this.skip;
}
else if(doHealthCheck.equals("true")){
List<String> urlList =getUrlfromEncodedString(url);
for (String url : urlList) {
boolean status =performHealthCheck(url);
if(status==false){
return this.skip = true;
}
}
return this.skip;
}
else {
throw new IllegalArgumentException("do health check can be either true or false");
}
}
/**
* Skip future polls.
*/
#ManagedOperation
public void skipPolls() {
this.skip = true;
}
/**
* Resume polling at the next {#code Trigger} event.
*/
#ManagedOperation
public void reset() {
this.skip = false;
}
private List<String> getUrlfromEncodedString(String urls) throws IllegalArgumentException
{
if(urls==null){
throw new IllegalArgumentException("urls passed is null");
}
List<String> urlList = Arrays.asList(urls.split("\\s*,\\s*"));
return urlList;
}
private boolean performHealthCheck(String url){
if(url==null){
throw new IllegalArgumentException("url passed is null");
}
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("API-Key", "RTM");
HttpEntity<String> request = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> response = restTemplate.
exchange(url, HttpMethod.OPTIONS, request, String.class);
if (response.getStatusCode().toString().equals("200")){
return true;
}
return false;
}
}
I get below exception
Unable to register MBean [test.main.ServiceHealthCheckPollSkipStrategy#73d4b814] with key 'healthCheckStrategy'; nested exception is javax.management.InstanceAlreadyExistsException: test.main:name=healthCheckStrategy,type=ServiceHealthCheckPollSkipStrategy
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:625)
at org.springframework.jmx.export.MBeanExporter.registerBeans(MBeanExporter.java:550)
at org.springframework.jmx.export.MBeanExporter.afterSingletonsInstantiated(MBeanExporter.java:432)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:775)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:139)
at org.springframework.xd.module.core.SimpleModule.initialize(SimpleModule.java:213)
at org.springframework.xd.dirt.module.ModuleDeployer.doDeploy(ModuleDeployer.java:217)
at org.springframework.xd.dirt.module.ModuleDeployer.deploy(ModuleDeployer.java:200)
at org.springframework.xd.dirt.server.container.DeploymentListener.deployModule(DeploymentListener.java:365)
at org.springframework.xd.dirt.server.container.DeploymentListener.deployStreamModule(DeploymentListener.java:334)
at org.springframework.xd.dirt.server.container.DeploymentListener.onChildAdded(DeploymentListener.java:181)
at org.springframework.xd.dirt.server.container.DeploymentListener.childEvent(DeploymentListener.java:149)
at org.apache.curator.framework.recipes.cache.PathChildrenCache$5.apply(PathChildrenCache.java:509)
at org.apache.curator.framework.recipes.cache.PathChildrenCache$5.apply(PathChildrenCache.java:503)
at org.apache.curator.framework.listen.ListenerContainer$1.run(ListenerContainer.java:92)
at com.google.common.util.concurrent.MoreExecutors$SameThreadExecutorService.execute(MoreExecutors.java:297)
at org.apache.curator.framework.listen.ListenerContainer.forEach(ListenerContainer.java:83)
at org.apache.curator.framework.recipes.cache.PathChildrenCache.callListeners(PathChildrenCache.java:500)
at org.apache.curator.framework.recipes.cache.EventOperation.invoke(EventOperation.java:35)
at org.apache.curator.framework.recipes.cache.PathChildrenCache$10.run(PathChildrenCache.java:762)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
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)
Caused by: javax.management.InstanceAlreadyExistsException: test.main:name=healthCheckStrategy,type=ServiceHealthCheckPollSkipStrategy
at com.sun.jmx.mbeanserver.Repository.addMBean(Repository.java:437)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerWithRepository(DefaultMBeanServerInterceptor.java:1898)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:966)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:900)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:324)
at com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:522)
at org.springframework.jmx.support.MBeanRegistrationSupport.doRegister(MBeanRegistrationSupport.java:195)
at org.springframework.jmx.export.MBeanExporter.registerBeanInstance(MBeanExporter.java:678)
at org.springframework.jmx.export.MBeanExporter.registerBeanNameOrInstance(MBeanExporter.java:615)
... 30 m
I got the javax.management.InstanceAlreadyExistsException as part of the stacktrace, however the leading error was java.lang.IllegalStateException:
javax.management.InstanceAlreadyExistsException: jboss.deployment:id="jboss.web.deployment:war=/my_application", type=Component already registered.
Caused by: java.lang.IllegalStateException: jboss.web.deployment:war=/my_application is already installed.
The reason was that I accidentally kept two .ear files in the /deploy folder of my JBOSS server - both the previous and the current .ear of my application.
As it was stated here: https://www.theserverside.com/discussions/thread/22674.html
I'm not sure there is a way to deploy two ear files with the same
classes inside and not have problems.
Since the two .ears had classes in common, that lead to InstanceAlreadyExistsException.
What has worked for me is:
Delete the war file from /webapps
Copy war file from /target and paste into /webapps
Hope it will work for you too.
It's because you also declare another bean with the same id as 'healthCheckStrategy' in another spring application. You probably put these two spring applications in the same server.
Solution 1:
change the bean id either in this spring application or the other one will solve your problem.
Solution 2:
add EnableMBeanExport annotation and set different defaultDomain for each spring application
#Configuration
#EnableMBeanExport(defaultDomain="first")
public class BeanGenerator {...}
#Configuration
#EnableMBeanExport(defaultDomain="second")
public class BeanGenerator {...}
I'm trying to send emails using an organisation mailSender.
Controller
#RequestMapping(value="/forgetPassword", method = RequestMethod.POST, consumes={"application/json"})
public #ResponseBody User forgetPassword(#RequestBody User user) throws Exception {
user=userService.forgetPassword(user, newPassword);
if(user !=null)
{
SendEmail callsendEmail = new SendEmail();
callsendEmail.emailSender(user);
return user;
}
else
{
return user;
}
}
SendEmail
public class SendEmail {
private JavaMailSender mailSender;
private VelocityEngine velocityEngine;
private SimpleMailMessage templateMessage;
public void emailSender(final User user) throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
message.setFrom(templateMessage.getFrom());
message.setTo(user.getEmail());
message.setSubject(templateMessage.getSubject());
Map<String, User> model = new HashMap<String, User>();
model.put("user", user);
/*String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "org/utility/mailTemplate.vm", model);
message.setText(text, true);*/
if (mailSender != null) {
mailSender.send(mimeMessage);
}
}
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
public JavaMailSender getMailSender() {
return mailSender;
}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public SimpleMailMessage getTemplateMessage() {
return templateMessage;
}
public void setTemplateMessage(SimpleMailMessage templateMessage) {
this.templateMessage = templateMessage;
}
}
Configuration
<bean id="emailSender" class="org.utility.SendEmail">
<property name="mailSender" ref="mailSender" />
<property name="velocityEngine" ref="velocityEngine" />
<property name="templateMessage" ref="templateMessage" />
</bean>
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="10.6.12.229" />
<property name="port" value="25" />
</bean>
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<value>resource.loader=class class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader</value>
</property>
</bean>
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="noreply#scrumtracker.com" />
<property name="subject" value="Scrum Tracker Login Details" />
</bean>
Here's the stack trace:
SEVERE: Servlet.service() for servlet [spring] in context with path [/OLPV] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at org.utility.SendEmail.emailSender(SendEmail.java:24)
at org.controller.UserController.forgetPassword(UserController.java:125)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.multipart.support.MultipartFilter.doFilterInternal(MultipartFilter.java:119)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:242)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:243)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:201)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:163)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:556)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:401)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:242)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:267)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:245)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:260)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I'm getting nullpointer exception on running the above code. Data is passing to the SendEmail class from Controller. Any idea on this?
Set #autowired from calling class (Don't do New) to the mailSend class.
Write #Service in mailSend class.
Directly call the mailSend.Send() method from the calling class.
All prop will be set automatically. No null point exception.
Namaste !
In your Controller class you don't need to instantiante the SendEmail like you do
SendEmail callsendEmail = new SendEmail();
But instead inject it as a spring bean
#Controller
class MyController {
#Autowired
private SendEmail callsendEmail;
#RequestMapping(value="/forgetPassword", method = RequestMethod.POST, consumes={"application/json"})
public #ResponseBody User forgetPassword(#RequestBody User user) throws Exception {
user=userService.forgetPassword(user, newPassword);
if(user !=null)
{
callsendEmail.emailSender(user);
return user;
}
else
{
return user;
}
}
}
If your application context is not configured to autowire beans by annotations, then use a regular setter in the class
#Required
public void setSendEmail( SendEmail sendEmail ) {
this.callsendEmail = sendEmail;
}
I am using Spring batch application and want to use late binding for stepExecutionContext. I am facing issues in resolving my error.
Following is my reader which has sql property using late binding:
<bean id="itemReader_S4_JPolicy" class="com.aegonusa.etl.readers.JDBCItemReader" scope="step">
<property name="jobParameters" ref="jobParameters" />
<property name="dataSource" ref="readDataSource" />
<property name="rowMapper">
<bean class="com.aegonusa.etl.readers.ResultSetRowMapper" scope="step" />
</property>
<property name="sql"
value="#{stepExecutionContext['readQuery']}"></property>
</bean>
I set this property ('readQuery') in following class:
public class StepListener implements StepExecutionListener
{
....
....
#Override
public void beforeStep(StepExecution execution) {
String s = "select getdate();
StepSynchronizationManager.getContext().setAttribute("readQuery", s);
.....
}
.....
}
Please note that I am able to do late binding using jobParameters.
But using stepExecutionContext, I get following exc. I tried lot of posts in forums but am unable to resolve it:
Throwable occurred: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'lazyBindingProxy.itemReader_S4_JPolicy#sysinit' defined in class path resource [Load_InforceToStage.xml]: Initialization of bean failed; nested exception is java.lang.IllegalStateException: Cannot bind to placeholder: stepExecutionContext['readQuery']
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(AccessController.java:224)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:302)
at org.springframework.batch.core.scope.StepScope.get(StepScope.java:150)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.batch.core.scope.util.PlaceholderTargetSource.getTarget(PlaceholderTargetSource.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:184)
at $Proxy1.close(Unknown Source)
at org.springframework.batch.item.support.CompositeItemStream.close(CompositeItemStream.java:83)
at org.springframework.batch.core.step.item.ChunkMonitor.close(ChunkMonitor.java:99)
at org.springframework.batch.item.support.CompositeItemStream.close(CompositeItemStream.java:83)
at org.springframework.batch.core.step.tasklet.TaskletStep.close(TaskletStep.java:297)
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:255)
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:135)
at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:61)
at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:60)
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:144)
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:124)
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:135)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:281)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:120)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:49)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:114)
at org.springframework.batch.core.launch.support.CommandLineJobRunner.start(CommandLineJobRunner.java:349)
at org.springframework.batch.core.launch.support.CommandLineJobRunner.main(CommandLineJobRunner.java:574)
at com.ebsadm.lh.LHSHEDToStage.runJob(LHSHEDToStage.java:124)
at com.ebsadm.lh.LHSHEDToStage.main(LHSHEDToStage.java:111)
at com.ebdadm.lh.TestLHSHEDToStage.testInforceLoadToStage(TestLHSHEDToStage.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:600)
at junit.framework.TestCase.runTest(TestCase.java:168)
at junit.framework.TestCase.runBare(TestCase.java:134)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:232)
at junit.framework.TestSuite.run(TestSuite.java:227)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:79)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.IllegalStateException: Cannot bind to placeholder: stepExecutionContext['readQuery']
at org.springframework.batch.core.scope.util.PlaceholderTargetSource$1.convertIfNecessary(PlaceholderTargetSource.java:140)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1294)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1250)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
... 50 more
Kindly help.
I would expect a call to getExecutionContext on the StepExecution to give you the proper context.
#Override
public void beforeStep(StepExecution execution) {
String s = "select getdate()";
execution.getExecutionContext().putString("readQuery", s);
}
Your current solution is getting the StepContext. The StepContext is the object that is exposed and used for expression parsing, whereas the ExecutionContext associated with the StepExecution is the actual stepExecutionContext. ItemReaders and ItemWriters and such object also use the ExecutionContext to update the state (skipped items, commit count etc.).
Try any of the below :
Use promotionListener bean to promote the scope of variable from step to job.
Use bean instead of executionContext.
I coded service to send email. Now I have to integrate velocity freamwork and so I edit my mail-context.xml
....
<bean id="mailService" class="xxx.xxxx.xxxx.service.MailServiceImpl">
<property name="mailSender" ref="mailSender" />
<property name="simpleMailMessage" ref="customeMailMessage" />
<property name="velocityEngine" ref="velocityEngine" />
</bean>
<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<props>
<prop key="resource.loader">webapp</prop>
<prop key="webapp.resource.loader.class">org.apache.velocity.tools.view.WebappResourceLoader</prop>
<prop key="webapp.resource.loader.path">/WEB-INF/email</prop>
</props>
</property>
</bean>
...
And I put in /WEB-INF/email my template file .vm
This is my mail service
#Service("MailService")
#Transactional
public class MailServiceImpl implements MailService {
private JavaMailSender mailSender;
private VelocityEngine velocityEngine;
private SimpleMailMessage simpleMailMessage;
public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
this.simpleMailMessage = simpleMailMessage;
}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
.....
public void sendEmailVelocity(final Userprofile userprofile) throws MessagingException, IOException {
System.out.println("Sending mail...");
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
Map model = new HashMap();
model.put("user", userprofile);
helper.setFrom("info#spidly.com");
helper.setTo("claudio.pomo#gmail.com");
helper.setSubject("velocity");
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "test.vm", model);
helper.setText(text, true);
mailSender.send(message);
System.out.println("Mail sent!");
}
...
And then the stack trace is
org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'test.vm'
at org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:474)
at org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:352)
at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1533)
at org.apache.velocity.app.VelocityEngine.mergeTemplate(VelocityEngine.java:343)
at org.apache.velocity.app.VelocityEngine.mergeTemplate(VelocityEngine.java:320)
at org.springframework.ui.velocity.VelocityEngineUtils.mergeTemplate(VelocityEngineUtils.java:58)
at org.springframework.ui.velocity.VelocityEngineUtils.mergeTemplateIntoString(VelocityEngineUtils.java:122)
at xx.xxxxxxx.xxx.service.MailServiceImpl.sendEmailVelocity(MailServiceImpl.java:410)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:319)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy61.sendEmailVelocity(Unknown Source)org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'test.vm'
at org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:474)
at org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:352)
at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1533)
at org.apache.velocity.app.VelocityEngine.mergeTemplate(VelocityEngine.java:343)
at org.apache.velocity.app.VelocityEngine.mergeTemplate(VelocityEngine.java:320)
at org.springframework.ui.velocity.VelocityEngineUtils.mergeTemplate(VelocityEngineUtils.java:58)
at org.springframework.ui.velocity.VelocityEngineUtils.mergeTemplateIntoString(VelocityEngineUtils.java:122)
at xx.xxxxx.xxxx.service.MailServiceImpl.sendEmailVelocity(MailServiceImpl.java:410)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:319)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy61.sendEmailVelocity(Unknown Source)
Any suggestion?
Change your velocityEngine bean to
<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="/WEB-INF/email/" />
</bean>
and it should work.