Null pointer exception when querying database from a Quartz job - java

My scheduler is triggering but I am not able to connect to the database. When I tried to query the database using a test case it worked so I tried to implement it using Quartz, but it's giving a NullPointerException.
public class JobScheduler extends QuartzJobBean {
#Autowired
ISourceService sourcedao;
#Override
protected void executeInternal(JobExecutionContext arg0)
throws JobExecutionException {
Client client = new Client();
client.setClientKey(300);
Source sourceobj = sourcedao.getSourceByClient(client);
String sourcetype = sourceobj.getSourceType();
System.out.println(sourcetype);
}
}
my application context.xml
<bean id="jobScheduler" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.dca.scheduling.JobScheduler" />
<property name="jobDataAsMap">
<map>
<entry key="timeout" value="5" />
</map>
</property>
</bean>
<bean id="cronTriggerjobScheduler" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="jobScheduler" />
<property name="cronExpression" value="0/15 0 * * * ?" />
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobDetails">
<list>
<ref bean="jobScheduler" />
</list>
</property>
<property name="triggers">
<list>
<ref bean="cronTriggerjobScheduler" />
</list>
</property>
</bean>
<bean id="jobClass"
class="com.dca.scheduling.JobScheduler">
</bean>
I checked many examples but didn't get any ideas.

The JobScheduler needs to be a Spring bean, too. You don't show how you annotate it. I would make it a Component and see if you fare better.

in the application context i have added a map
<bean id="jobScheduler" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.dca.scheduling.JobScheduler" />
<property name="jobDataAsMap">
<map>
<entry key ="DATA_MANAGER_MAP_KEY" value-ref="sourceDao"/>**i have added the bean id here**
<entry key="timeout" value="5" />
</map>
</property>
</bean>
and in the Jobscheduler class
sourceDao= (SourceDaoImpl)jobContext.getJobDetail().getJobDataMap().get("DATA_MANAGER_MAP_KEY");

Related

Send order Confirmation Email- Broadleaf

I went through the documentation of Broadleaf to send Email confirmation
Below is my applicationcontext-email.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<!-- A dummy mail sender has been set to send emails for testing purposes
only To view the emails sent use "DevNull SMTP" (download separately) with
the following setting: Port: 30000 -->
<!-- Broadleaf step 3 -->
<bean id="blServerInfo"
class="org.broadleafcommerce.common.email.service.info.ServerInfo">
<property name="serverName" value="smtp.office365.com" />
<property name="serverPort" value="587" />
</bean>
<bean id="blEmailTemplateResolver"
class="org.thymeleaf.templateresolver.ClassLoaderTemplateResolver">
<property name="prefix" value="emailTemplates/" />
<property name="suffix" value=".html" />
<property name="cacheable" value="${cache.page.templates}" />
<property name="cacheTTLMs" value="${cache.page.templates.ttl}" />
</bean>
<bean id="blEmailTemplateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolvers">
<set>
<ref bean="blEmailTemplateResolver" />
</set>
</property>
<property name="dialects">
<set>
<bean class="org.thymeleaf.spring4.dialect.SpringStandardDialect" />
<ref bean="blDialect" />
</set>
</property>
</bean>
<!-- Broadleaf email step 1 -->
<bean id="blMessageCreator"
class="org.broadleafcommerce.common.email.service.message.ThymeleafMessageCreator">
<constructor-arg ref="blEmailTemplateEngine" />
<constructor-arg ref="blMailSender" />
</bean>
<bean id="blEmailInfo"
class="org.broadleafcommerce.common.email.service.info.EmailInfo">
<property name="fromAddress">
<value>mulaygaurav3#gmail.com</value>
</property>
<property name="sendAsyncPriority">
<value>2</value>
</property>
<property name="sendEmailReliableAsync">
<value>false</value>
</property>
</bean>
<bean id="blMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
<value>localhost</value>
</property>
<property name="port">
<value>30000</value>
</property>
<property name="protocol">
<value>smtp</value>
</property>
<property name="username">
<value>gaurav</value>
</property>
<property name="password">
<value>mypassword</value>
</property>
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.smtp.timeout">25000</prop>
</props>
</property>
</bean>
<bean id="blVelocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="/WEB-INF/emailTemplates/" />
<property name="velocityProperties">
<value>
resource.loader=file,class
class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
runtime.references.strict = false
</value>
</property>
</bean>
<bean id="blMessageCreator"
class="org.broadleafcommerce.common.email.service.message.VelocityMessageCreator">
<constructor-arg ref="blVelocityEngine" />
<constructor-arg ref="blMailSender" />
<constructor-arg>
<map>
<entry key="number">
<bean class="org.apache.velocity.tools.generic.NumberTool"
scope="prototype" />
</entry>
<entry key="date">
<bean class="org.apache.velocity.tools.generic.ComparisonDateTool"
scope="prototype" />
</entry>
<entry key="list">
<bean class="org.apache.velocity.tools.generic.ListTool"
scope="prototype" />
</entry>
<entry key="math">
<bean class="org.apache.velocity.tools.generic.MathTool"
scope="prototype" />
</entry>
<entry key="iterator">
<bean class="org.apache.velocity.tools.generic.IteratorTool"
scope="prototype" />
</entry>
<entry key="alternator">
<bean class="org.apache.velocity.tools.generic.AlternatorTool"
scope="prototype" />
</entry>
<entry key="sorter">
<bean class="org.apache.velocity.tools.generic.SortTool"
scope="prototype" />
</entry>
<entry key="esc">
<bean class="org.apache.velocity.tools.generic.EscapeTool"
scope="prototype" />
</entry>
<entry key="serverInfo" value-ref="blServerInfo" />
</map>
</constructor-arg>
</bean>
<!-- <bean id="blMessageCreator" class="org.broadleafcommerce.common.email.service.message.NullMessageCreator">
<constructor-arg ref="blMailSender"/> </bean> -->
<bean id="blRegistrationEmailInfo" parent="blEmailInfo">
<property name="subject" value="You have successfully registered!" />
<property name="emailTemplate" value="register-email" />
</bean>
<bean id="blForgotPasswordEmailInfo" parent="blEmailInfo">
<property name="subject" value="Reset password request" />
<property name="emailTemplate" value="resetPassword-email" />
</bean>
<!-- Broadleaf email step 2 -->
<bean id="orderConfirmationEmailInfo" class="org.broadleafcommerce.common.email.service.info.EmailInfo" parent="blEmailInfo" scope="prototype">
<property name="messageBody" value="This is a test email!"/>
<property name="emailType" value="ORDERCONFIRMATION"/>
<property name="subject" value="Thank You For Your Order!"/>
</bean>
</beans>
I have also created an activity as mentioned in the documentation:
package com.mycompany.worklow.emailactivity;
import javax.annotation.Resource;
import org.broadleafcommerce.core.checkout.service.workflow.CheckoutSeed;
import org.broadleafcommerce.core.checkout.service.workflow.CompleteOrderActivity;
import org.broadleafcommerce.core.order.domain.Order;
import org.broadleafcommerce.core.workflow.ProcessContext;
import com.mycompany.service.MyEmailWebService;
enter code here
public class MyCompleteOrderActivity extends CompleteOrderActivity {
#Resource(name="myEmailService")
protected MyEmailWebService myEmailService;
#Override
public ProcessContext execute(ProcessContext context) throws Exception {
CheckoutSeed seed = (CheckoutSeed) context.getSeedData();
Order order = seed.getOrder();
myEmailService.sendOrderConfirmation(order.getSubmitDate(), order.getId().toString(), order.getCustomer().getEmailAddress());
return super.execute(context);
}
}
}
Also added this activity in the applicationcontext-workflow.xml
I am getting this below exxception:
Unable to merge source and patch locations; nested exception is org.broadleafcommerce.common.extensibility.context.merge.exceptions.MergeException: java.lang.NullPointerException
Can anybody explain the step by step procedure to implement the same?
Thanks in advance
You have to beans named blMessageCreator, remove one of them. Assuming you are using version 5 demo site, which uses thymeleaf templates then try removing:
<bean id="blMessageCreator" class="org.broadleafcommerce.common.email.service.message.VelocityMessageCreator">
...
...
</bean>

spring batch: job status completed but no data committed when using SyncTaskExecutor

Here is my job structure.
<bean id="ControlJob" class="com.example.batch.ControlJob">
<property name="jobRepository" ref="jobRepository" />
<property name="name" value="Outter job" />
<property name="moduleId" value="d" />
<property name="jobList">
<list>
<ref bean="a" />
<ref bean="b" />
<ref bean="c" />
<ref bean="d" />
<ref bean="e" />
<ref bean="f" />
<ref bean="g" />
<ref bean="h" />
</list>
</property>
<property name="jobLauncher" ref="jobLauncher" />
</bean>
<bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="taskExecutor" ref="syncTaskExecutor" />
<property name="jobRepository" ref="jobRepository" />
</bean>
<bean id="syncTaskExecutor" class="org.springframework.core.task.SyncTaskExecutor" />
This is my entrance:
public class SimpleJobLauncher {
public static void main(String[] args) {
String[] path = {"classpath:com/context.xml"};
AbstractApplicationContext context = new FileSystemXmlApplicationContext(path);
context.registerShutdownHook();
IBatchJobControllerBO batch = (IBatchJobControllerBO) context.getBean("batchJobControllerBO");
//IBatchJobControllerBO batch = (IBatchJobControllerBO) context.getBean("synchronizedBatchJobControllerBO");
try {
BatchJobExecution execution = batch.startBatchJob("Outter job");
//BatchJobExecution execution = batch.startBatchJob("Outter job");
String message = execution.getExitMessage();
System.out.println("job completed: " + message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Two different bo to run the Outter job:
<bean id="batchJobControllerBO"
class="com.bo.impl.BatchJobControllerBOImpl">
<property name="jobLauncher" ref="jobLauncher" />
<property name="jobRegistry" ref="jobConfigurationRegistry" />
<property name="batchJobDAO" ref="batchJobDAO" />
<property name="batchJobExecutionDAO" ref="batchJobExecutionDAO" />
</bean>
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
<property name="taskExecutor">
<bean class="org.springframework.core.task.SimpleAsyncTaskExecutor" />
</property>
</bean>
<bean id="synchronizedBatchJobControllerBO" parent="batchJobControllerBO"
class="com.bo.impl.BatchJobControllerBOImpl">
<property name="jobLauncher" ref="synchronizeJobLauncher" />
</bean>
<bean id="synchronizeJobLauncher" parent="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="taskExecutor">
<bean class="org.springframework.core.task.SyncTaskExecutor" />
</property>
</bean>
Each job a ~ h is working perfectly and for the Outter Job if i use jobLauncher : "SimpleAsyncTaskExecutor" to call the Outter Job, it will work fine.
But when I use jobLauncher : "SyncTaskExecutor" to call the Outter Job, some of the job (the error is not stable) didn't commit any data to DB (the table is empty).
The job status is completed without any error.
Can anyone tell me what's wrong in this scenario?

Spring MVC 4 is not generating json root object by default

I have a a controller class that was previously written using spring mvc 3 but for some reasons we decided to update the spring version to the 4.1.4.
After this change this controller stop working as it worked before...
In the previous version this below code returned like this: departmentList: {....} with this departmentList in the beginning but right now it is returning just as a simple array: [{...},{...}]
new ModelAndView().addObject(departmentList);
My configuration is on xml.
<bean id="cnManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="true"/>
<property name="ignoreAcceptHeader" value="true" />
<property name="defaultContentType" value="application/json" />
<property name="useJaf" value="true"/>
<property name="mediaTypes">
<map>
<entry key="html" value="text/html" />
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
</bean>
<bean id="jacksonObjectMapper" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"
p:targetMethod="disable">
<property name="targetObject">
<bean class="com.fasterxml.jackson.databind.ObjectMapper"/>
</property>
<property name="arguments">
<list>
<util:constant static-field="com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES"/>
</list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"
p:supportedMediaTypes="application/json"
p:objectMapper-ref="jacksonObjectMapper"/>
<bean id="mappingJacksonJsonView" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"
p:extractValueFromSingleKeyModel="true"
p:objectMapper-ref="jacksonObjectMapper"/>
<!--
View resolver that delegates to other view resolvers based on the content type
-->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<!-- All configuration is now done by the manager - since Spring V3.2 -->
<property name="contentNegotiationManager" ref="cnManager"/>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" p:extractValueFromSingleKeyModel="true"
p:objectMapper-ref="jacksonObjectMapper"/>
</list>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
</bean>
I resolved the problem.
I needed to changed my defaultViews to be like this:
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
</list>
</property>
Now it works as expected with no code change.
I have this problem. This code help me to generate pure json array.
#RequestMapping(path = "/getAll/{isDeletedShow}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ModelAndView getAllEntity(#PathVariable boolean isDeletedShow) {
try {
MappingJackson2JsonView mapping = new MappingJackson2JsonView();
Gson gson = new Gson();
List<EntityBank> b = service.findAll(isDeletedShow);
mapping.setEncoding(JsonEncoding.UTF8);
mapping.setPrettyPrint(true);
mapping.setPrefixJson(false);
mapping.setExtractValueFromSingleKeyModel(true);
ModelAndView modelAndView = new ModelAndView();
modelAndView.getModelMap().addAttribute("BanksList", b);
modelAndView.setView(mapping);
return modelAndView;
} catch (Exception e) {
e.printStackTrace();
LOGGER.error(ExceptionUtils.getStackTrace(e));
}
return null;
}

Validate format parameter via config in Spring MVC

Here is my situation:
I have my mvc-config.xml file for my web service set up to have JSON as the default media type. I also have favorParameter for the ContentNegotiatingViewResolver as true. Additionally, I have useNotAcceptableStatusCode as true so that not accepted formats will return a 406.
My question is: Is there a way, in the config, to trigger the 406 status code when someone passes in an unacceptable format parameter (format=foo)? Or must that be done with code?
Here is the config file:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
<property name="defaultViews">
<list>
<bean class="com.work.stuff.web.view.json.ExtendedMappingJacksonJsonView">
<property name="objectMapper">
<ref bean="JacksonObjectMapper" />
</property>
</bean>
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<property name="marshaller">
<ref bean="Jaxb2Marshaller" />
</property>
</bean>
</list>
</property>
<property name="defaultContentType" value="application/json" />
<property name="favorParameter" value="true" />
<property name="useNotAcceptableStatusCode" value="true" />
</bean>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper">
<ref bean="JacksonObjectMapper" />
</property>
</bean>
<ref bean="marshallingHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="marshallingHttpMessageConverter"
class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="Jaxb2Marshaller" />
<property name="unmarshaller" ref="Jaxb2Marshaller" />
</bean>
<bean id="JacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="JacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
factory-bean="JacksonObjectMapper" factory-method="getSerializationConfig" />
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="JacksonSerializationConfig" />
<property name="targetMethod" value="setSerializationInclusion" />
<property name="arguments">
<list>
<value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_NULL</value>
</list>
</property>
</bean>
<bean id="Jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.work.stuff.Concepts</value>
<value>com.work.stuff.Concept</value>
<value>com.work.stuff.Terms</value>
<value>com.work.stuff.Term</value>
<value>com.work.stuff.Namespaces</value>
<value>com.work.stuff.Namespace</value>
<value>com.work.stuff.Subsets</value>
<value>com.work.stuff.Subset</value>
<value>com.work.stuff.Associations</value>
<value>com.work.stuff.Association</value>
</list>
</property>
</bean>
</beans>
ContentNegotiatingViewResolver doesn't seem to support such behaviour. For now, I think your best bet is to subclass it and override the getMediaTypeFromParameter() method to throw an exception if the media type is not supported.
You can throw any RuntimeException from that method, and if you annotate the exception class with #ResponseStatus, you can control the HTTP response code, e.g.
#ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
public class FormatNotSupportedException extends RuntimeException {
}
In the longer term, I strongly encourage you to file an issue with http://jira.springsource.org, asking for such functionality to be added to ContentNegotiatingViewResolver. They should be able to add this as an optional behavioural parameter. It's requests like these that mean Spring keeps getting better.

method-invoking Spring bean

I've declared the following bean in my Spring config
<bean id="templateCacheClearingTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="delay" value="5000" />
<property name="period" value="5000" />
<property name="timerTask">
<bean class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean">
<property name="targetObject" ref="templateMailService" />
<property name="targetMethod" value="clearCache" />
</bean>
</property>
</bean>
This should cause the clearCache() method of the templateMailService bean to be invoked every 5000ms, but nothing appears to be happening. Am I missing something?
Cheers,
Don
I think you need:
<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="templateCacheClearingTask"/>
</list>
</property>
</bean>
In addition to what you already have.

Categories