Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
  * JBoss, Home of Professional Open Source
  * Copyright 2005, JBoss Inc., and individual contributors as indicated
  * by the @authors tag. See the copyright.txt in the distribution for a
  * full listing of individual contributors.
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
 
 package org.jboss.remoting.transport.servlet;
 
 import  org.jboss.logging.Logger;
 
 import  javax.servlet.ServletException;
 import  javax.servlet.ServletInputStream;
 import  javax.servlet.ServletOutputStream;
 import  javax.servlet.http.HttpServletRequest;
 import  javax.servlet.http.HttpServletResponse;
 import java.util.Map;
 import java.util.Set;
The servlet based server invoker that receives the original http request from the ServerInvokerServlet.

Author(s):
Tom Elrod
 
 public class ServletServerInvoker extends WebServerInvoker implements ServletServerInvokerMBean
 {
    public static final String UNWRAP_SINGLETON_ARRAYS = "unwrapSingletonArrays";
    public static final String CREATE_UNIQUE_OBJECT_NAME = "createUniqueObjectName";
    
    private static final Logger log = Logger.getLogger(ServletServerInvoker.class);
    
    private boolean unwrapSingletonArrays;
    private boolean createUniqueObjectName;
    private boolean useRemotingContentType;
 
    public ServletServerInvoker(InvokerLocator locator)
    {
       super(locator);
       init();
    }
 
    public ServletServerInvoker(InvokerLocator locatorMap configuration)
    {
       super(locatorconfiguration);
       init();
    }
 
    protected String getDefaultDataType()
    {
       return .;
    }
    
    protected void init()
    {
       if (val != null)
       {
          try
          {
              = Boolean.valueOf((String)val).booleanValue();
             .debug(this + " setting unwrapSingletonArrays to " + );
          }
          catch (Exception e)
         {
            .warn(this + " could not convert " + 
                      + " value of " +
                     val + " to a boolean value.");
         }
      }
      
      if (val != null)
      {
         try
         {
             = Boolean.valueOf((String)val).booleanValue();
            .debug(this + " setting createUniqueObjectName to " + );
         }
         catch (Exception e)
         {
            .warn(this + " could not convert " + 
                      + " value of " +
                     val + " to a boolean value.");
         }
      }
      if (val instanceof String)
      {
          = Boolean.valueOf((Stringval).booleanValue();
      }
      else if (val != null)
      {
         .warn(. + " value should be a String: " + val);
      }
      .debug(this + " useRemotingContentType: " + );
   }
   
   public String getMBeanObjectName()
   {
      if ()
      {
         .trace("returning (from super) " + super.getMBeanObjectName());
         return super.getMBeanObjectName();
      }
      .trace("returning (from here) jboss.remoting:service=invoker,transport=servlet");
      return "jboss.remoting:service=invoker,transport=servlet";
   }
   public void processRequest(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException
   {
      Map metadata = new HashMap();
      Enumeration enumer = request.getHeaderNames();
      while(enumer.hasMoreElements())
      {
         Object obj = enumer.nextElement();
         String headerKey = (Stringobj;
         String headerValue = request.getHeader(headerKey);
         metadata.put(headerKeyheaderValue);
      }
      Map urlParams = request.getParameterMap();
      if ()
      {
         Iterator it = urlParams.keySet().iterator();
         while (it.hasNext())
         {
            Object key = it.next();
            Object value = urlParams.get(key);
            String[] valueArray = (String[]) value;
            if (valueArray.length == 1)
            {
               value = valueArray[0];
            }
            metadata.put(keyvalue);
         }
      }
      else
      {
         metadata.putAll(urlParams);
      }
      
      if(.isTraceEnabled())
      {
         .trace("metadata:");
         Iterator it = metadata.keySet().iterator();
         while (it.hasNext())
         {
            Object key = it.next();
            .trace("  " + key + ": " + metadata.get(key));
         }
      }
      
      // UnMarshaller may not be an HTTPUnMarshaller, in which case it
      // can ignore this parameter.
      if (o != null)
      {
         if (o instanceof String[])
         {
            metadata.put(., ((String[]) o)[0]);
         }
         else
         {
            metadata.put(.o);
         }
      }
      String requestContentType = request.getContentType();
      try
      {
         Object invocationResponse = null;
         ServletInputStream inputStream = request.getInputStream();
         UnMarshaller unmarshaller = MarshalFactory.getUnMarshaller(.getSerializationType());
         Object obj = null;
         if (unmarshaller instanceof VersionedUnMarshaller)
            obj = ((VersionedUnMarshaller)unmarshaller).read(inputStreammetadata, Version.getDefaultVersion());
         else
            obj = unmarshaller.read(inputStreammetadata);
         inputStream.close();
         InvocationRequest invocationRequest = null;
         if(obj instanceof InvocationRequest)
         {
            invocationRequest = (InvocationRequestobj;
         }
         else
         {
            if(WebUtil.isBinary(requestContentType))
            {
               invocationRequest = getInvocationRequest(metadataobj);
            }
            else
            {
               invocationRequest = createNewInvocationRequest(metadataobj);
            }
         }
         try
         {
            // call transport on the subclass, get the result to handback
            invocationResponse = invoke(invocationRequest);
         }
         catch(Throwable ex)
         {
            .debug("Error thrown calling invoke on server invoker."ex);
            invocationResponse = null;
            response.sendError(500, "Error processing invocation request.  " + ex.getMessage());
         }
         if(invocationResponse != null)
         {
            if (isInvalidContentType(requestContentType))
            {
               .warn("Ignoring invalid content-type from client: " + requestContentType);
            }
            else
            {
               response.setContentType(requestContentType);
            }
            int iContentLength = getContentLength(invocationResponse);
            response.setContentLength(iContentLength);
            ServletOutputStream outputStream = response.getOutputStream();
            Marshaller marshaller = MarshalFactory.getMarshaller(.getSerializationType());
            if (marshaller instanceof VersionedMarshaller)
               ((VersionedMarshallermarshaller).write(invocationResponseoutputStream, Version.getDefaultVersion());
            else
               marshaller.write(invocationResponseoutputStream);
            outputStream.close();
         }
      }
      catch(ClassNotFoundException e)
      {
         .error("Error processing invocation request due to class not being found."e);
         response.sendError(500, "Error processing invocation request due to class not being found.  " + e.getMessage());
      }
   }
   public byte[] processRequest(HttpServletRequest requestbyte[] requestByte,
                                HttpServletResponse response)
         throws ServletException, IOException
   {
      byte[] retval = new byte[0];
      
      // Check if client is HTTPClientInvoker
      boolean isRemotingUserAgent = false;
      String userAgent = request.getHeader(.);
      if (userAgent != null)
      {
         isRemotingUserAgent = userAgent.startsWith("JBossRemoting");
      }
      Map metadata = new HashMap();
      Enumeration enumer = request.getHeaderNames();
      while(enumer.hasMoreElements())
      {
         Object obj = enumer.nextElement();
         String headerKey = (Stringobj;
         String headerValue = request.getHeader(headerKey);
         metadata.put(headerKeyheaderValue);
      }
      Map urlParams = request.getParameterMap();
      if ()
      {
         Iterator it = urlParams.keySet().iterator();
         while (it.hasNext())
         {
            Object key = it.next();
            Object value = urlParams.get(key);
            String[] valueArray = (String[]) value;
            if (valueArray.length == 1)
            {
               value = valueArray[0];
            }
            metadata.put(keyvalue);
         }
      }
      else
      {
         metadata.putAll(urlParams);
      }
      metadata.put(.request.getMethod());
      
      // UnMarshaller may not be an HTTPUnMarshaller, in which case it
      // can ignore this parameter.
      if (o != null)
      {
         if (o instanceof String[])
         {
            metadata.put(., ((String[]) o)[0]);
         }
         else
         {
            metadata.put(.o);
         }
      }
      
      String path = request.getPathTranslated();
      if (path != null)
         metadata.put(.path);
      String remotingContentType = (Stringmetadata.get(.);
      if (remotingContentType == null)
      {
         remotingContentType = (Stringmetadata.get(.);
      }
      
      String requestContentType = request.getContentType();
      try
      {
         InvocationRequest invocationRequest = null;
         Object responseObject = null;
         boolean isError = false;
         String method = request.getMethod();
         if (method.equals("GET") || method.equals("HEAD") || (method.equals("OPTIONS") && request.getContentLength() <= 0))
         {
            invocationRequest = createNewInvocationRequest(metadatanull);
         }
         else
         {
            ServletInputStream inputStream = request.getInputStream();
            UnMarshaller unmarshaller = getUnMarshaller();
            Object obj = null;
            if (unmarshaller instanceof VersionedUnMarshaller)
               obj = ((VersionedUnMarshaller)unmarshaller).read(new ByteArrayInputStream(requestByte), metadata, Version.getDefaultVersion());
            else
               obj = unmarshaller.read(new ByteArrayInputStream(requestByte), metadata);
            inputStream.close();
            if(obj instanceof InvocationRequest)
            {
               invocationRequest = (InvocationRequestobj;
               Map requestMap = invocationRequest.getRequestPayload();
               if (requestMap == null)
               {
                  invocationRequest.setRequestPayload(metadata);
               }
               else
               {
                  requestMap.putAll(metadata);
               }
            }
            else
            {
               if(( && ..equalsIgnoreCase(remotingContentType))
                  || (! && WebUtil.isBinary(requestContentType)))
               {
                  invocationRequest = getInvocationRequest(metadataobj);
               }
               else
               {
                  invocationRequest = createNewInvocationRequest(metadataobj);
               }
            }
         }
         try
         {
            // call transport on the subclass, get the result to handback
            responseObject = invoke(invocationRequest);
         }
         catch(Throwable ex)
         {
            .debug("Error thrown calling invoke on server invoker."ex);
            responseObject = ex;
            
            if (checkForExceptionReturn(metadata))
            {
               String sessionId = invocationRequest.getSessionId();
               ServletThrowable st = new ServletThrowable(ex);
               responseObject = new InvocationResponse(sessionIdsttruenull);
            }
            else
            {
               isError = true;
            }
         }
         //Start with response code of 204 (no content), then if is a return from handler, change to 200 (ok)
         int status = 200;
         if(responseObject != null)
         {
            if(isError)
            {
               status = 500;
            }
         }
         else
         {
            if (!isRemotingUserAgent || "HEAD".equals(request.getMethod()))
            {
               status = 204;
            }
         }
         // extract response code/message if exists
         Map responseMap = invocationRequest.getReturnPayload();
         if(responseMap != null)
         {
            Integer handlerStatus = (IntegerresponseMap.remove(.);
            if(handlerStatus != null)
            {
               status = handlerStatus.intValue();
            }
            // add any response map headers
            Set entries = responseMap.entrySet();
            Iterator itr = entries.iterator();
            while(itr.hasNext())
            {
               Map.Entry entry = (Map.Entry)itr.next();
               response.addHeader(entry.getKey().toString(), entry.getValue().toString());
            }
         }
         // can't set message anymore as is deprecated
         response.setStatus(status);
         
         if (isRemotingUserAgent && !(invocationRequest instanceof CreatedInvocationRequest))
         {
            responseObject = new InvocationResponse(invocationRequest.getSessionId(),
                                                    responseObjectisErrorresponseMap);
         }
         if(responseObject != null)
         {
            String responseContentType = null;
            if (responseMap != null)
            {
               responseContentType = (StringresponseMap.get("Content-Type");
            }
            
            if (responseContentType != null)
            {
               if (isInvalidContentType(responseContentType))
               {
                  .warn("Ignoring invalid content-type from ServerInvocationHandler: " + responseContentType);
                  responseContentType = WebUtil.getContentType(responseObject); 
               }
            }
            else
            {
               responseContentType = WebUtil.getContentType(responseObject); 
            }
            response.setContentType(responseContentType);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            Marshaller marshaller = getMarshaller();
            if (marshaller instanceof VersionedMarshaller)
               ((VersionedMarshallermarshaller).write(responseObjectoutputStream, Version.getDefaultVersion());
            else
               marshaller.write(responseObjectoutputStream);
            retval = outputStream.toByteArray();
            response.setContentLength(retval.length);
         }
         
         if (responseObject instanceof String)
         {
         }
         else
         {
            response.addHeader(..);        
         }
      }
      catch(ClassNotFoundException e)
      {
         .error("Error processing invocation request due to class not being found."e);
         response.sendError(500, "Error processing invocation request due to class not being found.  " + e.getMessage());
      }
      return retval;
   }
   
   static private boolean isInvalidContentType(String contentType)
   {
      return contentType.indexOf('\n') + contentType.indexOf('\r') > -2;
   }
   
   private boolean checkForExceptionReturn(Map headers)
   {
      boolean flag = false;
      if(headers != null)
      {
         Object val = headers.get(.);
         if (val != null)
         {
            if (val instanceof String)
            {
               flag = Boolean.valueOf((Stringval).booleanValue();
            }
            else if (val instanceof String[])
            {
               String param = ((String[]) val)[0];
               flag = Boolean.valueOf(param).booleanValue();
            }
         }
      }
      return flag;
   }
New to GrepCode? Check out our FAQ X