View Javadoc

1   /*
2    * $Id: InitServlet.java,v 1.19 2006/03/17 17:50:58 clq2 Exp $
3    * 
4    * Created on 14-Apr-2004 by Paul Harrison (pah@jb.man.ac.uk)
5    *
6    * Copyright 2004 AstroGrid. All rights reserved.
7    *
8    * This software is published under the terms of the AstroGrid 
9    * Software License version 1.2, a copy of which has been included 
10   * with this distribution in the LICENSE.txt file.  
11   *
12   */
13  
14  package org.astrogrid.applications.component;
15  
16  import java.io.BufferedReader;
17  import java.io.File;
18  import java.io.FileNotFoundException;
19  import java.io.FileReader;
20  import java.io.InputStreamReader;
21  import java.io.IOException;
22  import java.io.PrintWriter;
23  import java.net.MalformedURLException;
24  import java.net.URL;
25  
26  import javax.servlet.ServletException;
27  import javax.servlet.http.HttpServlet;
28  import javax.servlet.http.HttpServletRequest;
29  import javax.servlet.http.HttpServletResponse;
30  
31  import org.apache.axis.utils.XMLUtils;
32  import org.w3c.dom.Document;
33  
34  import org.astrogrid.applications.ApplicationExecutionException;
35  import org.astrogrid.applications.CeaException;
36  import org.astrogrid.applications.beans.v1.cea.castor.ExecutionSummaryType;
37  import org.astrogrid.applications.description.registry.RegistryUploader;
38  import org.astrogrid.applications.manager.ApplicationEnvironmentRetriver;
39  import org.astrogrid.applications.manager.MetadataService;
40  import org.astrogrid.applications.manager.QueryService;
41  import org.astrogrid.component.ComponentManagerException;
42  import org.astrogrid.config.SimpleConfig;
43  import org.astrogrid.registry.client.RegistryDelegateFactory;
44  ///CLOVER:OFF
45  /***
46   * 
47   * A simple servlet that starts cea service, by instantiating the pico container
48   * on destroy, calls back into container, giving things a chance to clean
49   * themselves up if needed.
50   * <p>
51   * Also provides access to some of the metadata methods of the container via
52   * HTTP-GET
53   * 
54   * @author Noel Winstanley
55   * @author Paul Harrison (pah@jb.man.ac.uk) 14-Apr-2004
56   * @version $Name: HEAD $
57   * @since iteration5
58   */
59  public class InitServlet extends HttpServlet {
60  
61     static private org.apache.commons.logging.Log logger = org.apache.commons.logging.LogFactory
62           .getLog(InitServlet.class);
63  
64     /***
65      * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
66      *      javax.servlet.http.HttpServletResponse)
67      */
68     protected void doGet(HttpServletRequest req, HttpServletResponse resp)
69           throws ServletException, IOException {
70        //always do it for now if (! LifecycleListener.storedEndpoint) {
71        URL url = makeEndPointURL(req);
72        LifecycleListener.writeEndpointConfig(url);
73        //        }
74        // expect a 'method' parameter.
75        PrintWriter writer = resp.getWriter();
76        String method = req.getParameter("method");
77        if (method == null || method.trim().length() == 0) {
78           usage(writer);
79        } else if (method.trim().toLowerCase().equals("returnregistryentry")) {
80           resp.setContentType("text/xml");
81           returnRegistryEntry(writer);
82        } else if (method.trim().toLowerCase().equals("getexecutionsummary")) {
83           resp.setContentType("text/xml");
84           String execId = req.getParameter("id");
85           getExecutionSummary(writer, execId);
86  
87        } else if (method.trim().toLowerCase().equals("getexecutionlog")) {
88           String execId = req.getParameter("id");
89           String type = req.getParameter("type");
90           getExecutionLog(resp, execId, type);
91  
92        } else if (method.trim().toLowerCase().equals("register")) {
93           String endpoint = req.getParameter("endpoint");
94           if (endpoint == null) {
95              endpoint = (String) SimpleConfig.getSingleton().getProperty(
96                    RegistryDelegateFactory.ADMIN_URL_PROPERTY);
97           }
98           resp.setContentType("text/html");
99           try {
100             writer
101                   .println("<html><head></head><body><p>registered with registry at "
102                         + endpoint + "</p>");
103             MetadataService voProvider = CEAComponentManagerFactory
104                   .getInstance().getMetadataService();
105 
106             RegistryUploader regUploader = CEAComponentManagerFactory
107                   .getInstance().getRegistryUploaderService();
108             regUploader.write(endpoint);
109             writer.println("</p><p>success</p></body></html>");
110          } catch (Exception e) {
111             writer.println("<p>error registering</p><pre>");
112             e.printStackTrace(writer);
113             writer.println("</pre></body></html>");
114          }
115 
116       }
117       
118       else if (method.trim().toLowerCase().equals("getregistrationtemplate")) {
119         resp.setContentType("application/xml");
120         this.getRegistrationTemplate(resp.getWriter());
121       }
122 
123       else if (method.trim().toLowerCase().equals("startup")) {
124          logger.info("Starting CEA server");
125          CEAComponentManagerFactory.getInstance();
126          resp.setContentType("text/html");
127          writer
128                .println("<html><head></head><body><p>Common Execution Controller Started..</p></body></html>");
129       }
130 
131       else {
132          usage(writer);
133       }
134    }
135 
136    /***
137     * @param resp
138     * @param execId
139     * @param type
140     * @throws IOException
141     */
142    private void getExecutionLog(HttpServletResponse resp, String execId,
143          String type) throws IOException {
144       ApplicationEnvironmentRetriver.StdIOType itype = ApplicationEnvironmentRetriver.StdIOType.out;
145       if (type != null && type.equalsIgnoreCase("err")) {
146          itype = ApplicationEnvironmentRetriver.StdIOType.err;
147       }
148       try {
149          QueryService queryService = CEAComponentManagerFactory.getInstance()
150                .getQueryService();
151          assert queryService != null : "interal error - no query service";
152          File logFile = queryService.getLogFile(execId, itype);
153          resp.setContentType("text/plain");
154          PrintWriter pw = resp.getWriter();
155          if(logFile != null)
156          {
157          BufferedReader inReader = new BufferedReader(new FileReader(logFile));
158 
159          String str = inReader.readLine();
160          while (str != null) {
161             pw.write(str);
162             pw.write("\n");
163             str = inReader.readLine();
164          }
165          }
166          else
167          {
168             pw.write("<b>error</b> log file could not be found");
169          }
170 
171       } catch (ComponentManagerException e) {
172          logger.error("internal error", e);
173          showError(resp, e);
174       } catch (FileNotFoundException e) {
175          logger.error("cannot find log file", e);
176          showError(resp, e);
177       } catch (CeaException e) {
178          logger.error("problem getting log file", e);
179          showError(resp, e);
180       }
181    }
182 
183    private void showError(HttpServletResponse resp, Exception e) {
184       try {
185          resp.setContentType("text/html");
186          PrintWriter writer = resp.getWriter();
187          writer.println("<html><head></head><body><p>Error.</p><p>");
188          writer.println(e.getMessage());
189          writer.println("</p></body></html>");
190       } catch (IOException e1) {
191 
192          e1.printStackTrace();
193       }
194 
195    }
196 
197    protected void returnRegistryEntry(PrintWriter pw) throws ServletException {
198       try {
199          Document regEntry = CEAComponentManagerFactory.getInstance()
200                .getMetadataService().returnRegistryEntry();
201          XMLUtils.DocumentToWriter(regEntry, pw);
202       }
203         catch (CeaException e) {
204          throw new ServletException(e);
205       }
206    }
207 
208    protected void getExecutionSummary(PrintWriter pw, String execId)
209          throws ServletException {
210       try {
211          ExecutionSummaryType summary = CEAComponentManagerFactory
212                .getInstance().getQueryService().getSummary(execId);
213          summary.marshal(pw);
214       } catch (Exception e) {
215          throw new ServletException(e);
216       }
217    }
218    
219    protected void getRegistrationTemplate(PrintWriter writer) 
220        throws ServletException {
221      try {
222        CEAComponentManager m = CEAComponentManagerFactory.getInstance();
223        URL url = m.getMetadataService().getRegistrationTemplate();
224        BufferedReader reader 
225            = new BufferedReader(new InputStreamReader(url.openStream()));
226        while(true) {
227          String line = reader.readLine();
228          if (line == null) {
229            break;
230          }
231          writer.print(line + "\n");
232        }
233      } catch (Exception e) {
234        throw new ServletException(e);
235      }
236    }
237 
238    protected void usage(PrintWriter pw) {
239       pw.println("<html><body>");
240       pw.println("<h1>Usage</h1>");
241       pw.println("<ul>");
242       pw
243             .println("<ul><tt>?method=startup</tt> - start the CommonExecutionController");
244       pw
245             .println("<li><tt>?method=returnRegistryEntry</tt> - display the VODescription for this service</li>");
246       pw
247       .println("<li><tt>?method=getExecutionSummary&amp;id=<i>executionId</i></tt> - display execution summary for <i>executionId</i>");
248       pw
249       .println("<li><tt>?method=getexecutionlog&amp;id=<i>executionId&type=out|err</i></tt> - display execution summary for <i>executionId</i>");
250       pw.println("</ul>");
251       pw.println("</body></html>");
252    }
253 
254    private URL makeEndPointURL(HttpServletRequest request) {
255       URL url = null;
256       try {
257          url = new URL("http", request.getServerName(),
258                request.getServerPort(), request.getContextPath()
259                      + "/services/CommonExecutionConnectorService");
260          logger.info("creating endpointURL=" + url);
261 
262       } catch (MalformedURLException e) {
263          logger.warn("could not create the context path from request data", e);
264       }
265       return url;
266 
267    }
268 
269 }