diff --git a/nbproject/build-impl.xml b/nbproject/build-impl.xml --- a/nbproject/build-impl.xml +++ b/nbproject/build-impl.xml @@ -50,7 +50,9 @@ - + + + @@ -185,6 +187,7 @@ Must set src.dir + Must set test.test.dir Must set build.dir Must set build.web.dir Must set build.generated.dir @@ -331,7 +334,11 @@ - + + + + + @@ -842,8 +849,10 @@ - - + + + + @@ -856,8 +865,10 @@ Must select some files in the IDE or set javac.includes - - + + + + diff --git a/nbproject/genfiles.properties b/nbproject/genfiles.properties --- a/nbproject/genfiles.properties +++ b/nbproject/genfiles.properties @@ -1,5 +1,5 @@ # This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. # Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. -nbproject/build-impl.xml.data.CRC32=b3efa9ac -nbproject/build-impl.xml.script.CRC32=6ea8d87d +nbproject/build-impl.xml.data.CRC32=3d51e9e9 +nbproject/build-impl.xml.script.CRC32=deace57a nbproject/build-impl.xml.stylesheet.CRC32=5b786168@1.24.0.1 diff --git a/nbproject/project.properties b/nbproject/project.properties --- a/nbproject/project.properties +++ b/nbproject/project.properties @@ -1,6 +1,5 @@ annotation.processing.enabled=true annotation.processing.enabled.in.editor=true -annotation.processing.processors.list= annotation.processing.run.all.processors=true annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output build.classes.dir=${build.web.dir}/WEB-INF/classes @@ -23,6 +22,7 @@ dist.ear.war=${dist.dir}/${war.ear.name} dist.javadoc.dir=${dist.dir}/javadoc dist.war=${dist.dir}/${war.name} +endorsed.classpath= excludes= includes=** j2ee.deploy.on.save=true @@ -39,13 +39,13 @@ javac.compilerargs= javac.debug=true javac.deprecation=false -javac.processorpath=${javac.classpath} +javac.processorpath=\ + ${javac.classpath} javac.source=1.5 javac.target=1.5 javac.test.classpath=\ ${javac.classpath}:\ ${build.classes.dir}:\ - ${libs.junit.classpath}:\ ${libs.junit_4.classpath} javac.test.processorpath=${javac.test.classpath} javadoc.additionalparam= @@ -62,7 +62,6 @@ javadoc.windowtitle= jspcompilation.classpath=${jspc.classpath}:${javac.classpath} lib.dir=${web.docbase.dir}/WEB-INF/lib -no.dependencies=false persistence.xml.dir=${conf.dir} platform.active=default_platform resource.dir=setup @@ -75,6 +74,7 @@ source.encoding=UTF-8 source.root=src src.dir=${source.root}/java +test.test.dir=test war.content.additional= war.ear.name=WebJpa.war war.name=WebJpa.war diff --git a/nbproject/project.xml b/nbproject/project.xml --- a/nbproject/project.xml +++ b/nbproject/project.xml @@ -8,9 +8,11 @@ - + - + + + diff --git a/src/conf/persistence.xml b/src/conf/persistence.xml --- a/src/conf/persistence.xml +++ b/src/conf/persistence.xml @@ -28,7 +28,6 @@ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --> - jdbc/__default @@ -40,4 +39,17 @@ --> + + org.eclipse.persistence.jpa.PersistenceProvider + webjpa.entity.Person + true + + + + + + + + + diff --git a/src/java/enterprise/web_jpa_war/entity/Person.java b/src/java/webjpa/entity/Person.java rename from src/java/enterprise/web_jpa_war/entity/Person.java rename to src/java/webjpa/entity/Person.java --- a/src/java/enterprise/web_jpa_war/entity/Person.java +++ b/src/java/webjpa/entity/Person.java @@ -29,8 +29,9 @@ */ -package enterprise.web_jpa_war.entity; +package webjpa.entity; +import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @@ -42,7 +43,7 @@ */ @Entity @Table(name = "PERSON") -public class Person { +public class Person implements Serializable { @Id @Column(name = "ID") @@ -77,5 +78,30 @@ public String getFirstName() { return this.firstName; } - + + @Override + public int hashCode() { + int hash = 0; + hash += (getId() != null ? getId().hashCode() : 0); + return hash; + } + + @Override + public boolean equals(Object object) { + // TODO: Warning - this method won't work in the case the id fields are not set + if (!(object instanceof Person)) { + return false; + } + Person other = (Person) object; + if ((this.getId() == null && other.getId() != null) || (this.getId() != null && !this.id.equals(other.id))) { + return false; + } + return true; + } + + @Override + public String toString() { + return "webjpa.entity.Person[id=" + getId() + "]"; + } + } diff --git a/src/java/webjpa/entity/PersonJpaController.java b/src/java/webjpa/entity/PersonJpaController.java new file mode 100644 --- /dev/null +++ b/src/java/webjpa/entity/PersonJpaController.java @@ -0,0 +1,145 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package webjpa.entity; + +import webjpa.entity.exceptions.NonexistentEntityException; +import webjpa.entity.exceptions.PreexistingEntityException; +import java.util.List; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.persistence.Query; +import javax.persistence.EntityNotFoundException; + +/** + * + * @author ms113234 + */ +public class PersonJpaController { + + public PersonJpaController() { + this("web-jpaPU"); + } + + public PersonJpaController(String persistanceUnitName) { + emf = Persistence.createEntityManagerFactory(persistanceUnitName); + } + + public PersonJpaController(EntityManagerFactory emf) { + this.emf = emf; + } + + private EntityManagerFactory emf = null; + + public EntityManager getEntityManager() { + return emf.createEntityManager(); + } + + public void create(Person person) throws PreexistingEntityException, Exception { + EntityManager em = null; + try { + em = getEntityManager(); + em.getTransaction().begin(); + em.persist(person); + em.getTransaction().commit(); + } catch (Exception ex) { + if (findPerson(person.getId()) != null) { + throw new PreexistingEntityException("Person " + person + " already exists.", ex); + } + throw ex; + } finally { + if (em != null) { + em.close(); + } + } + } + + public void edit(Person person) throws NonexistentEntityException, Exception { + EntityManager em = null; + try { + em = getEntityManager(); + em.getTransaction().begin(); + person = em.merge(person); + em.getTransaction().commit(); + } catch (Exception ex) { + String msg = ex.getLocalizedMessage(); + if (msg == null || msg.length() == 0) { + String id = person.getId(); + if (findPerson(id) == null) { + throw new NonexistentEntityException("The person with id " + id + " no longer exists."); + } + } + throw ex; + } finally { + if (em != null) { + em.close(); + } + } + } + + public void destroy(String id) throws NonexistentEntityException { + EntityManager em = null; + try { + em = getEntityManager(); + em.getTransaction().begin(); + Person person; + try { + person = em.getReference(Person.class, id); + person.getId(); + } catch (EntityNotFoundException enfe) { + throw new NonexistentEntityException("The person with id " + id + " no longer exists.", enfe); + } + em.remove(person); + em.getTransaction().commit(); + } finally { + if (em != null) { + em.close(); + } + } + } + + public List findPersonEntities() { + return findPersonEntities(true, -1, -1); + } + + public List findPersonEntities(int maxResults, int firstResult) { + return findPersonEntities(false, maxResults, firstResult); + } + + private List findPersonEntities(boolean all, int maxResults, int firstResult) { + EntityManager em = getEntityManager(); + try { + Query q = em.createQuery("select object(o) from Person as o"); + if (!all) { + q.setMaxResults(maxResults); + q.setFirstResult(firstResult); + } + return q.getResultList(); + } finally { + em.close(); + } + } + + public Person findPerson(String id) { + EntityManager em = getEntityManager(); + try { + return em.find(Person.class, id); + } finally { + em.close(); + } + } + + public int getPersonCount() { + EntityManager em = getEntityManager(); + try { + Query q = em.createQuery("select count(o) from Person as o"); + return ((Long) q.getSingleResult()).intValue(); + } finally { + em.close(); + } + } + +} diff --git a/src/java/webjpa/entity/exceptions/IllegalOrphanException.java b/src/java/webjpa/entity/exceptions/IllegalOrphanException.java new file mode 100644 --- /dev/null +++ b/src/java/webjpa/entity/exceptions/IllegalOrphanException.java @@ -0,0 +1,20 @@ +package webjpa.entity.exceptions; + +import java.util.ArrayList; +import java.util.List; + +public class IllegalOrphanException extends Exception { + private List messages; + public IllegalOrphanException(List messages) { + super((messages != null && messages.size() > 0 ? messages.get(0) : null)); + if (messages == null) { + this.messages = new ArrayList(); + } + else { + this.messages = messages; + } + } + public List getMessages() { + return messages; + } +} diff --git a/src/java/webjpa/entity/exceptions/NonexistentEntityException.java b/src/java/webjpa/entity/exceptions/NonexistentEntityException.java new file mode 100644 --- /dev/null +++ b/src/java/webjpa/entity/exceptions/NonexistentEntityException.java @@ -0,0 +1,10 @@ +package webjpa.entity.exceptions; + +public class NonexistentEntityException extends Exception { + public NonexistentEntityException(String message, Throwable cause) { + super(message, cause); + } + public NonexistentEntityException(String message) { + super(message); + } +} diff --git a/src/java/webjpa/entity/exceptions/PreexistingEntityException.java b/src/java/webjpa/entity/exceptions/PreexistingEntityException.java new file mode 100644 --- /dev/null +++ b/src/java/webjpa/entity/exceptions/PreexistingEntityException.java @@ -0,0 +1,10 @@ +package webjpa.entity.exceptions; + +public class PreexistingEntityException extends Exception { + public PreexistingEntityException(String message, Throwable cause) { + super(message, cause); + } + public PreexistingEntityException(String message) { + super(message); + } +} diff --git a/src/java/webjpa/entity/exceptions/RollbackFailureException.java b/src/java/webjpa/entity/exceptions/RollbackFailureException.java new file mode 100644 --- /dev/null +++ b/src/java/webjpa/entity/exceptions/RollbackFailureException.java @@ -0,0 +1,10 @@ +package webjpa.entity.exceptions; + +public class RollbackFailureException extends Exception { + public RollbackFailureException(String message, Throwable cause) { + super(message, cause); + } + public RollbackFailureException(String message) { + super(message); + } +} diff --git a/src/java/enterprise/web_jpa_war/servlet/CreatePersonServlet.java b/src/java/webjpa/servlet/CreatePersonServlet.java rename from src/java/enterprise/web_jpa_war/servlet/CreatePersonServlet.java rename to src/java/webjpa/servlet/CreatePersonServlet.java --- a/src/java/enterprise/web_jpa_war/servlet/CreatePersonServlet.java +++ b/src/java/webjpa/servlet/CreatePersonServlet.java @@ -28,10 +28,12 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -package enterprise.web_jpa_war.servlet; +package webjpa.servlet; -import enterprise.web_jpa_war.entity.Person; +import webjpa.entity.Person; +import webjpa.entity.PersonJpaController; import java.io.*; +import javax.annotation.PostConstruct; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; @@ -51,11 +53,16 @@ @PersistenceUnit //The emf corresponding to - private EntityManagerFactory emf; + private EntityManagerFactory emf; - @Resource - private UserTransaction utx; + private PersonJpaController personCtrl; + @PostConstruct + private void postConstruct() { + //Make sure injection went through correctly. + assert emf != null; + personCtrl = new PersonJpaController(emf); + } /** Processes requests for both HTTP GET and POST methods. * @param request servlet request @@ -63,40 +70,18 @@ */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException { - assert emf != null; //Make sure injection went through correctly. - EntityManager em = null; try { - //Get the data from user's form String id = (String) request.getParameter("id"); String firstName = (String) request.getParameter("firstName"); String lastName = (String) request.getParameter("lastName"); - //Create a person instance out of it - Person person = new Person(id, firstName, lastName); - - //begin a transaction - utx.begin(); - //create an em. - //Since the em is created inside a transaction, it is associsated with - //the transaction - em = emf.createEntityManager(); - //persist the person entity - em.persist(person); - //commit transaction which will trigger the em to - //commit newly created entity into database - utx.commit(); - + personCtrl.create(new Person(id, firstName, lastName)); //Forward to ListPerson servlet to list persons along with the newly //created person above request.getRequestDispatcher("ListPerson").forward(request, response); } catch (Exception ex) { throw new ServletException(ex); - } finally { - //close the em to release any resources held up by the persistebce provider - if(em != null) { - em.close(); - } } } diff --git a/src/java/enterprise/web_jpa_war/servlet/ListPersonServlet.java b/src/java/webjpa/servlet/ListPersonServlet.java rename from src/java/enterprise/web_jpa_war/servlet/ListPersonServlet.java rename to src/java/webjpa/servlet/ListPersonServlet.java --- a/src/java/enterprise/web_jpa_war/servlet/ListPersonServlet.java +++ b/src/java/webjpa/servlet/ListPersonServlet.java @@ -28,10 +28,12 @@ * THE POSSIBILITY OF SUCH DAMAGE. */ -package enterprise.web_jpa_war.servlet; +package webjpa.servlet; +import webjpa.entity.PersonJpaController; import java.io.*; import java.util.List; +import javax.annotation.PostConstruct; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; @@ -48,6 +50,16 @@ @PersistenceUnit private EntityManagerFactory emf; + + private PersonJpaController personCtrl; + + @PostConstruct + private void postConstruct() { + //Make sure injection went through correctly. + assert emf != null; + personCtrl = new PersonJpaController(emf); + } + /** Processes requests for both HTTP GET and POST methods. * @param request servlet request @@ -55,26 +67,14 @@ */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - assert emf != null; //Make sure injection went through correctly. - EntityManager em = null; try { - em = emf.createEntityManager(); - //query for all the persons in database - List persons = em.createQuery("select p from Person p").getResultList(); - request.setAttribute("personList",persons); - + request.setAttribute("personList",personCtrl.findPersonEntities()); //Forward to the jsp page for rendering request.getRequestDispatcher("ListPerson.jsp").forward(request, response); } catch (Exception ex) { throw new ServletException(ex); - } finally { - //close the em to release any resources held up by the persistebce provider - if(em != null) { - em.close(); - } - } - + } } // diff --git a/test/webjpa/entity/PersonJpaControllerTest.java b/test/webjpa/entity/PersonJpaControllerTest.java new file mode 100644 --- /dev/null +++ b/test/webjpa/entity/PersonJpaControllerTest.java @@ -0,0 +1,81 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package webjpa.entity; + +import java.util.logging.Level; +import java.util.logging.Logger; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import static org.junit.Assert.*; +import webjpa.entity.exceptions.NonexistentEntityException; + +/** + * + * @author ms113234 + */ +public class PersonJpaControllerTest { + private static final Logger LOG = Logger.getLogger(PersonJpaControllerTest.class.getName()); + + PersonJpaController personCtrl = new PersonJpaController("TestPU"); + + public PersonJpaControllerTest() { + } + + @BeforeClass + public static void setUpClass() throws Exception { + } + + @AfterClass + public static void tearDownClass() throws Exception { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + for (Person person : personCtrl.findPersonEntities()) { + try { + personCtrl.destroy(person.getId()); + } catch (NonexistentEntityException ex) { + LOG.log(Level.SEVERE, null, ex); + } + } + } + + + /** + * Test of create method, of class PersonJpaController. + */ + @Test + public void testCreate() throws Exception { + System.out.println("create"); + Person person = new Person("1", "Duke", "Sun"); + personCtrl.create(person); + Person person2 = personCtrl.findPerson("1"); + assertEquals(person, person2); + } + + /** + * Test of edit method, of class PersonJpaController. + */ + @Test + public void testEdit() throws Exception { + System.out.println("edit"); + Person person = new Person("2", "Duke", "Sun"); + personCtrl.create(person); + person = new Person("2", "Duke2", "Sun"); + personCtrl.edit(person); + Person person2 = personCtrl.findPerson("2"); + assertEquals(person2.getFirstName(), "Duke2"); + } + + //... +} \ No newline at end of file