Exemplo n.º 1
0
 protected String setBrowserId(HttpServletRequest request, HttpServletResponse response) {
   String browser_id =
       Long.toHexString(request.getRemotePort())
           + Long.toString(getBayeux().randomLong(), 36)
           + Long.toString(System.currentTimeMillis(), 36)
           + Long.toString(request.getRemotePort(), 36);
   Cookie cookie = new Cookie(_browserId, browser_id);
   cookie.setPath("/");
   cookie.setMaxAge(-1);
   response.addCookie(cookie);
   return browser_id;
 }
Exemplo n.º 2
0
  /*
   * 获取用户的网络出口端口号  网络层配置
   */
  public static int getUserPort(HttpServletRequest request) {
    String portStr = request.getParameter("Ty_Remote_Port");
    if (StringUtil.isNullOrBlank(portStr)) {
      return request.getRemotePort();
    }

    try {
      return Integer.parseInt(portStr);
    } catch (NumberFormatException e) {
      return request.getRemotePort();
    }
  }
Exemplo n.º 3
0
  /**
   * Determine the port number that the client targeted with their {@code request}. If {@code
   * considerHostHeader} is {@code true}, and a HTTP {@code Host} header is present, the value of
   * the port in the header will be used as the port number. If the header is not present, or if
   * {@code considerHostHeader} is {@code false}, the port number will be determined using {@link
   * javax.servlet.http.HttpServletRequest#getRemotePort()} (if {@code considerRemotePort} is {@code
   * true}) followed by {@link javax.servlet.http.HttpServletRequest#getLocalPort()} (if {@code
   * considerLocalPort} is {@code true}).
   *
   * @param request the request
   * @return the port number targeted by the {@code request}
   */
  private int determinePort(HttpServletRequest request) {

    int portNumber = -1;

    // If there is a 'Host' header with the request, and if
    // we are supposed to consider it when determining the port,
    // then use it.

    // This is the best way to go, because the client is indicating
    // what host and port they targeted
    final String hostHeader = request.getHeader(HOST_HEADER);
    if (considerHostHeader && hostHeader != null && hostHeader.trim().length() != 0) {
      String temp = parseHostHeader(hostHeader)[1];
      if (temp != null) {
        portNumber = Integer.parseInt(temp);
      }
    }

    // Either the 'Host' header wasn't considered, or parsing it failed for some reason.

    if (portNumber == -1 && considerRemotePort) {
      portNumber = request.getRemotePort();
    }

    if (portNumber == -1 && considerLocalPort) {
      portNumber = request.getLocalPort();
    }

    return portNumber;
  }
Exemplo n.º 4
0
  private static Properties createCGIEnvironment(
      HttpServletRequest sreq, URI root_uri, File canonical_script_file) throws URISyntaxException {

    URI full_request_uri =
        new URI(
            sreq.getScheme(),
            null,
            sreq.getServerName(),
            sreq.getServerPort(),
            sreq.getRequestURI(),
            sreq.getQueryString(),
            null);

    Properties p =
        createCGIEnvironment(
            sreq.getMethod(),
            sreq.getProtocol(),
            full_request_uri,
            new InetSocketAddress(sreq.getLocalAddr(), sreq.getLocalPort()),
            new InetSocketAddress(sreq.getRemoteAddr(), sreq.getRemotePort()),
            sreq.getContextPath() + "/",
            root_uri,
            canonical_script_file);

    // Add request headers

    for (Enumeration e = sreq.getHeaderNames(); e.hasMoreElements(); ) {
      String h = (String) e.nextElement();
      p.setProperty(ESXX.httpToCGI(h), sreq.getHeader(h));
    }

    return p;
  }
Exemplo n.º 5
0
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
      LOG.debug(String.format("*****Servlet***** - Starting"));

      // HttpUtils.dump(request);

      LOG.debug(String.format("*****Servlet***** - getRequestURL:   %s", request.getRequestURL()));
      LOG.debug(String.format("*****Servlet***** - getRemotePort:   %s", request.getRemotePort()));
      LOG.debug(
          String.format(
              "*****Servlet***** - Authorization:   %s", request.getHeader("Authorization")));
      LOG.debug(
          String.format(
              "*****Servlet***** - SSL Session Id:  %s",
              request.getAttribute("javax.servlet.request.ssl_session_id")));

      X509Certificate[] certs =
          (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
      if (certs != null && certs.length > 0) {
        LOG.debug(
            String.format(
                "*****Servlet***** - X509Certificate: %s", certs[0].getSubjectDN().getName()));
      }

      response.setContentType("text/html;charset=utf-8");
      response.setStatus(HttpServletResponse.SC_OK);
      response.getWriter().println("<h1>Hello World Servlet</h1>");

      LOG.debug(String.format("*****Servlet***** - Done"));
    }
Exemplo n.º 6
0
 /**
  * Returns a string with the remote user address.
  *
  * @return user address
  */
 private String remote() {
   return new StringBuilder()
       .append('[')
       .append(req.getRemoteAddr())
       .append(':')
       .append(req.getRemotePort())
       .append(']')
       .toString();
 }
Exemplo n.º 7
0
  /**
   * @param request
   * @return
   */
  public static String getRequestUrl(HttpServletRequest request, int defaultPort) {
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(request.getProtocol());
    stringBuilder.append("://");
    stringBuilder.append(request.getServerName());
    if (request.getRemotePort() != defaultPort) {
      stringBuilder.append(':');
      stringBuilder.append(request.getRemotePort());
    }

    stringBuilder.append(request.getContextPath());
    stringBuilder.append(request.getServletPath());
    if (!KernelString.isEmpty(request.getQueryString())) {
      stringBuilder.append('?');
      stringBuilder.append(request.getQueryString());
    }

    return stringBuilder.toString();
  }
Exemplo n.º 8
0
  @Override
  public int getRemotePort() {
    HttpServletRequest request = (HttpServletRequest) getRequest();
    String headerValue;

    headerValue = request.getHeader(headerPrefix + "REMOTE_PORT");
    if (headerValue != null) {
      return Integer.parseInt(headerValue);
    } else {
      return request.getRemotePort();
    }
  }
Exemplo n.º 9
0
 private static String requestIpAndPortMessage(Message message) {
   if (message != null) {
     HttpServletRequest servletRequest =
         (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
     // pull out the ip and port of the incoming connection so we know
     // who is trying to get access
     if (servletRequest != null) {
       return " Request IP: "
           + servletRequest.getRemoteAddr()
           + ", Port: "
           + servletRequest.getRemotePort();
     }
   }
   return "";
 }
Exemplo n.º 10
0
 public void doGet(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException {
   PrintWriter out;
   res.setContentType("text/html; charset = EUC-KR");
   out = res.getWriter();
   out.println("<html>");
   out.println("<head><title>Request 정보출력 Servlet</title></head>");
   out.println("<body>");
   out.println("<h3>네트워크 관련 요청정보</h3>");
   out.println("<pre>");
   out.println("Request Scheme : " + req.getScheme());
   out.println("Server Name : " + req.getServerName());
   out.println("Server Address : " + req.getLocalAddr());
   out.println("Server Port : " + req.getServerPort());
   out.println("Client Address : " + req.getRemoteAddr());
   out.println("Client Host : " + req.getRemoteHost());
   out.println("Client Port : " + req.getRemotePort());
   out.println("</pre>");
   out.println("</body></html>");
 }
Exemplo n.º 11
0
  private String rand(final HttpServletRequest req, final String suffix)
      throws UnsupportedEncodingException {
    // Produce a random suffix that is difficult (or nearly impossible)
    // for an attacker to guess in advance. This reduces the risk that
    // an attacker could upload a *.class file and have us send a ZIP
    // that can be invoked through an applet tag in the victim's browser.
    //
    final MessageDigest md = Constants.newMessageDigest();
    final byte[] buf = new byte[8];

    NB.encodeInt32(buf, 0, req.getRemotePort());
    md.update(req.getRemoteAddr().getBytes("UTF-8"));
    md.update(buf, 0, 4);

    NB.encodeInt64(buf, 0, System.currentTimeMillis());
    md.update(buf, 0, 8);

    rng.nextBytes(buf);
    md.update(buf, 0, 8);

    return suffix + "-" + ObjectId.fromRaw(md.digest()).name();
  }
Exemplo n.º 12
0
 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
     throws Exception {
   if (!(handler instanceof org.springframework.web.method.HandlerMethod)) {
     return true;
   }
   HandlerMethod handlerMethod = (HandlerMethod) handler;
   Log logAnnotation = handlerMethod.getMethodAnnotation(Log.class);
   StringBuilder sb = new StringBuilder();
   if (null != logAnnotation) {
     sb.append(logAnnotation.value()).append(" ");
   }
   sb.append(" Ip:")
       .append(request.getRemoteHost())
       .append(" Port:")
       .append(request.getRemotePort())
       .append(" Url:")
       .append(request.getRequestURI())
       .append(" Content-Type:")
       .append(request.getContentType())
       .append(" Param:{");
   if ("application/json".equalsIgnoreCase(request.getContentType())) {
     //			sb.append(readStream(request.getReader()));
   } else {
     Map<String, String[]> paramMap = request.getParameterMap();
     Iterator<Map.Entry<String, String[]>> iterator = paramMap.entrySet().iterator();
     while (iterator.hasNext()) {
       Map.Entry<String, String[]> entry = iterator.next();
       sb.append(entry.getKey()).append("=");
       for (Object obj : entry.getValue()) {
         sb.append(obj).append(" ");
       }
     }
   }
   log.debug(sb.append("}").toString());
   return true;
 }
Exemplo n.º 13
0
 /**
  * Prepare text.
  *
  * @param request The HTTP request
  * @return Builder of text
  */
 private StringBuilder text(final HttpServletRequest request) {
   final StringBuilder text = new StringBuilder();
   text.append(Logger.format("date: %s\n", new Date()));
   this.append(text, request, "code");
   this.append(text, request, "message");
   this.append(text, request, "exception_type");
   this.append(text, request, "request_uri");
   final ServletContext ctx = this.getServletContext();
   text.append(Logger.format("servlet context path: \"%s\"\n", request.getContextPath()));
   text.append(
       Logger.format(
           "requested: %s (%s) at %s:%d\n",
           request.getRequestURL().toString(),
           request.getMethod(),
           request.getServerName(),
           request.getServerPort()));
   text.append(
       Logger.format(
           "request: %s, %d bytes\n", request.getContentType(), request.getContentLength()));
   text.append(
       Logger.format(
           "remote: %s:%d (%s)\n",
           request.getRemoteAddr(), request.getRemotePort(), request.getRemoteHost()));
   text.append(
       Logger.format(
           "servlet: \"%s\" (API %d.%d) at \"%s\"\n",
           ctx.getServletContextName(),
           ctx.getMajorVersion(),
           ctx.getMinorVersion(),
           ctx.getServerInfo()));
   text.append("headers:\n").append(ExceptionTrap.headers(request)).append('\n');
   text.append(
       Logger.format(
           "exception: %[exception]s\n", request.getAttribute("javax.servlet.error.exception")));
   return text;
 }
Exemplo n.º 14
0
 /**
  * Get the actual remote addr (which could be a load balancer, for example) as address:port.
  *
  * @param req
  * @return
  */
 public static String getActualRemoteAddress(HttpServletRequest req) {
   return req.getRemoteAddr() + ":" + req.getRemotePort();
 }
Exemplo n.º 15
0
  public TaskHttpServletRequest(HttpServletRequest wrapping, Task task) {
    this.session = wrapping.getSession();
    String location = wrapping.getParameter("url");

    cookies = wrapping.getCookies();
    characterEncoding = wrapping.getCharacterEncoding();
    authType = wrapping.getAuthType();
    headerNames = new Vector<String>();
    headers = new MultiMap();
    for (Enumeration e = wrapping.getHeaderNames(); e.hasMoreElements(); ) {
      String headerName = (String) e.nextElement();
      for (Enumeration f = wrapping.getHeaders(headerName); f.hasMoreElements(); ) {
        String headerValue = (String) f.nextElement();
        headers.add(headerName, headerValue);
      }
    }
    contextPath = wrapping.getContextPath();
    pathInfo = wrapping.getPathInfo();
    pathTranslated = wrapping.getPathTranslated();
    remoteUser = wrapping.getRemoteUser(); // TODO check if needed
    requestedSessionId = wrapping.getRequestedSessionId(); // TODO check if needed
    userPrincipal = wrapping.getUserPrincipal(); // TODO check if needed
    requestedSessionIdFromCookie = wrapping.isRequestedSessionIdFromCookie();
    requestedSessionIdFromURL = wrapping.isRequestedSessionIdFromURL();
    requestedSessionIdValid = wrapping.isRequestedSessionIdValid();
    localAddr = wrapping.getLocalAddr();
    localName = wrapping.getLocalName();
    localPort = wrapping.getLocalPort();
    locale = wrapping.getLocale();
    locales = new Vector<Locale>();
    for (Enumeration e = wrapping.getLocales();
        e.hasMoreElements();
        locales.add((Locale) e.nextElement())) ;
    protocol = wrapping.getProtocol();
    remoteAddr = wrapping.getRemoteAddr();
    remoteHost = wrapping.getRemoteHost();
    remotePort = wrapping.getRemotePort();
    scheme = wrapping.getScheme();
    serverName = wrapping.getServerName();
    serverPort = wrapping.getServerPort();
    secure = wrapping.isSecure();

    // Extract the query (everything after ?)
    int idx = location.indexOf('?');
    query = null;
    if (idx != -1) {
      query = location.substring(idx + 1);
    }

    // Extract the URI (everything before ?)
    uri = location;
    if (idx != -1) {
      uri = uri.substring(0, idx);
    }

    // Servlet path (same as URI?)
    servletPath = uri;

    // Extract parameters
    params = new Hashtable<String, String[]>();
    if (query != null) {
      StringTokenizer t = new StringTokenizer(query, "&");
      while (t.hasMoreTokens()) {
        String token = t.nextToken();
        idx = token.indexOf('=');
        String name = token;
        String val = null;
        if (idx != -1) {
          name = token.substring(0, idx);
          val = token.substring(idx + 1);
        } else {
          val = "";
        }
        String[] vals = params.get(name);
        if (vals == null) {
          vals = new String[] {val};
        } else {
          String[] nvals = new String[vals.length + 1];
          System.arraycopy(vals, 0, nvals, 0, vals.length);
          nvals[vals.length] = val;
          vals = nvals;
        }
        params.put(name, vals);
      }
    }

    // Initialise attributes
    attributes = new Hashtable<String, Object>();

    // Create the URL (the URL with protocol / host / post)
    try {
      URL u = new URL(new URL(wrapping.getRequestURL().toString()), uri);
      url = new StringBuffer(u.toExternalForm());
    } catch (MalformedURLException e) {
    }

    setAttribute(ATTR_TASK, task);
  }
Exemplo n.º 16
0
 /**
  * Returns a string with the remote user address.
  *
  * @return user address
  */
 private String address() {
   return req.getRemoteAddr() + ':' + req.getRemotePort();
 }
Exemplo n.º 17
0
  /** {@inheritDoc} */
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    HttpServletRequest rqst = (HttpServletRequest) request;
    HttpServletResponse rsp = (HttpServletResponse) response;

    if (LOG.isDebugEnabled()) {
      StringBuilder b =
          new StringBuilder("Request from ")
              .append(rqst.getRemoteHost())
              .append("/")
              .append(rqst.getRemoteAddr())
              .append(":")
              .append(rqst.getRemotePort());

      @SuppressWarnings("unchecked")
      Enumeration<String> e = rqst.getAttributeNames();
      for (; e.hasMoreElements(); ) {
        String attribute = e.nextElement();
        b.append("\n  " + attribute + " => " + rqst.getAttribute(attribute));
      }

      X509Certificate[] userCerts =
          (X509Certificate[]) rqst.getAttribute("javax.servlet.request.X509Certificate");
      if (userCerts != null)
        for (X509Certificate cert : userCerts)
          b.append(
              "\n Client certificate Subject Name is " + cert.getSubjectX500Principal().getName());

      b.append("\n The Scheme is " + rqst.getScheme());
      b.append("\n The Auth Type is " + rqst.getAuthType());
      b.append("\n The Path Info is " + rqst.getPathInfo());
      b.append("\n The Translated Path Info is " + rqst.getPathTranslated());
      b.append("\n The Context Path is " + rqst.getContextPath());
      b.append("\n The Query String is " + rqst.getQueryString());
      b.append("\n The Remote User is " + rqst.getRemoteUser());
      b.append("\n The User Principal is " + rqst.getUserPrincipal());
      b.append("\n The Request URI is " + rqst.getRequestURI());
      b.append("\n The Request URL is " + rqst.getRequestURL());
      b.append("\n The Servlet Path is " + rqst.getServletPath());

      LOG.debug(b.toString());
    }

    if (rqst.getScheme().equalsIgnoreCase("https")) {
      boolean isAuthorized = false;
      X509Certificate[] certs =
          (X509Certificate[]) rqst.getAttribute("javax.servlet.request.X509Certificate");
      if (certs == null || certs.length == 0) {
        rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No client SSL certificate received");
        return;
      }
      for (X509Certificate cert : certs) {
        try {
          cert.checkValidity();
        } catch (CertificateExpiredException e) {
          LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " expired");
          rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate expired");
          return;
        } catch (CertificateNotYetValidException e) {
          LOG.info(
              "Received cert for "
                  + cert.getSubjectX500Principal().getName()
                  + " is not yet valid");
          rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate is not yet valid");
          return;
        }
      }

      String[] tokens = certs[0].getSubjectX500Principal().getName().split("\\s*,\\s*");
      String userID = null;
      for (String s : tokens) {
        if (s.startsWith("CN=")) {
          userID = s;
          break;
        }
      }
      if (userID == null || userID.length() < 4) {
        LOG.info("Can't retrieve user ID from SSL certificate");
        rsp.sendError(
            HttpServletResponse.SC_FORBIDDEN, "Can't retrieve user ID from SSL certificate");
        return;
      }
      userID = userID.substring(3);

      String servletPath = rqst.getServletPath();
      if (HFTP_PATTERN.matcher(servletPath).matches()) {
        // request is an HSFTP request
        if (FILEPATH_PATTERN.matcher(servletPath).matches()) {
          // file path as part of the URL
          isAuthorized =
              checkPath(userID, certs[0], rqst.getPathInfo() != null ? rqst.getPathInfo() : "/");
        } else {
          // file path is stored in "filename" parameter
          isAuthorized = checkPath(userID, certs[0], rqst.getParameter("filename"));
        }
      } else if (RELOAD_PATTERN.matcher(servletPath).matches() && checkUser("Admin", certs[0])) {
        Configuration conf = new Configuration(false);
        conf.addResource("hdfsproxy-default.xml");
        Map<String, Set<Path>> permsMap = getPermMap(conf);
        Map<String, Set<BigInteger>> certsMap = getCertsMap(conf);
        if (permsMap == null || certsMap == null) {
          LOG.warn("Permission files reloading failed");
          rsp.sendError(
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Permission files reloading failed");
          return;
        }
        ProxyFilter.permsMap = permsMap;
        ProxyFilter.certsMap = certsMap;
        LOG.info("User permissions and user certs files reloaded");
        rsp.setStatus(HttpServletResponse.SC_OK);
        return;
      } else if (CLEAR_PATTERN.matcher(servletPath).matches() && checkUser("Admin", certs[0])) {
        ProxyUgiManager.clearCache();
        LOG.info("Ugi cache cleared");
        rsp.setStatus(HttpServletResponse.SC_OK);
        return;
      }

      if (!isAuthorized) {
        rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Unauthorized access");
        return;
      }
      // request is authorized, set ugi for servlets
      UnixUserGroupInformation ugi = ProxyUgiManager.getUgiForUser(userID);
      if (ugi == null) {
        LOG.info("Can't retrieve ugi for user " + userID);
        rsp.sendError(
            HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Can't retrieve ugi for user " + userID);
        return;
      }
      rqst.setAttribute("authorized.ugi", ugi);
    } else { // http request, set ugi for servlets, only for testing purposes
      String ugi = rqst.getParameter("ugi");
      rqst.setAttribute("authorized.ugi", new UnixUserGroupInformation(ugi.split(",")));
    }

    chain.doFilter(request, response);
  }
Exemplo n.º 18
0
 /**
  * Helper routine to dump the HTTP servlet request being serviced. Primarily for debugging.
  *
  * @param request - Servlet request (from a POST/GET/PUT/etc.)
  */
 public static void dumpRequest(HttpServletRequest request) {
   if (logger.isDebugEnabled()) {
     // special-case for receiving heartbeat - don't need to repeatedly output all of the
     // information
     // in multiple lines
     if (request.getMethod().equals("GET") && "hb".equals(request.getParameter("type"))) {
       logger.debug("GET type=hb : heartbeat received");
       return;
     }
     logger.debug(
         request.getMethod()
             + ":"
             + request.getRemoteAddr()
             + " "
             + request.getRemoteHost()
             + " "
             + request.getRemotePort());
     logger.debug(
         request.getLocalAddr() + " " + request.getLocalName() + " " + request.getLocalPort());
     Enumeration<String> en = request.getHeaderNames();
     logger.debug("Headers:");
     while (en.hasMoreElements()) {
       String element = en.nextElement();
       Enumeration<String> values = request.getHeaders(element);
       while (values.hasMoreElements()) {
         String value = values.nextElement();
         logger.debug(element + ":" + value);
       }
     }
     logger.debug("Attributes:");
     en = request.getAttributeNames();
     while (en.hasMoreElements()) {
       String element = en.nextElement();
       logger.debug(element + ":" + request.getAttribute(element));
     }
     logger.debug("ContextPath: " + request.getContextPath());
     if (request.getMethod().equals("PUT") || request.getMethod().equals("POST")) {
       // POST and PUT are allowed to have parameters in the content, but in our usage the
       // parameters
       // are always in the Query string.
       // More importantly, there are cases where the POST and PUT content is NOT parameters (e.g.
       // it
       // might contain a Policy file).
       // Unfortunately the request.getParameterMap method reads the content to see if there are
       // any
       // parameters,
       // and once the content is read it cannot be read again.
       // Thus for PUT and POST we must avoid reading the content here so that the main code can
       // read
       // it.
       logger.debug("Query String:" + request.getQueryString());
       try {
         if (request.getInputStream() == null) {
           logger.debug("Content: No content inputStream");
         } else {
           logger.debug("Content available: " + request.getInputStream().available());
         }
       } catch (Exception e) {
         logger.debug(
             "Content: inputStream exception: " + e.getMessage() + ";  (May not be relevant)");
       }
     } else {
       logger.debug("Parameters:");
       Map<String, String[]> params = request.getParameterMap();
       Set<String> keys = params.keySet();
       for (String key : keys) {
         String[] values = params.get(key);
         logger.debug(key + "(" + values.length + "): " + (values.length > 0 ? values[0] : ""));
       }
     }
     logger.debug("Request URL:" + request.getRequestURL());
   }
 }
Exemplo n.º 19
0
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // Redirects to /Start if the Startup/YorkRedirect address is attempted
    if (request.getRequestURI().equals("/mCalc0/Startup/YorkRedirect")) {
      response.sendRedirect("/mCalc0/Start");
      System.out.println("Redirect successful\n");
    }

    // Send message to the console
    System.out.println("doGet Hello World\n");
    response.setContentType("plain");
    // Output message in the browser
    response.getWriter().println("doGet Hello World\n");

    double i = extractParameter("interest", request) / 100; // interest in %
    double a = extractParameter("amortization", request); // amortization
    double p = extractParameter("principle", request); // principle
    DecimalFormat truncate = new DecimalFormat("#.##");

    PrintWriter out = response.getWriter();
    out.println(
        "\tThe Networking Layer\n"
            + "Server IP: "
            + request.getLocalAddr()
            + "\n"
            + "Server Port: "
            + request.getLocalPort()
            + "\n"
            + "Client IP: "
            + request.getRemoteAddr()
            + "\n"
            + "Client Port: "
            + request.getRemotePort()
            + "\n"
            + "\n"
            + "\tThe HTTP Layer\n"
            + "Request Protocol: "
            + request.getProtocol()
            + "\n"
            + "Request Method: "
            + request.getMethod()
            + "\n"
            + "Client's query string: ("
            + request.getQueryString()
            + ")\n"
            + "Named Request Parameter: "
            + request.getParameter("name")
            + "\n"
            + "\n\tThe URL\n"
            + "URI: "
            + request.getRequestURI()
            + "\n"
            + "Context Path: "
            + request.getContextPath()
            + "\n"
            + "Servlet/Extra Path: "
            + request.getServletPath()
            + "\n"
            + "Translated Path: "
            + request.getPathTranslated()
            + "\n"
            + "\n\tContext Parameter\n"
            + "name - "
            + request.getSession().getServletContext().getServletContextName()
            + "\n"
            + "value - "
            + request.getSession().getServletContext().getInitParameter("ContextParameter")
            + "\n"
            + "\n\tThe Computation"
            + "\n"
            + "Principle: "
            + p
            + "\n"
            + "Amortization: "
            + a
            + "\n"
            + "Interest: "
            + i
            + "\n"
            + "Monthly payment: $"
            + truncate.format(computePayment(p, i, a))
            + "\n");
    // Error to be caught
    // int x = 0;
    // int y = 20/x;

  }
Exemplo n.º 20
0
 @Override
 public int getRemotePort() {
   return originalRequest.getRemotePort();
 }
Exemplo n.º 21
0
  /**
   * Copy the HttpServletRequest content inside an AtmosphereRequest. By default the returned
   * AtmosphereRequest is not destroyable.
   *
   * @param request {@link HttpServletRequest}
   * @return an {@link AtmosphereRequest}
   */
  public static final AtmosphereRequest cloneRequest(
      HttpServletRequest request,
      boolean loadInMemory,
      boolean copySession,
      boolean isDestroyable,
      boolean createSession) {
    Builder b;
    HttpServletRequest r;

    Cookie[] cs = request.getCookies();
    Set<Cookie> hs = Collections.synchronizedSet(new HashSet());
    if (cs != null) {
      for (Cookie c : cs) {
        hs.add(c);
      }
    }

    boolean isWrapped = false;
    if (AtmosphereRequestImpl.class.isAssignableFrom(request.getClass())) {
      b = AtmosphereRequestImpl.class.cast(request).b;
      isWrapped = true;
    } else {
      b = new Builder();
      b.request(request);
    }

    HttpSession session = null;
    if (copySession) {
      session = request.getSession(createSession);
      if (session != null) {
        session = new FakeHttpSession(session);
      } else {
        session = new FakeHttpSession("", null, System.currentTimeMillis(), -1);
      }
    }

    b.servletPath(request.getServletPath())
        .pathInfo(request.getPathInfo())
        .contextPath(request.getContextPath())
        .requestURI(request.getRequestURI())
        .requestURL(request.getRequestURL().toString())
        .method(request.getMethod())
        .serverName(request.getServerName())
        .serverPort(request.getServerPort())
        .remoteAddr(request.getRemoteAddr())
        .remoteHost(request.getRemoteHost())
        .remotePort(request.getRemotePort())
        .destroyable(isDestroyable)
        .cookies(hs)
        .session(session)
        .principal(request.getUserPrincipal())
        .authType(request.getAuthType())
        .isSSecure(request.isSecure());

    if (loadInMemory) {
      String s =
          (String)
              attributeWithoutException(request, FrameworkConfig.THROW_EXCEPTION_ON_CLONED_REQUEST);
      boolean throwException = s != null && Boolean.parseBoolean(s);
      r = new NoOpsRequest(throwException);
      if (isWrapped) {
        load(b.request, b);
      } else {
        load(request, b);
      }
      b.request(r);
    }

    return isWrapped ? AtmosphereRequestImpl.class.cast(request) : b.build();
  }
Exemplo n.º 22
0
 @Override
 public int getRemotePort() {
   return _outerRequest.getRemotePort();
 }
  /** 重写父类方法,当登录成功后,重置失败标志 */
  @Override
  protected boolean onLoginSuccess(
      AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response)
      throws Exception {
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;

    SourceUsernamePasswordToken sourceUsernamePasswordToken = (SourceUsernamePasswordToken) token;
    User authAccount =
        userService.findByAuthTypeAndAuthUid(
            User.AuthTypeEnum.SYS, sourceUsernamePasswordToken.getUsername());
    Date now = DateUtils.currentDate();

    // 更新Access Token,并设置半年后过期
    if (StringUtils.isBlank(authAccount.getAccessToken())
        || authAccount.getAccessTokenExpireTime().before(now)) {
      authAccount.setAccessToken(UUID.randomUUID().toString());
      authAccount.setAccessTokenExpireTime(
          new DateTime(DateUtils.currentDate()).plusMonths(6).toDate());
      userService.save(authAccount);
    }

    // 写入登入记录信息
    UserLogonLog userLogonLog = new UserLogonLog();
    userLogonLog.setLogonTime(DateUtils.currentDate());
    userLogonLog.setLogonYearMonthDay(DateUtils.formatDate(userLogonLog.getLogoutTime()));
    userLogonLog.setRemoteAddr(httpServletRequest.getRemoteAddr());
    userLogonLog.setRemoteHost(httpServletRequest.getRemoteHost());
    userLogonLog.setRemotePort(httpServletRequest.getRemotePort());
    userLogonLog.setLocalAddr(httpServletRequest.getLocalAddr());
    userLogonLog.setLocalName(httpServletRequest.getLocalName());
    userLogonLog.setLocalPort(httpServletRequest.getLocalPort());
    userLogonLog.setServerIP(IPAddrFetcher.getGuessUniqueIP());
    userLogonLog.setHttpSessionId(httpServletRequest.getSession().getId());
    userLogonLog.setUserAgent(httpServletRequest.getHeader("User-Agent"));
    userLogonLog.setXforwardFor(IPAddrFetcher.getRemoteIpAddress(httpServletRequest));
    userLogonLog.setAuthType(authAccount.getAuthType());
    userLogonLog.setAuthUid(authAccount.getAuthUid());
    userLogonLog.setAuthGuid(authAccount.getAuthGuid());
    userService.userLogonLog(authAccount, userLogonLog);

    if (isMobileAppAccess(request)) {
      return true;
    } else {
      // 根据不同登录类型转向不同成功界面
      AuthUserDetails authUserDetails = AuthContextHolder.getAuthUserDetails();

      // 判断密码是否已到期,如果是则转向密码修改界面
      Date credentialsExpireTime = authAccount.getCredentialsExpireTime();
      if (credentialsExpireTime != null && credentialsExpireTime.before(DateUtils.currentDate())) {
        httpServletResponse.sendRedirect(
            httpServletRequest.getContextPath()
                + authUserDetails.getUrlPrefixBySource()
                + "/profile/credentials-expire");
        return false;
      }

      // 如果是强制转向指定successUrl则清空SavedRequest
      if (forceSuccessUrl) {
        WebUtils.getAndClearSavedRequest(httpServletRequest);
      }

      return super.onLoginSuccess(token, subject, request, httpServletResponse);
    }
  }
  public boolean authenticateRequest(
      ServletContext context, HttpServletRequest sreq, HttpServletResponse sresp)
      throws IOException, ServletException {
    // Check if there is an authorization header with an NTLM security blob
    String authHdr = sreq.getHeader(AUTHORIZATION);
    boolean reqAuth = false;

    // Check if an NTLM authorization header was received

    if (authHdr != null) {
      // Check for an NTLM authorization header

      if (authHdr.startsWith(AUTH_NTLM)) reqAuth = true;
      else if (authHdr.startsWith("Negotiate")) {
        if (getLogger().isDebugEnabled())
          getLogger().debug("Received 'Negotiate' from client, may be SPNEGO/Kerberos logon");

        // Restart the authentication

        restartLoginChallenge(context, sreq, sresp);
        return false;
      } else if (isFallbackEnabled()) {
        return performFallbackAuthentication(context, sreq, sresp);
      }
    }

    // Check if the user is already authenticated
    SessionUser user = getSessionUser(context, sreq, sresp, true);

    // If the user has been validated and we do not require re-authentication then continue to
    // the next filter
    if (user != null && reqAuth == false) {
      // Filter validate hook
      onValidate(context, sreq, sresp, new TicketCredentials(user.getTicket()));

      if (getLogger().isDebugEnabled())
        getLogger().debug("Authentication not required (user), chaining ...");

      // Chain to the next filter
      return true;
    }

    // Check if the login page is being accessed, do not intercept the login page
    if (hasLoginPage() && sreq.getRequestURI().endsWith(getLoginPage()) == true) {
      if (getLogger().isDebugEnabled()) getLogger().debug("Login page requested, chaining ...");

      // Chain to the next filter
      return true;
    }

    // Check if the browser is Opera, if so then display the login page as Opera does not
    // support NTLM and displays an error page if a request to use NTLM is sent to it
    String userAgent = sreq.getHeader("user-agent");
    if (userAgent != null && userAgent.indexOf("Opera ") != -1) {
      if (getLogger().isDebugEnabled())
        getLogger().debug("Opera detected, redirecting to login page");

      // If there is no login page configured (WebDAV) then just keep requesting the user details
      // from the client

      if (hasLoginPage()) redirectToLoginPage(sreq, sresp);
      else restartLoginChallenge(context, sreq, sresp);
      return false;
    }

    // Check the authorization header
    if (authHdr == null) {
      // Check for a ticket based logon, if enabled

      if (allowsTicketLogons()) {
        // Check if the request includes an authentication ticket

        if (checkForTicketParameter(context, sreq, sresp)) {

          // Authentication was bypassed using a ticket parameter
          return true;
        }
      }

      // DEBUG

      if (getLogger().isDebugEnabled())
        getLogger()
            .debug(
                "New NTLM auth request from "
                    + sreq.getRemoteHost()
                    + " ("
                    + sreq.getRemoteAddr()
                    + ":"
                    + sreq.getRemotePort()
                    + ") SID:"
                    + sreq.getSession().getId());

      // Send back a request for NTLM authentication
      restartLoginChallenge(context, sreq, sresp);
      return false;
    } else {
      // Decode the received NTLM blob and validate
      final byte[] ntlmByts = Base64.decodeBase64(authHdr.substring(5).getBytes());
      int ntlmTyp = NTLMMessage.isNTLMType(ntlmByts);
      if (ntlmTyp == NTLM.Type1) {
        // Process the type 1 NTLM message
        Type1NTLMMessage type1Msg = new Type1NTLMMessage(ntlmByts);
        processType1(type1Msg, sreq, sresp);
        return false;
      } else if (ntlmTyp == NTLM.Type3) {
        // Process the type 3 NTLM message
        Type3NTLMMessage type3Msg = new Type3NTLMMessage(ntlmByts);
        return processType3(type3Msg, context, sreq, sresp);
      } else {
        if (getLogger().isDebugEnabled())
          getLogger().debug("NTLM blob not handled, redirecting to login page.");

        if (hasLoginPage()) redirectToLoginPage(sreq, sresp);
        else restartLoginChallenge(context, sreq, sresp);
        return false;
      }
    }
  }
  protected boolean loginUser(
      FilterChain chain,
      HttpServletRequest httpRequest,
      HttpServletResponse httpResponse,
      VOUser voUser,
      AuthorizationRequestData rdo,
      IdentityService identityService)
      throws ServletException, IOException {

    HttpSession session = httpRequest.getSession();
    boolean onlyServiceLogin = BesServletRequestReader.onlyServiceLogin(session);
    String forwardUrl = (String) session.getAttribute(Constants.SESS_ATTR_FORWARD_URL);
    SessionBean sessionBean = (SessionBean) session.getAttribute(Constants.SESS_ATTR_SESSION_BEAN);

    ServiceAccess serviceAccess = ServiceAccess.getServiceAcccessFor(session);

    if (onlyServiceLogin) {
      session.setAttribute(Constants.SESS_ATTR_ONLY_SERVICE_LOGIN, Boolean.TRUE);
    }

    if (!ADMStringUtils.isBlank(forwardUrl)) {
      session.setAttribute(Constants.SESS_ATTR_FORWARD_URL, forwardUrl);
    }

    if (sessionBean != null) {
      session.setAttribute(Constants.SESS_ATTR_SESSION_BEAN, sessionBean);
    }

    if (!ADMStringUtils.isBlank(rdo.getMarketplaceId())) {
      session.setAttribute(Constants.REQ_PARAM_MARKETPLACE_ID, rdo.getMarketplaceId());
    }

    // authenticate the user
    // IMPORTANT: Changes to this method must also be applied to
    // UserBean.login()
    try {
      serviceAccess.login(voUser, rdo.getPassword(), httpRequest, httpResponse);
    } catch (CommunicationException e) {
      handleCommunicationException(chain, httpRequest, httpResponse, rdo);
      return false;
    } catch (LoginException e) {
      logger.logInfo(
          Log4jLogger.ACCESS_LOG,
          LogMessageIdentifier.INFO_USER_LOGIN_INVALID,
          httpRequest.getRemoteHost(),
          Integer.toString(httpRequest.getRemotePort()),
          StringUtils.isNotBlank(voUser.getUserId()) ? voUser.getUserId() : "",
          IPResolver.resolveIpAddress(httpRequest),
          voUser.getTenantId());
      try {
        voUser = identityService.getUser(voUser);
      } catch (ObjectNotFoundException e1) {
        handleUserNotRegistered(chain, httpRequest, httpResponse, rdo);
        return false;
      } catch (SaaSApplicationException e1) {
        setErrorAttributesAndForward(errorPage, httpRequest, httpResponse, e1);
        return false;
      }

      if (voUser.getStatus() != null
          && voUser.getStatus().getLockLevel() > UserAccountStatus.LOCK_LEVEL_LOGIN) {
        httpRequest.setAttribute(Constants.REQ_ATTR_ERROR_KEY, BaseBean.ERROR_USER_LOCKED);
        forward(errorPage, httpRequest, httpResponse);
        return false;
      }

      handleLoginException(chain, httpRequest, httpResponse, rdo);
      return false;
    }

    if (!rdo.isMarketplace()
        && !rdo.isAccessToServiceUrl() // BE09588 Login is OK if a
        // service is accessed, whose
        // subscription has no
        // marketplace
        && identityService.getCurrentUserDetails().getOrganizationRoles().size() == 1
        && identityService
            .getCurrentUserDetails()
            .getOrganizationRoles()
            .contains(OrganizationRoleType.CUSTOMER)) {
      if (ADMStringUtils.isBlank(rdo.getMarketplaceId())) {
        if (redirectToMpUrl(httpRequest, httpResponse)) {
          setupUserDetail(httpRequest, rdo, identityService, session);
          return false;
        } else {
          httpRequest.setAttribute(
              Constants.REQ_ATTR_ERROR_KEY, BaseBean.ERROR_INVALID_MARKETPLACE_URL);
          forward(BaseBean.MARKETPLACE_ERROR_PAGE, httpRequest, httpResponse);
        }
      } else {
        setupUserDetail(httpRequest, rdo, identityService, session);
        forward(BaseBean.MARKETPLACE_START_SITE, httpRequest, httpResponse);
      }
      return false;
    }

    // get the service again because the credentials have been
    // changed (important for WS usage)
    identityService = serviceAccess.getService(IdentityService.class);
    try {
      identityService.refreshLdapUser();
    } catch (ValidationException e) {
      logger.logDebug(
          "Refresh of LDAP user failed, most likely due to missing/wrong LDAP settings");
    }

    logger.logInfo(
        Log4jLogger.ACCESS_LOG,
        LogMessageIdentifier.INFO_USER_LOGIN_SUCCESS,
        StringUtils.isNotBlank(voUser.getUserId()) ? voUser.getUserId() : "",
        IPResolver.resolveIpAddress(httpRequest),
        voUser.getTenantId());
    return true;
  }
  @SuppressWarnings("unchecked")
  private String processException(ModelMap model, HttpServletRequest request, String typ) {
    // Informationen bei aufgetretenen Fehlerseiten loggen
    Integer errorCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
    if (errorCode != null
        && !contains(request.getHeader("user-agent"), ignoredUserAgentForErrorLog)
        && !containsRegex(
            (String) request.getAttribute("javax.servlet.forward.request_uri"),
            ignoredRequestPathRegexForErrorLog)) {
      // Daten ermitteln
      String exceptionId = UUID.randomUUID().toString().replaceAll(":", "_");
      Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
      String requestPath = (String) request.getAttribute("javax.servlet.forward.request_uri");
      String queryString = (String) request.getAttribute("javax.servlet.forward.query_string");
      String forwardRequestPath = (String) request.getAttribute("javax.servlet.forward.path_info");
      String login = null;
      try {
        login = SecurityContextHolder.getContext().getAuthentication().getName();
      } catch (Exception e) {
      }

      // Fehlermeldung zusammensetzen
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      PrintWriter pw = new PrintWriter(bos, true);
      pw.println("#################### ERROR_PAGE " + errorCode + " [BEGIN] ####################");

      pw.println("  exceptionId=" + exceptionId);

      pw.println("  REQUEST");
      pw.println("    method=" + request.getMethod());
      pw.println("    requestPath=" + requestPath);
      pw.println("    queryString=" + queryString);
      for (Enumeration<String> iter = request.getParameterNames(); iter.hasMoreElements(); ) {
        String name = iter.nextElement();
        String value = request.getParameter(name);
        pw.println("    parameter: " + name + "=" + value);
      }

      pw.println("  REQUESTHEADER");
      for (Enumeration<String> iter = request.getHeaderNames(); iter.hasMoreElements(); ) {
        String name = iter.nextElement();
        String value = request.getHeader(name);
        pw.println("    " + name + "=" + value);
      }

      pw.println("  REMOTE");
      pw.println("    remoteAddr=" + request.getRemoteAddr());
      pw.println("    remoteHost=" + request.getRemoteHost());
      pw.println("    remotePort=" + request.getRemotePort());
      pw.println("    remoteUser="******"  forwardRequestPath=" + forwardRequestPath);
      pw.println("  login="******"\n---------- StackTrace ---------------------------\n");
        exception.printStackTrace(pw);

        Throwable ex = exception;
        while (ex != null) {
          // SQLException NextException
          if (ex instanceof SQLException && ((SQLException) ex).getNextException() != null) {
            pw.println("\n---------- SQLException NextException ------------\n");
            ((SQLException) ex).getNextException().printStackTrace(pw);
          }

          ex = ex.getCause();
        }
        pw.println("\n-------------------------------------------------\n");
      }

      // Fehlermeldung ins Log schreiben
      String errorText = new String(bos.toByteArray());
      pw.println("#################### ERROR_PAGE " + errorCode + " [END] ####################");
      logger.error("\n\n" + errorText);

      model.addAttribute("exceptionId", exceptionId);
      model.addAttribute("exceptionText", errorText);
    }
    model.addAttribute("showFehlerDetails", settingsService.getShowFehlerDetails());
    model.addAttribute("bugTrackingUrl", settingsService.getBugTrackingUrl());
    return typ;
  }
Exemplo n.º 27
0
 @Override
 public int getRemotePort() {
   return request.getRemotePort();
 }
  /**
   * Creates REST request.
   *
   * @param cmd Command.
   * @param params Parameters.
   * @param req Servlet request.
   * @return REST request.
   * @throws IgniteCheckedException If creation failed.
   */
  @Nullable
  private GridRestRequest createRequest(
      GridRestCommand cmd, Map<String, Object> params, HttpServletRequest req)
      throws IgniteCheckedException {
    GridRestRequest restReq;

    switch (cmd) {
      case GET_OR_CREATE_CACHE:
      case DESTROY_CACHE:
        {
          GridRestCacheRequest restReq0 = new GridRestCacheRequest();

          restReq0.cacheName((String) params.get("cacheName"));

          restReq = restReq0;

          break;
        }

      case ATOMIC_DECREMENT:
      case ATOMIC_INCREMENT:
        {
          DataStructuresRequest restReq0 = new DataStructuresRequest();

          restReq0.key(params.get("key"));
          restReq0.initial(longValue("init", params, null));
          restReq0.delta(longValue("delta", params, null));

          restReq = restReq0;

          break;
        }

      case CACHE_CONTAINS_KEY:
      case CACHE_CONTAINS_KEYS:
      case CACHE_GET:
      case CACHE_GET_ALL:
      case CACHE_GET_AND_PUT:
      case CACHE_GET_AND_REPLACE:
      case CACHE_PUT_IF_ABSENT:
      case CACHE_GET_AND_PUT_IF_ABSENT:
      case CACHE_PUT:
      case CACHE_PUT_ALL:
      case CACHE_REMOVE:
      case CACHE_REMOVE_VALUE:
      case CACHE_REPLACE_VALUE:
      case CACHE_GET_AND_REMOVE:
      case CACHE_REMOVE_ALL:
      case CACHE_ADD:
      case CACHE_CAS:
      case CACHE_METRICS:
      case CACHE_SIZE:
      case CACHE_METADATA:
      case CACHE_REPLACE:
      case CACHE_APPEND:
      case CACHE_PREPEND:
        {
          GridRestCacheRequest restReq0 = new GridRestCacheRequest();

          String cacheName = (String) params.get("cacheName");

          restReq0.cacheName(F.isEmpty(cacheName) ? null : cacheName);
          restReq0.key(params.get("key"));
          restReq0.value(params.get("val"));
          restReq0.value2(params.get("val2"));

          Object val1 = params.get("val1");

          if (val1 != null) restReq0.value(val1);

          restReq0.cacheFlags(intValue("cacheFlags", params, 0));
          restReq0.ttl(longValue("exp", params, null));

          if (cmd == CACHE_GET_ALL
              || cmd == CACHE_PUT_ALL
              || cmd == CACHE_REMOVE_ALL
              || cmd == CACHE_CONTAINS_KEYS) {
            List<Object> keys = values("k", params);
            List<Object> vals = values("v", params);

            if (keys.size() < vals.size())
              throw new IgniteCheckedException(
                  "Number of keys must be greater or equals to number of values.");

            Map<Object, Object> map = U.newHashMap(keys.size());

            Iterator<Object> keyIt = keys.iterator();
            Iterator<Object> valIt = vals.iterator();

            while (keyIt.hasNext()) map.put(keyIt.next(), valIt.hasNext() ? valIt.next() : null);

            restReq0.values(map);
          }

          restReq = restReq0;

          break;
        }

      case TOPOLOGY:
      case NODE:
        {
          GridRestTopologyRequest restReq0 = new GridRestTopologyRequest();

          restReq0.includeMetrics(Boolean.parseBoolean((String) params.get("mtr")));
          restReq0.includeAttributes(Boolean.parseBoolean((String) params.get("attr")));

          restReq0.nodeIp((String) params.get("ip"));

          restReq0.nodeId(uuidValue("id", params));

          restReq = restReq0;

          break;
        }

      case EXE:
      case RESULT:
      case NOOP:
        {
          GridRestTaskRequest restReq0 = new GridRestTaskRequest();

          restReq0.taskId((String) params.get("id"));
          restReq0.taskName((String) params.get("name"));

          restReq0.params(values("p", params));

          restReq0.async(Boolean.parseBoolean((String) params.get("async")));

          restReq0.timeout(longValue("timeout", params, 0L));

          restReq = restReq0;

          break;
        }

      case LOG:
        {
          GridRestLogRequest restReq0 = new GridRestLogRequest();

          restReq0.path((String) params.get("path"));

          restReq0.from(intValue("from", params, -1));
          restReq0.to(intValue("to", params, -1));

          restReq = restReq0;

          break;
        }

      case NAME:
      case VERSION:
        {
          restReq = new GridRestRequest();

          break;
        }

      case EXECUTE_SQL_QUERY:
      case EXECUTE_SQL_FIELDS_QUERY:
        {
          RestQueryRequest restReq0 = new RestQueryRequest();

          restReq0.sqlQuery((String) params.get("qry"));

          restReq0.arguments(values("arg", params).toArray());

          restReq0.typeName((String) params.get("type"));

          String pageSize = (String) params.get("pageSize");

          if (pageSize != null) restReq0.pageSize(Integer.parseInt(pageSize));

          restReq0.cacheName((String) params.get("cacheName"));

          if (cmd == EXECUTE_SQL_QUERY) restReq0.queryType(RestQueryRequest.QueryType.SQL);
          else restReq0.queryType(RestQueryRequest.QueryType.SQL_FIELDS);

          restReq = restReq0;

          break;
        }

      case EXECUTE_SCAN_QUERY:
        {
          RestQueryRequest restReq0 = new RestQueryRequest();

          restReq0.sqlQuery((String) params.get("qry"));

          String pageSize = (String) params.get("pageSize");

          if (pageSize != null) restReq0.pageSize(Integer.parseInt(pageSize));

          restReq0.cacheName((String) params.get("cacheName"));

          restReq0.className((String) params.get("className"));

          restReq0.queryType(RestQueryRequest.QueryType.SCAN);

          restReq = restReq0;

          break;
        }

      case FETCH_SQL_QUERY:
        {
          RestQueryRequest restReq0 = new RestQueryRequest();

          String qryId = (String) params.get("qryId");

          if (qryId != null) restReq0.queryId(Long.parseLong(qryId));

          String pageSize = (String) params.get("pageSize");

          if (pageSize != null) restReq0.pageSize(Integer.parseInt(pageSize));

          restReq0.cacheName((String) params.get("cacheName"));

          restReq = restReq0;

          break;
        }

      case CLOSE_SQL_QUERY:
        {
          RestQueryRequest restReq0 = new RestQueryRequest();

          String qryId = (String) params.get("qryId");

          if (qryId != null) restReq0.queryId(Long.parseLong(qryId));

          restReq0.cacheName((String) params.get("cacheName"));

          restReq = restReq0;

          break;
        }

      default:
        throw new IgniteCheckedException("Invalid command: " + cmd);
    }

    restReq.address(new InetSocketAddress(req.getRemoteAddr(), req.getRemotePort()));

    restReq.command(cmd);

    if (params.containsKey("ignite.login") || params.containsKey("ignite.password")) {
      SecurityCredentials cred =
          new SecurityCredentials(
              (String) params.get("ignite.login"), (String) params.get("ignite.password"));

      restReq.credentials(cred);
    }

    String clientId = (String) params.get("clientId");

    try {
      if (clientId != null) restReq.clientId(UUID.fromString(clientId));
    } catch (Exception ignored) {
      // Ignore invalid client id. Rest handler will process this logic.
    }

    String destId = (String) params.get("destId");

    try {
      if (destId != null) restReq.destinationId(UUID.fromString(destId));
    } catch (IllegalArgumentException ignored) {
      // Don't fail - try to execute locally.
    }

    String sesTokStr = (String) params.get("sessionToken");

    try {
      if (sesTokStr != null) restReq.sessionToken(U.hexString2ByteArray(sesTokStr));
    } catch (IllegalArgumentException ignored) {
      // Ignore invalid session token.
    }

    return restReq;
  }
 @Override
 public InetSocketAddress getRemoteAddress() {
   return new InetSocketAddress(_req.getRemoteAddr(), _req.getRemotePort());
 }