exception in gwt hibernate program - eclipse

I am trying to make a simple GWT RPC Hibernate program that adds a user to MySQL database. I am using Eclipse EE. The application is successfully adding user to database but it raises exception when compiled.
Here is the exception & source of my application.
exception:
Exception in thread "UnitCacheLoader" java.lang.RuntimeException: Unable to read from byte cache
at com.google.gwt.dev.util.DiskCache.transferFromStream(DiskCache.java:166)
at com.google.gwt.dev.util.DiskCacheToken.readObject(DiskCacheToken.java:87)
at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
at java.io.ObjectInputStream.readSerialData(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at com.google.gwt.dev.javac.PersistentUnitCache.loadUnitMap(PersistentUnitCache.java:493)
at com.google.gwt.dev.javac.PersistentUnitCache.access$000(PersistentUnitCache.java:92)
at com.google.gwt.dev.javac.PersistentUnitCache$UnitCacheMapLoader.run(PersistentUnitCache.java:122)
Caused by: java.io.StreamCorruptedException: unexpected EOF in middle of data block
at java.io.ObjectInputStream$BlockDataInputStream.refill(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.read(Unknown Source)
at java.io.ObjectInputStream.read(Unknown Source)
at java.io.InputStream.read(Unknown Source)
at com.google.gwt.dev.util.DiskCache.transferFromStream(DiskCache.java:154)
... 16 more
entrypoint 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:
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);
}
service Implementation class:
package rpctest.server;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.hibernate.Session;
import org.hibernate.Transaction;
import hibDomain.User;
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;
}
}
pojo class:
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="hibDomain.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"/>
</session-factory>
</hibernate-configuration>
Util class:
package rpctest.server;
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;
}
}

This unlikely to be related to running out of disk space.
Much more likely you either built as a different user or for some other reason there are existing, invalid, temporary files which are causing the problem.
Look in your GWT dir for the directories "gwt-unitCache", and "reports". Delete them. Then run ant clean, ant test; that should solve the problem~
Almost certainly the reason it 'suddenly started worked' was you did something like a fresh git clone or cleared out the directory, deleting these files. :)

Delete ./src/main/gwt-unitCache.

You ran out of disk space.
GWT compiler could not find temp space.

Related

Having trouble getting JPA to work on Wildfly 19.1

I am fairly new to Wildfly and really new to JPA. I get a null exception when I try to call a method from the DAO. I made some changes suggested using the #Stateless and #Inject annotations, but the DAO does not appear to be initializing at all. The object is null when I try to call the findAllClientCompanies method.
Here is the peristence.xml file.
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="miscPU">
<jta-data-source>java:/jdbc/misc</jta-data-source>
<properties>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.transaction.flush_before_completion" value="true"/>
</properties>
</persistence-unit>
<persistence-unit name="autojobsPU">
<jta-data-source>java:/jdbc/autojobs</jta-data-source>
<properties>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.transaction.flush_before_completion" value="true"/>
</properties>
</persistence-unit>
</persistence>
Here is the entity declaration:
#Entity
#Table(name="clientcompany")
public class ClientCompany extends Company implements Serializable {
Here is the dao, the findAllClientCompanies is the specific method that is blowing up with a null exception:
package com.lingosys.jpa;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.Query;
import java.io.Serializable;
import java.util.List;
/**
*
* #author mphoenix
*/
#Stateless
public class ClientCompanyDAO implements Serializable {
#PersistenceContext(unitName="miscPU")
private EntityManager em;
public ClientCompanyDAO() {
}
public void create(ClientCompany clientCompany) {
em.persist(clientCompany);
}
public EntityTransaction getTransaction() {
return em.getTransaction();
}
public ClientCompany findClientCompany(int id) {
ClientCompany clientCompany = (ClientCompany) em.find(ClientCompany.class, id);
return clientCompany;
}
public List <ClientCompany> findAllClientCompanies() {
TypedQuery<ClientCompany> query = em.createQuery("select c from ClientCompany c", ClientCompany.class);
return query.getResultList();
}
public void delete(ClientCompany clientCompany) {
em.remove(em.contains(clientCompany) ? clientCompany:em.merge(clientCompany));
}
public int deleteAllClientCompanies() {
Query query = em.createQuery("delete from ClientCompany");
return query.executeUpdate();
}
}
And here is the JSF bean that calls the dao method:
#Inject
private ClientCompanyDAO daoClientCompany;
private boolean noValidEmail = false;
private String fakeEmailUserName = "";
private Connection conn;
private List<ClientCompany> unsortedList;
private String specialInstructions;
private String createdBy;
//XML processing variables
private Document document = null;
private String xmlMsgs = "";
private boolean xmlLoaderDisabled = false;
//prospect handling variables
private boolean prospectDisabled = false;
private static final String YES = "Yes";
//Legal entity based variables
boolean entitySet = false;
boolean lls = false;
boolean clientIDSet = false;
boolean billingInstructionsSet = false;
boolean billingEmailSet = false;
private static final String[] IS_LLS = {"LLS", "Coto/TI", "LLS-UK"};
boolean companyLoggedOn = false;
private boolean processDisabled = true;
private boolean userSpecificEntity = false;
/**
* Constructor initializes Web Service client, Hibernate DAOs, UI lists, and
* client view.
*
*/
public ClientCreatorBean() {
fmrws = new FormerWSOps();
try {
unsortedList = daoClientCompany.findAllClientCompanies();
view = fmrws.getClientCompanyView();
} catch (Exception ex) {
java.util.logging.Logger.getLogger(ClientCreatorBean.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
reset();
OK it looks like this problem had to do with my invoking the DAO in my constructor. I resolved it by putting the code in another method and prefacing that method with the #PostConstructor annotation.

Cannot load JDBC driver class 'org.postgresql.Driver'

I am facing this problem since 3-4 days and really don't know what to do....
Employee.java
package com.tutorialspoint.test;
public class Employee {
EmployeeManager employeeManager;
private String fname;
private String lname;
private int dob;
private String add;
private int id;
public void setfname(String fname){
this.fname=fname;
}
public String getfname(){
return fname;
}
public void setlname(String lname){
this.lname=lname;
}
public String getlname(){
return lname;
}
public void setdob(int dob){
this.dob=dob;
}
public int getdob(){
return dob;
}
public void setadd(String add){
this.add=add;
}
public String getadd() {
return add;
}
public void setid(int id){
this.id=id;
}
public int getid(){
return id;
}
public void setEmployeeManager(EmployeeManager employeeManager) {
this.employeeManager = employeeManager;
}
}
EmployeeDAO.java
package com.tutorialspoint.test;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.io.Serializable;
public class EmployeeDAO implements Serializable{
private static final long serialVersionUID = 1L;
private Employee employee;
private DataSource dataSource;
//SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource){
this.dataSource=dataSource;
this.jdbcTemplate = new JdbcTemplate(this.dataSource);
}
public int saveEmployee(Employee employee) {
String fname = employee.getfname();
String lname = employee.getlname();
int dob = employee.getdob();
String add = employee.getadd();
int id = employee.getid();
Object p[] = { fname, lname, dob, add, id };
String query = "insert into employee values(?,?,?)";
return this.jdbcTemplate.update(query, p);
}
/*
* public int deleteEmployee(int id){ String sql
* ="delete from employee where id = ?"; return
* this.jdbcTemplate.update(sql, new Object[]{new Integer(id)}); }
*/
public int delete() {
return this.jdbcTemplate.update("DELETE FROM employee WHERE id = ?",
new Object[] { employee.getid() });
}
public void setEmployee(Employee employee){
this.employee=employee;
}
public Employee getEmployee() {
return employee;
}
public List<Employee> getAllEmployee(Employee employee){
return this.jdbcTemplate.query("select * from employee",new RowMapper<Employee>(){
public Employee mapRow(ResultSet rs, int rownumber) throws SQLException {
Employee employee=new Employee();
employee.setfname(rs.getString(1));
employee.setlname(rs.getString(2));
employee.setdob(rs.getInt(3));
employee.setadd(rs.getString(4));
employee.setid(rs.getInt(5));
return employee;
}
});
}
}
> applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- Scan the com.itcuties.registration package for Spring -->
<context:component-scan base-package="com.tutorialspoint.test" />
<bean id="employee" class="com.tutorialspoint.test.Employee" >
</bean>
<bean id="em" class="com.tutorialspoint.test.EmployeeManager">
<property name="employee" ref="employee"></property>
<property name="edao" ref="edao"></property>
</bean>
<bean id="ds"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/testdb"/>
<property name="username" value="postgres"/>
<property name="password" value="postgres"/>
</bean>
<bean id="edao" class="com.tutorialspoint.test.EmployeeDAO">
<property name="employee" ref="employee"></property>
<property name="dataSource" ref="ds"></property>
</bean>
</beans>
stack
org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'org.postgresql.Driver'
javax.faces.el.EvaluationException: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'org.postgresql.Driver'
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:877)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:594)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1675)
at java.lang.Thread.run(Thread.java:662)
Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'org.postgresql.Driver'
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:80)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:573)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:812)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:868)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:876)
at com.tutorialspoint.test.EmployeeDAO.delete(EmployeeDAO.java:53)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.el.parser.AstValue.invoke(AstValue.java:130)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
... 20 more
Caused by: org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'org.postgresql.Driver'
at org.apache.commons.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1429)
at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77)
... 33 more
Caused by: java.lang.UnsupportedClassVersionError: org/postgresql/Driver : Unsupported major.minor version 51.0 (unable to load class org.postgresql.Driver)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2822)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1159)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1647)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:171)
at org.apache.commons.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1415)
... 37 more
Is this definition for jdbc connection in applicationContext.xml efficient or need some code....
Pratik, If you have a look at exception trace properly the root exception is UnsupportedClassVersionError.
Caused by: java.lang.UnsupportedClassVersionError: org/postgresql/Driver : Unsupported major.minor version 51.0 (unable to load class org.postgresql.Driver)
Which means that postgres jar which you have included in your project is not compatible with JDK/JVM version of your runtime. Make sure that you include jars which are compatible to your JDK/JVM environment version.

JBoss Embedded jUnit testing for EJB : NameNotFoundException

I'm newbie in EJB and jUnit, and I'm trying to do Embedded testing for the simple EJB-project that running by jBoss AS 7.1.1.Final.
I've written this test:
package com.staff.test.logic;
import java.io.File;
import javax.ejb.embeddable.EJBContainer;
import javax.naming.Context;
import javax.naming.NamingException;
import org.jboss.as.embedded.EmbeddedServerFactory;
import org.jboss.as.embedded.StandaloneServer;
import org.junit.Before;
import org.junit.Test;
import com.staff.main.logic.ProjectBean;
public class ProjectBeanTest {
private StandaloneServer server;
private static EJBContainer ec;
private static Context ctx;
#Before
public void initContainer() throws Exception {
String jbossHomeDir = System.getenv("JBOSS_HOME");
System.setProperty("jboss.home","C:/eclipse/jboss-as-7.1.1.Final");
assert jbossHomeDir != null;
server = EmbeddedServerFactory.create(new File(jbossHomeDir), System.getProperties(), System.getenv(), "org.jboss.logmanager");
server.start();
ctx=server.getContext();
}
// #After
// public static void closeContainer() throws Exception {
// if (ec != null) {
// ec.close();
// }
// }
#Test
public void test() throws NamingException {
ProjectBean bean = (ProjectBean) ctx.lookup("java:global/ProjectBean");
}
}
But string
ProjectBean bean = (ProjectBean) ctx.lookup("java:global/ProjectBean") make exception:
do this exception:
javax.naming.NameNotFoundException: ProjectBean -- service jboss.naming.context.java.global.ProjectBean
at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBa sedNamingStore.java:97)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java: 178)
at org.jboss.as.naming.InitialContext.lookup(InitialContext.jav a:123)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java: 214)
at javax.naming.InitialContext.lookup(Unknown Source)
at com.staff.test.logic.ProjectBeanTest.test(ProjectBeanTest.ja va:80)
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 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall( FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(Refl ectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(Fr ameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate( InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(Ru nBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271 )
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit 4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit 4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java: 63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java :236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java: 53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java: 229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.r un(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(Test Execution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTe sts(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTe sts(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(R emoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main( RemoteTestRunner.java:197)
I dont understand why this string do exception, because I'm newbie.
My project have a bean "ProjectBean" with interface "ProjectBeanLocal" and an entity "Post". And I have a file persistence.xml to work with Oracle 10g.
ProjectBean:
package com.staff.main.logic;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.ejb.Ejb3Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import com.staff.main.domain.Post;
/**
* Session Bean implementation class ProjectBean
*/
#Stateless
#LocalBean
public class ProjectBean implements ProjectBeanLocal {
#PersistenceContext(unitName="StaffPU")
EntityManager manager;
public ProjectBean()
{
Ejb3Configuration cfg = new Ejb3Configuration();
cfg.configure("StaffPU", null);
SchemaExport schemaExport = new SchemaExport(cfg.getHibernateConfiguration());
//schemaExport.setOutputFile("schema.sql");
schemaExport.create(true, true);
}
#Override
public void savePost(Post post){
manager.persist(post);
}
#Override
public Post findPost(long id) {
Post post=manager.find(Post.class, id);
return post;
}
}
Interface ProjectBeanLocal:
package com.staff.main.logic;
import javax.ejb.Local;
import com.staff.main.domain.Post;
#Local
public interface ProjectBeanLocal {
void savePost(Post post);
Post findPost(long id);
}
Entity "Post":
package com.staff.main.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
#Entity
public class Post implements Serializable{
private static final long serialVersionUID = 6767319776206583629L;
#Id
#SequenceGenerator(name="ent2seq",sequenceName="seq_post")
#GeneratedValue(strategy=GenerationType.SEQUENCE,generator="ent2seq")
private long id;
#Column(nullable=false)
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And persistence.xml:
<?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_1_0.xsd"
version="1.0">
<persistence-unit name="StaffPU">
<jta-data-source>java:jboss/datasources/OracleDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create" />
<!-- <property name="javax.persistence.jdbc.show_sql" value="true" /> -->
<!-- <property name="hibernate.show_sql" value="true" /> -->
</properties>
</persistence-unit>
</persistence>
You need to expose your bean with a Remote interface.
After that, you probably will need to change the JNDI entry name used to lookup the ejb reference.
You don't provide information about how the bean is deployed which, among other things, determines the binding name, but you can search the correct lookup string in the server log.
import java.io.File;
import javax.naming.InitialContext;
import org.jboss.ejb3.embedded.EJB3StandaloneBootstrap;
import org.jboss.ejb3.embedded.EJB3StandaloneDeployer;
in your pom you have to add :
<dependency>
<groupId>org.jboss.embedded</groupId>
<artifactId>jboss-embedded-all</artifactId>
<version>beta3.SP9</version>
</dependency>
<dependency>
<groupId>org.jboss.embedded</groupId>
<artifactId>thirdparty-all</artifactId>
<version>beta3.SP9</version>
</dependency>
you have to add :
embedded-jboss-beans.xml
bean.xml,default.persistence.properties
ejb3-interceptors-aop.xml
into your resources folder and jndi.properties too whtch contains :
java.naming.factory.initial=org.jnp.interfaces.LocalOnlyContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
and you test class must contains :
EJB3StandaloneBootstrap.boot(null);
EJB3StandaloneBootstrap.scanClasspath();
EJB3StandaloneBootstrap.deployXmlResource(embeded.xml)
deployer = EJB3StandaloneBootstrap.createDeployer();
deployer.getArchives().add(new File("target/classes").toURI().toURL());
deployer.create();
deployer.start();
InitialContext context = new InitialContext();
and you look up your ejb

EntityManager is null. Using JAX-RS and JPA on WAS-Liberty

I have just started learning JAX-RS and am trying to modify some examples from the O'Reilly RESTful Java with JAX-RS book. I've run into an issue where I am getting a null pointer exception when I try and POST an XML file to one of my JAX-RS services. The specific resource I am posting to uses JPA to persist information to a derby database. After reading several other question/responses and tutorials I am convinced my code is correct but perhaps I am missing some configuration. It seems the entity manager isn't being injected for some reason even though I have the appropriate annotations. Any input on my issue would be appreciated. Please see the following excerpts of my project that I think will be useful:
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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">
<persistence-unit name="jpa-example" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>java:comp/env/jdbc/DerbyConnection</jta-data-source>
<class>com.example.persistence.UserEntity</class>
<class>com.example.persistence.SearchEntity</class>
<properties>
<property name="openjpa.TransactionMode" value="managed"/>
<property name="openjpa.ConnectionFactoryMode" value="managed"/>
<property name="openjpa.LockTimeout" value="30000"/>
<property name="openjpa.jdbc.TransactionIsolation" value="read-committed"/>
<property name="openjpa.Log" value="TRACE"/>
<property name="openjpa.jdbc.UpdateManager" value="operation-order"/>
</properties>
</persistence-unit>
</persistence>
server.xml
<server description="new server">
<!-- Enable features -->
<featureManager>
<feature>jsp-2.2</feature>
<feature>jdbc-4.0</feature>
<feature>jpa-2.0</feature>
<feature>localConnector-1.0</feature>
<feature>jaxrs-1.1</feature>
<feature>ejbLite-3.1</feature>
</featureManager>
<httpEndpoint host="localhost" httpPort="9080" httpsPort="9443" id="defaultHttpEndpoint"/>
<jdbcDriver id="derbyJDBCDriver">
<library name="DerbyLib">
<fileset dir="/Users/jackson/Documents/db-derby-10.10.1.1-bin/lib" includes="derby.jar"/>
</library>
</jdbcDriver>
<dataSource id="DerbyConnection" jdbcDriverRef="derbyJDBCDriver" jndiName="jdbc/DerbyConnection">
<properties.derby.embedded createDatabase="create" databaseName="example"/>
</dataSource>
<applicationMonitor updateTrigger="mbean"/>
<webApplication id="REST" location="REST.war" name="REST"/>
</server>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>REST</display-name>
<servlet>
<description>
JAX-RS Tools Generated - Do not modify</description>
<servlet-name>JAX-RS Servlet</servlet-name>
<servlet-class>com.ibm.websphere.jaxrs.server.IBMRestServlet</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.example.services.RESTConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<enabled>true</enabled>
<async-supported>false</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS Servlet</servlet-name>
<url-pattern>
/rest/*</url-pattern>
</servlet-mapping>
<ejb-local-ref>
<ejb-ref-name>ejb/UserResource</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local>com.example.services.UserResource</local>
<ejb-link>
com.example.services.UserResourceBean
</ejb-link>
</ejb-local-ref>
</web-app>
RESTConfig.java
package com.example.services;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
public class RESTConfig extends Application {
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(HelloWorld.class);
classes.add(UserResourceBean.class);
return classes;
}
}
UserEntity.java
package com.example.persistence;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity(name = "User")
public class UserEntity {
private long id;
private String login;
private String password;
private String firstName;
private String lastName;
private String email;
private String role;
private String status;
#Id
#GeneratedValue
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString()
{
return "UserEntity {" +
"id=" + id +
", email='" + email + '\'' +
", password='" + password + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", role='" + role + '\'' +
", status='" + status + '\'' +
'}';
}
}
UserResource.java
package com.example.services;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import com.example.domain.User;
import com.example.domain.Users;
#Path("/users")
public interface UserResource
{
#POST
#Consumes("application/xml")
Response createUser(User user, #Context UriInfo uriInfo);
#GET
#Produces("application/xml")
//#Formatted
Users getUsers(#QueryParam("start") int start,
#QueryParam("size") #DefaultValue("10") int size,
#QueryParam("firstName") String firstName,
#QueryParam("lastName") String lastName,
#Context UriInfo uriInfo);
#GET
#Path("{id}")
#Produces("application/xml")
User getUser(#PathParam("id") long id);
}
UserResourceBean.java
package com.example.services;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import com.example.domain.Link;
import com.example.domain.User;
import com.example.domain.Users;
import com.example.persistence.UserEntity;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
#Stateless
public class UserResourceBean implements UserResource
{
#PersistenceContext(unitName="jpa-example")
private EntityManager em;
public Response createUser(User user, UriInfo uriInfo)
{
UserEntity entity = new UserEntity();
domain2entity(entity, user);
System.out.println(entity);
em.persist(entity);
em.flush();
System.out.println("Created user " + entity.getId());
UriBuilder builder = uriInfo.getAbsolutePathBuilder();
builder.path(Long.toString(entity.getId()));
return Response.created(builder.build()).build();
}
public User getUser(long id)
{
UserEntity user = em.getReference(UserEntity.class, id);
return entity2domain(user);
}
public static void domain2entity(UserEntity entity, User user)
{
entity.setId(user.getId());
entity.setLogin(user.getLogin());
entity.setPassword(user.getPassword());
entity.setFirstName(user.getFirstName());
entity.setLastName(user.getLastName());
entity.setEmail(user.getEmail());
entity.setRole(user.getRole());
entity.setStatus(user.getStatus());
}
public static User entity2domain(UserEntity entity)
{
User u = new User();
u.setId(entity.getId());
u.setLogin(entity.getLogin());
u.setPassword(entity.getPassword());
u.setFirstName(entity.getFirstName());
u.setLastName(entity.getLastName());
u.setEmail(entity.getEmail());
u.setRole(entity.getRole());
u.setStatus(entity.getStatus());
return u;
}
public Users getUsers(int start,
int size,
String firstName,
String lastName,
UriInfo uriInfo)
{
UriBuilder builder = uriInfo.getAbsolutePathBuilder();
builder.queryParam("start", "{start}");
builder.queryParam("size", "{size}");
ArrayList<User> list = new ArrayList<User>();
ArrayList<Link> links = new ArrayList<Link>();
Query query = null;
if (firstName != null && lastName != null)
{
query = em.createQuery("select u from Users u where u.firstName=:first and u.lastName=:last");
query.setParameter("first", firstName);
query.setParameter("last", lastName);
}
else if (lastName != null)
{
query = em.createQuery("select u from Users u where u.lastName=:last");
query.setParameter("last", lastName);
}
else
{
query = em.createQuery("select u from Users u");
}
List userEntities = query.setFirstResult(start)
.setMaxResults(size)
.getResultList();
for (Object obj : userEntities)
{
UserEntity entity = (UserEntity) obj;
list.add(entity2domain(entity));
}
// next link
// If the size returned is equal then assume there is a next
if (userEntities.size() == size)
{
int next = start + size;
URI nextUri = builder.clone().build(next, size);
Link nextLink = new Link("next", nextUri.toString(), "application/xml");
links.add(nextLink);
}
// previous link
if (start > 0)
{
int previous = start - size;
if (previous < 0) previous = 0;
URI previousUri = builder.clone().build(previous, size);
Link previousLink = new Link("previous", previousUri.toString(), "application/xml");
links.add(previousLink);
}
Users users = new Users();
users.setUsers(list);
users.setLinks(links);
return users;
}
}
It is in this last file in which the NPE occurs. Specifically in function createUser, the following code throws a NPE: em.persist(entity);
I solved the injection issue by altering the code in RESTconfig.java to appear as follows:
package com.example.services;
import java.util.HashSet;
import java.util.Set;
import javax.naming.InitialContext;
import javax.ws.rs.core.Application;
public class RESTConfig extends Application {
public Set<Object> getSingletons()
{
HashSet<Object> set = new HashSet();
try
{
InitialContext ctx = new InitialContext();
obj = ctx.lookup(
"java:comp/env/ejb/UserResource");
set.add(obj);
}
catch (Exception ex)
{
throw new RuntimeException(ex);
}
return set;
}
}

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);
}
}