Invoke a MBean operation given the method name and its signature.
@param request The HTTP request
@param response The HTTP response
@exception ServletException Thrown if an error occurs
@exception IOException Thrown if an I/O error occurs
188773
private void invokeOpByName(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
   {
      String name = request.getParameter("name");

      if (trace)
         log.trace("invokeOpByName, name=" + name);

      String[] argTypes = request.getParameterValues("argType");
      String[] args = getArgs(request);
      String methodName = request.getParameter("methodName");

      if (methodName == null)
         throw new ServletException("No methodName given in invokeOpByName form");

      try
      {
         OpResultInfo opResult = invokeOpByName(name, methodName, argTypes, args);
         request.setAttribute("opResultInfo", opResult);

         RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/displayopresult.jsp");
         rd.forward(request, response);
      }
      catch (Exception e)
      {
         throw new ServletException("Failed to invoke operation", e);
      }
   }
1151102
public static HttpResponse execute(HttpRequestBase request) throws IOException {

		Assert.notNull(request, "Missing request!");
		HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new DefaultRedirectStrategy()).build();
		return client.execute(request);
	}
1161579
@Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    JsonGenerator jg = null;
    String jsonpcb = null;
    PrintWriter writer = null;
    try {

      writer = response.getWriter();

      // "callback" parameter implies JSONP output
      jsonpcb = request.getParameter(CALLBACK_PARAM);
      if (jsonpcb != null) {
        response.setContentType("application/javascript; charset=utf8");
        writer.write(jsonpcb + "(");
      } else {
        response.setContentType("application/json; charset=utf8");
      }

      jg = jsonFactory.createJsonGenerator(writer);
      jg.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
      jg.useDefaultPrettyPrinter();

      int statusCode = renderMBeans(jg, request.getParameterValues("qry"));
      response.setStatus(statusCode);

    } catch (IOException e) {
      writeException(jg, e);
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (MalformedObjectNameException e) {
      writeException(jg, e);
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } finally {
      if (jg != null) {
        jg.close();
      }
      if (jsonpcb != null) {
        writer.write(");");
      }
      if (writer != null) {
        writer.close();
      }
    }

  }
222081
public static void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    String handler = getHandler(request);
    if (handler.startsWith(CONTROLLER_PATH)) {
      if (!checkForTaskQueue(request, response)) {
        return;
      }
      new ShardedJobRunner<>().completeShard(
          checkNotNull(request.getParameter(JOB_ID_PARAM), "Null job id"),
          checkNotNull(request.getParameter(TASK_ID_PARAM), "Null task id"));
    } else if (handler.startsWith(WORKER_PATH)) {
      if (!checkForTaskQueue(request, response)) {
        return;
      }
      new ShardedJobRunner<>().runTask(
          checkNotNull(request.getParameter(JOB_ID_PARAM), "Null job id"),
          checkNotNull(request.getParameter(TASK_ID_PARAM), "Null task id"),
          Integer.parseInt(request.getParameter(SEQUENCE_NUMBER_PARAM)));
    } else if (handler.startsWith(COMMAND_PATH)) {
      if (!checkForAjax(request, response)) {
        return;
      }
      StatusHandler.handleCommand(handler.substring(COMMAND_PATH.length() + 1), request, response);
    } else {
      throw new RuntimeException(
          "Received an unknown MapReduce request handler. See logs for more detail.");
    }
  }
925464
@SuppressWarnings("unchecked")
    public static void after(Object request, Object response) {

        HttpData data = new HttpData();

        /*
         * Use reflection to access the HttpServletRequest/Response as using the
         * true method signature caused ClassLoader issues.
         */
        Class<?> reqClass = request.getClass();
        Class<?> respClass = response.getClass();
        try {
            /*
             * Retrieve the request tracker
             */
            Method getAttribute = reqClass.getMethod(GET_ATTRIBUTE, String.class);
            Method setAttribute = reqClass.getMethod(SET_ATTRIBUTE, String.class, Object.class);
            HttpRequestTracker tracker = (HttpRequestTracker) (getAttribute.invoke(request, TRACKER_ATTRIBUTE));
            if (tracker == null) {
                /*
                 * should never happen
                 */
                throw new JavametricsException("Unable to find request tracker");
            }

            /*
             * Decrement the nesting level and return if still nested
             */
            if (tracker.decrement()) {
                setAttribute.invoke(request, TRACKER_ATTRIBUTE, tracker);
                return;
            }

            /*
             * Clear the tracker
             */
            setAttribute.invoke(request, TRACKER_ATTRIBUTE, null);

            data.setRequestTime(tracker.getRequestTime());

            Method getRequestURL = reqClass.getMethod(GET_REQUEST_URL);
            data.setUrl(((StringBuffer) getRequestURL.invoke(request)).toString());

            Method getMethod = reqClass.getMethod(GET_METHOD);
            data.setMethod((String) getMethod.invoke(request));

            Method getStatus = respClass.getMethod(GET_STATUS);
            data.setStatus((Integer) getStatus.invoke(response));

            if (detailed) {
                Method getContentType = respClass.getMethod(GET_CONTENT_TYPE);
                data.setContentType((String) getContentType.invoke(response));

                Method getHeaders = respClass.getMethod(GET_HEADER_NAMES);
                Method getHeader = respClass.getMethod(GET_HEADER, String.class);
                Collection<String> headers = (Collection<String>) getHeaders.invoke(response);
                if (headers != null) {
                    for (String headerName : headers) {
                        String header = (String) getHeader.invoke(response, headerName);
                        if (header != null) {
                            data.addHeader(headerName, header);
                        }
                    }
                }

                Method getReqHeaders = reqClass.getMethod(GET_HEADER_NAMES);
                Method getReqHeader = reqClass.getMethod(GET_HEADER, String.class);
                Enumeration<String> reqHeaders = (Enumeration<String>) getReqHeaders.invoke(request);
                if (reqHeaders != null) {
                    while (reqHeaders.hasMoreElements()) {
                        String headerName = reqHeaders.nextElement();
                        String header = (String) getReqHeader.invoke(request, headerName);
                        if (header != null) {
                            data.addRequestHeader(headerName, header);
                        }
                    }
                }
            }
            
            data.setDuration(System.currentTimeMillis() - tracker.getRequestTime());

            if (Agent.debug) {
                System.err.println("Javametrics: Sending {\"http\":" + data.toJsonString() + "}");
            }

            /*
             * Send the http request data to the Javametrics agent
             */
            Javametrics.getInstance().sendJSON(HTTP_TOPIC, data.toJsonString());

        } catch (Exception e) {
            // Log any exception caused by our injected code
            System.err.println("Javametrics: Servlet callback exception: " + e.toString());
            e.printStackTrace();
        }

    }
885719
public void doPost(HttpServletRequest request,
                        HttpServletResponse response) 
        throws ServletException, IOException
    {
        String target=null;
        response.sendRedirect(request.getContextPath()+
                              request.getServletPath()+"/"+
                              Long.toString(System.currentTimeMillis(),36)+
                              (target!=null?("#"+target):""));
    }
1006768
public void doGeneric(String method, HttpServletRequest request, HttpServletResponse response) {
    try {
      ServletUtils.startTransaction(request.getHeader("User-Agent"));

      // Note that getServletPath does an un-escape so that the %24 of job id's are turned into $ characters.
      String uri = request.getServletPath();

      Properties headers = new Properties();
      Enumeration<String> en = request.getHeaderNames();
      while (en.hasMoreElements()) {
        String key = en.nextElement();
        String value = request.getHeader(key);
        headers.put(key, value);
      }

      final String contentType = request.getContentType();
      Properties parms = new Properties();
      String postBody = null;
      if (System.getProperty(H2O.OptArgs.SYSTEM_PROP_PREFIX + "debug.cors") != null) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
      }

      if (contentType != null && contentType.startsWith(MIME_JSON)) {
        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
          BufferedReader reader = request.getReader();
          while ((line = reader.readLine()) != null)
            jb.append(line);
        } catch (Exception e) {
          throw new H2OIllegalArgumentException("Exception reading POST body JSON for URL: " + uri);
        }
        postBody = jb.toString();
      } else {
        // application/x-www-form-urlencoded
        Map<String, String[]> parameterMap;
        parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
          String key = entry.getKey();
          String[] values = entry.getValue();

          if (values.length == 1) {
            parms.put(key, values[0]);
          } else if (values.length > 1) {
            StringBuilder sb = new StringBuilder();
            sb.append("[");
            boolean first = true;
            for (String value : values) {
              if (!first) sb.append(",");
              sb.append("\"").append(value).append("\"");
              first = false;
            }
            sb.append("]");
            parms.put(key, sb.toString());
          }
        }
      }

      // Make serve() call.
      NanoResponse resp = serve(uri, method, headers, parms, postBody);

      // Un-marshal Nano response back to Jetty.
      String choppedNanoStatus = resp.status.substring(0, 3);
      assert (choppedNanoStatus.length() == 3);
      int sc = Integer.parseInt(choppedNanoStatus);
      ServletUtils.setResponseStatus(response, sc);

      response.setContentType(resp.mimeType);

      Properties header = resp.header;
      Enumeration<Object> en2 = header.keys();
      while (en2.hasMoreElements()) {
        String key = (String) en2.nextElement();
        String value = header.getProperty(key);
        response.setHeader(key, value);
      }

      resp.writeTo(response.getOutputStream());

    } catch (IOException e) {
      e.printStackTrace();
      ServletUtils.setResponseStatus(response, 500);
      Log.err(e);
      // Trying to send an error message or stack trace will produce another IOException...
    } finally {
      ServletUtils.logRequest(method, request, response);
      // Handle shutdown if it was requested.
      if (H2O.getShutdownRequested()) {
        (new Thread() {
          public void run() {
            boolean [] confirmations = new boolean[H2O.CLOUD.size()];
            if (H2O.SELF.index() >= 0) {
              confirmations[H2O.SELF.index()] = true;
            }
            for(H2ONode n:H2O.CLOUD._memary) {
              if(n != H2O.SELF)
                new RPC<>(n, new UDPRebooted.ShutdownTsk(H2O.SELF,n.index(), 1000, confirmations, 0)).call();
            }
            try { Thread.sleep(2000); }
            catch (Exception ignore) {}
            int failedToShutdown = 0;
            // shutdown failed
            for(boolean b:confirmations)
              if(!b) failedToShutdown++;
            Log.info("Orderly shutdown: " + (failedToShutdown > 0? failedToShutdown + " nodes failed to shut down! ":"") + " Shutting down now.");
            H2O.closeAll();
            H2O.exit(failedToShutdown);
          }
        }).start();
      }
      ServletUtils.endTransaction();
    }
  }
359787
private String doAction(HttpServletRequest request)
        throws IOException
    {
        String action=request.getParameter("A");
        if ("exit all servers".equalsIgnoreCase(action))
        {
            new Thread(new Runnable()
                {
                    public void run()
                    {
                        try{Thread.sleep(1000);}
                        catch(Exception e){LogSupport.ignore(log,e);}
                        log.info("Stopping All servers");
                        Iterator s=_servers.iterator();
                        while(s.hasNext())
                        {
                            HttpServer server=(HttpServer)s.next();
                            try{server.stop();}
                            catch(Exception e){LogSupport.ignore(log,e);}
                        }
                        log.info("Exiting JVM");
                        System.exit(1);
                    }
                }).start();
            
            throw new HttpException(HttpResponse.__503_Service_Unavailable);
        }
        
        boolean start="start".equalsIgnoreCase(action);
        String id=request.getParameter("ID");

        StringTokenizer tok=new StringTokenizer(id,":");
        int tokens=tok.countTokens();
        String target=null;
        
        try{
            target=tok.nextToken();
            int t=Integer.parseInt(target);
            Iterator s=_servers.iterator();
            HttpServer server=null;
            while(s.hasNext() && t>=0)
                if (t--==0)
                    server=(HttpServer)s.next();
                else
                    s.next();
            
            if (tokens==1)
            {
                // Server stop/start
                if (start) server.start();
                else server.stop();
            }
            else if (tokens==3)
            {
                // Listener stop/start
                String l=tok.nextToken()+":"+tok.nextToken();

                HttpListener[] listeners=server.getListeners();
                for (int i2=0;i2<listeners.length;i2++)
                {
                    HttpListener listener = listeners[i2];
                    if (listener.toString().indexOf(l)>=0)
                    {
                        if (start) listener.start();
                        else listener.stop();
                    }
                }
            }
            else
            {
                String host=tok.nextToken();
                if ("null".equals(host))
                    host=null;
                
                String contextPath=tok.nextToken();
                target+=":"+host+":"+contextPath;
                if (contextPath.length()>1)
                    contextPath+="/*";
                int contextIndex=Integer.parseInt(tok.nextToken());
                target+=":"+contextIndex;
                HttpContext
                    context=server.getContext(host,contextPath,contextIndex);
                
                if (tokens==4)
                {
                    // Context stop/start
                    if (start) context.start();
                    else context.stop();
                }
                else if (tokens==5)
                {
                    // Handler stop/start
                    int handlerIndex=Integer.parseInt(tok.nextToken());
                    HttpHandler handler=context.getHandlers()[handlerIndex];
                    
                    if (start) handler.start();
                    else handler.stop();
                }
            }
        }
        catch(Exception e)
        {
            log.warn(LogSupport.EXCEPTION,e);
        }
        catch(Error e)
        {
            log.warn(LogSupport.EXCEPTION,e);
        }
        
        return target;
    }
24795
public void handleRequest(ServletRequest request, ServletResponse response) throws Exception {
        Object token = null;
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpServletRequest httpRequest = null; //PM88028
        StringBuffer path =null;
        WebAppDispatcherContext dispatchContext =null;
        String pathInfo = null; // PK64302
        FileNotFoundException fnf = null;
        
    	
//		if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
//         	logger.entering(CLASS_NAME,"handleRequest : request--->" + req.getRequestURI()+ "<---");
//		}
		
        try {
        	//IExtendedRequest wasreq = (IExtendedRequest) ServletUtil.unwrapRequest(request);
                //PM88028 Start
                IExtendedRequest wasreq = null;
                
                if(useOriginalRequestState){

                    WebContainerRequestState reqStateSaveRequest = WebContainerRequestState.getInstance(false);
                    if(reqStateSaveRequest != null){                        
                        httpRequest = (HttpServletRequest)reqStateSaveRequest.getAttribute("unFilteredRequestObject");
                        if(httpRequest != null) {
                            wasreq = (IExtendedRequest) ServletUtil.unwrapRequest(httpRequest);  
                            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                                logger.entering(CLASS_NAME,"handleRequest : useOriginalRequestState request--->" + httpRequest.getRequestURI()+ "<---");
                            }
                        }
                    } 
                }
                //if it is null then get it from the req
                if(httpRequest == null)
                {
                    httpRequest = (HttpServletRequest) request;
                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                        logger.entering(CLASS_NAME,"handleRequest : request--->" + httpRequest.getRequestURI()+ "<---");
                    }
                    wasreq = (IExtendedRequest) ServletUtil.unwrapRequest(request);
                }
            
		dispatchContext = (WebAppDispatcherContext)wasreq.getWebAppDispatcherContext();
			
        
            //LIBERTY: Talk to Namespace
                //webAppNameSpaceCollab.preInvoke(cmd);
			
            //remove since the preInvoke is done in WebAppFilterManager
			//The preInvoke in WebAppFilterManager calls with doAuth/enforceSecurity=true which will setup
			//the metadata for sync to thread just as well as a call with doAuth=false would.
			//securityPreInvokes.push(secCollab.preInvoke(req, resp, null, false));
        
            token = ThreadIdentityManager.runAsServer();
        
            boolean isInclude = false; // is this an include request?
            ServletContext context = _webapp;
            String fileSystemPath = null; // actual OS dependent path
            path = new StringBuffer(); // constructed path

            String servletPath = null; // PK64302
          //PM88028 change req to httpReques
            if (httpRequest.getAttribute(WebAppRequestDispatcher.REQUEST_URI_INCLUDE_ATTR) != null) {
                isInclude = true;
                servletPath = (String) httpRequest.getAttribute(WebAppRequestDispatcher.SERVLET_PATH_INCLUDE_ATTR);
                pathInfo = (String) httpRequest.getAttribute(WebAppRequestDispatcher.PATH_INFO_INCLUDE_ATTR);
            }// PM79476 (PM71901) Start
            else if(dispatchContext!= null && !handlingRequestWithOverridenPath){ //always here
                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                        logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "relative uri -->["+ dispatchContext.getRelativeUri()+"]");
                }
                servletPath = dispatchContext.getServletPath();
                if(servletPath!= null) {servletPath = WebGroup.stripURL(servletPath,false);}                    
                
                pathInfo = dispatchContext.getPathInfo();
                if(pathInfo!= null) {pathInfo = WebGroup.stripURL(pathInfo,false);}
                if(pathInfo == ""){pathInfo = null;}
                
            }// PM71901 End
            else { // never be here 
                // not get these from request as these can be overridden
                servletPath = httpRequest.getServletPath();
                pathInfo = httpRequest.getPathInfo();
            }

            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
            	logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "servletPath [" + servletPath +"] pathInfo [" + pathInfo +"]");
            }
            
            path.append(servletPath);

            if (pathInfo != null) {
            	int semicolon = pathInfo.indexOf(';');
                if (semicolon != -1)
                    pathInfo = pathInfo.substring(0, semicolon);
               
                path.append(pathInfo);
            }

            //PK36447

            String temporaryPath = WSUtil.resolveURI(path.toString());
            String upperMatchString = temporaryPath.toUpperCase();
            boolean forbidden = false;
            if (!exposeWebInfOnDispatch && (upperMatchString.startsWith("/WEB-INF/") || upperMatchString.equals("/WEB-INF")))
                forbidden = true;

            //We check META-INF by default in the JSP codepath
            else if (upperMatchString.startsWith("/META-INF/") || upperMatchString.equals("/META-INF"))
                forbidden = true;
            
            // PK24615 change conditionals from "indexOf() != -1" to "startsWith()"
            if (forbidden) {
                int statusCode;
                //We don't want to give out more information than required.  On tWAS, this code lived in the wrapper
                //and so returning a 403 would have meant that the file was, in fact, found.  Adding this check to maintain
                //the same behavior
                //If the path was encoded and illegal, then just return a 404.
                if (temporaryPath.equals(path.toString())) {
                    statusCode = HttpServletResponse.SC_FORBIDDEN;
                } else {
                    statusCode = HttpServletResponse.SC_NOT_FOUND;
                }
                resp.sendError(
                    statusCode,
                    MessageFormat.format(nls.getString("File.not.found", "File not found: {0}"), new Object[] { path.toString()}));
                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                    logger.exiting(CLASS_NAME,"handleRequest","Forbidden-WEB-INF/META-INF");
                return;
            }
            
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                logger.logp(Level.FINE, CLASS_NAME,"handleRequest"," after resolving the uri: path ---> " + path);

            
            //Liberty ArchiveAPI container to be used instead of File system.
            Container webModuleContainer = _webapp.getModuleContainer();

            /*
             * In Liberty, we'll leave the file system path as just the request path so we can keep 
             * the checks for illegal characters in the same code
             */
            fileSystemPath = path.toString();

            // PQ79698 part1 starts
            if (!isValidFilePath(fileSystemPath)) {
                resp.sendError(HttpServletResponse.SC_FORBIDDEN, nls.getString("File.name.contains.illegal.character", "File path contains illegal character."));
                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                	logger.exiting(CLASS_NAME,"handleRequest","Forbidden-invalid file path");
                return;
            }
            // PQ79698 part1 ends
			// defect 220552: begin implement the deny feature for specified URI patterns
			else{
				Object matchedURI = denyPatterns.match(path.toString());
				if(matchedURI != null){	
					if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
						logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "Attempted to serve URI that matches denied URL pattern URI =[" + path.toString() + "] matched [" + matchedURI + "]");
					}
					resp.sendError(HttpServletResponse.SC_FORBIDDEN,							
							MessageFormat.format(nls.getString(
							"File.not.found", "File not found: {0}"),
							new Object[] { path.toString() }));
                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                    	logger.exiting(CLASS_NAME,"handleRequest","Forbidden-denied pattern");
						return;
				}
			}
			// defect 220552: end implement the deny feature for specified URI patterns

            boolean fileIsDirectoryInDocumentRoot = false;         // PM17845

            File file = null;
            Entry entry = null;
            boolean requestForRoot = false;
           
            //Don't call getEntry for the root container's / as there is no entry.
            if(fileSystemPath.equals("/")){      
                requestForRoot = true;
            } 
            else {
                entry = webModuleContainer.getEntry(fileSystemPath);
            }
            
            //We failed to find something at the path, either in the filesystem or via the container.
            if ((file != null && !file.exists()) || (webModuleContainer != null && entry == null && !requestForRoot)) {
            	
            	if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
    				logger.logp(Level.FINE, CLASS_NAME,"handleRequest","file does not exist --> " + path);
            	DocumentRootUtils docRoot = new DocumentRootUtils(context,extendedDocumentRoot,preFragmentExtendedDocumentRoot);
            	try {
            	    docRoot.handleDocumentRoots(path.toString());
            	} catch (FileNotFoundException fnfe) {
    				throw new FileNotFoundException(MessageFormat.format(nls.getString("File.not.found","File not found: {0}"), new Object[]{path}));
            	}
            	if (docRoot.isDirectory()) {
                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                    	logger.exiting(CLASS_NAME,"handleRequest","matchedfile is a directory");
    		    	if (!docRoot.isMatchedFromEDR() || WCCustomProperties.ALLOW_PARTIAL_URL_TO_EDR ) {
    		    		fileIsDirectoryInDocumentRoot = true;
    		    	} 
            	} else {
            		
                    if (isRequestForbidden(path))   
    	            {
                        resp.sendError(HttpServletResponse.SC_FORBIDDEN, MessageFormat.format(nls.getString("File.not.found","File not found: {0}"), new Object[]{httpRequest.getPathInfo()})); //PM88028
                        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                        	logger.exiting(CLASS_NAME,"handleRequest","Forbidden-Extended doc root endsWith");
    		            return;
    	            }
            	
            	    ZipFileResource zipFileResource = docRoot.getMatchedZipFileResource();
            	    if (zipFileResource!=null)
            	    {            		
            		    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
            		     logger.logp(Level.FINE, CLASS_NAME,"handleRequest","zip file found: Use ZipFileServletWrapper");
            			
           		         handleZipFileWrapper(req, httpRequest, resp, path, dispatchContext,zipFileResource);
           		         return;
            	     } else {
            	        EntryResource entryResource = docRoot.getMatchedEntryResource();
            	        if(entryResource != null){
            	            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
            	                logger.logp(Level.FINE, CLASS_NAME,"handleRequest","entry is found: Use EntryServletWrapper");
            	            EntryServletWrapper ewrapper = new EntryServletWrapper(_webapp, this, entryResource.getEntry());
            	            ewrapper.handleRequest(req, resp);
            	            
            	            if(!_webapp.isCachingEnabled()){

            	                //PM84305
            	                if(!_webapp.getConfiguration().isDisableStaticMappingCache()){
            	                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
            	                        logger.logp(Level.FINE, CLASS_NAME,"handleRequest","ewrapper addMappingTarget URI -> "+ path);

            	                    _webapp.addMappingTarget(path.toString(), ewrapper);
            	                }
            	                
            	                if (!dispatchContext.isInclude() && !dispatchContext.isForward()) {
            	                    WebContainer.addToCache(httpRequest, ewrapper, this._webapp); //PM88028
            	                }
            	            }
            	            
            	            return;
            	        }  
            	    
            	    
            		           		
            	        File matchedFile = docRoot.getMatchedFile();

            	        if (matchedFile !=null) {


            	            FileServletWrapper fwrapper = getStaticFileWrapper(_webapp, this, matchedFile);
            	            fwrapper.handleRequest(req, resp);
            	            if (!_webapp.isCachingEnabled()){
            	                try
            	                {
            	                    //PM84305
            	                    if(!_webapp.getConfiguration().isDisableStaticMappingCache()){
            	                        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
            	                            logger.logp(Level.FINE, CLASS_NAME,"handleRequest","fwrapper addMappingTarget URI -> "+ path);

            	                        _webapp.addMappingTarget(path.toString(), fwrapper);
            	                    }

            	                    // begin 309663
            	                    // add to cache now versus wait until Webcontainer.handleRequest finds a IServletWrapper 
            	                    // (allows request.getPathInfo and request.servletPath() to stay valid)
            	                    if (!dispatchContext.isInclude() && !dispatchContext.isForward()) {
            	                        WebContainer.addToCache(httpRequest, fwrapper, this._webapp); //PM88028
            	                    }
            	                    // end 309663
            	                }
            	                catch (Exception e)
            	                {
            	                    // do nothing because its a race condition...won't happen again.
            	                }
            	            } 
            	            return;
            	        }
            	     }
            	}

               // PM17845 Add if statement
                if (!fileIsDirectoryInDocumentRoot) {
                    // Resource was not found...invoke filters                
    				throw new FileNotFoundException(MessageFormat.format(nls.getString("File.not.found","File not found: {0}"), new Object[]{path}));
                }   
            }    
            
            boolean isContainerDirectory = false;
            Container directory = null;
            // Determine if the entry is a directory
            if(webModuleContainer != null){
                if(requestForRoot){
                    directory = webModuleContainer;
                } else if (entry != null){
                    directory = entry.adapt(Container.class);
                }
                isContainerDirectory = requestForRoot || fileIsDirectoryInDocumentRoot || (entry.getSize()==0 && directory != null && directory.isRoot()==false);
            }
            
            // PM17845 Add check for ileIsDirectoryInExtendedDocumnetRoot
            if ((file != null && file.isDirectory()) || fileIsDirectoryInDocumentRoot || isContainerDirectory) 
            {
                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {
                    if (file != null) {
                        logger.logp(Level.FINE, CLASS_NAME, "handleRequest", "file is a directory --> " + file.getPath());
                    } else if (entry!=null) {
                        logger.logp(Level.FINE, CLASS_NAME, "handleRequest", "entry path --> " + entry.getPath());
                    } else {
                        logger.logp(Level.FINE, CLASS_NAME, "handleRequest", "file is null");
                    }
                }
                
                /*
                 * The file is a directory so first see if we should append a trailing slash to the
                 * uri and redirect.  After that try and serve a welcome file or directory browse.
                 */
                String requestString = getURLWithRequestURIEncoded(httpRequest).toString(); //PM88028
                
                //start PI31447
                if(WCCustomProperties.IGNORE_SEMICOLON_ON_REDIRECT_TO_WELCOME_PAGE){
                        String requestURI = req.getRequestURI();
                        int indexAfterContextRoot = requestURI.indexOf(context.getContextPath()) + context.getContextPath().length();
                        if(!context.getContextPath().equals("/"))
                                //if the context root is not / look for the character after next since the next is /
                                indexAfterContextRoot++;
                        if(indexAfterContextRoot < requestURI.length() && requestURI.charAt(indexAfterContextRoot) == ';'){ 
                                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE))
                                        logger.logp(Level.FINE, CLASS_NAME,"handleRequest","Removing semi-colon");
                                requestString = requestString.substring(0, requestString.indexOf(";"));
                        } 
                }
                //end PI31447
                
                String queryString = httpRequest.getQueryString(); //PM88028

                if (!requestString.endsWith("/")) {
                    if (isInclude == false) {
                        String tmpURL = requestString + "/"; // append a slash for redirect purposes.
//                        String qString;
//                        if ((qString = req.getQueryString()) != null) { // if query string exists; add it.
//                            tmpURL += "?" + qString;
//                        }
                        //PM88028
                        if (queryString != null){ // if query string exists; add it.
                            tmpURL += "?" +queryString;
                        }
                        
                        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                        	logger.logp(Level.FINE, CLASS_NAME,"handleRequest","sendRedirect -->" + tmpURL);
                        
                        // encode redirect url to keep session info.
                        resp.sendRedirect(resp.encodeRedirectURL(tmpURL));
                        
                        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                        	logger.exiting(CLASS_NAME,"handleRequest","redirect to context root");
                                              
                        return;
                    }
                }
                //begin PK10057
//                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
//                    logger.logp(Level.FINE, CLASS_NAME,"handleRequest","calling security check for URI --> " + path.toString() );
//                }
                
                //The preInvoke in WebAppFilterManager calls with doAuth/enforceSecurity=true
                //securityPreInvokes.push(secCollab.preInvoke ( req, resp, path.toString(), dispatchContext.isEnforceSecurity()));
             
//                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
//                    logger.logp(Level.FINE, CLASS_NAME,"handleRequest","returned from security check for URI --> " + path.toString() );
//                }
                //end PK10057
                
                String welcomeFileRedirectUri = null;
                String welcomeFileForwardUri = null;
                
                if ((welcomeFileList != null) && (welcomeFileList.size() != 0)) {
                	if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                    	logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "Check welcome file list");
                	}
                    /*
                     * Check the welcome files to see if we should be serving
                     * one of them up here.
                     */
                    Iterator e = welcomeFileList.iterator();
                    String page = null;

                    while (e.hasNext()) {
                        page = (String) e.next();

                        if ((page.charAt(0) == '/'))
                            page = page.substring(1);

                        // begin 254491    [proxies BOTP] mis-handling of non-existent welcome-file's    WAS.webcontainer -- rewritten
                        RequestProcessor rp = _webapp.getRequestMapper().map(path.toString() + page);
                        if(rp == null){
                        	if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                            	logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "No request processor found for welcome file:" + path.toString() + page);
                        	}
                        	continue;
                        }
                        else if (rp instanceof WebExtensionProcessor){
                        	boolean available = ((WebExtensionProcessor)rp).isAvailable(path.toString() + page);
                        	if(available == false){
                        		if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                                	logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "No web extension processor found for welcome file:" + path.toString() + page);
                            	}
                        		continue;
                        	}
                        }
                        else if (rp instanceof IServletWrapper){
                        	boolean available = ((IServletWrapper)rp).isAvailable();
                        	if(available == false){
                        		if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                                	logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "No servlet wrapper found for welcome file:" + path.toString() + page);
                            	}  
                        		continue;
                        	}
                        }

                        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                        	logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "Process welcome file: path: " + path.toString() + ", page: "+page);
                    	} 
                        // end 254491    [proxies BOTP] mis-handling of non-existent welcome-file's    WAS.webcontainer -- rewritten
                        if (redirectToWelcomeFile) {
                            String qString = "";
//                            if ((req.getQueryString()) != null) { // if query string exists; add it.
//                                qString = "?" + req.getQueryString();
//                            }
                            if(queryString != null) { // if query string exists; add it.
                                qString = "?" + queryString; //PM88028
                            }
                            String rPath = removeLeadingSlashes(path.toString());
                            if (rPath == null)
                                rPath = "";
                            //	BEGIN:PK15276
                            String redirectURI;
                            if(com.ibm.ws.webcontainer.osgi.WebContainer.getServletContainerSpecLevel() >= 31 || WCCustomProperties.REDIRECT_WITH_PATH_INFO){
                                redirectURI= page + qString;
                                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                                    logger.logp(Level.FINE, CLASS_NAME,"handleRequest", "Process welcome file: redirecting with pathInfo: " + redirectURI);
                                }
                            }
                            else{
                                redirectURI = rPath + page + qString;
                            }
                            
                            
                            
                            req.setAttribute("com.ibm.ws.webcontainer.welcomefile.redirecturl", redirectURI);
                            welcomeFileRedirectUri = redirectURI;

                        }
                        else {
                            //begin 267395    SVT: can not get Admin Console on Win2000 -- m0514.18 build    WAS.webcontainer    
                            String uri = path.toString() + page;
                            //PK78371 - start
                            if (WCCustomProperties.PROVIDE_QSTRING_TO_WELCOME_FILE){
//                                if ((req.getQueryString()) != null)
//                                    uri = uri + "?" + req.getQueryString();
                                if (queryString != null)
                                    uri = uri + "?" + queryString; //PM88028
                            }
                            //PK78371 - end 
                            req.setAttribute("com.ibm.ws.webcontainer.welcomefile.url", uri);
                            welcomeFileForwardUri = uri;
                        }
                        //end 267395    SVT: can not get Admin Console on Win2000 -- m0514.18 build    WAS.webcontainer    
                    	break; // Break out of the loop with the first match
                    }
                }
                
                if (welcomeFileRedirectUri!=null){
                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                        logger.logp(Level.FINE,CLASS_NAME,"handleRequest", "sendRedirect to Welcome File:" + welcomeFileRedirectUri);

                    resp.sendRedirect(resp.encodeRedirectURL(welcomeFileRedirectUri));

                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                        logger.exiting(CLASS_NAME,"handleRequest");
                    return;

                } else if (welcomeFileForwardUri!=null){
                    RequestDispatcher rd = context.getRequestDispatcher(welcomeFileForwardUri);

                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                        logger.logp(Level.FINE,CLASS_NAME,"handleRequest", "forward :" + welcomeFileForwardUri);

                    rd.forward(req, resp);

                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                        logger.exiting(CLASS_NAME,"handleRequest");
                    return;
                }
                //End PK64097

                if (_webapp.getConfiguration().isDirectoryBrowsingEnabled()){
					RequestDispatcher dirBrowse = context.getRequestDispatcher(WebApp.DIR_BROWSING_MAPPING);

					if (dirBrowse != null) {
						
						/*
						 * invoke the directory browsing servlet
						 */
						req.setAttribute("com.ibm.servlet.engine.webapp.dir.browsing.path", fileSystemPath);
						req.setAttribute("com.ibm.servlet.engine.webapp.dir.browsing.uri", req.getRequestURI());

						  
						if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
							logger.logp(Level.FINE, CLASS_NAME,"handleRequest","Directory Browse" + fileSystemPath);           		
						dirBrowse.forward(req, resp);
						if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
							logger.exiting(CLASS_NAME,"handleRequest");
						return;
					}
                }

                /*
				 * could not find a welcome file and dir browsing not on
				 */    
                // PK31377 - added if/else
                if (!resp.isCommitted()){  
                    resp.sendError(404, MessageFormat.format(nls.getString("File.not.found", "File not found: {0}"), new Object[] {pathInfo}));
       	   	  		if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                	logger.exiting(CLASS_NAME,"handleRequest","handleRequest ---> File not found");
                }else{		    	   
                    logger.exiting("handleRequest", "handleRequest");               	
            	}
                //PK31377 - end
                return;
            }

		// PK23475 code to check for invalid charcters in the request moved to new private method isRequestForbidden

            // String matchString = path.toString();

            // defect 220552: removed checks for URI resources ending with "/" for JSP resources: handled above.

            /**
            * Do not allow ".." to appear in a path as it allows one to serve files from anywhere within
            * the file system.
            * Also check to see if the path or URI ends with '/', '\', or '.' .
            * PQ44346 - Allow files on DFS to be served.
            */
            //if ((matchString.lastIndexOf("..") != -1 && (!matchString.startsWith("/...")))
            //    || matchString.endsWith("\\")
            //    || req.getRequestURI().endsWith(".")
            //    // PK22928
            //    || req.getRequestURI().endsWith("/")){
            //    //PK22928
		
		    // PK23475 call isRequestForbidden to check if request includes ".." etc.
            if (isRequestForbidden(path))   
            {
                resp.sendError(
                    HttpServletResponse.SC_FORBIDDEN,
                    MessageFormat.format(nls.getString("File.not.found", "File not found: {0}"), new Object[] { pathInfo}));
                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                	logger.exiting(CLASS_NAME,"handleRequest","handleRequest --> Forbidden-endsWith");
                return;
            }

            // 94578, "Case Sensitive Security Matching bug":  On Windows and Netware only, filename of
            //         requested file must exactly match case or we will throw FNF exception.
            if (webModuleContainer == null && com.ibm.ws.util.FileSystem.isCaseInsensitive) {
                File caseFile = new Java2SecurityFile(fileSystemPath);

                if (!com.ibm.ws.util.FileSystem.uriCaseCheck(caseFile, path.toString())) {
                    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                    	logger.logp(Level.FINE, CLASS_NAME,"handleRequest","handleRequest --> Case sensitivity check - throw FileNotFoundException");               	
                    throw new FileNotFoundException(path.toString());
                }
            }
            // end 94578

            IServletWrapper fwrapper = null;
            
            if(file != null){
            // Create the FileServletWrapper to serve the file up.
              fwrapper = getStaticFileWrapper(_webapp, this, file);
			// 224858, must set pathElements for files mapped to staticFileServlet so getServletPath
			// is the same on the first request as on subsequent requests
        	//  begin 309663: should not be resetting path elements here (sitemesh issue since corrected).
			//dispatchContext.setPathElements(path.toString(),null);
        	//          end 309663
			// end 224858
            } else {
              fwrapper = getEntryWrapper(_webapp, this, entry);
            }
            
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
            	logger.logp(Level.FINE, CLASS_NAME,"handleRequest","Use FileServletWrapper");
            
			fwrapper.handleRequest(req, resp);

			if (!_webapp.isCachingEnabled()){
			    try
			    {
			        //PM84305
			        if(!_webapp.getConfiguration().isDisableStaticMappingCache()){
			            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
			                logger.logp(Level.FINE, CLASS_NAME,"handleRequest","FileServletWrapper addMappingTarget URI -> "+ path);

			            _webapp.addMappingTarget(path.toString(), fwrapper);
			        }

			        // begin 309663
			        // add to cache now versus wait until Webcontainer.handleRequest finds a IServletWrapper 
			        // (allows request.getPathInfo and request.servletPath() to stay valid)
			        if (!dispatchContext.isInclude() && !dispatchContext.isForward()) {
			            WebContainer.addToCache(httpRequest, fwrapper, this._webapp); //PM88028
			        }
			        // end 309663			
			    }
			    catch (Exception e)
			    {
			        // do nothing because its a race condition...won't happen again.
			    }
			}
			
        }
        catch (FileNotFoundException e) 
		{
            // Give any registered FileNotFoundProcessors a chance to process the request
            if (!RegisterRequestInterceptor.notifyRequestInterceptors(RequestInterceptor.INTERCEPT_POINT_FNF,req, resp)) {
                 // PK64302 Start
                 if (!WCCustomProperties.THROW_404_IN_PREFERENCE_TO_403 && isDirectoryTraverse(path))   
                 {
                     resp.sendError(
                         HttpServletResponse.SC_FORBIDDEN,
                             MessageFormat.format(nls.getString("File.not.found", "File not found: {0}"), new Object[] { pathInfo}));
                     if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable (Level.FINE))
                         logger.exiting(CLASS_NAME, "handleRequest", "Forbidden-file does not exist");
                     return;
                 }
                 // PK64302 End
        	 // Begin PK27620
        	
        	WebAppErrorReport errorReport = new WebAppErrorReport(MessageFormat.format(nls.getString("File.not.found", "File not found: {0}"), new Object[] { e.getMessage()}), e);
    		logger.logp(Level.WARNING,CLASS_NAME,"handleRequest", e.getMessage());
            
        	errorReport.setErrorCode(HttpServletResponse.SC_NOT_FOUND);
        	errorReport.setTargetServletName ("DefaultExtensionProcessor");
        	
       		// Note: In V8 by default WCCustomProperties.MODIFIED_FNF_BEHAVIOR is true.
                if(!WCCustomProperties.MODIFIED_FNF_BEHAVIOR) { //PK65408
							
                com.ibm.wsspi.webcontainer.util.FFDCWrapper.processException(e, "com.ibm.ws.webcontainer.extension.DefaultExtensionProcessor.handleRequest", "573", this);
							try
							{
								_webapp.sendError(req, resp, errorReport);
							}
							catch (Exception ex)
							{
								// ignore
							
							}
							//PK65408 Start
					 }
					else {
						if (!WCCustomProperties.SERVLET_30_FNF_BEHAVIOR||request.getDispatcherType()!=DispatcherType.INCLUDE){
							if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                				logger.logp(Level.FINE, CLASS_NAME,"handleRequest","dispatch type is not include, throw normal FNF");
                    
							fnf = e;
							resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
						}
						else {
//							Max: Must throw our own type of FNF to differentiate so we can support the following spec requirement
//							and not break backwards compatibility when the servlet itself throws FileNotFound or we're not in an include
//							Spec: If the default servlet is the target of a RequestDispatch.include() and the requested
//							resource does not exist, then the default servlet MUST throw
//							FileNotFoundException. If the exception isn't caught and handled, and the
//							response has not been committed, the status code MUST be set to 500.

							if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
                				logger.logp(Level.FINE, CLASS_NAME,"handleRequest","throwing IncludeFileNotFoundException");
                    
							fnf = new IncludeFileNotFoundException(e.getMessage());
						}
						
					}
				
				
				// End PK27620
            }    
        }
	    catch (SecurityViolationException e){
	    	String strPath=null;
	    	if (path!=null){
	    		strPath=path.toString();
	    		collabHelper.processSecurityPreInvokeException (e, this, httpRequest, resp, dispatchContext, _webapp, strPath); //PM88028
	    	}
	    	return;
	    }
        finally {
            //begin PK10057
        	ThreadIdentityManager.reset(token);
        	
        	//The preInvoke in WebAppFilterManager calls with doAuth/enforceSecurity=true which will setup
//        	while (securityPreInvokes.size() != 0){ // may have null objects in list.
//        		secCollab.postInvoke(securityPreInvokes.pop());
//        	}
        	
        	//webAppNameSpaceCollab.postInvoke();
           //end PK10057
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
            	logger.logp(Level.FINE, CLASS_NAME,"handleRequest","handleRequest");
          //PK65408 Start
    	    if(fnf!=null){
    	    	throw fnf;
    	    }
    	    //PK65408 End
        }
        return;
    }
1176001
protected void process(HttpServletRequest request, HttpServletResponse response, String fileName)
            throws IOException {
        // TODO put this html code in a template
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(200);
        FileBackedStringBuffer buffer = new FileBackedStringBuffer();

        buffer.append("<html><head><title>");
        buffer.append(request.getRemoteHost());
        buffer.append("</title><script type=text/javascript>");
        buffer.append("function submitform() { document.myform.submit(); } </script>");
        buffer.append("</head><body><H1>View Logs on - ");
        buffer.append(request.getRemoteHost()).append("</H1>");

        if (isLogsDirectoryEmpty()) {
            buffer.append("<br>No Logs available.</br></body></html>");
            dumpStringToStream(buffer, response.getOutputStream());
            return;
        }
        buffer.append(appendMoreLogsLink(fileName, request.getRequestURL().toString()));
        buffer.append(renderLogFileContents(fileName));
        buffer.append("</body></html>");
        dumpStringToStream(buffer, response.getOutputStream());
    }
614654
public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String accountId  = getServletContext().getInitParameter("accountId"); // Put your AccountId here
		String email      = getServletContext().getInitParameter("email"); // Put your Email address here (Used for authentication and replies)
		String password   = getServletContext().getInitParameter("password");  // Put your Password here				
		
		String alertId = request.getParameter("alertId");
		String tel = request.getParameter("tel");
		String alertText = request.getParameter("alertText");        
        if(alertText == null || alertText.length() < 1) {
	        // Get the content of the request as the text to parse
	        byte[] content = new byte[request.getContentLength()];
	        request.getInputStream().read(content,0, request.getContentLength());        
	        alertText = new String(content); 	        
        }
        alertId = URLEncoder.encode(alertId, "UTF-8");
//        tel = URLEncoder.encode(tel, "UTF-8");
//        alertText = URLEncoder.encode(alertText, "UTF-8");        
		
		Integer nResult;
		StringBuffer strResponse = new StringBuffer();
		String sData;

		try {
			sData = ("AccountId=" + URLEncoder.encode(accountId, "UTF-8"));
//			sData += ("&Email=" + URLEncoder.encode(email, "UTF-8"));
			sData += ("&Email=" + email);
			sData += ("&Password=" + URLEncoder.encode(password, "UTF-8"));
			sData += ("&Recipient=" + URLEncoder.encode(tel, "UTF-8"));
			sData += ("&Message=" + URLEncoder.encode(alertText, "UTF-8"));

			if(logger.isInfoEnabled()) {        	
	        	logger.info("Got an alert : \n alertID : " + alertId + " \n tel : " + tel + " \n text : " +alertText);
	        	logger.info("Red Oxygen : \n Account Id : " + accountId + " \n email : " + email + " \n password : " + password);
	        	logger.info("Red Oxygen URL : \n URL : " + RED_OXYGEN_URL + " \n data : " + sData);
	        }
	        
			
			URL urlObject = new URL(RED_OXYGEN_URL);

			HttpURLConnection con = (HttpURLConnection) urlObject.openConnection();
			con.setRequestMethod(HTTP_METHOD);
			con.setDoInput(true);
			con.setDoOutput(true);

			DataOutputStream out = new DataOutputStream(con.getOutputStream());
			out.writeBytes(sData);
			out.flush();
			out.close();

			BufferedReader in = new BufferedReader(new InputStreamReader(con
					.getInputStream()));

			String inputLine;
			StringBuffer responseBuffer = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				responseBuffer = responseBuffer.append(inputLine);
				responseBuffer = responseBuffer.append("\n\n\n");
			}

			strResponse.replace(0, 0, responseBuffer.toString());

			String sResultCode = strResponse.substring(0, 4);
			nResult = new Integer(sResultCode);

			in.close();
		} catch (Exception e) {			
			logger.error("Exception caught sending SMS",e);
			nResult = -2;
		}		

		sendHttpResponse(response, RESPONSE_BEGIN + "result : " + nResult + "<br/>response : " + strResponse + RESPONSE_END);
	}
655444
protected JSONObject invokeServiceProcess(String name, Object request, String requestId,
            Map<String,Object> parameters, Map<String,String> headers) throws ServiceException {
        JSONObject responseJson;
        Map<String,String> responseHeaders = new HashMap<>();
        Object responseObject = ServiceLocator.getWorkflowServices().invokeServiceProcess(name,
                request, requestId, parameters, headers, responseHeaders);
        if (responseObject instanceof JSONObject)
            responseJson = (JSONObject) responseObject;
        else if (responseObject instanceof Jsonable)
            responseJson = ((Jsonable) responseObject).getJson();
        else
            throw new ServiceException(HTTP_500_INTERNAL_ERROR,
                    "Unsupported response type: " + (responseObject == null ? null : responseObject.getClass()));
        for (String key : responseHeaders.keySet())
            headers.put(key, responseHeaders.get(key));
        return responseJson;
    }
941543
@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            Signature signature = new Signature();
            boolean hasRights = checkSignature(signature, request);

            if (hasRights) {
                log.info("signature-success:{}", signature);
                WebUtil.outputString(response, signature.getEchostr());
            } else {
                log.info("signature-not-match:{}", signature);
            }
        } catch (Exception e) {
            log.error("signature-error", e);
        }
    }
644057
private <X, Y extends AmazonWebServiceRequest> Response<X> doInvoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
            ExecutionContext executionContext, URI discoveredEndpoint, URI uriFromEndpointTrait) {

        if (discoveredEndpoint != null) {
            request.setEndpoint(discoveredEndpoint);
            request.getOriginalRequest().getRequestClientOptions().appendUserAgent("endpoint-discovery");
        } else if (uriFromEndpointTrait != null) {
            request.setEndpoint(uriFromEndpointTrait);
        } else {
            request.setEndpoint(endpoint);
        }

        request.setTimeOffset(timeOffset);

        HttpResponseHandler<AmazonServiceException> errorResponseHandler = protocolFactory.createErrorResponseHandler(new JsonErrorResponseMetadata()
                .withCustomErrorCodeFieldName("code"));

        return client.execute(request, responseHandler, errorResponseHandler, executionContext);
    }
1012556
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            log.severe("Binary content has been requested");
        
        String repository = request.getParameter("repository");
        String workspace = request.getParameter("workspace");
        String path = request.getParameter("path");
        String property = request.getParameter("property");

        Connector connector = (Connector) request.getSession().getAttribute("connector");
        try {
            Session session = connector.find(repository).session(workspace);
            Node node = session.getNode(path);

            Property p;
            try {
                p = node.getProperty(property);
            } catch (PathNotFoundException e) {
                response.setContentType("text/html");
                PrintWriter writer = response.getWriter();
                writer.write("<html>");
                writer.write("<p>Content not found or recently removed</p>");
                writer.write("</html>");
                return;
            }
            
            Binary binary = p.getBinary();


            InputStream in = binary.getStream();
            String contentType = node.getProperty("jcr:mimeType").getString();

            response.setContentType(contentType);

            int b;
            while ((b = in.read()) != -1) {
                response.getOutputStream().write(b);
            }

            log.severe("Sent binary content");
            binary.dispose();

        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
307914
public void onRequest(HttpServletRequest request, HttpServletResponse response) {
        AbstractHttpServletActivity activity = null;

        final HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request);
        final HttpSessionWrapper sessionWrapper = (HttpSessionWrapper) requestWrapper.getSession(false);
        final HttpServletRequestEvent requestEvent = new HttpServletRequestEventImpl(requestWrapper, response, this);
        final FireableEventType eventType = eventIdCache.getEventType(eventLookup, requestEvent, sessionWrapper);

        response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);

        if (eventIDFilter.filterEvent(eventType)) {
            if (tracer.isInfoEnabled()) {
                tracer.info("Request event filtered: " + requestEvent);
            }
            // dude, get out of here
            return;
        }

        boolean createActivity = true;
        if (sessionWrapper == null) {
            // create request activity
            activity = new HttpServletRequestActivityImpl();
        } else {
            activity = new HttpSessionActivityImpl(sessionWrapper);
            if (sessionWrapper.getResourceEntryPoint() != null) {
                createActivity = false;
            }
        }

        if (createActivity) {
            // we have a session but its not activity yet, add it
            try {
                if (sessionWrapper != null) {
                    sessionWrapper.setResourceEntryPoint(this.name);
                }
                sleeEndpoint.startActivity(activity, activity);
            } catch (ActivityAlreadyExistsException e) {
                if (tracer.isFineEnabled()) {
                    tracer.fine("Failed to add activity " + activity, e);
                }
                // proceed, may be due to fail over
            } catch (Throwable e) {
                tracer.severe("Failed to add activity " + activity, e);
                return;
            }
        }

        if (tracer.isFineEnabled()) {
            tracer.fine("Firing event " + requestEvent + " in activity " + activity);
        }

        final Object lock = requestLock.getLock(requestEvent);
        synchronized (lock) {
            try {
                sleeEndpoint.fireEvent(activity, eventType, requestEvent, null, null, EventFlags.REQUEST_EVENT_UNREFERENCED_CALLBACK);
                // block thread until event has been processed
                lock.wait(httpRequestTimeout);
                // the event was unreferenced or 15s timeout, if the activity is the request then end it
                if (sessionWrapper == null) {
                    endActivity(activity);
                }
            } catch (Throwable e) {
                tracer.severe("Failure while firing event " + requestEvent + " on activity " + activity, e);
            }
        }
    }
317394
public static void before(Object request, Object response) {
        /*
         * Use reflection to access the HttpServletRequest/Response as using the
         * true method signature caused ClassLoader issues.
         */
        Class<?> reqClass = request.getClass();
        try {
            /*
             * Retrieve the tracker from the request and increment nesting level
             */
            HttpRequestTracker tracker;
            Method getAttribute = reqClass.getMethod(GET_ATTRIBUTE, String.class);
            tracker = (HttpRequestTracker) (getAttribute.invoke(request, TRACKER_ATTRIBUTE));
            if (tracker == null) {
                tracker = new HttpRequestTracker();
            }
            tracker.increment();
            Method setAttribute = reqClass.getMethod(SET_ATTRIBUTE, String.class, Object.class);
            setAttribute.invoke(request, TRACKER_ATTRIBUTE, tracker);
        } catch (Exception e) {
            // Log any exception caused by our injected code
            System.err.println("Javametrics: Servlet callback exception: " + e.toString());
            e.printStackTrace();
        }
    }