예제 #1
0
  void sendHTML(
      HttpServletRequest request,
      HttpServletResponse response,
      String script,
      Exception scriptError,
      Object scriptResult,
      StringBuffer scriptOutput,
      boolean capture)
      throws IOException {
    // Format the output using a simple templating utility
    SimpleTemplate st = new SimpleTemplate(BshServlet.class.getResource("page.template"));
    st.replace("version", getBshVersion());

    // String requestURI = HttpUtils.getRequestURL( request ).toString()
    // I was told this should work
    String requestURI = request.getRequestURI();

    st.replace("servletURL", requestURI);
    if (script != null) st.replace("script", script);
    else st.replace("script", exampleScript);
    if (capture) st.replace("captureOutErr", "CHECKED");
    else st.replace("captureOutErr", "");
    if (script != null)
      st.replace(
          "scriptResult", formatScriptResultHTML(script, scriptResult, scriptError, scriptOutput));

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    st.write(out);
    out.flush();
  }
예제 #2
0
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   String title = "Showing Request Headers";
   StringBuilder sb = new StringBuilder();
   sb.append("<html>\n<head>\n");
   sb.append("<title>" + title + "</title>\n");
   sb.append("</head>\n");
   sb.append("<body bgcolor='#FDF5E6'>\n");
   sb.append("<h1 align='center'>" + title + "</h1>\n");
   sb.append("<b> Request Method: </b>" + request.getMethod() + "<br>\n");
   sb.append("<b> Request URI: </b>" + request.getRequestURI() + "<br>\n");
   sb.append("<b> Request Protocol: </b>" + request.getProtocol() + "<br>\n");
   sb.append("<table border=1 align='center'>\n");
   sb.append("<tr bgcolor='#FFAD00'>\n");
   sb.append("<th> Header Name </th><th> Header Value </th></tr>\n");
   Enumeration headerNames = request.getHeaderNames();
   while (headerNames.hasMoreElements()) {
     String headerName = (String) headerNames.nextElement();
     sb.append("<tr><td>" + headerName + "</td>");
     sb.append("<td>" + request.getHeader(headerName) + "</td></tr>\n");
   }
   sb.append("</table>\n");
   sb.append("</body></html>");
   out.println(sb.toString());
   out.close();
 }
예제 #3
0
 public DownloadRequest(ServletContext context, HttpServletRequest request) {
   _context = context;
   _httpRequest = request;
   _path = request.getRequestURI();
   _encoding = request.getHeader(ACCEPT_ENCODING);
   String context_path = request.getContextPath();
   if (context_path != null) _path = _path.substring(context_path.length());
   if (_path == null) _path = request.getServletPath(); // This works for *.<ext> invocations
   if (_path == null) _path = "/"; // No path given
   _path = _path.trim();
   if (_context != null && !_path.endsWith("/")) {
     String realPath = _context.getRealPath(_path);
     // fix for 4474021 - getRealPath might returns NULL
     if (realPath != null) {
       File f = new File(realPath);
       if (f != null && f.exists() && f.isDirectory()) {
         _path += "/";
       }
     }
   }
   // Append default file for a directory
   if (_path.endsWith("/")) _path += "launch.jnlp";
   _version = getParameter(request, ARG_VERSION_ID);
   _currentVersionId = getParameter(request, ARG_CURRENT_VERSION_ID);
   _os = getParameterList(request, ARG_OS);
   _arch = getParameterList(request, ARG_ARCH);
   _locale = getParameterList(request, ARG_LOCALE);
   _knownPlatforms = getParameterList(request, ARG_KNOWN_PLATFORMS);
   String platformVersion = getParameter(request, ARG_PLATFORM_VERSION_ID);
   _isPlatformRequest = (platformVersion != null);
   if (_isPlatformRequest) _version = platformVersion;
   _query = request.getQueryString();
   _testJRE = getParameter(request, TEST_JRE);
 }
예제 #4
0
  /**
   * Attempts to send an internal server error HTTP error, if possible. Otherwise simply pushes the
   * exception message to the output stream.
   *
   * @param message Message to be printed to the logger and to the output stream.
   * @param t Exception that caused the error.
   */
  protected void filterError(String message, Throwable t) {
    log.error("XSLT filter error: " + message, t);
    if (false == origResponse.isCommitted()) {
      // Reset the buffer and previous status code.
      origResponse.reset();
      origResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      origResponse.setContentType("text/html; charset=UTF-8");
    }

    // Response committed. Just push the error to the output stream.
    try {
      final OutputStream os = origResponse.getOutputStream();
      final PrintWriter osw = new PrintWriter(new OutputStreamWriter(os, "iso8859-1"));
      osw.write("<html><body><!-- " + XSLTFilterConstants.ERROR_TOKEN + " -->");
      osw.write("<h1 style=\"color: red; margin-top: 1em;\">");
      osw.write("Internal server exception");
      osw.write("</h1>");
      osw.write("<b>URI</b>: " + origRequest.getRequestURI() + "\n<br/><br/>");
      serializeException(osw, t);
      if (t instanceof ServletException && ((ServletException) t).getRootCause() != null) {
        osw.write("<br/><br/><h2>ServletException root cause:</h2>");
        serializeException(osw, ((ServletException) t).getRootCause());
      }
      osw.write("</body></html>");
      osw.flush();
    } catch (IOException e) {
      // Not much to do in such case (connection broken most likely).
      log.debug("Filter error could not be returned to client.");
    }
  }
예제 #5
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    if (request.getParameter("setcookie") != null) {
      Cookie cookie = new Cookie("Learningjava", "Cookies!");
      cookie.setMaxAge(3600);
      response.addCookie(cookie);
      out.println("<html><body><h1>Cookie Set...</h1>");
    } else {
      out.println("<html><body>");
      Cookie[] cookies = request.getCookies();
      if (cookies.length == 0) {
        out.println("<h1>No cookies found...</h1>");
      } else {
        for (int i = 0; i < cookies.length; i++)
          out.print(
              "<h1>Name: "
                  + cookies[i].getName()
                  + "<br>"
                  + "Value: "
                  + cookies[i].getValue()
                  + "</h1>");
      }
      out.println(
          "<p><a href=\""
              + request.getRequestURI()
              + "?setcookie=true\">"
              + "Reset the Learning Java cookie.</a>");
    }
    out.println("</body></html>");
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

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

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

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

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

      out.close();
    }
  }
예제 #7
0
파일: postview.java 프로젝트: SuchiraD/Blog
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    // read the last post id here .......................
    String url = req.getRequestURI();
    String urlprt[] = url.split("/");
    int urlcount = urlprt.length - 1;

    JSONParser parserPost = new JSONParser();
    JSONObject post = null;
    String id = urlprt[urlcount];

    // read the post  here .............................

    try {

      if (id != null) {
        Object objPost =
            parserPost.parse(new FileReader("..\\webapps\\Blog\\post\\" + id + ".json"));

        post = (JSONObject) objPost;
        String postauthor = post.get("author").toString();
        String posttitle = post.get("title").toString();
        String postcontent = post.get("content").toString();

        JSONArray arr = (JSONArray) post.get("comments");
        List<String> list = new ArrayList<String>();
        Iterator<String> iterator = arr.iterator();

        while (iterator.hasNext()) {
          list.add(iterator.next());
        }

        int listsz = list.size();
        String[] comments = new String[listsz];
        for (int i = 0; i < listsz; i++) {
          comments[i] = list.get(i);
        }

        req.setAttribute("title", posttitle);
        req.setAttribute("content", postcontent);
        req.setAttribute("author", postauthor);
        req.setAttribute("comments", comments);
        req.setAttribute("id", id);

        req.getRequestDispatcher("/view.jsp").forward(req, res);
      }

    } catch (Exception e) {
      res.setContentType("text/html");
      PrintWriter out = res.getWriter();
      out.println("get POST ......................");
      out.println(e);
      out.println("......................");
    }
  }
예제 #8
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>");
  }
예제 #9
0
 /**
  * Show the pieces of the request, for debugging
  *
  * @param req the HttpServletRequest
  * @return parsed request
  */
 public static String getRequestParsed(HttpServletRequest req) {
   return req.getRequestURI()
       + " = "
       + req.getContextPath()
       + "(context), "
       + req.getServletPath()
       + "(servletPath), "
       + req.getPathInfo()
       + "(pathInfo), "
       + req.getQueryString()
       + "(query)";
 }
예제 #10
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String[] uri = request.getRequestURI().split("/");
    if (uri.length < 4) {
      response.getWriter().print(XavaResources.getString(request, "module_name_missing"));
      return;
    }
    String url = "/naviox/index.jsp?application=" + uri[1] + "&module=" + uri[3];
    RequestDispatcher dispatcher = request.getRequestDispatcher(url);

    Style.setPotalInstance(
        NaviOXStyle
            .getInstance()); // We manage style in NaviOX as in the portal case, to override the
                             // style defined in xava.properties and by device
    dispatcher.forward(request, response);
  }
예제 #11
0
파일: postview.java 프로젝트: SuchiraD/Blog
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    // read the last post id here .......................
    String url = req.getRequestURI();
    String urlprt[] = url.split("/");
    int urlcount = urlprt.length - 1;

    JSONParser parserPost = new JSONParser();
    JSONObject post = null;
    String id = urlprt[urlcount];

    // read the post  here .............................

    try {

      if (id != null) {
        Object objPost =
            parserPost.parse(new FileReader("..\\webapps\\Blog\\post\\" + id + ".json"));

        post = (JSONObject) objPost;
        JSONArray msg = (JSONArray) post.get("toapprove");
        msg.add(req.getParameter("content"));

        post.remove("toapprove");
        post.put("toapprove", msg);

        File file = new File("..\\webapps\\Blog\\post\\" + id + ".json");
        file.createNewFile();
        FileWriter filew = new FileWriter(file);
        filew.write(post.toJSONString());
        filew.flush();
        filew.close();

        doGet(req, res);
      }

    } catch (Exception e) {
      res.setContentType("text/html");
      PrintWriter out = res.getWriter();
      out.println("get POST ......................");
      out.println(e);
      out.println("......................");
    }
  }
예제 #12
0
  protected void doCommon(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    try {
      if (log.isDebugEnabled()) log.debug(HttpUtils.fmtRequest(httpRequest));

      // getRequestURL is the exact string used by the caller in the request.
      // Internally, it's the "request URI" that names the service

      // String requestURL = httpRequest.getRequestURL().toString() ;
      String uri = httpRequest.getRequestURI();

      if (uri.length() > urlLimit) {
        httpResponse.setStatus(HttpServletResponse.SC_REQUEST_URI_TOO_LONG);
        return;
      }

      String serviceURI = chooseServiceURI(uri, httpRequest);
      serviceURI = Service.canonical(serviceURI);

      String sender = httpRequest.getRemoteAddr();
      log.info("[" + sender + "] Service URI = <" + serviceURI + ">");

      // MIME-Type
      String contentType = httpRequest.getContentType();

      //            if ( Joseki.contentSPARQLUpdate.equals(contentType) ||
      //                Joseki.contentSPARQLUpdate_X.equals(contentType) )
      //            {}

      Request request = setupRequest(serviceURI, httpRequest);
      request.setParam(Joseki.VERB, httpRequest.getMethod());

      Response response = new ResponseHttp(request, httpRequest, httpResponse);
      Dispatcher.dispatch(serviceURI, request, response);
    } catch (Exception ex) {
      try {
        log.warn("Internal server error", ex);
        //                httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) ;
        //                httpResponse.flushBuffer() ;
        //                httpResponse.getWriter().close() ;
        httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      } catch (Exception e) {
      }
    }
  }
예제 #13
0
 public void doFilter(ServletRequest request0, ServletResponse response0, FilterChain filterChain)
     throws IOException, ServletException {
   HttpServletRequest request = (HttpServletRequest) request0;
   HttpServletResponse response = (HttpServletResponse) response0;
   if (request.getRequestURI().endsWith(requesturl)) {
     boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
     request.getSession().invalidate();
     if (isAjax) {
       Response<String> kv = new Response<String>();
       kv.setReturncode("00000000");
       kv.setReturnmsg("登出成功");
       outputJson(response, kv);
     } else {
       response.sendRedirect(request.getContextPath() + successurl);
     }
     return;
   }
   filterChain.doFilter(request, response);
 }
  /** Show appropriate order page. */
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    ServletContext sc = getServletContext();
    Connection conn = (Connection) sc.getAttribute("dbConnection");
    HttpSession session = request.getSession();
    synchronized (session) {
      LoginSession ls = (LoginSession) session.getAttribute("loginSession");
      if (ls == null) {
        return;
      }
      Basket basket = ls.getUser().getBasket();
      // If there is no basket, do nothing
      if (basket == null) {
        return;
      }
      if (request.getParameter("dialog").equals("yes")) {
        String msg = null;
        Order order = null;
        try {
          order = new Order();
          msg = order.form(basket, conn);
        } catch (SQLException exc) {
          request.setAttribute("sqlExc", exc);
          request.getRequestDispatcher("/error").forward(request, response);
          return;
        }
        // If there is a message (that means can't form an order)
        if (msg != null) {
          request.setAttribute("errMsg", msg);
        }
      }
      if (request.getParameter("dialog").equals("show")) {
        request.setAttribute("itemList", basket.getItemList());
      }
      request.setAttribute("url", request.getRequestURI());
      request.getRequestDispatcher("/WEB-INF/OrderVerified.jsp").forward(request, response);
    }
  }
예제 #15
0
  public int doEndTag() throws JspException {
    try {
      HttpServletRequest request = (HttpServletRequest) (pageContext.getRequest());
      String file_ext = pageContext.getServletContext().getInitParameter("FileExtention");
      String dbfs_ext = pageContext.getServletContext().getInitParameter("DatabaseExtention");
      String db_name = pageContext.getServletContext().getInitParameter("DatabaseName");
      String db_query = pageContext.getServletContext().getInitParameter("DatabaseQuery");
      JspWriter out = pageContext.getOut();

      int KEEP_CACHE_TIME = 300;
      long current_time = System.currentTimeMillis();

      if (pagebody != null || pageurl != null || dbfsurl != null) {
        VariableTable vt = new VariableTable();
        vt.loadContent(FileCache.getFileContent(getPhysicalPath("/global" + file_ext)));
        vt.loadContent(FileCache.getFileContent(getPhysicalPath("default" + file_ext)));
        if (pageurl != null) vt.loadContent(FileCache.getFileContent(getPhysicalPath(pageurl)));
        if (dbfsurl != null) {
          VariableTable dbparam = new VariableTable();
          dbparam.add("path", java.sql.Types.VARCHAR);
          dbparam.setValue("path", dbfsurl);
          String pagebody = TextCache.getTextContent("source::" + dbfsurl);
          if (pagebody == null) {
            try {
              DBPooledConnection dbconn = DBLogicalManager.getPoolConnection(db_name);
              try {
                pagebody = DBOperation.getString(dbconn, db_query, dbparam);
                vt.loadContent(pagebody);
                TextCache.putContent(
                    System.currentTimeMillis(), "source::" + dbfsurl, pagebody, 20);
              } catch (java.sql.SQLException sqle) {
              }
              dbconn.close();
            } catch (java.lang.Exception sqle) {
            }
          } else {
            vt.loadContent(pagebody);
          }
        }
        if (pagebody != null) vt.loadContent(pagebody);
        getEnv(vt);
        vt.add("JSP.TAG", java.sql.Types.VARCHAR);
        vt.setValue("JSP.TAG", "YES");
        vt.add("REQUEST.URL", java.sql.Types.VARCHAR);
        vt.setValue("REQUEST.URL", request.getRequestURI());

        if (vt.exists("WEBCHART.KEEP_CACHE_TIME")) {
          KEEP_CACHE_TIME = vt.getInt("WEBCHART.KEEP_CACHE_TIME", 300);
          if (KEEP_CACHE_TIME < 5) KEEP_CACHE_TIME = 5;
        }
        java.io.File xsl_file = null;
        if (vt.getString("WEBCHART.XSLDOC") != null)
          xsl_file = new java.io.File(getPhysicalPath(vt.getString("WEBCHART.XSLDOC")));
        String cachekey = vt.parseString(vt.getString("WEBCHART.CACHE"));

        String cache_content = null;

        if (cachekey != null && !vt.exists("WEBCHART.FORCECACHE"))
          cache_content = TextCache.getTextContent(cachekey);

        if (cache_content == null) {
          java.io.StringWriter xmlbuf = new java.io.StringWriter();
          writeXMLHeader(xmlbuf, vt);
          xmlbuf.write("<root>\n");
          WebChart2.generateChart(xmlbuf, null, vt, file_ext);
          xmlbuf.write("</root>\n");

          java.io.StringWriter htmlbuf = new java.io.StringWriter();
          if (xsl_file != null && xsl_file.exists())
            BaseServlet.XML2HTML(
                htmlbuf,
                new java.io.StringReader(xmlbuf.toString()),
                new java.io.StringReader(FileCache.getFileContent(xsl_file)),
                FileCache.getFileContent(xsl_file));
          else
            BaseServlet.XML2HTML(
                htmlbuf,
                new java.io.StringReader(xmlbuf.toString()),
                new java.io.StringReader(StaticResource.getTextResource("defaultxsl")),
                StaticResource.getTextResource("defaultxsl"));
          cache_content = htmlbuf.toString();
          out.write(cache_content);
          if (cachekey != null)
            TextCache.putContent(current_time, cachekey, cache_content, KEEP_CACHE_TIME);
        } else {
          out.write(cache_content);
        }
      }
    } catch (IOException ioe) {
      throw new JspException("Error:    " + ioe.getMessage());
    }
    return EVAL_PAGE;
  }
예제 #16
0
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    // create input/output dir patterns
    String contextPath = httpRequest.getContextPath();
    if (this.inDirPattern == null) {
      // NOTE: Have to do this here because the context path is not
      //       available in init().
      this.inDirPattern =
          Pattern.compile("^" + escape(contextPath) + escape(this.inDirName) + "/(.*)");
      this.outDirPattern =
          Pattern.compile("^" + escape(contextPath) + "/help/[a-z]{2}(?:_[A-Z]{2})?/.*");
      if (ZimbraLog.webclient.isDebugEnabled()) {
        ZimbraLog.webclient.debug("### indir pattern:  " + this.inDirPattern.pattern());
        ZimbraLog.webclient.debug("### outdir pattern: " + this.outDirPattern.pattern());
      }
    }

    // check to see if we need to redirect this request
    String requestUri = httpRequest.getRequestURI();
    if (this.outDirPattern.matcher(requestUri).matches()) {
      // allow it to go through
      chain.doFilter(request, response);
      return;
    }

    // make list of potential locales to check
    Locale preferredLocale = getLocale(httpRequest);
    String language = preferredLocale.getLanguage();
    String country = preferredLocale.getCountry();
    Locale[] locales = {preferredLocale, country != null ? new Locale(language) : null, Locale.US};
    if (ZimbraLog.webclient.isDebugEnabled()) {
      for (Locale locale : locales) {
        ZimbraLog.webclient.debug("locale: " + locale);
      }
    }

    // find out which version of the requested file exists
    Locale actualLocale = preferredLocale;
    Matcher matcher = this.inDirPattern.matcher(requestUri);
    if (!matcher.matches()) {
      httpResponse.sendError(
          HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Help URL doesn't match input pattern.");
      return;
    }

    if (ZimbraLog.webclient.isDebugEnabled()) {
      ZimbraLog.webclient.debug("### filename: " + matcher.group(1));
    }
    String filename = decode(matcher.group(1)).replace('/', File.separatorChar);
    if (ZimbraLog.webclient.isDebugEnabled()) {
      ZimbraLog.webclient.debug("### filename: " + filename);
    }
    File baseDir = new File(this.context.getRealPath("/"));
    if (ZimbraLog.webclient.isDebugEnabled()) {
      ZimbraLog.webclient.debug("### basedir:  " + baseDir);
    }
    for (Locale locale : locales) {
      if (locale == null) continue;
      File file =
          new File(
              baseDir,
              this.outDirName.replaceAll("\\{locale\\}", locale.toString())
                  + File.separatorChar
                  + filename);
      if (file.exists()) {
        actualLocale = locale;
        break;
      }
    }

    // redirect
    String redirectUrl =
        contextPath
            + this.outDirName.replaceAll("\\{locale\\}", actualLocale.toString())
            + "/"
            + filename;
    if (ZimbraLog.webclient.isDebugEnabled()) {
      ZimbraLog.webclient.debug("redirecting to: " + redirectUrl);
    }
    httpResponse.sendRedirect(redirectUrl);
  }
예제 #17
0
 public String getRequestURI() {
   return request.getRequestURI();
 }
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      Locales.setCurrent(request);
      if (Users.getCurrent() == null) { // for a bug in websphere portal 5.1 with Domino LDAP
        Users.setCurrent((String) request.getSession().getAttribute("xava.user"));
      }
      request.getParameter("application"); // for a bug in websphere 5.1
      request.getParameter("module"); // for a bug in websphere 5.1
      Tab tab = (Tab) request.getSession().getAttribute("xava_reportTab");
      int[] selectedRowsNumber =
          (int[]) request.getSession().getAttribute("xava_selectedRowsReportTab");
      Map[] selectedKeys = (Map[]) request.getSession().getAttribute("xava_selectedKeysReportTab");
      int[] selectedRows = getSelectedRows(selectedRowsNumber, selectedKeys, tab);
      request.getSession().removeAttribute("xava_selectedRowsReportTab");
      Integer columnCountLimit =
          (Integer) request.getSession().getAttribute("xava_columnCountLimitReportTab");
      request.getSession().removeAttribute("xava_columnCountLimitReportTab");

      setDefaultSchema(request);
      String user = (String) request.getSession().getAttribute("xava_user");
      request.getSession().removeAttribute("xava_user");
      Users.setCurrent(user);
      String uri = request.getRequestURI();
      if (uri.endsWith(".pdf")) {
        InputStream is;
        JRDataSource ds;
        Map parameters = new HashMap();
        synchronized (tab) {
          tab.setRequest(request);
          parameters.put("Title", tab.getTitle());
          parameters.put("Organization", getOrganization());
          parameters.put("Date", getCurrentDate());
          for (String totalProperty : tab.getTotalPropertiesNames()) {
            parameters.put(totalProperty + "__TOTAL__", getTotal(request, tab, totalProperty));
          }
          TableModel tableModel = getTableModel(request, tab, selectedRows, false, true, null);
          tableModel.getValueAt(0, 0);
          if (tableModel.getRowCount() == 0) {
            generateNoRowsPage(response);
            return;
          }
          is = getReport(request, response, tab, tableModel, columnCountLimit);
          ds = new JRTableModelDataSource(tableModel);
        }
        JasperPrint jprint = JasperFillManager.fillReport(is, parameters, ds);
        response.setContentType("application/pdf");
        response.setHeader(
            "Content-Disposition", "inline; filename=\"" + getFileName(tab) + ".pdf\"");
        JasperExportManager.exportReportToPdfStream(jprint, response.getOutputStream());
      } else if (uri.endsWith(".csv")) {
        String csvEncoding = XavaPreferences.getInstance().getCSVEncoding();
        if (!Is.emptyString(csvEncoding)) {
          response.setCharacterEncoding(csvEncoding);
        }
        response.setContentType("text/x-csv");
        response.setHeader(
            "Content-Disposition", "inline; filename=\"" + getFileName(tab) + ".csv\"");
        synchronized (tab) {
          tab.setRequest(request);
          response
              .getWriter()
              .print(
                  TableModels.toCSV(
                      getTableModel(request, tab, selectedRows, true, false, columnCountLimit)));
        }
      } else {
        throw new ServletException(
            XavaResources.getString("report_type_not_supported", "", ".pdf .csv"));
      }
    } catch (Exception ex) {
      log.error(ex.getMessage(), ex);
      throw new ServletException(XavaResources.getString("report_error"));
    } finally {
      request.getSession().removeAttribute("xava_reportTab");
    }
  }
예제 #19
0
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

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

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

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

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

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

    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<body>");
    out.println("<head>");

    String title = rb.getString("requestinfo.title");
    out.println("<title>" + title + "</title>");
    out.println("</head>");
    out.println("<body bgcolor=\"white\">");

    // img stuff not req'd for source code html showing
    // all links relative!

    // XXX
    // making these absolute till we work out the
    // addition of a PathInfo issue

    out.println("<a href=\"../reqinfo.html\">");
    out.println(
        "<img src=\"../images/code.gif\" height=24 "
            + "width=24 align=right border=0 alt=\"view code\"></a>");
    out.println("<a href=\"../index.html\">");
    out.println(
        "<img src=\"../images/return.gif\" height=24 "
            + "width=24 align=right border=0 alt=\"return\"></a>");

    out.println("<h3>" + title + "</h3>");
    out.println("<table border=0><tr><td>");
    out.println(rb.getString("requestinfo.label.method"));
    out.println("</td><td>");
    out.println(request.getMethod());
    out.println("</td></tr><tr><td>");
    out.println(rb.getString("requestinfo.label.requesturi"));
    out.println("</td><td>");
    out.println(HTMLFilter.filter(request.getRequestURI()));
    out.println("</td></tr><tr><td>");
    out.println(rb.getString("requestinfo.label.protocol"));
    out.println("</td><td>");
    out.println(request.getProtocol());
    out.println("</td></tr><tr><td>");
    out.println(rb.getString("requestinfo.label.pathinfo"));
    out.println("</td><td>");
    out.println(HTMLFilter.filter(request.getPathInfo()));
    out.println("</td></tr><tr><td>");
    out.println(rb.getString("requestinfo.label.remoteaddr"));

    String cipherSuite = (String) request.getAttribute("javax.servlet.request.cipher_suite");
    out.println("</td><td>");
    out.println(request.getRemoteAddr());
    out.println("</table>");

    if (cipherSuite != null) {
      out.println("</td></tr><tr><td>");
      out.println("SSLCipherSuite:");
      out.println("</td>");
      out.println("<td>");
      out.println(request.getAttribute("javax.servlet.request.cipher_suite"));
      out.println("</td>");
    }
  }
예제 #22
0
  /**
   * Show details about the request
   *
   * @param servlet used to get teh servlet context, may be null
   * @param req the request
   * @return string showing the details of the request.
   */
  public static String showRequestDetail(HttpServlet servlet, HttpServletRequest req) {
    StringBuilder sbuff = new StringBuilder();

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

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

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

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

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

    return sbuff.toString();
  }
예제 #23
0
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

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

    if (request instanceof HttpServletRequest) {

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

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

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

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

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

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

      // 压缩传输

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

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

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

  }