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;
}
Related
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>
The first request made to the messageSender via a webservicetemplate using credential is failing with 401 unauthorized, but second time it is all okay and works well.
Configuration:
<property name="messageSender">
<bean class="org.springframework.ws.transport.http.HttpComponentsMessageSender">
<property name="connectionTimeout" value="900000" />
<property name="readTimeout" value="0" />
<property name="credentials">
<bean class="org.apache.http.auth.UsernamePasswordCredentials">
<constructor-arg value="${userName}:${Password}" />
</bean>
</property>
From so far, what i have googled through I get to know that I will have to do a preemptive authentication to avoid 401 unauthorized using [org.apache.http.client.HttpClient]. I want a spring xml configuration to allow this so that I can configure preemptive authentication.
Also, is the behaviour as expected.
What I have tried so far.
class="org.springframework.ws.transport.http.HttpComponentsMessageSender">
<property name="connectionTimeout" value="900000" />
<property name="readTimeout" value="0" />
<property name="httpClient" ref="httpClient" />
<property name="credentials" ref="credentials"/>
</bean>
</property>
<bean id="httpClient" class="org.apache.http.client.HttpClient">
<!-- Not Sure what configuration to add here -->
</bean>
<bean id="credentials" class="org.apache.http.auth.UsernamePasswordCredentials">
<constructor-arg value="${userName}:${password}" />
</bean>
Creating the http client with a credentials provider, which need UsernamePasswordCredentials and AuthScope. AuthScope is created with default values and UsernamePasswordCredentials is created with username, password. BasicCredentialsProvider does not take provider and credentials in constructor or setter method. It has to set by invoking setCredentials() method.
<bean class="org.springframework.ws.transport.http.HttpComponentsMessageSender">
<property name="connectionTimeout" value="900000"/>
<property name="readTimeout" value="0"/>
<property name="httpClient" ref="httpClient"/>
</bean>
<bean id="credentialProvider" class="org.apache.http.impl.client.BasicCredentialsProvider" />
<bean id="methodInvoke" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject"><ref local="credentialProvider" /> </property>
<property name="targetMethod" value="setCredentials"> </property>
<property name="arguments" >
<list>
<ref local="authScope" />
<ref local="credentials" />
</list>
</property>
</bean>
<bean id="authScope" class="org.apache.http.auth.AuthScope">
<constructor-arg name="host"><null /></constructor-arg>
<constructor-arg><value>-1</value> </constructor-arg>
<constructor-arg><null /></constructor-arg>
<constructor-arg><null /></constructor-arg>
</bean>
<bean id="credentials" class="org.apache.http.auth.UsernamePasswordCredentials">
<constructor-arg name="userName"><value>xxx</value></constructor-arg>
<constructor-arg name="password"><value>xxx</value></constructor-arg>
</bean>
<bean id="httpClient" class="org.apache.http.impl.client.DefaultHttpClient">
<property name="credentialsProvider" ref="credentialProvider"/>
</bean>
The configuration which I had to add to the Webservicetemplate are shown below:
<!-- Custom Interceptor Implementation to WebServiceTemplate -->
<property name="interceptors">
<list>
<bean class="com.utils.AddHttpHeaderInterceptor" >
</bean>
</list>
</property>
And implement the AddHttpHeaderInterceptor class which implements ClientInterceptor as below:
HttpPost postMethod = connection.getHttpPost();
postMethod.addHeader("Authorization", "Basic " + base64Creds);
return true;
And note: base64Creds is nothing but base64.encode(username:pwd)
I want return json and html from spring mvc
the spring config:(when controller is not redirect it is OK!)
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="ignoreAcceptHeader" value="true" />
<property name="defaultContentType" value="text/html" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
<property name="favorParameter" value="false" />
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp">
</property>
</bean>
</list>
</property>
<!-- ............... -->
then controller :
#RequestMapping(value="test")
public ModelAndView test(HttpServletRequest request,HttpServletResponse response){
Result result = new Result(/*.......*/);
//return
{
//====>it is OK,when i call http://localhsot/test.json
ModelAndView mv = new ModelAndView("user/test","result",result);
return mv; //
}
{
//=====> it is also redirect,when i call http://localhsot/test.json (response statues 302!)
ModelAndView mv = new ModelAndView("redirect:user/test""result",result);
return mv;
}
}
How can i get json data when ModelAndView'view is redriect in my controller?
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");
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.