View Javadoc

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         String realPath = config.getServletContext().getRealPath("/");
101         try
102         {
103             InitialContext ic = new InitialContext();
104             woggle = (Integer)ic.lookup("java:comp/env/woggle");
105             System.err.println(realPath+":woggle="+woggle);
106             UserTransaction utx = (UserTransaction)ic.lookup("java:comp/UserTransaction");
107             System.err.println(realPath+":utx="+utx);
108             myMailSession = (Session)ic.lookup("java:comp/env/mail/Session");
109             System.err.println(realPath+":myMailSession: "+myMailSession);
110             
111             doSetup();
112         }
113         catch (Exception e)
114         {
115             System.err.println(realPath+":"+e.getMessage());
116             throw new ServletException(e);
117         }
118     }
119 
120     
121     
122     /* ------------------------------------------------------------ */
123     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
124     {
125         doGet(request, response);
126     }
127 
128     /* ------------------------------------------------------------ */
129     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
130     {
131         boolean doCommit = true;
132         
133         String complete = request.getParameter("completion");
134         String mailTo = request.getParameter("mailto");
135         String mailFrom = request.getParameter("mailfrom");
136         
137         if (complete != null)
138         {
139             complete = complete.trim();
140             if (complete.trim().equals("commit"))
141                 doCommit = true;
142             else
143                 doCommit = false;
144         }
145        
146         if (mailTo != null)
147             mailTo = mailTo.trim();
148         
149         if (mailFrom != null)
150             mailFrom = mailFrom.trim();
151         
152         try
153         {
154             response.setContentType("text/html");
155             ServletOutputStream out = response.getOutputStream();
156             out.println("<html>");
157             out.println("<h1>Jetty6 JNDI & Transaction Tests</h1>");
158             out.println("<body>");
159             if (complete != null)
160             {
161               doTransaction(out, doCommit);
162               out.println("<p>Value of foo in myDS after "+(doCommit?"commit":"rollback")+": <b>"+getFoo(myDS)+"</p>");
163               out.println("<p>Value of foo in myDS2 after "+(doCommit?"commit":"rollback")+": <b>"+getFoo(myDS2)+"</p>");
164             }
165             else if (mailTo != null && mailFrom != null)
166             {
167                 doMail (mailTo, mailFrom);
168                 out.println("<p>Sent!</p>");
169             }
170             out.println("<a href=\"index.html\">Try again?</a>");
171             
172             out.println("</body>");            
173             out.println("</html>");
174             out.flush();
175         }
176         catch (Exception e)
177         {
178             throw new ServletException(e);
179         }
180     }
181     
182     public void doMail (String mailTo, String mailFrom)
183     throws Exception
184     {
185         Message msg = new MimeMessage(myMailSession);
186 
187         
188         // set the from and to address
189         InternetAddress addressFrom = new InternetAddress(mailFrom);
190         msg.setFrom(addressFrom);
191         msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
192         msg.setSubject("Jetty Mail Test Succeeded");
193         msg.setContent("The test of Jetty Mail @ "+new Date()+" has been successful.", "text/plain");
194         msg.addHeader ("Date", dateFormat.format(new Date()));
195         Transport.send(msg);
196 
197     }
198 
199     public void doTransaction(ServletOutputStream out, boolean doCommit)
200     throws Exception
201     {
202         //check DataSource and Transactions
203         Connection c1 = null; 
204         Connection c2 = null;
205         Statement s1 = null;
206         Statement s2 = null;
207         UserTransaction utx = null;
208         try
209         {
210             doSetup();
211             
212             InitialContext ic = new InitialContext();
213             utx = (UserTransaction)ic.lookup("java:comp/UserTransaction");
214             
215             utx.begin();
216             
217             c1 = myDS.getConnection();
218             c2 = myDS2.getConnection();
219             
220             s1 = c1.createStatement();
221             s2 = c2.createStatement();
222             
223             s1.executeUpdate("update "+TABLE1+" set foo=foo + 1 where id=1");
224             s2.executeUpdate("update "+TABLE2+" set foo=foo + 1 where id=1");
225             
226             s1.close();
227             s2.close();
228             
229             c1.close();
230             c2.close();
231         }
232         catch (Exception e)
233         {
234             e.printStackTrace();
235             doCommit = false;
236         }
237         finally
238         {
239            if (doCommit)
240                utx.commit();
241            else
242                utx.rollback();
243         }
244         
245     }
246     
247     private Integer getFoo (DataSource ds)
248     throws Exception
249     {
250         Connection c = null;
251         Statement s = null;
252         Integer value = null;
253         try
254         {
255             c = ds.getConnection();
256             s = c.createStatement();
257             String tablename = (ds.equals(myDS)?TABLE1:TABLE2);
258             ResultSet results = s.executeQuery("select foo from "+tablename+" where id=1");
259             if (results.next())
260                 value = new Integer(results.getInt(1));
261             
262             results.close();
263             
264             return value;
265         }
266         finally
267         {
268             if (s != null) s.close();
269             if (c != null) c.close();
270         }
271     }
272     
273     private void doSetup ()
274     throws Exception
275     {
276         
277         if (setupDone)
278             return;
279         
280         
281         Connection c1=null;
282         Connection c2=null;
283         Statement s1=null;
284         Statement s2=null;
285         try
286         {
287             c1 = myDS.getConnection();
288             c2 = myDS2.getConnection();
289             
290             s1 = c1.createStatement();
291             s2 = c2.createStatement();
292             
293             s1.execute("create table "+TABLE1+" ( id INTEGER, foo INTEGER )");
294             s1.executeUpdate("insert into "+TABLE1+" (id, foo) values (1, 1)");
295             c1.commit();
296             s2.execute("create table "+TABLE2+" ( id INTEGER, foo INTEGER )");
297             s2.executeUpdate("insert into "+TABLE2+" (id, foo) values (1, 1)");
298             c2.commit();
299             
300             setupDone = true;
301         }
302         finally
303         {
304             if (s1 != null) s1.close();
305             if (s2 != null) s2.close();
306             if (c1 != null) c1.close();
307             if (c2 != null) c2.close();
308         }
309     }
310     
311     private void doTearDown()
312     throws Exception
313     {
314         Connection c1=null;
315         Connection c2=null;
316         Statement s1=null;
317         Statement s2=null;
318         try
319         {
320             c1 = myDS.getConnection();
321             c2 = myDS2.getConnection();
322             
323             s1 = c1.createStatement();
324             s2 = c2.createStatement();
325             
326             s1.execute("drop table "+TABLE1);
327             c1.commit();
328             s2.execute("drop table "+TABLE2);
329             c2.commit();
330             
331         }
332         catch (IllegalStateException e)
333         {
334             System.err.println("Caught expected IllegalStateException from Atomikos on doTearDown");
335             doTearDown();
336         }
337         finally
338         {
339             if (s1 != null) s1.close();
340             if (s2 != null) s2.close();
341             if (c1 != null) c1.close();
342             if (c2 != null) c2.close();
343         }
344     }
345     
346     public void destroy ()
347     {
348         
349         try
350         {
351             doTearDown();     
352         }
353         catch (Exception e)
354         {
355             throw new RuntimeException(e);
356         }
357         finally
358         {
359             super.destroy();
360         }
361     }
362 }