/**
   * this is the main method of the servlet that will service all get requests.
   *
   * @param request HttpServletRequest
   * @param responce HttpServletResponce
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = null;
    try {
      try {
        session = request.getSession(true);
      } catch (Exception e) {
        Log.error(e, "PingSession2.doGet(...): error getting session");
        // rethrow the exception for handling in one place.
        throw e;
      }

      // Get the session data value
      Integer ival = (Integer) session.getAttribute("sessiontest.counter");
      // if there is not a counter then create one.
      if (ival == null) {
        ival = new Integer(1);
      } else {
        ival = new Integer(ival.intValue() + 1);
      }
      session.setAttribute("sessiontest.counter", ival);
      // if the session count is equal to five invalidate the session
      if (ival.intValue() == 5) {
        session.invalidate();
      }

      try {
        // Output the page
        response.setContentType("text/html");
        response.setHeader("SessionTrackingTest-counter", ival.toString());

        PrintWriter out = response.getWriter();
        out.println(
            "<html><head><title>Session Tracking Test 2</title></head><body><HR><BR><FONT size=\"+2\" color=\"#000066\">HTTP Session Test 2: Session create/invalidate <BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time: "
                + initTime
                + "</FONT><BR><BR>");
        hitCount++;
        out.println(
            "<B>Hit Count: " + hitCount + "<BR>Session hits: " + ival + "</B></body></html>");
      } catch (Exception e) {
        Log.error(e, "PingSession2.doGet(...): error getting session information");
        // rethrow the exception for handling in one place.
        throw e;
      }

    } catch (Exception e) {
      // log the excecption
      Log.error(e, "PingSession2.doGet(...): error.");
      // set the server responce to 500 and forward to the web app defined error page
      response.sendError(500, "PingSession2.doGet(...): error. " + e.toString());
    }
  } // end of the method
 private void addPrebuiltJsp(String path, String className) {
   try {
     Class clazz =
         Class.forName(
             className); // ttt2 see if possible to not use this, preferably without doing
                         // redirections like RedirectServlet
     Object obj = clazz.newInstance();
     addServlet(new ServletHolder((Servlet) obj), path);
     LOG.info("Added prebuilt JSP: " + obj.toString());
   } catch (Exception e) {
     LOG.fatal(String.format("Failed to load prebuilt JSP for %s and %s", path, className), e);
   }
 }
Exemple #3
0
 private static void endInterpreter(String contextId) throws EvalError {
   Interpreter i = interpreters.get(contextId);
   if (i == null) return;
   i.eval("clear();"); // can't hurt to tell bsh to clean up internally
   interpreters.remove(contextId); // now wait for GC
   Log.log("Destroyed context: " + contextId + " (" + i + ")");
 }
  /**
   * Sell a current holding of stock shares for the given trader. Dispatch to the Trade Portfolio
   * JSP for display
   *
   * @param userID The User buying shares
   * @param symbol The stock to sell
   * @param indx The unique index identifying the users holding to sell
   * @param ctx the servlet context
   * @param req the HttpRequest object
   * @param resp the HttpResponse object
   * @exception javax.servlet.ServletException If a servlet specific exception is encountered
   * @exception javax.io.IOException If an exception occurs while writing results back to the user
   */
  void doSell(
      ServletContext ctx,
      HttpServletRequest req,
      HttpServletResponse resp,
      String userID,
      Integer holdingID)
      throws ServletException, IOException {
    String results = "";
    try {
      OrderDataBean orderData = tAction.sell(userID, holdingID, TradeConfig.orderProcessingMode);

      req.setAttribute("orderData", orderData);
      req.setAttribute("results", results);
    } catch (java.lang.IllegalArgumentException e) { // this is a user error so I will
      // just log the exception and then later on I will redisplay the portfolio page
      // because this is just a user exception
      Log.error(
          e,
          "TradeServletAction.doSell(...)",
          "illegal argument, information should be in exception string",
          "user error");
    } catch (Exception e) {
      // log the exception with error page
      throw new ServletException(
          "TradeServletAction.doSell(...)"
              + " exception selling holding "
              + holdingID
              + " for user ="
              + userID,
          e);
    }
    requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.ORDER_PAGE));
  }
  /**
   * Display User Profile information such as address, email, etc. for the given Trader Dispatch to
   * the Trade Account JSP for display
   *
   * @param userID The User to display profile info
   * @param ctx the servlet context
   * @param req the HttpRequest object
   * @param resp the HttpResponse object
   * @param results A short description of the results/success of this web request provided on the
   *     web page
   * @exception javax.servlet.ServletException If a servlet specific exception is encountered
   * @exception javax.io.IOException If an exception occurs while writing results back to the user
   */
  void doAccount(
      ServletContext ctx,
      HttpServletRequest req,
      HttpServletResponse resp,
      String userID,
      String results)
      throws javax.servlet.ServletException, java.io.IOException {
    try {

      AccountDataBean accountData = tAction.getAccountData(userID);
      AccountProfileDataBean accountProfileData = tAction.getAccountProfileData(userID);
      ArrayList orderDataBeans =
          (TradeConfig.getLongRun() ? new ArrayList() : (ArrayList) tAction.getOrders(userID));

      req.setAttribute("accountData", accountData);
      req.setAttribute("accountProfileData", accountProfileData);
      req.setAttribute("orderDataBeans", orderDataBeans);
      req.setAttribute("results", results);
      requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.ACCOUNT_PAGE));
    } catch (java.lang.IllegalArgumentException e) { // this is a user error so I will
      // forward them to another page rather than throw a 500
      req.setAttribute("results", results + "could not find account for userID = " + userID);
      requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.HOME_PAGE));
      // log the exception with an error level of 3 which means, handled exception but would
      // invalidate a automation run
      Log.error(
          "TradeServletAction.doAccount(...)",
          "illegal argument, information should be in exception string",
          e);
    } catch (Exception e) {
      // log the exception with error page
      throw new ServletException(
          "TradeServletAction.doAccount(...)" + " exception user =" + userID, e);
    }
  }
  private int[] getSelectedRows(int[] selectedRowsNumber, Map[] selectedRowsKeys, Tab tab) {
    if (selectedRowsKeys == null || selectedRowsKeys.length == 0) return new int[0];
    // selectedRowsNumber is the most performant so we use it when possible
    else if (selectedRowsNumber.length == selectedRowsKeys.length) return selectedRowsNumber;
    else {
      // find the rows from the selectedKeys

      // This has a poor performance, but it covers the case when the selected
      // rows are not loaded for the tab, something that can occurs if the user
      // select rows and afterwards reorder the list.
      try {
        int[] s = new int[selectedRowsKeys.length];
        List selectedKeys = Arrays.asList(selectedRowsKeys);
        int end = tab.getTableModel().getTotalSize();
        int x = 0;
        for (int i = 0; i < end; i++) {
          Map key = (Map) tab.getTableModel().getObjectAt(i);
          if (selectedKeys.contains(key)) {
            s[x] = i;
            x++;
          }
        }
        return s;
      } catch (Exception ex) {
        log.warn(XavaResources.getString("fails_selected"), ex);
        throw new XavaException("fails_selected");
      }
    }
  }
Exemple #7
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) {
      }
    }
  }
  /**
   * Logout a Trade User Dispatch to the Trade Welcome JSP for display
   *
   * @param userID The User to logout
   * @param ctx the servlet context
   * @param req the HttpRequest object
   * @param resp the HttpResponse object
   * @param results A short description of the results/success of this web request provided on the
   *     web page
   * @exception javax.servlet.ServletException If a servlet specific exception is encountered
   * @exception javax.io.IOException If an exception occurs while writing results back to the user
   */
  void doLogout(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String userID)
      throws ServletException, IOException {
    String results = "";

    try {
      tAction.logout(userID);

    } catch (java.lang.IllegalArgumentException e) { // this is a user error so I will
      // forward them to another page, at the end of the page.
      req.setAttribute("results", results + "illegal argument:" + e.getMessage());

      // log the exception with an error level of 3 which means, handled exception but would
      // invalidate a automation run
      Log.error(
          e,
          "TradeServletAction.doLogout(...)",
          "illegal argument, information should be in exception string",
          "treating this as a user error and forwarding on to a new page");
    } catch (Exception e) {
      // log the exception and foward to a error page
      Log.error(
          e,
          "TradeServletAction.doLogout(...):",
          "Error logging out" + userID,
          "fowarding to an error page");
      // set the status_code to 500
      throw new ServletException(
          "TradeServletAction.doLogout(...)" + "exception logging out user " + userID, e);
    }
    HttpSession session = req.getSession();
    if (session != null) {
      session.invalidate();
    }

    Object o = req.getAttribute("TSS-RecreateSessionInLogout");
    if (o != null && ((Boolean) o).equals(Boolean.TRUE)) {
      // Recreate Session object before writing output to the response
      // Once the response headers are written back to the client the opportunity
      // to create a new session in this request may be lost
      // This is to handle only the TradeScenarioServlet case
      session = req.getSession(true);
    }
    requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.WELCOME_PAGE));
  }
  // !!! IDEA reports this as unused, but it is called from JSP
  public static FeedInfo getFeedInfo(String feedPath) {
    if (feedPath.startsWith(PATH_FEED + "/")) {
      try {
        if (feedPath.endsWith("/")) {
          feedPath = feedPath.substring(0, feedPath.length() - 1);
        }
        int k = PATH_FEED.length() + 1;
        int p = feedPath.indexOf('/', k);
        return p >= 0
            ? new FeedInfo(feedPath.substring(k, p), Integer.parseInt(feedPath.substring(p + 1)))
            : new FeedInfo(feedPath.substring(k), -1);
      } catch (Exception e) {
        LOG.error("Exception trying to parse the feed info", e);
      }
    }

    LOG.error("Invalid path from feed: " + feedPath);
    return new FeedInfo("INVALID", -1);
  }
Exemple #10
0
  // ------------------------------------------
  public static String chooseServiceURI(String uri, HttpServletRequest httpRequest) {
    String serviceURI = uri;
    String contextPath = httpRequest.getContextPath();

    if (contextPath != null && contextPath.length() > 0)
      serviceURI = serviceURI.substring(contextPath.length());

    String servletPath = httpRequest.getServletPath();

    // Suggested by Frank Hartman: helps make conf files more portable
    // between /joseki/myModel and /myModel but if the servlet is
    // explicitly named in web.xml, it strips that off
    //        if ( servletPath != null && servletPath.length() > 0 )
    //            dispatchURI = dispatchURI.substring(servletPath.length()) ;

    // Suggested by damien_coraboeuf
    // TODO Test and verify
    //        if ( servletPath != null && servletPath.length() > 0 )
    //            serviceURI = serviceURI.substring(servletPath.length()) ;

    // Example:
    //    <servlet-mapping>
    //        <servlet-name>JosekiServlet</servlet-name>
    //        <url-pattern>/ws/joseki/*</url-pattern>
    //    </servlet-mapping>

    if (log.isDebugEnabled()) {
      if (servletPath == null) servletPath = "";
      if (contextPath == null) contextPath = "";
      log.debug(
          "DispatchURI: "
              + uri
              + " => "
              + serviceURI
              + " (ContextPath = "
              + contextPath
              + ", ServletPath = "
              + servletPath
              + ")");
    }
    return serviceURI;
  }
  /**
   * Update User Profile information such as address, email, etc. for the given Trader Dispatch to
   * the Trade Account JSP for display If any in put is incorrect revert back to the account page w/
   * an appropriate message
   *
   * @param userID The User to upddate profile info
   * @param password The new User password
   * @param cpassword Confirm password
   * @param fullname The new User fullname info
   * @param address The new User address info
   * @param cc The new User credit card info
   * @param email The new User email info
   * @param ctx the servlet context
   * @param req the HttpRequest object
   * @param resp the HttpResponse object
   * @exception javax.servlet.ServletException If a servlet specific exception is encountered
   * @exception javax.io.IOException If an exception occurs while writing results back to the user
   */
  void doAccountUpdate(
      ServletContext ctx,
      HttpServletRequest req,
      HttpServletResponse resp,
      String userID,
      String password,
      String cpassword,
      String fullName,
      String address,
      String creditcard,
      String email)
      throws javax.servlet.ServletException, java.io.IOException {
    String results = "";

    // First verify input data
    boolean doUpdate = true;
    if (password.equals(cpassword) == false) {
      results = "Update profile error: passwords do not match";
      doUpdate = false;
    } else if (password.length() <= 0
        || fullName.length() <= 0
        || address.length() <= 0
        || creditcard.length() <= 0
        || email.length() <= 0) {
      results = "Update profile error: please fill in all profile information fields";
      doUpdate = false;
    }
    AccountProfileDataBean accountProfileData =
        new AccountProfileDataBean(userID, password, fullName, address, email, creditcard);
    try {
      if (doUpdate) {
        accountProfileData = tAction.updateAccountProfile(accountProfileData);
        results = "Account profile update successful";
      }

    } catch (java.lang.IllegalArgumentException e) { // this is a user error so I will
      // forward them to another page rather than throw a 500
      req.setAttribute(
          "results",
          results
              + "invalid argument, check userID is correct, and the database is populated"
              + userID);
      Log.error(
          e,
          "TradeServletAction.doAccount(...)",
          "illegal argument, information should be in exception string",
          "treating this as a user error and forwarding on to a new page");
    } catch (Exception e) {
      // log the exception with error page
      throw new ServletException(
          "TradeServletAction.doAccountUpdate(...)" + " exception user =" + userID, e);
    }
    doAccount(ctx, req, resp, userID, results);
  }
  private void logOut(String browserId) throws Exception {
    // ttt2 the right way to do it is to go through all the sessions of the current browser, which
    // would require a new field and a new index;
    // not sure if it's worth it, but this would work: A logs in, forgets to log out, B delets the
    // cookies, logs in, A sees B is logged in, then B
    // restores the cookies and uses A's account
    if (browserId == null) {
      return;
    }

    List<LoginInfo> loginInfos = loginInfoDb.getLoginsForBrowser(browserId);
    long expireTarget = System.currentTimeMillis() - Utils.ONE_DAY;
    for (LoginInfo loginInfo : loginInfos) {
      if (loginInfo.expiresOn <= expireTarget) {
        LOG.info(String.format("LoginInfo %s is enough in the past", loginInfo));
      } else {
        LOG.info(String.format("Logging out: %s", loginInfo));
        loginInfoDb.updateExpireTime(browserId, loginInfo.sessionId, expireTarget);
      }
    }
  }
  private void handleRemoveFeedPost(Request request, HttpServletResponse httpServletResponse)
      throws Exception {
    LOG.info("removing feed");
    User user = userHelpers.getUser(request);

    try {
      if (user == null) {
        LOG.error("User not found");
        return;
      }

      String feedId = request.getParameter(PARAM_FEED_ID);

      LOG.info(String.format("Removing feed %s for user %s", feedId, user));

      // ttt1 add some validation; probably best try to actually get data, set the title, ...
      if (feedId == null || feedId.equals("")) {
        LOG.error("feed not specified");
        // ttt1 show some error
        return;
      }

      if (user.feedIds.remove(
          feedId)) { // ttt2 clean up the global feed table; that's probably better done if nobody
                     // accesses a feed for 3 months or so
        userDb.updateFeeds(user);
        LOG.info(String.format("Removed feed %s for user %s", feedId, user));
      } else {
        LOG.info(String.format("No feed found with ID %s for user %s", feedId, user));
      }
    } finally {
      httpServletResponse.sendRedirect(PATH_FEED_ADMIN);
    }
  }
  private void handleAddFeedPost(Request request, HttpServletResponse httpServletResponse)
      throws Exception {
    LOG.info("adding feed");
    User user = userHelpers.getUser(request);

    try {
      if (user == null) {
        LOG.error("User not found");
        return;
      }

      String url = request.getParameter(PARAM_NEW_FEED_URL);
      // ttt1 add some validation; probably best try to actually get data, set the title, ...
      if (url == null || url.equals("")) {
        LOG.error("New feed not specified");
        // ttt1 show some error
        return;
      }

      MessageDigest digest = MessageDigest.getInstance("MD5");
      String feedId = PrintUtils.byteArrayAsUrlString(digest.digest(url.getBytes("UTF-8")));
      feedId = feedId.substring(0, Config.getConfig().feedIdSize);

      Feed feed = feedDb.get(feedId);
      if (feed == null) {
        feed = new Feed(feedId, url);
        feedDb.add(feed);
      }

      if (user.feedIds.contains(feedId)) {
        LOG.error(String.format("Trying to add existing feed %s to user %s", feedId, user));
      } else {
        user.feedIds.add(feedId);
        userDb.updateFeeds(user);
      }
    } finally {
      httpServletResponse.sendRedirect(PATH_FEED_ADMIN);
    }
  }
  public int doStartTag() throws JspException {
    try {
      HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
      ModuleContext context = (ModuleContext) request.getSession().getAttribute("context");

      String viewObject = request.getParameter("viewObject");
      viewObject = (viewObject == null || viewObject.equals("")) ? "xava_view" : viewObject;
      View view = (View) context.get(request, viewObject);

      MetaReference metaReference = view.getMetaReference(reference).cloneMetaReference();
      metaReference.setName(reference);
      String prefix = request.getParameter("propertyPrefix");
      prefix = prefix == null ? "" : prefix;
      String application = request.getParameter("application");
      String module = request.getParameter("module");
      String referenceKey = Ids.decorate(application, module, prefix + reference);
      request.setAttribute(referenceKey, metaReference);
      String editorURL =
          "reference.jsp?referenceKey="
              + referenceKey
              + "&onlyEditor=true&frame=false&composite=false&descriptionsList=true";
      String editorPrefix = Module.isPortlet() ? "/WEB-INF/jsp/xava/" : "/xava/";
      try {
        pageContext.include(editorPrefix + editorURL);
      } catch (ServletException ex) {
        Throwable cause = ex.getRootCause() == null ? ex : ex.getRootCause();
        log.error(cause.getMessage(), cause);
        pageContext.include(editorPrefix + "editors/notAvailableEditor.jsp");
      } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        pageContext.include(editorPrefix + "editors/notAvailableEditor.jsp");
      }
    } catch (Exception ex) {
      log.error(ex.getMessage(), ex);
      throw new JspException(XavaResources.getString("descriptionsList_tag_error", reference));
    }
    return SKIP_BODY;
  }
  /**
   * Retrieve the current portfolio of stock holdings for the given trader Dispatch to the Trade
   * Portfolio JSP for display
   *
   * @param userID The User requesting to view their portfolio
   * @param ctx the servlet context
   * @param req the HttpRequest object
   * @param resp the HttpResponse object
   * @param results A short description of the results/success of this web request provided on the
   *     web page
   * @exception javax.servlet.ServletException If a servlet specific exception is encountered
   * @exception javax.io.IOException If an exception occurs while writing results back to the user
   */
  void doPortfolio(
      ServletContext ctx,
      HttpServletRequest req,
      HttpServletResponse resp,
      String userID,
      String results)
      throws ServletException, IOException {

    try {
      // Get the holdiings for this user

      Collection quoteDataBeans = new ArrayList();
      Collection holdingDataBeans = tAction.getHoldings(userID);

      // Walk through the collection of user
      //  holdings and creating a list of quotes
      if (holdingDataBeans.size() > 0) {

        Iterator it = holdingDataBeans.iterator();
        while (it.hasNext()) {
          HoldingDataBean holdingData = (HoldingDataBean) it.next();
          QuoteDataBean quoteData = tAction.getQuote(holdingData.getQuoteID());
          quoteDataBeans.add(quoteData);
        }
      } else {
        results = results + ".  Your portfolio is empty.";
      }
      req.setAttribute("results", results);
      req.setAttribute("holdingDataBeans", holdingDataBeans);
      req.setAttribute("quoteDataBeans", quoteDataBeans);
      requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.PORTFOLIO_PAGE));
    } catch (java.lang.IllegalArgumentException e) { // this is a user error so I will
      // forward them to another page rather than throw a 500
      req.setAttribute("results", results + "illegal argument:" + e.getMessage());
      requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.PORTFOLIO_PAGE));
      // log the exception with an error level of 3 which means, handled exception but would
      // invalidate a automation run
      Log.error(
          e,
          "TradeServletAction.doPortfolio(...)",
          "illegal argument, information should be in exception string",
          "user error");
    } catch (Exception e) {
      // log the exception with error page
      throw new ServletException(
          "TradeServletAction.doPortfolio(...)" + " exception user =" + userID, e);
    }
  }
  /**
   * Buy a new holding of shares for the given trader Dispatch to the Trade Portfolio JSP for
   * display
   *
   * @param userID The User buying shares
   * @param symbol The stock to purchase
   * @param amount The quantity of shares to purchase
   * @param ctx the servlet context
   * @param req the HttpRequest object
   * @param resp the HttpResponse object
   * @exception javax.servlet.ServletException If a servlet specific exception is encountered
   * @exception javax.io.IOException If an exception occurs while writing results back to the user
   */
  void doBuy(
      ServletContext ctx,
      HttpServletRequest req,
      HttpServletResponse resp,
      String userID,
      String symbol,
      String quantity)
      throws ServletException, IOException {

    String results = "";

    try {
      OrderDataBean orderData =
          tAction.buy(
              userID, symbol, new Double(quantity).doubleValue(), TradeConfig.orderProcessingMode);

      req.setAttribute("orderData", orderData);
      req.setAttribute("results", results);
    } catch (java.lang.IllegalArgumentException e) { // this is a user error so I will
      // forward them to another page rather than throw a 500
      req.setAttribute("results", results + "illegal argument:");
      requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.HOME_PAGE));
      // log the exception with an error level of 3 which means, handled exception but would
      // invalidate a automation run
      Log.error(
          e,
          "TradeServletAction.doBuy(...)",
          "illegal argument. userID = " + userID,
          "symbol = " + symbol);
    } catch (Exception e) {
      // log the exception with error page
      throw new ServletException(
          "TradeServletAction.buy(...)"
              + " exception buying stock "
              + symbol
              + " for user "
              + userID,
          e);
    }
    requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.ORDER_PAGE));
  }
Exemple #18
0
  /**
   * this is the main method of the servlet that will service all get requests.
   *
   * @param request HttpServletRequest
   * @param responce HttpServletResponce
   */
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      res.setContentType("text/html");

      // The following 2 lines are the difference between PingServlet and PingServletWriter
      //   the latter uses a PrintWriter for output versus a binary output stream.
      ServletOutputStream out = res.getOutputStream();
      // java.io.PrintWriter out = res.getWriter();
      hitCount++;
      out.println(
          "<html><head><title>Ping Servlet</title></head>"
              + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Ping Servlet<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time : "
              + initTime
              + "<BR><BR></FONT>  <B>Hit Count: "
              + hitCount
              + "</B></body></html>");
    } catch (Exception e) {
      Log.error(e, "PingServlet.doGet(...): general exception caught");
      res.sendError(500, e.toString());
    }
  }
Exemple #19
0
  private void servletEnv() {
    if (!log.isDebugEnabled()) return;

    try {
      java.net.URL url = servletContext.getResource("/");
      log.trace("Joseki base directory: " + url);
    } catch (Exception ex) {
    }

    if (servletConfig != null) {
      String tmp = servletConfig.getServletName();
      log.trace("Servlet = " + (tmp != null ? tmp : "<null>"));
      @SuppressWarnings("unchecked")
      Enumeration<String> en = servletConfig.getInitParameterNames();

      for (; en.hasMoreElements(); ) {
        String s = en.nextElement();
        log.trace("Servlet parameter: " + s + " = " + servletConfig.getInitParameter(s));
      }
    }
    if (servletContext != null) {
      // Name of webapp
      String tmp = servletContext.getServletContextName();
      // msg(Level.FINE, "Webapp = " + (tmp != null ? tmp : "<null>"));
      log.debug("Webapp = " + (tmp != null ? tmp : "<null>"));

      // NB This servlet may not have been loaded as part of a web app
      @SuppressWarnings("unchecked")
      Enumeration<String> en = servletContext.getInitParameterNames();
      for (; en.hasMoreElements(); ) {
        String s = en.nextElement();
        log.debug("Webapp parameter: " + s + " = " + servletContext.getInitParameter(s));
      }
    }
    /*
    for ( Enumeration enum = servletContext.getAttributeNames() ;  enum.hasMoreElements() ; )
    {
        String s = (String)enum.nextElement() ;
        logger.log(LEVEL, "Webapp attribute: "+s+" = "+context.getAttribute(s)) ;
    }
     */
  }
  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");
      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("\n\n\n\n\n\n\n<html>\n<head>\n    <title>");
      if (_jspx_meth_fmt_message_0(_jspx_page_context)) return;
      out.write(
          "</title>\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"/style/global.css\">\n    <style type=\"text/css\">\n        .drop-shadow {\n             font-weight: bold;\n             font-size: 14pt;\n             color: white;\n             text-shadow: black 0.1em 0.1em 0.2em;\n             padding-top: 21px;}\n    </style>\n    <meta name=\"decorator\" content=\"none\"/>\n</head>\n\n");
      org.jivesoftware.util.WebManager webManager = null;
      synchronized (_jspx_page_context) {
        webManager =
            (org.jivesoftware.util.WebManager)
                _jspx_page_context.getAttribute("webManager", PageContext.PAGE_SCOPE);
        if (webManager == null) {
          webManager = new org.jivesoftware.util.WebManager();
          _jspx_page_context.setAttribute("webManager", webManager, PageContext.PAGE_SCOPE);
        }
      }
      out.write('\n');
      java.util.HashMap errors = null;
      synchronized (_jspx_page_context) {
        errors =
            (java.util.HashMap) _jspx_page_context.getAttribute("errors", PageContext.PAGE_SCOPE);
        if (errors == null) {
          errors = new java.util.HashMap();
          _jspx_page_context.setAttribute("errors", errors, PageContext.PAGE_SCOPE);
        }
      }
      out.write('\n');
      webManager.init(request, response, session, application, out);

      boolean create = request.getParameter("create") != null;
      String username = ParamUtils.getParameter(request, "username");
      String name = ParamUtils.getParameter(request, "name");
      String email = ParamUtils.getParameter(request, "email");
      String password = ParamUtils.getParameter(request, "password");
      String passwordConfirm = ParamUtils.getParameter(request, "passwordConfirm");
      String reCaptchaChallenge = ParamUtils.getParameter(request, "recaptcha_challenge_field");
      String reCaptchaResponse = ParamUtils.getParameter(request, "recaptcha_response_field");

      RegistrationPlugin plugin =
          (RegistrationPlugin)
              webManager.getXMPPServer().getPluginManager().getPlugin("registration");
      ReCaptcha reCaptcha = null;
      if (plugin.reCaptchaEnabled()) {
        reCaptcha =
            ReCaptchaFactory.newReCaptcha(
                plugin.getReCaptchaPublicKey(),
                plugin.getReCaptchaPrivateKey(),
                plugin.reCaptchaNoScript());
      }

      // Handle a request to create a user:
      if (create) {
        // Validate
        if (username == null) {
          errors.put("username", "");
        } else {
          try {
            username = username.trim().toLowerCase();
            username = JID.escapeNode(username);
            username = Stringprep.nodeprep(username);
          } catch (StringprepException se) {
            errors.put("username", "");
          }
        }
        if (password == null) {
          errors.put("password", "");
        }
        if (passwordConfirm == null) {
          errors.put("passwordConfirm", "");
        }
        if (password != null && passwordConfirm != null && !password.equals(passwordConfirm)) {
          errors.put("passwordMatch", "");
        }
        if (plugin.reCaptchaEnabled()) {
          ReCaptchaResponse captchaResponse = null;
          try {
            captchaResponse =
                reCaptcha.checkAnswer(
                    request.getRemoteAddr(), reCaptchaChallenge, reCaptchaResponse);
          } catch (Exception e) {
          }
          if (captchaResponse == null || !captchaResponse.isValid()) {
            errors.put("reCaptchaFail", "");
          }
        }

        // do a create if there were no errors
        if (errors.size() == 0) {
          try {
            webManager.getUserManager().createUser(username, password, name, email);

            response.sendRedirect("sign-up.jsp?success=true");
            return;
          } catch (UserAlreadyExistsException e) {
            errors.put("usernameAlreadyExists", "");
          } catch (Exception e) {
            errors.put("general", "");
            Log.error(e);
          }
        }
      }

      out.write(
          "\n\n<body>\n\n<div id=\"jive-header\">\n<table cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" border=\"0\">\n    <tbody>\n        <tr><td class=\"drop-shadow\">&nbsp;");
      out.print(plugin.getHeader());
      out.write("</td></tr>    \n    </tbody>\n</table>\n</div>\n\n<div id=\"jive-content\">\n\n");
      if (!plugin.webEnabled()) {
        out.write('\n');
        out.write('\n');
        if (_jspx_meth_fmt_message_1(_jspx_page_context)) return;
        out.write('\n');
        out.write('\n');
      } else {
        out.write("\n\n<p>");
        if (_jspx_meth_fmt_message_2(_jspx_page_context)) return;
        out.write("</p>\n\n");
        if (_jspx_meth_c_set_0(_jspx_page_context)) return;
        out.write('\n');
        if (_jspx_meth_c_set_1(_jspx_page_context)) return;
        out.write('\n');
        out.write('\n');
        if (!errors.isEmpty()) {
          out.write(
              "\n\n    <div class=\"jive-error\">\n    <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n    <tbody>\n        <tr>\n            <td class=\"jive-icon\"><img src=\"images/error-16x16.gif\" width=\"16\" height=\"16\" border=\"0\"/></td>\n            <td class=\"jive-icon-label\">\n\n            ");
          if (errors.get("general") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_3(_jspx_page_context)) return;
            out.write("\n            ");
          } else if (errors.get("username") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_4(_jspx_page_context)) return;
            out.write("\n            ");
          } else if (errors.get("usernameAlreadyExists") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_5(_jspx_page_context)) return;
            out.write("\n            ");
          } else if (errors.get("name") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_6(_jspx_page_context)) return;
            out.write("\n            ");
          } else if (errors.get("email") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_7(_jspx_page_context)) return;
            out.write("\n            ");
          } else if (errors.get("password") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_8(_jspx_page_context)) return;
            out.write("\n            ");
          } else if (errors.get("passwordMatch") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_9(_jspx_page_context)) return;
            out.write("\n            ");
          } else if (errors.get("passwordConfirm") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_10(_jspx_page_context)) return;
            out.write("\n            ");
          } else if (errors.get("reCaptchaFail") != null) {
            out.write("\n                ");
            if (_jspx_meth_fmt_message_11(_jspx_page_context)) return;
            out.write("\n            ");
          }
          out.write(
              "\n            </td>\n        </tr>\n    </tbody>\n    </table>\n    </div>\n    <br>\n\n");
        } else if (request.getParameter("success") != null) {
          out.write(
              "\n\n    <div class=\"jive-success\">\n    <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n    <tbody>\n        <tr>\n            <td class=\"jive-icon\"><img src=\"images/success-16x16.gif\" width=\"16\" height=\"16\" border=\"0\"></td>\n            <td class=\"jive-icon-label\">");
          if (_jspx_meth_fmt_message_12(_jspx_page_context)) return;
          out.write("</td>\n        </tr>\n    </tbody>\n    </table>\n    </div><br>\n\n");
        }
        out.write(
            "\n\n<form name=\"f\" action=\"sign-up.jsp\" method=\"get\">\n\n<div class=\"jive-contentBoxHeader\">");
        if (_jspx_meth_fmt_message_13(_jspx_page_context)) return;
        out.write(
            "</div>\n<div class=\"jive-contentBox\">\n    <div>\n    <table cellpadding=\"3\" cellspacing=\"0\" border=\"0\" width=\"100%\">\n    <tbody>\n    <tr>\n        <td width=\"1%\" nowrap><label for=\"usernametf\">");
        if (_jspx_meth_fmt_message_14(_jspx_page_context)) return;
        out.write(
            ":</label> *</td>\n        <td width=\"99%\">\n            <input type=\"text\" name=\"username\" size=\"30\" maxlength=\"75\" value=\"");
        out.print(((username != null) ? username : ""));
        out.write(
            "\"\n             id=\"usernametf\" autocomplete=\"off\">\n        </td>\n    </tr>\n    <tr>\n        <td width=\"1%\" nowrap>\n            <label for=\"nametf\">");
        if (_jspx_meth_fmt_message_15(_jspx_page_context)) return;
        out.write(
            ":</label>\n        </td>\n        <td width=\"99%\">\n            <input type=\"text\" name=\"name\" size=\"30\" maxlength=\"75\" value=\"");
        out.print(((name != null) ? name : ""));
        out.write(
            "\"\n             id=\"nametf\">\n        </td>\n    </tr>\n    <tr>\n        <td width=\"1%\" nowrap>\n            <label for=\"emailtf\">");
        if (_jspx_meth_fmt_message_16(_jspx_page_context)) return;
        out.write(
            ":</label></td>\n        <td width=\"99%\">\n            <input type=\"text\" name=\"email\" size=\"30\" maxlength=\"75\" value=\"");
        out.print(((email != null) ? email : ""));
        out.write(
            "\"\n             id=\"emailtf\">\n        </td>\n    </tr>\n    <tr>\n        <td nowrap>\n            <label for=\"passtf\">");
        if (_jspx_meth_fmt_message_17(_jspx_page_context)) return;
        out.write(
            ":</label> *\n        </td>\n        <td width=\"99%\">\n            <input type=\"password\" name=\"password\" value=\"\" size=\"20\" maxlength=\"75\"\n             id=\"passtf\">\n        </td>\n    </tr>\n    <tr>\n        <td width=\"1%\" nowrap>\n            <label for=\"confpasstf\">");
        if (_jspx_meth_fmt_message_18(_jspx_page_context)) return;
        out.write(
            ":</label> *\n        </td>\n        <td width=\"99%\">\n            <input type=\"password\" name=\"passwordConfirm\" value=\"\" size=\"20\" maxlength=\"75\"\n             id=\"confpasstf\">\n        </td>\n    </tr>\n    </tbody>\n    </table>\n    <br>\n    <span class=\"jive-description\">\n    * ");
        if (_jspx_meth_fmt_message_19(_jspx_page_context)) return;
        out.write("\n    </span>\n    </div>\n</div>\n\n");
        if (reCaptcha != null) {
          out.write('\n');
          out.print(reCaptcha.createRecaptchaHtml(null, null, 0));
          out.write('\n');
        }
        out.write("\n<input type=\"submit\" name=\"create\" value=\"");
        if (_jspx_meth_fmt_message_20(_jspx_page_context)) return;
        out.write(
            "\">\n\n</form>\n\n<script language=\"JavaScript\" type=\"text/javascript\">\ndocument.f.username.focus();\n</script>\n\n");
      }
      out.write("\n\n</body>\n</html>");
    } 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);
    }
  }
Exemple #21
0
 public Servlet(String string) {
   log.info("-------- " + string);
 }
Exemple #22
0
  protected void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      // A good request looks like /mljam/contextid/verb?name=varname
      // The extra path info includes the context id and verb
      String extra = req.getPathInfo(); // "/contextid/verb"
      if (extra == null || extra.equals("")) {
        throw new ClientProblemException(
            "Request requires a context id and verb in its extra path info");
      }
      String[] parts = extra.split("/"); // { "", "contextid", "verb" }
      if (parts.length < 2) {
        throw new ClientProblemException(
            "Request requires a context id and verb in its extra path info");
      } else if (parts.length < 3) {
        throw new ClientProblemException("Request requires a verb in its extra path info");
      }

      String contextId = parts[1];
      String verb = parts[2];
      String method = req.getMethod();

      if (method.equalsIgnoreCase("get")) {

        // We have three GET verbs: get, get-stdout, get-stderr.
        // These are all idempotent, while the POST verbs aren't.  The get
        // verb accept a "name" query string parameter.  The get verb returns
        // either XQuery to evaluate (indicated by x-marklogic/xquery content type)
        // or a raw binary (indicated by an application/binary-encoded content type).

        if (verb.equalsIgnoreCase("get")) {
          String name = req.getParameter("name");
          if (name == null || name.equals("")) {
            throw new ClientProblemException("The get verb requires a name parameter");
          }
          Interpreter i = getInterpreter(contextId);
          Object o = i.get(name);
          if (o instanceof byte[]) {
            sendBinaryResponse(res, (byte[]) o);
          } else if (o instanceof String) {
            sendStringResponse(res, (String) o);
          } else {
            sendXQueryResponse(res, o);
          }
        } else if (verb.equalsIgnoreCase("get-stdout")) {
          Interpreter i = getInterpreter(contextId);
          i.getOut().flush();
          CircularByteArrayOutputStream circ = (CircularByteArrayOutputStream) i.get("mljamout");
          if (circ != null) {
            sendStringResponse(res, circ.toString());
            circ.reset();
          } else {
            throw new ServerProblemException("Could not fetch mljamout from interpreter context");
          }
        } else if (verb.equalsIgnoreCase("get-stderr")) {
          Interpreter i = getInterpreter(contextId);
          i.getErr().flush();
          CircularByteArrayOutputStream circ = (CircularByteArrayOutputStream) i.get("mljamerr");
          if (circ != null) {
            sendStringResponse(res, circ.toString());
            circ.reset();
          } else {
            throw new ServerProblemException("Could not fetch mljamerr from interpreter context");
          }
        } else {
          throw new ClientProblemException("Unrecognized GET verb: " + verb);
        }
      } else if (method.equalsIgnoreCase("post")) {
        // We have six POST verbs: eval, unset, end, source, set-string, and set-binary.
        // These are POST verbs because they aren't idempotent.
        // The set-string, set-binary, unset, and source verbs accept a "name"
        // query string parameter.  The set-string and set-binary verbs accept
        // a value in their post body.  The eval verb accepts code in its post body.

        if (verb.equalsIgnoreCase("set-string")) {
          String name = req.getParameter("name");
          if (name == null || name.equals("")) {
            throw new ClientProblemException("The set-string verb requires a name parameter");
          }
          String body = getBody(req); // a value of "" is legit
          Interpreter i = getInterpreter(contextId);
          i.unset(name);
          i.set(name, body);
          sendNoResponse(res);
        } else if (verb.equalsIgnoreCase("set-binary")) {
          String name = req.getParameter("name");
          if (name == null || name.equals("")) {
            throw new ClientProblemException("The set-binary verb requires a name parameter");
          }
          String body = getBody(req); // a value of "" is legit
          byte[] bodyBytes = hexDecode(body); // later could do this streaming for speed
          Interpreter i = getInterpreter(contextId);
          i.unset(name);
          i.set(name, bodyBytes);
          sendNoResponse(res);
        } else if (verb.equalsIgnoreCase("eval")) {
          String body = getBody(req);
          if (body == null || body.equals("")) {
            throw new ClientProblemException(
                "The eval verb requires a post body containing code to eval");
          }
          Interpreter i = getInterpreter(contextId);
          i.eval(body);
          sendNoResponse(res);
        } else if (verb.equalsIgnoreCase("eval-get")) {
          String body = getBody(req);
          if (body == null || body.equals("")) {
            throw new ClientProblemException(
                "The eval-get verb requires a post body containing code to eval");
          }
          Interpreter i = getInterpreter(contextId);
          Object o = i.eval(body);
          if (o instanceof byte[]) {
            sendBinaryResponse(res, (byte[]) o);
          } else if (o instanceof String) {
            sendStringResponse(res, (String) o);
          } else {
            sendXQueryResponse(res, o);
          }
        } else if (verb.equalsIgnoreCase("unset")) {
          String name = req.getParameter("name");
          if (name == null || name.equals("")) {
            throw new ClientProblemException("The unset verb requires a name parameter");
          }
          Interpreter i = getInterpreter(contextId);
          i.unset(name);
          sendNoResponse(res);
        } else if (verb.equalsIgnoreCase("end")) {
          endInterpreter(contextId);
          sendNoResponse(res);
        } else if (verb.equalsIgnoreCase("source")) {
          String name = req.getParameter("name");
          if (name == null || name.equals("")) {
            throw new ClientProblemException("The source verb requires a name parameter");
          }
          Interpreter i = getInterpreter(contextId);
          i.source(name);
          sendNoResponse(res);
        } else {
          throw new ClientProblemException("Unrecognized POST verb: " + verb);
        }
      }
    } catch (TargetError e) {
      Throwable target = e.getTarget();
      Log.log(e);
      Log.log("Target: " + target);
      sendServerProblemResponse(
          res,
          target.getClass().getName()
              + ": "
              + target.getMessage()
              + " when executing Java code: "
              + e.getErrorText()); // include full trace?
    } catch (EvalError e) {
      Log.log(e);
      sendServerProblemResponse(
          res, e.getClass().getName() + ": " + e.getMessage()); // include full trace?
    } catch (ClientProblemException e) {
      Log.log(e);
      sendClientProblemResponse(res, e.getMessage());
    } catch (ServerProblemException e) {
      Log.log(e);
      sendServerProblemResponse(res, e.getMessage());
    }
  }
Exemple #23
0
 /** Destroys the servlet. */
 @Override
 public void destroy() {
   log.debug("destroy");
 }
  /**
   * Normally sets the path and a few attributes that the JSPs are likely to need. Also verifies the
   * login information. If necessary, just redirects to the login page.
   *
   * @param target
   * @param request
   * @param httpServletResponse
   * @param secured
   * @return true if the request is already handled so the .jsp shouldn't get called
   * @throws Exception
   */
  private boolean prepareForJspGet(
      String target, Request request, HttpServletResponse httpServletResponse, boolean secured)
      throws Exception {

    LoginInfo.SessionInfo sessionInfo = UserHelpers.getSessionInfo(request);

    LOG.info(
        String.format(
            "hndl - %s ; %s; %s ; %s",
            target,
            request.getPathInfo(),
            request.getMethod(),
            secured ? "secured" : "not secured"));

    String path = request.getUri().getDecodedPath();

    boolean redirectToLogin = path.equals(PATH_LOGOUT);
    LoginInfo loginInfo = null;
    if (sessionInfo.isNull()) {
      redirectToLogin = true;
      LOG.info("Null session info. Logging in again.");
    } else {
      loginInfo =
          loginInfoDb.get(
              sessionInfo.browserId,
              sessionInfo.sessionId); // ttt2 use a cache, to avoid going to DB
      if (loginInfo == null || loginInfo.expiresOn < System.currentTimeMillis()) {
        LOG.info("Session has expired. Logging in again. Info: " + loginInfo);
        redirectToLogin = true;
      }
    }

    if (!path.equals(PATH_LOGIN) && !path.equals(PATH_SIGNUP) && !path.equals(PATH_ERROR)) {

      if (redirectToLogin) {
        // ttt2 perhaps store URI, to return to it after login
        logOut(sessionInfo.browserId);
        addLoginParams(request, loginInfo);
        httpServletResponse.sendRedirect(PATH_LOGIN);
        return true;
      }

      User user = userDb.get(loginInfo.userId);
      if (user == null) {
        WebUtils.redirectToError("Unknown user", request, httpServletResponse);
        return true;
      }
      if (!user.active) {
        WebUtils.redirectToError("Account is not active", request, httpServletResponse);
        return true;
      }
      request.setAttribute(VAR_FEED_DB, feedDb);
      request.setAttribute(VAR_USER_DB, userDb);
      request.setAttribute(VAR_ARTICLE_DB, articleDb);
      request.setAttribute(VAR_READ_ARTICLES_COLL_DB, readArticlesCollDb);

      request.setAttribute(VAR_USER, user);
      request.setAttribute(VAR_LOGIN_INFO, loginInfo);

      MultiMap<String> params = new MultiMap<>();
      params.put(PARAM_PATH, path);
      request.setParameters(params);
    }

    if (path.equals(PATH_LOGIN)) {
      addLoginParams(request, loginInfo);
    }
    return false;
  }
  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");
    }
  }
Exemple #26
0
  /**
   * this is the main method of the servlet that will service all get requests.
   *
   * @param request HttpServletRequest
   * @param responce HttpServletResponce
   */
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      res.setContentType("text/html");

      ServletOutputStream out = res.getOutputStream();
      hitCount++;
      long totalMemory = Runtime.getRuntime().totalMemory();

      long maxMemoryBeforeGC = Runtime.getRuntime().maxMemory();
      long freeMemoryBeforeGC = Runtime.getRuntime().freeMemory();
      long startTime = System.currentTimeMillis();

      System.gc(); // Invoke the GC.

      long endTime = System.currentTimeMillis();
      long maxMemoryAfterGC = Runtime.getRuntime().maxMemory();
      long freeMemoryAfterGC = Runtime.getRuntime().freeMemory();

      out.println(
          "<html><head><title>ExplicitGC</title></head>"
              + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Explicit Garbage Collection<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time : "
              + initTime
              + "<BR><BR></FONT>  <B>Hit Count: "
              + hitCount
              + "<br>"
              + "<table border=\"0\"><tr>"
              + "<td align=\"right\">Total Memory</td><td align=\"right\">"
              + totalMemory
              + "</td>"
              + "</tr></table>"
              + "<table width=\"350\"><tr><td colspan=\"2\" align=\"left\">"
              + "Statistics before GC</td></tr>"
              + "<tr><td align=\"right\">"
              + "Max Memory</td><td align=\"right\">"
              + maxMemoryBeforeGC
              + "</td></tr>"
              + "<tr><td align=\"right\">"
              + "Free Memory</td><td align=\"right\">"
              + freeMemoryBeforeGC
              + "</td></tr>"
              + "<tr><td align=\"right\">"
              + "Used Memory</td><td align=\"right\">"
              + (totalMemory - freeMemoryBeforeGC)
              + "</td></tr>"
              + "<tr><td colspan=\"2\" align=\"left\">Statistics after GC</td></tr>"
              + "<tr><td align=\"right\">"
              + "Max Memory</td><td align=\"right\">"
              + maxMemoryAfterGC
              + "</td></tr>"
              + "<tr><td align=\"right\">"
              + "Free Memory</td><td align=\"right\">"
              + freeMemoryAfterGC
              + "</td></tr>"
              + "<tr><td align=\"right\">"
              + "Used Memory</td><td align=\"right\">"
              + (totalMemory - freeMemoryAfterGC)
              + "</td></tr>"
              + "<tr><td align=\"right\">"
              + "Total Time in GC</td><td align=\"right\">"
              + Float.toString((endTime - startTime) / 1000)
              + "s</td></tr>"
              + "</table>"
              + "</body></html>");
    } catch (Exception e) {
      Log.error(e, "ExplicitGC.doGet(...): general exception caught");
      res.sendError(500, e.toString());
    }
  }
 private void handleUpdateFeedListPost(Request request, HttpServletResponse httpServletResponse)
     throws Exception {
   LOG.info("updating feed list"); // ttt2 implement
   httpServletResponse.sendRedirect(PATH_FEED_ADMIN);
 }
  private void handleLoginPost(
      Request request, HttpServletResponse httpServletResponse, boolean secured) throws Exception {
    String userId = request.getParameter(PARAM_USER_ID);
    String password = request.getParameter(PARAM_PASSWORD);
    String rememberAccountStr = request.getParameter(PARAM_REMEMBER_ACCOUNT);
    boolean rememberAccount = Boolean.parseBoolean(rememberAccountStr);
    LoginInfo.SessionInfo sessionInfo = UserHelpers.getSessionInfo(request);

    logOut(sessionInfo.browserId);

    User user = userDb.get(userId);
    if (user == null) {
      WebUtils.redirectToError("User " + userId + " not found", request, httpServletResponse);
      return;
    }

    if (!user.checkPassword(password)) {
      WebUtils.redirectToError("Invalid password", request, httpServletResponse);
      return;
    }

    if (!user.active) {
      WebUtils.redirectToError(
          "Account for User " + userId + " needs to be activated", request, httpServletResponse);
      return;
    }

    LOG.info("Logged in user " + userId);

    sessionInfo.sessionId = null;
    if (sessionInfo.browserId == null) {
      sessionInfo.browserId = getRandomId();
    } else {
      for (LoginInfo loginInfo : loginInfoDb.getLoginsForBrowser(sessionInfo.browserId)) {
        if (userId.equals(loginInfo.userId)) {
          sessionInfo.sessionId = loginInfo.sessionId;
          break;
        }
      }
    }

    long expireOn = System.currentTimeMillis() + Config.getConfig().loginExpireInterval;
    if (sessionInfo.sessionId == null) {
      sessionInfo.sessionId = getRandomId();
      Config config = Config.getConfig();
      loginInfoDb.add(
          new LoginInfo(
              sessionInfo.browserId,
              sessionInfo.sessionId,
              userId,
              expireOn,
              rememberAccount,
              config.defaultStyle,
              config.defaultItemsPerPage,
              config.defaultFeedDateFormat));
      LOG.info(String.format("Logging in in a new session. User: %s", user));
    } else {
      loginInfoDb.updateExpireTime(sessionInfo.browserId, sessionInfo.sessionId, expireOn);
      LOG.info(String.format("Logging in in an existing session. User: %s", user));
    }

    WebUtils.saveCookies(
        httpServletResponse, secured, sessionInfo.browserId, sessionInfo.sessionId);

    httpServletResponse.sendRedirect("/");
  }
Exemple #29
0
  private static Interpreter getInterpreter(String contextId) throws EvalError {
    // Get the appropriate interpreter
    Interpreter i = null;
    boolean createdInterp = false;
    synchronized (interpreters) { // serialize two gets of the same name
      i = interpreters.get(contextId);
      if (i == null) {
        i = new Interpreter();
        interpreters.put(contextId, i);
        createdInterp = true;
      }
    }
    if (createdInterp) {
      Log.log("Created context: " + contextId + " (" + i + ")");

      // Now configure stdin and stdout to capture 10k of content
      // Store references to the circular buffers within the interpreter itself.
      // This provides a nice place to store them plus theoretically allows
      // advanced use from within the bsh environment.
      // On Windows print() outputs \r\n but in XQuery that's normalized to \n
      // so the 10k of Java buffer may produce less than 10k of content in XQuery!
      OutputStream circularOutput = new CircularByteArrayOutputStream(10240);
      PrintStream printOutput = new PrintStream(circularOutput);
      i.setOut(printOutput);
      i.set("mljamout", circularOutput);

      OutputStream circularError = new CircularByteArrayOutputStream(10240);
      PrintStream printError = new PrintStream(circularError);
      i.setErr(printError);
      i.set("mljamerr", circularError);

      // Capture the built-in System.out and System.err also.
      // (Commented out since System appears global, can't do per interpreter.)
      // i.set("mljamprintout", printOutput);
      // i.set("mljamprinterr", printError);
      // i.eval("System.setOut(mljamprintout);");
      // i.eval("System.setErr(mljamprinterr);");

      // Need to expose hexdecode() and base64decode() built-in functions
      i.eval("hexdecode(String s) { return com.xqdev.jam.MLJAM.hexDecode(s); }");
      i.eval("base64decode(String s) { return com.xqdev.jam.MLJAM.base64Decode(s); }");

      // Let's tell the context what its id is
      i.set("mljamid", contextId);
    }

    // Update the last accessed time, used for cleaning
    i.set("mljamlast", System.currentTimeMillis());

    // If it's been long enough, go snooping for stale contexts
    if (System.currentTimeMillis() > lastClean + CLEAN_INTERVAL) {
      Log.log("Initiated periodic scan for stale context objects");
      lastClean = System.currentTimeMillis();
      Iterator<Interpreter> itr = interpreters.values().iterator();
      while (itr.hasNext()) {
        Interpreter interp = itr.next();
        Long last = (Long) interp.get("mljamlast");
        if (System.currentTimeMillis() > last + STALE_TIMEOUT) {
          itr.remove();
          Log.log("Staled context: " + interp.get("mljamid") + " (" + interp + ")");
        } else if ((System.currentTimeMillis() > last + TEMP_STALE_TIMEOUT)
            && ("" + interp.get("mljamid")).startsWith("temp:")) {
          itr.remove();
          Log.log("Staled temp context: " + interp.get("mljamid") + " (" + interp + ")");
        }
      }
    }

    return i;
  }
  @Override
  public void doHandle(
      String target,
      Request request,
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse)
      throws IOException, ServletException {

    LOG.info("handling " + target);

    // !!! doHandle() is called twice for a request when using redirectiion, first time with
    // request.getPathInfo()
    // set to the URI and target set to the path, then with request.getPathInfo() set to null and
    // target set to the .jsp
    try {
      // request.setHandled(true);
      boolean secured;
      if (request.getScheme().equals("https")) {
        secured = true;
      } else if (request.getScheme().equals("http")) {
        secured = false;
      } else {
        httpServletResponse
            .getWriter()
            .println(
                String.format(
                    "<h1>Unknown scheme %s at %s</h1>",
                    request.getScheme(), request.getUri().getDecodedPath()));
        return;
      }

      if (request.getMethod().equals("GET")) {
        if (isInJar || target.endsWith(".jsp")) {
          // !!! when not in jar there's no need to do anything about params if it's not a .jsp,
          // as this will get called again for the corresponding .jsp
          if (prepareForJspGet(target, request, httpServletResponse, secured)) {
            return;
          }
        }
        if (target.startsWith(PATH_OPEN_ARTICLE)) {
          handleOpenArticle(request, httpServletResponse, target);
          return;
        }
        super.doHandle(target, request, httpServletRequest, httpServletResponse);
        LOG.info("handling of " + target + " went to super");

        // httpServletResponse.setDateHeader("Date", System.currentTimeMillis());     //ttt2 review
        // these, probably not use
        // httpServletResponse.setDateHeader("Expires", System.currentTimeMillis() + 60000);

        return;
      }

      if (request.getMethod().equals("POST")) {
        if (request.getUri().getDecodedPath().equals(PATH_LOGIN)) {
          handleLoginPost(request, httpServletResponse, secured);
        } else if (request.getUri().getDecodedPath().equals(PATH_SIGNUP)) {
          handleSignupPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_CHANGE_PASSWORD)) {
          handleChangePasswordPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_UPDATE_FEED_LIST)) {
          handleUpdateFeedListPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_ADD_FEED)) {
          handleAddFeedPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_REMOVE_FEED)) {
          handleRemoveFeedPost(request, httpServletResponse);
        } else if (request.getUri().getDecodedPath().equals(PATH_CHANGE_SETTINGS)) {
          handleChangeSettingsPost(request, httpServletResponse);
        }
      }

      /*{ // for tests only;
          httpServletResponse.getWriter().println(String.format("<h1>Unable to process request %s</h1>",
                  request.getUri().getDecodedPath()));
          request.setHandled(true);
      }*/
    } catch (Exception e) {
      LOG.error("Error processing request", e);
      try {
        // redirectToError(e.toString(), request, httpServletResponse); //!!! redirectToError leads
        // to infinite loop, probably related to
        // the fact that we get 2 calls for a regular request when redirecting
        httpServletResponse
            .getWriter()
            .println(
                String.format(
                    "<h1>Unable to process request %s</h1>", // ttt1 generate some HTML
                    request.getUri().getDecodedPath()));
        request.setHandled(true);
      } catch (Exception e1) {
        LOG.error("Error redirecting", e1);
      }
    }
  }