001: package example;
002:
003: import java.io.PrintWriter;
004: import java.io.IOException;
005:
006: import javax.servlet.ServletException;
007:
008: import javax.servlet.http.HttpServlet;
009: import javax.servlet.http.HttpServletRequest;
010: import javax.servlet.http.HttpServletResponse;
011:
012: import javax.ejb.EntityManager;
013: import javax.ejb.Inject;
014: import javax.ejb.EJB;
015:
016: import javax.transaction.UserTransaction;
017:
018: /**
019: * The SwapServlet swaps cources.
020: */
021: public class SwapServlet extends HttpServlet {
022: @Inject
023: private EntityManager _manager;
024:
025: @Inject
026: private UserTransaction _uTrans;
027:
028: @EJB(jndiName="swap")
029: private Swap _swap;
030:
031: /**
032: * Initializes the database for the demo.
033: */
034: public void init() throws ServletException {
035: Course course = null;
036:
037: try {
038: course = (Course) _manager.find("Course", new Integer(1));
039: if (course != null)
040: return;
041: } catch (Exception e) {
042: }
043:
044: Course potions = new Course();
045: potions.setCourse("Potions");
046: potions.setTeacher("Severus Snape");
047:
048: _manager.create(potions);
049:
050: Course xfig = new Course();
051: xfig.setCourse("Transfiguration");
052: xfig.setTeacher("Minerva McGonagall");
053:
054: _manager.create(xfig);
055: }
056:
057: /**
058: * Illustrates how to swap with a transaction.
059: */
060: public void service(HttpServletRequest req, HttpServletResponse res)
061: throws java.io.IOException, ServletException {
062: PrintWriter out = res.getWriter();
063:
064: res.setContentType("text/html");
065:
066: Course[] courses = new Course[2];
067:
068: courses[0] = (Course) _manager.find("Course", new Integer(1));
069: courses[1] = (Course) _manager.find("Course", new Integer(2));
070:
071: printCourses(out, "Initial Teachers", courses);
072:
073: // Swaps the courses using a session bean to handle the transaction.
074: _swap.swap(courses[0], courses[1]);
075:
076: printCourses(out, "Swapped Teachers", courses);
077:
078: // Swaps the courses inside a transaction. The swap will be atomic,
079: // i.e. either the swap will succeed or fail. It will not end up
080: // in an intermediate state.
081: try {
082: _uTrans.begin();
083: try {
084: String teacher = courses[0].getTeacher();
085: courses[0].setTeacher(courses[1].getTeacher());
086: courses[1].setTeacher(teacher);
087: } finally {
088: _uTrans.commit();
089: }
090: } catch (Exception e) {
091: throw new ServletException(e);
092: }
093: }
094:
095: private void printCourses(PrintWriter out, String title,
096: Course[] courses) throws IOException {
097: out.println("<h3>" + title + "</h3>");
098:
099: for (Course course : courses) {
100: out.println("course: " + course.getCourse() + "<br>");
101: out.println("teacher: " + course.getTeacher() + "<br>");
102: out.println("<br>");
103: }
104: }
105: }
|