Integrate Hibernate into JSF project with Glassfish server - eclipse

I am using GlassFish server in Eclipse and am trying to intergerate the hibernate-release-5.1.0.Final into the JSF project. I have tried several steps but without seccuss.
I have Placed the Hibernate Jars inside the GlassFisch directrory glassfish4\bin and restarted the server.
I placed them inside the following foloder glassfish4\glassfish\bin and restarted the GlassFisch server.
I placed the Hibernate jars inside the WEB-INF/lib
I added this part .addResource("/resources/person.hbm.xml") to the CreatePersonDemo class.
I replaced the jboss-logging.jar inside the glassfish4\glassfish\modules directory with jboss-logging-3.3.0.Final.jar
CreatePersonDemo
package com.backing;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.model.Person;
public class CreatePersonDemo {
public static void main(String[] args) {
// create session factory.
// SessionFactory factory = new Configuration()
// .configure("/resources/hibernate.cfg.xml")
// .addAnnotatedClass(Person.class)
// .buildSessionFactory();
SessionFactory factory = new Configuration().configure("/resources/hibernate.cfg.xml")
.addResource("/resources/person.hbm.xml")
.addAnnotatedClass(Person.class)
.buildSessionFactory();
// create a session.
Session session = factory.getCurrentSession();
System.out.println("CreateStudentDemo");
}
}
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/GMapsYahooMeshup</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="current_session_context_class">thread</property>
<mapping resource="resources/person.hbm.xml" />
<!-- <mapping class ="com.Model.Person" /> -->
</session-factory>
</hibernate-configuration>
person.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Person" table="person">
<meta attribute="class-description">
This class contains the person detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native" />
</id>
<property name="full_name" column="full_name" type="string" />
<property name="email " column="email " type="string" />
<property name="location" column="location" type="string" />
<property name="pwd" column="pwd" type="string" />
</class>
</hibernate-mapping>
Person.Java
package com.model;
public class Person {
private int id;
private String full_name;
private String email;
private String location;
private String pwd;
public Person(int id, String full_name, String email, String location, String pwd) {
super();
this.id = id;
this.full_name = full_name;
this.email = email;
this.location = location;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFull_name() {
return full_name;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
Error
org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Jul 17, 2016 10:24:52 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Exception in thread "main" java.lang.NoSuchMethodError: org.hibernate.internal.CoreMessageLogger.debugf(Ljava/lang/String;I)V
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:34)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.<init>(PooledConnections.java:19)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections$Builder.build(PooledConnections.java:138)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.buildPool(DriverManagerConnectionProviderImpl.java:110)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:74)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:208)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:692)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at com.backing.CreatePersonDemo.main(CreatePersonDemo.java:22)
Project structure

Related

Transactional CDI bean not committing record to database

I am trying to build a simple REST service, using JAX-RS, that will perform the standard CRUD operations on a database table. I am able to successfully query for records, but I cannot insert new ones. I do not get any errors and when I step through the code in debug mode everything looks good. I am using a transactional CDI bean running in a Glassfish 4.1 container.
It feels like it's just never committing the transaction. I'm pretty new to Java EE, but my understanding is that since the bean is transactional the container should handle the commit for me. Anyone know why it is not?
#Path("/recipes")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public class RecipeResource {
#Inject
RecipesService recipesService;
#GET
public List<Recipe> getRecipes() {
return recipesService.getAllRecipes();
}
#POST
public void addRecipse(Recipe recipe) {
recipesService.addRecipe(recipe);
}
}
public class RecipesService {
#PersistenceContext(unitName="PANTRYDB", type=PersistenceContextType.TRANSACTION)
EntityManager em;
public RecipesService () {
}
public List<Recipe> getAllRecipes () {
List<Recipe> recipes = null;
try {
TypedQuery<Recipe> typedQuery = em.createQuery("select r from Recipe r", Recipe.class);
recipes = typedQuery.getResultList();
} catch (Exception e) {
System.out.println(e);
}
return recipes;
}
#Transactional
//This is the method that seems to not commit it's transaction
//The Recipe object is populated correctly, and the persist() doesn't
//throw any errors
public void addRecipe(Recipe recipe) {
try {
em.persist(recipe);
} catch (Exception e) {
System.out.println(e);
}
}
}
#Entity
#Table(name="RECIPES", schema="COOKBOOK")
public class Recipe {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column
private String name;
#Column(name="CREATED_DATE")
private Calendar createdDate;
#Column(name="LAST_MADE_DATE")
private Calendar lastMadeDate;
#Column
private String description;
#Column
private String notes;
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Calendar getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Calendar createdDate) {
this.createdDate = createdDate;
}
public Calendar getLastMadeDate() {
return lastMadeDate;
}
public void setLastMadeDate(Calendar lastMadeDate) {
this.lastMadeDate = lastMadeDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
#Override
public String toString() {
return name;
}
}
Persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="PANTRYDB" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.domain.Recipe</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:derby:/Users/development/eclipse/ws_playground/databases/pantry_db/PANTRYDB" />
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect"/>
<property name="javax.persistence.jdbc.user" value=""/>
<property name="javax.persistence.jdbc.password" value=""/>
</properties>
</persistence-unit>
</persistence>
I tried your application on a weblogic 12.2.1 and it successfully inserted in database and i do not have any problem with transaction.
Here is my code.
RecipeResource class (I modified the #Path to call it via web browser and also instanciated the Recipe manually):
#Path("/recipes")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public class RecipeResource {
#Inject
RecipesService recipesService;
#GET
#Path("get")
public List<Recipe> getRecipes() {
return recipesService.getAllRecipes();
}
#GET
#Path("add")
public String addRecipse() {
Recipe recipe = new Recipe();
recipe.setDescription("desc");
recipesService.addRecipe(recipe);
return "OK";
}
}
The Recipe class is same as yours except that i commented the schema :
#Entity
#Table(name="RECIPES") //, schema="COOKBOOK")
public class Recipe {
}
My persistence.xml (I'm using in-memory database):
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns /persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="PANTRYDB" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/__default</jta-data-source>
<class>org.jvi.webservice.transactional.db.Recipe</class>
<properties>
<!--<property name="eclipselink.ddl-generation" value="create-tables"/>-->
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
<property name="eclipselink.logging.level" value="FINE"/>
<property name="eclipselink.logging.level.sql" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
<property name="eclipselink.logging.logger" value="DefaultLogger"/>
<property name="eclipselink.cache.shared.default" value="false"/>
</properties>
</persistence-unit>
So your problem might come from the Application Server.
Did you try to deploy your webapp on another server?
When you are using JTA transaction management, responsibility for creating and managing database connections is provided by application server, not your application.
Basically, you have to configure your data source in your GlassFish server instance, not directly in persistence.xml via properties:
Configure connection pool and datasource JNDI name in your GlassFish server instance
Link data source configuration in your persistence.xml via <jta-data-source> element
Please check this answer for further details:
https://stackoverflow.com/a/9137741/1980178
Are you sure you are not mixing two frameworks. RecipeResource has a #Path annotation which is from the JavaEE framework, and the #Transactional annotation is from the Spring framework, I think you should replace it with #TransactionAttribute which is the equivalent JavaEE anotation.
Have a look here for details between transaction in Spring an JavaEE

no suitable HttpMessageConverter found for response type [com.src.model.UserDTO] and content type [text/html;charset=UTF-8]

first of all, i've already read all questions related with this topic in stackoverflow, but i can't find the solution. I have been working on this for days.
I have this restFull web app built with spring mvc. When i try to retrieve a User i get this error:
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [com.src.model.UserDTO] and content type [text/html;charset=UTF-8]
org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessag eConverterExtractor.java:84)
org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:627)
org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:1)
org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:454)
org.springframework.web.client.RestTemplate.execute(RestTemplate.java:409)
org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:385)
com.src.web.controller.HomeController.getHome(HomeController.java:42)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:100)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:604)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:565)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
The request never reach the server, so the problem isn't the response content-type, because there is no response. So i am loss there. I show here my classes and configs, if some info is missed, please let me know, and i will update the question. Thanks!
Client controller:
#Controller
public class HomeController extends GenericAbstractController{
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String getHome(HttpServletRequest request, Model model) {
Principal userPrincipal = request.getUserPrincipal();
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_XML);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
headers.setAccept(acceptableMediaTypes);
HttpEntity<UserDTO> entity = new HttpEntity<UserDTO>(headers);
ResponseEntity<UserDTO> result = restTemplate.exchange("http://localhost:8080/rideon/users/{id}",
HttpMethod.GET, entity, UserDTO.class, userPrincipal.getName());
model.addAttribute("user", result.getBody());
return "home";
}
Server controller:
#Controller
public class UsersController {
private static final Logger LOGGER = LoggerFactory.getLogger(UsersController.class);
#Autowired
private UserService userService;
#RequestMapping(value = "users/{id}", method = RequestMethod.GET, headers = "Accept=application/xml")
#ResponseBody
public UserDTO getUser(#PathVariable("id") String id) {
return userService.getUserById(id);
}
User:
#XmlRootElement
#Entity(name = "users")
public class UserDTO implements Serializable {
#Id
private String email;
private String password;
private String name;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Application-context:
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<bean id="marshallingHttpMessageConverter"
class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="jaxbMarshaller" />
<property name="unmarshaller" ref="jaxbMarshaller" />
</bean>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" />
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.src.model.UserDTO</value>
<value>com.src.model.MultimediaDTO</value>
<value>com.src.model.BicycleDTO</value>
<value>com.src.model.FriendshipRequestDTO</value>
</list>
</property>
</bean>
Dependencies:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.9</version>
<scope>runtime</scope>
</dependency>
Ok I finally found the problem. The response is actually an html error page generated by a wrong security configuration. Indeed the above code seems to be ok. Thanks!

RestTemplate POST a Collection

Ok here iam back to find a solution.
Iam trying Spring RestTemplate postForEntity method to send a Collection of instances. When attempting spring gives an error org.springframework.http.converter.HttpMessageNotWritableException: Could not write request: no suitable HttpMessageConverter found for request type [com.abc.base.domai
n.dto.gift.GiftItemList Appriciate, if someone can tells me how to send a an ArrayList with spring resttemplate POST method.
RestTemplate bean:
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg ref="httpClientFactory"/>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
<bean id="jsonViewResolver" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >
<property name="objectMapper">
<ref bean="JacksonObjectMapper" />
</property>
<property name="supportedMediaTypes">
<list>
<bean class="org.springframework.http.MediaType">
<constructor-arg value="application" />
<constructor-arg value="json" />
<constructor-arg value="#{T(java.nio.charset.Charset).forName('UTF-8')}"/>
</bean>
</list>
</property>
</bean>
</list>
</property>
</bean>
<bean id="JacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="httpClient" class="org.apache.commons.httpclient.HttpClient">
<constructor-arg ref="httpClientParams"/>
</bean>
<bean id="httpClientParams" class="org.apache.commons.httpclient.params.HttpClientParams">
<property name="connectionManagerClass" value="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager"/>
</bean>
<bean id="httpClientFactory" class="org.springframework.http.client.CommonsClientHttpRequestFactory">
<constructor-arg ref="httpClient"/>
</bean>
Instance that iam trying to POST,
public class GiftItem implements Entity, Serializable {
private static final long serialVersionUID = 1L;
private String redeemLocation;
private String itemName;
private String itemDescription;
private String merchantName;
private Integer quantity;
private Integer imageId;
public GiftItem() {
super();
}
//with getters and setters
}
GiftItem instance wraaper class
public class GiftItemList implements Serializable {
private static final long serialVersionUID = -8202204714984099030L;
public GiftItemList() {
}
private List<GiftItem> giftItemList;
public List<GiftItem> getGiftItemList() {
return giftItemList;
}
public void setGiftItemList(List<GiftItem> giftItemList) {
this.giftItemList = giftItemList;
}
}
this is how i use it,
public BaseResponse sendGiftEmail(final String token, final User sender,final String message, final GiftItemList giftItemList) {
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("token", token);
map.add("sender", sender);
map.add("message", message);
map.add("giftItemList", giftItemList);
return getRestTemplate().postForEntity(
"http://localhost:8080/notification/api/notification/send_gift_email",
map, BaseResponse.class).getBody();
}
and the error i am getting,
org.springframework.http.converter.HttpMessageNotWritableException: Could not write request: no suitable HttpMessageConverter found for request type [com.abc.base.domain.dto.gift.GiftItemList]
at org.springframework.http.converter.FormHttpMessageConverter.write Part(FormHttpMessageConverter.java:310)
at org.springframework.http.converter.FormHttpMessageConverter.write Parts(FormHttpMessageConverter.java:270)
at org.springframework.http.converter.FormHttpMessageConverter.write Multipart(FormHttpMessageConverter.java:260)
at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:200)
at org.springframework.http.converter.FormHttpMessageConverter.write(FormHttpMessageConverter.java:1)
at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:588)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:436)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:401)
at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:302)
at com.tapgift.gift.client.impl.GiftClientImpl.sendGiftNotifications(GiftClientImpl.java:101)
pom:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.2</version>
</dependency>
almost forgot receiver controller,
#RequestMapping(value = "/notification/send_gift_email", method = RequestMethod.POST)
public #ResponseBody BaseResponse sendGiftEmail(#RequestParam("token") String token, #RequestParam("sender")final User sender, #RequestParam("message")final String message,#RequestParam("giftItemList") GiftItemList giftItemList) {
}
You have to add MappingJacksonHttpMessageConveter to your messageCoverter :
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new FormHttpMessageConverter());
messageConverters.add(new StringHttpMessageConverter());
messageConverters.add(new MappingJacksonHttpMessageConverter());
restTemplate = new RestTemplate();
restTemplate.setMessageConverters(messageConverters);
You also need to add the dependency for :
jackson-core-asl-x.x.x.jar & jaackson.mapper.asl-x.x.x.jar
Another thing, you have to make sure that your class have the same attribute as your JSON properties. For example :
{"data":{"ticket":"TICKET_870299cf98e227abdbd5f9b7064390c5723a0c6a"}}
To fill your class properties, they have to be like this :
person.java
public class person {
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
data.java
public class Data {
private String ticket;
public String getTicket() {
return ticket;
}
public void setTicket(String ticket) {
this.ticket = ticket;
}
}
Finaly in your application your add :
person entity = restTemplate.postForObject(url, requestEntity,
person.class);
requestEntity is a String that contains your request body (JSON in my case).
Hope that helped !

no persistence provider for entitymanager named - tried everything

I'm new to JPA, and i got this infamous error "no persistence provider for entitymanager named". I search far and wide on google, and tried every single solution available, to no extent i'm afraid.
Stack Trace
javax.persistence.PersistenceException: No Persistence provider for EntityManager named suplink
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
at com.supinfo.suplink.util.PersistenceManager.getEntityManagerFactory(PersistenceManager.java:13)
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="suplink" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/SupLink" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
</properties>
<class>com.supinfo.suplink.entity.User</class>
</persistence-unit>
PersistenceManager
public class PersistenceManager {
private static EntityManagerFactory emf;
private PersistenceManager() { }
public static EntityManagerFactory getEntityManagerFactory() {
if(emf == null) {
emf = Persistence.createEntityManagerFactory("suplink");
}
return emf;
}
public static void closeEntityManagerFactory() {
if(emf != null && emf.isOpen()) emf.close();
}
}
Thanks for your help :)
try to remove the transaction-type="RESOURCE_LOCAL"
works on my machine without this code
Good luck for your graded exercise, try code underneath ;)
public class PersistenceManager {
private static final EntityManagerFactory emf;
private static final ThreadLocal<EntityManager> threadLocal;
private static final Logger logger;
static {
emf = Persistence.createEntityManagerFactory("SupLink");
threadLocal = new ThreadLocal<EntityManager>();
logger = Logger.getLogger("SupLink");
logger.setLevel(Level.ALL);
}
public static EntityManager getEntityManager() {
EntityManager manager = threadLocal.get();
if (manager == null || !manager.isOpen()) {
manager = emf.createEntityManager();
threadLocal.set(manager);
}
return manager;
}
public static void closeEntityManager() {
EntityManager em = threadLocal.get();
threadLocal.set(null);
if (em != null)
em.close();
}
public static void beginTransaction() {
getEntityManager().getTransaction().begin();
}
public static void commit() {
getEntityManager().getTransaction().commit();
}
public static void rollback() {
getEntityManager().getTransaction().rollback();
}
public static Query createQuery(String query) {
return getEntityManager().createQuery(query);
}
public static void log(String info, Level level, Throwable ex) {
logger.log(level, info, ex);
}
}

Unable to instantiate Action, signupFormAction, defined for 'signupForm' in namespace '/'signupFormAction. ClassNotFoundException: signupFormAction

Been trying to setup a Struts2 + Sprint + Hibernate basic framework and was working on creating a sample application. Everything configured and the stack doesnt through any error/exception while starting tomcat. Even when I run the action it doesnt throw any Exception, but on the browser it throws the following stack
Unable to instantiate Action, signupFormAction, defined for 'signupForm' in namespace '/'signupFormAction
com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:318)
com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:399)
com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:198)
org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61)
org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:475)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
root cause
java.lang.ClassNotFoundException: signupFormAction
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491)
com.opensymphony.xwork2.util.ClassLoaderUtil.loadClass(ClassLoaderUtil.java:157)
com.opensymphony.xwork2.ObjectFactory.getClassInstance(ObjectFactory.java:107)
com.opensymphony.xwork2.spring.SpringObjectFactory.getClassInstance(SpringObjectFactory.java:223)
com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:143)
com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:150)
com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:120)
com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:299)
com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:399)
com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:198)
org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61)
org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:475)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
My struts.xml
<struts>
<!-- <constant name="struts.enable.DynamicMethodInvocation" value="false" />-->
<constant name="struts.devMode" value="false" />
<constant name="struts.custom.i18n.resources" value="ApplicationResources" />
<package name="default" extends="struts-default" namespace="/">
<action name="login" class="loginAction">
<result name="success">welcome.jsp</result>
<result name="error">login.jsp</result>
</action>
<action name="signup" class="registerAction" method="add">
<result name="success">welcome.jsp</result>
<result name="error">login.jsp</result>
</action>
<action name="signupForm" class="signupFormAction">
<result name="input">registerForm.jsp</result>
<result name="error">login.jsp</result>
</action>
</package>
</struts>
My SpringBeans.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- Database Configuration -->
<import resource="config/spring/DataSource.xml" />
<import resource="config/spring/HibernateSessionFactory.xml" />
<!-- Beans Declaration -->
<import resource="com/srisris/khiraya/spring/register.xml" />
<import resource="com/srisris/khiraya/spring/login.xml" />
</beans>
My register.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- <bean id="ownerService" class="com.srisris.khiraya.service.OwnerServiceImpl">-->
<!-- <property name="ownerDAO" ref="ownerDAO" />-->
<!-- </bean>-->
<bean id="signupForm" class="com.srisris.khiraya.action.RegisterAction"/>
<!-- <bean id="registerAction" class="com.srisris.khiraya.action.RegisterAction">-->
<!-- <property name="ownerService" ref="ownerService" /> -->
<!-- </bean>-->
<!-- <bean id="ownerDAO" class="com.srisris.khiraya.dao.OwnerDAOImpl" >-->
<!-- <property name="sessionFactory" ref="sessionFactory" />-->
<!-- </bean>-->
</beans>
My Action Class
package com.srisris.khiraya.action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.srisris.khiraya.dao.hibernate.Owner;
import com.srisris.khiraya.service.OwnerService;
#SuppressWarnings("rawtypes")
public class RegisterAction extends ActionSupport implements ModelDriven{
private static final long serialVersionUID = 6521996078347478542L;
private String ownerFirstName;
private String ownerLastName;
private String username;
private String password;
private String ownerPhone;
private String ownerEmail;
private OwnerService ownerService;
Owner owner = new Owner();
public void setOwnerService(OwnerService ownerService) {
this.ownerService = ownerService;
}
public String add() {
owner.setOwnerFirstName(ownerFirstName);
owner.setOwnerLastName(ownerLastName);
owner.setOwnerPassword(password);
owner.setOwnerPhone(ownerPhone);
owner.setOwnerEmail(ownerEmail);
ownerService.save(owner);
return SUCCESS;
}
public String execute() {
return INPUT;
}
public String getOwnerFirstName() {
return ownerFirstName;
}
public void setOwnerFirstName(String ownerFirstName) {
this.ownerFirstName = ownerFirstName;
}
public String getOwnerLastName() {
return ownerLastName;
}
public void setOwnerLastName(String ownerLastName) {
this.ownerLastName = ownerLastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getOwnerPhone() {
return ownerPhone;
}
public void setOwnerPhone(String ownerPhone) {
this.ownerPhone = ownerPhone;
}
public String getOwnerEmail() {
return ownerEmail;
}
public void setOwnerEmail(String ownerEmail) {
this.ownerEmail = ownerEmail;
}
public Object getModel() {
return owner;
}
}
I made a trivial mistake which costed me hours of pain. Silly me the problem was that my class name in struts.xml and id in register.xml were not matching and hence the issue.