Exemplo n.º 1
0
 public void service(HttpServletRequest request, HttpServletResponse response)
     throws ServletException {
   try {
     ConnectionPool conPool = getConnectionPool();
     if (!realAuthentication(request, conPool)) {
       String queryString = request.getQueryString();
       if (request.getQueryString() == null) {
         queryString = "";
       }
       // if user is not authenticated send to signin
       response.sendRedirect(
           response.encodeRedirectURL(URLAUTHSIGNIN + "?" + URLBUY + "?" + queryString));
     } else {
       response.setHeader("Cache-Control", "no-cache");
       response.setHeader("Expires", "0");
       response.setHeader("Pragma", "no-cache");
       response.setContentType("text/html");
       String errorMessage = processRequest(request, response, conPool);
       if (errorMessage != null) {
         request.setAttribute(StringInterface.ERRORPAGEATTR, errorMessage);
         RequestDispatcher rd = getServletContext().getRequestDispatcher(PATHUSERERROR);
         rd.include(request, response);
       }
     }
   } catch (Exception e) {
     throw new ServletException(e);
   }
 }
Exemplo n.º 2
0
  /**
   * Constructor.
   *
   * @param rq request
   * @param rs response
   * @throws IOException I/O exception
   */
  public HTTPContext(final HttpServletRequest rq, final HttpServletResponse rs) throws IOException {

    req = rq;
    res = rs;
    final String m = rq.getMethod();
    method = HTTPMethod.get(m);

    final StringBuilder uri = new StringBuilder(req.getRequestURL());
    final String qs = req.getQueryString();
    if (qs != null) uri.append('?').append(qs);
    log(false, m, uri);

    // set UTF8 as default encoding (can be overwritten)
    res.setCharacterEncoding(UTF8);

    segments = toSegments(req.getPathInfo());
    path = join(0);

    user = System.getProperty(DBUSER);
    pass = System.getProperty(DBPASS);

    // set session-specific credentials
    final String auth = req.getHeader(AUTHORIZATION);
    if (auth != null) {
      final String[] values = auth.split(" ");
      if (values[0].equals(BASIC)) {
        final String[] cred = Base64.decode(values[1]).split(":", 2);
        if (cred.length != 2) throw new LoginException(NOPASSWD);
        user = cred[0];
        pass = cred[1];
      } else {
        throw new LoginException(WHICHAUTH, values[0]);
      }
    }
  }
Exemplo n.º 3
0
 public DownloadRequest(ServletContext context, HttpServletRequest request) {
   _context = context;
   _httpRequest = request;
   _path = request.getRequestURI();
   _encoding = request.getHeader(ACCEPT_ENCODING);
   String context_path = request.getContextPath();
   if (context_path != null) _path = _path.substring(context_path.length());
   if (_path == null) _path = request.getServletPath(); // This works for *.<ext> invocations
   if (_path == null) _path = "/"; // No path given
   _path = _path.trim();
   if (_context != null && !_path.endsWith("/")) {
     String realPath = _context.getRealPath(_path);
     // fix for 4474021 - getRealPath might returns NULL
     if (realPath != null) {
       File f = new File(realPath);
       if (f != null && f.exists() && f.isDirectory()) {
         _path += "/";
       }
     }
   }
   // Append default file for a directory
   if (_path.endsWith("/")) _path += "launch.jnlp";
   _version = getParameter(request, ARG_VERSION_ID);
   _currentVersionId = getParameter(request, ARG_CURRENT_VERSION_ID);
   _os = getParameterList(request, ARG_OS);
   _arch = getParameterList(request, ARG_ARCH);
   _locale = getParameterList(request, ARG_LOCALE);
   _knownPlatforms = getParameterList(request, ARG_KNOWN_PLATFORMS);
   String platformVersion = getParameter(request, ARG_PLATFORM_VERSION_ID);
   _isPlatformRequest = (platformVersion != null);
   if (_isPlatformRequest) _version = platformVersion;
   _query = request.getQueryString();
   _testJRE = getParameter(request, TEST_JRE);
 }
Exemplo n.º 4
0
  /**
   * The method redirects the user to the authentication module if he is not authenticated; else
   * redirects him back to the original referrer.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception ServletException if an input or output error is detected when the servlet handles
   *     the GET request
   * @exception IOException if the request for the GET could not be handled
   */
  private void doGetPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (debug.messageEnabled()) {
      debug.message(
          "CDCClientServlet.doGetPost:Query String received= " + request.getQueryString());
    }
    String gotoParameter = request.getParameter(GOTO_PARAMETER);
    String targetParameter = request.getParameter(TARGET_PARAMETER);
    if (targetParameter == null) {
      targetParameter = request.getParameter(TARGET_PARAMETER.toLowerCase());
    }
    // if check if goto ot target have invalid strings, to avoid
    // accepting invalid injected javascript.

    if ((gotoParameter != null) || (targetParameter != null)) {
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet:doGetPost():validating goto: "
                + gotoParameter
                + " and target: "
                + targetParameter);
      }
      for (String invalidStr : INVALID_SET) {
        if (gotoParameter != null && gotoParameter.toLowerCase().contains(invalidStr)) {
          showError(response, SERVER_ERROR_STR_MATCH + "GOTO parameter has invalid characters");
          return;
        }
        if (targetParameter != null && targetParameter.toLowerCase().contains(invalidStr)) {
          showError(response, SERVER_ERROR_STR_MATCH + "TARGET parameter has invalid characters");
          return;
        }
      }
    }

    /* Steps to be done
     * 1. If no SSOToken or policy advice present , forward to
     *    authentication.
     * 2. If SSOToken is valid tunnel request to the backend AM's
     *    CDCServlet and Form POST the received response to the agent.
     */
    // Check for a valid SSOToken in the request. If SSOToken is not found
    // or if the token is invalid, redirect the user for authentication.
    // Also re-direct if there are policy advices in the query string
    SSOToken token = getSSOToken(request, response);
    // collect advices in parsedRequestParams[0] String and rest of params
    // other than original goto url in parsedRequestParams[1] String.
    String[] parsedRequestParams = parseRequestParams(request);

    if ((token == null) || (parsedRequestParams[0] != null)) {
      // Redirect to authentication
      redirectForAuthentication(request, response, parsedRequestParams[0], parsedRequestParams[1]);
    } else {

      // tunnel request to AM
      // send the request to the CDCServlet of AM where the session
      // was created.
      sendAuthnRequest(request, response, token);
    }
  }
Exemplo n.º 5
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    System.out.println("queryString: " + request.getQueryString());
    out.println("FILTER-QUERYSTRING:" + (request.getQueryString() != null ? "PASS" : "FAIL"));
  }
Exemplo n.º 6
0
  /**
   * The method redirects the user to the authentication module if he is not authenticated; else
   * redirects him back to the original referrer.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception ServletException if an input or output error is detected when the servlet handles
   *     the GET request
   * @exception IOException if the request for the GET could not be handled
   */
  private void doGetPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (debug.messageEnabled()) {
      debug.message(
          "CDCClientServlet.doGetPost:Query String received= " + request.getQueryString());
    }
    String gotoParameter = request.getParameter(GOTO_PARAMETER);
    String targetParameter = request.getParameter(TARGET_PARAMETER);
    if (targetParameter == null) {
      targetParameter = request.getParameter(TARGET_PARAMETER.toLowerCase());
    }
    // if check if goto ot target have invalid strings, to avoid
    // accepting invalid injected javascript.

    if ((gotoParameter != null) || (targetParameter != null)) {
      debug.message("CDCServlet:doGetPost():goto or target is not null");
      for (Iterator it = invalidSet.iterator(); it.hasNext(); ) {
        String invalidStr = (String) it.next();
        if ((gotoParameter != null) && (gotoParameter.toLowerCase().indexOf(invalidStr) != -1)) {
          showError(response, "GOTO parameter has invalid " + "characters");
          return;
        }
        if ((targetParameter != null)
            && (targetParameter.toLowerCase().indexOf(invalidStr) != -1)) {
          showError(response, "TARGET parameter has invalid " + "characters");
          return;
        }
      }
    }

    /* Steps to be done
     * 1. If no SSOToken or policy advice present , forward to
     *    authentication.
     * 2. If SSOToken is valid tunnel request to the backend AM's
     *    CDCServlet and Form POST the received response to the agent.
     */
    // Check for a valid SSOToken in the request. If SSOToken is not found
    // or if the token is invalid, redirect the user for authentication.
    // Also re-direct if there are policy advices in the query string
    SSOToken token = getSSOToken(request, response);
    if (token == null) {
      policyAdviceList = null;
    }
    // collect advices in policyAdviceList String and rest of params
    // other than original goto url in "requestParams" String.
    parseRequestParams(request);
    if ((token == null) || (policyAdviceList != null)) {
      // Redirect to authentication
      redirectForAuthentication(request, response);
    } else {

      // tunnel request to AM
      // send the request to the CDCServlet of AM where the session
      // was created.
      sendAuthnRequest(request, response, token);
    }
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    System.out.println(
        "MyProtectedServlet.processRequest "
            + request.getRequestURI()
            + " "
            + request.getQueryString());

    String myUrl = request.getRequestURI();
    if (myUrl.indexOf("login") >= 0) {
      login(request, response);
      return;
    } else if (myUrl.indexOf("redirect") >= 0) {
      redirect(request, response);
      return;
    }

    if (request.getRemoteUser() == null) {
      String callUrl = request.getRequestURI();
      String query = request.getQueryString();
      if (query != null) {
        callUrl = callUrl + "?" + query;
      }
      String nextEncUrl = java.net.URLEncoder.encode(callUrl);
      String redirectUrl =
          request.getContextPath() + "/application/redirect?nextencurl=" + nextEncUrl;
      response.sendRedirect(redirectUrl);
    } else {
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet MyProtectedServlet</title>");
      out.println("</head>");
      out.println("<body>");
      out.println("<h1>Servlet MyProtectedServlet at " + request.getContextPath() + "</h1>");
      out.println("</body>");
      out.println("</html>");

      out.close();
    }
  }
Exemplo n.º 8
0
  /**
   * Forward this request to the CatalogServices servlet ("/catalog.html").
   *
   * @param req request
   * @param res response
   * @throws IOException on IO error
   * @throws ServletException other error
   */
  public static void forwardToCatalogServices(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {

    String reqs = "catalog=" + getReletiveURL(req);
    String query = req.getQueryString();
    if (query != null) reqs = reqs + "&" + query;
    log.info("forwardToCatalogServices(): request string = \"/catalog.html?" + reqs + "\"");

    // dispatch to CatalogHtml servlet
    RequestForwardUtils.forwardRequestRelativeToCurrentContext("/catalog.html?" + reqs, req, res);
  }
Exemplo n.º 9
0
 /**
  * Show the pieces of the request, for debugging
  *
  * @param req the HttpServletRequest
  * @return parsed request
  */
 public static String getRequestParsed(HttpServletRequest req) {
   return req.getRequestURI()
       + " = "
       + req.getContextPath()
       + "(context), "
       + req.getServletPath()
       + "(servletPath), "
       + req.getPathInfo()
       + "(pathInfo), "
       + req.getQueryString()
       + "(query)";
 }
  public URL getUrl(HttpServletRequest req) throws IOException {
    String servletPath = req.getServletPath();

    String selectedServerFullPath = getServerAddress(servletPath);
    String queryString = req.getQueryString();
    String newUrl = "";
    HttpSession session = req.getSession(false);

    newUrl = selectedServerFullPath + servletPath;

    if (req.getRequestedSessionId() != null)
      newUrl = newUrl + ";jsessionid=" + req.getRequestedSessionId();

    if (queryString != null) newUrl = newUrl + "?" + queryString;

    // if (session != null) newUrl = newUrl + ";jsessionid=" + session.getId();

    return new URL(newUrl);
  }
Exemplo n.º 11
0
  /**
   * Constructor.
   *
   * @param rq request
   * @param rs response
   * @param servlet calling servlet instance
   * @throws IOException I/O exception
   */
  public HTTPContext(
      final HttpServletRequest rq, final HttpServletResponse rs, final BaseXServlet servlet)
      throws IOException {

    req = rq;
    res = rs;
    params = new HTTPParams(this);

    method = rq.getMethod();

    final StringBuilder uri = new StringBuilder(req.getRequestURL());
    final String qs = req.getQueryString();
    if (qs != null) uri.append('?').append(qs);
    log('[' + method + "] " + uri, null);

    // set UTF8 as default encoding (can be overwritten)
    res.setCharacterEncoding(UTF8);
    segments = decode(toSegments(req.getPathInfo()));

    // adopt servlet-specific credentials or use global ones
    final GlobalOptions mprop = context().globalopts;
    user = servlet.user != null ? servlet.user : mprop.get(GlobalOptions.USER);
    pass = servlet.pass != null ? servlet.pass : mprop.get(GlobalOptions.PASSWORD);

    // overwrite credentials with session-specific data
    final String auth = req.getHeader(AUTHORIZATION);
    if (auth != null) {
      final String[] values = auth.split(" ");
      if (values[0].equals(BASIC)) {
        final String[] cred = org.basex.util.Base64.decode(values[1]).split(":", 2);
        if (cred.length != 2) throw new LoginException(NOPASSWD);
        user = cred[0];
        pass = cred[1];
      } else {
        throw new LoginException(WHICHAUTH, values[0]);
      }
    }
  }
Exemplo n.º 12
0
 public String getQueryString() {
   return request.getQueryString();
 }
Exemplo n.º 13
0
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      _jspxFactory = JspFactory.getDefaultFactory();
      response.setContentType("text/html;charset=EUC-KR");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\r\n");
      out.write("<HTML>\r\n");
      out.write("<BODY bgcolor=\"white\">\r\n");
      out.write("<H3>요청 정보 </H3>\r\n");

      response.setDateHeader("Expires", 0);
      response.setHeader("Pragma", "no-cache");
      if (request.getProtocol().equals("HTTP/1.1")) {
        response.setHeader("Cache-Control", "no-cache");
      }

      out.write("\r\n");
      out.write("<FONT size=\"4\">\r\n");
      out.write("JSP Request Method:");
      out.print(request.getMethod());
      out.write("<BR>\r\n");
      out.write("Request URI:");
      out.print(request.getRequestURI());
      out.write("<BR>\r\n");
      out.write("Request Protocol:");
      out.print(request.getProtocol());
      out.write("<BR>\r\n");
      out.write("Servlet path:");
      out.print(request.getServletPath());
      out.write("<BR>\r\n");
      out.write("Query string:");
      out.print(request.getQueryString());
      out.write("<BR>\r\n");
      out.write("Content length:");
      out.print(request.getContentLength());
      out.write("<BR>\r\n");
      out.write("Content type:");
      out.print(request.getContentType());
      out.write("<BR>\r\n");
      out.write("Server name:");
      out.print(request.getServerName());
      out.write("<BR>\r\n");
      out.write("Server port:");
      out.print(request.getServerPort());
      out.write("<BR>\r\n");
      out.write("Remote address:");
      out.print(request.getRemoteAddr());
      out.write("<BR>\r\n");
      out.write("Remote host:");
      out.print(request.getRemoteHost());
      out.write("<BR>\r\n");
      out.write("<HR>\r\n");
      out.write("The browser you are using is ");
      out.print(request.getHeader("User-Agent"));
      out.write("\r\n");
      out.write("</FONT>\r\n");
      out.write("</BODY>\r\n");
      out.write("</HTML>\r\n");
      out.write("\t");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0) out.clearBuffer();
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
Exemplo n.º 14
0
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\r\n");
      out.write("\r\n");
      out.write("<!DOCTYPE html>\r\n");
      org.apache.jasper.runtime.JspRuntimeLibrary.include(
          request, response, "/resource/jsp/resource_js.jsp", out, false);
      out.write("\r\n");
      out.write("<html lang=\"en\">\r\n");
      out.write("    <head>\r\n");
      out.write("        <meta charset=\"utf-8\">\r\n");
      out.write(
          "        <meta name=\"viewport\" content=\"width=device-width,initial-scale=1,user-scalable=0\">\r\n");
      out.write("        <title>项目详情</title>\r\n");
      out.write("        <link rel=\"stylesheet\" type=\"text/css\" href=\"../css/weui.css\">\r\n");
      out.write("        <link rel=\"stylesheet\" type=\"text/css\" href=\"../css/base.css\">\r\n");
      out.write(
          "        <link rel=\"stylesheet\" type=\"text/css\" href=\"../css/details-jie.css\">\r\n");
      out.write(
          "        <script src=\"http://res.wx.qq.com/open/js/jweixin-1.0.0.js\"></script>\r\n");
      out.write(
          "        <script type=\"text/javascript\" src=\"../js/jquery.2.1.4.js\"></script>\r\n");
      out.write("        <style type=\"text/css\">\r\n");
      out.write("\r\n");
      out.write("\t\t\t/*报名人员列表*/\r\n");
      out.write("\t\t\t.people-list{ color:#333;}\r\n");
      out.write("\t\t\t.people-list li{ padding:8px 0;}\r\n");
      out.write("\t\t\t.people-list li img{ height:40px; width:40px; border-radius:50%;}\r\n");
      out.write("\t\t\t.people-list p{line-height:40px; padding-left:15px;}\r\n");
      out.write("\t\t\t.people-list-ico{\r\n");
      out.write("\t\t\t\theight:25px;\r\n");
      out.write("\t\t\t\twidth:25px;\r\n");
      out.write("\t\t\t\tbackground: url(../images/p-li2.png) 0 0 no-repeat;\r\n");
      out.write("\t\t\t\tbackground-size:100%;\r\n");
      out.write("\t\t\t\tmargin-top:7px;\r\n");
      out.write("\t\t\t}\r\n");
      out.write("\t\t\t.yes .people-list-ico{background-image:url(../images/p-li1.png);}\r\n");
      out.write("        </style>\r\n");
      out.write("    </head>\r\n");
      out.write("    ");

      String openid = request.getParameter("OPENID");
      String wxid = request.getParameter("WXID");
      String itemid = request.getParameter("ITEMID");
      String appid = new String("");
      String noncestr = new String("");
      String signature = new String("");
      String timestamp = new String("");
      JsSdkConfig ro =
          WxJSSDKUtil.getConfig(
              wxid, request.getRequestURL().toString() + "?" + request.getQueryString());
      if (ro != null) {
        System.out.println(request.getRequestURL().toString() + "?" + request.getQueryString());
        appid = ro.getAppid();
        noncestr = ro.getNonceStr();
        signature = ro.getSignature();
        timestamp = ro.getTimestamp();
      }

      out.write("\r\n");
      out.write("    <body>\r\n");
      out.write("   <!--  头部区域 -->\r\n");
      out.write("    \t<header class=\"clearfix ft16 pd10 cor9\">\r\n");
      out.write(
          "    \t\t<p class=\"jie-hd-lf fl\">接单期限: 还剩<span style=\"color:#FE0000;\"></span>天</p>\r\n");
      out.write("    \t\t<div class=\"jie-hd-rt fr\">\r\n");
      out.write("    \t\t\t<p><i class=\"jie-hd-ico di\"></i></p>\r\n");
      out.write("    \t\t</div>\r\n");
      out.write("    \t</header>\r\n");
      out.write("    \t<!-- 预算区域 -->\r\n");
      out.write("    \t<div class=\"yu tc clearfix bd1\">\r\n");
      out.write("    \t\t<p class=\"cor9 yusuan fl\">预算</p>\r\n");
      out.write("    \t\t<p class=\"money fl\"> <i class=\"money-ico di\"></i></p>\r\n");
      out.write("\t\t\t<div class=\"starttime fl\">\r\n");
      out.write("\t\t\t\t<p>启动时间</p>\r\n");
      out.write("\t\t\t\t<p></p>\r\n");
      out.write("\t\t\t</div>\r\n");
      out.write("\t\t\t<div class=\"endtime tr fl\">\r\n");
      out.write("\t\t\t\t<p>完成时间</p>\r\n");
      out.write("\t\t\t\t<p></p>\r\n");
      out.write("\t\t\t</div>\r\n");
      out.write("    \t</div>\r\n");
      out.write("    \t<!-- 详情 -->\r\n");
      out.write("    \t<div class=\"jie-inf cor9 pd10 ft14 bd1\">\r\n");
      out.write("    \t\t<h1 class=\"ft16\">项目详情:</h1>\r\n");
      out.write("    \t\t <ul class=\"inf-lei\">\r\n");
      out.write("    \t\t\t<!-- <li>Java3人</li>\r\n");
      out.write("    \t\t\t<li>PHP3人</li> -->\r\n");
      out.write("    \t\t</ul> \r\n");
      out.write("    \t\t<p></p>\r\n");
      out.write("    \t</div>\r\n");
      out.write("    \t<div class=\"pd10 cor9\" id=\"bmlist\">\r\n");
      out.write("    \t\t<p style=\"padding:10px 0;\">报名人数: <span>0</span>人</p>\r\n");
      out.write("    \t\t<ul class=\"people-list\">\r\n");
      out.write("    \t\t\t<!-- <li class=\"clearfix\">\r\n");
      out.write("    \t\t\t\t<a href=\"ta.html\" class=\"fl clearfix\">\r\n");
      out.write("    \t\t\t\t\t<img src=\"../images/1.jpg\" class=\"fl\">\r\n");
      out.write("\t    \t\t\t\t<p class=\"fl\">西门科技有限公司</p>\r\n");
      out.write("    \t\t\t\t</a>\r\n");
      out.write("\t    \t\t\t<i class=\"di people-list-ico fr\"></i>\r\n");
      out.write("    \t\t\t</li>\r\n");
      out.write("    \t\t\t<li class=\"clearfix yes\">\r\n");
      out.write("    \t\t\t\t<a href=\"ta.html\" class=\"fl clearfix\">\r\n");
      out.write("    \t\t\t\t\t<img src=\"../images/1.jpg\" class=\"fl\">\r\n");
      out.write("\t    \t\t\t\t<p class=\"fl\">西门科技有限公司</p>\r\n");
      out.write("    \t\t\t\t</a>\r\n");
      out.write("\t    \t\t\t<i class=\"di people-list-ico fr\"></i>\r\n");
      out.write("    \t\t\t</li>  -->\r\n");
      out.write("    \t\t</ul>\r\n");
      out.write(
          "    \t\t<a  class=\"jie-btn weui_btn weui_btn_primary\" style=\"display: none\"></a>\r\n");
      out.write("    \t</div>\r\n");
      out.write("        <div class=\"down\" ></div>\r\n");
      out.write("    \t <!-- 补充资料 -->\r\n");
      out.write("    \t<div class=\"add\">\r\n");
      out.write("\t\t    <div class=\"weui_cells weui_cells_form adddate\">\r\n");
      out.write("\t\t    \t<div class=\"adddate-hd weui_cell bd1\" >\r\n");
      out.write(
          "\t\t    \t\t<p class=\"tc\">补充资料<i class=\"adddate-hd-ico di\"></i></p>\r\n");
      out.write("\t\t    \t</div>\r\n");
      out.write("\t\t    \t<div class=\"weui_cell bd1\" id=\"imgurl\">\r\n");
      out.write(
          "\t                <div class=\"weui_cell_hd\"><img  class=\"tou-img\" src=\"\"></div>\r\n");
      out.write("\t                <div class=\"weui_cell_bd weui_cell_primary\">\r\n");
      out.write(
          "\t                    <input class=\"weui_input tr\" disabled=\"disabled\" type=\"text\" placeholder=\"上传头像\"/>\r\n");
      out.write("\t                </div>\r\n");
      out.write("\t            </div>\r\n");
      out.write("\t            <div class=\"weui_cell bd1\" >\r\n");
      out.write(
          "\t                <div class=\"weui_cell_hd\"><label class=\"weui_label\" >昵称</label></div>\r\n");
      out.write("\t                <div class=\"weui_cell_bd weui_cell_primary\">\r\n");
      out.write(
          "\t                    <input class=\"weui_input tr\" type=\"text\" id=\"nickname\" placeholder=\"请输入\"/>\r\n");
      out.write("\t                </div>\r\n");
      out.write("\t            </div>\r\n");
      out.write("\t            <div class=\"weui_cell bd1\">\r\n");
      out.write(
          "\t                <div class=\"weui_cell_hd\"><label class=\"weui_label\">公司名</label></div>\r\n");
      out.write("\t                <div class=\"weui_cell_bd weui_cell_primary\">\r\n");
      out.write(
          "\t                    <input class=\"weui_input tr\" type=\"text\" id=\"company_name\" placeholder=\"请输入\"/>\r\n");
      out.write("\t                </div>\r\n");
      out.write("\t            </div>\r\n");
      out.write("\t            <div class=\"weui_cell bd1\">\r\n");
      out.write(
          "\t                <div class=\"weui_cell_hd\"><label class=\"weui_label\">联系人</label></div>\r\n");
      out.write("\t                <div class=\"weui_cell_bd weui_cell_primary\">\r\n");
      out.write(
          "\t                    <input class=\"weui_input tr\" type=\"text\" id=\"contact\" placeholder=\"请输入\"/>\r\n");
      out.write("\t                </div>\r\n");
      out.write("\t            </div>\r\n");
      out.write("\t            <div class=\"weui_cell bd1\">\r\n");
      out.write(
          "\t                <div class=\"weui_cell_hd\"><label class=\"weui_label\">联系电话</label></div>\r\n");
      out.write("\t                <div class=\"weui_cell_bd weui_cell_primary\">\r\n");
      out.write(
          "\t                    <input class=\"weui_input tr\" type=\"tel\" id=\"tel\" placeholder=\"请输入\"/>\r\n");
      out.write("\t                </div>\r\n");
      out.write("\t            </div>\r\n");
      out.write("\t\t\t\t<div class=\"weui_cell bd1\">\r\n");
      out.write(
          "\t                <div class=\"weui_cell_hd\"><label class=\"weui_label\">联系地址</label></div>\r\n");
      out.write("\t                <div class=\"weui_cell_bd weui_cell_primary\">\r\n");
      out.write(
          "\t                    <input class=\"weui_input tr\" type=\"text\" id=\"addr\" placeholder=\"请输入\"/>\r\n");
      out.write("\t                </div>\r\n");
      out.write("\t            </div>\r\n");
      out.write("\t\t\t\t<div class=\"weui_btn_area\">\r\n");
      out.write(
          "\t\t            <a class=\"weui_btn weui_btn_primary\" href=\"javascript:\" id=\"showTooltips\">提交资料</a>\r\n");
      out.write("\t\t        </div>\r\n");
      out.write("\t        </div>\r\n");
      out.write("    \t</div>\r\n");
      out.write("    </body>\r\n");
      out.write("    <script type=\"text/javascript\">\r\n");
      out.write("    var openid=\"");
      out.print(openid);
      out.write("\";\r\n");
      out.write("    var wxid=\"");
      out.print(wxid);
      out.write("\";\r\n");
      out.write("    var itemid=\"");
      out.print(itemid);
      out.write("\";\r\n");
      out.write("    var memberInfo=JSON.parse(sessionStorage.getItem(\"MEMBERINFO\"));\r\n");
      out.write("    var state=0;\r\n");
      out.write("    var serverId=\"\";\r\n");
      out.write("    var data=\"\";\r\n");
      out.write("    var hasbm=false;\r\n");
      out.write("    var isJD=false;  // 此项目是否已接单\r\n");
      out.write("\t\t    $(function() {\r\n");
      out.write("\t\t\t\tinitBind();\r\n");
      out.write("\t\t\t\tgetItemInfo();\t\r\n");
      out.write("\t\t\t\tgetJssdkConfig();\r\n");
      out.write("\t\t\t\tsetmemberinfo();\r\n");
      out.write("\t\t\t});\r\n");
      out.write("\t\t  //获取会员信息\r\n");
      out.write("    \t\tfunction setmemberinfo(){\r\n");
      out.write("    \t\t\t//alert(JSON.stringify(memberInfo));\r\n");
      out.write("    \t\t\tif(memberInfo==null){\r\n");
      out.write("    \t\t\t\tgetmemberinfo();\r\n");
      out.write("    \t\t\t\treturn;\r\n");
      out.write("    \t\t\t}\r\n");
      out.write("    \t\t\tif(memberInfo.STATE==\"0\"){\r\n");
      out.write("    \t\t\t\t$(\"#imgurl img\").attr(\"src\",memberInfo.data.HEADIMGURL);\r\n");
      out.write("    \t\t\t\t$(\"#nickname\").val(memberInfo.data.NICKNAME);\r\n");
      out.write("    \t\t\t}\r\n");
      out.write("    \t\t    if(memberInfo.STATE==\"1\"){\r\n");
      out.write("    \t\t    \tstate=1;\r\n");
      out.write("    \t\t    }\r\n");
      out.write("    \t\t}\r\n");
      out.write("    \t\tfunction getmemberinfo(){\r\n");
      out.write("        \t\t$.ajax({\r\n");
      out.write("        \t\t\turl:\"");
      out.print(request.getContextPath());
      out.write("/wci/yw/GetMemberInfo.do\",\r\n");
      out.write("        \t\t\tdata:{\"OPENID\":openid,\"WXID\":wxid},\r\n");
      out.write("        \t\t\tsuccess:function(res){\r\n");
      out.write(
          "        \t\t\t\tsessionStorage.setItem(\"MEMBERINFO\",JSON.stringify(res.data));\r\n");
      out.write("        \t\t\t\tmemberInfo=res.data;\r\n");
      out.write("        \t\t\t\tsetmemberinfo();\r\n");
      out.write(
          "        \t\t\t\t//window.location.href=base_url+\"/\"+reurl+\"?WXID=\"+wxid+\"&OPENID=\"+openid;\r\n");
      out.write("        \t\t\t}\r\n");
      out.write("        \t\t});\r\n");
      out.write("        \t}\r\n");
      out.write("\t\t    function getJssdkConfig(){\r\n");
      out.write("    \t\t\twx.config({\r\n");
      out.write("    \t\t\t    debug: false,\r\n");
      out.write("    \t\t\t    appId: \"");
      out.print(appid);
      out.write("\",\r\n");
      out.write("    \t\t\t    timestamp: \"");
      out.print(timestamp);
      out.write("\",\r\n");
      out.write("    \t\t\t    nonceStr: \"");
      out.print(noncestr);
      out.write("\",\r\n");
      out.write("    \t\t\t    signature: \"");
      out.print(signature);
      out.write("\",\r\n");
      out.write("    \t\t\t    jsApiList: [\r\n");
      out.write("    \t\t\t       'chooseImage',\r\n");
      out.write("    \t\t\t       'uploadImage',\r\n");
      out.write("    \t\t\t       'downloadImage'\r\n");
      out.write("    \t\t\t        ]\r\n");
      out.write("    \t\t\t  });\r\n");
      out.write("    \t\t\t\twx.error(function(res){\r\n");
      out.write("    \t\t\t\t\talert(\"服务器异常,请稍后重试!\");\r\n");
      out.write(
          "    \t\t\t\t    // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。\r\n");
      out.write("    \t\t\t\t});\r\n");
      out.write("    \t\t\t\twx.ready(function(){\r\n");
      out.write("    \t\t\t\t\tdocument.querySelector('#imgurl').onclick = function () {\r\n");
      out.write("    \t\t\t\t\t\twx.chooseImage({\r\n");
      out.write("    \t\t\t\t\t\t    count: 1, // 默认9\r\n");
      out.write(
          "    \t\t\t\t\t\t    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有\r\n");
      out.write(
          "    \t\t\t\t\t\t    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有\r\n");
      out.write("    \t\t\t\t\t\t    success: function (res) {\r\n");
      out.write("    \t\t\t\t\t\t    \t//alert(JSON.stringify(res));\r\n");
      out.write("    \t\t\t\t\t\t    \t$(\"#imgurl img\").attr(\"src\",res.localIds[0]);\r\n");
      out.write("    \t\t\t\t\t\t        wx.uploadImage({\r\n");
      out.write(
          "    \t\t\t\t\t\t            localId: res.localIds[0], // 需要上传的图片的本地ID,由chooseImage接口获得\r\n");
      out.write(
          "    \t\t\t\t\t\t            isShowProgressTips: 1, // 默认为1,显示进度提示\r\n");
      out.write("    \t\t\t\t\t\t            success: function (res) {\r\n");
      out.write(
          "    \t\t\t\t\t\t               serverId = res.serverId; // 返回图片的服务器端ID\r\n");
      out.write("    \t\t\t\t\t\t            }\r\n");
      out.write("    \t\t\t\t\t\t        });\r\n");
      out.write("    \t\t\t\t\t\t    }\r\n");
      out.write("    \t\t\t\t\t\t});\r\n");
      out.write("    \t\t\t\t\t}\r\n");
      out.write("    \t\t\t\t\t\r\n");
      out.write("    \t\t\t\t});\r\n");
      out.write("    \t\t}\r\n");
      out.write("\t\t    function getItemInfo(){\r\n");
      out.write("\t\t    \t$.ajax({\r\n");
      out.write("\t\t    \t\turl:\"");
      out.print(request.getContextPath());
      out.write("/wci/yw/GetItemInfo.do\",\r\n");
      out.write("\t\t    \t\tdata:{\"ITEM_ID\":itemid},\r\n");
      out.write("\t\t    \t\tbeforeSend:function(){\r\n");
      out.write("\t\t    \t\t\twc.showLoadding(\"加载中\");\r\n");
      out.write("\t\t    \t\t},\r\n");
      out.write("\t\t    \t\tsuccess:function(res){\r\n");
      out.write("\t\t    \t\t\t//alert(JSON.stringify(res.data));\r\n");
      out.write("\t\t    \t\t\tsetData(res.data);\r\n");
      out.write("\t\t    \t\t\tdata=res.data;\r\n");
      out.write("\t\t    \t\t},\r\n");
      out.write("\t\t    \t\tcomplete:function(){\r\n");
      out.write("\t\t    \t\t\twc.closeLoadding();\r\n");
      out.write("\t\t    \t\t},\r\n");
      out.write("\t\t    \t\terror:function(){\r\n");
      out.write("\t\t    \t\t\twc.closeLoadding();\r\n");
      out.write("\t\t    \t\t}\r\n");
      out.write("\t\t    \t});\r\n");
      out.write("\t\t    }\r\n");
      out.write("\t\t    function setData(data){\r\n");
      out.write("\t\t    \tsetCommData(data);\r\n");
      out.write("\t\t    \t//alert(JSON.stringify(data));\r\n");
      out.write("\t\t    \t// 若是发布人进入此页面\r\n");
      out.write("\t\t    \tif(data.ITEMINFO.OPENID==openid&&data.ITEMINFO.WXID==wxid){\r\n");
      out.write("\t\t    \t\tsetBMData(data);\r\n");
      out.write("\t\t    \t}else{  // 非发布人进入\r\n");
      out.write("\t\t    \t\tvar html=\"\";\r\n");
      out.write("\t\t    \t\t$(\"#bmlist span:first\").html(data.BMLIST.length);\r\n");
      out.write("\t\t    \t\tfor(var i=0;i<data.BMLIST.length;i++){\r\n");
      out.write("\t\t\t    \t\tif(data.BMLIST[i].IS_JD==\"1\"){\r\n");
      out.write("\t\t\t    \t\t\tisJD=true;\r\n");
      out.write("\t\t\t    \t\t}\r\n");
      out.write("\t\t\t    \t\tif(data.BMLIST[i].OPENID==openid&&data.BMLIST[i].WXID==wxid){\r\n");
      out.write("\t\t\t    \t\t\thasbm=true;\r\n");
      out.write("\t\t\t    \t\t}\r\n");
      out.write("\t\t\t    \t\thtml+=getPeopleHtml2(data.BMLIST[i]);\r\n");
      out.write("\t\t\t    \t}\r\n");
      out.write("\t\t    \t\t$(\".people-list\").html(html);\r\n");
      out.write("\t\t    \t\tif(!hasbm&&!isJD){\r\n");
      out.write("\t\t    \t\t\t$(\".jie-btn\").unbind();\r\n");
      out.write("\t\t\t    \t    $(\".jie-btn\").text(\"报名\");\r\n");
      out.write("\t\t\t    \t    $(\".jie-btn\").show();\r\n");
      out.write("\t\t\t    \t    $(\".jie-btn\").click(BMItem);\r\n");
      out.write("\t\t    \t\t}\r\n");
      out.write("\t\t    \t}\r\n");
      out.write("\t\t    }\r\n");
      out.write("\t\t    function BMItem(){\r\n");
      out.write("\t\t    \tif(state==0){\r\n");
      out.write("\t\t    \t\t$(\".add\").show();\r\n");
      out.write("\t\t    \t\t$(\".down\").show();\r\n");
      out.write("\t\t    \t}else{\r\n");
      out.write("\t\t    \t\t$.ajax({\r\n");
      out.write("\t\t\t    \t\turl:\"");
      out.print(request.getContextPath());
      out.write("/wci/yw/BMItem.do\",\r\n");
      out.write("\t\t\t    \t\tdata:{\"ITEM_ID\":itemid,\"OPENID\":openid,\"WXID\":wxid},\r\n");
      out.write("\t\t\t    \t\tbeforeSend:function(){\r\n");
      out.write("\t\t\t    \t\t\twc.showLoadding(\"操作中\");\r\n");
      out.write("\t\t\t    \t\t},\r\n");
      out.write("\t\t\t    \t\tsuccess:function(res){\r\n");
      out.write("\t\t\t    \t\t\tif(res.data==\"1\"){\r\n");
      out.write("\t\t\t    \t\t\t\twc.showMsg(\"报名成功\",function(){\r\n");
      out.write(
          "\t\t\t    \t\t\t\t\twindow.location.href=\"./succss-baoming.jsp?OPENID=\"+openid+\"&WXID=\"+wxid+\"&ITEM_ID=\"+itemid;\r\n");
      out.write("\t\t\t    \t\t\t\t});\r\n");
      out.write("\t\t\t    \t\t\t}\r\n");
      out.write("\t\t\t    \t\t\t\r\n");
      out.write("\t\t\t    \t\t},\r\n");
      out.write("\t\t\t    \t\tcomplete:function(){\r\n");
      out.write("\t\t\t    \t\t\twc.closeLoadding();\r\n");
      out.write("\t\t\t    \t\t}\r\n");
      out.write("\t\t\t    \t\t\r\n");
      out.write("\t\t\t    \t});\r\n");
      out.write("\t\t    \t}\r\n");
      out.write("\t\t    \t\r\n");
      out.write("\t\t    }\r\n");
      out.write("\t\t    function setBMData(data){  //记载报名列表\r\n");
      out.write("\t\t    \tvar html=\"\";\r\n");
      out.write("\t\t        $(\"#bmlist span:first\").html(data.BMLIST.length);\r\n");
      out.write("\t\t        //alert(JSON.stringify(data));\r\n");
      out.write("\t\t    \tfor(var i=0;i<data.BMLIST.length;i++){\r\n");
      out.write("\t\t    \t\tif(data.BMLIST[i].IS_JD==\"1\"){\r\n");
      out.write("\t\t    \t\t\tisJD=true;\r\n");
      out.write("\t\t    \t\t}\r\n");
      out.write("\t\t    \t\thtml+=getPeopleHtml(data.BMLIST[i]);\r\n");
      out.write("\t\t    \t}\r\n");
      out.write("\t\t    \t$(\".people-list\").html(html);\r\n");
      out.write("\t\t    \tif(data.BMLIST.length==0){  //没有人接单可以进行修改\r\n");
      out.write("\t\t    \t\t$(\".jie-btn\").unbind();\r\n");
      out.write("\t\t    \t    $(\".jie-btn\").text(\"修改需求\");\r\n");
      out.write("\t\t    \t    $(\".jie-btn\").show();\r\n");
      out.write("\t\t    \t    $(\".jie-btn\").click(updateItem);\r\n");
      out.write("\t\t    \t}\r\n");
      out.write("\t\t    \tif(data.BMLIST.length>0&&!isJD){\r\n");
      out.write("\t\t    \t\t$(\".jie-btn\").unbind();\r\n");
      out.write("\t\t    \t    $(\".jie-btn\").text(\"确认接单公司\");\r\n");
      out.write("\t\t    \t    $(\".jie-btn\").show();\r\n");
      out.write("\t\t    \t    $(\".jie-btn\").click(updateJDGS);\r\n");
      out.write("\t\t    \t}\t\r\n");
      out.write("\t\t    \t\r\n");
      out.write("\t\t    }\r\n");
      out.write("\t\t    //确认接单公司\r\n");
      out.write("\t\t    \r\n");
      out.write("\t\t    function updateJDGS(data){\r\n");
      out.write("\t\t    \t\tif(checkJDGS()){\r\n");
      out.write("\t\t    \t\t\tsubmitJDGS();\r\n");
      out.write("\t\t    \t\t}\r\n");
      out.write("\t\t    }\r\n");
      out.write("\t\t    function submitJDGS(){\r\n");
      out.write("\t\t    \t$.ajax({\r\n");
      out.write("\t    \t\t\turl:\"");
      out.print(request.getContextPath());
      out.write("/wci/yw/SetJD.do\",\r\n");
      out.write("\t    \t\t\tdata:{\"ITEM_ID\":itemid,\"JDGSARR\":JSON.stringify(jdgsarr)},\r\n");
      out.write("\t    \t\t\tbeforeSend:function(){\r\n");
      out.write("\t    \t\t\t\twc.showLoadding(\"操作中\");\r\n");
      out.write("\t    \t\t\t},\r\n");
      out.write("\t    \t\t\tsuccess:function(res){\r\n");
      out.write("\t    \t\t\t\tif(parseInt(res.data)>=1){\r\n");
      out.write("\t    \t\t\t\t\twc.showMsg(\"设置成功\",function(){\r\n");
      out.write("\t\t    \t\t\t\t\twindow.location.reload();\r\n");
      out.write("\t    \t\t\t\t\t});\r\n");
      out.write("\t    \t\t\t\t}\r\n");
      out.write("\t    \t\t\t},\r\n");
      out.write("\t    \t\t\tcomplete:function(){\r\n");
      out.write("\t    \t\t\t\twc.closeLoadding();\r\n");
      out.write("\t    \t\t\t}\r\n");
      out.write("\t    \t\t});\r\n");
      out.write("\t\t    }\r\n");
      out.write("\t\t    var jdgsarr=[];\r\n");
      out.write("\t\t    function checkJDGS(){\r\n");
      out.write("\t\t    \tif($(\".people-list>li.yes\").length==0){\r\n");
      out.write("\t\t    \t\twc.showDialog(\"\",\"请选择接单公司\");\r\n");
      out.write("\t\t    \t\treturn false\r\n");
      out.write("\t\t    \t}\r\n");
      out.write("\t\t    \t$(\".people-list>li.yes\").each(function(){\r\n");
      out.write("\t\t    \t\tvar item={};\r\n");
      out.write("\t\t    \t\titem.OPENID=$(this).attr(\"openid\");\r\n");
      out.write("\t\t    \t\titem.WXID=$(this).attr(\"wxid\");\r\n");
      out.write("\t\t    \t\titem.NAME=$(this).find(\"p\").html();\r\n");
      out.write("\t\t    \t\tjdgsarr.push(item);\r\n");
      out.write("\t\t    \t});\r\n");
      out.write("\t\t    \t//alert(JSON.stringify(jdgsarr));\r\n");
      out.write("\t\t    \treturn true;\r\n");
      out.write("\t\t    }\r\n");
      out.write("\t\t    function updateItem(){\r\n");
      out.write("\t\t    \tif(data.ITEMINFO.ITEM_TYPE==\"1\"){\r\n");
      out.write(
          "\t\t    \t\twindow.location.href=\"./project.jsp?OPENID=\"+openid+\"&WXID=\"+wxid+\"&ITEMID=\"+itemid;\r\n");
      out.write("\t\t    \t}\r\n");
      out.write("\t\t    \tif(data.ITEMINFO.ITEM_TYPE==\"2\"){\r\n");
      out.write(
          "\t\t    \t\twindow.location.href=\"./resources.jsp?OPENID=\"+openid+\"&WXID=\"+wxid+\"&ITEMID=\"+itemid;\r\n");
      out.write("\t\t    \t}\r\n");
      out.write("\t\t    }\r\n");
      out.write("\t\t    function getPeopleHtml(item){\r\n");
      out.write(
          "\t\t    \tvar html=\"<li class='clearfix \"+(item.IS_JD==\"1\"?'yes':'')+\"' openid='\"+item.OPENID+\"' wxid='\"+item.WXID+\"'>\"+\r\n");
      out.write("\t\t\t\t\t\t\t\t\"<a  class='fl clearfix'>\"+\r\n");
      out.write("\t\t\t\t\t\t\t\t\"<img src='\"+item.IMGURL+\"' class='fl'>\"+\r\n");
      out.write("\t\t\t\t\t\t\t\t\"<p class='fl'>\"+item.COMPANY_NAME+\"</p>\"+\r\n");
      out.write("\t\t\t\t\t\t\t\"</a>\"+\r\n");
      out.write("\t\t\t\t\t\t\t\"<i class='di people-list-ico fr' ></i>\"+\r\n");
      out.write("\t\t\t\t\t\t\"</li>\";\r\n");
      out.write("\t\t\t\t\t\treturn html;\r\n");
      out.write("\t\t    }\r\n");
      out.write("\t\t    function getPeopleHtml2(item){\r\n");
      out.write(
          "\t\t    \tvar html=\"<li class='clearfix \"+(item.IS_JD==\"1\"?'yes':'')+\"' openid='\"+item.OPENID+\"' wxid='\"+item.WXID+\"'>\"+\r\n");
      out.write("\t\t\t\t\t\t\t\t\"<a  class='fl clearfix'>\"+\r\n");
      out.write("\t\t\t\t\t\t\t\t\"<img src='\"+item.IMGURL+\"' class='fl'>\"+\r\n");
      out.write("\t\t\t\t\t\t\t\t\"<p class='fl'>\"+item.COMPANY_NAME+\"</p>\"+\r\n");
      out.write("\t\t\t\t\t\t\t\"</a>\"+\r\n");
      out.write(
          "\t\t\t\t\t\t\t\"<i class='di people-list-ico fr' style='display:\"+(item.IS_JD==\"1\"?'block':'none')+\"'></i>\"+\r\n");
      out.write("\t\t\t\t\t\t\"</li>\";\r\n");
      out.write("\t\t\t\t\t\treturn html;\r\n");
      out.write("\t\t    }\r\n");
      out.write("\t\t    function setCommData(data){\r\n");
      out.write("\t\t    \tvar item=data.ITEMINFO;\r\n");
      out.write("\t\t    \t$(\"header p:first span\").html(item.JSQX);\r\n");
      out.write("\t\t    \t$(\"header p:last\").prepend(item.COMPANY_NAME);\r\n");
      out.write("\t\t    \t$(\".money\").prepend(cc(item.ITEM_XMYS));\r\n");
      out.write("\t\t    \t$(\".starttime p:last\").html(item.ITEM_QDSJ);\r\n");
      out.write("\t\t    \t$(\".endtime p:last\").html(item.ITEM_WCSJ);\r\n");
      out.write("\t\t    \t$(\".jie-inf p:last\").html(item.ITEM_XQ);\r\n");
      out.write("\t\t    \t\r\n");
      out.write("\t\t    \tif(item.ITEM_TYPE==\"2\"){\r\n");
      out.write("\t\t    \t\tfor(var i=0;i<data.TYPELIST.length;i++){\r\n");
      out.write(
          "\t\t    \t\t\t$(\".inf-lei\").append(\"<li>\"+data.TYPELIST[i].ITEM_TYPE_NAME+\" \"+data.TYPELIST[i].ITEM_TYPE_NUM+\"人</li>\");\r\n");
      out.write("\t\t    \t\t}\r\n");
      out.write("\t\t    \t}\r\n");
      out.write("\t\t    \t\r\n");
      out.write("\t\t    }\r\n");
      out.write("\t\t    function cc(s){\r\n");
      out.write("\t            if(/[^0-9\\.]/.test(s)) return \"invalid value\";\r\n");
      out.write("\t            s=s.replace(/^(\\d*)$/,\"$1.\");\r\n");
      out.write("\t            s=(s+\"00\").replace(/(\\d*\\.\\d\\d)\\d*/,\"$1\");\r\n");
      out.write("\t            s=s.replace(\".\",\",\");\r\n");
      out.write("\t            var re=/(\\d)(\\d{3},)/;\r\n");
      out.write("\t            while(re.test(s))\r\n");
      out.write("\t                    s=s.replace(re,\"$1,$2\");\r\n");
      out.write("\t            s=s.replace(/,(\\d\\d)$/,\".$1\");\r\n");
      out.write("\t            return  s.replace(/^\\./,\"0.\");\r\n");
      out.write("\t            }\r\n");
      out.write("\t\t    $(\"#showTooltips\").click(function(){\r\n");
      out.write("    \t\t\tif(memberCheck()){\r\n");
      out.write("    \t\t\t\tmemberSubmit();\r\n");
      out.write("    \t\t\t}\r\n");
      out.write("    \t\t});\r\n");
      out.write("    \t\tfunction memberSubmit(){\r\n");
      out.write("    \t\t\t//alert(1);\r\n");
      out.write("    \t\t\t$.ajax({\r\n");
      out.write("    \t\t\t\turl:\"");
      out.print(request.getContextPath());
      out.write("/wci/yw/MemberSubmit.do\",\r\n");
      out.write(
          "    \t\t\t\tdata:{\"OPENID\":openid,\"WXID\":wxid,\"SERVERID\":serverId,\"NICKNAME\":$(\"#nickname\").val(),\r\n");
      out.write(
          "    \t\t\t\t\t   \"COMPANY_NAME\":$(\"#company_name\").val(),\"CONTACT\":$(\"#contact\").val(),\"IMGURL\":memberInfo.data.HEADIMGURL,\r\n");
      out.write("    \t\t\t\t\t   \"TEL\":$(\"#tel\").val(),\"ADDR\":$(\"#addr\").val()\r\n");
      out.write("    \t\t\t\t     },\r\n");
      out.write("    \t\t\t\tbeforeSend:function(){\r\n");
      out.write("    \t\t\t\t\twc.showLoadding(\"提交中.....\");\r\n");
      out.write("    \t\t\t\t},\r\n");
      out.write("    \t\t\t\tsuccess:function(res){\r\n");
      out.write("    \t\t\t\t\tif(res.data==\"1\"){\r\n");
      out.write("    \t\t\t\t\t\twc.showMsg(\"提交成功\",function(){\r\n");
      out.write("        \t\t\t\t\t\t$(\".add\").hide();\r\n");
      out.write("                \t\t\t\t$(\".down\").hide();\r\n");
      out.write("                \t\t\t\tmemberInfo.STATE=1;\r\n");
      out.write(
          "                \t\t\t\tsessionStorage.setItem(\"MEMBERINFO\",JSON.stringify(memberInfo));\r\n");
      out.write("                \t\t\t\tstate=1;\r\n");
      out.write("        \t\t\t\t\t});\r\n");
      out.write("    \t\t\t\t\t}\r\n");
      out.write("    \t\t\t\t\t//setTime\r\n");
      out.write("    \t\t\t\t\t\r\n");
      out.write("    \t\t\t\t},\r\n");
      out.write("    \t\t\t\tcomplete:function(){\r\n");
      out.write("    \t\t\t\t\twc.closeLoadding();\r\n");
      out.write("    \t\t\t\t}\r\n");
      out.write("    \t\t\t});\r\n");
      out.write("    \t\t}\r\n");
      out.write("    \t\tfunction memberCheck(){\r\n");
      out.write("    \t\t\t//wc.showDialog(\"title\",\"text\");\r\n");
      out.write("    \t\t\tif($(\"#nickname\").val()==\"\"){\r\n");
      out.write("    \t\t\t\twc.showDialog(\"\",\"昵称不能为空!\");\r\n");
      out.write("    \t\t\t\treturn false;\r\n");
      out.write("    \t\t\t}\r\n");
      out.write("    \t\t\tif($(\"#company_name\").val()==\"\"){\r\n");
      out.write("    \t\t\t\twc.showDialog(\"\",\"公司名不能为空!\");\r\n");
      out.write("    \t\t\t\treturn false;\r\n");
      out.write("    \t\t\t}\r\n");
      out.write("    \t\t\tif($(\"#contact\").val()==\"\"){\r\n");
      out.write("    \t\t\t\twc.showDialog(\"\",\"联系人不能为空!\");\r\n");
      out.write("    \t\t\t\treturn false;\r\n");
      out.write("    \t\t\t}\r\n");
      out.write("    \t\t\tif($(\"#tel\").val()==\"\"){\r\n");
      out.write("    \t\t\t\twc.showDialog(\"\",\"联系电话不能为空!\");\r\n");
      out.write("    \t\t\t\treturn false;\r\n");
      out.write("    \t\t\t}\r\n");
      out.write("    \t\t\tif(!$(\"#tel\").val().match(/^1[0-9]{10}$/)){\r\n");
      out.write("    \t\t\t\twc.showDialog(\"\",\"联系电话格式不正确!\");\r\n");
      out.write("    \t\t\t\treturn false;\r\n");
      out.write("    \t\t\t}\r\n");
      out.write("    \t\t\tif($(\"#addr\").val()==\"\"){\r\n");
      out.write("    \t\t\t\twc.showDialog(\"\",\"联系地址不能为空!\");\r\n");
      out.write("    \t\t\t\treturn false;\r\n");
      out.write("    \t\t\t}\r\n");
      out.write("    \t\t\treturn true;\r\n");
      out.write("    \t\t}\r\n");
      out.write("            function initBind(){\r\n");
      out.write("            \t//人员列表情况\r\n");
      out.write(
          "            \t$(\".people-list\").delegate(\"i.people-list-ico\",\"click\",function(){\r\n");
      out.write("                       if(!isJD){  //没有人接单\r\n");
      out.write("                    \t   //$(\".people-list>li\").removeClass(\"yes\");\r\n");
      out.write("                           $(this).parent(\"li\").toggleClass(\"yes\");\r\n");
      out.write("                       }\r\n");
      out.write("            \t});\r\n");
      out.write("            \t$(\".people-list\").delegate(\"a\",\"click\",function(){\r\n");
      out.write(
          "            \t\twindow.location.href=\"./my.jsp?OPENID=\"+$(this).parent().attr(\"openid\")+\"&WXID=\"+$(this).parent().attr(\"wxid\");\r\n");
      out.write("            \t})\r\n");
      out.write("\t\t\t\t/* $(\".people-list-ico\").click(function(event) {\r\n");
      out.write("\t\t\t\t\t//判断是否具有类名\r\n");
      out.write("\t\t\t\t\tif ($(this).parent(\"li\").hasClass('yes')) {\r\n");
      out.write("\t\t\t\t\t\t$(this).parent(\"li\").removeClass('yes')\r\n");
      out.write("\t\t\t\t\t}else{\r\n");
      out.write("\t\t\t\t\t\t$(this).parent(\"li\").addClass('yes');\r\n");
      out.write("\t\t\t\t\t};\r\n");
      out.write("\t\t\t\t\t//如果li 任意具有就\r\n");
      out.write("\t\t\t\t\tif ($(\".people-list li\").hasClass('yes')) {\r\n");
      out.write("\t\t\t\t\t\t$(\".jie-btn\").text(\"确认接单公司\")\r\n");
      out.write("\t\t\t\t\t}else{\r\n");
      out.write("\t\t\t\t\t\t$(\".jie-btn\").text(\"修改需求\")\r\n");
      out.write("\t\t\t\t\t};\r\n");
      out.write("\t\t\t\t}); */\r\n");
      out.write("\t\t\t\t$(\".down\").click(function(){\r\n");
      out.write("\t\t\t\t\t$(\".down\").hide();\r\n");
      out.write("\t\t\t\t\t$(\".add\").hide();\r\n");
      out.write("\t\t\t\t});\r\n");
      out.write("            }\r\n");
      out.write("\t\t</script>\r\n");
      out.write("</html>");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            out.clearBuffer();
          } catch (java.io.IOException e) {
          }
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else log(t.getMessage(), t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
Exemplo n.º 15
0
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    //		权限判断
    StringBuffer sb = new StringBuffer();
    String actionType = null;
    String queryString = null;
    String userid = null;
    String isCanAccess = "1";
    HttpServletRequest hrequest = (HttpServletRequest) request;
    String strContext = hrequest.getContextPath();

    if (request instanceof HttpServletRequest) {

      // 获取用户信息
      userid = (String) hrequest.getSession().getAttribute("AuthorizedUserID");

      strContext = hrequest.getContextPath();
      queryString = hrequest.getQueryString(); // 整个参数串
      actionType = hrequest.getParameter("actionType"); // 一般操作
      if (actionType == null) {
        actionType = hrequest.getParameter("formSN"); // 针对查询的操作
        if (actionType != null) {
          actionType = "formSN=" + actionType;
        }
      } else {
        actionType = "actionType=" + actionType;
      }
    }

    if (actionType != null) { // 如果参数不为空,则判断权限,通过存储过程判断
      DBConnectionManager dbManager = new DBConnectionManager();
      CallableStatement cstmt = null;
      Connection conn = null;
      try {
        conn = dbManager.getConnection();
        String query = "{call pkg_security.userAccessFunction(?,?,?,?)}";
        cstmt = conn.prepareCall(query);
        cstmt.registerOutParameter(1, OracleTypes.VARCHAR);
        cstmt.setString(2, userid);
        cstmt.setString(3, actionType == null ? null : actionType.trim());
        cstmt.setString(4, queryString == null ? null : queryString.trim());
        cstmt.execute();
        isCanAccess = cstmt.getString(1);

      } catch (SQLException e) {
        e.printStackTrace();
      } finally {
        try {
          if (cstmt != null) {
            cstmt.close();
          }
        } catch (Exception ex) {
          if (conn != null)
            try {
              conn.close();
            } catch (SQLException e1) {
              e1.printStackTrace();
            }
        }
        if (conn != null)
          try {
            conn.close();
          } catch (SQLException e1) {
            e1.printStackTrace();
          }
      }
    }

    // 如果没有权限,定位到提示页面。
    if (!isCanAccess.equals("1")) {
      HttpServletResponse out = (HttpServletResponse) response;
      out.sendRedirect(strContext + "/common/erroraccess.jsp");
      return;
    } else {

      // 汉字问题
      HttpServletRequest httpRequest = (HttpServletRequest) request;
      httpRequest.setCharacterEncoding(encoding);
      //  chain.doFilter(request, response);

      // 压缩传输

      HttpServletResponse httpResponse = (HttpServletResponse) response;
      String uri = httpRequest.getRequestURI();

      String transferEncoding = getGZIPEncoding((HttpServletRequest) request);
      if (transferEncoding == null) {
        setResponseHeader(httpResponse, uri, transferEncoding);
        chain.doFilter(request, response);
      } else {
        if (!uri.endsWith("dd.xml")) // 不处理的有哪些??????
        {
          chain.doFilter(request, response);
        } else {
          System.out.println("FrameworkFilter::  Filter handle dd.xml");
          setResponseHeader(httpResponse, uri, transferEncoding);
          httpResponse.setHeader("Content-Encoding", transferEncoding);
          GZIPEncodableResponse wrappedResponse =
              new GZIPEncodableResponse((HttpServletResponse) response);
          chain.doFilter(request, wrappedResponse);
          wrappedResponse.flush();
        }
      }
    }

    //		 Pass control on to the next filter
    // chain.doFilter(request, response);

  }
Exemplo n.º 16
0
  /**
   * Redirects the HTTP request to the Authentication module. It gets the authentication url from
   * <code>SystemProperties</code>.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception IOException If an input or output exception occurs
   */
  private void redirectForAuthentication(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    if (debug.messageEnabled()) {
      debug.message(
          "CDCClientServlet.redirectForAuthentication: " + "requestURL=" + request.getRequestURL());
    }
    StringBuffer redirectURL = new StringBuffer(100);
    StringBuffer gotoURL = new StringBuffer(100);

    // Check if user has authenticated to another OpenSSO
    // instance
    String authURL = null;
    Cookie authCookie = CookieUtils.getCookieFromReq(request, authURLCookieName);
    if (authCookie != null) {
      authURL = CookieUtils.getCookieValue(authCookie);
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication: "
                + "got an authenticated URL= "
                + authURL);
      }
    }
    try {
      if (authURL == null
          || authURL.length() == 0
          || !authURL.toLowerCase().startsWith("http")
          || policyAdviceList != null) {
        String finalURL = request.getParameter(GOTO_PARAMETER);

        if (finalURL == null || finalURL.equals("")) {
          finalURL = request.getParameter(TARGET_PARAMETER);
        }

        if (finalURL == null || finalURL.equals("")) {
          showError(response, "GOTO or TARGET parameter is missing" + " in the request");
          return;
        }

        gotoURL
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(TARGET_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(finalURL))
            .append(AMPERSAND)
            .append(requestParams);

        // Construct the login URL
        String cdcurl = SystemProperties.get(Constants.CDCSERVLET_LOGIN_URL);
        if (cdcurl != null && cdcurl.length() > 0) {
          if (cdcurl.indexOf("?") == -1) {
            redirectURLStr = cdcurl + QUESTION_MARK;
          } else {
            redirectURLStr = cdcurl + AMPERSAND;
          }
        } else {
          redirectURLStr = AUTHURI + QUESTION_MARK;
        }
        if (debug.messageEnabled()) {
          debug.message("CDCClientServlet init redirect URL is" + "set to= " + redirectURLStr);
        }

        redirectURL.append(redirectURLStr);
        if (policyAdviceList != null) {
          redirectURL.append(policyAdviceList).append(AMPERSAND);
        }
        redirectURL
            .append(GOTO_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(gotoURL.toString()));

        // Check for policy advices
        if (policyAdviceList != null) {
          redirectURL.append(AMPERSAND).append(policyAdviceList);
        }
        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.redirectForAuthentication"
                  + ":redirectURL before dispatching is="
                  + redirectURL);
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher(redirectURL.toString());
        dispatcher.forward(request, response);
      } else {
        // Redirect the user to the authenticated URL
        redirectURL
            .append(authURL)
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(request.getQueryString());
        // Reset the cookie value to null, to avoid continous loop
        // when a load balancer is used
        if (authCookie != null) {
          authCookie.setValue("");
          response.addCookie(authCookie);
        }
        response.sendRedirect(redirectURL.toString());
      }

      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication:"
                + "Forwarding for authentication to= "
                + redirectURL);
      }
    } catch (IOException ex) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication: Failed "
              + "in forwarding to Authentication service. IOException",
          ex);
      showError(response, "Could for forward to authentication service:" + ex.getMessage());
    } catch (ServletException se) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. ServletException",
          se);
      showError(response, "Could for forward to authentication service:" + se.getMessage());
    } catch (IllegalStateException ie) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. Illegal state",
          ie);
      showError(response, "Could for forward to authentication service:" + ie.getMessage());
    }
  }
Exemplo n.º 17
0
 /**
  * The entire request including query string
  *
  * @param req the HttpServletRequest
  * @return entire parsed request
  */
 public static String getRequest(HttpServletRequest req) {
   String query = req.getQueryString();
   return getRequestBase(req) + (query == null ? "" : "?" + query);
 }
Exemplo n.º 18
0
  /**
   * Redirects the HTTP request to the Authentication module. It gets the authentication url from
   * <code>SystemProperties</code>.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception IOException If an input or output exception occurs
   */
  private void redirectForAuthentication(
      HttpServletRequest request,
      HttpServletResponse response,
      String policyAdviceList,
      String requestParams)
      throws IOException {
    if (debug.messageEnabled()) {
      debug.message(
          "CDCClientServlet.redirectForAuthentication: " + "requestURL=" + request.getRequestURL());
    }
    StringBuilder redirectURL = new StringBuilder(100);
    StringBuilder gotoURL = new StringBuilder(100);

    // Check if user has authenticated to another OpenAM
    // instance
    String authURL = null;
    Cookie authCookie = CookieUtils.getCookieFromReq(request, authURLCookieName);
    if (authCookie != null) {
      authURL = CookieUtils.getCookieValue(authCookie);
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication: "
                + "got an authenticated URL= "
                + authURL);
      }
    }
    try {
      if (authURL == null
          || authURL.length() == 0
          || !authURL.toLowerCase().startsWith("http")
          || policyAdviceList != null) {
        String finalURL = request.getParameter(GOTO_PARAMETER);

        if (finalURL == null || finalURL.equals("")) {
          finalURL = request.getParameter(TARGET_PARAMETER);
        }

        if (finalURL == null || finalURL.equals("")) {
          if (debug.messageEnabled()) {
            debug.message(
                "CDCClientServlet.redirectForAuthentication: "
                    + "goto or target parameter is missing in the request.");
          }

          showError(response, SERVER_ERROR_STR_MATCH);
          return;
        }

        gotoURL
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(TARGET_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(finalURL))
            .append(AMPERSAND)
            .append(requestParams);

        // Construct the login URL
        String loginURI = request.getParameter(LOGIN_URI);
        String cdcUri;

        if (loginURI != null && !loginURI.isEmpty() && isValidCDCURI(loginURI)) {
          if (debug.messageEnabled()) {
            debug.message(
                "CDCClientServlet.redirectForAuthentication:found " + LOGIN_URI + "=" + loginURI);
          }

          cdcUri = loginURI;
        } else {
          cdcUri = cdcAuthURI;
        }

        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.redirectForAuthentication: Login URI is set to = " + cdcUri);
        }

        if (cdcUri.indexOf(QUESTION_MARK) == -1) {
          redirectURL.append(cdcUri).append(QUESTION_MARK);
        } else {
          redirectURL.append(cdcUri).append(AMPERSAND);
        }

        if (policyAdviceList != null) {
          redirectURL.append(policyAdviceList).append(AMPERSAND);
        }
        redirectURL
            .append(GOTO_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(gotoURL.toString()));

        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.redirectForAuthentication"
                  + ":redirectURL before dispatching is="
                  + redirectURL);
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher(redirectURL.toString());
        dispatcher.forward(request, response);
      } else {
        // Redirect the user to the authenticated URL
        redirectURL
            .append(authURL)
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(request.getQueryString());
        // Reset the cookie value to null, to avoid continuous loop
        // when a load balancer is used
        if (authCookie != null) {
          authCookie.setValue("");
          response.addCookie(authCookie);
        }
        response.sendRedirect(redirectURL.toString());
      }

      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication:"
                + "Forwarding for authentication to= "
                + redirectURL);
      }
    } catch (IOException ex) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication: Failed "
              + "in forwarding to Authentication service. IOException",
          ex);
      showError(response, "Could for forward to authentication service:" + ex.getMessage());
    } catch (ServletException se) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. ServletException",
          se);
      showError(response, "Could for forward to authentication service:" + se.getMessage());
    } catch (IllegalStateException ie) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. Illegal state",
          ie);
      showError(response, "Could for forward to authentication service:" + ie.getMessage());
    }
  }
Exemplo n.º 19
0
  public void generateFileDetails(JspWriter out, HttpServletRequest req, Configuration conf)
      throws IOException, InterruptedException {

    int chunkSizeToView = 0;
    long startOffset = 0;
    int datanodePort;

    String blockIdStr = null;
    long currBlockId = 0;
    blockIdStr = req.getParameter("blockId");
    if (blockIdStr == null) {
      out.print("Invalid input (blockId absent)");
      return;
    }
    currBlockId = Long.parseLong(blockIdStr);

    String datanodePortStr = req.getParameter("datanodePort");
    if (datanodePortStr == null) {
      out.print("Invalid input (datanodePort absent)");
      return;
    }
    datanodePort = Integer.parseInt(datanodePortStr);

    String namenodeInfoPortStr = req.getParameter("namenodeInfoPort");
    int namenodeInfoPort = -1;
    if (namenodeInfoPortStr != null) namenodeInfoPort = Integer.parseInt(namenodeInfoPortStr);

    String chunkSizeToViewStr = req.getParameter("chunkSizeToView");
    if (chunkSizeToViewStr != null && Integer.parseInt(chunkSizeToViewStr) > 0) {
      chunkSizeToView = Integer.parseInt(chunkSizeToViewStr);
    } else {
      chunkSizeToView = JspHelper.getDefaultChunkSize(conf);
    }

    String startOffsetStr = req.getParameter("startOffset");
    if (startOffsetStr == null || Long.parseLong(startOffsetStr) < 0) startOffset = 0;
    else startOffset = Long.parseLong(startOffsetStr);

    String filename = HtmlQuoting.unquoteHtmlChars(req.getParameter("filename"));
    if (filename == null || filename.length() == 0) {
      out.print("Invalid input");
      return;
    }

    String blockSizeStr = req.getParameter("blockSize");
    long blockSize = 0;
    if (blockSizeStr == null || blockSizeStr.length() == 0) {
      out.print("Invalid input");
      return;
    }
    blockSize = Long.parseLong(blockSizeStr);

    String tokenString = req.getParameter(JspHelper.DELEGATION_PARAMETER_NAME);
    UserGroupInformation ugi = JspHelper.getUGI(req, conf);
    DFSClient dfs = JspHelper.getDFSClient(ugi, jspHelper.nameNodeAddr, conf);
    List<LocatedBlock> blocks =
        dfs.namenode.getBlockLocations(filename, 0, Long.MAX_VALUE).getLocatedBlocks();
    // Add the various links for looking at the file contents
    // URL for downloading the full file
    String downloadUrl =
        "http://"
            + req.getServerName()
            + ":"
            + +req.getServerPort()
            + "/streamFile"
            + URLEncoder.encode(filename, "UTF-8")
            + "?"
            + JspHelper.DELEGATION_PARAMETER_NAME
            + "="
            + tokenString;
    out.print("<a name=\"viewOptions\"></a>");
    out.print("<a href=\"" + downloadUrl + "\">Download this file</a><br>");

    DatanodeInfo chosenNode;
    // URL for TAIL
    LocatedBlock lastBlk = blocks.get(blocks.size() - 1);
    long blockId = lastBlk.getBlock().getBlockId();
    try {
      chosenNode = jspHelper.bestNode(lastBlk);
    } catch (IOException e) {
      out.print(e.toString());
      dfs.close();
      return;
    }
    String fqdn = InetAddress.getByName(chosenNode.getHost()).getCanonicalHostName();
    String tailUrl =
        "http://"
            + fqdn
            + ":"
            + chosenNode.getInfoPort()
            + "/tail.jsp?filename="
            + URLEncoder.encode(filename, "UTF-8")
            + "&namenodeInfoPort="
            + namenodeInfoPort
            + "&chunkSizeToView="
            + chunkSizeToView
            + "&referrer="
            + URLEncoder.encode(req.getRequestURL() + "?" + req.getQueryString(), "UTF-8")
            + JspHelper.getDelegationTokenUrlParam(tokenString);
    out.print("<a href=\"" + tailUrl + "\">Tail this file</a><br>");

    out.print("<form action=\"/browseBlock.jsp\" method=GET>");
    out.print("<b>Chunk size to view (in bytes, up to file's DFS block size): </b>");
    out.print("<input type=\"hidden\" name=\"blockId\" value=\"" + currBlockId + "\">");
    out.print("<input type=\"hidden\" name=\"blockSize\" value=\"" + blockSize + "\">");
    out.print("<input type=\"hidden\" name=\"startOffset\" value=\"" + startOffset + "\">");
    out.print("<input type=\"hidden\" name=\"filename\" value=\"" + filename + "\">");
    out.print("<input type=\"hidden\" name=\"datanodePort\" value=\"" + datanodePort + "\">");
    out.print(
        "<input type=\"hidden\" name=\"namenodeInfoPort\" value=\"" + namenodeInfoPort + "\">");
    out.print(
        "<input type=\"text\" name=\"chunkSizeToView\" value="
            + chunkSizeToView
            + " size=10 maxlength=10>");
    out.print("&nbsp;&nbsp;<input type=\"submit\" name=\"submit\" value=\"Refresh\">");
    out.print("</form>");
    out.print("<hr>");
    out.print("<a name=\"blockDetails\"></a>");
    out.print("<B>Total number of blocks: " + blocks.size() + "</B><br>");
    // generate a table and dump the info
    out.println("\n<table>");
    for (LocatedBlock cur : blocks) {
      out.print("<tr>");
      blockId = cur.getBlock().getBlockId();
      blockSize = cur.getBlock().getNumBytes();
      String blk = "blk_" + Long.toString(blockId);
      out.print("<td>" + Long.toString(blockId) + ":</td>");
      DatanodeInfo[] locs = cur.getLocations();
      for (int j = 0; j < locs.length; j++) {
        String datanodeAddr = locs[j].getName();
        datanodePort =
            Integer.parseInt(
                datanodeAddr.substring(datanodeAddr.indexOf(':') + 1, datanodeAddr.length()));
        fqdn = InetAddress.getByName(locs[j].getHost()).getCanonicalHostName();
        String blockUrl =
            "http://"
                + fqdn
                + ":"
                + locs[j].getInfoPort()
                + "/browseBlock.jsp?blockId="
                + Long.toString(blockId)
                + "&blockSize="
                + blockSize
                + "&filename="
                + URLEncoder.encode(filename, "UTF-8")
                + "&datanodePort="
                + datanodePort
                + "&genstamp="
                + cur.getBlock().getGenerationStamp()
                + "&namenodeInfoPort="
                + namenodeInfoPort
                + "&chunkSizeToView="
                + chunkSizeToView;
        out.print(
            "<td>&nbsp</td>" + "<td><a href=\"" + blockUrl + "\">" + datanodeAddr + "</a></td>");
      }
      out.println("</tr>");
    }
    out.println("</table>");
    out.print("<hr>");
    String namenodeHost = jspHelper.nameNodeAddr.getHostName();
    out.print(
        "<br><a href=\"http://"
            + InetAddress.getByName(namenodeHost).getCanonicalHostName()
            + ":"
            + namenodeInfoPort
            + "/dfshealth.jsp\">Go back to DFS home</a>");
    dfs.close();
  }
Exemplo n.º 20
0
  /**
   * This the main method of this servlet which takes in the request opens a URLConnection to the
   * CDCServlet endpoint in the OpenAM, and tunnels the request content to it. It parses the
   * Response received and if the HTTP_STATUS is "HTTP_OK" or "HTTP_MOVED_TEMP" POSTs the received
   * Liberty Authn Response to the goto URL specified in the original request.
   */
  private void sendAuthnRequest(
      HttpServletRequest request, HttpServletResponse response, SSOToken token)
      throws ServletException, IOException {
    SessionID sessid = new SessionID(request);
    URL CDCServletURL = null;
    URL sessionServiceURL = null;
    try {
      sessionServiceURL = Session.getSessionServiceURL(sessid);
    } catch (SessionException se) {
      debug.error(
          "CDCClientServlet.sendAuthnRequest: Cannot locate" + " OpenAM instance to forward to.",
          se);
      showError(response, "Cannot locate OpenAM instance to forward to");
    }
    if (sessionServiceURL == null) {
      showError(response, "Cannot locate OpenAM instance to forward to");
    }
    // replace "sessionservice" by cdcservlet in obtained URL
    // we use naming so that we get the URL of the exact server
    // where the session is located and get the right deployment
    // descriptor.
    String sessionServiceURLString = sessionServiceURL.toString();
    int serviceNameIndex =
        sessionServiceURLString.lastIndexOf(
            "/", sessionServiceURLString.length() - 2); // avoiding trailing "/"
    // if any
    StringBuilder buffer = new StringBuilder(150);
    buffer
        .append(sessionServiceURLString.substring(0, serviceNameIndex))
        .append(CDCURI)
        .append(QUESTION_MARK)
        .append(request.getQueryString()); // add query string to
    // CDCServletURL

    CDCServletURL = new URL(buffer.toString());

    // save the go to URL of the agent side to ultimately
    // POST to.
    try {
      HttpURLConnection connection = HttpURLConnectionManager.getConnection(CDCServletURL);
      connection.setRequestMethod("GET");
      connection.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
      connection.setDoOutput(true);
      connection.setUseCaches(false);
      // replay cookies
      String strCookies = getCookiesFromRequest(request);
      if (strCookies != null) {
        if (debug.messageEnabled()) {
          debug.message("CDCClientServlet.sendAuthnRequest:Setting " + "cookies = " + strCookies);
        }
        connection.setRequestProperty("Cookie", strCookies);
      }
      // dont wish to follow redirect to agent, since
      // the response needs to go via the CDCClientServlet.
      HttpURLConnection.setFollowRedirects(false);

      // Receiving input from CDCServlet on the AM server instance
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.sendAuthnRequest:Getting " + "response back from  " + CDCServletURL);
        debug.message(
            "CDCClientServlet.sendAuthnRequest:Response " + "Code " + connection.getResponseCode());
        debug.message(
            "CDCClientServlet.sendAuthnRequest:Response "
                + "Message= "
                + connection.getResponseMessage());
      }

      // Check response code
      if ((connection.getResponseCode() == HttpURLConnection.HTTP_OK)
          || (connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP)) {
        /**
         * Read the response back from CDCServlet, got a redirect since this response contains the
         * "LARES" ( Liberty authn response, which needs to be posted back to the dest url (agent).
         */
        StringBuilder inBuf = new StringBuilder();
        BufferedReader in =
            new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        int len;
        char[] buf = new char[1024];
        while ((len = in.read(buf, 0, buf.length)) != -1) {
          inBuf.append(buf, 0, len);
        }
        String inString = inBuf.toString();
        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.sendAuthnRequest:" + "Received response data = " + inString);
        }
        // put the received Liberty Auth Response
        // in the servlet's response.
        sendAuthnResponse(request, response, inString);
      } else {
        debug.error("CDCClientServlet.sendAuthnRequest: Response " + "code NOT OK/MOVED_TEMP ");
        showError(
            response,
            "ERROR: Received HTTP error code "
                + connection.getResponseCode()
                + " from "
                + CDCServletURL);
      }
    } catch (ConnectException ce) {
      // Debug the exception
      if (debug.warningEnabled()) {
        debug.warning(
            "CDCClientServlet.sendAuthnRequest: " + "Connection Exception to " + CDCServletURL, ce);
      }
      showError(
          response, "Could not connect to CDCServlet at " + CDCServletURL + ":" + ce.getMessage());
    }
  }
Exemplo n.º 21
0
  // get pathInfo and parmameters from servlet call
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    PrintWriter pw = null;
    try {
      long startms = System.currentTimeMillis();

      if (cat == null || rm.nexradList == null) { // something major wrong
        res.sendError(
            HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
            "radarServer Radar Station/Catalog initialization problem");
        return;
      }
      // setup
      String pathInfo = req.getPathInfo();
      if (pathInfo == null) pathInfo = "";
      RadarType radarType = RadarType.nexrad; // default
      if (pathInfo.indexOf('/', 1) > 1) {
        String rt = pathInfo.substring(1, pathInfo.indexOf('/', 1));
        radarType = RadarType.valueOf(rt);
      }
      // default is xml, assume errors will be recorded by logger from this point
      if (!pathInfo.endsWith("html")) {
        pw = res.getWriter();
        res.setContentType("text/xml; charset=iso-8859-1"); // default
      }
      // radar  query
      if (req.getQueryString() != null) {
        // log.debug("RadarServer query ="+ req.getQueryString() );
        if (log.isDebugEnabled())
          log.debug("<documentation>\n" + req.getQueryString() + "</documentation>\n");
        rm.radarQuery(radarType, req, res, pw);
        if (log.isDebugEnabled())
          log.debug("after doGet " + (System.currentTimeMillis() - startms));
        pw.flush();
        return;
      }
      // return radarCollections catalog   xml or html
      if (pathInfo.startsWith("/catalog.xml") || pathInfo.startsWith("/dataset.xml")) {
        InvCatalogFactory factory = InvCatalogFactory.getDefaultFactory(false); // no validation
        String catAsString = factory.writeXML(cat);
        pw.println(catAsString);
        res.setStatus(HttpServletResponse.SC_OK);
        pw.flush();
        return;
      } else if (pathInfo.startsWith("/catalog.html") || pathInfo.startsWith("/dataset.html")) {
        try {
          int i =
              HtmlWriter.getInstance().writeCatalog(req, res, cat, true); // show catalog as HTML
        } catch (Exception e) {
          log.error("Radar HtmlWriter failed ", e);
          res.sendError(
              HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
              "radarServer HtmlWriter error " + pathInfo);
          return;
        }
        return;
      }
      // level2 and level3 catalog/dataset
      if (pathInfo.contains("level2/catalog.")
          || pathInfo.contains("level3/catalog.")
          || pathInfo.contains("level2/dataset.")
          || pathInfo.contains("level3/dataset.")) {
        level2level3catalog(radarType, pathInfo, pw, req, res);
        return;
      }
      // return stations of dataset
      if (pathInfo.endsWith("stations.xml")) {
        pathInfo = pathInfo.replace("/stations.xml", "");
        Element rootElem = new Element("stationsList");
        Document doc = new Document(rootElem);
        doc = rm.stationsXML(radarType, doc, rootElem, pathInfo.substring(1));
        XMLOutputter fmt = new XMLOutputter(Format.getPrettyFormat());
        pw.println(fmt.outputString(doc));
        pw.flush();
        return;
      }
      // return specific dataset information, ie IDD
      if (pathInfo.endsWith("dataset.xml") || pathInfo.endsWith("catalog.xml")) {
        datasetInfoXml(radarType, pathInfo, pw);
        return;
      }
      // needs work nobody using it now
      // return Dataset information in html form format
      if (pathInfo.endsWith("dataset.html") || pathInfo.endsWith("catalog.html")) {
        datasetInfoHtml(radarType, pathInfo, pw, res);
        return;
      }
      // mal formed request with no exceptions
      res.sendError(HttpServletResponse.SC_NOT_FOUND);

    } catch (FileNotFoundException e) {
      if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_NOT_FOUND);

    } catch (Throwable e) {
      log.error("RadarServer.doGet failed", e);
      if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  } // end doGet
Exemplo n.º 22
0
  public void getEnv(VariableTable vt) {
    Enumeration e = null;
    HttpServletRequest request = (HttpServletRequest) (pageContext.getRequest());
    HttpSession session = request.getSession(false);

    String db_charset = "gb2312";
    String url_charset = null;

    vt.remove("SESSION.LOGINID");
    vt.remove("SESSION.LOGINNAME");
    vt.remove("SESSION.LOGINROLE");

    if (vt.exists("WEBCHART.DB_CHARSET")) {
      db_charset = vt.getString("WEBCHART.DB_CHARSET");
    }

    if (vt.exists("WEBCHART.URL_CHARSET")) {
      url_charset = vt.getString("WEBCHART.URL_CHARSET");
    }

    if (session != null) {
      e = session.getAttributeNames();
      while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        Object value = session.getAttribute(name);
        vt.add(name, java.sql.Types.VARCHAR);
        if (value != null) vt.setValue(name, value.toString());
      }
      vt.add("SESSION.ID", java.sql.Types.VARCHAR);
      vt.setValue("SESSION.ID", session.getId());
      vt.add("SESSION.CREATE", java.sql.Types.VARCHAR);
      vt.setValue(
          "SESSION.CREATE",
          DBOperation.toString(
              new java.util.Date(session.getCreationTime()), "yyyy-MM-dd HH:mm:ss"));
      vt.add("SESSION.ACCESS", java.sql.Types.VARCHAR);
      vt.setValue(
          "SESSION.ACCESS",
          DBOperation.toString(
              new java.util.Date(session.getLastAccessedTime()), "yyyy-MM-dd HH:mm:ss"));
    }
    e = request.getParameterNames();
    while (e.hasMoreElements()) {
      String name = (String) e.nextElement();
      String value = request.getParameter(name);
      ;
      String par_values[] = request.getParameterValues(name);
      name = name.toUpperCase();
      if (name.equalsIgnoreCase("WEBCHART.SECURITY")
          || name.equalsIgnoreCase("WEBCHART.DEFAULTACCESS")
          || name.equalsIgnoreCase("WEBCHART.ALLOW")
          || name.equalsIgnoreCase("WEBCHART.DENY")
          || name.equalsIgnoreCase("WEBCHART.IPSECURITY")
          || name.equalsIgnoreCase("WEBCHART.IPACCESS")
          || name.equalsIgnoreCase("WEBCHART.IPALLOW")
          || name.equalsIgnoreCase("WEBCHART.IPDENY")
          || name.equalsIgnoreCase("WEBCHART.XSLDOC")
          || name.equalsIgnoreCase("WEBCHART.IMAGEONLY")
          || name.equalsIgnoreCase("WEBCHART.XMLDATA")
          || name.equalsIgnoreCase("WEBCHART.LOGSQL")
          || name.equalsIgnoreCase("WEBCHART.DATATYPE")
          || name.equalsIgnoreCase("WEBCHART.URLS")
          || name.equalsIgnoreCase("WEBCHART.TOPURLS")
          || name.equalsIgnoreCase("WEBCHART.TOPCURR")
          || name.equalsIgnoreCase("WEBCHART.LEFTURLS")
          || name.equalsIgnoreCase("WEBCHART.LEFTCURR")
          || name.equalsIgnoreCase("WEBCHART.INPUTS")
          || name.equalsIgnoreCase("WEBCHART.CACHE")
          || name.equalsIgnoreCase("WEBCHART.DATA")
          || name.equalsIgnoreCase("WEBCHART.CSS")
          || name.equalsIgnoreCase("WEBCHART.RELOAD")
          || name.equalsIgnoreCase("WEBCHART.EXPIRE")
          || name.equalsIgnoreCase("WEBCHART.DMLKEY")
          || name.equalsIgnoreCase("WEBCHART.ENGINE")
          || name.equalsIgnoreCase("WEBCHART.EXCELURL")
          || name.equalsIgnoreCase("WEBCHART.DBID")
          || name.equalsIgnoreCase("WEBCHART.DBIDSEED")
          || name.equalsIgnoreCase("WEBCHART.SECUREFIELDS")
          || name.equalsIgnoreCase("WEBCHART.KEEP_CACHE_IMAGE")
          || name.equalsIgnoreCase("WEBCHART.KEEP_CACHE_TIME")
          || name.startsWith("WEBCHART.SECUREMEMO")
          || name.startsWith("WEBCHART.QUERY_")
          || name.startsWith("WEBCHART.HEADHTML_")
          || name.startsWith("WEBCHART.DATAHTML_")
          || name.startsWith("WEBCHART.VARLIST_")
          || name.startsWith("WEBCHART.FORALL_")
          || name.startsWith("WEBCHART.XMLDATA_")
          || name.startsWith("WEBCHART.TABLE_")
          || name.startsWith("WEBCHART.COLUMN_")
          || name.startsWith("SESSION.")) continue;
      if (name.startsWith("WEBCHART.") && !name.equals("WEBCHART.DOCTYPE")) continue;
      vt.add(name, java.sql.Types.VARCHAR);

      if (par_values != null && par_values.length > 1) {
        StringBuffer temp = new StringBuffer();
        for (int i = 0; i < par_values.length; i++) {
          if (par_values[i] != null && par_values[i].trim().length() > 0) {
            if (temp.length() > 0) {
              temp.append(",");
            }
            temp.append(par_values[i]);
          }
        }
        value = temp.toString();
      }
      if (url_charset != null) {
        try {
          value = new String(value.getBytes(url_charset), db_charset);
        } catch (java.io.UnsupportedEncodingException uee) {
        }
        ;
      }
      vt.setValue(name, value);
    }
    vt.add("REQUEST.REMOTEADDR", java.sql.Types.VARCHAR);
    vt.setValue("REQUEST.REMOTEADDR", getClientIPAddr());
    vt.add("REQUEST.REMOTEHOST", java.sql.Types.VARCHAR);
    vt.setValue("REQUEST.REMOTEHOST", request.getRemoteAddr());
    vt.add("REQUEST.REFERER", java.sql.Types.VARCHAR);
    vt.setValue("REQUEST.REFERER", request.getHeader("Referer"));
    vt.add("REQUEST.QUERYSTRING", java.sql.Types.VARCHAR);
    vt.setValue("REQUEST.QUERYSTRING", request.getQueryString());
  }
Exemplo n.º 23
0
  /**
   * Show details about the request
   *
   * @param servlet used to get teh servlet context, may be null
   * @param req the request
   * @return string showing the details of the request.
   */
  public static String showRequestDetail(HttpServlet servlet, HttpServletRequest req) {
    StringBuilder sbuff = new StringBuilder();

    sbuff.append("Request Info\n");
    sbuff.append(" req.getServerName(): ").append(req.getServerName()).append("\n");
    sbuff.append(" req.getServerPort(): ").append(req.getServerPort()).append("\n");
    sbuff.append(" req.getContextPath:").append(req.getContextPath()).append("\n");
    sbuff.append(" req.getServletPath:").append(req.getServletPath()).append("\n");
    sbuff.append(" req.getPathInfo:").append(req.getPathInfo()).append("\n");
    sbuff.append(" req.getQueryString:").append(req.getQueryString()).append("\n");
    sbuff
        .append(" getQueryStringDecoded:")
        .append(EscapeStrings.urlDecode(req.getQueryString()))
        .append("\n");
    /*try {
      sbuff.append(" getQueryStringDecoded:").append(URLDecoder.decode(req.getQueryString(), "UTF-8")).append("\n");
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }*/
    sbuff.append(" req.getRequestURI:").append(req.getRequestURI()).append("\n");
    sbuff.append(" getRequestBase:").append(getRequestBase(req)).append("\n");
    sbuff.append(" getRequestServer:").append(getRequestServer(req)).append("\n");
    sbuff.append(" getRequest:").append(getRequest(req)).append("\n");
    sbuff.append("\n");

    sbuff.append(" req.getPathTranslated:").append(req.getPathTranslated()).append("\n");
    String path = req.getPathTranslated();
    if ((path != null) && (servlet != null)) {
      ServletContext context = servlet.getServletContext();
      sbuff.append(" getMimeType:").append(context.getMimeType(path)).append("\n");
    }
    sbuff.append("\n");
    sbuff.append(" req.getScheme:").append(req.getScheme()).append("\n");
    sbuff.append(" req.getProtocol:").append(req.getProtocol()).append("\n");
    sbuff.append(" req.getMethod:").append(req.getMethod()).append("\n");
    sbuff.append("\n");
    sbuff.append(" req.getContentType:").append(req.getContentType()).append("\n");
    sbuff.append(" req.getContentLength:").append(req.getContentLength()).append("\n");

    sbuff.append(" req.getRemoteAddr():").append(req.getRemoteAddr());
    try {
      sbuff
          .append(" getRemoteHost():")
          .append(java.net.InetAddress.getByName(req.getRemoteHost()).getHostName())
          .append("\n");
    } catch (java.net.UnknownHostException e) {
      sbuff.append(" getRemoteHost():").append(e.getMessage()).append("\n");
    }
    sbuff.append(" getRemoteUser():").append(req.getRemoteUser()).append("\n");

    sbuff.append("\n");
    sbuff.append("Request Parameters:\n");
    Enumeration params = req.getParameterNames();
    while (params.hasMoreElements()) {
      String name = (String) params.nextElement();
      String values[] = req.getParameterValues(name);
      if (values != null) {
        for (int i = 0; i < values.length; i++) {
          sbuff
              .append("  ")
              .append(name)
              .append("  (")
              .append(i)
              .append("): ")
              .append(values[i])
              .append("\n");
        }
      }
    }
    sbuff.append("\n");

    sbuff.append("Request Headers:\n");
    Enumeration names = req.getHeaderNames();
    while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      Enumeration values = req.getHeaders(name); // support multiple values
      if (values != null) {
        while (values.hasMoreElements()) {
          String value = (String) values.nextElement();
          sbuff.append("  ").append(name).append(": ").append(value).append("\n");
        }
      }
    }
    sbuff.append(" ------------------\n");

    return sbuff.toString();
  }
Exemplo n.º 24
0
  /**
   * Constructs a new MultipartRequest to handle the specified request, saving any uploaded files to
   * the given directory, and limiting the upload size to the specified length. If the content is
   * too large, an IOException is thrown. This constructor actually parses the
   * <tt>multipart/form-data</tt> and throws an IOException if there's any problem reading or
   * parsing the request.
   *
   * <p>To avoid file collisions, this constructor takes an implementation of the FileRenamePolicy
   * interface to allow a pluggable rename policy.
   *
   * @param request the servlet request.
   * @param saveDirectory the directory in which to save any uploaded files.
   * @param maxPostSize the maximum size of the POST content.
   * @param encoding the encoding of the response, such as ISO-8859-1
   * @param policy a pluggable file rename policy
   * @exception IOException if the uploaded content is larger than <tt>maxPostSize</tt> or there's a
   *     problem reading or parsing the request.
   */
  public MultipartRequest(
      HttpServletRequest request,
      String saveDirectory,
      int maxPostSize,
      String encoding,
      FileRenamePolicy policy)
      throws IOException {
    // Sanity check values
    if (request == null) throw new IllegalArgumentException("request cannot be null");
    if (saveDirectory == null) throw new IllegalArgumentException("saveDirectory cannot be null");
    if (maxPostSize <= 0) {
      throw new IllegalArgumentException("maxPostSize must be positive");
    }

    // Save the dir
    File dir = new File(saveDirectory);

    // Check saveDirectory is truly a directory
    if (!dir.isDirectory()) throw new IllegalArgumentException("Not a directory: " + saveDirectory);

    // Check saveDirectory is writable
    if (!dir.canWrite()) throw new IllegalArgumentException("Not writable: " + saveDirectory);

    // Parse the incoming multipart, storing files in the dir provided,
    // and populate the meta objects which describe what we found
    MultipartParser parser = new MultipartParser(request, maxPostSize, true, true, encoding);

    // Some people like to fetch query string parameters from
    // MultipartRequest, so here we make that possible.  Thanks to
    // Ben Johnson, [email protected], for the idea.
    if (request.getQueryString() != null) {
      // Let HttpUtils create a name->String[] structure
      Hashtable queryParameters = HttpUtils.parseQueryString(request.getQueryString());
      // For our own use, name it a name->Vector structure
      Enumeration queryParameterNames = queryParameters.keys();
      while (queryParameterNames.hasMoreElements()) {
        Object paramName = queryParameterNames.nextElement();
        String[] values = (String[]) queryParameters.get(paramName);
        Vector newValues = new Vector();
        for (int i = 0; i < values.length; i++) {
          newValues.add(values[i]);
        }
        parameters.put(paramName, newValues);
      }
    }

    Part part;
    while ((part = parser.readNextPart()) != null) {
      String name = part.getName();
      if (name == null) {
        throw new IOException("Malformed input: parameter name missing (known Opera 7 bug)");
      }
      if (part.isParam()) {
        // It's a parameter part, add it to the vector of values
        ParamPart paramPart = (ParamPart) part;
        String value = paramPart.getStringValue();
        Vector existingValues = (Vector) parameters.get(name);
        if (existingValues == null) {
          existingValues = new Vector();
          parameters.put(name, existingValues);
        }
        existingValues.addElement(value);
      } else if (part.isFile()) {
        // It's a file part
        FilePart filePart = (FilePart) part;
        String fileName = filePart.getFileName();
        if (fileName != null) {
          filePart.setRenamePolicy(policy); // null policy is OK
          // The part actually contained a file
          filePart.writeTo(dir);
          files.put(
              name,
              new UploadedFile(
                  dir.toString(), filePart.getFileName(), fileName, filePart.getContentType()));
        } else {
          // The field did not contain a file
          files.put(name, new UploadedFile(null, null, null, null));
        }
      }
    }
  }
Exemplo n.º 25
0
    public Writer getErrorReport(
        Writer to, final HttpServletRequest request, CharTransformer escape) throws IOException {
      final Writer logMsg = new StringWriter();
      final Writer tee = new org.mmbase.util.ChainedWriter(to, logMsg);
      Writer msg = tee;

      LinkedList<Throwable> stack = getStack();
      String ticket = new Date().toString();

      Map<String, String> props;
      try {
        props = org.mmbase.util.ApplicationContextReader.getProperties("mmbase_errorpage");
      } catch (javax.naming.NamingException ne) {
        props = Collections.emptyMap();
        log.info(ne);
      }

      if (request != null) {
        {
          msg.append("Headers\n----------\n");
          // request properties
          for (Object name : Collections.list(request.getHeaderNames())) {
            msg.append(
                escape.transform(
                    name + ": " + escape.transform(request.getHeader((String) name)) + "\n"));
          }
        }
        {
          msg.append("\nAttributes\n----------\n");
          Pattern p = requestIgnore;
          if (p == null && props.get("request_ignore") != null) {
            p = Pattern.compile(props.get("request_ignore"));
          }
          for (Object name : Collections.list(request.getAttributeNames())) {
            if (p == null || !p.matcher((String) name).matches()) {
              msg.append(
                  escape.transform(name + ": " + request.getAttribute((String) name) + "\n"));
            }
          }
        }
        if (Boolean.TRUE.equals(showSession)
            || (showSession == null && !"false".equals(props.get("show_session")))) {
          HttpSession ses = request.getSession(false);
          if (ses != null) {
            msg.append("\nSession\n----------\n");
            Pattern p = sessionIgnore;
            if (p == null && props.get("session_ignore") != null) {
              p = Pattern.compile(props.get("session_ignore"));
            }
            for (Object name : Collections.list(ses.getAttributeNames())) {
              if (p == null || !p.matcher((String) name).matches()) {
                msg.append(escape.transform(name + ": " + ses.getAttribute((String) name) + "\n"));
              }
            }
          }
        }
      }
      msg.append("\n");
      msg.append("Misc. properties\n----------\n");

      if (request != null) {
        msg.append("method: ").append(escape.transform(request.getMethod())).append("\n");
        msg.append("querystring: ").append(escape.transform(request.getQueryString())).append("\n");
        msg.append("requesturl: ")
            .append(escape.transform(request.getRequestURL().toString()))
            .append("\n");
      }
      if (Boolean.TRUE.equals(showMMBaseVersion)
          || (showMMBaseVersion == null && !"false".equals(props.get("show_mmbase_version")))) {
        msg.append("mmbase version: ").append(org.mmbase.Version.get()).append("\n");
      }
      msg.append("status: ").append("").append(String.valueOf(status)).append("\n\n");

      if (request != null) {
        msg.append("Parameters\n----------\n");
        // request parameters
        Enumeration en = request.getParameterNames();
        while (en.hasMoreElements()) {
          String name = (String) en.nextElement();
          msg.append(name)
              .append(": ")
              .append(escape.transform(request.getParameter(name)))
              .append("\n");
        }
      }
      msg.append("\nException ")
          .append(ticket)
          .append("\n----------\n\n")
          .append(
              exception != null
                  ? (escape.transform(exception.getClass().getName()))
                  : "NO EXCEPTION")
          .append(": ");

      int wroteCauses = 0;
      while (!stack.isEmpty()) {

        Throwable t = stack.removeFirst();
        // add stack stacktraces
        if (t != null) {
          if (stack.isEmpty()) { // write last message always
            msg = tee;
          }
          String message = t.getMessage();
          if (msg != tee) {
            to.append("\n=== skipped(see log)  : ")
                .append(escape.transform(t.getClass().getName()))
                .append(": ")
                .append(message)
                .append("\n");
          }

          msg.append("\n\n").append(escape.transform(t.getClass().getName() + ": " + message));
          StackTraceElement[] stackTrace = t.getStackTrace();
          for (StackTraceElement e : stackTrace) {
            msg.append("\n        at ").append(escape.transform(e.toString()));
          }
          if (!stack.isEmpty()) {
            msg.append("\n-------caused:\n");
          }
          wroteCauses++;
          if (wroteCauses >= MAX_CAUSES) {
            msg = logMsg;
          }
        }
      }
      // write errors to  log
      if (status == 500) {
        try {
          if (props.get("to") != null && props.get("to").length() > 0) {
            javax.naming.Context initCtx = new javax.naming.InitialContext();
            javax.naming.Context envCtx = (javax.naming.Context) initCtx.lookup("java:comp/env");
            Object mailSession = envCtx.lookup("mail/Session");
            Class sessionClass = Class.forName("javax.mail.Session");
            Class recipientTypeClass = Class.forName("javax.mail.Message$RecipientType");
            Class messageClass = Class.forName("javax.mail.internet.MimeMessage");
            Object mail = messageClass.getConstructor(sessionClass).newInstance(mailSession);
            messageClass
                .getMethod("addRecipients", recipientTypeClass, String.class)
                .invoke(mail, recipientTypeClass.getDeclaredField("TO").get(null), props.get("to"));
            messageClass.getMethod("setSubject", String.class).invoke(mail, ticket);
            mail.getClass().getMethod("setText", String.class).invoke(mail, logMsg.toString());
            Class.forName("javax.mail.Transport")
                .getMethod("send", Class.forName("javax.mail.Message"))
                .invoke(null, mail);
            tee.append("\nmailed to (").append(String.valueOf(props)).append(")");
          }

        } catch (Exception nnfe) {
          tee.append("\nnot mailed (").append(String.valueOf(nnfe)).append(")");
          if (log.isDebugEnabled()) {
            log.debug(nnfe.getMessage(), nnfe);
          }
        }
        log.error("TICKET " + ticket + ":\n" + logMsg);
      }
      return to;
    }
Exemplo n.º 26
0
 public void doGet(HttpServletRequest request, HttpServletResponse response) {
   response.setContentType("text/html");
   PrintWriter webPageOutput = null;
   try {
     webPageOutput = response.getWriter();
   } catch (IOException error) {
     Routines.writeToLog(servletName, "getWriter error : " + error, false, context);
   }
   HttpSession session = request.getSession();
   session.setAttribute("redirect", request.getRequestURL() + "?" + request.getQueryString());
   Connection database = null;
   try {
     database = pool.getConnection(servletName);
   } catch (SQLException error) {
     Routines.writeToLog(servletName, "Unable to connect to database : " + error, false, context);
   }
   if (Routines.loginCheck(true, request, response, database, context)) {
     return;
   }
   String server = context.getInitParameter("server");
   boolean liveSever = false;
   if (server == null) {
     server = "";
   }
   if (server.equals("live")) {
     response.setHeader("Refresh", "60");
   }
   Routines.WriteHTMLHead(
       "View System Log", // title
       false, // showMenu
       13, // menuHighLight
       false, // seasonsMenu
       false, // weeksMenu
       false, // scores
       false, // standings
       false, // gameCenter
       false, // schedules
       false, // previews
       false, // teamCenter
       false, // draft
       database, // database
       request, // request
       response, // response
       webPageOutput, // webPageOutput
       context); // context
   webPageOutput.println("<CENTER>");
   webPageOutput.println(
       "<IMG SRC=\"../Images/Admin.gif\"" + " WIDTH='125' HEIGHT='115' ALT='Admin'>");
   webPageOutput.println("</CENTER>");
   pool.returnConnection(database);
   webPageOutput.println(Routines.spaceLines(1));
   Routines.tableStart(false, webPageOutput);
   Routines.tableHeader("System Log", 0, webPageOutput);
   Routines.tableDataStart(true, false, false, true, true, 0, 0, "scoresrow", webPageOutput);
   boolean firstLine = true;
   int numOfLines = 0;
   try {
     String file = context.getRealPath("/");
     FileReader logFile = new FileReader(file + "/Data/log.txt");
     BufferedReader logFileBuffer = new BufferedReader(logFile);
     boolean endOfFile = false;
     while (!endOfFile) {
       String logFileText = logFileBuffer.readLine();
       if (logFileText == null) {
         endOfFile = true;
       } else {
         if (firstLine) {
           firstLine = false;
         } else {
           webPageOutput.println(Routines.spaceLines(1));
         }
         numOfLines++;
         webPageOutput.println(logFileText);
       }
     }
     logFileBuffer.close();
   } catch (IOException error) {
     Routines.writeToLog(servletName, "Problem with log file : " + error, false, context);
   }
   Routines.tableDataEnd(false, true, true, webPageOutput);
   Routines.tableEnd(webPageOutput);
   if (numOfLines < 20) {
     webPageOutput.println(Routines.spaceLines(20 - numOfLines));
   }
   Routines.WriteHTMLTail(request, response, webPageOutput);
 }
  // authentication response
  public Account verifyResponse(HttpServletRequest httpReq) throws ServletException {

    try {
      // extract the parameters from the authentication response
      // (which comes in as a HTTP request from the OpenID provider)
      ParameterList response = new ParameterList(httpReq.getParameterMap());

      // retrieve the previously stored discovery information
      DiscoveryInformation discovered =
          (DiscoveryInformation) httpReq.getSession().getAttribute("openid-disc");

      // extract the receiving URL from the HTTP request
      StringBuffer receivingURL = httpReq.getRequestURL();
      String queryString = httpReq.getQueryString();
      if (queryString != null && queryString.length() > 0)
        receivingURL.append("?").append(httpReq.getQueryString());

      // verify the response; ConsumerManager needs to be the same
      // (static) instance used to place the authentication request
      VerificationResult verification =
          manager.verify(receivingURL.toString(), response, discovered);

      // examine the verification result and extract the verified
      // identifier
      Identifier verified = verification.getVerifiedId();
      if (verified != null) {
        // success

        String accountName = AccountImpl.escape(verified.getIdentifier());
        AbstractAccount account = (AbstractAccount) OpenIDRealm.instance.getAccount(accountName);
        if (account == null) {
          Database db = OpenIDRealm.instance.getDatabase();
          org.exist.security.Subject currentSubject = db.getSubject();
          try {
            db.setSubject(db.getSecurityManager().getSystemSubject());

            // XXX: set OpenID group by default
            account =
                (AbstractAccount)
                    OpenIDRealm.instance.addAccount(
                        new UserAider(OpenIDRealm.instance.getId(), accountName));
          } finally {
            db.setSubject(currentSubject);
          }
        }

        org.exist.security.Subject principal = new SubjectAccreditedImpl(account, verified);

        AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
        authSuccess.getExtensions();

        if (authSuccess.hasExtension(SRegMessage.OPENID_NS_SREG)) {
          MessageExtension ext = authSuccess.getExtension(SRegMessage.OPENID_NS_SREG);
          if (ext instanceof SRegResponse) {
            SRegResponse sregResp = (SRegResponse) ext;
            for (Iterator iter = sregResp.getAttributeNames().iterator(); iter.hasNext(); ) {
              String name = (String) iter.next();
              if (LOG.isDebugEnabled()) LOG.debug(name + " : " + sregResp.getParameterValue(name));
              principal.setMetadataValue(
                  AXSchemaType.valueOfNamespace(name), sregResp.getParameterValue(name));
            }
          }
        }
        if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
          FetchResponse fetchResp =
              (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);

          List aliases = fetchResp.getAttributeAliases();
          for (Iterator iter = aliases.iterator(); iter.hasNext(); ) {
            String alias = (String) iter.next();
            List values = fetchResp.getAttributeValues(alias);
            if (values.size() > 0) {
              if (LOG.isDebugEnabled()) LOG.debug(alias + " : " + values.get(0));
              principal.setMetadataValue(AXSchemaType.valueOfAlias(alias), (String) values.get(0));
            }
          }
        }
        // update metadata
        Database db = OpenIDRealm.instance.getDatabase();
        org.exist.security.Subject currentSubject = db.getSubject();
        try {
          db.setSubject(db.getSecurityManager().getSystemSubject());

          OpenIDRealm.instance.updateAccount(principal);
        } finally {
          db.setSubject(currentSubject);
        }

        OpenIDUtility.registerUser(principal);
        return principal;
      }
    } catch (OpenIDException e) {
      LOG.error(e);
    } catch (ConfigurationException e) {
      LOG.error(e);
    } catch (PermissionDeniedException e) {
      LOG.error(e);
    } catch (EXistException e) {
      LOG.error(e);
    }

    return null;
  }