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
Related
I have an user.csv file .I want to store the data of csv file into sql
database. I provide proper sql connection in yml file but it throws
run time exception
Caused by: java.sql.SQLSyntaxErrorException: Table 'login.batch_job_instance' doesn't exist
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.26.jar:8.0.26]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.26.jar:8.0.26]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.26.jar:8.0.26]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003) ~[mysql-connector-java-8.0.26.jar:8.0.26]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-4.0.3.jar:na]
at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:722) ~[spring-jdbc-5.3.10.jar:5.3.10]
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:651) ~[spring-jdbc-5.3.10.jar:5.3.10]
... 42 common frames omitted
2021-09-27 16:31:27.913 INFO 3800 --- [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-09-27 16:31:27.915 INFO 3800 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-09-27 16:31:27.922 INFO 3800 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Process finished with exit code 1
batch.config
package com.nilmani.literalmission.config
import com.nilmani.literalmission.model.User
import org.springframework.batch.core.Job
import org.springframework.batch.core.Step
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory
import org.springframework.batch.core.launch.support.RunIdIncrementer
import org.springframework.batch.item.ItemProcessor
import org.springframework.batch.item.ItemReader
import org.springframework.batch.item.ItemWriter
import org.springframework.batch.item.file.FlatFileItemReader
import org.springframework.batch.item.file.LineMapper
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper
import org.springframework.batch.item.file.mapping.DefaultLineMapper
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.io.FileSystemResource
#Configuration
#EnableBatchProcessing
class BatchConfig {
#Bean
fun job(jobBuilderFactory: JobBuilderFactory,
stepBuilderFactory: StepBuilderFactory,
itemReader: ItemReader<User>,
itemProcessor: ItemProcessor<User,User>,
itemWriter: ItemWriter<User>
):Job{
val step: Step = stepBuilderFactory["ETL-file-load"]
.chunk<User, User>(100)
.reader(itemReader)
.processor(itemProcessor)
.writer(itemWriter)
.build()
return jobBuilderFactory["ETL-Load"]
.incrementer(RunIdIncrementer())
.start(step)
.build()
}
#Bean
fun itemReader(): FlatFileItemReader<User>? {
val flatFileItemReader: FlatFileItemReader<User> = FlatFileItemReader<User>()
flatFileItemReader.setResource(FileSystemResource("src/main/resources/users.csv"))
flatFileItemReader.setName("CSV-Reader")
flatFileItemReader.setLinesToSkip(1)
flatFileItemReader.setLineMapper(lineMapper()!!)
return flatFileItemReader
}
#Bean
fun lineMapper(): LineMapper<User>? {
val defaultLineMapper: DefaultLineMapper<User> = DefaultLineMapper<User>()
val lineTokenizer = DelimitedLineTokenizer()
lineTokenizer.setDelimiter(",")
lineTokenizer.setStrict(false)
lineTokenizer.setNames("id", "name", "dept", "salary")
val fieldSetMapper: BeanWrapperFieldSetMapper<User> = BeanWrapperFieldSetMapper<User>()
fieldSetMapper.setTargetType(User::class.java)
defaultLineMapper.setLineTokenizer(lineTokenizer)
defaultLineMapper.setFieldSetMapper(fieldSetMapper)
return defaultLineMapper
}
}
DBWriter.kt
package com.nilmani.literalmission.batch
import com.nilmani.literalmission.model.User
import com.nilmani.literalmission.repository.UserRepository
import org.springframework.batch.item.ItemWriter
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
#Component
class DBWriter :ItemWriter<User> {
#Autowired
private lateinit var userRepository: UserRepository
#Autowired
fun DBWriter(userRepository: UserRepository){
this.userRepository = userRepository
}
#Throws(Exception::class)
override fun write(users: MutableList<out User>) {
println("Data Saved for Users: $users")
userRepository.saveAll(users)
}
}
itemprocessor.kt
package com.nilmani.literalmission.batch
import com.nilmani.literalmission.model.User
import org.springframework.batch.item.ItemProcessor
import org.springframework.stereotype.Component
import java.util.*
import kotlin.collections.HashMap
#Component
class Processor : ItemProcessor<User,User> {
private val DEPT_NAMES: MutableMap<String, String> = HashMap()
fun Processor() {
DEPT_NAMES["100"] = "Technology"
DEPT_NAMES["102"] = "Operations"
DEPT_NAMES["103"] = "Accounts"
DEPT_NAMES["104"] = "Devloper"
}
#Throws(Exception::class)
override fun process(user: User): User? {
val deptCode:String=user.dept
val dept=DEPT_NAMES[deptCode]
if (dept != null) {
user.dept = dept
}
user.time= Date()
println(String.format("Converted from [%s] to [%s]", deptCode, dept))
return user
}
}
LoadController.kt
package com.nilmani.literalmission.controller
import org.springframework.batch.core.*
import org.springframework.batch.core.launch.JobLauncher
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException
import org.springframework.batch.core.repository.JobRestartException
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
#RestController
#RequestMapping("/load")
class LoadController {
#Autowired
private lateinit var jobLauncher: JobLauncher
#Autowired
private lateinit var job:Job
#GetMapping
#Throws(
JobParametersInvalidException::class,
JobExecutionAlreadyRunningException::class,
JobRestartException::class,
JobInstanceAlreadyCompleteException::class
)
fun load(): BatchStatus {
val maps: MutableMap<String, JobParameter> = HashMap()
maps["time"] = JobParameter(System.currentTimeMillis())
val parameters = JobParameters(maps)
val jobExecution: JobExecution = jobLauncher.run(job, parameters)
System.out.println("JobExecution: " + jobExecution.status)
println("Batch is Running...")
while (jobExecution.isRunning) {
println("...")
}
return jobExecution.status
}
}
User.kt
package com.nilmani.literalmission.model
import java.util.*
import javax.persistence.Entity
import javax.persistence.Id
#Entity
data class User(
#Id
val id:Long=0,
val name:String="",
var dept:String="",
val salary:String="",
var time:Date
)
I added every thing properly how I get this type of issue
I added all the gradel depedency ,I donot know where I make mistakes I
provide all the database connection releated stuff
Here my database connection details
spring:
datasource:
url: jdbc:mysql://localhost:3306/login
driverClassName: com.mysql.cj.jdbc.Driver
username: root
password:
jpa:
database-platform: org.hibernate.dialect.MySQL5Dialect
show-sql: true
hibernate:
ddl-auto: update
According to the error Table 'login.batch_job_instance' doesn't exist, you need to create Spring Batch tables in the database before running your job.
You can do that either manually by execution the DDL script for MySQL, or if you use Spring Boot, set the property spring.batch.initialize-schema=always.
I need to set cookie and store cookie - key, value and timestamp in MYSQL.
Hence, i have a CookieUtil.java to set(addCookie) and get cookie. Then I created a CookieEntity.java and mapped it with a DAO layer - interface and implementation. I have nullpointer at int noOfRows = namedParameterJdbcTemplate.update(SQL,namedParameters);.
It seems namedParameterJdbcTemplate is null. But I really can't figure out why?
CookieEntity.java
import java.sql.Timestamp;
public class EWPCookieEntity {
private String key;
private String value;
private Timestamp timeStamp;
//.... setters and getters
}
CookieDao.java interface
public boolean saveCookie(CookieEntity reqCookie);
CookieDaoImpl.java
package com......dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import com......CookieDao;
import com......CookieEntity;
#Repository
public class CookieDaoImpl implements CookieDao{
#Autowired(required=false)
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
private String FETCH_USER_DETAILS_QUERY = "fetch.user.query";
private static Logger logger = Logger.getLogger(CookieDaoImpl.class.getName());
#Override
public boolean saveCookie(CookieEntity reqCookie) {
String SQL = "insert into cookie_details(KEY, VALUE, TIMESTAMP) VALUES (:key, :value, :timeStamp)";
Map<String,String > namedParameters = new HashMap<String, String>();
namedParameters.put("key", reqCookie.getKey());
namedParameters.put("value", reqCookie.getValue());
//namedParameters.put("timeStamp", reqCookie.getTimeStamp());
int noOfRows = namedParameterJdbcTemplate.update(SQL,namedParameters);
System.out.println(noOfRows);
logger.info("Cookie Details Saved: [ " + reqCookie.toString() + " ]");
return noOfRows > 0 ? true : false;
}
#Override
public List<CookieEntity> getCookieValue(String key) {
return null;
}
#Override
public int deleteCookie(String key) {
return 0;
}
#SuppressWarnings("unused")
private void mapFromCookieDetailsResultSet(final CookieEntity cookieEntity, final ResultSet resultSet) {
try {
cookieEntity.setKey(resultSet.getString("KEY"));
cookieEntity.setValue(resultSet.getString("VALUE"));
cookieEntity.setTimeStamp(resultSet.getTimestamp("TIMESTAMP"));
} catch (SQLException se) {
if (logger.isDebugEnabled()) {
logger.debug(
"**** Class UserDetailsDaoImpl **** Method mapFromUserDetailsResultSet **** SQLException Occured : "
+ se.getMessage());
}
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug(
"**** Class UserDetailsDaoImpl **** Method mapFromUserDetailsResultSet **** Exception Occured : "
+ e.getMessage());
}
}
}
/**
* #param namedParameterJdbcTemplate the namedParameterJdbcTemplate to set
*/
public void setNamedParameterJdbcTemplate(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}
}
My stacktrace is:
SEVERE: Servlet.service() for servlet [SimulatorServlet] in context with path [/abc]
threw exception [Request processing failed; nested exception
java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com....CookieDaoImpl.saveCookie(CookieDaoImpl.java:36)
at com......LoginController.doLogin(LoginController.java:69)
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:498)
My root_context.xml
<!-- JdbcTemplate -Starts -->
<bean id = "jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate">
<property name="fetchSize" value = "100"/>
<property name="dataSource" ref = "appDataSource"/>
</bean>
<!-- JdbcTemplate -Ends -->
<!-- NamedParameterJdbcTemplate -Starts -->
<bean id = "namedParameterJdbcTemplate" class = "org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="jdbcTemplate"/>
</bean>
<!-- NamedParameterJdbcTemplate -ends -->
You can add <context:annotation-config /> in your root_context.xml to get #Autowired working.
Or you add <context:component-scan base-package="your.package"/> in root_context.xml if you plan to use annotations like #Service, #Component etc. The latter one has the first one already included.
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);
}
Im trying to run a mapreduce program in hadoop. Basically it takes in a text file as input in which each line is a json text. Im using simple json to parse this data in my mapper and the reducer does some other stuff. I have included the simple json jar file in hadoop/lib folder. here is the code below
package org.myorg;
import java.io.IOException;
import java.util.Iterator;
import java.util.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
public class ALoc
{
public static class AMapper extends Mapper<Text, Text, Text, Text>
{
private Text kword = new Text();
private Text vword = new Text();
JSONParser parser = new JSONParser();
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException{
try {
String line = value.toString();
Object obj = parser.parse(line);
JSONObject jsonObject = (JSONObject) obj;
String val = (String)jsonObject.get("m1") + "," + (String)jsonObject.get("m3");
kword.set((String)jsonObject.get("m0"));
vword.set(val);
context.write(kword, vword);
}
catch (IOException e) {
e.printStackTrace();
}
catch (ParseException e) {
e.printStackTrace();
}
}
}
public static class CountryReducer
extends Reducer<Text,Text,Text,Text>
{
private Text result = new Text();
public void reduce(Text key, Iterable<Text> values,
Context context
) throws IOException, InterruptedException
{
int ccount = 0;
HashMap<Text, Integer> hm = new HashMap<Text, Integer>();
for (Text val : values)
{
if(hm.containsKey(val)){
Integer n = (Integer)hm.get(val);
hm.put(val, n+1);
}else{
hm.put(val, new Integer(1));
}
}
Set set = hm.entrySet();
Iterator i = set.iterator();
String agr = "";
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
agr += "|" + me.getKey() + me.getValue();
}
result.set(agr);
context.write(key, result);
}
}
public static void main(String[] args) throws Exception
{
Configuration conf = new Configuration();
Job job = new Job(conf, "ALoc");
job.setJarByClass(ALoc.class);
job.setMapperClass(AMapper.class);
job.setReducerClass(CountryReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.setInputFormatClass(TextInputFormat.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
When I try to run the job. It gives the following error.
I am running this in a aws micro instance single node.
I have been following this tutorial http://www.michael-noll.com/tutorials/running-hadoop-on-ubuntu-linux-single-node-cluster/
hadoop#domU-18-11-19-02-92-8E:/$ bin/hadoop jar ALoc.jar org.myorg.ALoc /user/hadoop/adata /user/hadoop/adata-op5 -D mapred.reduce.tasks=16
13/02/12 08:39:50 WARN mapred.JobClient: Use GenericOptionsParser for parsing the arguments. Applications should implement Tool for the same.
13/02/12 08:39:50 INFO input.FileInputFormat: Total input paths to process : 1
13/02/12 08:39:50 INFO util.NativeCodeLoader: Loaded the native-hadoop library
13/02/12 08:39:50 WARN snappy.LoadSnappy: Snappy native library not loaded
13/02/12 08:39:51 INFO mapred.JobClient: Running job: job_201302120714_0006
13/02/12 08:39:52 INFO mapred.JobClient: map 0% reduce 0%
13/02/12 08:40:10 INFO mapred.JobClient: Task Id : attempt_201302120714_0006_m_000000_0, Status : FAILED
java.lang.RuntimeException: Error while running command to get file permissions : java.io.IOException: Cannot run program "/bin/ls": java.io.IOException: error=12, Cannot allocate memory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:475)
at org.apache.hadoop.util.Shell.runCommand(Shell.java:200)
at org.apache.hadoop.util.Shell.run(Shell.java:182)
at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:375)
at org.apache.hadoop.util.Shell.execCommand(Shell.java:461)
at org.apache.hadoop.util.Shell.execCommand(Shell.java:444)
at org.apache.hadoop.fs.FileUtil.execCommand(FileUtil.java:710)
at org.apache.hadoop.fs.RawLocalFileSystem$RawLocalFileStatus.loadPermissionInfo(RawLocalFileSystem.java:443)
at org.apache.hadoop.fs.RawLocalFileSystem$RawLocalFileStatus.getOwner(RawLocalFileSystem.java:426)
at org.apache.hadoop.mapred.TaskLog.obtainLogDirOwner(TaskLog.java:267)
at org.apache.hadoop.mapred.TaskLogsTruncater.truncateLogs(TaskLogsTruncater.java:124)
at org.apache.hadoop.mapred.Child$4.run(Child.java:260)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:416)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1121)
at org.apache.hadoop.mapred.Child.main(Child.java:249)
Caused by: java.io.IOException: java.io.IOException: error=12, Cannot allocate memory
at java.lang.UNIXProcess.<init>(UNIXProcess.java:164)
at java.lang.ProcessImpl.start(ProcessImpl.java:81)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:468)
... 15 more
at org.apache.hadoop.fs.RawLocalFileSystem$RawLocalFileStatus.loadPermissionInfo(RawLocalFileSystem.java:468)
at org.apache.hadoop.fs.RawLocalFileSystem$RawLocalFileStatus.getOwner(RawLocalFileSystem.java:426)
at org.apache.hadoop.mapred.TaskLog.obtainLogDirOwner(TaskLog.java:267)
at org.apache.hadoop.mapred.TaskLogsTruncater.truncateLogs(TaskLogsTruncater.java:124)
at org.apache.hadoop.mapred.Child$4.run(Child.java:260)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:416)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1121)
at org.apache.hadoop.mapred.Child.main(Child.java:249)
I guess you must be trying hadoop on Micro instance which have very less memory (~700MB).
Try increasing the HADOOP Heapsize parameter (in hadoop/conf/hadoop-env.sh) .. as the basic reason is shortage of memory required to fork processes
I manage to solve this problem getting hint from post stackoverflow post about GWT. The post tells that as JDBC shouldn'e be on client side, rather on server side.
I am trying to make a simple web application that adds a user to database using GWT RPC with Hibernate, MySql & eclipse IDE. I have already a simple version of hibernate program running & now I am trying to do same using GWT RPC.
Though probably there are certain different practices when using hibernate with RPC. Firstly I had to put jars/libs to war/web.inf/lib add before adding them to classpath, while I made a simple folder in src, put all jars/libraries to that & then added to classpath for simple hibernate app. It continues, compiler then raised error about unavailability of cfg.xml & mapping files which were in the hibernate files package(that contain pojo files). I moved them to src folder & error gone. But now error is about session creation. This time moving Util file to src did not work.
This is directory structure of my project:
src
hbm.xml
cfg.xml
hibDomain(hibernate package)
rppctest.client (GWT package)
rppctest.server (GWT package)
I am using MySQL on Windows 7.
Here are the error messages & my code.
errors
94 [btpool0-2] INFO org.hibernate.cfg.Environment - Hibernate 3.3.1.GA
126 [btpool0-2] INFO org.hibernate.cfg.Environment - hibernate.properties not found
173 [btpool0-2] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
282 [btpool0-2] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
751 [btpool0-2] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
751 [btpool0-2] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
3657 [btpool0-2] INFO org.hibernate.cfg.Configuration - Reading mappings from resource : user.hbm.xml
4018 [btpool0-2] INFO org.hibernate.cfg.HbmBinder - Mapping class: com.hib.User -> users
Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource user.hbm.xml
Starting Jetty on port 8888
[WARN] Exception while dispatching incoming RPC call
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract java.lang.String rpctest.client.RpctestService.addUser(java.lang.String,java.lang.String) throws java.lang.IllegalArgumentException' threw an unexpected exception: java.lang.ExceptionInInitializerError
at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java:385)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:588)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:324)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:205)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
Caused by: java.lang.ExceptionInInitializerError
at hibDomain.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
at hibDomain.HibernateUtil.<clinit>(HibernateUtil.java:7)
at rpctest.server.RpctestServiceImpl.addUser(RpctestServiceImpl.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569)
... 22 more
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from resource user.hbm.xml
at org.hibernate.cfg.Configuration.addResource(Configuration.java:602)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1621)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1589)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1568)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1542)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1462)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1448)
at hibDomain.HibernateUtil.buildSessionFactory(HibernateUtil.java:11)
... 29 more
Caused by: org.hibernate.MappingException: class com.hib.User not found while looking for property: firstName
at org.hibernate.util.ReflectHelper.reflectedPropertyClass(ReflectHelper.java:97)
at org.hibernate.mapping.SimpleValue.setTypeUsingReflection(SimpleValue.java:302)
at org.hibernate.cfg.HbmBinder.createProperty(HbmBinder.java:2193)
at org.hibernate.cfg.HbmBinder.createClassProperties(HbmBinder.java:2170)
at org.hibernate.cfg.HbmBinder.createClassProperties(HbmBinder.java:2060)
at org.hibernate.cfg.HbmBinder.bindRootPersistentClassCommonValues(HbmBinder.java:381)
at org.hibernate.cfg.HbmBinder.bindRootClass(HbmBinder.java:295)
at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:166)
at org.hibernate.cfg.Configuration.add(Configuration.java:702)
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:537)
at org.hibernate.cfg.Configuration.addResource(Configuration.java:599)
... 36 more
Caused by: java.lang.ClassNotFoundException: com.hib.User
at java.lang.ClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:352)
at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:337)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at org.hibernate.util.ReflectHelper.classForName(ReflectHelper.java:123)
at org.hibernate.util.ReflectHelper.reflectedPropertyClass(ReflectHelper.java:93)
... 46 more
[ERROR] 500 - POST /rpctest/testService (127.0.0.1) 57 bytes
Request headers
Accept: */*
X-GWT-Permutation: HostedMode
X-GWT-Module-Base: http://127.0.0.1:8888/rpctest/
Content-Type: text/x-gwt-rpc; charset=utf-8
Referer: http://127.0.0.1:8888/Rpctest.html?gwt.codesvr=127.0.0.1:9997
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Host: 127.0.0.1:8888
Content-Length: 168
Connection: Keep-Alive
Cache-Control: no-cache
Response headers
Content-Type: text/plain
entry point class
package rpctest.client;
import rpctest.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Rpctest implements EntryPoint {
final TextBox firstName = new TextBox();
final TextBox lastName = new TextBox();
final Button ans = new Button("Add User");
final Label label1 = new Label("First Name");
final Label label2 = new Label("Last Name");
//final Label errorLabel = new Label();
private VerticalPanel mainpanel = new VerticalPanel();
private HorizontalPanel addpanel1 = new HorizontalPanel();
private HorizontalPanel addpanel2 = new HorizontalPanel();
private final RpctestServiceAsync calNumbers = GWT
.create(RpctestService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
addpanel1.add(label1);
addpanel1.add(firstName);
addpanel2.add(label2);
addpanel2.add(lastName);
mainpanel.add(addpanel1);
mainpanel.add(addpanel2);
mainpanel.add(ans);
ans.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
String name1 = firstName.getValue();
String name2 = lastName.getValue();
calNumbers.addUser(name1,name2,
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
Window.alert("check your inputs");
}
#Override
public void onSuccess(String result) {
// TODO Auto-generated method stub
Window.alert("User is ->"+result);
}
});}
});
// We can add style names to widgets
//sendButton.addStyleName("sendButton");
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
/*RootPanel.get("nameFieldContainer").add(nameField);
*
RootPanel.get("sendButtonContainer").add(sendButton);
RootPanel.get("errorLabelContainer").add(errorLabel);*/
RootPanel.get().add(mainpanel);
}
}
interfaces
package rpctest.client;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
#RemoteServiceRelativePath("testService")
public interface RpctestService extends RemoteService {
String addUser(String firstName,String lastName) throws IllegalArgumentException;
}
package rpctest.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface RpctestServiceAsync {
void addUser(String firstName, String lastName,
AsyncCallback<String> callback);
}
Implementation
package rpctest.server;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import hibDomain.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import hibDomain.User;
import hibDomain.Task;
import rpctest.client.RpctestService;
public class RpctestServiceImpl extends RemoteServiceServlet implements RpctestService {
public String addUser(String name1, String name2)
throws IllegalArgumentException {
Transaction trns = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try {
trns = session.beginTransaction();
User user = new User();
user.setFirstName(name1);
user.setLastName(name2);
session.save(user);
session.getTransaction().commit();
} catch (RuntimeException e) {
if(trns != null){
trns.rollback();
}
e.printStackTrace();
} finally{
session.flush();
session.close();
}
return name1;
}
}
Hibernate files
package hibDomain;
public class User {
private Integer id;
private String firstName;
private String lastName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
mapping file
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.hib.User" table="users" >
<id name="id" type="int" column="id" >
<generator class="native"/>
</id>
<property name="firstName">
<column name="first_name" />
</property>
<property name="lastName">
<column name="last_name"/>
</property>
</class>
</hibernate-mapping>
cfg file
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/userdata</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="user.hbm.xml"/>
<mapping resource="task.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Util
package hibDomain;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Your hibernate class file (User) is in "hibDomain" package. where as the mapping you are making is for "com.hib.User". change this to hibDomain.User and it might work.