axis-java-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Doug Davis <...@us.ibm.com>
Subject Re: cvs commit: xml-axis/java/src/org/apache/axis/transport/http QSHandler.java QSListHandler.java QSMethodHandler.java QSWSDLHandler.java AxisServlet.java HTTPConstants.java
Date Thu, 07 Aug 2003 00:14:06 GMT





Oops - forgot to say:
Author:  Curtiss Howard  cjhoward@us.ibm.com

-Dug


dug@apache.org on 08/06/2003 08:12:45 PM

Please respond to axis-dev@ws.apache.org

To:    xml-axis-cvs@apache.org
cc:
Subject:    cvs commit: xml-axis/java/src/org/apache/axis/transport/http
       QSHandler.java QSListHandler.java QSMethodHandler.java
       QSWSDLHandler.java AxisServlet.java HTTPConstants.java


dug         2003/08/06 17:12:45

  Modified:    java/src/org/apache/axis/server server-config.wsdd
               java/src/org/apache/axis/transport/http AxisServlet.java
                        HTTPConstants.java
  Added:       java/src/org/apache/axis/transport/http QSHandler.java
                        QSListHandler.java QSMethodHandler.java
                        QSWSDLHandler.java
  Log:
  Pluggable query string support.
  For now see the default server-config.wsdd for an example.
  Docs will soon follow.

  Revision  Changes    Path
  1.15      +8 -0
xml-axis/java/src/org/apache/axis/server/server-config.wsdd

  Index: server-config.wsdd
  ===================================================================
  RCS file:
/home/cvs/xml-axis/java/src/org/apache/axis/server/server-config.wsdd,v
  retrieving revision 1.14
  retrieving revision 1.15
  diff -u -r1.14 -r1.15
  --- server-config.wsdd             4 Dec 2002 20:12:05 -0000
1.14
  +++ server-config.wsdd             7 Aug 2003 00:12:45 -0000
1.15
  @@ -43,6 +43,14 @@
    </service>

    <transport name="http">
  +  <parameter name="qs:list"
  +               value="org.apache.axis.transport.http.QSListHandler"/>
  +  <parameter name="qs:method"
  +               value="org.apache.axis.transport.http.QSMethodHandler"/>
  +  <parameter name="qs:wsdl"
  +               value="org.apache.axis.transport.http.QSWSDLHandler"/>
  +  <parameter name="qs:wsdldoc"
  +
value="com.ibm.wstk.axis.transport.http.QSWSDLDocHandler"/>
     <requestFlow>
      <handler type="URLMapper"/>
      <handler type="java:org.apache.axis.handlers.http.HTTPAuthHandler"/>



  1.164     +132 -232
xml-axis/java/src/org/apache/axis/transport/http/AxisServlet.java

  Index: AxisServlet.java
  ===================================================================
  RCS file:
/home/cvs/xml-axis/java/src/org/apache/axis/transport/http/AxisServlet.java,v

  retrieving revision 1.163
  retrieving revision 1.164
  diff -u -r1.163 -r1.164
  --- AxisServlet.java         18 Jul 2003 12:40:40 -0000          1.163
  +++ AxisServlet.java         7 Aug 2003 00:12:45 -0000           1.164
  @@ -59,6 +59,7 @@
   import org.apache.axis.AxisFault;
   import org.apache.axis.ConfigurationException;
   import org.apache.axis.Constants;
  +import org.apache.axis.Handler;
   import org.apache.axis.Message;
   import org.apache.axis.MessageContext;
   import org.apache.axis.components.logger.LogFactory;
  @@ -84,6 +85,7 @@
   import java.io.File;
   import java.io.IOException;
   import java.io.PrintWriter;
  +import java.lang.reflect.Method;
   import java.net.HttpURLConnection;
   import java.util.ArrayList;
   import java.util.Enumeration;
  @@ -231,8 +233,6 @@
                   realpath = request.getServletPath();
               }

  -            boolean wsdlRequested = false;
  -            boolean listRequested = false;
               boolean hasParameters =
request.getParameterNames().hasMoreElements();

               //JWS pages are special; they are the servlet path and there
  @@ -242,19 +242,15 @@
               if(isJWSPage) {
                   pathInfo= request.getServletPath();
               }
  -
  -            // check first if we are doing WSDL or a list operation
  -            String queryString = request.getQueryString();
  -            if (queryString != null) {
  -                if (queryString.equalsIgnoreCase("wsdl")) {
  -                    wsdlRequested = true;
  -                } else if (queryString.equalsIgnoreCase("list")) {
  -                    listRequested = true;
  -                }
  +
  +            // Try to execute a query string plugin and return upon
success.
  +
  +            if (processQuery (request, response, writer) == true) {
  +                 return;
               }
  -
  +
               boolean hasNoPath = (pathInfo == null ||
pathInfo.equals(""));
  -            if (!wsdlRequested && !listRequested && hasNoPath) {
  +            if (hasNoPath) {
                   // If the user requested the servlet (i.e.
/axis/servlet/AxisServlet)
                   // with no service name, present the user with a list of
deployed
                   // services to be helpful
  @@ -279,46 +275,29 @@

                   msgContext.setProperty(MessageContext.TRANS_URL, url);

  -
  -                if (wsdlRequested) {
  -                    // Do WSDL generation
  -                    processWsdlRequest(msgContext, response, writer);
  -                } else if (listRequested) {
  -                    // Do list, if it is enabled
  -                    processListRequest(response, writer);
  -                } else if (hasParameters) {
  -                    // If we have ?method=x&param=y in the URL, make a
stab
  -                    // at invoking the method with the parameters
specified
  -                    // in the URL
  -
  -                    processMethodRequest(msgContext, request, response,
writer);
  -
  +                // See if we can locate the desired service.  If we
  +                // can't, return a 404 Not Found.  Otherwise, just
  +                // print the placeholder message.
  +
  +                String serviceName;
  +                if (pathInfo.startsWith("/")) {
  +                    serviceName = pathInfo.substring(1);
                   } else {
  +                    serviceName = pathInfo;
  +                }

  -                    // See if we can locate the desired service.  If we
  -                    // can't, return a 404 Not Found.  Otherwise, just
  -                    // print the placeholder message.
  -
  -                    String serviceName;
  -                    if (pathInfo.startsWith("/")) {
  -                        serviceName = pathInfo.substring(1);
  +                SOAPService s = engine.getService(serviceName);
  +                if (s == null) {
  +                    //no service: report it
  +                    if(isJWSPage) {
  +                        reportCantGetJWSService(request, response,
writer);
                       } else {
  -                        serviceName = pathInfo;
  +                        reportCantGetAxisService(request, response,
writer);
                       }

  -                    SOAPService s = engine.getService(serviceName);
  -                    if (s == null) {
  -                        //no service: report it
  -                        if(isJWSPage) {
  -                            reportCantGetJWSService(request, response,
writer);
  -                        } else {
  -                            reportCantGetAxisService(request, response,
writer);
  -                        }
  -
  -                    } else {
  -                        //print a snippet of service info.
  -                        reportServiceInfo(response, writer, s,
serviceName);
  -                    }
  +                } else {
  +                    //print a snippet of service info.
  +                    reportServiceInfo(response, writer, s, serviceName);
                   }
               } else {
                   // We didn't have a real path in the request, so just
  @@ -424,149 +403,6 @@
       }

       /**
  -     * scan through the request for parameters, invoking the endpoint
  -     * if we get a method param. If there was no method param then the
  -     * response is set to a 400 Bad Request and some error text
  -     * @param msgContext current message
  -     * @param request incoming requests
  -     * @param response response to generate
  -     * @param writer output stream
  -     * @throws AxisFault if anything goes wrong during method execution
  -     */
  -    protected void processMethodRequest(MessageContext msgContext,
  -                                        HttpServletRequest request,
  -                                        HttpServletResponse response,
  -                                        PrintWriter writer) throws
AxisFault {
  -        Enumeration enum = request.getParameterNames();
  -        String method = null;
  -        String args = "";
  -        while (enum.hasMoreElements()) {
  -            String param = (String) enum.nextElement();
  -            if (param.equalsIgnoreCase("method")) {
  -                method = request.getParameter(param);
  -            } else {
  -                args += "<" + param + ">" +
  -                    request.getParameter(param) +
  -                    "</" + param + ">";
  -            }
  -        }
  -
  -        if (method == null) {
  -            response.setContentType("text/html");
  -            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
  -            writer.println("<h2>" +
  -                           Messages.getMessage("error00") +
  -                           ":  " +
  -                           Messages.getMessage("invokeGet00") +
  -                           "</h2>");
  -            writer.println("<p>" +
  -                           Messages.getMessage("noMethod01") +
  -                           "</p>");
  -        } else {
  -            invokeEndpointFromGet(msgContext, response, writer, method,
args);
  -
  -        }
  -    }
  -
  -    /**
  -     * handle a ?wsdl request
  -     * @param msgContext message context so far
  -     * @param response response to write to
  -     * @param writer output stream
  -     * @throws AxisFault when anything other than a Server.NoService
fault is reported
  -     * during WSDL generation
  -     */
  -    protected void processWsdlRequest(MessageContext msgContext,
  -                                      HttpServletResponse response,
  -                                      PrintWriter writer) throws
AxisFault {
  -        AxisEngine engine = getEngine();
  -        try {
  -            engine.generateWSDL(msgContext);
  -            Document doc = (Document) msgContext.getProperty("WSDL");
  -            if (doc != null) {
  -                response.setContentType("text/xml");
  -                XMLUtils.DocumentToWriter(doc, writer);
  -            } else {
  -                if (log.isDebugEnabled()) {
  -                    log.debug("processWsdlRequest: failed to create
WSDL");
  -                }
  -                reportNoWSDL(response, writer, "noWSDL02", null);
  -            }
  -        } catch (AxisFault axisFault) {
  -            //the no-service fault is mapped to a no-wsdl error
  -            if(axisFault.getFaultCode()
.equals(Constants.QNAME_NO_SERVICE_FAULT_CODE)) {
  -                //which we log
  -                processAxisFault(axisFault);
  -                //then report under a 404 error
  -                response.setStatus(HttpURLConnection.HTTP_NOT_FOUND);
  -                reportNoWSDL(response, writer, "noWSDL01", axisFault);
  -            } else {
  -                //all other faults get thrown
  -                throw axisFault;
  -            }
  -        }
  -    }
  -
  -    /**
  -     * invoke an endpoint from a get request by building an XML request
and
  -     * handing it down. If anything goes wrong, we generate an XML
formatted
  -     * axis fault
  -     * @param msgContext current message
  -     * @param response to return data
  -     * @param writer output stream
  -     * @param method method to invoke (may be null)
  -     * @param args argument list in XML form
  -     * @throws AxisFault iff something goes wrong when turning the
response message
  -     * into a SOAP string.
  -     */
  -    protected void invokeEndpointFromGet(MessageContext msgContext,
  -                                       HttpServletResponse response,
  -                                       PrintWriter writer,
  -                                       String method,
  -                                       String args) throws AxisFault {
  -        String body =
  -            "<" + method + ">" + args + "</" + method + ">";
  -
  -        String msgtxt =
  -            "<SOAP-ENV:Envelope" +
  -            " xmlns:SOAP-ENV=\"
http://schemas.xmlsoap.org/soap/envelope/\">" +
  -            "<SOAP-ENV:Body>" + body + "</SOAP-ENV:Body>" +
  -            "</SOAP-ENV:Envelope>";
  -
  -        Message responseMsg=null;
  -        try {
  -            ByteArrayInputStream istream =
  -                new
ByteArrayInputStream(msgtxt.getBytes(XMLUtils.httpAuthCharEncoding));
  -
  -            AxisEngine engine = getEngine();
  -            Message msg = new Message(istream, false);
  -            msgContext.setRequestMessage(msg);
  -            engine.invoke(msgContext);
  -            responseMsg = msgContext.getResponseMessage();
  -            //turn off caching for GET requests
  -            response.setHeader("Cache-Control", "no-cache");
  -            response.setHeader("Pragma", "no-cache");
  -            if (responseMsg == null) {
  -                //tell everyone that something is wrong
  -                throw new
Exception(Messages.getMessage("noResponse01"));
  -            }
  -        } catch (AxisFault fault) {
  -            processAxisFault(fault);
  -            configureResponseFromAxisFault(response, fault);
  -            if (responseMsg == null) {
  -                responseMsg = new Message(fault);
  -            }
  -        } catch (Exception e) {
  -
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
  -            responseMsg = convertExceptionToAxisFault(e,responseMsg);
  -        }
  -        //this call could throw an AxisFault. We delegate it up, because
  -        //if we cant write the message there is not a lot we can do in
pure SOAP terms.
  -        response.setContentType("text/xml");
  -        writer.println(responseMsg.getSOAPPartAsString());
  -    }
  -
  -    /**
        * print a snippet of service info.
        * @param service service
        * @param writer output channel
  @@ -588,47 +424,7 @@
                   Messages.getMessage("perhaps00") +
                   "</i>");
       }
  -
  -    /**
  -     * respond to the ?list command.
  -     * if enableList is set, we list the engine config. If it isnt, then
an
  -     * error is written out
  -     * @param response
  -     * @param writer
  -     * @throws AxisFault
  -     */
  -    protected void processListRequest(HttpServletResponse response,
PrintWriter writer) throws AxisFault {
  -        AxisEngine engine = getEngine();
  -        if (enableList) {
  -            Document doc = Admin.listConfig(engine);
  -            if (doc != null) {
  -                response.setContentType("text/xml");
  -                XMLUtils.DocumentToWriter(doc, writer);
  -            } else {
  -                //error code is 404
  -                response.setStatus(HttpURLConnection.HTTP_NOT_FOUND);
  -                response.setContentType("text/html");
  -                writer.println("<h2>" +
  -                               Messages.getMessage("error00") +
  -                               "</h2>");
  -                writer.println("<p>" +
  -                               Messages.getMessage("noDeploy00") +
  -                               "</p>");
  -            }
  -        } else {
  -            // list not enable, return error
  -            //error code is, what, 401
  -            response.setStatus(HttpURLConnection.HTTP_FORBIDDEN);
  -            response.setContentType("text/html");
  -            writer.println("<h2>" +
  -                           Messages.getMessage("error00") +
  -                           "</h2>");
  -            writer.println("<p><i>?list</i> " +
  -                           Messages.getMessage("disabled00") +
  -                           "</p>");
  -        }
  -    }
  -
  +
       /**
        * report that we have no WSDL
        * @param res
  @@ -1164,4 +960,108 @@
           }
           return ret;
       }
  +
  +    /**
  +     * Attempts to invoke a plugin for the query string supplied in the
URL.
  +     *
  +     * @param request the servlet's HttpServletRequest object.
  +     * @param response the servlet's HttpServletResponse object.
  +     * @param writer the servlet's PrintWriter object.
  +     */
  +
  +    private boolean processQuery (HttpServletRequest request,
HttpServletResponse response,
  +          PrintWriter writer) throws AxisFault {
  +          // Attempt to instantiate a plug-in handler class for the
query string
  +          // handler classes defined in the HTTP transport.
  +
  +          String path = request.getServletPath();
  +          String queryString = request.getQueryString();
  +          String serviceName;
  +          AxisEngine engine = getEngine();
  +          Handler httpTransport = engine.getTransport ("http");
  +          Iterator i = httpTransport.getOptions().keySet().iterator();
  +
  +          if (queryString == null) {
  +               return false;
  +          }
  +
  +          serviceName = request.getRequestURI().substring
  +               (request.getRequestURI().indexOf (path) + path.length() +
1);
  +
  +          while (i.hasNext() == true) {
  +               String queryHandler = (String) i.next();
  +
  +               if (queryHandler.startsWith ("qs:") == true) {
  +                    // Only attempt to match the query string with
transport
  +                    // parameters prefixed with "qs:".
  +
  +                    String handlerName = queryHandler.substring
  +                         (queryHandler.indexOf (":") + 1).toLowerCase();
  +
  +                    // Determine the name of the plugin to invoke by
using all text
  +                    // in the query string up to the first occurence of
&, =, or the
  +                    // whole string if neither is present.
  +
  +                    int length = 0;
  +                    boolean firstParamFound = false;
  +
  +                    while (firstParamFound == false && length <
queryString.length()) {
  +                         char ch = queryString.charAt (length++);
  +
  +                         if (ch == '&' || ch == '=') {
  +                              firstParamFound = true;
  +
  +                              --length;
  +                         }
  +                    }
  +
  +                    if (length < queryString.length()) {
  +                         queryString = queryString.substring (0,
length);
  +                    }
  +
  +                    if (queryString.toLowerCase().equals (handlerName)
== true) {
  +                         // Query string matches a defined query string
handler name.
  +
  +                         try {
  +                              // Attempt to dynamically load the query
string handler
  +                              // and its "invoke" method.
  +
  +                              MessageContext msgContext =
createMessageContext (engine, request, response);
  +                              Class plugin = Class.forName ((String)
httpTransport.getOption (queryHandler));
  +                              Method pluginMethod =
plugin.getDeclaredMethod ("invoke",
  +                                new Class[] { msgContext.getClass() });
  +                              String url = HttpUtils.getRequestURL
(request).toString();
  +
  +                              // Place various useful servlet-related
objects in
  +                              // the MessageContext object being
delivered to the
  +                              // plugin.
  +
  +                              msgContext.setProperty
(MessageContext.TRANS_URL, url);
  +                              msgContext.setProperty
(HTTPConstants.PLUGIN_SERVICE_NAME, serviceName);
  +                              msgContext.setProperty
(HTTPConstants.PLUGIN_NAME, handlerName);
  +                              msgContext.setProperty
(HTTPConstants.PLUGIN_IS_DEVELOPMENT, new Boolean (isDevelopment()));
  +                              msgContext.setProperty
(HTTPConstants.PLUGIN_ENABLE_LIST, new Boolean (enableList));
  +                              msgContext.setProperty
(HTTPConstants.PLUGIN_ENGINE, engine);
  +                              msgContext.setProperty
(HTTPConstants.PLUGIN_WRITER, writer);
  +                              msgContext.setProperty
(HTTPConstants.PLUGIN_LOG, log);
  +                              msgContext.setProperty
(HTTPConstants.PLUGIN_EXCEPTION_LOG, exceptionLog);
  +
  +                              // Invoke the plugin.
  +
  +                              pluginMethod.invoke (plugin.newInstance(),
new Object[] { msgContext });
  +
  +                              writer.close();
  +
  +                              return true;
  +                         }
  +
  +                         catch (Exception e) {
  +                              reportTroubleInGet (e, response, writer);
  +                         }
  +                    }
  +               }
  +          }
  +
  +          return false;
  +     }
   }



  1.26      +13 -0
xml-axis/java/src/org/apache/axis/transport/http/HTTPConstants.java

  Index: HTTPConstants.java
  ===================================================================
  RCS file:
/home/cvs/xml-axis/java/src/org/apache/axis/transport/http/HTTPConstants.java,v

  retrieving revision 1.25
  retrieving revision 1.26
  diff -u -r1.25 -r1.26
  --- HTTPConstants.java             22 Apr 2003 19:35:51 -0000
1.25
  +++ HTTPConstants.java             7 Aug 2003 00:12:45 -0000
1.26
  @@ -149,4 +149,17 @@
       /** HTTP header field values
        */
       public static final String HEADER_DEFAULT_CHAR_ENCODING =
"iso-8859-1";
  +
  +    /**
  +     * AXIS servlet plugin parameter names.
  +     */
  +
  +    public static final String PLUGIN_NAME =
"transport.http.plugin.pluginName";
  +    public static final String PLUGIN_SERVICE_NAME =
"transport.http.plugin.serviceName";
  +    public static final String PLUGIN_IS_DEVELOPMENT =
"transport.http.plugin.isDevelopment";
  +    public static final String PLUGIN_ENABLE_LIST =
"transport.http.plugin.enableList";
  +    public static final String PLUGIN_ENGINE =
"transport.http.plugin.engine";
  +    public static final String PLUGIN_WRITER =
"transport.http.plugin.writer";
  +    public static final String PLUGIN_LOG = "transport.http.plugin.log";
  +    public static final String PLUGIN_EXCEPTION_LOG =
"transport.http.plugin.exceptionLog";
   }



  1.1
xml-axis/java/src/org/apache/axis/transport/http/QSHandler.java

  Index: QSHandler.java
  ===================================================================
  package org.apache.axis.transport.http;

  import org.apache.axis.AxisFault;
  import org.apache.axis.MessageContext;

  /**
   * The QSHandler interface defines an interface for classes that handle
the
   * actions necessary when a particular query string is encountered in an
AXIS
   * servlet invocation.
   *
   * @author Curtiss Howard
   */

  public interface QSHandler {
       /**
        * Performs the action associated with this particular query string
        * handler.
        *
        * @param msgContext a MessageContext object containing message
context
        *        information for this query string handler.
        * @throws AxisFault if an error occurs.
        */

       public void invoke (MessageContext msgContext) throws AxisFault;
  }



  1.1
xml-axis/java/src/org/apache/axis/transport/http/QSListHandler.java

  Index: QSListHandler.java
  ===================================================================
  package org.apache.axis.transport.http;

  import java.io.PrintWriter;
  import java.net.HttpURLConnection;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;

  import org.apache.axis.AxisFault;
  import org.apache.axis.MessageContext;
  import org.apache.axis.server.AxisServer;
  import org.apache.axis.transport.http.HTTPConstants;
  import org.apache.axis.utils.Admin;
  import org.apache.axis.utils.Messages;
  import org.apache.axis.utils.XMLUtils;

  import org.w3c.dom.Document;

  /**
   * The QSListHandler class is a handler which lists the AXIS Server's
   * configuration when the query string "list" is encountered in an AXIS
servlet
   * invocation.
   *
   * @author Curtiss Howard (code mostly from AxisServlet class)
   * @author Doug Davis (dug@us.ibm.com)
   * @author Steve Loughran
   */

  public class QSListHandler implements QSHandler {
       /**
        * Performs the action associated with this particular query string
        * handler.
        *
        * @param msgContext a MessageContext object containing message
context
        *        information for this query string handler.
        * @throws AxisFault if an error occurs.
        */

       public void invoke (MessageContext msgContext) throws AxisFault {
            // Obtain objects relevant to the task at hand from the
provided
            // MessageContext's bag.

            boolean enableList = ((Boolean) msgContext.getProperty
                 (HTTPConstants.PLUGIN_ENABLE_LIST)).booleanValue();
            AxisServer engine = (AxisServer) msgContext.getProperty
                 (HTTPConstants.PLUGIN_ENGINE);
            PrintWriter writer = (PrintWriter) msgContext.getProperty
                 (HTTPConstants.PLUGIN_WRITER);
            HttpServletResponse response = (HttpServletResponse)
                 msgContext.getProperty
(HTTPConstants.MC_HTTP_SERVLETRESPONSE);

            if (enableList) {
                 Document doc = Admin.listConfig (engine);

                 if (doc != null) {
                      response.setContentType ("text/xml");
                      XMLUtils.DocumentToWriter (doc, writer);
                 }

                 else {
                      //error code is 404

                      response.setStatus
(HttpURLConnection.HTTP_NOT_FOUND);
                      response.setContentType ("text/html");

                      writer.println ("<h2>" + Messages.getMessage
("error00") +
                           "</h2>");
                      writer.println ("<p>" + Messages.getMessage
("noDeploy00") +
                           "</p>");
                 }
            }

            else {
                 // list not enable, return error
                 //error code is, what, 401

                 response.setStatus (HttpURLConnection.HTTP_FORBIDDEN);
                 response.setContentType ("text/html");

                 writer.println ("<h2>" + Messages.getMessage ("error00") +
                      "</h2>");
                 writer.println ("<p><i>?list</i> " +
                      Messages.getMessage ("disabled00") + "</p>");
            }
       }
  }



  1.1
xml-axis/java/src/org/apache/axis/transport/http/QSMethodHandler.java

  Index: QSMethodHandler.java
  ===================================================================
  package org.apache.axis.transport.http;

  import java.io.ByteArrayInputStream;
  import java.io.PrintWriter;
  import java.util.Enumeration;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;

  import org.apache.axis.AxisFault;
  import org.apache.axis.Constants;
  import org.apache.axis.Message;
  import org.apache.axis.MessageContext;
  import org.apache.axis.server.AxisServer;
  import org.apache.axis.transport.http.HTTPConstants;
  import org.apache.axis.utils.Messages;
  import org.apache.commons.logging.Log;

  import org.w3c.dom.Element;

  /**
   * The QSMethodHandler class is a handler which executes a given method
from an
   * an AXIS service's WSDL definition when the query string "method" is
   * encountered in an AXIS servlet invocation.
   *
   * @author Curtiss Howard (code mostly from AxisServlet class)
   * @author Doug Davis (dug@us.ibm.com)
   * @author Steve Loughran
   */

  public class QSMethodHandler implements QSHandler {
       private boolean development;
       private Log exceptionLog;

       /**
        * probe for the system being 'production'
        * @return true for a dev system.
        */

       private boolean isDevelopment () {
            return this.development;
       }

       /**
        * Performs the action associated with this particular query string
        * handler.
        *
        * @param msgContext a MessageContext object containing message
context
        *        information for this query string handler.
        * @throws AxisFault if an error occurs.
        */

       public void invoke (MessageContext msgContext) throws AxisFault {
            // Obtain objects relevant to the task at hand from the
provided
            // MessageContext's bag.

            AxisServer engine = (AxisServer) msgContext.getProperty
                 (HTTPConstants.PLUGIN_ENGINE);
            PrintWriter writer = (PrintWriter) msgContext.getProperty
                 (HTTPConstants.PLUGIN_WRITER);
            HttpServletRequest request = (HttpServletRequest)
                 msgContext.getProperty
(HTTPConstants.MC_HTTP_SERVLETREQUEST);
            HttpServletResponse response = (HttpServletResponse)
                 msgContext.getProperty
(HTTPConstants.MC_HTTP_SERVLETRESPONSE);
            this.development = ((Boolean) msgContext.getProperty
                 (HTTPConstants.PLUGIN_IS_DEVELOPMENT)).booleanValue();
            this.exceptionLog = (Log) msgContext.getProperty
                 (HTTPConstants.PLUGIN_EXCEPTION_LOG);

            String method = null;
            String args = "";
            Enumeration enum = request.getParameterNames();

            while (enum.hasMoreElements()) {
                 String param = (String) enum.nextElement();
                 if (param.equalsIgnoreCase ("method")) {
                      method = request.getParameter (param);
                 }

                 else {
                      args += "<" + param + ">" + request.getParameter
(param) +
                           "</" + param + ">";
                 }
            }

            if (method == null) {
                 response.setContentType ("text/html");
                 response.setStatus (HttpServletResponse.SC_BAD_REQUEST);

                 writer.println ("<h2>" + Messages.getMessage ("error00") +
                      ":  " + Messages.getMessage ("invokeGet00") +
"</h2>");
                 writer.println ("<p>" + Messages.getMessage ("noMethod01")
+
                      "</p>");
            }

            else {
                 invokeEndpointFromGet (msgContext, response, writer,
method, args);
            }
       }

       /**
        * invoke an endpoint from a get request by building an XML request
and
        * handing it down. If anything goes wrong, we generate an XML
formatted
        * axis fault
        * @param msgContext current message
        * @param response to return data
        * @param writer output stream
        * @param method method to invoke (may be null)
        * @param args argument list in XML form
        * @throws AxisFault iff something goes wrong when turning the
response message
        * into a SOAP string.
        */

       private void invokeEndpointFromGet (MessageContext msgContext,
            HttpServletResponse response, PrintWriter writer, String
method,
            String args) throws AxisFault {
            String body = "<" + method + ">" + args + "</" + method + ">";
            String msgtxt = "<SOAP-ENV:Envelope" +
                 " xmlns:SOAP-ENV=\"
http://schemas.xmlsoap.org/soap/envelope/\">" +
                 "<SOAP-ENV:Body>" + body + "</SOAP-ENV:Body>" +
                 "</SOAP-ENV:Envelope>";
            ByteArrayInputStream istream =
                 new ByteArrayInputStream (msgtxt.getBytes());
            Message responseMsg = null;

            try {
                 AxisServer engine = (AxisServer) msgContext.getProperty
                      (HTTPConstants.PLUGIN_ENGINE);
                 Message msg = new Message (istream, false);

                 msgContext.setRequestMessage (msg);
                 engine.invoke (msgContext);

                 responseMsg = msgContext.getResponseMessage();

                 //turn off caching for GET requests

                 response.setHeader ("Cache-Control", "no-cache");
                 response.setHeader ("Pragma", "no-cache");

                 if (responseMsg == null) {
                      //tell everyone that something is wrong

                      throw new Exception (Messages.getMessage
("noResponse01"));
                 }

            }

            catch (AxisFault fault) {
                 processAxisFault (fault);

                 configureResponseFromAxisFault (response, fault);

                 if (responseMsg == null) {
                      responseMsg = new Message (fault);
                 }
            }

            catch (Exception e) {
                 response.setStatus
(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                 responseMsg = convertExceptionToAxisFault (e,
responseMsg);
            }

            //this call could throw an AxisFault. We delegate it up,
because
            //if we cant write the message there is not a lot we can do in
pure SOAP terms.

            response.setContentType ("text/xml");

            writer.println (responseMsg.getSOAPPartAsString());
       }

       /**
        * routine called whenever an axis fault is caught; where they
        * are logged and any other business. The method may modify the
fault
        * in the process
        * @param fault what went wrong.
        */

       private void processAxisFault (AxisFault fault) {
            //log the fault

            Element runtimeException = fault.lookupFaultDetail
                 (Constants.QNAME_FAULTDETAIL_RUNTIMEEXCEPTION);

            if (runtimeException != null) {
                 exceptionLog.info (Messages.getMessage ("axisFault00"),
fault);

                 //strip runtime details

                 fault.removeFaultDetail
                      (Constants.QNAME_FAULTDETAIL_RUNTIMEEXCEPTION);
            }

            else if (exceptionLog.isDebugEnabled()) {
                 exceptionLog.debug (Messages.getMessage ("axisFault00"),
fault);
            }

            //dev systems only give fault dumps

            if (!isDevelopment()) {
                 //strip out the stack trace

                 fault.removeFaultDetail
(Constants.QNAME_FAULTDETAIL_STACKTRACE);
            }
       }

       /**
        * Configure the servlet response status code and maybe other
headers
        * from the fault info.
        * @param response response to configure
        * @param fault what went wrong
        */

       private void configureResponseFromAxisFault (HttpServletResponse
response,
            AxisFault fault) {
            // then get the status code
            // It's been suggested that a lack of SOAPAction
            // should produce some other error code (in the 400s)...

            int status = getHttpServletResponseStatus (fault);

            if (status == HttpServletResponse.SC_UNAUTHORIZED) {
                 // unauth access results in authentication request
                 // TODO: less generic realm choice?

                 response.setHeader ("WWW-Authenticate", "Basic
realm=\"AXIS\"");
            }

            response.setStatus (status);
       }

       /**
        * turn any Exception into an AxisFault, log it, set the response
        * status code according to what the specifications say and
        * return a response message for posting. This will be the response
        * message passed in if non-null; one generated from the fault
otherwise.
        *
        * @param exception what went wrong
        * @param responseMsg what response we have (if any)
        * @return a response message to send to the user
        */

       private Message convertExceptionToAxisFault (Exception exception,
            Message responseMsg) {
            logException (exception);

            if (responseMsg == null) {
                 AxisFault fault = AxisFault.makeFault (exception);

                 processAxisFault (fault);

                 responseMsg = new Message (fault);
            }

            return responseMsg;
       }

       /**
        * Extract information from AxisFault and map it to a HTTP Status
code.
        *
        * @param af Axis Fault
        * @return HTTP Status code.
        */

       private int getHttpServletResponseStatus (AxisFault af) {
            // TODO: Should really be doing this with explicit AxisFault
            // subclasses... --Glen

            return af.getFaultCode().getLocalPart().startsWith
("Server.Unauth")
                 ? HttpServletResponse.SC_UNAUTHORIZED
                 : HttpServletResponse.SC_INTERNAL_SERVER_ERROR;

            // This will raise a 401 for both
            // "Unauthenticated" & "Unauthorized"...
       }

       /**
        * log any exception to our output log, at our chosen level
        * @param e what went wrong
        */

       private void logException (Exception e) {
            exceptionLog.info (Messages.getMessage ("exception00"), e);
       }
  }



  1.1
xml-axis/java/src/org/apache/axis/transport/http/QSWSDLHandler.java

  Index: QSWSDLHandler.java
  ===================================================================
  package org.apache.axis.transport.http;

  import java.io.PrintWriter;
  import java.net.HttpURLConnection;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;

  import org.apache.axis.AxisFault;
  import org.apache.axis.Constants;
  import org.apache.axis.MessageContext;
  import org.apache.axis.server.AxisServer;
  import org.apache.axis.transport.http.HTTPConstants;
  import org.apache.axis.utils.Messages;
  import org.apache.axis.utils.XMLUtils;
  import org.apache.commons.logging.Log;

  import org.w3c.dom.Document;
  import org.w3c.dom.Element;

  /**
   * The QSWSDLHandler class is a handler which provides an AXIS service's
WSDL
   * document when the query string "wsdl" is encountered in an AXIS
servlet
   * invocation.
   *
   * @author Curtiss Howard (code mostly from AxisServlet class)
   * @author Doug Davis (dug@us.ibm.com)
   * @author Steve Loughran
   */

  public class QSWSDLHandler implements QSHandler {
       private boolean development;
       private Log log;
       private Log exceptionLog;

       /**
        * probe for the system being 'production'
        * @return true for a dev system.
        */

       private boolean isDevelopment () {
            return this.development;
       }

       /**
        * Performs the action associated with this particular query string
        * handler.
        *
        * @param msgContext a MessageContext object containing message
context
        *        information for this query string handler.
        * @throws AxisFault if an error occurs.
        */

       public void invoke (MessageContext msgContext) throws AxisFault {
            // Obtain objects relevant to the task at hand from the
provided
            // MessageContext's bag.

            AxisServer engine = (AxisServer) msgContext.getProperty
                 (HTTPConstants.PLUGIN_ENGINE);
            PrintWriter writer = (PrintWriter) msgContext.getProperty
                 (HTTPConstants.PLUGIN_WRITER);
            HttpServletRequest request = (HttpServletRequest)
                 msgContext.getProperty
(HTTPConstants.MC_HTTP_SERVLETREQUEST);
            HttpServletResponse response = (HttpServletResponse)
                 msgContext.getProperty
(HTTPConstants.MC_HTTP_SERVLETRESPONSE);
            this.development = ((Boolean) msgContext.getProperty
                 (HTTPConstants.PLUGIN_IS_DEVELOPMENT)).booleanValue();
            this.log = (Log) msgContext.getProperty
(HTTPConstants.PLUGIN_LOG);
            this.exceptionLog = (Log) msgContext.getProperty
                 (HTTPConstants.PLUGIN_EXCEPTION_LOG);

            try {
                 engine.generateWSDL (msgContext);

                 Document doc = (Document) msgContext.getProperty ("WSDL");

                 if (doc != null) {
                      response.setContentType ("text/xml");
                      XMLUtils.DocumentToWriter (doc, writer);
                 }

                 else {
                      if (log.isDebugEnabled()) {
                           log.debug ("processWsdlRequest: failed to create
WSDL");
                      }

                      reportNoWSDL (response, writer, "noWSDL02", null);
                 }
            }

            catch (AxisFault axisFault) {
                 //the no-service fault is mapped to a no-wsdl error

                 if (axisFault.getFaultCode().equals
                      (Constants.QNAME_NO_SERVICE_FAULT_CODE)) {
                      //which we log

                      processAxisFault (axisFault);

                      //then report under a 404 error

                      response.setStatus
(HttpURLConnection.HTTP_NOT_FOUND);

                      reportNoWSDL (response, writer, "noWSDL01",
axisFault);
                 }

                 else {
                      //all other faults get thrown

                      throw axisFault;
                 }
            }
       }

       /**
        * report that we have no WSDL
        * @param res
        * @param writer
        * @param moreDetailCode optional name of a message to provide more
detail
        * @param axisFault optional fault string, for extra info at debug
time only
        */

       private void reportNoWSDL (HttpServletResponse res, PrintWriter
writer,
            String moreDetailCode, AxisFault axisFault) {
            res.setStatus (HttpURLConnection.HTTP_NOT_FOUND);
            res.setContentType ("text/html");

            writer.println ("<h2>" + Messages.getMessage ("error00") +
"</h2>");
            writer.println ("<p>" + Messages.getMessage ("noWSDL00") +
"</p>");

            if (moreDetailCode != null) {
                 writer.println("<p>" + Messages.getMessage
(moreDetailCode)
                      + "</p>");
            }

            if (axisFault != null && isDevelopment()) {
                 //dev systems only give fault dumps

                 writeFault (writer, axisFault);
            }
       }

       /**
        * this method writes a fault out to an HTML stream. This includes
        * escaping the strings to defend against cross-site scripting
attacks
        * @param writer
        * @param axisFault
        */

       private void writeFault (PrintWriter writer, AxisFault axisFault) {
            String localizedMessage = XMLUtils.xmlEncodeString
                 (axisFault.getLocalizedMessage());

            writer.println ("<pre>Fault - " + localizedMessage + "<br>");
            writer.println (axisFault.dumpToString());
            writer.println ("</pre>");
       }

       /**
        * routine called whenever an axis fault is caught; where they
        * are logged and any other business. The method may modify the
fault
        * in the process
        * @param fault what went wrong.
        */

       private void processAxisFault (AxisFault fault) {
            //log the fault

            Element runtimeException = fault.lookupFaultDetail
                 (Constants.QNAME_FAULTDETAIL_RUNTIMEEXCEPTION);

            if (runtimeException != null) {
                 exceptionLog.info (Messages.getMessage ("axisFault00"),
fault);

                 //strip runtime details

                 fault.removeFaultDetail
                      (Constants.QNAME_FAULTDETAIL_RUNTIMEEXCEPTION);
            }

            else if (exceptionLog.isDebugEnabled()) {
                 exceptionLog.debug (Messages.getMessage ("axisFault00"),
fault);
            }

            //dev systems only give fault dumps

            if (!isDevelopment()) {
                 //strip out the stack trace

                 fault.removeFaultDetail
(Constants.QNAME_FAULTDETAIL_STACKTRACE);
            }
       }
  }







Mime
View raw message