repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/hibernate/envers/implementvalidityauditstrategytest/ImplementValidityAuditStrategyTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.hibernate.envers.implementvalidityauditstrategytest; import java.util.Date; import java.util.List; import java.util.Map; import javax.naming.InitialContext; import javax.naming.NamingException; import org.hibernate.envers.DefaultRevisionEntity; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.junit.InSequence; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.jpa.hibernate.envers.Organization; import org.jboss.as.test.integration.jpa.hibernate.envers.SLSBValidityStrategyOrg; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * This testcase verifies whether Envers/Auditing functions properly when implemented with Validity Audit Strategy * * @author Madhumita Sadhukhan */ @RunWith(Arquillian.class) public class ImplementValidityAuditStrategyTestCase { private static final String ARCHIVE_NAME = "jpa_ImplementValidityAuditStrategyTestCase"; @ArquillianResource private static InitialContext iniCtx; @BeforeClass public static void beforeClass() throws NamingException { iniCtx = new InitialContext(); } @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses(Organization.class, SLSBValidityStrategyOrg.class); jar.addAsManifestResource(ImplementValidityAuditStrategyTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); return jar; } protected static <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { return interfaceType .cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName())); } @Test @InSequence(1) public void testEnversforValidityStrategy() throws Exception { SLSBValidityStrategyOrg slsbvalidityOrg = lookup("SLSBValidityStrategyOrg", SLSBValidityStrategyOrg.class); Organization o1 = slsbvalidityOrg.createOrg("REDHAT", "Software Co", "10/10/1994", "eternity", "Raleigh"); Organization o2 = slsbvalidityOrg.createOrg("HALDIRAMS", "Food Co", "10/10/1974", "eternity", "Delhi"); o2.setStartDate("10/10/1924"); o2.setName("BIKANER"); slsbvalidityOrg.updateOrg(o2); Organization ret1 = slsbvalidityOrg.retrieveOldOrgbyId(o2.getId()); // check that property startDate is audited Assert.assertEquals("10/10/1974", ret1.getStartDate()); Assert.assertEquals("HALDIRAMS", ret1.getName()); // check that property location is notaudited Assert.assertNull(ret1.getLocation()); } @Test @InSequence(2) public void testValidityStrategyActivationforEnvers() throws Exception { SLSBValidityStrategyOrg slsbvalidityOrg = lookup("SLSBValidityStrategyOrg", SLSBValidityStrategyOrg.class); Organization o1 = slsbvalidityOrg.createOrg("REDHAT", "Software Co", "10/10/1994", "eternity", "Raleigh"); Organization o2 = slsbvalidityOrg.createOrg("HALDIRAMS", "Food Co", "10/10/1974", "eternity", "Delhi"); o2.setStartDate("10/10/1924"); o2.setName("BIKANER"); slsbvalidityOrg.updateOrg(o2); // check if REV END Date is populated List<Map<String, Object>> orgHistory = slsbvalidityOrg.verifyEndRevision(new Integer(o2.getId())); for (Map<String, Object> revisionEntity : orgHistory) { Assert.assertNotNull(revisionEntity); Date revendTimestamp = (Date) revisionEntity.get("REVEND_VALIDITY"); DefaultRevisionEntity revEnd = (DefaultRevisionEntity) revisionEntity.get("REVEND"); if (revendTimestamp != null) { Assert.assertEquals(revendTimestamp.getTime(), revEnd.getTimestamp()); } } } }
5,165
38.738462
131
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/hibernate/envers/basicenverstest/BasicEnversTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.hibernate.envers.basicenverstest; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.jpa.hibernate.envers.Address; import org.jboss.as.test.integration.jpa.hibernate.envers.Person; import org.jboss.as.test.integration.jpa.hibernate.envers.SLSBPU; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * @author Strong Liu */ @RunWith(Arquillian.class) public class BasicEnversTestCase { private static final String ARCHIVE_NAME = "jpa_BasicEnversTestCase"; @ArquillianResource private static InitialContext iniCtx; @BeforeClass public static void beforeClass() throws NamingException { iniCtx = new InitialContext(); } @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses( Person.class, Address.class, SLSBPU.class ); jar.addAsManifestResource(BasicEnversTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); return jar; } protected static <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName())); } @Test public void testSimpleEnversOperation() throws Exception { SLSBPU slsbpu = lookup("SLSBPU", SLSBPU.class); Person p1 = slsbpu.createPerson("Strong", "Liu", "kexueyuan source road", 307); Person p2 = slsbpu.createPerson("tom", "cat", "apache", 34); Address a1 = p1.getAddress(); a1.setHouseNumber(5); p2.setAddress(a1); slsbpu.updateAddress(a1); slsbpu.updatePerson(p2); int size = slsbpu.retrieveOldPersonVersionFromAddress(a1.getId()); Assert.assertEquals(1, size); } }
3,360
35.934066
129
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/hibernate/envers/basicselectiveenverstest/BasicSelectiveEnversTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.hibernate.envers.basicselectiveenverstest; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.jpa.hibernate.envers.Organization; import org.jboss.as.test.integration.jpa.hibernate.envers.SLSBOrg; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * This testcase verifies Envers/Auditing functions on selected attributes(Audited and NotAudited) * * @author Madhumita Sadhukhan */ @RunWith(Arquillian.class) public class BasicSelectiveEnversTestCase { private static final String ARCHIVE_NAME = "jpa_BasicSelectiveEnversTestCase"; @ArquillianResource private static InitialContext iniCtx; @BeforeClass public static void beforeClass() throws NamingException { iniCtx = new InitialContext(); } @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses(Organization.class, SLSBOrg.class); jar.addAsManifestResource(BasicSelectiveEnversTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); return jar; } protected static <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { return interfaceType .cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName())); } @Test public void testSelectiveEnversOperations() throws Exception { SLSBOrg slsbOrg = lookup("SLSBOrg", SLSBOrg.class); Organization o1 = slsbOrg.createOrg("REDHAT", "Software Co", "10/10/1994", "eternity", "Raleigh"); Organization o2 = slsbOrg.createOrg("HALDIRAMS", "Food Co", "10/10/1974", "eternity", "Delhi"); o2.setStartDate("10/10/1924"); o2.setName("BIKANER"); slsbOrg.updateOrg(o2); o1.setStartDate("10/10/1924"); slsbOrg.updateOrg(o1); slsbOrg.deleteOrg(o1); testSelectiveEnversOperationonAuditedandNonAuditedProperty(o2, slsbOrg); testSelectiveEnversOperationonFetchbyEntityName(o2, slsbOrg); testEnversOperationonDelete(o1, slsbOrg); } private void testSelectiveEnversOperationonAuditedandNonAuditedProperty(Organization o2, SLSBOrg slsbOrg) throws Exception { Organization ret1 = slsbOrg.retrieveOldOrgbyId(o2.getId()); // check that property startDate is audited Assert.assertEquals("10/10/1974", ret1.getStartDate()); Assert.assertEquals("HALDIRAMS", ret1.getName()); // check that property location is notaudited Assert.assertNull(ret1.getLocation()); } private void testSelectiveEnversOperationonFetchbyEntityName(Organization o2, SLSBOrg slsbOrg) throws Exception { Organization ret1 = slsbOrg.retrieveOldOrgbyEntityName(Organization.class.getName(), o2.getId()); // check that fetch by Entityname works Assert.assertNotNull(ret1.getName()); Assert.assertEquals("BIKANER", ret1.getName()); } private void testEnversOperationonDelete(Organization o1, SLSBOrg slsbOrg) throws Exception { Organization ret1 = slsbOrg.retrieveDeletedOrgbyId(o1.getId()); // check that revisions of deleted entity can be retrieved Assert.assertNotNull(ret1); } }
4,735
38.466667
128
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/hibernate/envers/validityauditstrategyoninheritancetest/ValidityAuditStrategyonInheritanceTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.hibernate.envers.validityauditstrategyoninheritancetest; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.jpa.hibernate.envers.Player; import org.jboss.as.test.integration.jpa.hibernate.envers.SLSBAuditInheritance; import org.jboss.as.test.integration.jpa.hibernate.envers.SoccerPlayer; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * Test Auditing on inherited attributes using Validity Audit strategy * * @author Madhumita Sadhukhan */ @RunWith(Arquillian.class) public class ValidityAuditStrategyonInheritanceTestCase { private static final String ARCHIVE_NAME = "jpa_TestValidityAuditStrategyonInheritance"; @ArquillianResource private static InitialContext iniCtx; @BeforeClass public static void beforeClass() throws NamingException { iniCtx = new InitialContext(); } @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses(Player.class, SoccerPlayer.class, SLSBAuditInheritance.class); jar.addAsManifestResource(ValidityAuditStrategyonInheritanceTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); return jar; } protected static <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { return interfaceType .cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName())); } /* Ensure that auditing works for inherited attributes */ @Test public void testValidityStrategyonInheritance() throws Exception { SLSBAuditInheritance slsb = lookup("SLSBAuditInheritance", SLSBAuditInheritance.class); SoccerPlayer socplayer = slsb.createSoccerPlayer("LEONARDO", "MESSI", "SOCCER", "REAL MADRID"); socplayer.setFirstName("Christiano"); socplayer.setLastName("Ronaldo"); socplayer.setGame("FOOTBALL"); // update Player socplayer = slsb.updateSoccerPlayer(socplayer); SoccerPlayer val = slsb.retrieveSoccerPlayerbyId(socplayer.getId()); Assert.assertNotNull(val); Assert.assertEquals("LEONARDO", val.getFirstName()); Assert.assertEquals("MESSI", val.getLastName()); Assert.assertNull(val.getGame()); } }
3,794
38.123711
135
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/hibernate/entity/Flight.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.hibernate.entity; import java.util.Set; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToMany; import jakarta.persistence.ManyToOne; /** * Flight entity class * * @author Zbyněk Roubalík */ @Entity public class Flight { private Long id; private String name; private Company company; private Set<Customer> customers; public Flight() { } @Id @Column(name = "flight_id") @GeneratedValue(strategy = GenerationType.IDENTITY) public Long getId() { return id; } public void setId(Long long1) { id = long1; } @Column(updatable = false, name = "flight_name", nullable = false, length = 50) public String getName() { return name; } public void setName(String string) { name = string; } @ManyToOne(cascade = {CascadeType.ALL}) @JoinColumn(name = "comp_id") public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER) public Set<Customer> getCustomers() { return customers; } public void setCustomers(Set<Customer> customers) { this.customers = customers; } }
2,645
27.148936
92
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/hibernate/entity/Customer.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.hibernate.entity; import java.util.Set; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.ManyToMany; import jakarta.persistence.NamedQueries; import jakarta.persistence.NamedQuery; import jakarta.persistence.OneToMany; /** * Customer entity class * * @author Zbyněk Roubalík */ @Entity @NamedQueries( {@NamedQuery(name = "allCustomers", query = "select c from Customer c"), @NamedQuery(name = "customerById", query = "select c from Customer c where c.id=:id")}) public class Customer { private Long id; private String name; private String address; private Set<Ticket> tickets; private Set<Flight> flights; // Address address; public Customer() { } @Id @GeneratedValue(strategy = GenerationType.AUTO) 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; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "customer") public Set<Ticket> getTickets() { return tickets; } public void setTickets(Set<Ticket> tickets) { this.tickets = tickets; } @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER, mappedBy = "customers") public Set<Flight> getFlights() { return flights; } public void setFlights(Set<Flight> flights) { this.flights = flights; } }
2,966
27.257143
116
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/hibernate/entity/Ticket.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.hibernate.entity; import jakarta.persistence.CascadeType; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; /** * Ticket entity class * * @author Zbyněk Roubalík */ @Entity public class Ticket { Long id; String number; Customer customer; public Ticket() { } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Long getId() { return id; } public void setId(Long long1) { id = long1; } public String getNumber() { return number; } public void setNumber(String string) { number = string; } @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "CUSTOMER_ID") public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } }
2,089
25.794872
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/hibernate/entity/Company.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.hibernate.entity; import java.util.HashSet; import java.util.Set; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; /** * Company entity class * * @author Zbyněk Roubalík */ @Entity public class Company { private Long id; private String name; private Set<Flight> flights = new HashSet<Flight>(); public Company() { } @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "comp_id") public Long getId() { return id; } public String getName() { return name; } public void setId(Long newId) { id = newId; } public void setName(String string) { name = string; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "company") @Column(name = "flight_id") public Set<Flight> getFlights() { return flights; } public void setFlights(Set<Flight> flights) { this.flights = flights; } }
2,280
27.160494
88
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/hibernate/management/Employee.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.hibernate.management; import jakarta.persistence.Entity; import jakarta.persistence.Id; /** * Employee entity class * * @author Scott Marlow */ @Entity public class Employee { @Id private int id; private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
1,725
24.382353
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/hibernate/management/ManagementTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.hibernate.management; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.junit.Assert.assertTrue; import java.io.IOException; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.arquillian.api.ContainerResource; import org.jboss.as.arquillian.container.ManagementClient; import org.jboss.dmr.ModelNode; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Jakarta Persistence management operations to ensure jboss-cli.sh/admin console will work with Jakarta Persistence statistics * * @author Scott Marlow */ @RunWith(Arquillian.class) @RunAsClient public class ManagementTestCase { private static final String ARCHIVE_NAME = "jpa_ManagementTestCase"; @ArquillianResource private Deployer deployer; @Deployment(name = ARCHIVE_NAME, managed = false) public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses(ManagementTestCase.class, Employee.class, SFSB1.class ); jar.addAsManifestResource(ManagementTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); jar.addAsManifestResource(new StringAsset("Dependencies: org.jboss.as.controller-client, org.jboss.dmr, org.jboss.marshalling \n"), "MANIFEST.MF"); return jar; } @ArquillianResource private InitialContext iniCtx; protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName())); } protected <T> T rawLookup(String name, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup(name)); } /** * Test that we can get the entity-insert-count attribute from the Hibernate 4 management statistics. * * @throws Exception */ @Test public void getEntityInsertCountAttribute() throws Exception { try { deployer.deploy(ARCHIVE_NAME); assertTrue("obtained entity-insert-count attribute from JPA persistence unit", 0 == getEntityInsertCount()); } finally { deployer.undeploy(ARCHIVE_NAME); } } @ContainerResource private ManagementClient managementClient; int getEntityInsertCount() throws IOException { final ModelNode address = new ModelNode(); address.add("deployment", ARCHIVE_NAME + ".jar"); address.add("subsystem", "jpa"); address.add("hibernate-persistence-unit", ARCHIVE_NAME + ".jar#mypc"); address.protect(); final ModelNode operation = new ModelNode(); operation.get(OP).set("read-attribute"); operation.get(OP_ADDR).set(address); operation.get(NAME).set("entity-insert-count"); ModelNode result = managementClient.getControllerClient().execute(operation); //System.out.println("\n\ngetEntityInsertCount result asString = " + result.asString()); assertTrue("success".equals(result.get("outcome").asString())); result = result.get("result"); return result.asInt(); } }
4,976
37.284615
155
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/hibernate/management/SFSB1.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.hibernate.management; import jakarta.ejb.Stateful; import jakarta.persistence.EntityManager; import jakarta.persistence.LockModeType; import jakarta.persistence.PersistenceContext; /** * stateful session bean * * @author Scott Marlow */ @Stateful public class SFSB1 { @PersistenceContext(unitName = "mypc") EntityManager em; public void createEmployee(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); em.persist(emp); } public Employee getEmployeeNoTX(int id) { return em.find(Employee.class, id, LockModeType.NONE); } public void deleteEmployeeNoTX(Employee employee) { em.remove(employee); } }
1,840
31.298246
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/hibernate/classfiletransformertest/ClassFileTransformerTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.hibernate.classfiletransformertest; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.jpa.hibernate.Employee; import org.jboss.as.test.integration.jpa.hibernate.SFSB1; import org.jboss.as.test.integration.jpa.hibernate.SFSBHibernateSession; import org.jboss.as.test.integration.jpa.hibernate.SFSBHibernateSessionFactory; import org.jboss.as.test.shared.util.AssumeTestGroupUtil; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * Hibernate "hibernate.ejb.use_class_enhancer" test that causes hibernate to add a * jakarta.persistence.spi.ClassTransformer to the pu. * * @author Scott Marlow */ @RunWith(Arquillian.class) public class ClassFileTransformerTestCase { private static final String ARCHIVE_NAME = "jpa_ClassFileTransformerTestCase"; @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses(ClassFileTransformerTestCase.class, Employee.class, SFSB1.class, SFSBHibernateSession.class, SFSBHibernateSessionFactory.class ); jar.addAsManifestResource(ClassFileTransformerTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); return jar; } @BeforeClass public static void skipSecurityManager() { // See WFLY-11359 AssumeTestGroupUtil.assumeSecurityManagerDisabled(); } @ArquillianResource private InitialContext iniCtx; protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName())); } @Test public void testhibernate_ejb_use_class_enhancer() throws Exception { SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); sfsb1.createEmployee("Kelly Smith", "Watford, England", 10); sfsb1.createEmployee("Alex Scott", "London, England", 20); Employee emp = sfsb1.getEmployeeNoTX(10); assertTrue("was able to read database row with hibernate.ejb.use_class_enhancer enabled", emp != null); } @Test public void testHibernateByteCodeEnhancementIsDisabledByDefault() { // Note: ManagedTypeHelper is an internal Hibernate ORM class, if it is removed or renamed then this test can be updated // accordingly. assertFalse("Employee class is not bytecode enhanced", org.hibernate.engine.internal.ManagedTypeHelper.isManagedType(Employee.class)); } }
4,104
39.245098
142
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/hibernate/entitytest/EntityTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.hibernate.entitytest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import java.util.Set; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.junit.InSequence; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.jpa.hibernate.EntityTest; import org.jboss.as.test.integration.jpa.hibernate.entity.Company; import org.jboss.as.test.integration.jpa.hibernate.entity.Customer; import org.jboss.as.test.integration.jpa.hibernate.entity.Flight; import org.jboss.as.test.integration.jpa.hibernate.entity.Ticket; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * Hibernate entity tests (based on the EAP 5 test), using {@link EntityTest} bean. Tests relations between entities, * loading entities and named queries. * <p> * Note that this test uses an extended persistence context, so that the Hibernate session will stay open long enough * to complete each test. A transaction scoped entity manager would be closed after each JTA transaction completes. * * @author Zbyněk Roubalík */ @RunWith(Arquillian.class) public class EntityTestCase { private static final String ARCHIVE_NAME = "jpa_entitytest"; @ArquillianResource private InitialContext iniCtx; protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName())); } protected <T> T rawLookup(String name, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup(name)); } // This test needs to be recompiled against Hibernate ORM 6 (WFLY-16178) in order to pass. @BeforeClass public static void beforeClass() { assumeTrue(System.getProperty("ts.ee9") == null && System.getProperty("ts.bootable.ee9") == null); } @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses(EntityTestCase.class, Customer.class, Ticket.class, Flight.class, EntityTest.class, Company.class); jar.addAsManifestResource(EntityTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); return jar; } @Test @InSequence(1) public void testOneToMany() throws Exception { EntityTest test = lookup("EntityTest", EntityTest.class); Customer c = test.oneToManyCreate(); assertNotNull(c); assertNotNull(c.getTickets()); Set<Ticket> tickets = c.getTickets(); assertTrue(tickets.size() > 0); assertNotNull(c); assertNotNull(c.getTickets()); tickets = c.getTickets(); assertTrue(tickets.size() > 0); } @Test @InSequence(2) public void testManyToOne() throws Exception { EntityTest test = lookup("EntityTest", EntityTest.class); Flight f = test.manyToOneCreate(); Flight f2 = test.findFlightById(f.getId()); assertEquals(f.getId(), new Long(1)); assertEquals(f.getName(), f2.getName()); assertEquals(f.getCompany().getName(), f2.getCompany().getName()); Company c = test.findCompanyById(f.getCompany().getId()); assertNotNull("Company has one flight.", c.getFlights()); assertEquals(f.getCompany().getFlights().size(), c.getFlights().size()); } @Test @InSequence(3) public void testManyToMany() throws Exception { EntityTest test = lookup("EntityTest", EntityTest.class); test.manyToManyCreate(); Flight f1 = test.findFlightById(new Long(1)); assertTrue("Name read from Hibernate is Airline 1", f1.getCompany().getName().equals("Airline 1")); Flight f2 = test.findFlightById(new Long(2)); assertTrue("Name read from Hibernate is Airline 1", f2.getCompany().getName().equals("Airline 2")); assertEquals(1, f1.getCustomers().size()); assertEquals(2, f2.getCustomers().size()); } @Test @InSequence(4) public void testNamedQueries() throws Exception { EntityTest test = lookup("EntityTest", EntityTest.class); int count = test.testAllCustomersQuery(); assertEquals("Number returned for allCustomers query", 4, count); Customer c = test.testCustomerByIdQuery(); assertNotNull("One object should be returned by customerById query", c); } @Test @InSequence(5) public void testFlush() throws Exception { EntityTest test = lookup("EntityTest", EntityTest.class); Customer c = test.createCustomer("Thomas"); test.changeCustomer(c.getId(), "George"); Customer c2 = test.findCustomerById(c.getId()); assertEquals("George", c2.getName()); } }
6,316
35.304598
129
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/hibernate/sessionfactorytest/SessionFactoryTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.hibernate.sessionfactorytest; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import javax.naming.InitialContext; import javax.naming.NamingException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.jpa.hibernate.Employee; import org.jboss.as.test.integration.jpa.hibernate.SFSB1; import org.jboss.as.test.integration.jpa.hibernate.SFSBHibernateSession; import org.jboss.as.test.integration.jpa.hibernate.SFSBHibernateSessionFactory; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * Hibernate session factory tests * * @author Scott Marlow */ @RunWith(Arquillian.class) public class SessionFactoryTestCase { private static final String ARCHIVE_NAME = "jpa_sessionfactory"; // This test needs to be recompiled against Hibernate ORM 6 (WFLY-16178) in order to pass. @BeforeClass public static void beforeClass() { assumeTrue(System.getProperty("ts.ee9") == null && System.getProperty("ts.bootable.ee9") == null); } @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses(SessionFactoryTestCase.class, Employee.class, SFSB1.class, SFSBHibernateSession.class, SFSBHibernateSessionFactory.class ); jar.addAsManifestResource(SessionFactoryTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); return jar; } @ArquillianResource private InitialContext iniCtx; protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName())); } protected <T> T rawLookup(String name, Class<T> interfaceType) throws NamingException { try { return interfaceType.cast(iniCtx.lookup(name)); } catch (NamingException e) { throw e; } } // test that we didn't break the Hibernate hibernate.session_factory_name (bind Hibernate session factory to // specified jndi name) functionality. @Test public void testHibernateSessionFactoryName() throws Exception { SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); sfsb1.createEmployee("Sally", "1 home street", 1); // check if we can look up the Hibernate session factory that should of been bound because of // the hibernate.session_factory_name was specified in the properties (in peristence.xml above). SessionFactory hibernateSessionFactory = rawLookup("modelSessionFactory", SessionFactory.class); assertNotNull("jndi lookup of hibernate.session_factory_name should return HibernateSessionFactory", hibernateSessionFactory); Session session = hibernateSessionFactory.openSession(); Employee emp = session.get(Employee.class, 1); assertTrue("name read from hibernate session is Sally", "Sally".equals(emp.getName())); } // Test that an extended Persistence context can be injected into a Hibernate Session // We use extended persistence context, otherwise the Hibernate session will be closed after each transaction and // the assert test would fail (due to lazy loading of the Employee entity. // Using extended persistence context allows the hibernate session to stay open long enough for the lazy fetch. @Test public void testInjectPCIntoHibernateSession() throws Exception { SFSBHibernateSession sfsbHibernateSession = lookup("SFSBHibernateSession", SFSBHibernateSession.class); sfsbHibernateSession.createEmployee("Molly", "2 apple way", 2); Employee emp = sfsbHibernateSession.getEmployee(2); assertTrue("name read from hibernate session is Molly", "Molly".equals(emp.getName())); } // Test that a Persistence unit can be injected into a Hibernate Session factory @Test public void testInjectPUIntoHibernateSessionFactory() throws Exception { SFSBHibernateSessionFactory sfsbHibernateSessionFactory = lookup("SFSBHibernateSessionFactory", SFSBHibernateSessionFactory.class); sfsbHibernateSessionFactory.createEmployee("Sharon", "3 beach ave", 3); Employee emp = sfsbHibernateSessionFactory.getEmployee(3); assertTrue("name read from hibernate session is Sharon", "Sharon".equals(emp.getName())); } }
5,967
42.246377
134
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/packaging/PersistenceUnitPackagingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.packaging; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.persistence.EntityManagerFactory; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests that we are following the JPA 8.2.2 persistence unit scoping rules * * @author Stuart Douglas */ @RunWith(Arquillian.class) public class PersistenceUnitPackagingTestCase { @Deployment public static Archive<?> deploy() { EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "scopedToEar.ear"); JavaArchive lib = ShrinkWrap.create(JavaArchive.class, "lib.jar"); lib.addClasses(Employee.class); lib.addAsManifestResource(PersistenceUnitPackagingTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); ear.addAsLibrary(lib); JavaArchive override = ShrinkWrap.create(JavaArchive.class, "override.jar"); override.addClasses(Organisation.class, OrganisationBean.class, LibPersistenceUnitBean.class); override.addAsManifestResource(PersistenceUnitPackagingTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); ear.addAsModule(override); JavaArchive noOverride = ShrinkWrap.create(JavaArchive.class, "noOverride.jar"); noOverride.addClasses(EmployeeBean.class, PersistenceUnitPackagingTestCase.class); ear.addAsModule(noOverride); return ear; } @ArquillianResource private static InitialContext iniCtx; /** * As override.jar has it's own PU with the same name as the ear level PU then the local PU should be used */ @Test public void testLocalPuDefinitionOverridesEarLibPu() throws NamingException { OrganisationBean bean = (OrganisationBean) iniCtx.lookup("java:app/override/OrganisationBean"); validate(bean.getEntityManagerFactory(), Organisation.class, Employee.class); validate(bean.getDefaultEntityManagerFactory(), Organisation.class, Employee.class); } /** * noOverride.jar should be able to resolve the ear level pu */ @Test public void testUsingEarLibPuInSubdeployment() throws NamingException { EmployeeBean bean = (EmployeeBean) iniCtx.lookup("java:app/noOverride/EmployeeBean"); validate(bean.getEntityManagerFactory(), Employee.class, Organisation.class); validate(bean.getDefaultEntityManagerFactory(), Employee.class, Organisation.class); } @Test public void testUserOfOveriddenSubDeploymentUsingExplicitPath() throws NamingException { LibPersistenceUnitBean bean = (LibPersistenceUnitBean) iniCtx.lookup("java:app/override/LibPersistenceUnitBean"); validate(bean.getEntityManagerFactory(), Employee.class, Organisation.class); } private static void validate(EntityManagerFactory emf, Class<?> entity, Class<?> notAnEntity) { emf.getMetamodel().entity(entity); try { emf.getMetamodel().entity(notAnEntity); Assert.fail(notAnEntity + " should not be an entity in this PU"); } catch (IllegalArgumentException expected) { } } }
4,554
40.036036
130
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/packaging/LibPersistenceUnitBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.packaging; import jakarta.ejb.Stateless; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.PersistenceUnit; /** * stateful session bean * * @author Stuart Douglas */ @Stateless public class LibPersistenceUnitBean { @PersistenceUnit(unitName = "../lib/lib.jar#mainPu") EntityManagerFactory entityManagerFactory; public EntityManagerFactory getEntityManagerFactory() { return entityManagerFactory; } }
1,524
33.659091
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/packaging/OrganisationBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.packaging; import jakarta.ejb.Stateless; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.PersistenceUnit; /** * stateful session bean * * @author Stuart Douglas */ @Stateless public class OrganisationBean { @PersistenceUnit(unitName = "mainPu") private EntityManagerFactory entityManagerFactory; // AS7-2275 requires each PU reference to specify a persistence unit name, if there are // multiple persistence unit definitions. // as a workaround, specified the pu name @PersistenceUnit(unitName = "mainPu") private EntityManagerFactory defaultEntityManagerFactory; public EntityManagerFactory getEntityManagerFactory() { return entityManagerFactory; } public EntityManagerFactory getDefaultEntityManagerFactory() { return defaultEntityManagerFactory; } }
1,918
34.537037
91
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/packaging/Employee.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.packaging; import jakarta.persistence.Entity; import jakarta.persistence.Id; /** * Employee entity class * * @author Scott Marlow */ @Entity public class Employee { @Id private int id; private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
1,713
24.58209
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/packaging/EmployeeBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.packaging; import jakarta.ejb.Stateless; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.PersistenceUnit; /** * stateful session bean * * @author Stuart Douglas */ @Stateless public class EmployeeBean { @PersistenceUnit(unitName = "mainPu") EntityManagerFactory entityManagerFactory; // AS7-2275 requires each PU reference to specify a persistence unit name, if there are // multiple persistence unit definitions. // as a workaround, specified the pu name @PersistenceUnit(unitName = "mainPu") EntityManagerFactory defaultEntityManagerFactory; public EntityManagerFactory getEntityManagerFactory() { return entityManagerFactory; } public EntityManagerFactory getDefaultEntityManagerFactory() { return defaultEntityManagerFactory; } // AS7-2829 bean in ejbjar should be able to access class in persistence provider public Class getPersistenceProviderClass(String classname) { Class result = null; try { result = EmployeeBean.class.getClassLoader().loadClass(classname); } catch (ClassNotFoundException e) { return null; } return result; } }
2,281
34.107692
91
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/packaging/PersistenceUnitWarPackagingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.packaging; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.persistence.EntityManagerFactory; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests that we are following the JPA 8.2.2 persistence unit scoping rules * * @author Stuart Douglas */ @RunWith(Arquillian.class) public class PersistenceUnitWarPackagingTestCase { @Deployment public static Archive<?> deploy() { EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "scopedToEar.ear"); JavaArchive lib = ShrinkWrap.create(JavaArchive.class, "lib.jar"); lib.addClasses(Employee.class); lib.addAsManifestResource(PersistenceUnitWarPackagingTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); ear.addAsLibrary(lib); WebArchive override = ShrinkWrap.create(WebArchive.class, "override.war"); override.addClasses(Organisation.class, OrganisationBean.class, LibPersistenceUnitBean.class, PersistenceUnitWarPackagingTestCase.class); override.addAsResource(PersistenceUnitWarPackagingTestCase.class.getPackage(), "persistence.xml", "META-INF/persistence.xml"); ear.addAsModule(override); JavaArchive noOverride = ShrinkWrap.create(JavaArchive.class, "noOverride.jar"); noOverride.addClasses(EmployeeBean.class); ear.addAsModule(noOverride); return ear; } @ArquillianResource private static InitialContext iniCtx; /** * As override.jar has it's own PU with the same name as the ear level PU then the local PU should be used */ @Test public void testLocalPuDefinitionOverridesEarLibPu() throws NamingException { OrganisationBean bean = (OrganisationBean) iniCtx.lookup("java:app/override/OrganisationBean"); validate(bean.getEntityManagerFactory(), Organisation.class, Employee.class); validate(bean.getDefaultEntityManagerFactory(), Organisation.class, Employee.class); } /** * noOverride.jar should be able to resolve the ear level pu */ @Test public void testUsingEarLibPuInSubdeployment() throws NamingException { EmployeeBean bean = (EmployeeBean) iniCtx.lookup("java:app/noOverride/EmployeeBean"); validate(bean.getEntityManagerFactory(), Employee.class, Organisation.class); validate(bean.getDefaultEntityManagerFactory(), Employee.class, Organisation.class); } @Test public void testUserOfOveriddenSubDeploymentUsingExplicitPath() throws NamingException { LibPersistenceUnitBean bean = (LibPersistenceUnitBean) iniCtx.lookup("java:app/override/LibPersistenceUnitBean"); validate(bean.getEntityManagerFactory(), Employee.class, Organisation.class); } private static void validate(EntityManagerFactory emf, Class<?> entity, Class<?> notAnEntity) { emf.getMetamodel().entity(entity); try { emf.getMetamodel().entity(notAnEntity); Assert.fail(notAnEntity + " should not be an entity in this PU"); } catch (IllegalArgumentException expected) { } } }
4,613
40.567568
145
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/packaging/EJBJarPackagingTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.packaging; import static org.junit.Assert.assertNotNull; import javax.naming.InitialContext; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Test that an EJB jar can reference the persistence provider classes */ @RunWith(Arquillian.class) public class EJBJarPackagingTestCase { @Deployment public static Archive<?> deploy() { EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "scopedToEar.ear"); JavaArchive ejbjar = ShrinkWrap.create(JavaArchive.class, "ejbjar.jar"); ejbjar.addAsManifestResource(emptyEjbJar(), "ejb-jar.xml"); ejbjar.addClasses(EmployeeBean.class, EJBJarPackagingTestCase.class); ear.addAsModule(ejbjar); // add ejbjar to root of ear JavaArchive lib = ShrinkWrap.create(JavaArchive.class, "lib.jar"); lib.addClasses(Employee.class); ear.addAsLibrary(lib); // add entity jar to ear/lib // add persistence.xml to ear/META-INF ear.addAsManifestResource(EJBJarPackagingTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); return ear; } @ArquillianResource private static InitialContext iniCtx; /** * Test that bean in ejbjar can access persistence provider class */ @Test public void testBeanInEJBJarCanAccessPersistenceProviderClass() throws Exception { EmployeeBean bean = (EmployeeBean) iniCtx.lookup("java:app/ejbjar/EmployeeBean"); Class sessionClass = bean.getPersistenceProviderClass("org.hibernate.Session"); assertNotNull("was able to load 'org.hibernate.Session' class from persistence provider", sessionClass); } private static StringAsset emptyEjbJar() { return new StringAsset( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ejb-jar xmlns=\"http://java.sun.com/xml/ns/javaee\" \n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" + " xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd\"\n" + " version=\"3.0\">\n" + " \n" + "</ejb-jar>"); } }
3,753
39.804348
145
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/packaging/Organisation.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.packaging; import jakarta.persistence.Entity; import jakarta.persistence.Id; /** * Employee entity class * * @author Scott Marlow */ @Entity public class Organisation { @Id private int id; private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
1,717
24.641791
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/basic/SLSBPersistenceUnits.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.basic; import java.util.Map; import jakarta.annotation.Resource; import jakarta.ejb.EJBContext; import jakarta.ejb.Stateless; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.PersistenceUnit; /** * stateless session bean * * @author Scott Marlow */ @Stateless @PersistenceUnit(name = "pu1", unitName = "pu1") @PersistenceUnit(name = "pu2", unitName = "pu2") public class SLSBPersistenceUnits { @Resource EJBContext ctx; public Map<String, Object> getPU1Info() { EntityManagerFactory emf = (EntityManagerFactory) ctx.lookup("pu1"); return emf.getProperties(); } public Map<String, Object> getPU2Info() { EntityManagerFactory emf = (EntityManagerFactory) ctx.lookup("pu2"); return emf.getProperties(); } }
1,864
31.719298
76
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/basic/SLSBPersistenceContexts.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.basic; import java.util.Map; import jakarta.annotation.Resource; import jakarta.ejb.EJBContext; import jakarta.ejb.Stateless; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.persistence.PersistenceContexts; /** * stateless session bean * * @author Scott Marlow */ @Stateless @PersistenceContexts({ @PersistenceContext(name = "pu1", unitName = "pu1"), @PersistenceContext(name = "pu2", unitName = "pu2") }) public class SLSBPersistenceContexts { @Resource EJBContext ctx; public Map<String, Object> getPU1Info() { EntityManager em = (EntityManager) ctx.lookup("pu1"); return em.getEntityManagerFactory().getProperties(); } public Map<String, Object> getPU2Info() { EntityManager em = (EntityManager) ctx.lookup("pu2"); return em.getEntityManagerFactory().getProperties(); } }
1,979
32.559322
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/basic/Employee.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.basic; import jakarta.persistence.Entity; import jakarta.persistence.Id; /** * Employee entity class * * @author Scott Marlow */ @Entity public class Employee { @Id private int id; private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
1,709
24.522388
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/basic/SLSBAmbiguousPU.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.basic; import java.util.Map; import jakarta.ejb.Stateless; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.PersistenceUnit; /** * stateless session bean * * @author Scott Marlow */ @Stateless public class SLSBAmbiguousPU { @PersistenceUnit() private EntityManagerFactory emf; public Map<String, Object> getEMInfo() { return emf.getProperties(); } }
1,476
31.108696
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/basic/SLSBPU2.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.basic; import java.util.Map; import jakarta.ejb.Stateless; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.PersistenceUnit; /** * stateless session bean * * @author Scott Marlow */ @Stateless public class SLSBPU2 { @PersistenceUnit(unitName = "pu2") private EntityManagerFactory emf; public Map<String, Object> getEMInfo() { return emf.getProperties(); } }
1,484
31.282609
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/basic/SLSBPU1.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.basic; import java.util.Map; import jakarta.ejb.Stateless; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.PersistenceUnit; /** * stateless session bean * * @author Scott Marlow */ @Stateless public class SLSBPU1 { @PersistenceUnit(unitName = "pu1") private EntityManagerFactory emf; public Map<String, Object> getEMInfo() { return emf.getProperties(); } }
1,484
31.282609
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/basic/SFSB1.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.basic; import jakarta.annotation.Resource; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; import jakarta.persistence.EntityManager; import jakarta.persistence.NoResultException; import jakarta.persistence.PersistenceContext; import jakarta.persistence.Query; import jakarta.transaction.UserTransaction; /** * stateful session bean * * @author Scott Marlow */ @Stateful public class SFSB1 { @PersistenceContext(unitName = "mypc") EntityManager em; @Resource SessionContext sessionContext; public void createEmployee(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); em.persist(emp); } // always throws a TransactionRequiredException @TransactionAttribute(TransactionAttributeType.NEVER) public void createEmployeeNoTx(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); UserTransaction tx1 = sessionContext.getUserTransaction(); try { tx1.begin(); em.joinTransaction(); em.persist(emp); tx1.commit(); } catch (Exception e) { throw new RuntimeException("couldn't start tx", e); } em.flush(); // should throw TransactionRequiredException } @TransactionAttribute(TransactionAttributeType.NEVER) public Employee getEmployeeNoTX(int id) { return em.find(Employee.class, id); } @TransactionAttribute(TransactionAttributeType.NEVER) public String queryEmployeeNameNoTX(int id) { Query q = em.createQuery("SELECT e.name FROM Employee e"); try { String name = (String) q.getSingleResult(); return name; } catch (NoResultException expected) { return "success"; } catch (Exception unexpected) { return unexpected.getMessage(); } } }
3,209
29.283019
73
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/basic/entitymanagerfactorytest/EntityManagerFactoryTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.basic.entitymanagerfactorytest; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.integration.jpa.basic.Employee; import org.jboss.as.test.integration.jpa.basic.SFSB1; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * EntityManagerFactory tests * * @author Zbynek Roubalik */ @RunWith(Arquillian.class) public class EntityManagerFactoryTestCase { private static final String ARCHIVE_NAME = "jpa_emfactory"; @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses(EntityManagerFactoryTestCase.class, SFSB1.class, Employee.class); jar.addAsManifestResource(EntityManagerFactoryTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); return jar; } @ArquillianResource private InitialContext iniCtx; protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName())); } protected <T> T rawLookup(String name, Class<T> interfaceType) throws NamingException { try { return interfaceType.cast(iniCtx.lookup(name)); } catch (NamingException e) { throw e; } } /** * Test that EntityManagerFactory can be bind to specified JNDI name */ @Test public void testEntityManagerFactoryName() throws Exception { SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); sfsb1.createEmployee("Sally", "1 home street", 1); EntityManagerFactory emf = rawLookup("myEMF", EntityManagerFactory.class); assertNotNull("JNDI lookup of jboss.entity.manager.factory.jndi.name should return EntityManagerFactory", emf); EntityManager em = emf.createEntityManager(); Employee emp = em.find(Employee.class, 1); assertTrue("Name read from EntityManager is Sally", "Sally".equals(emp.getName())); } /** * Test that EntityManager can be bound to specified JNDI name in persistence unit property jboss.entity.manager.jndi.name (AS7-6835) */ @Test public void testEntityManagerName() throws Exception { SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); sfsb1.createEmployee("Sharon", "304 Bubbles Lane", 2); EntityManager em = rawLookup("java:/Manager1", EntityManager.class); assertNotNull("JNDI lookup of jboss.entity.manager.jndi.name should return EntityManager", em); Employee emp = em.find(Employee.class, 2); assertTrue("Name read from EntityManager is Sharon", "Sharon".equals(emp.getName())); } }
4,317
36.877193
137
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/basic/relativedatasourcetest/RelativeDataSourceNameTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.basic.relativedatasourcetest; import jakarta.ejb.EJB; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.integration.jpa.basic.Employee; import org.jboss.as.test.integration.jpa.basic.SFSB1; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Transaction tests * * @author Scott Marlow */ @RunWith(Arquillian.class) public class RelativeDataSourceNameTestCase { private static final String ARCHIVE_NAME = "RelativeDataSourceNameTestCase"; @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses(RelativeDataSourceNameTestCase.class, Employee.class, SFSB1.class ); jar.addAsManifestResource(RelativeDataSourceNameTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); return jar; } @EJB(mappedName = "java:global/" + ARCHIVE_NAME + "/SFSB1") private SFSB1 sfsb1; @Test public void testQueryNonTXTransactionalEntityManagerInvocations() throws Exception { Exception error = null; sfsb1.createEmployee("Susan Sells", "1 Main Street", 1); } }
2,464
34.724638
123
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/basic/multiplepersistenceunittest/MultiplePuTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.basic.multiplepersistenceunittest; import java.util.Map; import jakarta.ejb.EJB; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.as.test.integration.jpa.basic.SLSBAmbiguousPU; import org.jboss.as.test.integration.jpa.basic.SLSBPU1; import org.jboss.as.test.integration.jpa.basic.SLSBPU2; import org.jboss.as.test.integration.jpa.basic.SLSBPersistenceContexts; import org.jboss.as.test.integration.jpa.basic.SLSBPersistenceUnits; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Ensure that both pu definitions can be used. * * @author Scott Marlow */ @RunWith(Arquillian.class) public class MultiplePuTestCase { private static final String ARCHIVE_NAME = "MultiplePuTestCase"; @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses(MultiplePuTestCase.class, SLSBPU1.class, SLSBPU2.class, SLSBPersistenceContexts.class, SLSBPersistenceUnits.class, SLSBAmbiguousPU.class); jar.addAsManifestResource(MultiplePuTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); return jar; } @EJB(mappedName = "java:global/" + ARCHIVE_NAME + "/SLSBPU1") private SLSBPU1 slsbpu1; @EJB(mappedName = "java:global/" + ARCHIVE_NAME + "/SLSBPU2") private SLSBPU2 slsbpu2; @EJB(mappedName = "java:global/" + ARCHIVE_NAME + "/SLSBAmbiguousPU") private SLSBAmbiguousPU slsbAmbiguousPU; @EJB(mappedName = "java:global/" + ARCHIVE_NAME + "/SLSBPersistenceContexts") private SLSBPersistenceContexts slsbPersistenceContexts; @EJB(mappedName = "java:global/" + ARCHIVE_NAME + "/SLSBPersistenceUnits") private SLSBPersistenceUnits slsbPersistenceUnits; @Test public void testBothPersistenceUnitDefinitions() throws Exception { Map<String, Object> sl1Props = slsbpu1.getEMInfo(); Map<String, Object> sl2Props = slsbpu2.getEMInfo(); Map<String, Object> slsbAmbiguousPUEMInfo = slsbAmbiguousPU.getEMInfo(); Assert.assertEquals("wrong pu ", sl1Props.get("PersistenceUnitName"), "pu1"); Assert.assertEquals("wrong pu ", sl2Props.get("PersistenceUnitName"), "pu2"); // pu2 is the default pu Assert.assertEquals("wrong pu ", slsbAmbiguousPUEMInfo.get("PersistenceUnitName"), "pu2"); } /** * test that jakarta.persistence.PersistenceContexts binds two persistence contexts (pu1 + pu2) to * the SLSBBothPUs class, which we lookup from JNDI and use to get the persistence unit properties. * Get the "PersistenceUnitName" property that we added in persistence.xml to verify that the expected * persistence unit is used. * * @throws Exception */ @Test public void testPersistenceContextsAnnotation() throws Exception { Map<String, Object> sl1Props = slsbPersistenceContexts.getPU1Info(); Map<String, Object> sl2Props = slsbPersistenceContexts.getPU2Info(); Assert.assertEquals("wrong pu ", sl1Props.get("PersistenceUnitName"), "pu1"); Assert.assertEquals("wrong pu ", sl2Props.get("PersistenceUnitName"), "pu2"); } /** * test that jakarta.persistence.PersistenceUnits binds two persistence units (pu1 + pu2) to * the SLSBBothPUs class, which we lookup from JNDI and use to get the persistence unit properties. * Get the "PersistenceUnitName" property that we added in persistence.xml to verify that the expected * persistence unit is used. * * @throws Exception */ @Test public void testPersistenceUnitsAnnotation() throws Exception { Map<String, Object> sl1Props = slsbPersistenceUnits.getPU1Info(); Map<String, Object> sl2Props = slsbPersistenceUnits.getPU2Info(); Assert.assertEquals("wrong pu ", sl1Props.get("PersistenceUnitName"), "pu1"); Assert.assertEquals("wrong pu ", sl2Props.get("PersistenceUnitName"), "pu2"); } }
5,240
41.959016
161
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/resourceref/Employee.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.resourceref; import jakarta.persistence.Entity; import jakarta.persistence.Id; /** * Employee entity class * * @author Scott Marlow */ @Entity public class Employee { @Id private int id; private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
1,715
24.61194
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/resourceref/MyEjb.java
/* * JBoss, Home of Professional Open Source. * Copyright 2020 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.jpa.resourceref; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; @Stateful @TransactionManagement(TransactionManagementType.CONTAINER) public class MyEjb { @PersistenceContext(unitName = "mainPu") EntityManager em; public Employee queryEmployeeName(int id) { return em.find(Employee.class, id); } }
1,232
30.615385
75
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/resourceref/DataSourceResourceReferenceTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2020, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.resourceref; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Verify that persistence unit using DataSource resource reference can work with entity class enhancement enabled. * */ @RunWith(Arquillian.class) public class DataSourceResourceReferenceTestCase { private static final String ARCHIVE_NAME = "DataSourceResourceReferenceTestCase.ear"; @Deployment public static Archive<?> deployment() { final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, ARCHIVE_NAME); ear.addAsResource(DataSourceResourceReferenceTestCase.class.getPackage(), "application.xml", "application.xml"); final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "ejb.jar"); jar.addClasses(MyEjb.class, DataSourceResourceReferenceTestCase.class, Employee.class); jar.addAsManifestResource(DataSourceResourceReferenceTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); ear.addAsModule(jar); return ear; } /** * Test that an application defined DataSource (via resource reference) can be used by persistence unit, in * addition to using (Hibernate ORM) bytecode enhancement. * * Note that the persistence.xml "jboss.as.jpa.classtransformer" is true to enable bytecode enhancement. * "wildfly.jpa.applicationdatasource" is also set to true, if it was false (default), the application * deployment would fail with: * * Required services that are not installed:" => ["jboss.naming.context.java.app.DataSourceResourceReferenceTestCase.env.testDS"], * "WFLYCTL0180: Services with missing/unavailable dependencies" => ["jboss.persistenceunit.\"DataSourceResourceReferenceTestCase.ear/ * ejb.jar#mainPu\".__FIRST_PHASE__ is missing [jboss.naming.context.java.app.DataSourceResourceReferenceTestCase.env.testDS]" * * @throws NamingException */ @Test public void testPostConstruct() throws NamingException { MyEjb myEjb = (MyEjb) new InitialContext().lookup("java:module/" + MyEjb.class.getSimpleName()); Assert.assertEquals(null, myEjb.queryEmployeeName(100)); } }
3,625
44.325
138
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/ormxml/Employee.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.ormxml; import jakarta.persistence.Id; /** * Employee entity class * * @author Scott Marlow */ public class Employee { @Id private int id; private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
1,668
24.287879
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/ormxml/SFSBCMT.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.ormxml; import jakarta.annotation.Resource; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; /** * stateful session bean * * @author Scott Marlow */ @Stateful @TransactionManagement(TransactionManagementType.CONTAINER) public class SFSBCMT { @PersistenceContext(unitName = "ORMpc") EntityManager em; @Resource SessionContext sessionContext; public Employee queryEmployeeName(int id) { return em.find(Employee.class, id); } }
1,725
31.566038
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/ormxml/OrmTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.ormxml; import static org.junit.Assert.assertNull; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Transaction tests * * @author Scott Marlow */ @RunWith(Arquillian.class) public class OrmTestCase { private static final String ARCHIVE_NAME = "jpa_OrmTestCase"; private static final String orm_xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<entity-mappings xmlns=\"http://java.sun.com/xml/ns/persistence/orm\" version=\"2.0\">" + "<entity class=\"org.jboss.as.test.integration.jpa.ormxml.Employee\"/>" + "</entity-mappings>"; @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses(OrmTestCase.class, Employee.class, SFSBCMT.class ); jar.addAsManifestResource(OrmTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); jar.addAsResource(new StringAsset(orm_xml), "META-INF/orm.xml"); return jar; } @ArquillianResource private InitialContext iniCtx; @Test public void testOrmXmlDefinedEmployeeEntity() throws Exception { SFSBCMT sfsbcmt = lookup("SFSBCMT", SFSBCMT.class); Employee emp = sfsbcmt.queryEmployeeName(1); assertNull("entity shouldn't exist", emp); } protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName())); } }
3,133
35.44186
129
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/version/VersionTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.version; import static org.junit.Assert.assertTrue; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Ensure that version handling works. * This tests that JPA 2.0 specification section 7.6.1 is followed. Specifically: * " * If the entity manager is invoked outside the scope of a transaction, any entities loaded from the database * will immediately become detached at the end of the method call. * " * * @author Scott Marlow */ @RunWith(Arquillian.class) public class VersionTestCase { private static final String ARCHIVE_NAME = "jpa_sessionfactory"; @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses(VersionTestCase.class, Employee.class, SFSB1.class ); jar.addAsManifestResource(VersionTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); return jar; } @ArquillianResource private static InitialContext iniCtx; protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName())); } protected <T> T rawLookup(String name, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup(name)); } /** * @throws Exception */ @Test public void testVersion() throws Exception { SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); // tx1 will create the employee sfsb1.createEmployee("Sally", "1 home street", 1); // non-tx2 will load the entity Employee emp = sfsb1.getEmployeeNoTX(1); Integer firstVersion = emp.getVersion(); // non-tx3 will load the entity // tx4 will update the employee // no-tx4 will load the entity (shouldn't see the stale entity read in non-tx3) Employee updatedEmp = sfsb1.mutateEmployee(emp); assertTrue( "entities read in non-tx should be detached from persistence context as they are read." + " version at time of creation = " + firstVersion + ", version after update should be greater than creation version" + ", version after update is = " + updatedEmp.getVersion(), firstVersion.intValue() < updatedEmp.getVersion().intValue()); } }
3,951
36.638095
129
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/version/Employee.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.version; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.Version; /** * Employee entity class * * @author Scott Marlow */ @Entity public class Employee { @Id private int id; @Version private Integer version; private String name; private String address; public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
1,940
23.56962
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/version/SFSB1.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.version; import jakarta.annotation.Resource; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.transaction.UserTransaction; /** * stateful session bean * * @author Scott Marlow */ @Stateful @TransactionManagement(TransactionManagementType.BEAN) public class SFSB1 { @PersistenceContext EntityManager em; @Resource SessionContext sessionContext; public void createEmployee(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); UserTransaction tx1 = sessionContext.getUserTransaction(); try { tx1.begin(); em.joinTransaction(); em.persist(emp); tx1.commit(); } catch (Exception e) { throw new RuntimeException("createEmployee couldn't start tx", e); } } public Employee mutateEmployee(Employee employee) { employee.setName(employee.getName() + " +1"); // load the entity with no Jakarta Transactions transaction (entity should be detached from persistence context) getEmployeeNoTX(employee.getId()); // update the entity, which will increment the version field UserTransaction tx1 = sessionContext.getUserTransaction(); try { tx1.begin(); em.joinTransaction(); em.merge(employee); em.flush(); tx1.commit(); // load the entity with no Jakarta Transactions transaction (should get fresh copy of entity with updated version field) return getEmployeeNoTX(employee.getId()); } catch (Exception e) { throw new RuntimeException("mutateEmployee couldn't start tx", e); } } public Employee getEmployeeNoTX(int id) { return em.find(Employee.class, id); } }
3,140
32.774194
132
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/initializeinorder/SingletonCMT.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.initializeinorder; import jakarta.ejb.LocalBean; import jakarta.ejb.Singleton; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; /** * @author Scott Marlow */ @Singleton @LocalBean @TransactionManagement(TransactionManagementType.CONTAINER) public class SingletonCMT extends AbstractCMTBean { }
1,403
35.947368
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/initializeinorder/AbstractCMTBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.initializeinorder; import jakarta.annotation.Resource; import jakarta.ejb.SessionContext; import jakarta.persistence.EntityManager; import jakarta.persistence.LockModeType; import jakarta.persistence.PersistenceContext; /** * @author Scott Marlow */ public abstract class AbstractCMTBean { @PersistenceContext(unitName = "pu1") EntityManager em; @PersistenceContext(unitName = "pu2") EntityManager em2; @Resource SessionContext sessionContext; public void createEmployee(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); em.joinTransaction(); em.persist(emp); //em.flush(); } public void updateEmployee(Employee emp) { emp.setName("hacked " + emp.getName()); em2.merge(emp); //em.flush(); } public Employee getEmployeeNoTX(int id) { return em.find(Employee.class, id, LockModeType.NONE); } }
2,084
30.590909
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/initializeinorder/MyServlet.java
package org.jboss.as.test.integration.jpa.initializeinorder; import java.io.IOException; import jakarta.annotation.PostConstruct; import jakarta.inject.Inject; import jakarta.servlet.Servlet; import jakarta.servlet.ServletConfig; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.annotation.WebServlet; /** * @author Scott Marlow */ @WebServlet(name = "MyServlet", urlPatterns = {"/test"}, loadOnStartup = 1) public class MyServlet implements Servlet { @Inject CdiJpaInjectingBean bean; @PostConstruct public void postConstruct() { //we wait a second, to make sure that the EJB is actually waiting for us to start, and it is not just //the normal random init order try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } TestState.addInitOrder(MyServlet.class.getSimpleName()); if (bean != null) { TestState.setJpaInjectingBeanAvailable(); if (bean.entityManagerFactory() != null) { TestState.setEntityManagerFactoryAvailable(); } if (bean.entityManager() != null) { TestState.setEntityManagerAvailable(); } } } @Override public void init(final ServletConfig config) throws ServletException { } @Override public ServletConfig getServletConfig() { return null; } @Override public void service(final ServletRequest req, final ServletResponse res) throws ServletException, IOException { } @Override public String getServletInfo() { return null; } @Override public void destroy() { } }
1,800
25.485294
115
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/initializeinorder/Employee.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.initializeinorder; import jakarta.persistence.Entity; import jakarta.persistence.EntityListeners; import jakarta.persistence.Id; /** * Employee entity class * * @author Scott Marlow */ @Entity @EntityListeners({MyListener.class}) public class Employee { @Id private int id; private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String toString() { return "employee " + name + ", " + address + ", #" + id; } }
1,905
25.109589
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/initializeinorder/InitializeInOrderTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright (c) 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.initializeinorder; import static org.junit.Assert.assertTrue; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Tests that <initialize-in-order> works as expected. * * @author Scott Marlow (clone of test written by Stuart Douglas) */ @RunWith(Arquillian.class) public class InitializeInOrderTestCase { private static final String ARCHIVE_NAME = "InitializeInOrderTestCase"; @Deployment public static Archive<?> deployment() { final EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, ARCHIVE_NAME + ".ear"); ear.addAsResource(InitializeInOrderTestCase.class.getPackage(), "application.xml", "application.xml"); final JavaArchive sharedJar = ShrinkWrap.create(JavaArchive.class, "shared.jar"); sharedJar.addClasses(InitializeInOrderTestCase.class, TestState.class, Employee.class, MyListener.class, SingletonCMT.class ); ear.addAsLibraries(sharedJar); final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "ejb.jar"); jar.addClasses(MyEjb.class); jar.addAsManifestResource(InitializeInOrderTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); ear.addAsModule(jar); final JavaArchive jar2 = ShrinkWrap.create(JavaArchive.class, "ejb2.jar"); jar2.addClasses(MyEjb2.class); jar2.addClass(SFSBCMT.class); jar2.addClass(AbstractCMTBean.class); jar2.addClass(Employee.class); jar2.addAsManifestResource(InitializeInOrderTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); ear.addAsModule(jar2); final WebArchive war = ShrinkWrap.create(WebArchive.class, "web.war"); war.addClasses(MyServlet.class, CdiJpaInjectingBean.class, QualifyEntityManagerFactory.class, CdiJpaInjectingBean.class); war.addAsResource( InitializeInOrderTestCase.class.getPackage(), "persistence.xml", "META-INF/persistence.xml"); war.addAsWebInfResource(new StringAsset("<beans bean-discovery-mode=\"all\"></beans>"), "beans.xml"); ear.addAsModule(war); return ear; } @Test public void testPostConstruct() throws NamingException { Assert.assertEquals("check of initOrder (" + TestState.getInitOrder().toString() + ") size is expected to be 3 but was " + TestState.getInitOrder().size(), 3, TestState.getInitOrder().size()); Assert.assertEquals("MyServlet", TestState.getInitOrder().get(0)); Assert.assertEquals("MyEjb", TestState.getInitOrder().get(1)); TestState.clearInitOrder(); } /** * Tests that the entity listeners are correctly invoked and have access to the java:comp/EJBContext * when an entity is persisted via a stateful CMT bean * * @throws Exception */ @Test public void testSFSBCMT() throws Exception { MyListener.setInvocationCount(0); // java:global/InitializeInOrderTestCase/ejb2/SFSBCMT SFSBCMT cmt = lookup("ejb2/SFSBCMT", SFSBCMT.class); doCMTTest(cmt, 2); } /** * Tests that both MyEJB + MyEJB2 have access to the persistence context defined in the other EJB * * @throws Exception */ @Test public void testSubDeploymentsHaveAllPersistenceUnits() throws Exception { // java:global/InitializeInOrderTestCase/ejb2/SFSBCMT MyEjb myEjb = lookup("ejb/MyEjb", MyEjb.class); MyEjb2 myEjb2 = lookup("ejb2/MyEjb2", MyEjb2.class); assertTrue(myEjb.hasPersistenceContext()); assertTrue(myEjb2.hasPersistenceContext()); } /** * Tests that the entity listeners are correctly invoked and have access to the java:comp/EJBContext * when an entity is persisted via a CMT bean * * @param cmtBean The CMT bean * @throws Exception */ private void doCMTTest(final AbstractCMTBean cmtBean, final int empId) throws Exception { cmtBean.createEmployee("Alfred E. Neuman", "101010 Mad Street", empId); Employee emp = cmtBean.getEmployeeNoTX(empId); cmtBean.updateEmployee(emp); assertTrue("could not load added employee", emp != null); assertTrue("EntityListener wasn't invoked twice as expected, instead " + MyListener.getInvocationCount(), 2 == MyListener.getInvocationCount()); } @Test public void testInjectedPersistenceContext() throws Exception { Assert.assertTrue("CdiJpaInjectingBean should be true but is", TestState.isJpaInjectingBeanAvailable()); Assert.assertTrue("injected EntityManagerFactory should not be null but is", TestState.isEntityManagerFactoryAvailable()); Assert.assertTrue("injected EntityManager should not be null but is", TestState.isEntityManagerAvailable()); } @ArquillianResource private static InitialContext iniCtx; protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName())); } protected <T> T rawLookup(String name, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup(name)); } }
6,948
40.610778
200
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/initializeinorder/MyListener.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.initializeinorder; import jakarta.annotation.PostConstruct; import jakarta.ejb.EJBContext; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.persistence.PrePersist; import jakarta.persistence.PreUpdate; public class MyListener { private static volatile int invocationCount = 0; private static volatile int postCtorInvocationCount = 0; public static int getInvocationCount() { return invocationCount; } public static void setInvocationCount(int invocationCount) { MyListener.invocationCount = invocationCount; } public static int getPostCtorInvocationCount() { return postCtorInvocationCount; } public static void setPostCtorInvocationCount(int postCtorInvocationCount) { MyListener.postCtorInvocationCount = postCtorInvocationCount; } @PrePersist @PreUpdate public void onEntityCallback(Object entity) { try { invocationCount++; InitialContext jndiContext = new InitialContext(); EJBContext ctx = (EJBContext) jndiContext.lookup("java:comp/EJBContext"); //System.out.println(ctx.getCallerPrincipal().getName() + ", entity=" + entity); } catch (NamingException e) { throw new RuntimeException("initial context error", e); } } @PostConstruct public void postCtor() { postCtorInvocationCount++; } }
2,504
32.851351
92
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/initializeinorder/TestState.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.as.test.integration.jpa.initializeinorder; import java.util.ArrayList; import java.util.List; /** * TestState * * @author Scott Marlow */ public class TestState { private static final List<String> initOrder = new ArrayList<String>(); private static boolean gotJpaInjectingBean; private static boolean gotEntityManagerFactory; private static boolean gotEntityManager; public static boolean isJpaInjectingBeanAvailable() { return gotJpaInjectingBean; } public static void setJpaInjectingBeanAvailable() { gotJpaInjectingBean = true; } public static boolean isEntityManagerFactoryAvailable() { return gotEntityManagerFactory; } public static void setEntityManagerFactoryAvailable() { gotEntityManagerFactory = true; } public static boolean isEntityManagerAvailable() { return gotEntityManager; } public static void setEntityManagerAvailable() { gotEntityManager = true; } public static final List<String> getInitOrder() { return new ArrayList(initOrder); } public static void addInitOrder(String simpleName) { initOrder.add(simpleName); } public static void clearInitOrder() { initOrder.clear(); } }
1,999
26.777778
75
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/initializeinorder/SFSBCMT.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.initializeinorder; import jakarta.ejb.LocalBean; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; /** * stateful session bean * * @author Scott Marlow */ @Stateful @LocalBean @TransactionManagement(TransactionManagementType.CONTAINER) public class SFSBCMT extends AbstractCMTBean { }
1,424
34.625
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/initializeinorder/QualifyEntityManager.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.initializeinorder; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; /** * QualifyEntityManager * * @author Scott Marlow */ @Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER}) public @interface QualifyEntityManager { }
1,652
34.934783
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/initializeinorder/MyEjb.java
package org.jboss.as.test.integration.jpa.initializeinorder; import jakarta.annotation.PostConstruct; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; /** * @author Scott Marlow */ @Singleton @Startup public class MyEjb { @PersistenceContext(unitName = "pu1") EntityManager em; @PersistenceContext(unitName = "pu2") EntityManager em2; @PostConstruct public void postConstruct() { TestState.addInitOrder(MyEjb.class.getSimpleName()); } public boolean hasPersistenceContext() { return em != null && em2 != null; } }
672
20.709677
60
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/initializeinorder/QualifyEntityManagerFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.initializeinorder; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import jakarta.inject.Qualifier; /** * QualifyEntityManagerFactory * * @author Scott Marlow */ @Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER}) public @interface QualifyEntityManagerFactory { }
1,666
35.23913
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/initializeinorder/CdiJpaInjectingBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2021, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.initializeinorder; import jakarta.enterprise.inject.Produces; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.PersistenceContext; import jakarta.persistence.PersistenceUnit; public class CdiJpaInjectingBean { @Produces @QualifyEntityManagerFactory @PersistenceUnit(unitName = "pu1") EntityManagerFactory emf; @Produces @QualifyEntityManager @PersistenceContext(unitName = "pu1") EntityManager em; public EntityManagerFactory entityManagerFactory() { return emf; } public EntityManager entityManager() { return em; } }
1,725
32.192308
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/initializeinorder/MyEjb2.java
package org.jboss.as.test.integration.jpa.initializeinorder; import jakarta.annotation.PostConstruct; import jakarta.ejb.Singleton; import jakarta.ejb.Startup; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; /** * @author Scott Marlow */ @Singleton @Startup public class MyEjb2 { @PersistenceContext(unitName = "pu1") EntityManager em; @PersistenceContext(unitName = "pu2") EntityManager em2; @PostConstruct public void postConstruct() { TestState.addInitOrder(MyEjb2.class.getSimpleName()); } public boolean hasPersistenceContext() { return em != null && em2 != null; } }
674
20.774194
61
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/cfgfile/Employee.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.cfgfile; import jakarta.persistence.Cacheable; import jakarta.persistence.Entity; import jakarta.persistence.Id; /** * Cachable Employee entity class * * @author Scott Marlow */ @Entity @Cacheable(true) public class Employee { @Id private int id; private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
1,776
24.385714
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/cfgfile/CfgFileTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.cfgfile; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Test Hibernate configuration in hibernate.cfg.xml file * * @author Zbynek Roubalik */ @RunWith(Arquillian.class) public class CfgFileTestCase { private static final String ARCHIVE_NAME = "jpa_cfgfile"; private static final String hibernate_cfg_xml = "<?xml version='1.0' encoding='utf-8'?>\n " + "<!DOCTYPE hibernate-configuration>\n" + "<hibernate-configuration>\n" + "<session-factory>\n" + " <property name=\"show_sql\">true</property>\n" + " <property name=\"hibernate.default_batch_fetch_size\">5</property>\n" + " <property name=\"dialect\">org.hibernate.dialect.HSQLDialect</property>\n" + " <property name=\"hibernate.hbm2ddl.auto\">create-drop</property>\n" + " </session-factory>\n" + "</hibernate-configuration>"; @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses(CfgFileTestCase.class, Employee.class, SFSB1.class ); jar.addAsManifestResource(CfgFileTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); jar.addAsResource(new StringAsset(hibernate_cfg_xml), "hibernate.cfg.xml"); return jar; } @ArquillianResource private InitialContext iniCtx; protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName())); } protected <T> T rawLookup(String name, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup(name)); } @Test public void testEntityManagerInvocation() throws Exception { SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); sfsb1.getEmployeeNoTX(1); } }
3,604
37.763441
129
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/cfgfile/SFSB1.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.cfgfile; import jakarta.ejb.Stateful; import jakarta.persistence.EntityManager; import jakarta.persistence.LockModeType; import jakarta.persistence.PersistenceContext; /** * stateful session bean * * @author Scott Marlow and Zbynek Roubalik */ @Stateful public class SFSB1 { @PersistenceContext(unitName = "mypc") EntityManager em; public void createEmployee(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); em.persist(emp); } public Employee getEmployeeNoTX(int id) { return em.find(Employee.class, id, LockModeType.NONE); } }
1,755
32.132075
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/transaction/SFSBXPC.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.transaction; import jakarta.annotation.Resource; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.persistence.PersistenceContextType; import jakarta.transaction.NotSupportedException; import jakarta.transaction.SystemException; import jakarta.transaction.UserTransaction; /** * stateful session bean with an extended persistence context * * @author Scott Marlow */ @Stateful @TransactionManagement(TransactionManagementType.BEAN) public class SFSBXPC { @PersistenceContext(unitName = "mypc", type = PersistenceContextType.EXTENDED) EntityManager extendedEm; @Resource UserTransaction tx; public void createEmployeeNoTx(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); extendedEm.persist(emp); } /** * UT part of test for JPA 7.9.1 Container Responsibilities for XPC * <p> * "When a business method of the stateful session bean is invoked, if the stateful session bean * uses bean managed transaction demarcation and a UserTransaction is begun within the method, * the container associates the persistence context with the Jakarta Transactions transaction and calls * EntityManager.joinTransaction. * " */ public void savePendingChanges() { try { tx.begin(); tx.commit(); } catch (Exception e) { throw new RuntimeException("could not commit pending extended persistence changes", e); } } public void forceRollbackAndLosePendingChanges(int id, boolean shouldOfSavedAlready) { Employee employee = extendedEm.find(Employee.class, id); if (employee == null) { // employee should be found throw new RuntimeException("pending database changes were not saved previously, could not find Employee id = " + id); } try { tx.begin(); tx.rollback(); } catch (NotSupportedException ignore) { } catch (SystemException ignore) { } employee = extendedEm.find(Employee.class, id); if (shouldOfSavedAlready && employee == null) { throw new RuntimeException("unexpectedly in forceRollbackAndLosePendingChanges(), rollback lost Employee id = " + id + ", which should of been previously saved"); } else if (!shouldOfSavedAlready && employee != null) { throw new RuntimeException("unexpectedly in forceRollbackAndLosePendingChanges(), database changes shouldn't of been saved yet for Employee id = " + id); } } public Employee lookup(int empid) { return extendedEm.find(Employee.class, empid); } }
3,960
35.675926
174
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/transaction/UnsynchronizedSFSB.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.transaction; import jakarta.ejb.EJB; import jakarta.ejb.Stateful; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.persistence.SynchronizationType; /** * stateful session bean * * @author Scott Marlow */ @Stateful public class UnsynchronizedSFSB { @PersistenceContext(unitName = "unsynchronized", synchronization = SynchronizationType.UNSYNCHRONIZED) EntityManager em; @EJB InnerUnsynchronizedSFSB innerUnsynchronizedSFSB; // for UNSYNCHRONIZED propagation test @EJB InnerSynchronizedSFSB innerSynchronizedSFSB; // forces a mixed SYNCHRONIZATION/UNSYNCHRONIZED ERROR public Employee createAndFind(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); em.persist(emp); // new employee will not be saved to the database return em.find(Employee.class, id); } public void createAndJoin(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); em.persist(emp); em.joinTransaction(); // new employee will be saved to database } public Employee find(int id) { return em.find(Employee.class, id); } public Employee createAndPropagatedFind(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); em.persist(emp); // new employee will not be saved to the database return innerUnsynchronizedSFSB.find(id); } public Employee createAndPropagatedFindMixExceptionExcepted(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); em.persist(emp); // new employee will not be saved to the database return innerSynchronizedSFSB.find(id); } public void createAndPropagatedJoin(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); em.persist(emp); // new employee will not be saved to the database innerUnsynchronizedSFSB.joinTransaction(); } }
3,495
32.941748
110
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/transaction/Employee.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.transaction; import jakarta.persistence.Entity; import jakarta.persistence.Id; /** * Employee entity class * * @author Scott Marlow */ @Entity public class Employee { @Id private int id; private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
1,715
24.61194
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/transaction/SFSBCMT.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.transaction; import jakarta.annotation.Resource; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.persistence.Query; /** * stateful session bean * * @author Scott Marlow */ @Stateful @TransactionManagement(TransactionManagementType.CONTAINER) public class SFSBCMT { @PersistenceContext(unitName = "mypc") EntityManager em; @Resource SessionContext sessionContext; @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public Employee queryEmployeeNameRequireNewTX(int id) { Query q = em.createQuery("SELECT e FROM Employee e where id=?"); q.setParameter(1, new Integer(id)); return (Employee) q.getSingleResult(); } }
2,046
33.694915
72
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/transaction/InnerUnsynchronizedSFSB.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.transaction; import jakarta.ejb.Stateful; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.persistence.SynchronizationType; /** * stateful session bean * * @author Scott Marlow */ @Stateful public class InnerUnsynchronizedSFSB { @PersistenceContext(unitName = "unsynchronized", synchronization = SynchronizationType.UNSYNCHRONIZED) EntityManager em; public Employee find(int id) { return em.find(Employee.class, id); } // join persistence context to Jakarta Transactions transaction to save pending changes to database public void joinTransaction() { em.joinTransaction(); } }
1,750
34.734694
106
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/transaction/InnerSynchronizedSFSB.java
/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.transaction; import jakarta.ejb.Stateful; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.persistence.SynchronizationType; /** * stateful session bean * * @author Scott Marlow */ @Stateful public class InnerSynchronizedSFSB { @PersistenceContext(unitName = "unsynchronized", synchronization = SynchronizationType.SYNCHRONIZED) EntityManager em; public Employee find(int id) { return em.find(Employee.class, id); } // join persistence context to Jakarta Transactions transaction to save pending changes to database public void joinTransaction() { em.joinTransaction(); } }
1,746
34.653061
104
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/transaction/UnsynchronizedSFSBXPC.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.transaction; import jakarta.ejb.Stateful; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.persistence.PersistenceContextType; import jakarta.persistence.SynchronizationType; /** * stateful session bean * * @author Scott Marlow */ @Stateful public class UnsynchronizedSFSBXPC { @PersistenceContext(unitName = "unsynchronized", type = PersistenceContextType.EXTENDED, synchronization = SynchronizationType.UNSYNCHRONIZED) EntityManager em; public Employee createAndFind(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); em.persist(emp); // new employee will not be saved to the database return em.find(Employee.class, id); } public Employee find(int id) { return em.find(Employee.class, id); } }
1,992
34.589286
146
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/transaction/TransactionTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.transaction; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.persistence.TransactionRequiredException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.junit.InSequence; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Transaction tests * * @author Scott Marlow and Zbynek Roubalik */ @RunWith(Arquillian.class) public class TransactionTestCase { private static final String ARCHIVE_NAME = "jpa_transaction"; @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses(TransactionTestCase.class, Employee.class, Company.class, SFSB1.class, SFSBXPC.class, SFSBCMT.class, SLSB1.class, UnsynchronizedSFSB.class, InnerUnsynchronizedSFSB.class, UnsynchronizedSFSBXPC.class, InnerSynchronizedSFSB.class ); jar.addAsManifestResource(TransactionTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); return jar; } @ArquillianResource private static InitialContext iniCtx; protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName())); } protected <T> T rawLookup(String name, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup(name)); } @Test @InSequence(1) public void testMultipleNonTXTransactionalEntityManagerInvocations() throws Exception { SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); sfsb1.getEmployeeNoTX(1); // For each call in, we will use a transactional entity manager // that isn't running in a transaction. So, a new underlying // entity manager will be obtained. The is to ensure that we don't blow up. sfsb1.getEmployeeNoTX(1); sfsb1.getEmployeeNoTX(1); } @Test @InSequence(2) public void testQueryNonTXTransactionalEntityManagerInvocations() throws Exception { SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); String name = sfsb1.queryEmployeeNameNoTX(1); assertEquals("Query should of thrown NoResultException, which we indicate by returning 'success'", "success", name); } // Test that the queried Employee is detached as required by JPA 2.0 section 3.8.6 // For a transaction scoped persistence context non Jakarta Transactions tx invocation, entities returned from Query // must be detached. @Test @InSequence(3) public void testQueryNonTXTransactionalDetach() throws Exception { SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); sfsb1.createEmployee("Jill", "54 Country Lane", 2); Employee employee = sfsb1.queryEmployeeNoTX(2); assertNotNull(employee); boolean detached = sfsb1.isQueryEmployeeDetached(2); assertTrue("JPA 2.0 section 3.8.6 violated, query returned entity in non-tx that wasn't detached ", detached); } /** * Ensure that calling entityManager.flush outside of a transaction, throws a TransactionRequiredException * * @throws Exception */ @Test @InSequence(4) public void testTransactionRequiredException() throws Exception { Throwable error = null; try { SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); sfsb1.createEmployeeNoTx("Sally", "1 home street", 1); } catch (TransactionRequiredException e) { error = e; } catch (Exception failed) { error = failed; } // jakarta.ejb.EJBException: jakarta.persistence.TransactionRequiredException: no transaction is in progress while (error != null && !(error instanceof TransactionRequiredException) && error.getCause() != null) { error = error.getCause(); } assertTrue( "attempting to persist entity with transactional entity manager and no transaction, should fail with a TransactionRequiredException" + " but we instead got a " + error, error instanceof TransactionRequiredException); } /** * Tests Jakarta Transactions involving an EJB 3 SLSB which makes two DAO calls in transaction. * Scenarios: * 1) The transaction fails during the first DAO call and the Jakarta Transactions transaction is rolled back and no database changes should occur. * 2) The transaction fails during the second DAO call and the Jakarta Transactions transaction is rolled back and no database changes should occur. * 3) The transaction fails after the DAO calls and the Jakarta Transactions transaction is rolled back and no database changes should occur. */ @Test @InSequence(5) public void testFailInDAOCalls() throws Exception { SLSB1 slsb1 = lookup("SLSB1", SLSB1.class); slsb1.addEmployee(); String message = slsb1.failInFirstCall(); assertEquals("DB should be unchanged, which we indicate by returning 'success'", "success", message); message = slsb1.failInSecondCall(); assertEquals("DB should be unchanged, which we indicate by returning 'success'", "success", message); message = slsb1.failAfterCalls(); assertEquals("DB should be unchanged, which we indicate by returning 'success'", "success", message); } @Test @InSequence(6) public void testUserTxRollbackDiscardsChanges() throws Exception { SFSBXPC sfsbxpc = lookup("SFSBXPC", SFSBXPC.class); sfsbxpc.createEmployeeNoTx("Amory Lorch", "Lannister House", 10); // create the employee but leave in xpc Employee employee = sfsbxpc.lookup(10); assertNotNull("could read employee record from extended persistence context (not yet saved to db)", employee); // rollback any changes that haven't been saved yet sfsbxpc.forceRollbackAndLosePendingChanges(10, false); employee = sfsbxpc.lookup(10); assertNull("employee record should not be found in db after rollback", employee); } @Test @InSequence(7) public void testEnlistXPCInUserTx() throws Exception { SFSBXPC sfsbxpc = lookup("SFSBXPC", SFSBXPC.class); sfsbxpc.createEmployeeNoTx("Amory Lorch", "Lannister House", 20); // create the employee but leave in xpc Employee employee = sfsbxpc.lookup(20); assertNotNull("could read employee record from extended persistence context (not yet saved to db)", employee); // start/end a user transaction without invoking the (extended) entity manager, which should cause the // pending changes to be saved to db sfsbxpc.savePendingChanges(); sfsbxpc.forceRollbackAndLosePendingChanges(20, true); employee = sfsbxpc.lookup(20); assertNotNull("could read employee record from extended persistence context (wasn't saved to db during savePendingChanges())", employee); } /** * test JPA 2.1 SynchronizationType.UNSYNCHRONIZED support * <p> * Note: Each invocation to UnsynchronizedSFSB will get a new persistence context as expected for transaction scoped entity manager. */ @Test @InSequence(8) public void testUnsynchronized() throws Exception { UnsynchronizedSFSB unsynchronizedSFSB = lookup("UnsynchronizedSFSB", UnsynchronizedSFSB.class); SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); // create entity in UNSYNCHRONIZED persistence context which shouldn't be stored in the database until after em.joinTransaction() Employee employee = unsynchronizedSFSB.createAndFind("New England Revolution", "Gillette Stadium", 50); assertNotNull("SynchronizationType.UNSYNCHRONIZED should be visible in the same persistence context", employee); // we should see new employee in unsynchronized persistence context employee = sfsb1.getEmployeeNoTX(50); assertNull("SynchronizationType.UNSYNCHRONIZED change is visible to separate persistence context", employee); // other persistence context shouldn't see unsynchronized (pending) changes unsynchronizedSFSB.createAndJoin("New England Revolution", "Gillette Stadium", 50); employee = sfsb1.getEmployeeNoTX(50); // so that other persistence context can also see new entity assertNotNull("SynchronizationType.UNSYNCHRONIZED should be visible to separate persistence context after joining persistence context to Jakarta Transactions transaction", employee); // check that propagation of UNSYNCHRONIZED persistence context happens during call to inner bean and that // inner bean sees new entity that hasn't been saved to the database employee = unsynchronizedSFSB.createAndPropagatedFind("Catherine Stark", "Winterfell", 55); assertNotNull("SynchronizationType.UNSYNCHRONIZED should be propagated across bean invocations as per JPA 2.1 section 7.6.4", employee); unsynchronizedSFSB.createAndPropagatedJoin("Jon Snow", "knows nothing", 56); employee = unsynchronizedSFSB.find(56); assertNotNull("SynchronizationType.UNSYNCHRONIZED should be propagated across bean invocations as per JPA 2.1 section 7.6.4 and " + "pending changes saved when inner bean calls EntityManager.joinTransaction", employee); } @Test @InSequence(9) public void testUnsynchronizedXPC() throws Exception { UnsynchronizedSFSBXPC unsynchronizedSFSBXPC = lookup("UnsynchronizedSFSBXPC", UnsynchronizedSFSBXPC.class); SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); // create entity in UNSYNCHRONIZED persistence context which shouldn't be stored in the database until after em.joinTransaction() Employee employee = unsynchronizedSFSBXPC.createAndFind("Tom Jones", "Singer", 500); assertNotNull("SynchronizationType.UNSYNCHRONIZED should be visible in the same extended persistence context within same tx", employee); // we should see new employee in unsynchronized persistence context employee = sfsb1.getEmployeeNoTX(500); assertNull("entity created in SynchronizationType.UNSYNCHRONIZED XPC should not of been saved to database", employee); // same extended persistence context } @Test @InSequence(10) public void testQueryNonTXTransactionalDetachIsDeferred() throws Exception { SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); sfsb1.createEmployee("Mad", "368 Mad Country Lane", 204); assertTrue("expecting that lazily fetched association is still attached, so that we can verify its lazy fetched collection size of one", sfsb1.isLazyAssociationAccessibleWithDeferredDetach(204)); } @Test @InSequence(11) public void testSyncUnsynchMixedErrorExpected() throws Exception { UnsynchronizedSFSB unsynchronizedSFSB = lookup("UnsynchronizedSFSB", UnsynchronizedSFSB.class); try { Employee employee = unsynchronizedSFSB.createAndPropagatedFindMixExceptionExcepted("Catherine Stark", "Winterfell", 203); fail("If there is a persistence context of type SynchronizationType.UNSYNCHRONIZED\n" + "associated with the Jakarta Transactions transaction and the target component specifies a persistence context of\n" + "type SynchronizationType.SYNCHRONIZED, the IllegalStateException is\n" + "thrown by the container."); } catch (/*EJBTransactionRolledbackException*/ Exception expected) { assertTrue("should of been caused by IllegalStateException", expected.getCause() instanceof IllegalStateException); } } }
13,486
46.322807
215
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/transaction/SFSB1.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.transaction; import java.util.HashSet; import jakarta.annotation.Resource; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; import jakarta.persistence.EntityManager; import jakarta.persistence.NoResultException; import jakarta.persistence.PersistenceContext; import jakarta.persistence.Query; import jakarta.persistence.TypedQuery; import jakarta.transaction.UserTransaction; /** * stateful session bean * * @author Scott Marlow */ @Stateful @TransactionManagement(TransactionManagementType.BEAN) public class SFSB1 { @PersistenceContext(unitName = "mypc") EntityManager em; @PersistenceContext(unitName = "deferdetachpc") EntityManager deferDetachEm; @Resource SessionContext sessionContext; // always throws a TransactionRequiredException public void createEmployeeNoTx(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); UserTransaction tx1 = sessionContext.getUserTransaction(); try { tx1.begin(); em.joinTransaction(); em.persist(emp); tx1.commit(); } catch (Exception e) { throw new RuntimeException("couldn't start tx", e); } em.flush(); // should throw TransactionRequiredException } public void createEmployee(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); Company theCompany = new Company(); theCompany.setId(id); // reuse the employee id HashSet set = new HashSet(); set.add(emp); theCompany.setEmployees(set); UserTransaction tx1 = sessionContext.getUserTransaction(); try { tx1.begin(); em.joinTransaction(); em.persist(emp); em.persist(theCompany); tx1.commit(); } catch (Exception e) { throw new RuntimeException("couldn't start tx", e); } } public Employee getEmployeeNoTX(int id) { return em.find(Employee.class, id); } public String queryEmployeeNameNoTX(int id) { Query q = em.createQuery("SELECT e.name FROM Employee e where e.id=:id"); q.setParameter("id", new Integer(id)); try { String name = (String) q.getSingleResult(); return name; } catch (NoResultException expected) { return "success"; } catch (Exception unexpected) { return unexpected.getMessage(); } } public Employee queryEmployeeNoTX(int id) { TypedQuery<Employee> q = em.createQuery("SELECT e FROM Employee e where e.id=:id", Employee.class); q.setParameter("id", new Integer(id)); return q.getSingleResult(); } // return true if the queried Employee is detached as required by JPA 2.0 section 3.8.6 // For a transaction scoped persistence context non Jakarta Transactions tx invocation, entities returned from Query // must be detached. public boolean isQueryEmployeeDetached(int id) { TypedQuery<Employee> q = em.createQuery("SELECT e FROM Employee e where e.id=:id", Employee.class); q.setParameter("id", new Integer(id)); Employee employee = q.getSingleResult(); return em.contains(employee) != true; } // return true if lazy associations are accessible as per the WFLY-3674 extension (jboss.as.jpa.deferdetach) public boolean isLazyAssociationAccessibleWithDeferredDetach(int id) { Company company = deferDetachEm.find(Company.class, id); return company.getEmployees().size() == 1; } }
4,925
32.972414
120
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/transaction/Company.java
package org.jboss.as.test.integration.jpa.transaction; import java.util.HashSet; import java.util.Set; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; /** * Company * * @author Scott Marlow */ @Entity public class Company { public int getId() { return id; } public void setId(int id) { this.id = id; } public Set<Employee> getEmployees() { return employees; } public void setEmployees(Set<Employee> employees) { this.employees = employees; } @Id private int id; @OneToMany(fetch = FetchType.LAZY) public Set<Employee> employees = new HashSet<Employee>(); }
744
17.170732
61
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/transaction/SLSB1.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.transaction; import java.sql.Connection; import java.sql.ResultSet; import java.util.Arrays; import jakarta.annotation.Resource; import jakarta.ejb.Stateless; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; import javax.naming.Context; import javax.naming.InitialContext; import jakarta.persistence.EntityExistsException; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import javax.sql.DataSource; import jakarta.transaction.UserTransaction; /** * @author Zbynek Roubalik */ @Stateless @TransactionManagement(TransactionManagementType.BEAN) public class SLSB1 { @PersistenceContext(unitName = "mypc") EntityManager em; @Resource UserTransaction tx; public Employee createEmployee(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); return emp; } /** * Makes two DAO calls, the transaction fails during the first DAO call. The * Jakarta Transactions transaction is rolled back and no database changes should occur. */ public String failInFirstCall() throws Exception { int[] initialList = getEmployeeIDsNoEM(); try { tx.begin(); performFailCall(); em.persist(createEmployee("Tony", "Butcher", 101)); tx.commit(); return "Transaction was performed, but shouldn't"; } catch (EntityExistsException e) { tx.rollback(); int[] newList = getEmployeeIDsNoEM(); if (Arrays.equals(initialList, newList)) { return "success"; } else { return "Database changed."; } } } /** * Makes two DAO calls, the transaction fails during the second DAO call. * The Jakarta Transactions transaction is rolled back and no database changes should occur. */ @TransactionAttribute(TransactionAttributeType.REQUIRED) public String failInSecondCall() throws Exception { int[] initialList = getEmployeeIDsNoEM(); try { tx.begin(); em.persist(createEmployee("Jane", "Butcher", 102)); performFailCall(); tx.commit(); return "Transaction was performed, but shouldn't"; } catch (EntityExistsException e) { tx.rollback(); int[] newList = getEmployeeIDsNoEM(); if (Arrays.equals(initialList, newList)) { return "success"; } else { return "Database changed."; } } catch (Exception unexpected) { return unexpected.getMessage(); } } /** * Makes two DAO calls, the transaction fails after the DAO calls. * The Jakarta Transactions rolled back and no database changes should occur. */ public String failAfterCalls() throws Exception { int[] initialList = getEmployeeIDsNoEM(); try { tx.begin(); em.persist(createEmployee("Peter", "Butcher", 103)); em.persist(createEmployee("John", "Butcher", 104)); int n = 100 / 0; // this should throw exception: division by zero n = n + 20; tx.commit(); return "Transaction was performed, but shouldn't"; } catch (Exception e) { tx.rollback(); int[] newList = getEmployeeIDsNoEM(); if (Arrays.equals(initialList, newList)) { return "success"; } else { return "Database changed."; } } } /** * Persisting existing entity, should throws EntityExistsException */ public void performFailCall() { Employee emp = em.find(Employee.class, 1212); if (emp == null) { emp = createEmployee("Mr. Problem", "Brno ", 1212); em.persist(emp); em.flush(); } em.persist(createEmployee(emp.getName(), emp.getAddress(), emp.getId())); } /** * Returns array of Employee IDs in DB using raw connection to the * DataSource */ public int[] getEmployeeIDsNoEM() throws Exception { int[] idList = null; Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx .lookup("java:jboss/datasources/ExampleDS"); Connection conn = ds.getConnection(); try { ResultSet rs = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY).executeQuery( "SELECT e.id FROM Employee e ORDER BY e.id"); rs.last(); int rowCount = rs.getRow(); idList = new int[rowCount]; rs.first(); int i = 0; while (rs.next()) { idList[i] = rs.getInt(1); i++; } } catch (Exception e) { e.printStackTrace(); } finally { conn.close(); } return idList; } /** * Adds new Employee */ public void addEmployee() throws Exception { try { tx.begin(); em.persist(createEmployee("John", "Wayne", 100)); tx.commit(); } catch (Exception e) { throw new Exception("Couldn't add an Employee."); } } }
6,655
29.392694
96
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/transaction/envers/Employee.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.transaction.envers; import jakarta.persistence.Entity; import jakarta.persistence.Id; import org.hibernate.envers.Audited; /** * Employee entity class * * @author Madhumita Sadhukhan */ @Entity @Audited public class Employee { @Id private int id; private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
1,776
24.385714
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/transaction/envers/TransactionAuditedTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.transaction.envers; import static org.junit.Assert.assertEquals; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.persistence.TransactionRequiredException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * Test Envers on Transactions * * @author Madhumita Sadhukhan */ @RunWith(Arquillian.class) public class TransactionAuditedTestCase { private static final String ARCHIVE_NAME = "jpa_sessionfactory"; @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addClasses(TransactionAuditedTestCase.class, Employee.class, SFSB1.class); jar.addAsManifestResource(TransactionAuditedTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); return jar; } @ArquillianResource private static InitialContext iniCtx; protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { return interfaceType .cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName())); } protected <T> T rawLookup(String name, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup(name)); } /** * Ensure that auditing works with transactions */ @Test public void testAuditingOverTransaction() throws Exception { try { SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); Employee emp = sfsb1.createEmployeeTx("Madhumita", "1 home street", 1); sfsb1.updateEmployeeTx("40 Patrice Lumumby", emp); sfsb1.updateEmployeeTx("40 Patrice Lumumby Ostrava CZ", emp); String address = sfsb1.retrieveOldEmployeeVersion(emp.getId()); assertEquals("1 home street", address); } catch (TransactionRequiredException e) { System.out.println("TransactionRequiredException in catch:--"); } catch (Exception failed) { System.out.println("Exception in catch:--"); } } /** * Ensure that auditing does not save data not committed when a transaction is rolled back * * @throws Exception */ @Test public void testAuditingOverTransactionRollback() throws Exception { SFSB1 sfsb1 = lookup("SFSB1", SFSB1.class); Employee emp = null; try { emp = sfsb1.createEmployeeTx("Kaushik", "Red Hat Purkynova Brno", 2); sfsb1.updateEmployeeTxwithRollBack("Vratimovska 689", emp); sfsb1.updateEmployeeTx("Vratimovska 689", emp); sfsb1.updateEmployeeTx("Schwaigrova 2 Brno CZ", emp); sfsb1.updateEmployeeTx("40 Patrice Lumumby Ostrava CZ", emp); } catch (Exception e) { System.out.println("Rollback in testAuditingOverTransactionRollback() catch:--"); } } }
4,307
34.9
119
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/transaction/envers/SFSB1.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.transaction.envers; import static org.junit.Assert.assertEquals; import jakarta.annotation.Resource; import jakarta.ejb.SessionContext; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.transaction.UserTransaction; import org.hibernate.envers.AuditReader; import org.hibernate.envers.AuditReaderFactory; /** * stateful session bean * * @author Madhumita Sadhukhan */ @Stateful @TransactionManagement(TransactionManagementType.BEAN) public class SFSB1 { @PersistenceContext(unitName = "mypc") EntityManager em; @Resource SessionContext sessionContext; // create Employee public Employee createEmployeeTx(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); UserTransaction tx1 = sessionContext.getUserTransaction(); try { tx1.begin(); em.joinTransaction(); em.persist(emp); tx1.commit(); return emp; } catch (Exception e) { throw new RuntimeException("couldn't start tx", e); } } public void updateEmployeeTx(String address, Employee emp) { emp.setAddress(address); UserTransaction tx1 = sessionContext.getUserTransaction(); try { tx1.begin(); //System.out.println("Inside JTA updateEmployeeTx after transaction begins:--"); em.joinTransaction(); em.merge(emp); tx1.commit(); } catch (Exception e) { throw new RuntimeException("couldn't start tx", e); } } public void updateEmployeeTxwithRollBack(String address, Employee emp) { emp.setAddress(address); UserTransaction tx1 = sessionContext.getUserTransaction(); try { tx1.begin(); em.joinTransaction(); em.merge(emp); em.getTransaction().setRollbackOnly(); // force rollback of transaction tx1.commit(); } catch (Exception e) { throw new RuntimeException("couldn't start tx", e); } finally { String obtainedaddress = retrieveOldEmployeeVersionforRollBack(emp.getId()); assertEquals("Red Hat Purkynova Brno", obtainedaddress); } } public String retrieveOldEmployeeVersion(int id) { AuditReader reader = AuditReaderFactory.get(em); Employee emp1_rev = reader.find(Employee.class, id, 1); return emp1_rev.getAddress(); } public String retrieveOldEmployeeVersionforRollBack(int id) { AuditReader reader = AuditReaderFactory.get(em); Employee emp1_rev = reader.find(Employee.class, id, 5); return emp1_rev.getAddress(); } }
4,010
30.335938
92
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/entitylistener/SingletonCMT.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.entitylistener; import jakarta.ejb.LocalBean; import jakarta.ejb.Singleton; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; /** * @author Jaikiran Pai */ @Singleton @LocalBean @TransactionManagement(TransactionManagementType.CONTAINER) public class SingletonCMT extends AbstractCMTBean { }
1,400
35.868421
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/entitylistener/AbstractCMTBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.entitylistener; import jakarta.annotation.Resource; import jakarta.ejb.SessionContext; import jakarta.persistence.EntityManager; import jakarta.persistence.LockModeType; import jakarta.persistence.PersistenceContext; /** * @author Jaikiran Pai */ public abstract class AbstractCMTBean { @PersistenceContext(unitName = "mypc") EntityManager em; @Resource SessionContext sessionContext; public void createEmployee(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); em.joinTransaction(); em.persist(emp); //em.flush(); } public void updateEmployee(Employee emp) { emp.setName("hacked " + emp.getName()); em.merge(emp); //em.flush(); } public Employee getEmployeeNoTX(int id) { return em.find(Employee.class, id, LockModeType.NONE); } }
2,014
31.5
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/entitylistener/Employee.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.entitylistener; import jakarta.persistence.Entity; import jakarta.persistence.EntityListeners; import jakarta.persistence.Id; /** * Employee entity class * * @author Scott Marlow */ @Entity @EntityListeners({MyListener.class}) public class Employee { @Id private int id; private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String toString() { return "employee " + name + ", " + address + ", #" + id; } }
1,902
25.068493
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/entitylistener/SFSBBMT.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.entitylistener; import jakarta.ejb.LocalBean; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; /** * stateful session bean * * @author Scott Marlow */ @Stateful @LocalBean @TransactionManagement(TransactionManagementType.BEAN) public class SFSBBMT extends AbstractBMTBean { }
1,416
34.425
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/entitylistener/AbstractBMTBean.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.entitylistener; import jakarta.annotation.Resource; import jakarta.ejb.SessionContext; import jakarta.persistence.EntityManager; import jakarta.persistence.LockModeType; import jakarta.persistence.PersistenceContext; import jakarta.transaction.UserTransaction; /** * @author Jaikiran Pai */ public abstract class AbstractBMTBean { @PersistenceContext(unitName = "mypc") EntityManager em; @Resource SessionContext sessionContext; public void createEmployee(String name, String address, int id) { Employee emp = new Employee(); emp.setId(id); emp.setAddress(address); emp.setName(name); UserTransaction tx1 = sessionContext.getUserTransaction(); try { tx1.begin(); em.joinTransaction(); em.persist(emp); //em.flush(); tx1.commit(); } catch (Exception e) { throw new RuntimeException("couldn't start tx", e); } } public void updateEmployee(Employee emp) { emp.setName("hacked " + emp.getName()); UserTransaction tx1 = sessionContext.getUserTransaction(); try { tx1.begin(); em.joinTransaction(); em.merge(emp); //em.flush(); tx1.commit(); } catch (Exception e) { throw new RuntimeException("couldn't start tx", e); } } public Employee getEmployeeNoTX(int id) { return em.find(Employee.class, id, LockModeType.NONE); } }
2,592
30.621951
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/entitylistener/MyListener.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.entitylistener; import jakarta.annotation.PostConstruct; import jakarta.ejb.EJBContext; import javax.naming.InitialContext; import javax.naming.NamingException; import jakarta.persistence.PrePersist; import jakarta.persistence.PreUpdate; /** * test case from AS7-2968 */ public class MyListener { private static volatile int invocationCount = 0; private static volatile int postCtorInvocationCount = 0; public static int getInvocationCount() { return invocationCount; } public static void setInvocationCount(int invocationCount) { MyListener.invocationCount = invocationCount; } public static int getPostCtorInvocationCount() { return postCtorInvocationCount; } public static void setPostCtorInvocationCount(int postCtorInvocationCount) { MyListener.postCtorInvocationCount = postCtorInvocationCount; } @PrePersist @PreUpdate public void onEntityCallback(Object entity) { try { invocationCount++; InitialContext jndiContext = new InitialContext(); EJBContext ctx = (EJBContext) jndiContext.lookup("java:comp/EJBContext"); //System.out.println(ctx.getCallerPrincipal().getName() + ", entity=" + entity); } catch (NamingException e) { throw new RuntimeException("initial context error", e); } } @PostConstruct public void postCtor() { postCtorInvocationCount++; } }
2,537
31.538462
92
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/entitylistener/SLSBCMT.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.entitylistener; import jakarta.ejb.LocalBean; import jakarta.ejb.Stateless; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; /** * @author Jaikiran Pai */ @Stateless @LocalBean @TransactionManagement(TransactionManagementType.CONTAINER) public class SLSBCMT extends AbstractCMTBean { }
1,395
35.736842
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/entitylistener/SFSBCMT.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.entitylistener; import jakarta.ejb.LocalBean; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; /** * stateful session bean * * @author Scott Marlow */ @Stateful @LocalBean @TransactionManagement(TransactionManagementType.CONTAINER) public class SFSBCMT extends AbstractCMTBean { }
1,421
34.55
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/entitylistener/EntityListenersTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.entitylistener; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; /** * EntityListeners tests * * @author Scott Marlow */ @RunWith(Arquillian.class) public class EntityListenersTestCase { private static final String ARCHIVE_NAME = "jpa_EntityListeners"; @Deployment public static Archive<?> deploy() { JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar"); jar.addPackage(EntityListenersTestCase.class.getPackage()); jar.addAsManifestResource(EntityListenersTestCase.class.getPackage(), "persistence.xml", "persistence.xml"); jar.addAsManifestResource(EntityListenersTestCase.class.getPackage(), "beans.xml", "beans.xml"); return jar; } @ArquillianResource private static InitialContext iniCtx; protected <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + beanName + "!" + interfaceType.getName())); } protected <T> T rawLookup(String name, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup(name)); } /** * Tests that the entity listeners are correctly invoked and have access to the java:comp/EJBContext * when an entity is persisted via a stateful BMT bean * * @throws Exception */ @Test public void testSFSBBMT() throws Exception { MyListener.setInvocationCount(0); SFSBBMT bmt = lookup("SFSBBMT", SFSBBMT.class); this.doBMTTest(bmt, 1); } /** * Tests that the entity listeners are correctly invoked and have access to the java:comp/EJBContext * when an entity is persisted via a stateful CMT bean * * @throws Exception */ @Test public void testSFSBCMT() throws Exception { MyListener.setInvocationCount(0); SFSBCMT cmt = lookup("SFSBCMT", SFSBCMT.class); this.doCMTTest(cmt, 2); } /** * Test that @PostConstruct is invoked * * @throws Exception */ @Test public void testCDICallbackInvoked() throws Exception { SFSBCMT cmt = lookup("SFSBCMT", SFSBCMT.class); assertEquals("MyListener should of been created by the BeanManager instance passed into the " + "persistence provider via property 'javax.persistence.bean.manager'. " , 1, MyListener.getPostCtorInvocationCount()); } /** * Tests that the entity listeners are correctly invoked and have access to the java:comp/EJBContext * when an entity is persisted via a stateless CMT bean * * @throws Exception */ @Test public void testSLSBCMT() throws Exception { MyListener.setInvocationCount(0); SLSBCMT cmt = lookup("SLSBCMT", SLSBCMT.class); this.doCMTTest(cmt, 3); } /** * Tests that the entity listeners are correctly invoked and have access to the java:comp/EJBContext * when an entity is persisted via a stateless BMT bean * * @throws Exception */ @Test public void testSLSBBMT() throws Exception { MyListener.setInvocationCount(0); SLSBBMT bmt = lookup("SLSBBMT", SLSBBMT.class); this.doBMTTest(bmt, 4); } /** * Tests that the entity listeners are correctly invoked and have access to the java:comp/EJBContext * when an entity is persisted via a singleton CMT bean * * @throws Exception */ @Test public void testSingletonCMT() throws Exception { MyListener.setInvocationCount(0); SingletonCMT cmt = lookup("SingletonCMT", SingletonCMT.class); this.doCMTTest(cmt, 5); } /** * Tests that the entity listeners are correctly invoked and have access to the java:comp/EJBContext * when an entity is persisted via a singleton BMT bean * * @throws Exception */ @Test public void testSingletonBMT() throws Exception { MyListener.setInvocationCount(0); SingletonBMT bmt = lookup("SingletonBMT", SingletonBMT.class); this.doBMTTest(bmt, 6); } /** * Tests that the entity listeners are correctly invoked and have access to the java:comp/EJBContext * when an entity is persisted via a BMT bean * * @param bmtBean The BMT bean * @throws Exception */ private void doBMTTest(final AbstractBMTBean bmtBean, final int empId) throws Exception { bmtBean.createEmployee("Alfred E. Neuman", "101010 Mad Street", empId); Employee emp = bmtBean.getEmployeeNoTX(empId); bmtBean.updateEmployee(emp); assertTrue("could not load added employee", emp != null); assertTrue("EntityListener wasn't invoked twice as expected, instead " + MyListener.getInvocationCount(), 2 == MyListener.getInvocationCount()); } /** * Tests that the entity listeners are correctly invoked and have access to the java:comp/EJBContext * when an entity is persisted via a CMT bean * * @param cmtBean The CMT bean * @throws Exception */ private void doCMTTest(final AbstractCMTBean cmtBean, final int empId) throws Exception { cmtBean.createEmployee("Alfred E. Neuman", "101010 Mad Street", empId); Employee emp = cmtBean.getEmployeeNoTX(empId); cmtBean.updateEmployee(emp); assertTrue("could not load added employee", emp != null); assertTrue("EntityListener wasn't invoked twice as expected, instead " + MyListener.getInvocationCount(), 2 == MyListener.getInvocationCount()); } }
7,157
34.969849
152
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/entitylistener/SLSBBMT.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.entitylistener; import jakarta.ejb.LocalBean; import jakarta.ejb.Stateless; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; /** * @author Jaikiran Pai */ @Stateless @LocalBean @TransactionManagement(TransactionManagementType.BEAN) public class SLSBBMT extends AbstractBMTBean { }
1,390
35.605263
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jpa/entitylistener/SingletonBMT.java
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.jpa.entitylistener; import jakarta.ejb.LocalBean; import jakarta.ejb.Singleton; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; /** * @author Jaikiran Pai */ @Singleton @LocalBean @TransactionManagement(TransactionManagementType.BEAN) public class SingletonBMT extends AbstractBMTBean { }
1,395
35.736842
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/SFSBHibernateTransaction.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate; import java.util.Properties; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.engine.transaction.jta.platform.internal.JBossAppServerJtaPlatform; import org.hibernate.internal.util.config.ConfigurationHelper; /** * Test operations including rollback using Hibernate transaction and Sessionfactory inititated from hibernate.cfg.xml and * properties added to Hibernate Configuration in AS7 container without any Jakarta Persistence assistance * * @author Madhumita Sadhukhan */ @Stateful @TransactionManagement(TransactionManagementType.BEAN) public class SFSBHibernateTransaction { private static SessionFactory sessionFactory; public void cleanup() { sessionFactory.close(); } public void setupConfig() { // static { try { // prepare the configuration Configuration configuration = new Configuration(); configuration.getProperties().put(AvailableSettings.JTA_PLATFORM, JBossAppServerJtaPlatform.class); configuration.setProperty(Environment.HBM2DDL_AUTO, "create-drop"); configuration.setProperty(Environment.DATASOURCE, "java:jboss/datasources/ExampleDS"); configuration.setProperty("hibernate.listeners.envers.autoRegister", "false"); // fetch the properties Properties properties = new Properties(); configuration = configuration.configure("hibernate.cfg.xml"); properties.putAll(configuration.getProperties()); ConfigurationHelper.resolvePlaceHolders(properties); sessionFactory = configuration.buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed throw new RuntimeException("Could not setup config", ex); } } // create student public Student createStudent(String firstName, String lastName, String address, int id) { // setupConfig(); Student student = new Student(); student.setStudentId(id); student.setAddress(address); student.setFirstName(firstName); student.setLastName(lastName); Session session = sessionFactory.openSession(); try { Transaction trans = session.beginTransaction(); session.save(student); trans.commit(); } catch (Exception e) { throw new RuntimeException("transactional failure while persisting student entity", e); } session.close(); return student; } // update student public Student updateStudent(String address, int id) { Session session = sessionFactory.openSession(); Student student = session.load(Student.class, id); student.setAddress(address); try { // invoking the Hibernate transaction Transaction trans = session.beginTransaction(); session.save(student); trans.commit(); } catch (Exception e) { throw new RuntimeException("transactional failure while persisting student entity", e); } session.close(); return student; } // fetch student public Student getStudentNoTx(int id) { // Transaction trans = sessionFactory.openSession().beginTransaction(); Student emp = sessionFactory.openSession().load(Student.class, id); return emp; } }
4,785
36.100775
122
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/Student.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate; /** * Represents a student object. * * @author Madhumita Sadhukhan */ public class Student { // unique student id private int studentId; // first name of the student private String firstName; // last name of the student private String lastName; // address of the student private String address; /** * Default constructor */ public Student() { } /** * Creates a new instance of Student. * * @param firstName first name. * @param lastName last name. * @param address address. */ public Student(String firstName, String lastName, String address) { this.firstName = firstName; this.lastName = lastName; this.address = address; } /** * Gets the student id for this student. * * @return student id. */ public int getStudentId() { return studentId; } /** * Sets the student id for this student. * * @return student id. */ public void setStudentId(int studentId) { this.studentId = studentId; } /** * Gets the first name for this student. * * @return first name. */ public String getFirstName() { return firstName; } /** * Sets the first name for this student. * * @param first name. */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * Gets the last name for this student. * * @return last name. */ public String getLastName() { return lastName; } /** * Sets the last name for this student. * * @param last name. */ public void setLastName(String lastName) { this.lastName = lastName; } /** * Gets the address for this student. * * @return address. */ public String getAddress() { return address; } /** * Sets the address for this student. * * @param address. */ public void setAddress(String address) { this.address = address; } /** * Method used by the UI to clear information on the screen. * * @return String used in the navigation rules. */ public String clear() { firstName = ""; lastName = ""; address = ""; return "clear"; } }
3,456
23.006944
71
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/Satellite.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate; /** * Represents a satellite object. * * @author Madhumita Sadhukhan */ public class Satellite { private Integer id; private String name; @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Satellite)) { return false; } final Satellite satellite = (Satellite) o; return name.equals(satellite.name); } @Override public int hashCode() { return name.hashCode(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
1,813
25.676471
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/SFSBHibernate2LcacheStats.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate; import static org.junit.Assert.assertEquals; import java.util.HashSet; import java.util.Iterator; import java.util.Properties; import java.util.Set; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.engine.transaction.jta.platform.internal.JBossAppServerJtaPlatform; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.stat.SessionStatistics; import org.hibernate.stat.Statistics; /** * @author Madhumita Sadhukhan */ @Stateful @TransactionManagement(TransactionManagementType.CONTAINER) public class SFSBHibernate2LcacheStats { private static SessionFactory sessionFactory; public void cleanup() { sessionFactory.close(); } @TransactionAttribute(TransactionAttributeType.NEVER) public void setupConfig() { // static { try { // prepare the configuration Configuration configuration = new Configuration(); configuration.getProperties().put(AvailableSettings.JTA_PLATFORM, JBossAppServerJtaPlatform.class); configuration.getProperties().put(AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, "jta"); configuration.setProperty(Environment.HBM2DDL_AUTO, "create-drop"); configuration.setProperty(Environment.DATASOURCE, "java:jboss/datasources/ExampleDS"); // set property to enable statistics configuration.setProperty("hibernate.generate_statistics", "true"); // fetch the properties Properties properties = new Properties(); configuration = configuration.configure("hibernate.cfg.xml"); properties.putAll(configuration.getProperties()); ConfigurationHelper.resolvePlaceHolders(properties); // build the serviceregistry sessionFactory = configuration.buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed ex.printStackTrace(); throw new ExceptionInInitializerError(ex); } //System.out.println("setupConfig: done"); } // create planet public Planet prepareData(String planetName, String galaxyName, String starName, Set<Satellite> satellites, Integer id) { Session session = sessionFactory.openSession(); Planet planet = new Planet(); planet.setPlanetId(id); planet.setPlanetName(planetName); planet.setGalaxy(galaxyName); planet.setStar(starName); // Transaction trans = session.beginTransaction(); try { session.save(planet); if (satellites != null && satellites.size() > 0) { Iterator<Satellite> itrSat = satellites.iterator(); while (itrSat.hasNext()) { Satellite sat = itrSat.next(); session.save(sat); } planet.setSatellites(new HashSet<Satellite>()); planet.getSatellites().addAll(satellites); } session.saveOrUpdate(planet); SessionStatistics stats = session.getStatistics(); assertEquals(2, stats.getEntityKeys().size()); assertEquals(2, stats.getEntityCount()); // session.flush(); // session.close(); } catch (Exception e) { throw new RuntimeException("transactional failure while persisting planet entity", e); } // trans.commit(); session.close(); return planet; } // fetch planet public Planet getPlanet(Integer id) { Planet planet = sessionFactory.openSession().get(Planet.class, id); return planet; } // fetch satellites public boolean isSatellitesPresentInCache(Integer id) { boolean indicator = sessionFactory.getCache().containsCollection( org.jboss.as.test.integration.hibernate.Planet.class.getName() + ".satellites", id); return indicator; } // fetch statistics public Statistics getStatistics() { Statistics sessionStats = sessionFactory.getStatistics(); return sessionStats; } // fetch statistics after eviction of collection from cache public Statistics getStatisticsAfterEviction() { sessionFactory.getCache().evictCollectionData( org.jboss.as.test.integration.hibernate.Planet.class.getName() + ".satellites", new Integer(1)); Statistics sessionStats = sessionFactory.getStatistics(); return sessionStats; } }
5,971
35.864198
125
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/HibernateNativeAPITransactionTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.shared.util.AssumeTestGroupUtil; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * Test operations including rollback using Hibernate transaction and Sessionfactory inititated from hibernate.cfg.xml and * properties added to Hibernate Configuration in AS7 container without any Jakarta Persistence assistance * * @author Madhumita Sadhukhan */ @RunWith(Arquillian.class) public class HibernateNativeAPITransactionTestCase { private static final String ARCHIVE_NAME = "hibernate4native_transactiontest"; public static final String hibernate_cfg = "<?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>" + "<property name=\"show_sql\">false</property>" + "<property name=\"current_session_context_class\">thread</property>" + "<mapping resource=\"testmapping.hbm.xml\"/>" + "</session-factory></hibernate-configuration>"; public static final String testmapping = "<?xml version=\"1.0\"?>" + "<!DOCTYPE hibernate-mapping PUBLIC " + "\"-//Hibernate/Hibernate Mapping DTD 3.0//EN\" " + "\"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd\">" + "<hibernate-mapping package=\"org.jboss.as.test.integration.hibernate\">" + "<class name=\"org.jboss.as.test.integration.hibernate.Student\" table=\"STUDENT\">" + "<id name=\"studentId\" column=\"student_id\">" + "<generator class=\"native\"/>" + "</id>" + "<property name=\"firstName\" column=\"first_name\"/>" + "<property name=\"lastName\" column=\"last_name\"/>" + "<property name=\"address\"/>" // + "<set name=\"courses\" table=\"student_courses\">" // + "<key column=\"student_id\"/>" // + "<many-to-many column=\"course_id\" class=\"org.jboss.as.test.integration.nonjpa.hibernate.Course\"/>" // + "</set>" + + "</class></hibernate-mapping>"; @ArquillianResource private static InitialContext iniCtx; @BeforeClass public static void beforeClass() throws NamingException { // TODO This can be re-looked at once HHH-13188 is resolved. This may require further changes in Hibernate. AssumeTestGroupUtil.assumeSecurityManagerDisabled(); // This test needs to be recompiled against Hibernate ORM 6 (WFLY-16178) in order to pass. assumeTrue(System.getProperty("ts.ee9") == null && System.getProperty("ts.bootable.ee9") == null); iniCtx = new InitialContext(); } @Deployment public static Archive<?> deploy() throws Exception { EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, ARCHIVE_NAME + ".ear"); // add required jars as manifest dependencies ear.addAsManifestResource(new StringAsset("Dependencies: org.hibernate\n"), "MANIFEST.MF"); JavaArchive lib = ShrinkWrap.create(JavaArchive.class, "beans.jar"); lib.addClasses(SFSBHibernateTransaction.class); ear.addAsModule(lib); lib = ShrinkWrap.create(JavaArchive.class, "entities.jar"); lib.addClasses(Student.class); lib.addAsResource(new StringAsset(testmapping), "testmapping.hbm.xml"); lib.addAsResource(new StringAsset(hibernate_cfg), "hibernate.cfg.xml"); ear.addAsLibraries(lib); final WebArchive main = ShrinkWrap.create(WebArchive.class, "main.war"); main.addClasses(HibernateNativeAPITransactionTestCase.class); ear.addAsModule(main); // add application dependency on H2 JDBC driver, so that the Hibernate classloader (same as app classloader) // will see the H2 JDBC driver. // equivalent hack for use of shared Hiberante module, would be to add the H2 dependency directly to the // shared Hibernate module. // also add dependency on org.slf4j ear.addAsManifestResource(new StringAsset("<jboss-deployment-structure>" + " <deployment>" + " <dependencies>" + " <module name=\"com.h2database.h2\" />" + " <module name=\"org.slf4j\"/>" + " </dependencies>" + " </deployment>" + "</jboss-deployment-structure>"), "jboss-deployment-structure.xml"); return ear; } protected static <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { try { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + "beans/" + beanName + "!" + interfaceType.getName())); } catch (NamingException e) { throw e; } } @Test public void testSimpleOperation() throws Exception { SFSBHibernateTransaction sfsb = lookup("SFSBHibernateTransaction", SFSBHibernateTransaction.class); // setup Configuration and SessionFactory sfsb.setupConfig(); try { Student s1 = sfsb.createStudent("MADHUMITA", "SADHUKHAN", "99 Purkynova REDHAT BRNO CZ", 1); Student s2 = sfsb.createStudent("REDHAT", "LINUX", "Worldwide", 3); assertTrue("address read from hibernate session associated with hibernate transaction is 99 Purkynova REDHAT BRNO CZ", "99 Purkynova REDHAT BRNO CZ".equals(s1.getAddress())); // update Student Student s3 = sfsb.updateStudent("REDHAT RALEIGH, NORTH CAROLINA", 1); Student st = sfsb.getStudentNoTx(s1.getStudentId()); assertTrue( "address read from hibernate session associated with hibernate transaction is REDHAT RALEIGH, NORTH CAROLINA", "REDHAT RALEIGH, NORTH CAROLINA".equals(st.getAddress())); } finally { sfsb.cleanup(); } } // tests rollback @Test public void testRollBackOperation() throws Exception { SFSBHibernateTransaction sfsb = lookup("SFSBHibernateTransaction", SFSBHibernateTransaction.class); // setup Configuration and SessionFactory try { sfsb.setupConfig(); Student s2 = sfsb.createStudent("REDHAT", "LINUX", "Worldwide", 3); // force creation of student with same Id to ensure RollBack Student s3 = sfsb.createStudent("Hibernate", "ORM", "JavaWorld", s2.getStudentId()); Student st = sfsb.getStudentNoTx(s2.getStudentId()); assertTrue("name read from hibernate session associated with hibernate transaction after rollback is REDHAT", "REDHAT".equals(st.getFirstName())); } finally { sfsb.cleanup(); } } }
8,484
48.619883
130
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/Hibernate2LCacheStatsTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import java.sql.Connection; import java.util.HashSet; import java.util.Set; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.hibernate.stat.Statistics; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.shared.util.AssumeTestGroupUtil; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * Test that Hibernate statistics is working on native Hibernate and second level cache * * @author Madhumita Sadhukhan */ @RunWith(Arquillian.class) public class Hibernate2LCacheStatsTestCase { private static final String FACTORY_CLASS = "<property name=\"hibernate.cache.region.factory_class\">org.infinispan.hibernate.cache.v51.InfinispanRegionFactory</property>"; private static final String MODULE_DEPENDENCIES = "Dependencies: org.hibernate.envers export,org.hibernate\n"; private static final String ARCHIVE_NAME = "hibernateSecondLevelStats_test"; public static final String hibernate_cfg = "<?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>" + "<property name=\"show_sql\">false</property>" + "<property name=\"hibernate.cache.use_second_level_cache\">true</property>" + "<property name=\"hibernate.show_sql\">false</property>" + FACTORY_CLASS + "<property name=\"hibernate.cache.infinispan.shared\">false</property>" + "<mapping resource=\"testmapping.hbm.xml\"/>" + "</session-factory></hibernate-configuration>"; public static final String testmapping = "<?xml version=\"1.0\"?>" + "<!DOCTYPE hibernate-mapping PUBLIC " + "\"-//Hibernate/Hibernate Mapping DTD 3.0//EN\" " + "\"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd\">" + "<hibernate-mapping package=\"org.jboss.as.test.integration.hibernate\">" + "<class name=\"org.jboss.as.test.integration.hibernate.Planet\" table=\"PLANET\">" + "<cache usage=\"transactional\"/>" + "<id name=\"planetId\" column=\"planetId\">" + "<generator class=\"native\"/>" + "</id>" + "<property name=\"planetName\" column=\"planet_name\"/>" + "<property name=\"galaxy\" column=\"galaxy_name\"/>" + "<property name=\"star\" column=\"star_name\"/>" + "<set name=\"satellites\">" + "<cache usage=\"read-only\"/>" + "<key column=\"id\"/>" + "<one-to-many class=\"org.jboss.as.test.integration.hibernate.Satellite\"/>" + "</set>" + "</class>" + "<class name=\"org.jboss.as.test.integration.hibernate.Satellite\" table=\"SATELLITE\">" + "<id name=\"id\">" + "<generator class=\"native\"/>" + "</id>" + "<property name=\"name\" column=\"satellite_name\"/>" + "</class></hibernate-mapping>"; @ArquillianResource private static InitialContext iniCtx; @BeforeClass public static void beforeClass() throws NamingException { // TODO This can be re-looked at once HHH-13188 is resolved. This may require further changes in Hibernate. AssumeTestGroupUtil.assumeSecurityManagerDisabled(); // This test needs to be recompiled against Hibernate ORM 6 (WFLY-16178) in order to pass. assumeTrue(System.getProperty("ts.ee9") == null && System.getProperty("ts.bootable.ee9") == null); iniCtx = new InitialContext(); } @Deployment public static Archive<?> deploy() throws Exception { EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, ARCHIVE_NAME + ".ear"); // add required jars as manifest dependencies ear.addAsManifestResource(new StringAsset(MODULE_DEPENDENCIES), "MANIFEST.MF"); JavaArchive lib = ShrinkWrap.create(JavaArchive.class, "beans.jar"); lib.addClasses(SFSBHibernate2LcacheStats.class); ear.addAsModule(lib); lib = ShrinkWrap.create(JavaArchive.class, "entities.jar"); lib.addClasses(Planet.class); lib.addClasses(Satellite.class); lib.addAsResource(new StringAsset(testmapping), "testmapping.hbm.xml"); lib.addAsResource(new StringAsset(hibernate_cfg), "hibernate.cfg.xml"); ear.addAsLibraries(lib); final WebArchive main = ShrinkWrap.create(WebArchive.class, "main.war"); main.addClasses(Hibernate2LCacheStatsTestCase.class); ear.addAsModule(main); // add application dependency on H2 JDBC driver, so that the Hibernate classloader (same as app classloader) // will see the H2 JDBC driver. // equivalent hack for use of shared Hiberante module, would be to add the H2 dependency directly to the // shared Hibernate module. // also add dependency on org.slf4j ear.addAsManifestResource(new StringAsset("<jboss-deployment-structure>" + " <deployment>" + " <dependencies>" + " <module name=\"com.h2database.h2\" />" + " <module name=\"org.slf4j\"/>" + " </dependencies>" + " </deployment>" + "</jboss-deployment-structure>"), "jboss-deployment-structure.xml"); return ear; } protected static <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { try { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + "beans/" + beanName + "!" + interfaceType.getName())); } catch (NamingException e) { throw e; } } protected <T> T rawLookup(String name, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup(name)); } @Test public void testHibernateStatistics() throws Exception { SFSBHibernate2LcacheStats sfsb = lookup("SFSBHibernate2LcacheStats", SFSBHibernate2LcacheStats.class); // setup Configuration and SessionFactory sfsb.setupConfig(); try { Set<Satellite> satellites1 = new HashSet<Satellite>(); Satellite sat = new Satellite(); sat.setId(new Integer(1)); sat.setName("MOON"); satellites1.add(sat); Planet s1 = sfsb.prepareData("EARTH", "MILKY WAY", "SUN", satellites1, new Integer(1)); Planet s2 = sfsb.getPlanet(s1.getPlanetId()); DataSource ds = rawLookup("java:jboss/datasources/ExampleDS", DataSource.class); Connection conn = ds.getConnection(); int updated = conn.prepareStatement("update PLANET set galaxy_name='ANDROMEDA' where planetId=1").executeUpdate(); assertTrue("was able to update added Planet. update count=" + updated, updated > 0); conn.close(); // read updated (dirty) data from second level cache s2 = sfsb.getPlanet(s2.getPlanetId()); assertTrue("was able to read updated Planet entity", s2 != null); assertEquals("Galaxy for Planet " + s2.getPlanetName() + " was read from second level cache = " + s2.getGalaxy(), "MILKY WAY", s2.getGalaxy()); assertEquals(s2.getSatellites().size(), 1); Statistics stats = sfsb.getStatistics(); assertEquals(stats.getCollectionLoadCount(), 1); assertEquals(stats.getEntityLoadCount(), 2); assertEquals(stats.getSecondLevelCacheHitCount(), 1); // Collection in secondlevel cache before eviction assertTrue(sfsb.isSatellitesPresentInCache(1)); Statistics statsAfterEviction = sfsb.getStatisticsAfterEviction(); // Collection in secondlevel cache after eviction assertFalse(sfsb.isSatellitesPresentInCache(1)); } finally { sfsb.cleanup(); } } }
9,567
48.57513
176
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/Planet.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate; import java.util.Set; /** * Represents a planet object. * * @author Madhumita Sadhukhan */ public class Planet { // unique id private Integer planetId; // name of the planet private String planetName; // name of the galaxy it is situated in private String galaxy; // name of the star it rotates private String star; // set of satellites associated with planet private Set<Satellite> satellites; /** * Default constructor */ public Planet() { } /** * Creates a new instance of Planet. * * @param planetName planetName. * @param galaxy galaxy name. * @param star star name. */ public Planet(String planetName, String galaxy, String star, Set<Satellite> satellites) { this.planetName = planetName; this.galaxy = galaxy; this.star = star; this.satellites = satellites; } /** * Gets the planet id for planet. * * @return planet id. */ public Integer getPlanetId() { return planetId; } /** * Sets the planetId id for this student. * * @return planetId id. */ public void setPlanetId(Integer planetId) { this.planetId = planetId; } public String getPlanetName() { return planetName; } public void setPlanetName(String planetName) { this.planetName = planetName; } public String getGalaxy() { return galaxy; } public void setGalaxy(String galaxy) { this.galaxy = galaxy; } public String getStar() { return star; } public void setStar(String star) { this.star = star; } public Set<Satellite> getSatellites() { return satellites; } public void setSatellites(Set<Satellite> satellites) { this.satellites = satellites; } }
2,956
24.938596
93
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/Hibernate4NativeAPIProviderTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.shared.util.AssumeTestGroupUtil; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * Test that a Hibernate sessionfactory can be inititated from hibernate.cfg.xml and properties added to Hibernate Configuration * in AS7 container without any Jakarta Persistence assistance * * @author Madhumita Sadhukhan */ @RunWith(Arquillian.class) public class Hibernate4NativeAPIProviderTestCase { private static final String ARCHIVE_NAME = "hibernate4native_test"; public static final String hibernate_cfg = "<?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>" + "<property name=\"show_sql\">false</property>" + "<property name=\"current_session_context_class\">thread</property>" // only needed for ORM 5.3.0 + "<property name=\"hibernate.allow_update_outside_transaction\">true</property>" + "<mapping resource=\"testmapping.hbm.xml\"/>" + "</session-factory></hibernate-configuration>"; public static final String testmapping = "<?xml version=\"1.0\"?>" + "<!DOCTYPE hibernate-mapping PUBLIC " + "\"-//Hibernate/Hibernate Mapping DTD 3.0//EN\" " + "\"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd\">" + "<hibernate-mapping package=\"org.jboss.as.test.integration.hibernate\">" + "<class name=\"org.jboss.as.test.integration.hibernate.Student\" table=\"STUDENT\">" + "<id name=\"studentId\" column=\"student_id\">" + "<generator class=\"native\"/>" + "</id>" + "<property name=\"firstName\" column=\"first_name\"/>" + "<property name=\"lastName\" column=\"last_name\"/>" + "<property name=\"address\"/>" // + "<set name=\"courses\" table=\"student_courses\">" // + "<key column=\"student_id\"/>" // + "<many-to-many column=\"course_id\" class=\"org.jboss.as.test.integration.nonjpa.hibernate.Course\"/>" // + "</set>" + + "</class></hibernate-mapping>"; @ArquillianResource private static InitialContext iniCtx; @BeforeClass public static void beforeClass() throws NamingException { // TODO This can be re-looked at once HHH-13188 is resolved. This may require further changes in Hibernate. AssumeTestGroupUtil.assumeSecurityManagerDisabled(); // This test needs to be recompiled against Hibernate ORM 6 (WFLY-16178) in order to pass. assumeTrue(System.getProperty("ts.ee9") == null && System.getProperty("ts.bootable.ee9") == null); iniCtx = new InitialContext(); } @Deployment public static Archive<?> deploy() throws Exception { EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, ARCHIVE_NAME + ".ear"); // add required jars as manifest dependencies ear.addAsManifestResource(new StringAsset("Dependencies: org.hibernate\n"), "MANIFEST.MF"); JavaArchive lib = ShrinkWrap.create(JavaArchive.class, "beans.jar"); lib.addClasses(SFSBHibernateSessionFactory.class); ear.addAsModule(lib); lib = ShrinkWrap.create(JavaArchive.class, "entities.jar"); lib.addClasses(Student.class); lib.addAsResource(new StringAsset(testmapping), "testmapping.hbm.xml"); lib.addAsResource(new StringAsset(hibernate_cfg), "hibernate.cfg.xml"); ear.addAsLibraries(lib); final WebArchive main = ShrinkWrap.create(WebArchive.class, "main.war"); main.addClasses(Hibernate4NativeAPIProviderTestCase.class); ear.addAsModule(main); // add application dependency on H2 JDBC driver, so that the Hibernate classloader (same as app classloader) // will see the H2 JDBC driver. // equivalent hack for use of shared Hiberante module, would be to add the H2 dependency directly to the // shared Hibernate module. // also add dependency on org.slf4j ear.addAsManifestResource(new StringAsset("<jboss-deployment-structure>" + " <deployment>" + " <dependencies>" + " <module name=\"com.h2database.h2\" />" + " <module name=\"org.slf4j\"/>" + " </dependencies>" + " </deployment>" + "</jboss-deployment-structure>"), "jboss-deployment-structure.xml"); return ear; } protected static <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { try { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + "beans/" + beanName + "!" + interfaceType.getName())); } catch (NamingException e) { throw e; } } @Test public void testSimpleOperation() throws Exception { SFSBHibernateSessionFactory sfsb = lookup("SFSBHibernateSessionFactory", SFSBHibernateSessionFactory.class); // setup Configuration and SessionFactory sfsb.setupConfig(); try { Student s1 = sfsb.createStudent("MADHUMITA", "SADHUKHAN", "99 Purkynova REDHAT BRNO CZ", 1); Student s2 = sfsb.createStudent("REDHAT", "LINUX", "Worldwide", 3); Student st = sfsb.getStudent(s1.getStudentId()); assertTrue("name read from hibernate session is MADHUMITA", "MADHUMITA".equals(st.getFirstName())); } finally { sfsb.cleanup(); } } }
7,256
48.705479
128
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/SFSBHibernateSessionFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate; import java.util.Properties; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.internal.util.config.ConfigurationHelper; /** * Test that a Hibernate sessionfactory can be inititated from hibernate.cfg.xml and properties added to Hibernate Configuration * in AS7 container without any Jakarta Persistence assistance * * @author Madhumita Sadhukhan */ @Stateful @TransactionManagement(TransactionManagementType.BEAN) public class SFSBHibernateSessionFactory { private static SessionFactory sessionFactory; public void cleanup() { sessionFactory.close(); } public void setupConfig() { // static { try { // prepare the configuration Configuration configuration = new Configuration(); configuration.setProperty(Environment.HBM2DDL_AUTO, "create-drop"); configuration.setProperty(Environment.DATASOURCE, "java:jboss/datasources/ExampleDS"); configuration.setProperty("hibernate.listeners.envers.autoRegister", "false"); /* Hibernate 5.2+ (see https://hibernate.atlassian.net/browse/HHH-10877 + https://hibernate.atlassian.net/browse/HHH-12665) no longer defaults to allowing a DML operation outside of a started transaction. The application workaround is to configure new property hibernate.allow_update_outside_transaction=true. */ configuration.setProperty("hibernate.allow_update_outside_transaction","true"); // fetch the properties Properties properties = new Properties(); configuration = configuration.configure("hibernate.cfg.xml"); properties.putAll(configuration.getProperties()); ConfigurationHelper.resolvePlaceHolders(properties); sessionFactory = configuration.buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed throw new RuntimeException("Could not setup config", ex); } } // create student public Student createStudent(String firstName, String lastName, String address, int id) { Student student = new Student(); student.setStudentId(id); student.setAddress(address); student.setFirstName(firstName); student.setLastName(lastName); try { // We are not explicitly initializing a Transaction as Hibernate is expected to invoke the Jakarta Transactions TransactionManager // implicitly Session session = sessionFactory.openSession(); session.save(student); session.flush(); session.close(); } catch (Exception e) { throw new RuntimeException("transactional failure while persisting student entity", e); } return student; } // fetch student public Student getStudent(int id) { Student emp = sessionFactory.openSession().load(Student.class, id); return emp; } }
4,340
37.758929
142
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/envers/Hibernate4NativeAPIEnversTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate.envers; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.shared.util.AssumeTestGroupUtil; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * Test that Hibernate Envers is working over Native Hibernate API in AS7 container without any Jakarta Persistence assistance * * @author Madhumita Sadhukhan */ @RunWith(Arquillian.class) public class Hibernate4NativeAPIEnversTestCase { private static final String ARCHIVE_NAME = "hibernate4native_test"; public static final String hibernate_cfg = "<?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>" + "<property name=\"show_sql\">false</property>" + "<property name=\"current_session_context_class\">thread</property>" + "<mapping resource=\"testmapping.hbm.xml\"/>" + "</session-factory></hibernate-configuration>"; public static final String testmapping = "<?xml version=\"1.0\"?>" + "<!DOCTYPE hibernate-mapping PUBLIC " + "\"-//Hibernate/Hibernate Mapping DTD 3.0//EN\" " + "\"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd\">" + "<hibernate-mapping package=\"org.jboss.as.test.integration.hibernate\">" + "<class name=\"org.jboss.as.test.integration.hibernate.envers.StudentAudited\" table=\"STUDENT\">" + "<id name=\"studentId\" column=\"student_id\">" + "<generator class=\"native\"/>" + "</id>" + "<property name=\"firstName\" column=\"first_name\"/>" + "<property name=\"lastName\" column=\"last_name\"/>" + "<property name=\"address\"/>" // + "<set name=\"courses\" table=\"student_courses\">" // + "<key column=\"student_id\"/>" // + "<many-to-many column=\"course_id\" class=\"org.jboss.as.test.integration.nonjpa.hibernate.Course\"/>" // + "</set>" + + "</class></hibernate-mapping>"; @ArquillianResource private static InitialContext iniCtx; @BeforeClass public static void beforeClass() throws NamingException { // TODO This can be re-looked at once HHH-13188 is resolved. This may require further changes in Hibernate. AssumeTestGroupUtil.assumeSecurityManagerDisabled(); // This test needs to be recompiled against Hibernate ORM 6 (WFLY-16178) in order to pass. assumeTrue(System.getProperty("ts.ee9") == null && System.getProperty("ts.bootable.ee9") == null); iniCtx = new InitialContext(); } @Deployment public static Archive<?> deploy() throws Exception { EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, ARCHIVE_NAME + ".ear"); // add required jars as manifest dependencies ear.addAsManifestResource(new StringAsset("Dependencies: org.hibernate.envers export,org.hibernate\n"), "MANIFEST.MF"); JavaArchive lib = ShrinkWrap.create(JavaArchive.class, "beans.jar"); lib.addClasses(SFSBHibernateEnversSessionFactory.class); ear.addAsModule(lib); lib = ShrinkWrap.create(JavaArchive.class, "entities.jar"); lib.addClasses(StudentAudited.class); lib.addAsResource(new StringAsset(testmapping), "testmapping.hbm.xml"); lib.addAsResource(new StringAsset(hibernate_cfg), "hibernate.cfg.xml"); ear.addAsLibraries(lib); final WebArchive main = ShrinkWrap.create(WebArchive.class, "main.war"); main.addClasses(Hibernate4NativeAPIEnversTestCase.class); ear.addAsModule(main); // add application dependency on H2 JDBC driver, so that the Hibernate classloader (same as app classloader) // will see the H2 JDBC driver. // equivalent hack for use of shared Hiberante module, would be to add the H2 dependency directly to the // shared Hibernate module. // also add dependency on org.slf4j ear.addAsManifestResource(new StringAsset("<jboss-deployment-structure>" + " <deployment>" + " <dependencies>" + " <module name=\"com.h2database.h2\" />" + " <module name=\"org.slf4j\"/>" + " </dependencies>" + " </deployment>" + "</jboss-deployment-structure>"), "jboss-deployment-structure.xml"); return ear; } protected static <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { try { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + "beans/" + beanName + "!" + interfaceType.getName())); } catch (NamingException e) { throw e; } } @Test public void testEnversonHibernateNativeAPI() throws Exception { SFSBHibernateEnversSessionFactory sfsb = lookup("SFSBHibernateEnversSessionFactory", SFSBHibernateEnversSessionFactory.class); // setup Configuration and SessionFactory sfsb.setupConfig(); try { StudentAudited s1 = sfsb.createStudent("MADHUMITA", "SADHUKHAN", "99 Purkynova REDHAT BRNO CZ", 1); StudentAudited s2 = sfsb.updateStudent("REDHAT Brisbane,Australia", 1); StudentAudited st = sfsb.retrieveOldStudentVersion(s2.getStudentId()); assertTrue("address read from audit tables after envers implementation is 99 Purkynova REDHAT BRNO CZ", "99 Purkynova REDHAT BRNO CZ".equals(st.getAddress())); } finally { sfsb.cleanup(); } } }
7,294
48.62585
127
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/envers/StudentAudited.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate.envers; import org.hibernate.envers.Audited; /** * Represents a student object. * * @author Madhumita Sadhukhan */ @Audited public class StudentAudited { // unique student id private int studentId; // first name of the student private String firstName; // last name of the student private String lastName; // address of the student private String address; /** * Default constructor */ public StudentAudited() { } /** * Creates a new instance of Student. * * @param firstName first name. * @param lastName last name. * @param address address. */ public StudentAudited(String firstName, String lastName, String address) { this.firstName = firstName; this.lastName = lastName; this.address = address; } /** * Gets the student id for this student. * * @return student id. */ public int getStudentId() { return studentId; } /** * Sets the student id for this student. * * @return student id. */ public void setStudentId(int studentId) { this.studentId = studentId; } /** * Gets the first name for this student. * * @return first name. */ public String getFirstName() { return firstName; } /** * Sets the first name for this student. * * @param first name. */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * Gets the last name for this student. * * @return last name. */ public String getLastName() { return lastName; } /** * Sets the last name for this student. * * @param last name. */ public void setLastName(String lastName) { this.lastName = lastName; } /** * Gets the address for this student. * * @return address. */ public String getAddress() { return address; } /** * Sets the address for this student. * * @param address. */ public void setAddress(String address) { this.address = address; } /** * Method used by the UI to clear information on the screen. * * @return String used in the navigation rules. */ public String clear() { firstName = ""; lastName = ""; address = ""; return "clear"; } }
3,531
23.027211
78
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/envers/SFSBHibernateEnversSessionFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate.envers; import java.util.List; import java.util.Properties; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.envers.AuditReader; import org.hibernate.envers.AuditReaderFactory; import org.hibernate.internal.util.config.ConfigurationHelper; /** * Test that Hibernate Envers is working over Native Hibernate API in AS7 container without any Jakarta Persistence assistance * * @author Madhumita Sadhukhan */ @Stateful @TransactionManagement(TransactionManagementType.BEAN) public class SFSBHibernateEnversSessionFactory { private static SessionFactory sessionFactory; public void cleanup() { sessionFactory.close(); } public void setupConfig() { // static { try { // prepare the configuration Configuration configuration = new Configuration(); configuration.setProperty(Environment.HBM2DDL_AUTO, "create-drop"); configuration.setProperty(Environment.DATASOURCE, "java:jboss/datasources/ExampleDS"); // fetch the properties Properties properties = new Properties(); configuration = configuration.configure("hibernate.cfg.xml"); properties.putAll(configuration.getProperties()); ConfigurationHelper.resolvePlaceHolders(properties); sessionFactory = configuration.buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed throw new RuntimeException("Could not setup config", ex); } } // create student public StudentAudited createStudent(String firstName, String lastName, String address, int id) { // setupConfig(); StudentAudited student = new StudentAudited(); student.setStudentId(id); student.setAddress(address); student.setFirstName(firstName); student.setLastName(lastName); try { Session session = sessionFactory.openSession(); Transaction trans = session.beginTransaction(); session.save(student); session.flush(); trans.commit(); session.close(); } catch (Exception e) { throw new RuntimeException("Failure while persisting student entity", e); } return student; } // update student public StudentAudited updateStudent(String address, int id) { StudentAudited student; try { Session session = sessionFactory.openSession(); Transaction trans = session.beginTransaction(); student = session.load(StudentAudited.class, id); student.setAddress(address); session.save(student); session.flush(); trans.commit(); session.close(); } catch (Exception e) { throw new RuntimeException("Failure while persisting student entity", e); } // session.close(); return student; } // fetch Audited entity from Audit tables public StudentAudited retrieveOldStudentVersion(int id) { AuditReader reader = AuditReaderFactory.get(sessionFactory.openSession()); StudentAudited student_rev = reader.find(StudentAudited.class, id, 1); List<Number> revlist = reader.getRevisions(StudentAudited.class, id); // this is for checking revision size hence not removing this S.o.p return student_rev; } }
4,774
35.730769
126
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/naturalid/Person.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate.naturalid; /** * Represents a Person object. * * @author Madhumita Sadhukhan */ public class Person { // unique person id private int personId; // unique voterid private int personVoterId; // first name of the person private String firstName; // last name of the person private String lastName; // address of the person private String address; /** * Default constructor */ public Person() { } /** * Creates a new instance of Person. * * @param firstName first name. * @param lastName last name. * @param address address. */ public Person(String firstName, String lastName, String address) { this.firstName = firstName; this.lastName = lastName; this.address = address; } /** * Gets the person id for this student. * * @return person id. */ public int getPersonId() { return personId; } /** * Sets the person id for this Person. * * @return person id. */ public void setPersonId(int personId) { this.personId = personId; } /** * Gets the first name for this person. * * @return first name. */ public String getFirstName() { return firstName; } /** * Sets the first name for this person. * * @param first name. */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * Gets the last name for this person. * * @return last name. */ public String getLastName() { return lastName; } /** * Sets the last name for this person. * * @param last name. */ public void setLastName(String lastName) { this.lastName = lastName; } /** * Gets the address for this student. * * @return address. */ public String getAddress() { return address; } /** * Sets the address for this student. * * @param address. */ public void setAddress(String address) { this.address = address; } public int getPersonVoterId() { return personVoterId; } public void setPersonVoterId(int personVoterId) { this.personVoterId = personVoterId; } /** * Method used by the UI to clear information on the screen. * * @return String used in the navigation rules. */ public String clear() { firstName = ""; lastName = ""; address = ""; return "clear"; } }
3,673
22.703226
70
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/naturalid/SFSBHibernateSFNaturalId.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate.naturalid; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.AvailableSettings; import org.hibernate.service.ServiceRegistry; /** * Test that naturalId API used with Hibernate sessionfactory can be initiated from hibernate.cfg.xml and properties added to * Hibernate Configuration in AS7 container * * @author Madhumita Sadhukhan */ @Stateful @TransactionManagement(TransactionManagementType.BEAN) public class SFSBHibernateSFNaturalId { private static SessionFactory sessionFactory; public void cleanup() { sessionFactory.close(); } public void setupConfig() { try { final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(new BootstrapServiceRegistryBuilder().build()) .configure("hibernate.cfg.xml") .applySetting(AvailableSettings.HBM2DDL_AUTO, "create-drop") .applySetting(AvailableSettings.DATASOURCE, "java:jboss/datasources/ExampleDS") .build(); final Metadata metadata = new MetadataSources(serviceRegistry) .buildMetadata(); sessionFactory = metadata.buildSessionFactory(); } catch (Throwable ex) { throw new RuntimeException("Could not setup config", ex); } } // create person public Person createPerson(String firstName, String lastName, String address, int voterId, int id) { Person per = new Person(); per.setPersonId(id); per.setAddress(address); per.setPersonVoterId(voterId); per.setFirstName(firstName); per.setLastName(lastName); try { // We are not explicitly initializing a Transaction as Hibernate is expected to invoke the JTA TransactionManager // implicitly Session session = sessionFactory.openSession(); session.save(per); session.flush(); session.close(); } catch (Exception e) { throw new RuntimeException("transactional failure while persisting student entity", e); } return per; } // fetch person reference public Person getPersonReference(String name, int voterid) { Person emp = sessionFactory.openSession().byNaturalId(Person.class).using("firstName", name) .using("personVoterId", voterid).getReference(); return emp; } // load person public Person loadPerson(String name, int voterid) { Person emp = sessionFactory.openSession().byNaturalId(Person.class).using("firstName", name) .using("personVoterId", voterid).load(); return emp; } }
4,122
36.144144
133
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/naturalid/HibernateNativeAPINaturalIdTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate.naturalid; import static org.junit.Assert.assertEquals; import static org.junit.Assume.assumeTrue; import jakarta.ejb.EJB; import javax.naming.InitialContext; import javax.naming.NamingException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.shared.util.AssumeTestGroupUtil; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * Test that naturalId API used with Hibernate sessionfactory can be initiated from hibernate.cfg.xml and properties added to * Hibernate Configuration in AS7 container * * @author Madhumita Sadhukhan */ @RunWith(Arquillian.class) public class HibernateNativeAPINaturalIdTestCase { private static final String ARCHIVE_NAME = "hibernate4naturalid_test"; public static final String hibernate_cfg = "<?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>" + "<property name=\"show_sql\">false</property>" + "<property name=\"current_session_context_class\">thread</property>" /* Hibernate 5.2+ (see https://hibernate.atlassian.net/browse/HHH-10877 + https://hibernate.atlassian.net/browse/HHH-12665) no longer defaults to allowing a DML operation outside of a started transaction. The application workaround is to configure new property hibernate.allow_update_outside_transaction=true. */ + "<property name=\"hibernate.allow_update_outside_transaction\">true</property>" + "<mapping resource=\"testmapping.hbm.xml\"/>" + "</session-factory></hibernate-configuration>"; public static final String testmapping = "<?xml version=\"1.0\"?>" + "<!DOCTYPE hibernate-mapping PUBLIC " + "\"-//Hibernate/Hibernate Mapping DTD 3.0//EN\" " + "\"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd\">" + "<hibernate-mapping package=\"org.jboss.as.test.integration.hibernate.naturalid\">" + "<class name=\"org.jboss.as.test.integration.hibernate.naturalid.Person\" table=\"PERSON\">" + "<id name=\"personId\" column=\"person_id\">" + "<generator class=\"native\"/>" + "</id>" + "<natural-id><property name=\"personVoterId\" column=\"personVoter_id\"/><property name=\"firstName\" column=\"first_name\"/></natural-id>" + "<property name=\"lastName\" column=\"last_name\"/>" + "<property name=\"address\"/>" // + "<set name=\"courses\" table=\"student_courses\">" // + "<key column=\"student_id\"/>" // + "<many-to-many column=\"course_id\" class=\"org.jboss.as.test.integration.nonjpa.hibernate.Course\"/>" // + "</set>" + + "</class></hibernate-mapping>"; @ArquillianResource private static InitialContext iniCtx; @EJB private SFSBHibernateSFNaturalId sfsb; @BeforeClass public static void beforeClass() throws NamingException { // TODO This can be re-looked at once HHH-13188 is resolved. This may require further changes in Hibernate. AssumeTestGroupUtil.assumeSecurityManagerDisabled(); // This test needs to be recompiled against Hibernate ORM 6 (WFLY-16178) in order to pass. assumeTrue(System.getProperty("ts.ee9") == null && System.getProperty("ts.bootable.ee9") == null); iniCtx = new InitialContext(); } @Deployment public static Archive<?> deploy() throws Exception { EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, ARCHIVE_NAME + ".ear"); // add required jars as manifest dependencies ear.addAsManifestResource(new StringAsset("Dependencies: org.hibernate \n"), "MANIFEST.MF"); JavaArchive lib = ShrinkWrap.create(JavaArchive.class, "beans.jar"); lib.addClasses(SFSBHibernateSFNaturalId.class); ear.addAsModule(lib); lib = ShrinkWrap.create(JavaArchive.class, "entities.jar"); lib.addClasses(Person.class); lib.addAsResource(new StringAsset(testmapping), "testmapping.hbm.xml"); lib.addAsResource(new StringAsset(hibernate_cfg), "hibernate.cfg.xml"); ear.addAsLibraries(lib); final WebArchive main = ShrinkWrap.create(WebArchive.class, "main.war"); main.addClasses(HibernateNativeAPINaturalIdTestCase.class); ear.addAsModule(main); // add application dependency on H2 JDBC driver, so that the Hibernate classloader (same as app classloader) // will see the H2 JDBC driver. // equivalent hack for use of shared Hibernate module, would be to add the H2 dependency directly to the // shared Hibernate module. // also add dependency on org.slf4j ear.addAsManifestResource(new StringAsset("<jboss-deployment-structure>" + " <deployment>" + " <dependencies>" + " <module name=\"com.h2database.h2\" />" + " <module name=\"org.slf4j\"/>" + " </dependencies>" + " </deployment>" + "</jboss-deployment-structure>"), "jboss-deployment-structure.xml"); return ear; } @Test public void testNaturalIdload() throws Exception { // setup Configuration and SessionFactory sfsb.setupConfig(); try { Person s1 = sfsb.createPerson("MADHUMITA", "SADHUKHAN", "99 Purkynova REDHAT BRNO CZ", 123, 1); Person s2 = sfsb.createPerson("REDHAT", "LINUX", "Worldwide", 435, 3); Person p1 = sfsb.getPersonReference("REDHAT", 435); Person p2 = sfsb.loadPerson("MADHUMITA", 123); assertEquals(p2.getAddress(), "99 Purkynova REDHAT BRNO CZ"); } finally { sfsb.cleanup(); } } }
7,398
47.677632
153
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/secondlevelcache/Student.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate.secondlevelcache; /** * Represents a student object. * * @author Madhumita Sadhukhan */ public class Student { // unique student id private int studentId; // first name of the student private String firstName; // last name of the student private String lastName; // address of the student private String address; /** * Default constructor */ public Student() { } /** * Creates a new instance of Student. * * @param firstName first name. * @param lastName last name. * @param address address. */ public Student(String firstName, String lastName, String address) { this.firstName = firstName; this.lastName = lastName; this.address = address; } /** * Gets the student id for this student. * * @return student id. */ public int getStudentId() { return studentId; } /** * Sets the student id for this student. * * @return student id. */ public void setStudentId(int studentId) { this.studentId = studentId; } /** * Gets the first name for this student. * * @return first name. */ public String getFirstName() { return firstName; } /** * Sets the first name for this student. * * @param first name. */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * Gets the last name for this student. * * @return last name. */ public String getLastName() { return lastName; } /** * Sets the last name for this student. * * @param last name. */ public void setLastName(String lastName) { this.lastName = lastName; } /** * Gets the address for this student. * * @return address. */ public String getAddress() { return address; } /** * Sets the address for this student. * * @param address. */ public void setAddress(String address) { this.address = address; } /** * Method used by the UI to clear information on the screen. * * @return String used in the navigation rules. */ public String clear() { firstName = ""; lastName = ""; address = ""; return "clear"; } }
3,474
22.965517
71
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/secondlevelcache/SFSB.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate.secondlevelcache; import java.util.Properties; import jakarta.ejb.Stateful; import jakarta.ejb.TransactionAttribute; import jakarta.ejb.TransactionAttributeType; import jakarta.ejb.TransactionManagement; import jakarta.ejb.TransactionManagementType; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.engine.transaction.jta.platform.internal.JBossAppServerJtaPlatform; import org.hibernate.internal.util.config.ConfigurationHelper; /** * @author Madhumita Sadhukhan */ @Stateful @TransactionManagement(TransactionManagementType.CONTAINER) public class SFSB { private static SessionFactory sessionFactory; public void cleanup() { sessionFactory.close(); } @TransactionAttribute(TransactionAttributeType.NEVER) public void setupConfig() { // static { try { // prepare the configuration Configuration configuration = new Configuration(); configuration.getProperties().put(AvailableSettings.JTA_PLATFORM, JBossAppServerJtaPlatform.class); configuration.getProperties().put(AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, "jta"); configuration.setProperty(Environment.HBM2DDL_AUTO, "create-drop"); configuration.setProperty(Environment.DATASOURCE, "java:jboss/datasources/ExampleDS"); // fetch the properties Properties properties = new Properties(); configuration = configuration.configure("hibernate.cfg.xml"); properties.putAll(configuration.getProperties()); ConfigurationHelper.resolvePlaceHolders(properties); sessionFactory = configuration.buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed ex.printStackTrace(); throw new ExceptionInInitializerError(ex); } } // create student public Student createStudent(String firstName, String lastName, String address, int id) { // setupConfig(); Student student = new Student(); student.setStudentId(id); student.setAddress(address); student.setFirstName(firstName); student.setLastName(lastName); try { Session session = sessionFactory.openSession(); // Hibernate ORM 5.2+ doesn't allow beginTransaction in an active Jakarta Transactions transaction, as openSession // will automatically join the Jakarta Transactions transaction. // See https://github.com/hibernate/hibernate-orm/wiki/Migration-Guide---5.2 //Transaction ormTransaction = session.beginTransaction(); // join the current Jakarta Transactions transaction //TransactionStatus status = ormTransaction.getStatus(); //if(status.isNotOneOf(TransactionStatus.ACTIVE)) { // throw new RuntimeException("Hibernate Transaction is not active after joining Hibernate to Jakarta Transactions transaction: " + status.name()); //} session.save(student); // trans.commit(); session.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Failure while persisting student entity", e); } return student; } // get student public Student getStudent(int id) { Student student; try { Session session = sessionFactory.openSession(); // Hibernate ORM 5.2+ doesn't allow beginTransaction in an active Jakarta Transactions transaction, as openSession // will automatically join the Jakarta Transactions transaction. // See https://github.com/hibernate/hibernate-orm/wiki/Migration-Guide---5.2 // Transaction ormTransaction = session.beginTransaction(); // join the current Jakarta Transactions transaction // TransactionStatus status = ormTransaction.getStatus(); // if(status.isNotOneOf(TransactionStatus.ACTIVE)) { // throw new RuntimeException("Hibernate Transaction is not active after joining Hibernate to Jakarta Transactions transaction: " + status.name()); // } student = session.load(Student.class, id); session.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Failure while loading student entity", e); } return student; } public void clearCache() { sessionFactory.getCache().evictAllRegions(); } }
5,789
39.774648
162
java
null
wildfly-main/testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/hibernate/secondlevelcache/HibernateSecondLevelCacheTestCase.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.test.integration.hibernate.secondlevelcache; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; import java.sql.Connection; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.as.test.shared.util.AssumeTestGroupUtil; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * Test that Hibernate second level cache is working native Hibernate * * @author Scott Marlow (based on Madhumita's Hibernate test) */ @RunWith(Arquillian.class) public class HibernateSecondLevelCacheTestCase { private static final String FACTORY_CLASS = "<property name=\"hibernate.cache.region.factory_class\">org.infinispan.hibernate.cache.v51.InfinispanRegionFactory</property>"; private static final String MODULE_DEPENDENCIES = "Dependencies: org.hibernate.envers export,org.hibernate\n"; private static final String ARCHIVE_NAME = "hibernateSecondLevel_test"; public static final String hibernate_cfg = "<?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>" + "<property name=\"show_sql\">false</property>" + "<property name=\"hibernate.cache.use_second_level_cache\">true</property>" + "<property name=\"hibernate.show_sql\">false</property>" + FACTORY_CLASS + "<property name=\"hibernate.cache.infinispan.shared\">false</property>" + "<mapping resource=\"testmapping.hbm.xml\"/>" + "</session-factory></hibernate-configuration>"; public static final String testmapping = "<?xml version=\"1.0\"?>" + "<!DOCTYPE hibernate-mapping PUBLIC " + "\"-//Hibernate/Hibernate Mapping DTD 3.0//EN\" " + "\"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd\">" + "<hibernate-mapping package=\"org.jboss.as.test.integration.hibernate\">" + "<class name=\"" + Student.class.getName() + "\" lazy=\"false\" table=\"STUDENT\">" + "<cache usage=\"transactional\"/>" + "<id name=\"studentId\" column=\"student_id\">" + "<generator class=\"native\"/>" + "</id>" + "<property name=\"firstName\" column=\"first_name\"/>" + "<property name=\"lastName\" column=\"last_name\"/>" + "<property name=\"address\"/>" + "</class></hibernate-mapping>"; @ArquillianResource private static InitialContext iniCtx; @BeforeClass public static void beforeClass() throws NamingException { // TODO This can be re-looked at once HHH-13188 is resolved. This may require further changes in Hibernate. AssumeTestGroupUtil.assumeSecurityManagerDisabled(); // This test needs to be recompiled against Hibernate ORM 6 (WFLY-16178) in order to pass. assumeTrue(System.getProperty("ts.ee9") == null && System.getProperty("ts.bootable.ee9") == null); iniCtx = new InitialContext(); } @Deployment public static Archive<?> deploy() throws Exception { EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, ARCHIVE_NAME + ".ear"); // add required jars as manifest dependencies ear.addAsManifestResource(new StringAsset(MODULE_DEPENDENCIES), "MANIFEST.MF"); JavaArchive lib = ShrinkWrap.create(JavaArchive.class, "beans.jar"); lib.addClasses(SFSB.class); ear.addAsModule(lib); lib = ShrinkWrap.create(JavaArchive.class, "entities.jar"); lib.addClasses(Student.class); lib.addAsResource(new StringAsset(testmapping), "testmapping.hbm.xml"); lib.addAsResource(new StringAsset(hibernate_cfg), "hibernate.cfg.xml"); ear.addAsLibraries(lib); final WebArchive main = ShrinkWrap.create(WebArchive.class, "main.war"); main.addClasses(HibernateSecondLevelCacheTestCase.class); ear.addAsModule(main); // add application dependency on H2 JDBC driver, so that the Hibernate classloader (same as app classloader) // will see the H2 JDBC driver. // equivalent hack for use of shared Hiberante module, would be to add the H2 dependency directly to the // shared Hibernate module. // also add dependency on org.slf4j ear.addAsManifestResource(new StringAsset("<jboss-deployment-structure>" + " <deployment>" + " <dependencies>" + " <module name=\"com.h2database.h2\" />" + " <module name=\"org.slf4j\"/>" + " </dependencies>" + " </deployment>" + "</jboss-deployment-structure>"), "jboss-deployment-structure.xml"); return ear; } protected static <T> T lookup(String beanName, Class<T> interfaceType) throws NamingException { try { return interfaceType.cast(iniCtx.lookup("java:global/" + ARCHIVE_NAME + "/" + "beans/" + beanName + "!" + interfaceType.getName())); } catch (NamingException e) { throw e; } } protected <T> T rawLookup(String name, Class<T> interfaceType) throws NamingException { return interfaceType.cast(iniCtx.lookup(name)); } @Test public void testSecondLevelCache() throws Exception { SFSB sfsb = lookup("SFSB", SFSB.class); // setup Configuration and SessionFactory sfsb.setupConfig(); DataSource ds = rawLookup("java:jboss/datasources/ExampleDS", DataSource.class); try { Student s1 = sfsb.createStudent("MADHUMITA", "SADHUKHAN", "99 Purkynova REDHAT BRNO CZ", 1); Student s2 = sfsb.getStudent(1); Connection conn = ds.getConnection(); int updated = conn.prepareStatement("update Student set first_name='hacked' where student_id=1").executeUpdate(); assertTrue("was able to update added Student. update count=" + updated, updated > 0); conn.close(); // read updated (dirty) data from second level cache s2 = sfsb.getStudent(1); assertTrue("was able to read updated Student entity", s2 != null); assertEquals("Student first name was read from second level cache = " + s2.getFirstName(), "MADHUMITA", s2.getFirstName()); // clear dirty data from second level cache and verify that updated data is read from database sfsb.clearCache(); s2 = sfsb.getStudent(1); assertTrue("was able to read updated Student entity from database after clearing cache", s2 != null); assertEquals("Updated Student first name was read from database = " + s2.getFirstName(), "hacked", s2.getFirstName()); } finally { Connection conn = ds.getConnection(); conn.prepareStatement("delete from Student").executeUpdate(); conn.close(); try { sfsb.cleanup(); } catch (Throwable ignore) {} } } @Test public void testReadDeletedRowFrom2lc() throws Exception { SFSB sfsb = lookup("SFSB", SFSB.class); // setup Configuration and SessionFactory sfsb.setupConfig(); DataSource ds = rawLookup("java:jboss/datasources/ExampleDS", DataSource.class); try { Student s1 = sfsb.createStudent("Hope", "Solo", "6415 NE 138th Pl. Kirkland, WA 98034 USA", 1); Student s2 = sfsb.getStudent(1); Connection conn = ds.getConnection(); int updated = conn.prepareStatement("delete from Student where student_id=1").executeUpdate(); assertTrue("was able to delete row from Student. update count=" + updated, updated > 0); conn.close(); // read updated (dirty) data from second level cache s2 = sfsb.getStudent(1); assertTrue("was able to read deleted Student entity", s2 != null); assertEquals("deleted Student first name was read from second level cache = " + s2.getFirstName(), "Hope", s2.getFirstName()); } finally { Connection conn = ds.getConnection(); conn.prepareStatement("delete from Student").executeUpdate(); conn.close(); try { sfsb.cleanup(); } catch (Throwable ignore) {} } } }
10,002
47.323671
176
java