Parses an HTML based response and removes the items that are not
permitted.

@param request
the http servlet request
@param response
the http servlet response
@return the new response body without non-permissable objects.
@throws ServletException
171767
private String filterHTML(HttpServletRequest request,
                              DataResponseWrapper response)
            throws ServletException {
        String path = request.getPathInfo();
        String[] parts = path.split("/");

        String pid = parts[1];

        String body = new String(response.getData());

        InputStream is = new ByteArrayInputStream(body.getBytes());
        Document doc = tidy.parseDOM(is, null);

        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList rows = null;
        try {
            rows =
                    (NodeList) xpath.evaluate("//table[2]/tr",
                                              doc,
                                              XPathConstants.NODESET);
            if (logger.isDebugEnabled()) {
                logger.debug("number of rows found: " + rows.getLength());
            }
        } catch (XPathExpressionException xpe) {
            throw new ServletException("Error parsing HTML for search results: ",
                                       xpe);
        }

        // only the header row, no results.
        if (rows.getLength() < 2) {
            if (logger.isDebugEnabled()) {
                logger.debug("No results to filter.");
            }
            return body;
        }

        Map<String, Node> dsids = new HashMap<String, Node>();
        for (int x = 1; x < rows.getLength(); x++) {
            NodeList elements = rows.item(x).getChildNodes();
            String dsid = elements.item(0).getFirstChild().getNodeValue();
            if (logger.isDebugEnabled()) {
                logger.debug("dsid: " + dsid);
            }
            dsids.put(dsid, rows.item(x));
        }

        Set<Result> results =
                evaluatePids(dsids.keySet(), pid, request, response);

        for (Result r : results) {
            String resource = r.getResource();
            if (resource == null || resource.isEmpty()) {
                logger.warn("This resource has no resource identifier in the xacml response results!");
            } else if (logger.isDebugEnabled()) {
                logger.debug("Checking: " + r.getResource());
            }

            int lastSlash = resource.lastIndexOf('/');
            String rid = resource.substring(lastSlash + 1);

            if (r.getStatus().getCode().contains(Status.STATUS_OK)
                    && r.getDecision() != Result.DECISION_PERMIT) {
                Node node = dsids.get(rid);
                node.getParentNode().removeChild(node);
                if (logger.isDebugEnabled()) {
                    logger.debug("Removing: " + resource + "[" + rid + "]");
                }
            }
        }

        Source src = new DOMSource(doc);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        javax.xml.transform.Result dst = new StreamResult(os);
        try {
            xFormer.transform(src, dst);
        } catch (TransformerException te) {
            throw new ServletException("error generating output", te);
        }

        return new String(os.toByteArray());
    }
1358314
@Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        String api = request.getParameter("api");

        if (api == null || api.length() == 0) {
            response.setContentType("text/html; charset=UTF-8");
            getIndex(response.getWriter());
        } else {
            response.setContentType("text/xml; charset=UTF-8");
            getWSDL(api.toUpperCase(), request.getRequestURL()
                            .toString(), response.getWriter());
        }

        response.flushBuffer();
    }
1370418
public AmazonWebServiceResponse<String> handle(HttpResponse response) throws Exception {
        AmazonWebServiceResponse<String> awsResponse = parseResponseMetadata(response);

        int bytesRead;
        byte[] buffer = new byte[1024];
        StringBuilder builder = new StringBuilder();
        InputStream content = response.getContent();
        while ((bytesRead = content.read(buffer)) > 0) {
            builder.append(new String(buffer, 0, bytesRead, StringUtils.UTF8));
        }
        awsResponse.setResult(builder.toString());

        return awsResponse;
    }
639771
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // Get the script path from the request - include aware (GROOVY-815)
        final String scriptUri = getScriptUri(request);

        // Set it to HTML by default
        response.setContentType("text/html; charset="+encoding);

        // Set up the script context
        final ServletBinding binding = new ServletBinding(request, response, servletContext);
        setVariables(binding);

        // Run the script
        try {
            Closure closure = new Closure(gse) {

                public Object call() {
                    try {
                        return ((GroovyScriptEngine) getDelegate()).run(scriptUri, binding);
                    } catch (ResourceException | ScriptException e) {
                        throw new RuntimeException(e);
                    }
                }

            };
            GroovyCategorySupport.use(ServletCategory.class, closure);
        } catch (RuntimeException runtimeException) {
            StringBuilder error = new StringBuilder("GroovyServlet Error: ");
            error.append(" script: '");
            error.append(scriptUri);
            error.append("': ");
            Throwable e = runtimeException.getCause();
            /*
             * Null cause?!
             */
            if (e == null) {
                error.append(" Script processing failed.\n");
                error.append(runtimeException.getMessage());
                if (runtimeException.getStackTrace().length > 0)
                    error.append(runtimeException.getStackTrace()[0].toString());
                servletContext.log(error.toString());
                System.err.println(error.toString());
                runtimeException.printStackTrace(System.err);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error.toString());
                return;
            }
            /*
             * Resource not found.
             */
            if (e instanceof ResourceException) {
                error.append(" Script not found, sending 404.");
                servletContext.log(error.toString());
                System.err.println(error.toString());
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            /*
             * Other internal error. Perhaps syntax?!
             */
            servletContext.log("An error occurred processing the request", runtimeException);
            error.append(e.getMessage());
            if (e.getStackTrace().length > 0)
                error.append(e.getStackTrace()[0].toString());
            servletContext.log(e.toString());
            System.err.println(e.toString());
            runtimeException.printStackTrace(System.err);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        }
    }
556701
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String servletPath = (String) request.getAttribute(Dispatcher.__INCLUDE_SERVLET_PATH);
        String pathInfo = null;
        if (servletPath == null)
        {
            servletPath = request.getServletPath();
            pathInfo = request.getPathInfo();
        }
        else
            pathInfo = (String) request.getAttribute(Dispatcher.__INCLUDE_PATH_INFO);

        String pathInContext = URI.addPaths(servletPath, pathInfo);
                
        boolean endsWithSlash = pathInContext.endsWith("/");
        Resource resource = getResource(pathInContext);

        // Is the method allowed?
        String method = request.getMethod();
        if (_AllowString.indexOf(method) < 0)
        {
            if (resource != null && resource.exists())
            {
                response.setHeader(HttpFields.__Allow, _AllowString);
                response.sendError(HttpResponse.__405_Method_Not_Allowed);
            }
            else
                response.sendError(HttpResponse.__404_Not_Found);
            return;
        }

        // Handle the request
        try
        {
            // handle by method.
            if (method.equals(HttpRequest.__GET) || method.equals(HttpRequest.__POST) || method.equals(HttpRequest.__HEAD))
                handleGet(request, response, pathInContext, resource, endsWithSlash);
            else if (_putAllowed && method.equals(HttpRequest.__PUT))
                handlePut(request, response, pathInContext, resource);
            else if (_delAllowed && method.equals(HttpRequest.__DELETE))
                handleDelete(request, response, pathInContext, resource);
            else if (_putAllowed && _delAllowed && method.equals(HttpRequest.__MOVE))
                handleMove(request, response, pathInContext, resource);
            else if (method.equals(HttpRequest.__OPTIONS))
                handleOptions(request, response);
            else if (method.equals(HttpRequest.__TRACE))
                _servletHandler.handleTrace(request, response);
            else
            {
                // anything else...
                try
                {
                    if (resource.exists())
                        response.sendError(HttpResponse.__501_Not_Implemented);
                    else
                        _servletHandler.notFound(request, response);
                }
                catch (Exception e)
                {
                    LogSupport.ignore(log, e);
                }
            }
        }
        catch (IllegalArgumentException e)
        {
            LogSupport.ignore(log, e);
        }
        finally
        {
            if (resource != null && !(resource instanceof CachedResource))
                resource.release();
        }

    }
1322690
public void doGet(HttpServletRequest request,
                      HttpServletResponse response) 
        throws ServletException, IOException
    {
        if (request.getQueryString()!=null &&
            request.getQueryString().length()>0)
        {
            String target=doAction(request);
            response.sendRedirect(request.getContextPath()+
                                  request.getServletPath()+
                                  (request.getPathInfo()!=null
                                   ?request.getPathInfo():"")+
                                  (target!=null?("#"+target):""));
            return;
        }
        
        Page page= new Page();
        page.title(getServletInfo());
        page.addHeader("");
        page.attribute("text","#000000");
        page.attribute(Page.BGCOLOR,"#FFFFFF");
        page.attribute("link","#606CC0");
        page.attribute("vlink","#606CC0");
        page.attribute("alink","#606CC0");

        page.add(new Block(Block.Bold).add(new Font(3,true).add(getServletInfo())));
        page.add(Break.rule);
        Form form=new Form(request.getContextPath()+
                           request.getServletPath()+
                           "?A=exit");
        form.method("GET");
        form.add(new Input(Input.Submit,"A","Exit All Servers"));
        page.add(form);
        page.add(Break.rule);
        page.add(new Heading(3,"Components:"));

        List sList=new List(List.Ordered);
        page.add(sList);
        
        String id1;
        int i1=0;
        Iterator s=_servers.iterator();
        while(s.hasNext())
        {
            id1=""+i1++;
            HttpServer server=(HttpServer)s.next();            
            Composite sItem = sList.newItem();
            sItem.add("<B>HttpServer&nbsp;");
            sItem.add(lifeCycle(request,id1,server));
            sItem.add("</B>");
            sItem.add(Break.line);
            sItem.add("<B>Listeners:</B>");
            List lList=new List(List.Unordered);
            sItem.add(lList);

            HttpListener[] listeners=server.getListeners();
            for (int i2=0;i2<listeners.length;i2++)
            {
                HttpListener listener = listeners[i2];
                String id2=id1+":"+listener;
                lList.add(lifeCycle(request,id2,listener));
            }

            Map hostMap = server.getHostMap();
            
            sItem.add("<B>Contexts:</B>");
            List hcList=new List(List.Unordered);
            sItem.add(hcList);
            Iterator i2=hostMap.entrySet().iterator();
            while(i2.hasNext())
            {
                Map.Entry hEntry=(Map.Entry)(i2.next());
                String host=(String)hEntry.getKey();

                PathMap contexts=(PathMap)hEntry.getValue();
                Iterator i3=contexts.entrySet().iterator();
                while(i3.hasNext())
                {
                    Map.Entry cEntry=(Map.Entry)(i3.next());
                    String contextPath=(String)cEntry.getKey();
                    java.util.List contextList=(java.util.List)cEntry.getValue();
                    
                    Composite hcItem = hcList.newItem();
                    if (host!=null)
                        hcItem.add("Host="+host+":");
                    hcItem.add("ContextPath="+contextPath);
                    
                    String id3=id1+":"+host+":"+
                        (contextPath.length()>2
                         ?contextPath.substring(0,contextPath.length()-2)
                         :contextPath);
                    
                    List cList=new List(List.Ordered);
                    hcItem.add(cList);
                    for (int i4=0;i4<contextList.size();i4++)
                    {
                        String id4=id3+":"+i4;
                        Composite cItem = cList.newItem();
                        HttpContext hc=
                            (HttpContext)contextList.get(i4);
                        cItem.add(lifeCycle(request,id4,hc));
                        cItem.add("<BR>ResourceBase="+hc.getResourceBase());
                        cItem.add("<BR>ClassPath="+hc.getClassPath());

                    
                        List hList=new List(List.Ordered);
                        cItem.add(hList);
                        int handlers = hc.getHandlers().length;
                        for(int i5=0;i5<handlers;i5++)
                        {
                            String id5=id4+":"+i5;
                            HttpHandler handler = hc.getHandlers()[i5];
                            Composite hItem=hList.newItem();
                            hItem.add(lifeCycle(request,
                                                id5,
                                                handler,
                                                handler.getName()));
                            if (handler instanceof ServletHandler)
                            {
                                hItem.add("<BR>"+
                                          ((ServletHandler)handler)
                                          .getServletMap());
                            }
                        }
                    }
                }
            }
            sItem.add("<P>");
        }


        response.setContentType("text/html");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache,no-store");
        Writer writer=response.getWriter();
        page.write(writer);
        writer.flush();
    }
589740
private HttpHandler validate(final HttpServletRequest request,
                               final HttpServletResponse response,
                               final ParsedHttpRequest parsedHttpRequest) throws IOException, ServletException {
    final String specification = parsedHttpRequest.getTargetSpecification();
    final String version = parsedHttpRequest.getVersion();

    if (specification == null) {
      writeMessage(response, "Specification is not provided in the request.", HttpServletResponse.SC_BAD_REQUEST);
      return null;
    }

    final HttpHandler handler = eventHandlers.get(specification.toLowerCase());
    if (handler == null) {
      writeMessage(response, String.format("No event handler registered for: [%s].", specification),
          HttpServletResponse.SC_NOT_FOUND);
      return null;
    }

    if (version == null) {
      writeMessage(response, "Version is not provided in the request.", HttpServletResponse.SC_BAD_REQUEST);
      return null;
    }
    return handler;
  }
302980
protected void handleResponse(HttpRequest<?> request, MutableHttpResponse<?> response) {
        HttpHeaders headers = request.getHeaders();
        Optional<String> originHeader = headers.getOrigin();
        originHeader.ifPresent(requestOrigin -> {

            Optional<CorsOriginConfiguration> optionalConfig = getConfiguration(requestOrigin);

            if (optionalConfig.isPresent()) {
                CorsOriginConfiguration config = optionalConfig.get();

                if (CorsUtil.isPreflightRequest(request)) {
                    Optional<HttpMethod> result = headers.getFirst(ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.class);
                    setAllowMethods(result.get(), response);
                    Argument<List> type = Argument.of(List.class, String.class);
                    Optional<List> allowedHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS, type);
                    allowedHeaders.ifPresent(val ->
                        setAllowHeaders(val, response)
                    );

                    setMaxAge(config.getMaxAge(), response);
                }

                setOrigin(requestOrigin, response);
                setVary(response);
                setExposeHeaders(config.getExposedHeaders(), response);
                setAllowCredentials(config, response);
            }
        });
    }
288833
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<FileItem> items;
        // Parse the request
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            throw new ServletException(e);
        }

        String repository = getParameter(items, REPOSITORY_NAME_PARAMETER);
        String incBinaries = getParameter(items, INCLUDE_BINARY_PARAMETER);
        String reindexOnFinish = getParameter(items, REINDEX_ON_FINISH_PARAMETER);

        RestoreParams params = new RestoreParams();
        params.setIncludeBinaries(Boolean.valueOf(incBinaries));
        params.setReindexOnFinish(Boolean.valueOf(reindexOnFinish));
        
        InputStream in = getStream(items);

        File dir = new File(tempDir.getAbsolutePath() + File.pathSeparator + 
                Long.toString(System.currentTimeMillis()));
        
        FileUtil.unzip(in, dir.getAbsolutePath());
        Connector connector = (Connector) request.getSession().getAttribute(REPOSITORY_CONNECTOR);

        try {
            connector.find(repository).restore(dir.getAbsolutePath(), params);
        } catch (Exception e) {
            throw new ServletException(e);
        }

        String uri = request.getContextPath()
                + String.format(DESTINATION_URL, repository);
        response.sendRedirect(uri);
    }
886941
protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
    {
        if (processStatus(request, response)) {
            return;
        }
        
        if (!isRunning()) {
            int errorCode = mProperties.getInt("startup.codes.error", 503);
            response.sendError(errorCode);
            return;
        }
        
        if (mUseSpiderableRequest) {
            request = new SpiderableRequest(request,
                                            mQuerySeparator,
                                            mParameterSeparator,
                                            mValueSeparator);
        }

        // start transaction
        TeaServletTransaction tsTrans = 
            getEngine().createTransaction(request, response, true);
    
        // load associated request/response
        ApplicationRequest appRequest = tsTrans.getRequest();
        ApplicationResponse appResponse = tsTrans.getResponse();

        // process template
        processTemplate(appRequest, appResponse);
        appResponse.finish();
        
        // flush the output
        response.flushBuffer();
    }
2690
private void processBatchRequestResponse(CloseableHttpResponse response) throws IOException,
      UnexpectedResponseException {
    String entityStr = EntityUtils.toString(response.getEntity());
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode >= 400) {
      throw new RuntimeException("Failed due to " + entityStr + " (Detail: "
          + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE) + " )");
    }

    JsonObject jsonBody = new JsonParser().parse(entityStr).getAsJsonObject();
    if (!jsonBody.get("hasErrors").getAsBoolean()) {
      return;
    }

    JsonArray results = jsonBody.get("results").getAsJsonArray();
    for (JsonElement jsonElem : results) {
      JsonObject json = jsonElem.getAsJsonObject();
      int subStatusCode = json.get("statusCode").getAsInt();
      if (subStatusCode < 400) {
        continue;
      } else if (subStatusCode == 400
                 && Operation.INSERT_ONLY_NOT_EXIST.equals(operation)) {
        JsonElement resultJsonElem = json.get("result");
        Preconditions.checkNotNull(resultJsonElem, "Error response should contain result property");
        JsonObject resultJsonObject = resultJsonElem.getAsJsonArray().get(0).getAsJsonObject();
        if (isDuplicate(resultJsonObject, subStatusCode)) {
          continue;
        }
      }
      throw new RuntimeException("Failed due to " + jsonBody + " (Detail: "
          + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE) + " )");
    }
  }
428922
public static HttpResponse response(String body) {
        return new HttpResponse().withStatusCode(OK_200.code()).withReasonPhrase(OK_200.reasonPhrase()).withBody(body);
    }
495586
public void service(ServletRequest request, ServletResponse response)
        throws IOException, ServletException
    {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        if (!req.getMethod().equals("POST")) {
            res.setStatus(500); // , "Hessian Requires POST");
            PrintWriter out = res.getWriter();

            res.setContentType("text/html");
            out.println("<h1>Hessian Requires POST</h1>");

            return;
        }

        String serviceId = req.getPathInfo();
        String objectId = req.getParameter("id");
        if (objectId == null)
            objectId = req.getParameter("ejbid");

        ServiceContext.begin(req, res, serviceId, objectId);

        try {
            InputStream is = request.getInputStream();
            OutputStream os = response.getOutputStream();

            response.setContentType("x-application/hessian");

            SerializerFactory serializerFactory = getSerializerFactory();

            invoke(is, os, objectId, serializerFactory);
        } catch (RuntimeException e) {
            throw e;
        } catch (ServletException e) {
            throw e;
        } catch (Throwable e) {
            throw new ServletException(e);
        } finally {
            ServiceContext.end();
        }
    }
1091371
private HttpServletResponse getHttpServletResponseUrlEncoder(
			final Response response) {

		return new HttpServletResponse() {

			public void setLocale(Locale loc) {

			}

			public void setContentType(String type) {

			}

			public void setContentLength(int len) {

			}

			public void setBufferSize(int size) {

			}

			public void resetBuffer() {

			}

			public void reset() {

			}

			public boolean isCommitted() {
				return false;
			}

			public PrintWriter getWriter() throws IOException {
				return new PrintWriter(new RedirectWriter(getResponse()));
			}

			public ServletOutputStream getOutputStream() throws IOException {
				return null;
			}

			public Locale getLocale() {
				return null;
			}

			public int getBufferSize() {
				return 0;
			}

			public void flushBuffer() throws IOException {

			}

			public void setStatus(int sc, String sm) {

			}

			public void setStatus(int sc) {

			}

			public void setIntHeader(String name, int value) {

			}

			public void setHeader(String name, String value) {

			}

			public void setDateHeader(String name, long date) {

			}

			public void sendRedirect(String location) throws IOException {

			}

			public void sendError(int sc, String msg) throws IOException {

			}

			public void sendError(int sc) throws IOException {

			}

			public String encodeUrl(String url) {
				return response.encodeURL(url).toString();
			}

			public String encodeURL(String url) {
				return response.encodeURL(url).toString();
			}

			public String encodeRedirectUrl(String url) {
				return null;
			}

			public String encodeRedirectURL(String url) {
				return null;
			}

			public boolean containsHeader(String name) {
				return false;
			}

			public void addIntHeader(String name, int value) {

			}

			public void addHeader(String name, String value) {

			}

			public void addDateHeader(String name, long date) {

			}

			public void addCookie(Cookie cookie) {

			}

			public String getContentType() {
				return null;
			}

			public void setCharacterEncoding(String charset) {

			}

			@Override
			public String getCharacterEncoding() {
				return "UTF-8";
			}
		};
	}
699158
public void respond(String html) throws IOException, ServletException {
        response.setContentType("text/html");
        response.getWriter().print(html);
    }
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();
    }
  }
148311
@Override
  public void processResponse(CloseableHttpResponse response) throws IOException, UnexpectedResponseException {
    if (response.getStatusLine().getStatusCode() >= 400) {
      if (response.getEntity() != null) {
        throw new RuntimeException("Failed. " + EntityUtils.toString(response.getEntity())
                                 + " , response: " + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE));
      }
      throw new RuntimeException("Failed. Response: " + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE));
    }
  }