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