1   /**
2    * 
3    */
4   package com.acme;
5   
6   import java.io.IOException;
7   import java.sql.Connection;
8   import java.sql.ResultSet;
9   import java.sql.Statement;
10  import java.text.SimpleDateFormat;
11  import java.util.Date;
12  
13  import javax.mail.Message;
14  import javax.mail.Session;
15  import javax.mail.Transport;
16  import javax.mail.internet.InternetAddress;
17  import javax.mail.internet.MimeMessage;
18  import javax.naming.InitialContext;
19  import javax.servlet.ServletConfig;
20  import javax.servlet.ServletException;
21  import javax.servlet.ServletOutputStream;
22  import javax.servlet.http.HttpServlet;
23  import javax.servlet.http.HttpServletRequest;
24  import javax.servlet.http.HttpServletResponse;
25  import javax.sql.DataSource;
26  import javax.sql.XADataSource;
27  import javax.transaction.UserTransaction;
28  
29  /**
30   * JNDITest
31   * 
32   * Use JNDI from within Jetty.
33   * 
34   * Also, use servlet spec 2.5 resource injection and lifecycle callbacks from within the web.xml
35   * to set up some of the JNDI resources.
36   *
37   */
38  public class JNDITest extends HttpServlet {
39      public static final String DATE_FORMAT = "EEE, d MMM yy HH:mm:ss Z";
40      private static SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
41  
42      
43      private static final String TABLE1 = "mytestdata1";
44      private static final String TABLE2 = "mytestdata2";
45      
46      private static boolean setupDone = false;
47      
48      private DataSource myDS;
49      private DataSource myDS2;
50      private DataSource myDS99;
51      private Session myMailSession;
52      private Double wiggle;
53      private Integer woggle;
54      
55      public void setMyDatasource(DataSource ds)
56      {
57          myDS=ds;
58      }
59      
60      public void setMyDatasource2(DataSource ds)
61      {
62          myDS2=ds;
63      }
64  
65      public void setMyDatasource99(DataSource ds)
66      {
67          myDS99=ds;
68      }
69      
70      private void postConstruct ()
71      {
72          System.err.println("mydatasource="+myDS);
73          System.err.println("mydatasource2="+myDS2);
74          System.err.println("mydatasource99="+myDS99);
75          System.err.println("wiggle="+wiggle);
76      }
77      
78      private void preDestroy()
79      {
80          System.err.println("PreDestroy called");
81      }
82      
83      public void init(ServletConfig config) throws ServletException
84      {
85          super.init(config);
86          try
87          {
88              InitialContext ic = new InitialContext();
89              woggle = (Integer)ic.lookup("java:comp/env/woggle");
90              System.err.println("woggle="+woggle);
91              System.err.println("gargle="+(Double)ic.lookup("java:comp/env/gargle"));
92              UserTransaction utx = (UserTransaction)ic.lookup("java:comp/UserTransaction");
93              System.err.println("utx="+utx);
94              myMailSession = (Session)ic.lookup("java:comp/env/mail/Session");
95              System.err.println("myMailSession: "+myMailSession);
96              
97              doSetup();
98          }
99          catch (Exception e)
100         {
101             throw new ServletException(e);
102         }
103     }
104 
105     
106     
107     /* ------------------------------------------------------------ */
108     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
109     {
110         doGet(request, response);
111     }
112 
113     /* ------------------------------------------------------------ */
114     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
115     {
116         boolean doCommit = true;
117         
118         String complete = request.getParameter("completion");
119         String mailTo = request.getParameter("mailto");
120         String mailFrom = request.getParameter("mailfrom");
121         
122         if (complete != null)
123         {
124             complete = complete.trim();
125             if (complete.trim().equals("commit"))
126                 doCommit = true;
127             else
128                 doCommit = false;
129         }
130        
131         if (mailTo != null)
132             mailTo = mailTo.trim();
133         
134         if (mailFrom != null)
135             mailFrom = mailFrom.trim();
136         
137         try
138         {
139             response.setContentType("text/html");
140             ServletOutputStream out = response.getOutputStream();
141             out.println("<html>");
142             out.println("<h1>Jetty6 JNDI & Transaction Tests</h1>");
143             out.println("<body>");
144             if (complete != null)
145             {
146               doTransaction(out, doCommit);
147               out.println("<p>Value of foo in myDS after "+(doCommit?"commit":"rollback")+": <b>"+getFoo(myDS)+"</p>");
148               out.println("<p>Value of foo in myDS2 after "+(doCommit?"commit":"rollback")+": <b>"+getFoo(myDS2)+"</p>");
149             }
150             else if (mailTo != null && mailFrom != null)
151             {
152                 doMail (mailTo, mailFrom);
153                 out.println("<p>Sent!</p>");
154             }
155             out.println("<a href=\"index.html\">Try again?</a>");
156             
157             out.println("</body>");            
158             out.println("</html>");
159             out.flush();
160         }
161         catch (Exception e)
162         {
163             throw new ServletException(e);
164         }
165     }
166     
167     public void doMail (String mailTo, String mailFrom)
168     throws Exception
169     {
170         Message msg = new MimeMessage(myMailSession);
171 
172         
173         // set the from and to address
174         InternetAddress addressFrom = new InternetAddress(mailFrom);
175         msg.setFrom(addressFrom);
176         msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
177         msg.setSubject("Jetty Mail Test Succeeded");
178         msg.setContent("The test of Jetty Mail @ "+new Date()+" has been successful.", "text/plain");
179         msg.addHeader ("Date", dateFormat.format(new Date()));
180         Transport.send(msg);
181 
182     }
183 
184     public void doTransaction(ServletOutputStream out, boolean doCommit)
185     throws Exception
186     {
187         //check DataSource and Transactions
188         Connection c1 = null; 
189         Connection c2 = null;
190         Statement s1 = null;
191         Statement s2 = null;
192         UserTransaction utx = null;
193         try
194         {
195             doSetup();
196             
197             InitialContext ic = new InitialContext();
198             utx = (UserTransaction)ic.lookup("java:comp/UserTransaction");
199             
200             utx.begin();
201             
202             c1 = myDS.getConnection();
203             c2 = myDS2.getConnection();
204             
205             s1 = c1.createStatement();
206             s2 = c2.createStatement();
207             
208             s1.executeUpdate("update "+TABLE1+" set foo=foo + 1 where id=1");
209             s2.executeUpdate("update "+TABLE2+" set foo=foo + 1 where id=1");
210             
211             s1.close();
212             s2.close();
213             
214             c1.close();
215             c2.close();
216         }
217         catch (Exception e)
218         {
219             e.printStackTrace();
220             doCommit = false;
221         }
222         finally
223         {
224            if (doCommit)
225                utx.commit();
226            else
227                utx.rollback();
228         }
229         
230     }
231     
232     private Integer getFoo (DataSource ds)
233     throws Exception
234     {
235         Connection c = null;
236         Statement s = null;
237         Integer value = null;
238         try
239         {
240             c = ds.getConnection();
241             s = c.createStatement();
242             String tablename = (ds.equals(myDS)?TABLE1:TABLE2);
243             ResultSet results = s.executeQuery("select foo from "+tablename+" where id=1");
244             if (results.next())
245                 value = new Integer(results.getInt(1));
246             
247             results.close();
248             
249             return value;
250         }
251         finally
252         {
253             if (s != null) s.close();
254             if (c != null) c.close();
255         }
256     }
257     
258     private void doSetup ()
259     throws Exception
260     {
261         
262         if (setupDone)
263             return;
264         
265         
266         Connection c1=null;
267         Connection c2=null;
268         Statement s1=null;
269         Statement s2=null;
270         try
271         {
272             c1 = myDS.getConnection();
273             c2 = myDS2.getConnection();
274             
275             s1 = c1.createStatement();
276             s2 = c2.createStatement();
277             
278             s1.execute("create table "+TABLE1+" ( id INTEGER, foo INTEGER )");
279             s1.executeUpdate("insert into "+TABLE1+" (id, foo) values (1, 1)");
280             c1.commit();
281             s2.execute("create table "+TABLE2+" ( id INTEGER, foo INTEGER )");
282             s2.executeUpdate("insert into "+TABLE2+" (id, foo) values (1, 1)");
283             c2.commit();
284             
285             setupDone = true;
286         }
287         finally
288         {
289             if (s1 != null) s1.close();
290             if (s2 != null) s2.close();
291             if (c1 != null) c1.close();
292             if (c2 != null) c2.close();
293         }
294     }
295     
296     private void doTearDown()
297     throws Exception
298     {
299         Connection c1=null;
300         Connection c2=null;
301         Statement s1=null;
302         Statement s2=null;
303         try
304         {
305             c1 = myDS.getConnection();
306             c2 = myDS2.getConnection();
307             
308             s1 = c1.createStatement();
309             s2 = c2.createStatement();
310             
311             s1.execute("drop table "+TABLE1);
312             c1.commit();
313             s2.execute("drop table "+TABLE2);
314             c2.commit();
315             
316         }
317         catch (IllegalStateException e)
318         {
319             System.err.println("Caught expected IllegalStateException from Atomikos on doTearDown");
320             doTearDown();
321         }
322         finally
323         {
324             if (s1 != null) s1.close();
325             if (s2 != null) s2.close();
326             if (c1 != null) c1.close();
327             if (c2 != null) c2.close();
328         }
329     }
330     
331     public void destroy ()
332     {
333         
334         try
335         {
336             doTearDown();     
337         }
338         catch (Exception e)
339         {
340             throw new RuntimeException(e);
341         }
342         finally
343         {
344             super.destroy();
345         }
346     }
347 }