Пример #1
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]);
      }
    }
  }
Пример #2
0
 // Update the agent URL in the agent details if not already done
 private void updateAgentDetailsIfNeeded(HttpServletRequest pReq) {
   // Lookup the Agent URL if needed
   AgentDetails details = backendManager.getAgentDetails();
   if (details.isInitRequired()) {
     synchronized (details) {
       if (details.isInitRequired()) {
         if (details.isUrlMissing()) {
           String url =
               getBaseUrl(
                   NetworkUtil.sanitizeLocalUrl(pReq.getRequestURL().toString()),
                   extractServletPath(pReq));
           details.setUrl(url);
         }
         if (details.isSecuredMissing()) {
           details.setSecured(pReq.getAuthType() != null);
         }
         details.seal();
       }
     }
   }
 }
Пример #3
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]);
      }
    }
  }
Пример #4
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;
    }
Пример #5
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());
    }
  }
Пример #6
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());
    }
  }
Пример #7
0
 /**
  * This is everything except the query string
  *
  * @param req the HttpServletRequest
  * @return parsed request base
  */
 public static String getRequestBase(HttpServletRequest req) {
   // return "http://"+req.getServerName()+":"+ req.getServerPort()+req.getRequestURI();
   return req.getRequestURL().toString();
 }
Пример #8
0
  /**
   * Handle a request for a raw/static file (i.e., not a catalog or dataset request).
   *
   * <p>Look in the content (user) directory then the root (distribution) directory for a file that
   * matches the given path and, if found, return it as the content of the HttpServletResponse. If
   * the file is forbidden (i.e., the path contains a "..", "WEB-INF", or "META-INF" directory),
   * send a HttpServletResponse.SC_FORBIDDEN response. If no file matches the request (including an
   * "index.html" file if the path ends in "/"), send an HttpServletResponse.SC_NOT_FOUND..
   *
   * <p>
   *
   * <ol>
   *   <li>Make sure the path does not contain ".." directories.
   *   <li>Make sure the path does not contain "WEB-INF" or "META-INF".
   *   <li>Check for requested file in the content directory (if the path is a directory, make sure
   *       the path ends with "/" and check for an "index.html" file).
   *   <li>Check for requested file in the root directory (if the path is a directory, make sure the
   *       path ends with "/" and check for an "index.html" file). </ol
   *
   * @param path the requested path
   * @param servlet the servlet handling the request
   * @param req the HttpServletRequest
   * @param res the HttpServletResponse
   * @throws IOException if can't complete request due to IO problems.
   */
  public static void handleRequestForRawFile(
      String path, HttpServlet servlet, HttpServletRequest req, HttpServletResponse res)
      throws IOException {
    // Don't allow ".." directories in path.
    if (path.indexOf("/../") != -1
        || path.equals("..")
        || path.startsWith("../")
        || path.endsWith("/..")) {
      res.sendError(HttpServletResponse.SC_FORBIDDEN, "Path cannot contain \"..\" directory.");
      log.info(UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_FORBIDDEN, -1));
      return;
    }

    // Don't allow access to WEB-INF or META-INF directories.
    String upper = path.toUpperCase();
    if (upper.indexOf("WEB-INF") != -1 || upper.indexOf("META-INF") != -1) {
      res.sendError(
          HttpServletResponse.SC_FORBIDDEN, "Path cannot contain \"WEB-INF\" or \"META-INF\".");
      log.info(UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_FORBIDDEN, -1));
      return;
    }

    // Find a regular file
    File regFile = null;
    // Look in content directory for regular file.
    File cFile = new File(ServletUtil.formFilename(getContentPath(), path));
    if (cFile.exists()) {
      if (cFile.isDirectory()) {
        if (!path.endsWith("/")) {
          String newPath = req.getRequestURL().append("/").toString();
          ServletUtil.sendPermanentRedirect(newPath, req, res);
        }
        // If request path is a directory, check for index.html file.
        cFile = new File(cFile, "index.html");
        if (cFile.exists() && !cFile.isDirectory()) regFile = cFile;
      }
      // If not a directory, use this file.
      else regFile = cFile;
    }

    if (regFile == null) {
      // Look in root directory.
      File rFile = new File(ServletUtil.formFilename(getRootPath(), path));
      if (rFile.exists()) {
        if (rFile.isDirectory()) {
          if (!path.endsWith("/")) {
            String newPath = req.getRequestURL().append("/").toString();
            ServletUtil.sendPermanentRedirect(newPath, req, res);
          }
          rFile = new File(rFile, "index.html");
          if (rFile.exists() && !rFile.isDirectory()) regFile = rFile;
        } else regFile = rFile;
      }
    }

    if (regFile == null) {
      res.sendError(HttpServletResponse.SC_NOT_FOUND); // 404
      log.info(UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, -1));
      return;
    }

    ServletUtil.returnFile(servlet, req, res, regFile, null);
  }
Пример #9
0
  /**
   * Convenience routine used by handleRequestForContentFile() and handleRequestForRootFile().
   *
   * @param pathPrefix
   * @param path
   * @param servlet
   * @param req request
   * @param res response
   * @throws IOException on IO error
   */
  private static void handleRequestForContentOrRootFile(
      String pathPrefix,
      String path,
      HttpServlet servlet,
      HttpServletRequest req,
      HttpServletResponse res)
      throws IOException {
    if (!pathPrefix.equals("/content/") && !pathPrefix.equals("/root/")) {
      log.error(
          "handleRequestForContentFile(): The path prefix <"
              + pathPrefix
              + "> must be \"/content/\" or \"/root/\".");
      throw new IllegalArgumentException("Path prefix must be \"/content/\" or \"/root/\".");
    }

    if (!path.startsWith(pathPrefix)) {
      log.error(
          "handleRequestForContentFile(): path <"
              + path
              + "> must start with \""
              + pathPrefix
              + "\".");
      throw new IllegalArgumentException("Path must start with \"" + pathPrefix + "\".");
    }

    // Don't allow ".." directories in path.
    if (path.indexOf("/../") != -1
        || path.equals("..")
        || path.startsWith("../")
        || path.endsWith("/..")) {
      res.sendError(HttpServletResponse.SC_FORBIDDEN, "Path cannot contain \"..\" directory.");
      log.info(UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_FORBIDDEN, -1));
      return;
    }

    // Find the requested file.
    File file =
        new File(
            ServletUtil.formFilename(getContentPath(), path.substring(pathPrefix.length() - 1)));
    if (file.exists()) {
      // Do not allow request for a directory.
      if (file.isDirectory()) {
        if (!path.endsWith("/")) {
          String redirectPath = req.getRequestURL().append("/").toString();
          ServletUtil.sendPermanentRedirect(redirectPath, req, res);
          return;
        }

        int i = HtmlWriter.getInstance().writeDirectory(res, file, path);
        int status = i == 0 ? HttpServletResponse.SC_NOT_FOUND : HttpServletResponse.SC_OK;
        log.info(UsageLog.closingMessageForRequestContext(status, i));

        return;
      }

      // Return the requested file.
      ServletUtil.returnFile(servlet, req, res, file, null);
    } else {
      // Requested file not found.
      log.info(UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, -1));
      res.sendError(HttpServletResponse.SC_NOT_FOUND); // 404
    }
  }
  // authentication request
  public String authRequest(
      String userSuppliedString, HttpServletRequest httpReq, HttpServletResponse httpResp)
      throws IOException, ServletException {

    if (OpenIDRealm.instance == null) {
      ServletOutputStream out = httpResp.getOutputStream();
      httpResp.setContentType("text/html; charset=\"UTF-8\"");
      httpResp.addHeader("pragma", "no-cache");
      httpResp.addHeader("Cache-Control", "no-cache");

      httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      out.print("<html><head>");
      out.print("<title>OpenIDServlet Error</title>");
      out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>");
      out.print("<body><div id=\"container\"><h1>Error found</h1>");

      out.print("<h2>Message:");
      out.print("OpenID realm wasn't initialized.");
      out.print("</h2>");

      // out.print(HTTPUtils.printStackTraceHTML(t));

      out.print("</div></body></html>");
      return null;
    }
    try {
      String returnAfterAuthentication = httpReq.getParameter("return_to");

      // configure the return_to URL where your application will receive
      // the authentication responses from the OpenID provider
      String returnToUrl =
          httpReq.getRequestURL().toString()
              + "?is_return=true&exist_return="
              + returnAfterAuthentication;

      // perform discovery on the user-supplied identifier
      List<?> discoveries = manager.discover(userSuppliedString);

      // attempt to associate with the OpenID provider
      // and retrieve one service endpoint for authentication
      DiscoveryInformation discovered = manager.associate(discoveries);

      // store the discovery information in the user's session
      httpReq.getSession().setAttribute("openid-disc", discovered);

      // obtain a AuthRequest message to be sent to the OpenID provider
      AuthRequest authReq = manager.authenticate(discovered, returnToUrl);

      if (authReq.getOPEndpoint().indexOf("myopenid.com") > 0) {
        SRegRequest sregReq = SRegRequest.createFetchRequest();

        sregReq.addAttribute(AXSchemaType.FULLNAME.name().toLowerCase(), true);
        sregReq.addAttribute(AXSchemaType.EMAIL.name().toLowerCase(), true);
        sregReq.addAttribute(AXSchemaType.COUNTRY.name().toLowerCase(), true);
        sregReq.addAttribute(AXSchemaType.LANGUAGE.name().toLowerCase(), true);

        authReq.addExtension(sregReq);
      } else {

        FetchRequest fetch = FetchRequest.createFetchRequest();

        fetch.addAttribute(
            AXSchemaType.FIRSTNAME.getAlias(), AXSchemaType.FIRSTNAME.getNamespace(), true);
        fetch.addAttribute(
            AXSchemaType.LASTNAME.getAlias(), AXSchemaType.LASTNAME.getNamespace(), true);
        fetch.addAttribute(AXSchemaType.EMAIL.getAlias(), AXSchemaType.EMAIL.getNamespace(), true);
        fetch.addAttribute(
            AXSchemaType.COUNTRY.getAlias(), AXSchemaType.COUNTRY.getNamespace(), true);
        fetch.addAttribute(
            AXSchemaType.LANGUAGE.getAlias(), AXSchemaType.LANGUAGE.getNamespace(), true);

        // wants up to three email addresses
        fetch.setCount(AXSchemaType.EMAIL.getAlias(), 3);

        authReq.addExtension(fetch);
      }

      if (!discovered.isVersion2()) {
        // Option 1: GET HTTP-redirect to the OpenID Provider endpoint
        // The only method supported in OpenID 1.x
        // redirect-URL usually limited ~2048 bytes
        httpResp.sendRedirect(authReq.getDestinationUrl(true));
        return null;

      } else {
        // Option 2: HTML FORM Redirection (Allows payloads >2048 bytes)

        Object OPEndpoint = authReq.getDestinationUrl(false);

        ServletOutputStream out = httpResp.getOutputStream();

        httpResp.setContentType("text/html; charset=UTF-8");
        httpResp.addHeader("pragma", "no-cache");
        httpResp.addHeader("Cache-Control", "no-cache");

        out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        out.println("<head>");
        out.println("    <title>OpenID HTML FORM Redirection</title>");
        out.println("</head>");
        out.println("<body onload=\"document.forms['openid-form-redirection'].submit();\">");
        out.println(
            "    <form name=\"openid-form-redirection\" action=\""
                + OPEndpoint
                + "\" method=\"post\" accept-charset=\"utf-8\">");

        Map<String, String> parameterMap = authReq.getParameterMap();
        for (Entry<String, String> entry : parameterMap.entrySet()) {
          out.println(
              "	<input type=\"hidden\" name=\""
                  + entry.getKey()
                  + "\" value=\""
                  + entry.getValue()
                  + "\"/>");
        }

        out.println("        <button type=\"submit\">Continue...</button>");
        out.println("    </form>");
        out.println("</body>");
        out.println("</html>");

        out.flush();
      }
    } catch (OpenIDException e) {
      // present error to the user
      LOG.debug("OpenIDException", e);

      ServletOutputStream out = httpResp.getOutputStream();
      httpResp.setContentType("text/html; charset=\"UTF-8\"");
      httpResp.addHeader("pragma", "no-cache");
      httpResp.addHeader("Cache-Control", "no-cache");

      httpResp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      out.print("<html><head>");
      out.print("<title>OpenIDServlet Error</title>");
      out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"error.css\"></link></head>");
      out.print("<body><div id=\"container\"><h1>Error found</h1>");

      out.print("<h2>Message:");
      out.print(e.getMessage());
      out.print("</h2>");

      Throwable t = e.getCause();
      if (t != null) {
        // t can be null
        out.print(HTTPUtils.printStackTraceHTML(t));
      }

      out.print("</div></body></html>");
    }

    return null;
  }
  // 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;
  }
Пример #12
0
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    JspFactory _jspxFactory = null;
    javax.servlet.jsp.PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;

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

      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");

      /** This include page ensures that the handler exists and is ready to be accessed. */
      CrawlJobHandler handler = (CrawlJobHandler) application.getAttribute("handler");
      Heritrix heritrix = (Heritrix) application.getAttribute("heritrix");

      // If handler is empty then this is the first time this bit of code is
      // being run since the server came online. In that case get or create the
      // handler.
      if (handler == null) {
        if (Heritrix.isSingleInstance()) {
          heritrix = Heritrix.getSingleInstance();
          handler = heritrix.getJobHandler();
          application.setAttribute("heritrix", heritrix);
          application.setAttribute("handler", handler);
        } else {
          // TODO:
          // If we get here, then there are multiple heritrix instances
          // and we have to put up a screen allowing the user choose between.
          // Otherwise, there is no Heritrix instance.  Thats a problem.
          throw new RuntimeException(
              "No heritrix instance (or multiple "
                  + "to choose from and we haven't implemented this yet)");
        }
      }

      // ensure controller's settingsHandler is always thread-installed
      // in web ui threads
      if (handler != null) {
        CrawlJob job = handler.getCurrentJob();
        if (job != null) {
          CrawlController controller = job.getController();
          if (controller != null) {
            controller.installThreadContextSettingsHandler();
          }
        }
      }

      out.write("\n");
      out.write("\n\n");

      String title = "Help";
      int tab = 6;

      out.write("\n\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");

      String currentHeritrixName =
          (heritrix == null)
              ? "No current Heritrix instance"
              : (heritrix.getMBeanName() == null)
                  ? heritrix.getInstances().keySet().iterator().next().toString()
                  : heritrix.getMBeanName().toString();

      /**
       * An include file that handles the "look" and navigation of a web page. Include at top (where
       * you would normally begin the HTML code). If used, the include "foot.jsp" should be included
       * at the end of the HTML code. It will close any table, body and html tags left open in this
       * one. Any custom HTML code is thus placed between the two.
       *
       * <p>The following variables must exist prior to this file being included:
       *
       * <p>String title - Title of the web page int tab - Which to display as 'selected'. 0 -
       * Console 1 - Jobs 2 - Profiles 3 - Logs 4 - Reports 5 - Settings 6 - Help
       *
       * <p>SimpleHandler handler - In general this is provided by the include page 'handler.jsp'
       * which should be included prior to this one.
       *
       * @author Kristinn Sigurdsson
       */
      String shortJobStatus = null;
      if (handler.getCurrentJob() != null) {
        shortJobStatus = TextUtils.getFirstWord(handler.getCurrentJob().getStatus());
      }
      String favicon = System.getProperties().getProperty("heritrix.favicon", "h.ico");

      out.write("\n");

      StatisticsTracker stats = null;
      if (handler.getCurrentJob() != null) {
        // Assume that StatisticsTracker is being used.
        stats = (StatisticsTracker) handler.getCurrentJob().getStatisticsTracking();
      }

      out.write("\n");
      out.write("\n\n");
      out.write("<html>\n    ");
      out.write("<head>\n    \t");
      out.write(
          "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n        ");
      out.write("<title>Heritrix: ");
      out.print(title);
      out.write("</title>\n        ");
      out.write("<link rel=\"stylesheet\" \n            href=\"");
      out.print(request.getContextPath());
      out.write("/css/heritrix.css\">\n        ");
      out.write("<link rel=\"icon\" href=\"");
      out.print(request.getContextPath());
      out.write("/images/");
      out.print(favicon);
      out.write("\" type=\"image/x-icon\" />\n        ");
      out.write("<link rel=\"shortcut icon\" href=\"");
      out.print(request.getContextPath());
      out.write("/images/");
      out.print(favicon);
      out.write("\" type=\"image/x-icon\" />\n        ");
      out.write("<script src=\"/js/util.js\">\n        ");
      out.write("</script>\n    ");
      out.write("</head>\n\n    ");
      out.write("<body>\n        ");
      out.write(
          "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"100%\">\n            ");
      out.write("<tr>\n                ");
      out.write("<td>\n                    ");
      out.write(
          "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" height=\"100%\">\n                        ");
      out.write("<tr>\n                            ");
      out.write(
          "<td height=\"60\" width=\"155\" valign=\"top\" nowrap>\n                                ");
      out.write(
          "<table border=\"0\" width=\"155\" cellspacing=\"0\" cellpadding=\"0\" height=\"60\">\n                                    ");
      out.write("<tr>\n                                        ");
      out.write(
          "<td align=\"center\" height=\"40\" valign=\"bottom\">\n                                            ");
      out.write("<a border=\"0\" \n                                            href=\"");
      out.print(request.getContextPath());
      out.write("/index.jsp\">");
      out.write("<img border=\"0\" src=\"");
      out.print(request.getContextPath());
      out.write("/images/logo.gif\" height=\"37\" width=\"145\">");
      out.write("</a>\n                                        ");
      out.write("</td>\n                                    ");
      out.write("</tr>\n                                    ");
      out.write("<tr>\n                                        ");
      out.write("<td class=\"subheading\">\n                                            ");
      out.print(title);
      out.write("\n                                        ");
      out.write("</td>\n                                    ");
      out.write("</tr>\n                                ");
      out.write("</table>\n                            ");
      out.write("</td>\n                            ");
      out.write(
          "<td width=\"5\" nowrap>\n                                &nbsp;&nbsp;\n                            ");
      out.write("</td>\n                            ");
      out.write("<td width=\"460\" align=\"left\" nowrap>\n                                ");
      out.write(
          "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" height=\"60\">\n                                    ");
      out.write("<tr>\n                                        ");
      out.write("<td colspan=\"2\" nowrap>\n                                            ");

      SimpleDateFormat sdf = new SimpleDateFormat("MMM. d, yyyy HH:mm:ss");
      sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));

      out.write("\n                                            ");
      out.write("<b>\n                                                Status as of ");
      out.write("<a style=\"color: #000000\" href=\"");
      out.print(request.getRequestURL());
      out.write("\">");
      out.print(sdf.format(new java.util.Date()));
      out.write(" GMT");
      out.write("</a>\n                                            ");
      out.write(
          "</b>\n                                            &nbsp;&nbsp;\n                                            ");
      out.write("<span style=\"text-align:right\">\n                                            ");
      out.write(
          "<b>\n                                                Alerts: \n                                            ");
      out.write("</b>\n                                            ");
      if (heritrix.getAlertsCount() == 0) {
        out.write("\n                                                ");
        out.write("<a style=\"color: #000000; text-decoration: none\" href=\"");
        out.print(request.getContextPath());
        out.write("/console/alerts.jsp\">no alerts");
        out.write("</a>\n                                            ");
      } else if (heritrix.getNewAlertsCount() > 0) {
        out.write("\n                                                ");
        out.write("<b>");
        out.write("<a href=\"");
        out.print(request.getContextPath());
        out.write("/console/alerts.jsp\">");
        out.print(heritrix.getAlerts().size());
        out.write(" (");
        out.print(heritrix.getNewAlertsCount());
        out.write(" new)");
        out.write("</a>");
        out.write("</b>\n                                            ");
      } else {
        out.write("\n                                                ");
        out.write("<a style=\"color: #000000\" href=\"");
        out.print(request.getContextPath());
        out.write("/console/alerts.jsp\">");
        out.print(heritrix.getAlertsCount());
        out.write(" (");
        out.print(heritrix.getNewAlertsCount());
        out.write(" new)");
        out.write("</a>\n                                            ");
      }
      out.write("\n                                            ");
      out.write("</span>\n                                        ");
      out.write("</td>\n                                    ");
      out.write("</tr>\n                                    ");
      out.write("<tr>\n                                        ");
      out.write("<td valign=\"top\" nowrap>\n\t\t\t\t\t\t\t\t\t\t");
      out.print(
          handler.isRunning()
              ? "<span class='status'>Crawling Jobs</span>"
              : "<span class='status'>Holding Jobs</span>");
      out.write("<i>&nbsp;");
      out.write("</i>\n\t\t\t\t\t\t\t\t\t\t");
      out.write("</td>\n\t\t\t\t\t\t\t\t\t\t");
      out.write("<td valign=\"top\" align=\"right\" nowrap>\n\t\t\t\t\t\t\t\t\t\t");

      if (handler.isRunning() || handler.isCrawling()) {
        if (handler.getCurrentJob() != null) {
          out.write("\n\t\t\t\t\t\t\t\t\t\t");
          out.write("<span class='status'>\n\t\t\t\t\t\t\t\t\t\t");
          out.print(shortJobStatus);
          out.write("</span> job:\n\t\t\t\t\t\t\t\t\t\t");
          out.write("<i>");
          out.print(handler.getCurrentJob().getJobName());
          out.write("</i>\n\t\t\t\t\t\t\t\t\t\t");

        } else {
          out.println("No job ready <a href=\"");
          out.println(request.getContextPath());
          out.println("/jobs.jsp\" style='color: #000000'>(create new)</a>");
        }
      }

      out.write("\n\t\t\t\t\t\t\t\t\t\t");
      out.write("</td>\n                                    ");
      out.write("</tr>\n                                    ");
      out.write("<tr>\n                                        ");
      out.write("<td nowrap>\n                                            ");
      out.print(handler.getPendingJobs().size());
      out.write(
          "\n                                            jobs\n                                            ");
      out.write("<a style=\"color: #000000\" href=\"");
      out.print(request.getContextPath());
      out.write("/jobs.jsp#pending\">pending");
      out.write("</a>,\n                                            ");
      out.print(handler.getCompletedJobs().size());
      out.write("\n                                            ");
      out.write("<a style=\"color: #000000\" href=\"");
      out.print(request.getContextPath());
      out.write("/jobs.jsp#completed\">completed");
      out.write(
          "</a>\n                                            &nbsp;\n                                        ");
      out.write("</td>\n                                        ");
      out.write("<td nowrap align=\"right\">\n                                            ");
      if (handler.isCrawling()) {
        out.write("\n                                                    ");
        out.print((stats != null) ? stats.successfullyFetchedCount() : 0);
        out.write(" URIs in \n\t\t                                            ");
        out.print(
            ArchiveUtils.formatMillisecondsToConventional(
                ((stats != null) ? (stats.getCrawlerTotalElapsedTime()) : 0), false));
        out.write("\n\t\t                                            (");
        out.print(
            ArchiveUtils.doubleToString(
                ((stats != null) ? stats.currentProcessedDocsPerSec() : 0), 2));
        out.write("/sec)\n                                            ");
      }
      out.write("\n                                        ");
      out.write("</td>\n                                    ");
      out.write("</tr>\n                                ");
      out.write("</table>\n                            ");
      out.write("</td>\n                        ");
      out.write("</tr>\n                    ");
      out.write("</table>\n                ");
      out.write("</td>\n                ");
      out.write("<td width=\"100%\" nowrap>\n                    &nbsp;\n                ");
      out.write("</td>\n            ");
      out.write("</tr>\n            ");
      out.write("<tr>\n                ");
      out.write("<td bgcolor=\"#0000FF\" height=\"1\" colspan=\"4\">\n                ");
      out.write("</td>\n            ");
      out.write("</tr>\n            ");
      out.write("<tr>\n                ");
      out.write("<td colspan=\"4\" height=\"20\">\n                    ");
      out.write(
          "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"100%\" height=\"20\">\n                        ");
      out.write("<tr>\n                            ");
      out.write("<td class=\"tab_seperator\">&nbsp;");
      out.write("</td>\n                            ");
      out.write("<td class=\"tab");
      out.print(tab == 0 ? "_selected" : "");
      out.write("\">\n                                ");
      out.write("<a href=\"");
      out.print(request.getContextPath());
      out.write("/index.jsp\" class=\"tab_text");
      out.print(tab == 0 ? "_selected" : "");
      out.write("\">Console");
      out.write("</a>\n                            ");
      out.write("</td>\n                            ");
      out.write("<td class=\"tab_seperator\">&nbsp;");
      out.write("</td>\n                            ");
      out.write("<td class=\"tab");
      out.print(tab == 1 ? "_selected" : "");
      out.write("\">\n                                ");
      out.write("<a href=\"");
      out.print(request.getContextPath());
      out.write("/jobs.jsp\" class=\"tab_text");
      out.print(tab == 1 ? "_selected" : "");
      out.write("\">Jobs");
      out.write("</a>\n                            ");
      out.write("</td>\n                            ");
      out.write("<td class=\"tab_seperator\">&nbsp;");
      out.write("</td>\n                            ");
      out.write("<td class=\"tab");
      out.print(tab == 2 ? "_selected" : "");
      out.write("\">\n                                ");
      out.write("<a href=\"");
      out.print(request.getContextPath());
      out.write("/profiles.jsp\" class=\"tab_text");
      out.print(tab == 2 ? "_selected" : "");
      out.write("\">Profiles");
      out.write("</a>\n                            ");
      out.write("</td>\n                            ");
      out.write("<td class=\"tab_seperator\">&nbsp;");
      out.write("</td>\n                            ");
      out.write("<td class=\"tab");
      out.print(tab == 3 ? "_selected" : "");
      out.write("\">\n                                ");
      out.write("<a href=\"");
      out.print(request.getContextPath());
      out.write("/logs.jsp\" class=\"tab_text");
      out.print(tab == 3 ? "_selected" : "");
      out.write("\">Logs");
      out.write("</a>\n                            ");
      out.write("</td>\n                            ");
      out.write("<td class=\"tab_seperator\">&nbsp;");
      out.write("</td>\n                            ");
      out.write("<td class=\"tab");
      out.print(tab == 4 ? "_selected" : "");
      out.write("\">\n                                ");
      out.write("<a href=\"");
      out.print(request.getContextPath());
      out.write("/reports.jsp\" class=\"tab_text");
      out.print(tab == 4 ? "_selected" : "");
      out.write("\">Reports");
      out.write("</a>\n                            ");
      out.write("</td>\n                            ");
      out.write("<td class=\"tab_seperator\">&nbsp;");
      out.write("</td>\n                            ");
      out.write("<td class=\"tab");
      out.print(tab == 5 ? "_selected" : "");
      out.write("\">\n                                ");
      out.write("<a href=\"");
      out.print(request.getContextPath());
      out.write("/setup.jsp\" class=\"tab_text");
      out.print(tab == 5 ? "_selected" : "");
      out.write("\">Setup");
      out.write("</a>\n                            ");
      out.write("</td>\n                            ");
      out.write("<td class=\"tab_seperator\">&nbsp;");
      out.write("</td>\n                            ");
      out.write("<td class=\"tab");
      out.print(tab == 6 ? "_selected" : "");
      out.write("\">\n                                ");
      out.write("<a href=\"");
      out.print(request.getContextPath());
      out.write("/help.jsp\" class=\"tab_text");
      out.print(tab == 6 ? "_selected" : "");
      out.write("\">Help");
      out.write("</a>\n                             ");
      out.write("</td>\n                            ");
      out.write("<td width=\"100%\">\n                            ");
      out.write("</td>\n                        ");
      out.write("</tr>\n                    ");
      out.write("</table>\n                ");
      out.write("</td>\n            ");
      out.write("</tr>\n            ");
      out.write("<tr>\n                ");
      out.write("<td bgcolor=\"#0000FF\" height=\"1\" colspan=\"4\">");
      out.write("</td>\n            ");
      out.write("</tr>\n         ");
      out.write("</table>\n                    ");
      out.write("<!-- MAIN BODY -->\n");
      out.write("\n\n");
      out.write("<div class=\"margined\">\n    ");
      out.write("<h1>Heritrix online help");
      out.write("</h1>\n");
      out.write("<p>\n    ");
      out.write("<b>");
      out.write("<a href=\"");
      out.print(request.getContextPath());
      out.write("/about.jsp\">About Heritrix");
      out.write("</a>");
      out.write("</b>");
      out.write("</br>\n    Includes license and current environment information.\n");
      out.write("</p>\n");
      out.write("<p>\n    ");
      out.write("<b>");
      out.write("<a target=\"_blank\" \n    href=\"");
      out.print(request.getContextPath());
      out.write("/docs/articles/user_manual/index.html\">User\n        Manual");
      out.write("</a>");
      out.write("</b>");
      out.write(
          "<br> Covers creating, configuring, launching,\n        monitoring and analysing crawl jobs. For all users.\n");
      out.write("</p>\n");
      out.write("<p>\n    ");
      out.write("<b>");
      out.write("<a target=\"_blank\" \n        href=\"");
      out.print(request.getContextPath());
      out.write("/docs/articles/developer_manual/index.html\">Developer Manual");
      out.write("</a>");
      out.write("</b>");
      out.write(
          "<br> Covers how to write add on modules for Heritrix\n        and provides in depth coverage of Heritrix's architecture. For\n        advanced users.\n");
      out.write("</p>\n");
      out.write("<p>\n    ");
      out.write("<b>");
      out.write("<a target=\"_blank\" \n        href=\"");
      out.print(request.getContextPath());
      out.write("/docs/articles/releasenotes/index.html\">Release Notes");
      out.write("</a>");
      out.write("</b>");
      out.write("<br>\n");
      out.write("</p>\n");
      out.write("<p>\n\t");
      out.write("<b>");
      out.write(
          "<a href=\"http://crawler.archive.org/issue-tracking.html\" target=\"_blank\">Issue Tracking");
      out.write("</a>");
      out.write("</b>");
      out.write(
          "<br />\n\tIf you have found a bug or would like to see new features in Heritrix, check the following links:\n\t");
      out.write("<ul>\n\t\t");
      out.write("<li>");
      out.write(
          "<a href=\"http://sourceforge.net/tracker/?atid=539099&amp;group_id=73833&amp;func=browse\" target=\"_blank\">Bugs");
      out.write("</a>");
      out.write("</li>\n\t\t");
      out.write("<li>");
      out.write(
          "<a href=\"http://sourceforge.net/tracker/?atid=539102&amp;group_id=73833&amp;func=browse\" target=\"_blank\">Feature Requests");
      out.write("</a>");
      out.write("</li>\n\t");
      out.write("</ul>\n");
      out.write("</p>\n");
      out.write("<p>\n    ");
      out.write("<b>");
      out.write(
          "<a href=\"http://crawler.archive.org/mail-lists.html\" target=\"_blank\">Mailing Lists");
      out.write("</a>");
      out.write("</b>");
      out.write("<br />\n    For general discussion on Heritrix, use our ");
      out.write(
          "<a href=\"http://groups.yahoo.com/group/archive-crawler/\" target=\"_blank\">Crawler Discussion List");
      out.write("</a>.\n");
      out.write("</p>\n");
      out.write("<p>\n    ");
      out.write("<b>");
      out.write("<a href=\"");
      out.print(request.getContextPath());
      out.write("/help/regexpr.jsp\">Regular Expressions");
      out.write("</a>");
      out.write("</b>");
      out.write(
          "<br />\n    Information about the regular expressions used in Heritrix and a tool to double check that your regular expressions are valid and that they correctly identify the desired strings.\n");
      out.write("</p>\n");
      out.write("<p>\n    ");
      out.write("<b>");
      out.write("<a href=\"");
      out.print(request.getContextPath());
      out.write("/help/codes.jsp\">URI Fetch Status Codes");
      out.write("</a>");
      out.write("</b>");
      out.write(
          "<br />\n    This reference details what each of the fetch status codes assigned to URIs means.\n");
      out.write("</p>\n");
      out.write("<hr />\n");
      out.write("<font size=\"-1\">Heritrix version @VERSION@");
      out.write("</font>\n");
      out.write("</div>\n");

      /**
       * An include file that handles the "look" and navigation of a web page. Wrapps up things
       * begun in the "head.jsp" include file. See it for more details.
       *
       * @author Kristinn Sigurdsson
       */
      out.write("\n");
      out.write("<br/>\n");
      out.write("<br/>\n        ");
      out.write(
          "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"100%\">\n            ");
      out.write("<tr>\n            ");
      out.write("<td bgcolor=\"#0000FF\" height=\"1\" colspan=\"4\">");
      out.write("</td>\n            ");
      out.write("</tr>\n            ");
      out.write("<tr>\n            ");
      out.write("<td class=\"instance_name\">Identifier: ");
      out.print(currentHeritrixName);
      out.write("</td>\n            ");
      out.write("</tr>\n        ");
      out.write("</table>\n                    ");
      out.write("<!-- END MAIN BODY -->\n    ");
      out.write("</body>\n");
      out.write("</html>");
      out.write("\n");
    } catch (Throwable t) {
      out = _jspx_out;
      if (out != null && out.getBufferSize() != 0) out.clearBuffer();
      if (pageContext != null) pageContext.handlePageException(t);
    } finally {
      if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext);
    }
  }
Пример #13
0
  private int _writeXML(PrintWriter out, int level, ReportData rd, boolean urlOnly)
      throws ReportException {
    boolean isSoapRequest = rd.isSoapRequest();
    RequestProperties reqState = rd.getRequestProperties();
    PrivateLabel privLabel = rd.getPrivateLabel();
    I18N i18n = privLabel.getI18N(ReportTable.class);
    String PFX1 = XMLTools.PREFIX(isSoapRequest, level * ReportTable.INDENT);
    String PFX2 = XMLTools.PREFIX(isSoapRequest, (level + 1) * ReportTable.INDENT);

    /* begin */
    out.print(PFX1);
    out.print(
        XMLTools.startTAG(
            isSoapRequest,
            "Report", // TAG_Report
            XMLTools.ATTR("name", rd.getReportName())
                + // ATTR_name
                XMLTools.ATTR("type", rd.getReportType()), // ATTR_type
            false,
            true));

    /* constraints */
    ReportConstraints rc = rd.getReportConstraints();
    String dtFmt = DateTime.DEFAULT_DATE_FORMAT + "," + DateTime.DEFAULT_TIME_FORMAT;
    TimeZone tzone = rd.getTimeZone();
    String tzStr = rd.getTimeZoneString();
    long tmBeg = rc.getTimeStart();
    long tmEnd = rc.getTimeEnd();
    DateTime dtStr = new DateTime(tmBeg, tzone);
    DateTime dtEnd = new DateTime(tmEnd, tzone);

    /* Account */
    out.print(PFX2);
    out.print(XMLTools.startTAG(isSoapRequest, "Account", "", false, false)); // TAG_Account
    out.print(XmlFilter(isSoapRequest, rd.getAccountID()));
    out.print(XMLTools.endTAG(isSoapRequest, "Account", true)); // TAG_Account

    /* TimeFrom */
    out.print(PFX2);
    out.print(
        XMLTools.startTAG(
            isSoapRequest,
            "TimeFrom", // TAG_TimeFrom
            XMLTools.ATTR("timestamp", String.valueOf(tmBeg))
                + // ATTR_timestamp
                XMLTools.ATTR("timezone", tzStr), // ATTR_timezone
            false,
            false));
    out.print((tmBeg > 0L) ? XmlFilter(isSoapRequest, dtStr.format(dtFmt)) : "");
    out.print(XMLTools.endTAG(isSoapRequest, "TimeFrom", true)); // TAG_TimeFrom

    /* TimeTo */
    out.print(PFX2);
    out.print(
        XMLTools.startTAG(
            isSoapRequest,
            "TimeTo", // TAG_TimeTo
            XMLTools.ATTR("timestamp", String.valueOf(tmEnd))
                + // ATTR_timestamp
                XMLTools.ATTR("timezone", tzStr), // ATTR_timezone
            false,
            false));
    out.print((tmEnd > 0L) ? XmlFilter(isSoapRequest, dtEnd.format(dtFmt)) : "");
    out.print(XMLTools.endTAG(isSoapRequest, "TimeTo", true)); // TAG_TimeTo

    /* ValidGPSRequired */
    out.print(PFX2);
    out.print(
        XMLTools.startTAG(
            isSoapRequest, "ValidGPSRequired", "", false, false)); // TAG_ValidGPSRequired
    out.print(XmlFilter(isSoapRequest, rc.getValidGPSRequired()));
    out.print(XMLTools.endTAG(isSoapRequest, "ValidGPSRequired", true)); // TAG_ValidGPSRequired

    /* SelectionLimit */
    out.print(PFX2);
    out.print(
        XMLTools.startTAG(
            isSoapRequest,
            "SelectionLimit", // TAG_SelectionLimit
            XMLTools.ATTR("type", rc.getSelectionLimitType()),
            false,
            false));
    out.print(XmlFilter(isSoapRequest, rc.getSelectionLimit()));
    out.print(XMLTools.endTAG(isSoapRequest, "SelectionLimit", true)); // TAG_SelectionLimit

    /* Ascending */
    out.print(PFX2);
    out.print(XMLTools.startTAG(isSoapRequest, "Ascending", "", false, false)); // TAG_Ascending
    out.print(XmlFilter(isSoapRequest, rc.getOrderAscending()));
    out.print(XMLTools.endTAG(isSoapRequest, "Ascending", true)); // TAG_Ascending

    /* ReportLimit */
    out.print(PFX2);
    out.print(XMLTools.startTAG(isSoapRequest, "ReportLimit", "", false, false)); // TAG_ReportLimit
    out.print(XmlFilter(isSoapRequest, rc.getReportLimit()));
    out.print(XMLTools.endTAG(isSoapRequest, "ReportLimit", true)); // TAG_ReportLimit

    /* Where */
    if (rc.hasWhere()) {
      out.print(PFX2);
      out.print(XMLTools.startTAG(isSoapRequest, "Where", "", false, false)); // TAG_Where
      out.print(XmlFilter(isSoapRequest, rc.getWhere()));
      out.print(XMLTools.endTAG(isSoapRequest, "Where", true)); // TAG_Where
    }

    /* RuleSelector */
    if (rc.hasRuleSelector()) {
      out.print(PFX2);
      out.print(
          XMLTools.startTAG(isSoapRequest, "RuleSelector", "", false, false)); // TAG_RuleSelector
      out.print(XmlFilter(isSoapRequest, rc.getRuleSelector()));
      out.print(XMLTools.endTAG(isSoapRequest, "RuleSelector", true)); // TAG_RuleSelector
    }

    /* Title */
    out.print(PFX2);
    out.print(XMLTools.startTAG(isSoapRequest, "Title", "", false, false)); // TAG_Title
    out.print(XmlFilter(isSoapRequest, rd.getReportTitle()));
    out.print(XMLTools.endTAG(isSoapRequest, "Title", true)); // TAG_Title

    /* Subtitle */
    out.print(PFX2);
    out.print(XMLTools.startTAG(isSoapRequest, "Subtitle", "", false, false)); // TAG_Subtitle
    out.print(XmlFilter(isSoapRequest, rd.getReportSubtitle()));
    out.print(XMLTools.endTAG(isSoapRequest, "Subtitle", true)); // TAG_Subtitle

    /* URL */
    if (urlOnly) {
      // Web-URL only
      HttpServletRequest request = reqState.getHttpServletRequest();
      ReportDeviceList devList = rd.getReportDeviceList();
      String deviceID = devList.isDeviceGroup() ? null : devList.getFirstDeviceID();
      String groupID = devList.isDeviceGroup() ? devList.getDeviceGroupID() : null;
      String baseURL =
          privLabel.hasDefaultBaseURL()
              ? privLabel.getDefaultBaseURL()
              : ((request != null) ? request.getRequestURL().toString() : "");
      URIArg rptURL =
          ReportURL.createReportURL(
              baseURL,
              false,
              rd.getAccountID(),
              rd.getUserID(),
              "",
              deviceID,
              groupID,
              rc.getTimeStart(),
              rc.getTimeEnd(),
              rd.getTimeZoneString(),
              rd.getReportName(),
              rc.getReportLimit(),
              rc.getSelectionLimitType().toString(),
              ReportPresentation.FORMAT_HTML);
      out.print(PFX2);
      out.print(XMLTools.startTAG(isSoapRequest, "URL", "", false, false)); // TAG_URL
      out.print(XmlFilter(isSoapRequest, rptURL.toString()));
      out.print(XMLTools.endTAG(isSoapRequest, "URL", true)); // TAG_URL
    } else {
      // Report header/body
      this.rptHeader.writeXML(out, level + 1, rd);
      this.rptBody.writeXML(out, level + 1, rd);
    }

    /* Partial */
    out.print(PFX2);
    out.print(XMLTools.startTAG(isSoapRequest, "Partial", "", false, false)); // TAG_Partial
    out.print(XmlFilter(isSoapRequest, this.rptBody.isPartial()));
    out.print(XMLTools.endTAG(isSoapRequest, "Partial", true)); // TAG_Partial

    /* end of report */
    out.print(PFX1);
    out.print(XMLTools.endTAG(isSoapRequest, "Report", true)); // TAG_Report
    return this.rptBody.getRecordCount();
  }
Пример #14
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();
  }
Пример #15
0
 public StringBuffer getRequestURL() {
   return request.getRequestURL();
 }
Пример #16
0
  /**
   * Send a permanent redirect (HTTP status 301 "Moved Permanently") response with the given target
   * path.
   *
   * <p>The given target path may be relative or absolute. If it is relative, it will be resolved
   * against the request URL.
   *
   * @param targetPath the path to which the client is redirected.
   * @param req the HttpServletRequest
   * @param res the HttpServletResponse
   * @throws IOException if can't write the response.
   */
  public static void sendPermanentRedirect(
      String targetPath, HttpServletRequest req, HttpServletResponse res) throws IOException {
    // Absolute URL needed so resolve the target path against the request URL.
    URI uri;
    try {
      uri = new URI(req.getRequestURL().toString());
    } catch (URISyntaxException e) {
      log.error(
          "sendPermanentRedirect(): Bad syntax on request URL <" + req.getRequestURL() + ">.", e);
      log.info(
          "sendPermanentRedirect(): "
              + UsageLog.closingMessageForRequestContext(
                  HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 0));
      if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      return;
    }
    String absolutePath = uri.resolve(targetPath).toString();
    absolutePath = res.encodeRedirectURL(absolutePath);

    res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    res.addHeader("Location", absolutePath);

    String title = "Permanently Moved - 301";
    String body =
        new StringBuilder()
            .append("<p>")
            .append("The requested URL <")
            .append(req.getRequestURL())
            .append("> has been permanently moved (HTTP status code 301).")
            .append(" Instead, please use the following URL: <a href=\"")
            .append(absolutePath)
            .append("\">")
            .append(absolutePath)
            .append("</a>.")
            .append("</p>")
            .toString();
    String htmlResp =
        new StringBuilder()
            .append(HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag())
            .append("<head><title>")
            .append(title)
            .append("</title></head><body>")
            .append("<h1>")
            .append(title)
            .append("</h1>")
            .append(body)
            .append("</body></html>")
            .toString();

    log.info("sendPermanentRedirect(): redirect to " + absolutePath);
    log.info(
        "sendPermanentRedirect(): "
            + UsageLog.closingMessageForRequestContext(
                HttpServletResponse.SC_MOVED_PERMANENTLY, htmlResp.length()));

    // Write the catalog out.
    PrintWriter out = res.getWriter();
    res.setContentType("text/html");
    out.print(htmlResp);
    out.flush();
  }
Пример #17
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);
 }
Пример #18
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);
    }
  }