Newcomer to spring here, so i am trying to test if the persistence of certain element in my database is perfectly done using. those elements exist in a excel file. I have tried this so far. and I keep having the same application context loading failure problem
`#RunWith(SpringJUnit4ClassRunner.class)
#Transactional
#TransactionConfiguration(defaultRollback = true)
#ContextConfiguration(
{ "/applicationContext1.xml",
"file:C:/Users/Mohammed.yasserdahbi/Desktop/Workspace/APCITA380/src/main/resources/META-INF/spring/applicationContext-security.xml",
"file:C:/Users/Mohammed.yasserdahbi/Desktop/Workspace/APCITA380/src/main/resources/META-INF/spring/applicationContext-jpa.xml",
}
)
public class TestCase {
#Autowired
PerimetreComposantService perimetreComposantService;
#Test
public void testSavePerimetreComposant() throws IOException {
try {
String content = readFile("C:/Users/Mohammed.yasserdahbi/Desktop/test.txt");
String[] parts=content.split("####");
long id =Long.parseLong(parts[1]);
FileInputStream inputStream = new FileInputStream(new File("C:/Users/Mohammed.yasserdahbi/Desktop/aa.xlsx"));
ArrayList<String> values = new ArrayList<String>();
List<Article> articles =new ArrayList();
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(9);
Iterator<Row> iterator = firstSheet.iterator();
while (iterator.hasNext()) {
Row nextRow = iterator.next();
Iterator<Cell> cellIterator = nextRow.cellIterator();
if (nextRow.getRowNum() == 0 || nextRow.getRowNum() == 1) {
/*
* Do Nothing
*/
}
else {
Cell cell;
/* For each row, iterate through each columns */
for (int i = 0; i < 5; i++) {
/*
* Get the cell content including the blank cells
*/
cell = nextRow.getCell(i, Row.CREATE_NULL_AS_BLANK);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
values.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
values.add(Integer.toString((int) cell
.getNumericCellValue()));
break;
case Cell.CELL_TYPE_BOOLEAN:
values.add(Boolean.toString((boolean) cell
.getBooleanCellValue()));
break;
/*
* When it's a blank cell, fill it with empty string
*/
case Cell.CELL_TYPE_BLANK:
values.add("");
break;
default:
values.add(cell.getStringCellValue());
}
}
try{
System.out.println("toto");
articles = perimetreComposantService.findArticlesBy(values.get(0), values.get(1), Double.parseDouble(values.get(2)), Integer.parseInt(values.get(3)), values.get(4), id);
}catch (Exception e) {
e.printStackTrace();
}
assertFalse(!articles.isEmpty());
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}`
failure details:
2017-12-08 11:42:30 [INFO ]
(XmlBeanDefinitionReader.java:loadBeanDefinitions:315) => Loading XML
bean definitions from URL
[file:/C:/Users/Mohammed.yasserdahbi/Desktop/Workspace/APCITA380/target/classes/META-INF/spring/applicationContext.xml]
2017-12-08 11:42:31 [INFO ]
(XmlBeanDefinitionReader.java:loadBeanDefinitions:315) => Loading XML
bean definitions from URL
[file:/C:/Users/Mohammed.yasserdahbi/Desktop/Workspace/APCITA380/target/test-classes/applicationContext1.xml]
2017-12-08 11:42:31 [INFO ]
(DefaultListableBeanFactory.java:registerBeanDefinition:665) =>
Overriding bean definition for bean 'dataSource': replacing [Generic
bean: class [org.apache.commons.dbcp.BasicDataSource]; scope=;
abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0;
autowireCandidate=true; primary=false; factoryBeanName=null;
factoryMethodName=null; initMethodName=null; destroyMethodName=close;
defined in URL
[file:/C:/Users/Mohammed.yasserdahbi/Desktop/Workspace/APCITA380/target/classes/META-INF/spring/applicationContext.xml]]
with [Generic bean: class [org.apache.commons.dbcp.BasicDataSource];
scope=; abstract=false; lazyInit=false; autowireMode=0;
dependencyCheck=0; autowireCandidate=true; primary=false;
factoryBeanName=null; factoryMethodName=null; initMethodName=null;
destroyMethodName=close; defined in URL
[file:/C:/Users/Mohammed.yasserdahbi/Desktop/Workspace/APCITA380/target/test-classes/applicationContext1.xml]]
2017-12-08 11:42:31 [INFO ]
(DefaultListableBeanFactory.java:registerBeanDefinition:665) =>
Overriding bean definition for bean 'transactionManager': replacing
[Generic bean: class
[org.springframework.orm.jpa.JpaTransactionManager]; scope=;
abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0;
autowireCandidate=true; primary=false; factoryBeanName=null;
factoryMethodName=null; initMethodName=null; destroyMethodName=null;
defined in URL
[file:/C:/Users/Mohammed.yasserdahbi/Desktop/Workspace/APCITA380/target/classes/META-INF/spring/applicationContext.xml]]
with [Generic bean: class
[org.springframework.orm.jpa.JpaTransactionManager]; scope=;
abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0;
autowireCandidate=true; primary=false; factoryBeanName=null;
factoryMethodName=null; initMethodName=null; destroyMethodName=null;
defined in URL
[file:/C:/Users/Mohammed.yasserdahbi/Desktop/Workspace/APCITA380/target/test-classes/applicationContext1.xml]]
2017-12-08 11:42:31 [INFO ]
(DefaultListableBeanFactory.java:registerBeanDefinition:665) =>
Overriding bean definition for bean 'viewResolver': replacing [Generic
bean: class
[org.springframework.web.servlet.view.UrlBasedViewResolver]; scope=;
abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0;
autowireCandidate=true; primary=false; factoryBeanName=null;
factoryMethodName=null; initMethodName=null; destroyMethodName=null;
defined in URL
[file:/C:/Users/Mohammed.yasserdahbi/Desktop/Workspace/APCITA380/target/classes/META-INF/spring/applicationContext.xml]]
with [Generic bean: class
[org.springframework.web.servlet.view.UrlBasedViewResolver]; scope=;
abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0;
autowireCandidate=true; primary=false; factoryBeanName=null;
factoryMethodName=null; initMethodName=null; destroyMethodName=null;
defined in URL
[file:/C:/Users/Mohammed.yasserdahbi/Desktop/Workspace/APCITA380/target/test-classes/applicationContext1.xml]]
2017-12-08 11:42:31 [INFO ]
(DefaultListableBeanFactory.java:registerBeanDefinition:665) =>
Overriding bean definition for bean 'entityManagerFactory': replacing
[Generic bean: class
[org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean];
scope=; abstract=false; lazyInit=false; autowireMode=0;
dependencyCheck=0; autowireCandidate=true; primary=false;
factoryBeanName=null; factoryMethodName=null; initMethodName=null;
destroyMethodName=null; defined in URL
[file:/C:/Users/Mohammed.yasserdahbi/Desktop/Workspace/APCITA380/target/classes/META-INF/spring/applicationContext.xml]]
with [Generic bean: class
[org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean];
scope=; abstract=false; lazyInit=false; autowireMode=0;
dependencyCheck=0; autowireCandidate=true; primary=false;
factoryBeanName=null; factoryMethodName=null; initMethodName=null;
destroyMethodName=null; defined in URL
[file:/C:/Users/Mohammed.yasserdahbi/Desktop/Workspace/APCITA380/target/test-classes/applicationContext1.xml]]
2017-12-08 11:42:31 [INFO ]
(XmlBeanDefinitionReader.java:loadBeanDefinitions:315) => Loading XML
bean definitions from URL
[file:/C:/Users/Mohammed.yasserdahbi/Desktop/Workspace/APCITA380/target/classes/META-INF/spring/applicationContext-jpa.xml]
2017-12-08 11:42:31 [ERROR]
(TestContextManager.java:prepareTestInstance:314) => Caught exception
while allowing TestExecutionListener
[org.springframework.test.context.support.DependencyInjectionTestExecutionListener#5c8c05]
to prepare test instance
[com.zodiac.apcit.business.test.TestCase2#1ecade2]
java.lang.IllegalStateException: Failed to load ApplicationContext at
org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at
org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122)
at
org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at
org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at
org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at
org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at
org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by:
org.springframework.beans.factory.BeanDefinitionStoreException:
Unexpected exception parsing XML document from URL
[file:/C:/Users/Mohammed.yasserdahbi/Desktop/Workspace/APCITA380/target/classes/META-INF/spring/applicationContext-jpa.xml];
nested exception is org.springframework.beans.FatalBeanException:
Invalid NamespaceHandler class
[org.springframework.data.jpa.repository.config.JpaRepositoryNameSpaceHandler]
for namespace [http://www.springframework.org/schema/data/jpa]:
problem with handler class file or dependent class; nested exception
is java.lang.NoClassDefFoundError:
org/springframework/beans/factory/xml/NamespaceHandlerSupport at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:412)
at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at
org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)
at
org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)
at
org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at
org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:243)
at
org.springframework.test.context.support.AbstractGenericContextLoader.loadBeanDefinitions(AbstractGenericContextLoader.java:233)
at
org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:117)
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:248)
at
org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
at
org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
... 25 more Caused by: org.springframework.beans.FatalBeanException:
Invalid NamespaceHandler class
[org.springframework.data.jpa.repository.config.JpaRepositoryNameSpaceHandler]
for namespace [http://www.springframework.org/schema/data/jpa]:
problem with handler class file or dependent class; nested exception
is java.lang.NoClassDefFoundError:
org/springframework/beans/factory/xml/NamespaceHandlerSupport at
org.springframework.beans.factory.xml.DefaultNamespaceHandlerResolver.resolve(DefaultNamespaceHandlerResolver.java:139)
at
org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1433)
at
org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1428)
at
org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:195)
at
org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:139)
at
org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:108)
at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493)
at
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390)
... 38 more Caused by: java.lang.NoClassDefFoundError:
org/springframework/beans/factory/xml/NamespaceHandlerSupport at
java.lang.ClassLoader.findBootstrapClass(Native Method) at
java.lang.ClassLoader.findBootstrapClassOrNull(ClassLoader.java:1061)
at java.lang.ClassLoader.loadClass(ClassLoader.java:412) at
java.lang.ClassLoader.loadClass(ClassLoader.java:410) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at
java.lang.ClassLoader.loadClass(ClassLoader.java:356) at
org.springframework.util.ClassUtils.forName(ClassUtils.java:257) at
org.springframework.beans.factory.xml.DefaultNamespaceHandlerResolver.resolve(DefaultNamespaceHandlerResolver.java:124)
... 45 more
can anybody tell what is the problem is?
Related
I am trying to configure Hibernate, Spring Data JPA for MySQL. I would really appreciate if anyone could point out what I am missing? Also, I was unable to find the reason for IllegalArgumentException.
2016-07-05 19:07:06.677 INFO 7760 --- [ main] o.s.j.d.DriverManagerDataSource : Loaded JDBC driver: com.mysql.jdbc.Driver
file:/C:/Users/eprisur/.gradle/caches/modules-2/files-2.1/org.hibernate.javax.persistence/hibernate-jpa-2.1-api/1.0.0.Final/5e731d961297e5a07290bfaf3db1fbc8bbbf405a/hibernate-jpa-2.1-api-1.0.0.Final.jar
2016-07-05 19:07:06.799 WARN 7760 --- [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/test/authflow/config/DatabaseConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Class name must not be null
2016-07-05 19:07:06.810 INFO 7760 --- [ main] o.apache.catalina.core.StandardService : Stopping service Tomcat
2016-07-05 19:07:06.822 ERROR 7760 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/test/authflow/config/DatabaseConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Class name must not be null
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.3.RELEASE.jar:1.3.3.RELEASE]
at com.test.authflow.LoginSystemApplication.main(LoginSystemApplication.java:11) [bin/:na]
Caused by: java.lang.IllegalArgumentException: Class name must not be null
at org.springframework.util.Assert.notNull(Assert.java:115) ~[spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.util.ClassUtils.convertClassNameToResourcePath(ClassUtils.java:960) ~[spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.buildDefaultPersistenceUnitInfo(DefaultPersistenceUnitManager.java:522) ~[spring-orm-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.readPersistenceUnitInfos(DefaultPersistenceUnitManager.java:503) ~[spring-orm-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.preparePersistenceUnitInfos(DefaultPersistenceUnitManager.java:440) ~[spring-orm-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.afterPropertiesSet(DefaultPersistenceUnitManager.java:424) ~[spring-orm-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:310) ~[spring-orm-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:319) ~[spring-orm-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]
2016-07-05 19:07:06.825 WARN 7760 --- [ main] o.s.boot.SpringApplication : Error handling failed (Error creating bean with name 'delegatingApplicationListener' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration': Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry' is defined)
My build.gradle looks like:
buildscript {
ext { springBootVersion = '1.3.3.RELEASE' }
repositories {
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse-wtp'
apply plugin: 'spring-boot'
jar {
manifest {
attributes 'Main-Class': 'com.test.authflow.LoginSystemApplication'
}
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
configurations {
providedRuntime
}
configurations {
runtime.exclude group: "org.slf4j", module: "slf4j-simple"
compile.exclude group: "org.slf4j", module: "slf4j-simple"
}
dependencies {
//for external container
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
providedRuntime("org.apache.tomcat:tomcat-juli")
providedRuntime("org.apache.tomcat:tomcat-jdbc")
}
ext['hibernate.version'] = '5.2.1.Final'
dependencies {
compile ('org.springframework.boot:spring-boot-starter')
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("org.springframework.boot:spring-boot-starter-security")
compile("mysql:mysql-connector-java")
}
task wrapper(type: Wrapper) {
gradleVersion = '2.13'
}
This is my DatabaseConfig class:
package com.test.authflow.config;
import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#PropertySource(value = { "application.properties" })
#EnableTransactionManagement
public class DatabaseConfig {
#Bean
public DataSource dataSource()
{
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("db.driver"));
dataSource.setUrl(env.getProperty("db.url"));
dataSource.setUsername(env.getProperty("db.username"));
dataSource.setPassword(env.getProperty("db.password"));
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em =
new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
// Classpath scanning of #Component, #Service, etc annotated class
em.setPackagesToScan(
env.getProperty("em.setPackagesToScan"));
//Vendor Adapter
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
//Hibernate Properties
Properties additionalProperties = new Properties();
additionalProperties.put(
"hibernate.dialect",
env.getProperty("hibernate.dialect"));
additionalProperties.put(
"hibernate.show_sql",
env.getProperty("hibernate.dialect"));
additionalProperties.put(
"hibernate.hbm2ddl.auto",
env.getProperty("hibernate.hbm2ddl.auto"));
em.setJpaProperties(additionalProperties);
System.out.println(EntityManager.class.getProtectionDomain()
.getCodeSource()
.getLocation());
return em;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager =
new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
public PersistenceExceptionTranslationPostProcessor ExceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Autowired
private Environment env;
}
Accord to DefaultPersistenceUnitManager.java: line 522
The problem is that you didn't set the packagesToScan
for (String pkg : this.packagesToScan) {
try {
String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
ClassUtils.convertClassNameToResourcePath(pkg) + CLASS_RESOURCE_PATTERN;
public static String convertClassNameToResourcePath(String className) {
Assert.notNull(className, "Class name must not be null");
return className.replace(PACKAGE_SEPARATOR, PATH_SEPARATOR);
}
So you can check you code in
em.setPackagesToScan(env.getProperty("em.setPackagesToScan"));
env.getProperty("em.setPackagesToScan") is null;
you may have a java class into your package that's not a JPA/Entity
This question already has an answer here:
How to convert Part to Blob, so I can store it in MySQL?
(1 answer)
Closed 6 years ago.
I want to upload a file and save it to mysql database. thus far, I am able to upload the file, print its detail. However, when I attempt to store it in the database via a helper class everything except for the ID become null. Can you take a look and let me know what I am missing? Also, let me know if you see anything that I should change/modify as code enhancement.
Uploading the file using JSF/Primefaces:
<h:form enctype="multipart/form-data">
<p:growl id="messages" showDetail="true" />
<p:fileUpload value="#{fileUploadView1.file}" mode="simple"/>
<p:commandButton value="Submit" ajax="false" actionListener="#{fileUploadView1.upload}" />
</h:form>
FileBean:
#ManagedBean
#SessionScoped
public class FileUploadView1 {
private InputStream input;
private String fileName;
private Long fileSize;
private UploadedFile file;
#Inject
private FileController1 fileController;
public InputStream getInput() {
return input;
}
public String getFileName() {
return fileName;
}
public Long getFileSize() {
return fileSize;
}
public FileController1 getFileController() {
return fileController;
}
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
System.out.println("filesize " + file.getSize());
}
public void upload() throws IOException {
if (file != null) {
FacesMessage message = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, message);
input = file.getInputstream();
fileName = file.getFileName();
fileSize = file.getSize();
System.out.println("filesize3 " + file.getSize());
fileController.uploadFile(file);
}
}
}
FileController:
#ManagedBean
#SessionScoped
public class FileController1 {
private FileDbUtil1 fileDbUtil;
private Logger logger = Logger.getLogger(getClass().getName());
public FileController1() throws Exception {
fileDbUtil = FileDbUtil1.getInstance();
}
public String uploadFile(UploadedFile theFile) {
logger.info("Uploading File: " + theFile);
try {
fileDbUtil.uploadFile(theFile);
} catch (Exception exc) {
logger.log(Level.SEVERE, "Error adding files", exc);
addErrorMessage(exc);
return null;
}
return "welcomePrimefaces";
}
private void addErrorMessage(Exception exc) {
FacesMessage message = new FacesMessage("Error: " + exc.getMessage());
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
FileDbUtil File
public static FileDbUtil1 getInstance() throws Exception {
if (instance == null) {
instance = new FileDbUtil1();
}
return instance;
}
private FileDbUtil1() throws Exception {
dataSource = getDataSource();
}
private DataSource getDataSource() throws NamingException {
Context context = new InitialContext();
DataSource theDataSource = (DataSource) context.lookup(jndiName);
return theDataSource;
}
public void uploadFile(UploadedFile theFile) throws Exception {
fileName = theFile.getFileName();
input = theFile.getInputstream();
Connection myConn = null;
PreparedStatement myStmt = null;
try {
myConn = getConnection();
String sql = "insert into upload"
+ "(name, file)"
+ " values (?,?)";
myStmt = myConn.prepareStatement(sql);
// set params
myStmt.setString(1, fileName);
myStmt.setBinaryStream(2, input);
myStmt.executeUpdate();
} finally {
close(myConn, myStmt);
}
}
private Connection getConnection() throws Exception {
Connection theConn = dataSource.getConnection();
return theConn;
}
private void close(Connection theConn, Statement theStmt) {
close(theConn, theStmt, null);
}
private void close(Connection theConn, Statement theStmt, ResultSet theRs) {
try {
if (theRs != null) {
theRs.close();
}
if (theStmt != null) {
theStmt.close();
}
if (theConn != null) {
theConn.close();
}
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
Stack Trace: Note that I am able to print the file size before calling the helper class
Info: filesize 3501
Info: filesize3 3501
Warning: java.lang.NullPointerException
javax.el.ELException: java.lang.NullPointerException
at com.sun.el.parser.AstValue.invoke(AstValue.java:293)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:149)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:814)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at com.uploadfile.test.FileUploadView1.upload(FileUploadView1.java:70)
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:606)
at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
... 39 more
FATAL: JSF1073: javax.faces.FacesException caught during processing of INVOKE_APPLICATION 5 : UIComponent-ClientId=, Message=java.lang.NullPointerException
FATAL: java.lang.NullPointerException
javax.faces.FacesException: java.lang.NullPointerException
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:89)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.el.ELException: java.lang.NullPointerException
at com.sun.el.parser.AstValue.invoke(AstValue.java:293)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:149)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:814)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
... 31 more
Caused by: java.lang.NullPointerException
at com.uploadfile.test.FileUploadView1.upload(FileUploadView1.java:70)
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:606)
at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
... 39 more
Caused by: java.lang.NullPointerException
at com.uploadfile.test.FileUploadView1.upload(FileUploadView1.java:68)
fileController isn't getting injected.
Use #Inject private FileController1 fileController.
BalusC is right on his comment.
In this example I face a problem to write a junit test, which consumes a HAL-formatted rest-service. As I understand I can use MockRestServiceServer to fake a communication. You can find here two simple spring applications; one which provides a HAL-formatted rest-service and one which consumes it. Everything works fine, when both services are started up.
So, when you start both services with the command mvn spring-boot:run and you navigate to http://localhost:8080/products/list, then you can see the consumed rest-service.
The consumer itself uses a modified RestTemplate to request a response entity from the type PagedResources. My consumer-test defines a response body, which looks exactly similar to a normal request from the "provider" service.
My Test
package consumer;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import static org.springframework.test.util.AssertionErrors.assertEquals;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
import consumer.model.Product;
import consumer.service.ProductServiceImpl;
import consumer.service.util.CustomRestTemplate;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = ConsumerApplication.class)
#WebAppConfiguration
#IntegrationTest
public class ConsumerApplicationTests {
private MockRestServiceServer mockServer;
private RestTemplate restTemplate;
#Mock
private CustomRestTemplate customRestTemplate;
#InjectMocks
private ProductServiceImpl productServiceImpl;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
this.restTemplate = new RestTemplate();
this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
String responseBody = "\"_links\" : { \"self\" : { \"href\" : \"http://localhost:1234/products/list\" } }, \"_embedded\" : { \"products\" : [ { \"name\" : \"Product 1\", \"price\" : 0.99, \"_links\" : { \"self\" : { \"href\" : \"http://localhost:1234/v1/products/list/product/1\" } } }] }}";
this.mockServer.expect(requestTo("http://localhost:1234/products?size=" + Integer.MAX_VALUE)).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(responseBody, MediaType.parseMediaTypes("application/hal+json").get(0)));
}
#Test
public void contextLoads() {
when(customRestTemplate.getRestTemplateJackson2HttpMessageConverter()).thenReturn(restTemplate);
List<Product> productList = productServiceImpl.retrieveAllProduct();
assertEquals("Expected one product", 1, productList.size());
mockServer.verify();
}
}
When I execute the test I receive that error:
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not instantiate value of type [simple type, class org.springframework.hateoas.PagedResources<consumer.model.Product>] from String value ('_links'); no single-String constructor/factory method
at [Source: java.io.ByteArrayInputStream#1966492; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class org.springframework.hateoas.PagedResources<consumer.model.Product>] from String value ('_links'); no single-String constructor/factory method
at [Source: java.io.ByteArrayInputStream#1966492; line: 1, column: 1]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:208)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:200)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:97)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:809)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:793)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:572)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:530)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:476)
at consumer.service.ProductServiceImpl.retrieveAllProduct(ProductServiceImpl.java:35)
at consumer.ConsumerApplicationTests.contextLoads(ConsumerApplicationTests.java:58)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class org.springframework.hateoas.PagedResources<consumer.model.Product>] from String value ('_links'); no single-String constructor/factory method
at [Source: java.io.ByteArrayInputStream#1966492; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:770)
at com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:277)
at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:289)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1141)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:135)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:126)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3066)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2221)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:205)
... 39 more
If I am not completely wrong, the error occurrs because PagedResources does not have a String constructor. So what would be the best solution to test that code?
Thank you in advance!
Check this answer. It was very useful for me. Basically, what you have todo is to remove the PagedResourcesAssembler parameter from the Controller. And build it into the method.
#RequestMapping(method=RequestMethod.GET)
public ResponseEntity<PagedResources<AccountResource>> getAccounts(
#RequestParam(value="name", required = false) String name,
#RequestParam(value="username", required = false) String username,
#RequestParam(value="email", required = false) String email,
#RequestParam(value="lastName", required = false) String lastName,
#RequestParam(value="size", required = true, defaultValue = "10") Integer size,
#RequestParam(value="page", required = true, defaultValue = "0") int page,
#RequestParam(value="sort", required = false, defaultValue = "username") String sort,
#RequestParam(value="direction", required = false, defaultValue = "asc") String direction,
UriComponentsBuilder uriBuilder,
HttpServletRequest request,
HttpServletResponse response) {
// Build page request
AccountList list = null;
Page<Account> resultPage = null;
Direction sortDirection = Direction.ASC;
if(direction.equals("desc")) {
sortDirection = Direction.DESC;
}
PageRequest pReq = new PageRequest(page, size, sortDirection, sort);
resultPage = accountService.findAll(pReq);
HateoasPageableHandlerMethodArgumentResolver resolver = new HateoasPageableHandlerMethodArgumentResolver();
PagedResourcesAssembler<Account> accountPageAssembler = new PagedResourcesAssembler<Account>(resolver, null);
return new ResponseEntity<PagedResources<AccountResource>>(accountPageAssembler.toResource(resultPage, new AccountResourceAsm()), HttpStatus.OK);
}
I have the following definition for PersonDTO:
public class PersonDTO
{
private String id
private String firstName;
private String lastName;
private String maritalStatus;
}
Here is a sample record :
{
"id": 1,
"firstName": "John",
"lastName": "Doe",
"maritalStatus": "married"
}
Now, John Doe gets divorced. So I need to send a PATCH request to this URL:
http://localhost:8080/people/1
With the following request body:
{
"maritalStatus": "divorced"
}
I cannot figure out how to do it. Here is what I tried so far:
// Create Person
PersonDTO person = new PersonDTO();
person.setMaritalStatus("Divorced");
// Create HttpEntity
final HttpEntity<ObjectNode> requestEntity = new HttpEntity<>(person);
// Create URL (for eg: localhost:8080/people/1)
final URI url = buildUri(id);
ResponseEntity<Void> responseEntity = restTemplate.exchange(url, HttpMethod.PATCH, requestEntity, Void.class);
Here are the problems with the above:
1) As I am setting only MaritalStatus, the other fields would all be null. So if I print out the request, it will look like this:
{
"id": null,
"firstName": "null",
"lastName": "null",
"maritalStatus": "married" // I only need to update this field.
}
Does that mean that I have to a GET before I do a PATCH?
2) I am getting the following stack trace:
08:48:52.717 ERROR c.n.d.t.s.PersonServiceImpl - Unexpected Exception :
org.springframework.web.client.ResourceAccessException: I/O error on PATCH request for "http://localhost:8080/people/1":Invalid HTTP method: PATCH; nested exception is java.net.ProtocolException: Invalid HTTP method: PATCH
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:580) ~[spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:545) ~[spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:466) ~[spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at com.sp.restclientexample..service.PersonServiceImpl.doPatch(PersonServiceImpl.java:75) ~[classes/:na]
at com.sp.restclientexample..service.PatchTitle.itDoPatch(PatchTitle.java:53) [test-classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_20]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_20]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_20]
at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_20]
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) [junit-4.12.jar:4.12]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) [junit-4.12.jar:4.12]
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163) [spring-test-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [.cp/:na]
Caused by: java.net.ProtocolException: Invalid HTTP method: PATCH
at java.net.HttpURLConnection.setRequestMethod(HttpURLConnection.java:440) ~[na:1.8.0_20]
at sun.net.www.protocol.http.HttpURLConnection.setRequestMethod(HttpURLConnection.java:517) ~[na:1.8.0_20]
at org.springframework.http.client.SimpleClientHttpRequestFactory.prepareConnection(SimpleClientHttpRequestFactory.java:209) ~[spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.http.client.SimpleClientHttpRequestFactory.createRequest(SimpleClientHttpRequestFactory.java:138) ~[spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.http.client.support.HttpAccessor.createRequest(HttpAccessor.java:76) ~[spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:565) ~[spring-web-4.1.6.RELEASE.jar:4.1.6.RELEASE]
... 33 common frames omitted
Appreciate any pointers from folks who have written client applications to consume a Restful webservice using Spring's RestTemplate.
For completeness, let me also state that we use SpringDataRest for our backend restful webservices.
SGB
I solved this problem just adding a new HttpRequestFactory to my restTemplate instance. Like this
RestTemplate restTemplate = new RestTemplate();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setConnectTimeout(TIMEOUT);
requestFactory.setReadTimeout(TIMEOUT);
restTemplate.setRequestFactory(requestFactory);
For TestRestTemplate, add
#Autowired
private TestRestTemplate restTemplate;
#Before
public void setup() {
restTemplate.getRestTemplate().setRequestFactory(new HttpComponentsClientHttpRequestFactory());
}
PS: You will need add httpClient component in your project
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>
For cases where RestTemplate is built from a RestTemplateBuilder, constructor for the custom RestClient can be written as,
public PersonRestClient(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.requestFactory(new HttpComponentsClientHttpRequestFactory()).build();
}
Also, the org.apache.httpcomponents.httpclient dependency needs to added to pom.
I have added the below code in the java file. It worked for me.
String url="Your API URL";
RestTemplate restTemplate = new RestTemplate();
HttpClient httpClient = HttpClientBuilder.create().build();
restTemplate.setRequestFactory(new
HttpComponentsClientHttpRequestFactory(httpClient));
HttpHeaders reqHeaders = new HttpHeaders();
reqHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> requestEntity = new HttpEntity<String>(requestJson, reqHeaders);
ResponseEntity<String> responseEntity=restTemplate.exchange(url, HttpMethod.PATCH,
requestEntity, String.class);
Also, need to add the below dependency in the pom.xml file.
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
For me solved by adding below line:
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
I created a generic method to do this when there are linked resources involved:
public void patch(M theEntity, Integer entityId, String linkName, URI linkUri) {
ObjectMapper objectMapper = getObjectMapperWithHalModule();
ObjectNode linkedNode = (ObjectNode) objectMapper.valueToTree(theEntity);
linkedNode.put(linkName, linkUri.getPath());
HttpEntity<ObjectNode> requestEntity = new HttpEntity<>(linkedNode);
restTemplate.exchange(uri + "/" + entityId, HttpMethod.PATCH, requestEntity, Void.class);
}
private ObjectMapper getObjectMapperWithHalModule() {
if(objectMapperHal == null) {
objectMapperHal = new ObjectMapper();
objectMapperHal.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapperHal.registerModule(new Jackson2HalModule());
}
return objectMapperHal;
}
Feel free to look at an implementation of this example at my full jal+json implementation
If you have an older spring version than 3.1.0, then you don't have the PATCH method in the HttpMethods. You can still use HttpClient from apache. Here is a short example on how I did it:
try {
//This is just to avoid ssl hostname verification and to trust all, you can use simple Http client also
CloseableHttpClient httpClient = HttpClientBuilder.create().setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build())
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
HttpPatch request = new HttpPatch(REST_SERVICE_URL);
StringEntity params = new StringEntity(JSON.toJSONString(payload), ContentType.APPLICATION_JSON);
request.setEntity(params);
request.addHeader(org.apache.http.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
request.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
//You can use other authorization method, like user credentials
request.addHeader(HttpHeaders.AUTHORIZATION, OAuth2AccessToken.BEARER_TYPE + " " + accessToken);
HttpResponse response = httpClient.execute(request);
String statusCode = response.getStatusLine().getStatusCode();
} catch (Exception ex) {
// handle exception here
}
The equivalent of this, with RestTemplate would be:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", OAuth2AccessToken.BEARER_TYPE + " " + accessToken);
final HttpEntity<String> entity = new HttpEntity<String>(JSON.toJSONString(payload), headers);
RestTemplate restTemplate = new RestTemplate();
try {
ResponseEntity<String> response = restTemplate.exchange(REST_SERVICE_URL, HttpMethod.PATCH, entity, String.class);
String statusCode = response.getStatusCode();
} catch (HttpClientErrorException e) {
// handle exception here
}
Also, make sure the payload only contains the values you need to change, and make sure you are sending the request to the right URL. (this can be in some cases something ending like /api/guest/{id} )
this will work if verified answer dose works
#Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
restTemplate.setRequestFactory(requestFactory);
return restTemplate;
}
WebClient offers a modern alternative to the RestTemplate with efficient support for both sync and async, as well as streaming scenarios. You can implement this with WebClient.
Configure WebClient
#Configuration
public class WebConfig {
public WebClient.Builder webClientBuilder() {
return WebClient.builder();
}
}
Then you can call method
//Constructor Injection
public YourClassName(WebClient.Builder webClientBuilder) {
this.webClientBuilder = webClientBuilder;
}
webClientBuilder.build()
.patch()
.uri("http://localhost:8081/api/v1/customers/{id}", id)
.contentType(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Void.class)
.block();
Dependency for pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
I am trying to configure a simple example for REST service using CXF + Jackson with JaxB #XmlRootElement annotation. I have already gone through various similar questions in stack overflow as well as blogs like this and have come up with the below solution:
Created a custom object mapper as follows:
public class CustomObjectMapper extends ObjectMapper{
public CustomObjectMapper() {
super();
super.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
super.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
AnnotationIntrospector primary = new JaxbAnnotationIntrospector();
AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
AnnotationIntrospector pair = new AnnotationIntrospector.Pair(primary, secondary);
super.setAnnotationIntrospector(pair);
}
}
Passed this to Json provided's constructor in spring config
<bean id="jacksonMapper" class="com.myorg.test.CustomObjectMapper" />
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider">
<constructor-arg ref="jacksonMapper" />
</bean>
</jaxrs:providers>
Added a simple class JsonBean with JAXB Root element annotation
#XmlRootElement(name = "JsonBean")
public class JsonBean {
private String val1;
private String val2;
public String getVal1() {
return val1;
}
public void setVal1(String val1) {
this.val1 = val1;
}
public String getVal2() {
return val2;
}
public void setVal2(String val2) {
this.val2 = val2;
}
}
When I pass the below json,
{
"JsonBean": {
"val1": "Hello",
"val2": "Hi"
}
}
it's throwing below exception:
WARNING: javax.ws.rs.InternalServerErrorException: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "JsonBean" (Class com.cognizan
t.poc.connectedcar.JsonBean), not marked as ignorable
at [Source: org.apache.cxf.transport.http.AbstractHTTPDestination$1#1f2fae4; line: 2, column: 13] (through reference chain: com.myorg.test.Json
Bean["JsonBean"])
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:243)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:99)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:271)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:239)
at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:223)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:203)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:137)
at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:158)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:243)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:163)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:219)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:669)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:457)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:557)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1075)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:384)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1009)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:255)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
at org.eclipse.jetty.server.Server.handle(Server.java:368)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:489)
at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:953)
Am I missing something here? Please help.
I got it right.
I missed to add unwrap for de-serialization in the custom mapper:
added the below line in CustomObjectMaller
super.configure(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true);
also, modified the spring config file as:
<jaxrs:providers>
<bean id="jsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider">
<property name="mapper" ref="jacksonMapper" />
</bean>
</jaxrs:providers>
It started working as expected..