View Javadoc

1   /*
2    * Copyright (c) 2005-2007 Creative Sphere Limited.
3    * All rights reserved. This program and the accompanying materials
4    * are made available under the terms of the Eclipse Public License v1.0
5    * which accompanies this distribution, and is available at
6    * http://www.eclipse.org/legal/epl-v10.html
7    *
8    * Contributors:
9    *
10   *   Creative Sphere - initial API and implementation
11   *
12   */
13  package org.abstracthorizon.danube.http.util;
14  
15  import org.abstracthorizon.danube.connection.Connection;
16  import org.abstracthorizon.danube.connection.ConnectionHandler;
17  import org.abstracthorizon.danube.http.HTTPConnection;
18  import org.abstracthorizon.danube.http.Status;
19  
20  import java.io.PrintWriter;
21  
22  /**
23   * Default error connection handler.
24   * It outputs simple html with response status and response code.
25   *
26   * @author Daniel Sendula
27   */
28  public class ErrorConnectionHandler implements ConnectionHandler {
29  
30      /** Constructor */
31      public ErrorConnectionHandler() {
32      }
33  
34      /**
35       * Returns simple http with error description
36       * @param connection http connection
37       */
38      public void handleConnection(Connection connection) {
39          HTTPConnection httpConnection = (HTTPConnection)connection.adapt(HTTPConnection.class);
40          Status status = httpConnection.getResponseStatus();
41          if (status == null) {
42              status = Status.INTERNAL_SERVER_ERROR;
43              httpConnection.setResponseStatus(status);
44          }
45  
46          PrintWriter out = (PrintWriter)httpConnection.adapt(PrintWriter.class);
47          out.println("<http><head><title>Error</title></head>");
48          out.println("<body><h2>" + status.getCode() + " " + status.getMessage() + "</h2><br />");
49          Throwable t = (Throwable)httpConnection.getAttributes().get("_exception");
50          if (t != null) {
51              out.print("<pre>");
52              t.printStackTrace(out);
53              out.print("</pre>");
54          }
55          out.println("</body></html>");
56          out.close();
57      }
58  
59  }