I am new to web services. After much googling and trying everything that's been posted about accessing the SoapHeader from endpoints, I still cannot get it to work. I'm getting the following error:
java.lang.IllegalStateException: No adapter for endpoint when adding
SoapHeader in the method signature of the handling method.
If I remove the SoapHeader parameter, I do not have any issues.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:sws="http://www.springframework.org/schema/web-services"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/web-services
http://www.springframework.org/schema/web-services/web-services-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="services" />
<sws:annotation-driven />
<sws:interceptors>
<bean id="validatingInterceptor"
class="org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor">
<property name="schema" value="/WEB-INF/schemas/cfPostBack2015.xsd" />
<property name="validateRequest" value="true"/>
<property name="validateResponse" value="true"/>
</bean>
<bean id="loggingInterceptor"
class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor" />
</sws:interceptors>
<sws:static-wsdl id="postBackService2015"
location="/WEB-INF/schemas/postBackService2015.wsdl" />
<bean id="marshaller" class="org.springframework.oxm.xmlbeans.XmlBeansMarshaller" />
<bean id="marshallingPayloadMethodProcessor"
class="org.springframework.ws.server.endpoint.adapter.method.MarshallingPayloadMethodProcessor">
<constructor-arg ref="marshaller"/>
<constructor-arg ref="marshaller"/>
</bean>
<bean id="defaultMethodEndpointAdapter"
class="org.springframework.ws.server.endpoint.adapter.DefaultMethodEndpointAdapter">
<property name="methodArgumentResolvers">
<list>
<ref bean="marshallingPayloadMethodProcessor" />
</list>
</property>
<property name="methodReturnValueHandlers">
<list>
<ref bean="marshallingPayloadMethodProcessor" />
</list>
</property>
</bean>
<bean id="postbackService"
class="PostBackServiceImpl" />
<bean id="postBackEndpoint"
class="PostBackEndpoint">
<property name="postBackService" ref="postBackService" />
</bean>
</beans>
Endpoint class:
package endpoints;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import org.springframework.ws.soap.SoapHeader;
import PostBackService;
import cfPostBack.x2015.PostBackRequestDocument;
import cfPostBack.x2015.PostBackResponseDocument;
#Endpoint
public class PostBackServiceEndpoint {
private static final String TARGET_NAMESPACE =
"http://services/cfPostBack/2015/";
#Resource(name="postBackService")
private PostBackService postBackService;
#Autowired
public PostBackServiceEndpoint(PostBackService postBackService) {
this.postBackService = postBackService;
}
#PayloadRoot(localPart = "postBackRequest", namespace = TARGET_NAMESPACE)
#ResponsePayload
public PostBackResponseDocument getPostBackResponse(
#RequestPayload PostBackRequestDocument request, SoapHeader soapHeader)
throws Exception {
PostBackResponseDocument response =
postBackService.processPostBackRequest(request);
return response;
}
public void setPostBackService(PostBackService postBackService) {
this.postBackService = postBackService;
}
}
You probably need to add a org.springframework.ws.soap.server.endpoint.adapter.method.SoapMethodArgumentResolver bean to the methodArgumentResolvers list.
Actually, Andreas, you are right. Adding SoapMethodArgumentResolver bean to the methodArgumentResolvers list does work. I was trying to access the MessageContext in the endpoint instead of the SoapHeader. For the MessageContext, I added MessageContextMethodArgumentResolver.
Related
I have a small project that I’m using to learn Spring Batch. I want to read data from Oracle Database and write to an XML file, but I got an error:
Error creating bean with name 'step1': Cannot resolve reference to bean 'jobRepository' while setting bean property 'jobRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository' defined in class path resource [Spring/batch/config/spring-batch-contextOriginal.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'dataSource' of bean class [org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean]: Bean property 'dataSource' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
I think I put everything but I think the most important things for this error are: spring-batch-context.xml and spring-datasource.xml. Am I missing something or is something wrong? Let me know if you need more details. Thank you. (I tried the example without using database and it has worked good.)
spring-batch-context.xml:
<?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-3.2.xsd">
<import resource="../jobs/jobPerson.xml"/>
<import resource="../config/spring-datasource.xml" />
<!-- <context:annotation-config />
<tx:annotation-driven transaction-manager="transactionManager"/>a PlatformTransactionManager is still required
-->
<!-- JobRepository and JobLauncher are configuration/setup classes -->
<bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean" >
<property name="dataSource" ref="dataSource" />
<property name="transactionManager" ref="transactionManager" />
<property name="databaseType" value="oracle" />
</bean>
<bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>
<!-- Optional ItemProcessor to perform business logic/filtering on the input records -->
<bean id="itemProcessor" class="springBatch.ExamResultItemProcessor" />
<!-- Optional JobExecutionListener to perform business logic before and after the job -->
<bean id="jobListener" class="springBatch.ExamResultJobListener" />
<!-- Step will need a transaction manager -->
<bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />
</beans>
spring-datasource.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
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-3.2.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd">
<!-- Info to connect To Database -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#*********:1552/******" />
<property name="username" value="*******" />
<property name="password" value="*******" />
</bean>
<bean id="transactionManager"
class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />
<!-- create job-meta tables automatically -->
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="org/springframework/batch/core/schema-drop-oracle10g.sql" />
<jdbc:script location="org/springframework/batch/core/schema-oracle10g.sql" />
</jdbc:initialize-database>
</beans>
jobPerson.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc">
<!-- <import resource="../config/spring-batch-contextOriginal.xml"/>
-->
<bean id="itemReader" class="org.springframework.batch.item.database.JdbcCursorItemReader" scope="step">
<property name="dataSource" ref="dataSource"/>
<property name="sql" value="SELECT internal_Id,individual_Id FROM Person" />
<property name="rowMapper">
<bean class="sb.dbToXml.PersonRowMapper"></bean>
</property>
</bean>
<bean id="itemWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
<property name="resource" value="file:xml/persons.xml"/>
<property name="marshaller" ref="personMarshaller"/>
<property name="rootTagName" value="persons"/>
</bean>
<bean id="personMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<value>sb.dbToxml.Person </value>
</property>
</bean>
<batch:job id="personJob">
<batch:step id="step1" >
<batch:tasklet transaction-manager="transactionManager">
<batch:chunk reader="itemReader" writer="itemWriter" commit-interval="10" />
</batch:tasklet>
</batch:step>
<batch:listeners>
<batch:listener ref="jobListener" />
</batch:listeners>
</batch:job>
</beans>
Main class:
package sb.dbToxml;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionException;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainDbToXml
{
public static void main(String[] args)
{
ApplicationContext context=new ClassPathXmlApplicationContext("Spring/batch/config/spring-batch-context.xml");
JobLauncher jobLauncher= (JobLauncher) context.getBean("jobLauncher");
Job job=(Job) context.getBean("personJob");
try
{
JobExecution execution=jobLauncher.run(job, new JobParameters());
System.out.println("Main/try :Job Person Exit Status "+execution.getStatus());
}
catch (JobExecutionException e)
{
System.out.println("Main /catch :Job Person failed");
e.printStackTrace();
}
}
}
Person class:
package sb.dbToxml;
import javax.xml.bind.annotation.XmlAccessOrder;
import javax.xml.bind.annotation.XmlAccessorOrder;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="Person")
//#XmlAccessorOrder(XmlAccessOrder.UNDEFINED)
public class Person
{
Long internal_id;
Long Individual_id;
#XmlElement(name="int_id")
public Long getInternal_id()
{
return internal_id;
}
public void setInternal_id(Long internal_id)
{
this.internal_id = internal_id;
}
#XmlElement(name="indv_id")
public Long getIndividual_id()
{
return Individual_id;
}
public void setIndividual_id(Long individual_id)
{
Individual_id = individual_id;
}
}
PersonRawMapper:
package sb.dbToxml;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class PersonRowMapper implements RowMapper <Person>
{
#Override
public Person mapRow(ResultSet rs, int rowNum) throws SQLException
{
Person person=new Person();
person.setIndividual_id(rs.getLong("individual_id"));
person.setInternal_id(rs.getLong("internal_id"));
return person;
}
}
The MapJobRepositoryFactoryBean does not have the properties dataSource, transactionManager and databaseType. You should use the JobRepositoryFactoryBean instead of the MapJobRepositoryFactoryBean:
So replace this:
<!-- JobRepository and JobLauncher are configuration/setup classes -->
<bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean" >
<property name="dataSource" ref="dataSource" />
<property name="transactionManager" ref="transactionManager" />
<property name="databaseType" value="oracle" />
</bean>
with this:
<!-- JobRepository and JobLauncher are configuration/setup classes -->
<bean id="jobRepository" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean" >
<property name="dataSource" ref="dataSource" />
<property name="transactionManager" ref="transactionManager" />
<property name="databaseType" value="oracle" />
</bean>
and it should work.
I have an application using spring-boot, Apache Camel and active MQ. The camel routes are activeMQ queue polling routes.
This is the camel-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- Configures the Camel Context-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:amq="http://activemq.apache.org/schema/core"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>file:${envpath}/activemqApplication.properties</value>
</list>
</property>
</bean>
<bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" init-method="start" destroy-method="stop">
<property name="connectionFactory" ref="jmsConnectionFactory"/>
<property name="maximumActiveSessionPerConnection" value="${message.sessions.per.connection}"/>
<property name="maxConnections" value="${message.max.connections}"/>
</bean>
<bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory" primary="true">
<property name="brokerURL" value="${message.broker.url}"/>
<property name="trustAllPackages" value="true"/>
</bean>
<bean id="jmsTransactionManager" class="org.springframework.jms.connection.JmsTransactionManager">
<property name="connectionFactory" ref="pooledConnectionFactory"/>
</bean>
<bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent">
<property name="connectionFactory" ref="pooledConnectionFactory"/>
<property name="transactionManager" ref="jmsTransactionManager"/>
<property name="usePooledConnection" value="true"/>
<property name="concurrentConsumers" value="${activemq.concurrency}" />
</bean>
<bean id="fileSupport" class=" com.archive.app.module.helper.filesSupport">
</bean>
<camelContext xmlns="http://camel.apache.org/schema/spring">
<package>com.fileSupport.app.routes</package>
</camelContext>
</beans>
These are the classes
Spring boot class
package com.fileSupport.app;
import org.springframework.boot.SpringApplication;
public final class FileSupportMain {
public static void main(final String[] args) {
SpringApplication app = new SpringApplication(FileArchiveSpringBootApplication.class);
app.setWebEnvironment(false);
app.run(args);
}
private FileSupportMain() {
}
}
Spring boot main class
package com.fileSupport.app;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
#ImportResource({"classpath:/META-INF/spring/camel-context.xml"})
#EnableConfigurationProperties
#SpringBootApplication
public class FileSupportSpringBootApplication {
}
package com.fileSupport.app.routes;
import org.apache.camel.Exchange;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jackson.JacksonDataFormat;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.springframework.stereotype.Component;
Camel Routes:
/**
* ActiveMQ queue is watched by
* this route which then performs content based
* routing on the messages using XPath.
*/
#Component
public final class ConsumeActiveMQmessages extends RouteBuilder {
#Override
public void configure() throws Exception {
from("activemq:queue:" + Variables.RECEIVE_QUEUE1)
.routeId("queueRoute")
.log(LoggingLevel.INFO, "Body: $simple{body}")
.to("activemq:queue:" + Variables.RECEIVE_QUEUE2);
from("activemq:queue:" + Variables.RECEIVE_QUEUE2)
.to("direct:callback");
from("direct:callback")
.log(LoggingLevel.INFO, "body: $simple{body}")
.end();
}
}
If you are not using spring-boot-starter-web you should turn on the Camel run controller option.
See the docs for the option at: https://github.com/apache/camel/blob/master/components/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/CamelConfigurationProperties.java#L124
You just configure this using normal spring boot configuration style.
I am just writing a very basic Aspect #before function as I am new to AspectJ.
I have read spring documentation and experimenting with it in my example.
But Aspect is not appearing to be woven with my code.
Here is my controller whose method I wish to advice.
Please note it is a simple java method and not any request method.
public void printData()
{
System.out.println("just to test aspect programming");
}
It is invoked from one of the request method in my web application.
#RequestMapping("/")
public String doLogin(ModelMap modelMap)
{
System.out.println("doLogin" +loginService);
String message=messageSource.getMessage("message", null, "default", Locale.UK);
System.out.println("Message is:" + message);
printData();
LoginForm loginForm=new LoginForm();
modelMap.put("loginForm",loginForm);
return "login";
}
My Aspect class is as follows:
package com.neha.javabrains;
import org.springframework.stereotype.Component;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
#Component
#Aspect
public class LogTime {
#Before("execution(* com.neha.javabrains.LoginController.printData(..))")
public void loggedData()
{
System.out.println("In Pointcut Expression");
}
}
My Config class is as below:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- <bean/> definitions here -->
<context:component-scan base-package="com.neha.javabrains" />
<context:annotation-config/>
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" />
<tx:annotation-driven transaction-manager="txManager"/>
<aop:aspectj-autoproxy />
<bean id="loginDAO" class="com.neha.javabrains.LoginDAO">
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="myDataSource"/>
</bean>
<bean id="loginFormValidator" class="com.neha.javabrains.LoginFormValidator"/>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="message" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<beans profile="dev">
<bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:books"></property>
<property name="username" value="system"></property>
<property name="password" value="xyz"></property>
</bean>
</beans>
<beans profile="prod">
<bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:orcl"></property>
<property name="username" value="system"></property>
<property name="password" value="abc"></property>
</bean>
</beans>
</beans>
When I run my app it is working fine but just ASpect Before method is not getting executed as its sysout is not being printed.
It seems as if Aspect is not even attached to my method.
Please help!!!!!!!!!!!
Currently I'm trying to setup Spring MVC Controller testing for a school project I'm working on next to my job. Normally I program in php and frameworks like Laravel so this is pretty new for me. The problem is that I can't figure out how to solve the problem that keeps popping up on loading the ApplicationContext. Any help is appreciated.
Update:
I'm now told that test cases don't use a jndi ref in my app server. So this reference would fail on a test case, it runs fine on starting the application. Now I made a second file called servlet-test.xml (listed below) that uses a reference to the database on port 3306. I only use this file on tests not when starting up the application. But when I use this method I get Following error: Error creating bean with name 'productController': Injection of autowired dependencies failed. Any help is welcome as I'm struggling to setup MVC Controller tests for my school project. Other students I've been working with also are stuck with the same problem I am so I could help them out too.
I suspect the problem is the following, but I'm not sure how to solve this.
Error creating bean with name 'myDataSource' defined in URL
[file:web/WEB-INF/servlet.xml]: Invocation of init method failed;
nested exception is javax.naming.NamingException: Lookup failed for
'java:app/fotoproducent' ...
The Error Stack Trace
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in URL [file:web/WEB-INF/servlet.xml]: Cannot resolve reference to bean 'myDataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myDataSource' defined in URL [file:web/WEB-INF/servlet.xml]: Invocation of init method failed; nested exception is javax.naming.NamingException: Lookup failed for 'java:app/fotoproducent' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.url.pkgs=com.sun.enterprise.naming, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl} [Root exception is javax.naming.NamingException: Invocation exception: Got null ComponentInvocation ]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1456)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1197)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:973)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:750)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:121)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:250)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
The Controller test i'm trying to run:
ProductController Test
package controller.tests.config;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration({"file:web/WEB-INF/servlet-test.xml", "file:web/WEB-INF/dispatcher-servlet.xml"})
public class ProductControllerTest {
#Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
#Before
public void setup() {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
}
#Test
public void testProductAction() throws Exception {
ResultMatcher ok = MockMvcResultMatchers.status().isOk();
ResultMatcher msg = MockMvcResultMatchers.model()
.attribute("msg", "Spring quick start!!");
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/product");
this.mockMvc.perform(builder)
.andExpect(ok)
.andExpect(msg);
}
}
servlet.xml / applicationContext.xml file
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- module/package declarations -->
<context:component-scan base-package="Application" />
<context:component-scan base-package="Authentication" />
<context:component-scan base-package="Photo" />
<context:component-scan base-package="Product" />
<context:component-scan base-package="Organisation" />
<context:component-scan base-package="Login" />
<context:component-scan base-package="UI" />
<context:component-scan base-package="I18n" />
<context:component-scan base-package="Internationalization" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="myDataSource" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton">
<property name="jndiName" value="java:app/fotoproducent" />
<property name="resourceRef" value="true" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="packagesToScan" value="*" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
<mvc:resources mapping="/static/**" location="/static/"/>
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:default-servlet-handler/>
<mvc:annotation-driven />
</beans>
Dispatcher-servlet.xml
<?xml version='1.0' encoding='UTF-8' ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMap ping"/>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.html">indexController</prop>
<prop key="test.html">testController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/views/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
<!--
The test controller.
-->
<bean name="testController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="test" />
</beans>
Update 1: "DataSource Configuration"
This shows how the datasource is configured.
glassfish-resources.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="mysql_fotoproducent_rootPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
<property name="serverName" value="localhost"/>
<property name="portNumber" value="3306"/>
<property name="databaseName" value="fotoproducent"/>
<property name="User" value="root"/>
<property name="Password" value="password"/>
<property name="URL" value="jdbc:mysql://localhost:3306/fotoproducent?zeroDateTimeBehavior=convertToNull"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
</jdbc-connection-pool>
<jdbc-resource enabled="true" jndi-name="app/fotoproducent" object-type="user" pool-name="mysql_fotoproducent_rootPool"/>
</resources>
Update 2: Additional Bean Config file (servlet-test.xml)
This results in beans not being loaded. Following error: Error creating bean with name 'productController': Injection of autowired dependencies failed
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:annotation-config/>
<mvc:annotation-driven />
<!-- module/package declarations -->
<context:component-scan base-package="Application" />
<context:component-scan base-package="Authentication" />
<context:component-scan base-package="Photo" />
<context:component-scan base-package="Product" />
<context:component-scan base-package="Organisation" />
<context:component-scan base-package="Login" />
<context:component-scan base-package="UI" />
<context:component-scan base-package="I18n" />
<context:component-scan base-package="Internationalization" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/fotoproducent?zeroDateTimeBehavior=convertToNull" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
<property name="packagesToScan" value="*" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
</bean>
</property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
<mvc:resources mapping="/static/**" location="/static/"/>
<mvc:resources mapping="/resources/**" location="/resources/" />
</beans>
Update 3: Additional Code for problem resolving
Product Controller
package Product.Controller;
import Product.Sevice.ProductService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/product")
public class ProductController {
#Autowired
protected ProductService service;
#RequestMapping(value = "", method = RequestMethod.GET)
public String productAction(ModelMap model)
{
model.put("productList", this.service.findAll());
return "product/overview";
}
}
Product Service
package Product.Sevice;
import Product.Entity.Product;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import org.springframework.stereotype.Service;
#Service
public class ProductService {
#PersistenceContext
private EntityManager em;
#Transactional
public void insert(Product product)
{
// insert into database
// persist function is for NEW entities in database
this.em.persist(product);
}
#Transactional
public Product get(Integer id)
{
// this gets the entity from the database and returns it
return this.em.find(Product.class, (long) id);
}
#Transactional
public Product update(Product product)
{
// this updates the ExampleEntity in within the database
return this.em.merge(product);
}
#Transactional
public void remove(Integer id)
{
Product product = this.em.find(Product.class, (long) id);
product.delete();
// this updates the product in within the database
this.update(product);
}
#Transactional
public List<Product> findAll()
{
Query q = this.em.createNamedQuery("product.namedquery", Product.class);
return q.getResultList();
}
}
According to your stack trace when application context is initializing it still try to load wrong configuration files (servlet.xml), but should load servlet-test.xml. Please try to change your config locations with using path from root (src) folder, such as:
#ContextConfiguration({"file:src/main/web/WEB-INF/servlet-test.xml", "file:src/main/web/WEB-INF/dispatcher-servlet.xml"})
P.S Also you can try to move your config for tests (servlet-test.xml) to src/test/resources and load it from classpath: "classpath:servlet-test.xml". Also you can check this thread on stackoverflow: Spring #ContextConfiguration how to put the right location for the xml for extended discussion of similar problem.
You get an error which says that Spring IOC container fails to create and instantiate entityManagerFactory bean. Why?
That's another thing that your error exception mention. It fails to do so because it can't instantiate the myDataSource bean. Why?
According to your error message:
Lookup failed for 'java:app/fotoproducent'
It means that when IOC Spring container tried to create myDataSource bean, it failed to do so because it failed to set the jndiName with value of java:app/fotoproducent
Instead of using this:
<bean id="myDataSource" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton">
<property name="jndiName" value="java:app/fotoproducent" />
<property name="resourceRef" value="true" />
</bean>
Replace it with:
<bean id="myDataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="your_driver_class_name" />
<property name="url" value="url_to_your_db" />
<property name="username" value="user_name_to_db" />
<property name="password" value="password_to_db" />
</bean>
My suggestion is to create a standard dataSource like mentioned on Spring docs above.
Now don't forget to replace the values for driver class name, url, user name, and password.
Here is an example from Spring docs, of how to define a data source for use of Hibernate ORM: http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#orm-hibernate
I'm trying to execute Spring Batch Example – CSV File To MySQL Database.
when im running the App.java the following error it is displaying.
java.lang.NumberFormatException: Unparseable number: Clicks
java.lang.IllegalArgumentException: Unparseable date: "Order Date", format: [dd/MM/yyyy]
Can anyone pls let me know where i have done mistake..
Source Code :
report.csv
OrderDate,Impressions,Clicks,Earning
6/1/13, "139,237", 37, 227.21
6/2/13, "149,582", 55, 234.71
6/3/13, "457,425", 132, 211.48
6/4/13, "466,870", 141, 298.40
6/5/13,"472,385",194,281.35
......
resources/spring/batch/config/database.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
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-3.2.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd">
<!-- connect to database -->
<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/test" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="transactionManager"
class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />
<!-- create job-meta tables automatically -->
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="org/springframework/batch/core/schema-drop-mysql.sql" />
<jdbc:script location="org/springframework/batch/core/schema-mysql.sql" />
</jdbc:initialize-database>
</beans
resources/spring/batch/config/context.xml
<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-3.2.xsd">
<!-- stored job-metadata in database -->
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="transactionManager" ref="transactionManager" />
<property name="databaseType" value="mysql" />
</bean>
<!-- stored job-metadata in memory -->
<!--
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>
-->
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>
</beans>
resources/spring/batch/jobs/job-report.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<bean id="report" class="com.mkyong.model.Report" scope="prototype" />
<batch:job id="reportJob">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="cvsFileItemReader" writer="mysqlItemWriter"
commit-interval="2">
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<bean id="cvsFileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader">
<!-- Read a csv file -->
<property name="resource" value="classpath:cvs/report.csv" />
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<!-- split it -->
<property name="lineTokenizer">
<bean
class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="names" value="date,impressions,clicks,earning" />
</bean>
</property>
<property name="fieldSetMapper">
<!-- map to an object -->
<bean class="com.mkyong.ReportFieldSetMapper" />
</property>
</bean>
</property>
</bean>
<bean id="mysqlItemWriter"
class="org.springframework.batch.item.database.JdbcBatchItemWriter">
<property name="dataSource" ref="dataSource" />
<property name="sql">
<value>
<![CDATA[
insert into RAW_REPORT(DATE,IMPRESSIONS,CLICKS,EARNING)
values (:date, :impressions, :clicks, :earning)
]]>
</value>
</property>
<!-- It will take care matching between object property and sql name parameter -->
<property name="itemSqlParameterSourceProvider">
<bean
class="org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider" />
</property>
</bean>
</beans>
com/mkyong/model/Report.java
package com.mkyong.model;
public class Report {
private Date orderDate;
private String impressions;
private int clicks;
private String earning;
//getter and setter methods
}
com/mkyong/App.java
package com.mkyong;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
String[] springConfig =
{ "spring/batch/config/database.xml",
"spring/batch/config/context.xml",
"spring/batch/jobs/job-report.xml"
};
ApplicationContext context =
new ClassPathXmlApplicationContext(springConfig);
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("reportJob");
try {
JobExecution execution = jobLauncher.run(job, new JobParameters());
System.out.println("Exit Status : " + execution.getStatus());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done");
}
}
ReportFieldSetMapper.java
package com.mkyong;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.validation.BindException;
import com.mkyong.model.Report;
public class ReportFieldSetMapper implements FieldSetMapper<Report> {
#Override
public Report mapFieldSet(FieldSet fieldSet) throws BindException {
Report report = new Report();
report.setOrderDate(fieldSet.readDate(0,"dd/MM/yyyy"));
report.setImpressions(fieldSet.readString (1));
report.setClicks;(fieldSet.readInt(2));
report.setEarning(fieldSet.readString(3));
}
}
Looks like you try to parse the header line
add <property name="linesToSkip" value="1"></property> to your bean <bean id="cvsFileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader">