Example #1
1
  public static void showSession(HttpServletRequest req, PrintStream out) {

    // res.setContentType("text/html");

    // Get the current session object, create one if necessary
    HttpSession session = req.getSession();

    out.println("Session id: " + session.getId());
    out.println(" session.isNew(): " + session.isNew());
    out.println(" session.getMaxInactiveInterval(): " + session.getMaxInactiveInterval() + " secs");
    out.println(
        " session.getCreationTime(): "
            + session.getCreationTime()
            + " ("
            + new Date(session.getCreationTime())
            + ")");
    out.println(
        " session.getLastAccessedTime(): "
            + session.getLastAccessedTime()
            + " ("
            + new Date(session.getLastAccessedTime())
            + ")");
    out.println(" req.isRequestedSessionIdFromCookie: " + req.isRequestedSessionIdFromCookie());
    out.println(" req.isRequestedSessionIdFromURL: " + req.isRequestedSessionIdFromURL());
    out.println(" req.isRequestedSessionIdValid: " + req.isRequestedSessionIdValid());

    out.println("Saved session Attributes:");
    Enumeration atts = session.getAttributeNames();
    while (atts.hasMoreElements()) {
      String name = (String) atts.nextElement();
      out.println(" " + name + ": " + session.getAttribute(name) + "<BR>");
    }
  }
Example #2
0
  public static void showSession(HttpServletRequest req, HttpServletResponse res, PrintStream out) {

    // res.setContentType("text/html");

    // Get the current session object, create one if necessary
    HttpSession session = req.getSession();

    // Increment the hit count for this page. The value is saved
    // in this client's session under the name "snoop.count".
    Integer count = (Integer) session.getAttribute("snoop.count");
    if (count == null) {
      count = 1;
    } else count = count + 1;
    session.setAttribute("snoop.count", count);

    out.println(HtmlWriter.getInstance().getHtmlDoctypeAndOpenTag());
    out.println("<HEAD><TITLE>SessionSnoop</TITLE></HEAD>");
    out.println("<BODY><H1>Session Snoop</H1>");

    // Display the hit count for this page
    out.println(
        "You've visited this page " + count + ((!(count.intValue() != 1)) ? " time." : " times."));

    out.println("<P>");

    out.println("<H3>Here is your saved session data:</H3>");
    Enumeration atts = session.getAttributeNames();
    while (atts.hasMoreElements()) {
      String name = (String) atts.nextElement();
      out.println(name + ": " + session.getAttribute(name) + "<BR>");
    }

    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Timeout: " + session.getMaxInactiveInterval());
    out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>");

    out.println(
        "Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>");
    out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>");
    out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>");

    out.println("<H3>Test URL Rewriting</H3>");
    out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>");
    out.println("to test that session tracking works via URL");
    out.println("rewriting even when cookies aren't supported.");

    out.println("</BODY></HTML>");
  }
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   String title = "Shared Info";
   out.println(
       "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
           + "Transitional//EN\">"
           + "<HTML>\n"
           + "<HEAD><TITLE>"
           + title
           + "</TITLE></HEAD>\n"
           + "<BODY BGCOLOR=\"#FDF5E6\">\n"
           + "<H1 ALIGN=\"CENTER\">"
           + title
           + "</H1>\n"
           + "<UL>\n"
           + "  <LI>Session:");
   HttpSession session = request.getSession(true);
   Enumeration attributes = session.getAttributeNames();
   out.println(getAttributeList(attributes));
   out.println("  <LI>Current Servlet Context:");
   ServletContext application = getServletContext();
   attributes = application.getAttributeNames();
   out.println(getAttributeList(attributes));
   out.println("  <LI>Servlet Context of /shareTest1:");
   application = application.getContext("/shareTest1");
   if (application == null) {
     out.println("Context sharing disabled");
   } else {
     attributes = application.getAttributeNames();
     out.println(getAttributeList(attributes));
   }
   out.println("  <LI>Cookies:<UL>");
   Cookie[] cookies = request.getCookies();
   if ((cookies == null) || (cookies.length == 0)) {
     out.println("    <LI>No cookies found.");
   } else {
     Cookie cookie;
     for (int i = 0; i < cookies.length; i++) {
       cookie = cookies[i];
       out.println("    <LI>" + cookie.getName());
     }
   }
   out.println("    </UL>\n" + "</UL>\n" + "</BODY></HTML>");
 }
Example #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;
    }
Example #5
0
  public void getEnv(VariableTable vt) {
    Enumeration e = null;
    HttpServletRequest request = (HttpServletRequest) (pageContext.getRequest());
    HttpSession session = request.getSession(false);

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

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

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

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

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

      if (par_values != null && par_values.length > 1) {
        StringBuffer temp = new StringBuffer();
        for (int i = 0; i < par_values.length; i++) {
          if (par_values[i] != null && par_values[i].trim().length() > 0) {
            if (temp.length() > 0) {
              temp.append(",");
            }
            temp.append(par_values[i]);
          }
        }
        value = temp.toString();
      }
      if (url_charset != null) {
        try {
          value = new String(value.getBytes(url_charset), db_charset);
        } catch (java.io.UnsupportedEncodingException uee) {
        }
        ;
      }
      vt.setValue(name, value);
    }
    vt.add("REQUEST.REMOTEADDR", java.sql.Types.VARCHAR);
    vt.setValue("REQUEST.REMOTEADDR", getClientIPAddr());
    vt.add("REQUEST.REMOTEHOST", java.sql.Types.VARCHAR);
    vt.setValue("REQUEST.REMOTEHOST", request.getRemoteAddr());
    vt.add("REQUEST.REFERER", java.sql.Types.VARCHAR);
    vt.setValue("REQUEST.REFERER", request.getHeader("Referer"));
    vt.add("REQUEST.QUERYSTRING", java.sql.Types.VARCHAR);
    vt.setValue("REQUEST.QUERYSTRING", request.getQueryString());
  }