diff options
| author | Sven Eisenhauer <sven@sven-eisenhauer.net> | 2023-11-10 15:11:48 +0100 |
|---|---|---|
| committer | Sven Eisenhauer <sven@sven-eisenhauer.net> | 2023-11-10 15:11:48 +0100 |
| commit | 33613a85afc4b1481367fbe92a17ee59c240250b (patch) | |
| tree | 670b842326116b376b505ec2263878912fca97e2 /Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity | |
| download | Studium-33613a85afc4b1481367fbe92a17ee59c240250b.tar.gz Studium-33613a85afc4b1481367fbe92a17ee59c240250b.tar.bz2 | |
Diffstat (limited to 'Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity')
11 files changed, 345 insertions, 0 deletions
diff --git a/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/Account.java b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/Account.java new file mode 100644 index 0000000..1efa132 --- /dev/null +++ b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/Account.java @@ -0,0 +1 @@ +package examples.entity.intro;
import java.io.Serializable;
import javax.persistence.AccessType;
import javax.persistence.Entity;
import javax.persistence.EntityListener;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.PostLoad;
import javax.persistence.PostUpdate;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Version;
/**
* This demo entity represents a Bank Account.
* <p>
* The entity is not a remote object and can only be accessed locally by
* clients. However, it is made serializable so that instances can be passed by
* value to remote clients for local inspection.
* <p>
* Access to persistent state is by direct field access.
*/
@Entity(access = AccessType.FIELD)
@EntityListener(MyListener.class)
@NamedQuery(name="findThem", query="SELECT a FROM Account a")
public class Account implements Serializable {
/** The account number is the primary key for the persistent object */
@Id
public int accountNumber;
public String ownerName;
public int balance;
@Version
public int version;
/**
* Entity beans must have a public no-arg constructor
*/
public Account() {
// our own primary key generation, workaround for the
// time being as Glassfish persistence does not support
// auto-generation
accountNumber = (int) System.nanoTime();
}
public String toString() {
return "Acc.# " + accountNumber + ", owner" + ownerName + ", balance: " + balance
+ " $";
}
@PrePersist
void prepersist() {
System.out.println("pre persist!!");
}
@PreUpdate
void preupdate() {
System.out.println("pre update!!");
}
@PostUpdate
void postupdate() {
System.out.println("post update!!");
}
@PostLoad
void postload() {
System.out.println("post load!!");
}
}
\ No newline at end of file diff --git a/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/AccountBean.java b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/AccountBean.java new file mode 100644 index 0000000..45f05c3 --- /dev/null +++ b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/AccountBean.java @@ -0,0 +1,70 @@ +package examples.entity.intro;
+
+import javax.ejb.Interceptors;
+import javax.ejb.Remote;
+import javax.ejb.Stateful;
+import javax.ejb.TransactionAttribute;
+import javax.ejb.TransactionAttributeType;
+import javax.persistence.EntityListener;
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.persistence.PersistenceContextType;
+
+/**
+ * Stateful session bean facade for account entities, remotely accessible
+ */
+
+@Stateful
+@Remote(AccountInterface.class)
+public class AccountBean implements AccountInterface {
+
+ /** The entity manager, injected by the container */
+ @PersistenceContext(type=PersistenceContextType.EXTENDED)
+ private EntityManager manager;
+
+ private Account account;
+
+ @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
+ public void open(int accountNumber) {
+ account = manager.find(Account.class, accountNumber);
+ if(account == null)
+ account = new Account();
+
+ account.ownerName = "anonymous";
+ account.accountNumber = accountNumber;
+ manager.persist(account);
+ }
+
+ @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
+ public int getBalance() {
+ if(account==null)
+ throw new IllegalStateException();
+ return account.balance;
+ }
+
+ @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
+ public void deposit(int amount) {
+ if(account==null)
+ throw new IllegalStateException();
+ //manager = emf.createEntityManager(PersistenceContextType.EXTENDED);
+ //account = manager.merge(account);
+ account.balance += amount;
+ //manager.flush();
+ }
+
+ @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
+ public int withdraw(int amount) {
+ if(account==null)
+ throw new IllegalStateException();
+ // manager.lock(account, LockMode.WRITE);
+ if (amount > account.balance) {
+ return 0;
+ } else {
+ account.balance -= amount;
+ return amount;
+ }
+ }
+
+
+
+}
diff --git a/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/AccountClient.java b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/AccountClient.java new file mode 100644 index 0000000..ae85824 --- /dev/null +++ b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/AccountClient.java @@ -0,0 +1 @@ +package examples.entity.intro;
import java.util.Iterator;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
/**
* Sample client code for an Account entity that is accessed through
* a stateful session bean facade.
*/
public class AccountClient {
public static void main(String[] args) {
AccountInterface account = null;
try {
/*
* Get a reference to the Account Session Object
*/
Context ctx = new InitialContext(System.getProperties());
account = (AccountInterface)ctx.lookup(AccountInterface.class.getName());
Bank bank = (Bank)ctx.lookup(Bank.class.getName());
/*
* Let's find existing accounts in the bank...
*/
List<Account> accounts = bank.listAccounts();
/*
* ... and print them to the screen
*/
System.out.println("--- Accounts in this bank ---");
for(Iterator iter = accounts.iterator(); iter.hasNext();) {
System.out.println(iter.next());
}
System.out.println("-----------------------------");
/*
* Open the account
*/
account.open(4444);
System.out.println("Initial Balance = " + account.getBalance());
/*
* Deposit $100 into the account
*/
account.deposit(100);
/*
* Retrieve the resulting balance both from
* the original and the local copy
*/
System.out.println("After depositing $100, the account balance is: $"
+ account.getBalance());
/*
* Try to withdraw $150
*/
System.out.println("Now trying to withdraw $150.");
int withdrawn = account.withdraw(150);
if(withdrawn != 150)
System.out.println("No success...");
else
System.out.println("Success, got the money!");
System.out.println("Finally, the account balance is: $"
+ account.getBalance());
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
\ No newline at end of file diff --git a/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/AccountInterface.java b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/AccountInterface.java new file mode 100644 index 0000000..132accf --- /dev/null +++ b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/AccountInterface.java @@ -0,0 +1,13 @@ +package examples.entity.intro;
+
+public interface AccountInterface {
+
+ public void open(int accountNumber) ;
+
+ public int getBalance();
+
+ public void deposit(int amount) ;
+
+ public int withdraw(int amount) ;
+
+}
\ No newline at end of file diff --git a/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/Bank.java b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/Bank.java new file mode 100644 index 0000000..625978e --- /dev/null +++ b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/Bank.java @@ -0,0 +1,60 @@ +package examples.entity.intro;
+
+import java.util.List;
+
+/**
+ * Business interface of the Bank session bean, a facade for the
+ * Account entity bean.
+ */
+
+public interface Bank {
+
+ /**
+ * List accounts in the bank
+ * @return the list of accounts
+ */
+ List<Account> listAccounts();
+
+ /**
+ * Opens a new account
+ * @param ownerName
+ * @return the account object
+ */
+ Account openAccount(String ownerName);
+
+ Account openAccount(String ownerName, int accNum);
+
+ void printBigAccounts();
+
+ /**
+ * Find out the balance of account with given accountNumber
+ * @param accountNumber
+ * @return the current balance
+ */
+ int getBalance(int accountNumber);
+
+ /**
+ * Increases the balance of account with given accountNumber by amount
+ * @param accountNumber
+ * @param amount the amount
+ */
+ void deposit(int accountNumber, int amount);
+
+ /**
+ * Withdraws a given amount, the current balance permitting
+ * @param accountNumber
+ * @param amount
+ * @return amount, if successful, 0 otherwise
+ */
+ int withdraw(int accountNumber, int amount);
+
+ public void checkBalance(int accountNumber);
+
+ /**
+ * Destroys the entity permanently
+ * @param accountNumber
+ */
+ void close(int accountNumber);
+
+ void update(Account a);
+}
diff --git a/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/BankBean.java b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/BankBean.java new file mode 100644 index 0000000..de5e59a --- /dev/null +++ b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/BankBean.java @@ -0,0 +1,119 @@ +package examples.entity.intro;
+
+import java.util.List;
+
+import javax.ejb.Stateless;
+import javax.ejb.Remote;
+import javax.persistence.*;
+
+/**
+ * Stateless session bean facade for account entities, remotely accessible
+ */
+@Stateless
+@Remote(Bank.class)
+@EntityListener(MyListener.class)
+public class BankBean implements Bank {
+ /**
+ * The entity manager object, injected by the container
+ */
+ @PersistenceContext
+ private EntityManager manager;
+
+ public List<Account> listAccounts() {
+ //Query query = manager.createQuery("SELECT a FROM Account a");
+ Query query = manager.createNamedQuery("findThem");
+ return query.getResultList();
+ }
+
+ public void printBigAccounts() {
+ Query query =
+ manager.createQuery("SELECT a FROM Account a WHERE a.balance > 1000");
+
+ System.out.println("Got " + query.getResultList().size() + " records.");
+
+ // do sth else in the meantime
+ try {
+ Thread.sleep(15000);
+ } catch (InterruptedException e )
+ {}
+
+ query =
+ manager.createQuery("SELECT a FROM Account a WHERE a.balance > 1000");
+
+ System.out.println("Got " + query.getResultList().size() + " records.");
+ }
+
+
+ public Account openAccount(String ownerName) {
+ Account account = new Account();
+ account.ownerName = ownerName;
+ System.out.println("Entity belongs to persistence context: " +
+ manager.contains(account));
+ manager.persist(account);
+ System.out.println("Entity belongs to persistence context: " +
+ manager.contains(account));
+ return account;
+ }
+
+ public Account openAccount(String ownerName, int accNum) {
+ Account account = new Account();
+ account.ownerName = ownerName;
+ account.accountNumber = accNum;
+ System.out.println("Entity belongs to persistence context: " +
+ manager.contains(account));
+ manager.persist(account);
+ System.out.println("Entity belongs to persistence context: " +
+ manager.contains(account));
+ return account;
+ }
+
+ public int getBalance(int accountNumber) {
+ Account account = manager.find(Account.class, accountNumber);
+ return account.balance;
+ }
+
+ public void deposit(int accountNumber, int amount) {
+ Account account = manager.find(Account.class, accountNumber);
+ account.balance += amount;
+ }
+
+ public int withdraw(int accountNumber, int amount) {
+ Account account = manager.find(Account.class, accountNumber);
+ System.out.println("Withdrawing... " );
+
+ account.balance -= amount;
+ System.out.println("... amount now... " + account.balance );
+ manager.flush();
+ return amount;
+ }
+
+ public void close(int accountNumber) {
+ Account account = manager.find(Account.class, accountNumber);
+ try {
+ Thread.sleep(20000);
+ } catch (InterruptedException e )
+ {}
+ manager.remove(account);
+ try {
+ Thread.sleep(20000);
+ } catch (InterruptedException e )
+ {}
+ }
+
+ public void update(Account a) {
+ manager.merge(a);
+ }
+
+ public void checkBalance(int accountNumber) {
+ System.out.println("Checking... sleep");
+ try {
+ Thread.sleep(3000);
+ } catch (InterruptedException e )
+ {}
+ Account account = manager.find(Account.class, accountNumber);
+ manager.refresh(account);
+ int b = account.balance;
+ System.out.println("Checking... " + b );
+ }
+
+}
diff --git a/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/Client.java b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/Client.java new file mode 100644 index 0000000..16863fc --- /dev/null +++ b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/Client.java @@ -0,0 +1 @@ +package examples.entity.intro;
import java.util.Iterator;
import java.util.List;
import javax.naming.*;
/**
* Sample client code for an Account entity that is accessed through
* a stateless session bean.
*/
public class Client {
public static void main(String[] args) {
Bank bank = null;
Account account = null;
int accountNumber = 0;
try {
/*
* Get a reference to the Account Session Object
*/
Context ctx = new InitialContext(System.getProperties());
bank = (Bank)ctx.lookup(Bank.class.getName());
/*
* Let's find existing accounts in the bank...
*/
List<Account> accounts = bank.listAccounts();
/*
* ... and print them to the screen
*/
System.out.println("--- Accounts in this bank ---");
for(Iterator iter = accounts.iterator(); iter.hasNext();) {
System.out.println(iter.next());
}
System.out.println("-----------------------------");
/*
* Open an account and get a local copy of the account object
* We can access the object in the bank by using our account number.
*/
account = bank.openAccount("Ben Johnson");
accountNumber = account.accountNumber;
/*
* Call the balance() method, and print it
*/
System.out.println("Initial Balance = " +
bank.getBalance(accountNumber));
/*
* Deposit $100 into the account
*/
bank.deposit(accountNumber,100);
/*
* Retrieve the resulting balance both from
* the original and the local copy
*/
System.out.println("After depositing $100, the account balance is: $"
+ bank.getBalance(accountNumber));
System.out.println("Sadly, the local account balance still is: $"
+ account.balance);
/*
* Try to withdraw $150
*/
System.out.println("Now trying to withdraw $150, which is more than is currently available.");
int withdrawn = bank.withdraw(accountNumber,150);
if(withdrawn != 150)
System.out.println("No success...");
else
System.out.println("Success");
// account.balance += 10000;
// bank.update(account);
//
// System.out.println("After depositing $10,000 locally and updating, the account balance is: $"
// + bank.getBalance(accountNumber));
} catch (Exception e) {
System.out.println("Message: " + e.getMessage());
} finally {
/*
* Destroy the Entity permanently
try {
if (account != null) {
System.out.println("Destroying account..");
bank.close(accountNumber);
}
} catch (Exception e) {
e.printStackTrace();
}
*/
}
}
}
\ No newline at end of file diff --git a/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/ConflictingClient.java b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/ConflictingClient.java new file mode 100644 index 0000000..f19d236 --- /dev/null +++ b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/ConflictingClient.java @@ -0,0 +1 @@ +package examples.entity.intro;
import javax.naming.Context;
import javax.naming.InitialContext;
/**
* Sample client code for an Account entity that is accessed through
* a stateful session bean facade.
*/
public class ConflictingClient {
static Bank bank = null;
static int num = 13;
static class SecondClientThread extends Thread {
public void run() {
System.out.println("Withdrawing... " );
try {
bank.withdraw(num, 100000);
} catch (Exception e) {
//System.out.println("Exception: " + e.getMessage());
}
System.out.println("Balance = " + bank.getBalance(num));
}
}
static class FirstClientThread extends Thread {
public void run() {
bank.printBigAccounts();
}
}
public static void main(String[] args) {
try {
Context ctx = new InitialContext(System.getProperties());
bank = (Bank)ctx.lookup(Bank.class.getName());
bank.openAccount("blub", num);
bank.deposit(num, 100000);
Thread fst = new FirstClientThread();
Thread scn = new SecondClientThread();
fst.start();
scn.start();
fst.join();
scn.join();
System.out.println("Balance = " + bank.getBalance(num));
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
\ No newline at end of file diff --git a/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/META-INF/persistence.xml b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/META-INF/persistence.xml new file mode 100644 index 0000000..3427b20 --- /dev/null +++ b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/META-INF/persistence.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" encoding="UTF-8"?>
+<persistence xmlns="http://java.sun.com/xml/ns/persistence">
+ <persistence-unit name="intro">
+ <jta-data-source>jdbc/__default</jta-data-source>
+ <properties>
+ <property name="ddl-generation" value="createtables"/>
+ <property name="toplink.platform.class.name"
+ value="oracle.toplink.essentials.platform.database.DerbyPlatform"/>
+<!-- <property name="toplink.logging.level" value="FINEST"/> -->
+
+ </properties>
+ </persistence-unit>
+</persistence>
\ No newline at end of file diff --git a/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/MyListener.java b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/MyListener.java new file mode 100644 index 0000000..f6cabcd --- /dev/null +++ b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/MyListener.java @@ -0,0 +1,34 @@ +package examples.entity.intro;
+
+import javax.persistence.PostLoad;
+import javax.persistence.PostUpdate;
+import javax.persistence.PrePersist;
+import javax.persistence.PreUpdate;
+
+public class MyListener {
+
+ public MyListener() {
+ }
+
+ @PrePersist
+ public void prepersist(Account a) {
+ System.out.println("pre persist " + a );
+ }
+
+ @PreUpdate
+ public void preupdate(Account a) {
+ System.out.println("pre update " + a);
+ }
+
+ @PostUpdate
+ public void postupdate(Account a) {
+ System.out.println("post update " + a);
+ }
+
+
+ @PostLoad
+ public void postload(Account a) {
+ System.out.println("post load!!" + a );
+ }
+
+}
diff --git a/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/build.xml b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/build.xml new file mode 100644 index 0000000..1f2983f --- /dev/null +++ b/Master/Reference Architectures and Patterns/EJB 3.0 Code/Gerald Examples/src/examples/entity/intro/build.xml @@ -0,0 +1,32 @@ +<?xml version="1.0"?> +<!DOCTYPE project [ <!ENTITY include SYSTEM "../../../../etc/common.xml"> ]> + +<project name="ejb3-examples-entity-intro" default="jar" + basedir="../../../.."> + + <!-- basic settings --> + <property name="src.dir" value="${basedir}/src"/> + <property name="build.dir" value="${basedir}/build"/> + <property name="build.classes.dir" value="${build.dir}/classes"/> + <property name="appname" value="AccountEntity"/> + <property name="client.class" value="examples.entity.intro.AccountClient"/> + <property name="app.pkg" value="examples/entity/intro"/> + <property name="package" value="${app.pkg}"/> + <property name="pack.dir" value="${src.dir}/${app.pkg}"/> + <property name="jar.pkg" value="examples/entity/intro"/> + + + <!-- Include common.xml --> + &include; + + <property name="deploy.file" value="${assemble.ejbjar}/${ejbjar}" /> + + <target name="jar" depends="compile_common, create_ejbjar_common"/> + <target name="ear" depends="jar,create_ear_common"/> + + <target name="deploy" depends="jar"> + <copy file="${deploy.file}" todir="${deploy.dir}"/> + </target> + +</project> + |
