Exemplo n.º 1
1
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    HttpSession session = request.getSession();
    PrintWriter out = response.getWriter();
    StringBuilder sb = new StringBuilder();

    HashMap<String, String> userInfo = (HashMap<String, String>) session.getAttribute("userInfo");
    String ticket = request.getParameter("ticket");

    if (userInfo == null) {
      response.sendRedirect(response.encodeRedirectUrl(request.getContextPath() + "/SignIn"));
    } else {
      if (userInfo.get("role").equals("technician")) {
        sb.append(LayoutProvider.getInstance().getLoggedInHeader(userInfo.get("name")));
        sb.append("<div id=\"body\">");
        sb.append(
            "<h3>Schedule Confirmation</h3><p>You have scheduled <strong>ticket # "
                + ticket
                + "</strong></p>");
        if (ticket != null) {
          List<String> tickets;
          try {
            if (userInfo.get("tickets").equals("")) {
              tickets = null;
            } else {
              tickets = Arrays.asList(userInfo.get("tickets").split("\\,"));
            }
          } catch (Exception ex) {
            System.out.println("PayBill: error splitting tickets");
            tickets = null;
          }
          String remaining = "";
          if (tickets != null && tickets.size() > 0) {
            for (String t : tickets) {
              if (!t.equals(ticket)) {
                remaining += t + ",";
              }
            }
            if (remaining.length() > 0) remaining = remaining.substring(0, remaining.length() - 1);
          } else {
            remaining = "";
          }
          userInfo.put("tickets", remaining);
        }
        sb.append("</div>");
      } else {
        sb.append("<h2>Error</h2>");
        sb.append("<p>You do not have access to this page.</p>");
        sb.append("</div>");
      }
    }
    out.println(sb.toString());
    out.close();
  }
Exemplo n.º 2
0
 // Get cookies string from HTTP request object
 private String getCookiesFromRequest(HttpServletRequest request) {
   Cookie cookies[] = CookieUtils.getCookieArrayFromReq(request);
   // above call would return pure sid in iPlanetDirectoryPro cookie
   // independent of container encoding
   StringBuilder cookieStr = null;
   String strCookies = null;
   if (cookies != null) {
     for (int nCookie = 0; nCookie < cookies.length; nCookie++) {
       String cookieName = cookies[nCookie].getName();
       String cookieVal = cookies[nCookie].getValue();
       if (cookieName.equals(CookieUtils.getAmCookieName()) && cookieEncoding) {
         cookieVal = URLEncDec.encode(cookieVal);
       }
       if (debug.messageEnabled()) {
         debug.message("CDCClientServlet.getCookiesFromRequest:" + "Cookie name = " + cookieName);
         debug.message("CDCClientServlet.getCookiesFromRequest:" + "Cookie val= " + cookieVal);
       }
       if (cookieStr == null) {
         cookieStr = new StringBuilder();
       } else {
         cookieStr.append(SEMI_COLON).append(SPACE);
       }
       cookieStr.append(cookieName).append(EQUAL_TO).append(cookieVal);
     }
   }
   if (cookieStr != null) {
     strCookies = cookieStr.toString();
   }
   return strCookies;
 }
 private void addAttribute(StringBuilder sb, String attributeName, Object attributeValue) {
   sb.append(" ");
   sb.append(attributeName);
   sb.append("=\"");
   sb.append(attributeValue);
   sb.append("\"");
 }
Exemplo n.º 4
0
  /**
   * Constructor.
   *
   * @param rq request
   * @param rs response
   * @throws IOException I/O exception
   */
  public HTTPContext(final HttpServletRequest rq, final HttpServletResponse rs) throws IOException {

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

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

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

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

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

    // set session-specific credentials
    final String auth = req.getHeader(AUTHORIZATION);
    if (auth != null) {
      final String[] values = auth.split(" ");
      if (values[0].equals(BASIC)) {
        final String[] cred = Base64.decode(values[1]).split(":", 2);
        if (cred.length != 2) throw new LoginException(NOPASSWD);
        user = cred[0];
        pass = cred[1];
      } else {
        throw new LoginException(WHICHAUTH, values[0]);
      }
    }
  }
Exemplo n.º 5
0
  /**
   * Gathers the parameters in the request as a HTTP URL string. to form request parameters and
   * policy advice String array. It collects all the parameters from the original request except the
   * original goto url and any advice parameters. Note: All the paramters will be url decoded by
   * default., we should make sure that these values are encoded again
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @return An String array, index 0 is policy advice, index 1 is rest of the request parameters
   */
  private String[] parseRequestParams(HttpServletRequest request) {
    StringBuilder adviceList = null;
    StringBuilder parameterString = new StringBuilder(100);
    for (Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) {
      String paramName = (String) e.nextElement();
      if (adviceParams.contains(paramName.toLowerCase())) {
        if (adviceList == null) {
          adviceList = new StringBuilder();
        } else {
          adviceList.append(AMPERSAND);
        }
        String[] values = request.getParameterValues(paramName);
        for (int i = 0; values != null && i < values.length; i++) {
          adviceList.append(paramName).append(EQUAL_TO).append(values[i]);
        }
      } else {
        if (!paramName.equals(GOTO_PARAMETER)) {
          String[] values = request.getParameterValues(paramName);
          for (int i = 0; values != null && i < values.length; i++) {
            parameterString
                .append(AMPERSAND)
                .append(paramName)
                .append(EQUAL_TO)
                .append(URLEncDec.encode(values[i]));
          }
        }
      }
    }
    if (debug.messageEnabled()) {
      debug.message("CDCClientServlet.parseRequestParams:" + "Advice List is = " + adviceList);
      debug.message(
          "CDCClientServlet.parseRequestParams:"
              + "Parameter String is = "
              + parameterString.toString());
    }

    String policyAdviceList;
    String requestParams;

    if (adviceList == null) {
      policyAdviceList = null;
    } else {
      policyAdviceList = adviceList.toString();
    }

    if (parameterString.length() > 0) {
      requestParams = (parameterString.deleteCharAt(0).toString());
    } else {
      requestParams = parameterString.toString();
    }

    return new String[] {policyAdviceList, requestParams};
  }
Exemplo n.º 6
0
  private void handleSignupPost(Request request, HttpServletResponse httpServletResponse)
      throws Exception {
    String userId = request.getParameter(PARAM_USER_ID);
    String userName = request.getParameter(PARAM_USER_NAME);
    String email = request.getParameter(PARAM_EMAIL);
    String stringPassword = request.getParameter(PARAM_PASSWORD);
    String stringPasswordConfirm = request.getParameter(PARAM_PASSWORD_CONFIRM);

    if (!stringPassword.equals(stringPasswordConfirm)) {
      WebUtils.redirectToError(
          "Mismatch between password and password confirmation", request, httpServletResponse);
      return;
    }

    SecureRandom secureRandom = new SecureRandom();
    String salt = "" + secureRandom.nextLong();
    byte[] password = User.computeHashedPassword(stringPassword, salt);
    User user = userDb.get(userId);
    if (user != null) {
      WebUtils.redirectToError(
          "There already exists a user with the ID " + userId, request, httpServletResponse);
      return;
    }

    user =
        new User(
            userId,
            userName,
            password,
            salt,
            email,
            new ArrayList<String>(),
            Config.getConfig().activateAccountsAtCreation,
            false);
    // ttt2 add confirmation by email, captcha, ...
    List<String> fieldErrors = user.checkFields();
    if (!fieldErrors.isEmpty()) {
      StringBuilder bld =
          new StringBuilder("Invalid values when trying to create user with ID ")
              .append(userId)
              .append("<br/>");
      for (String s : fieldErrors) {
        bld.append(s).append("<br/>");
      }
      WebUtils.redirectToError(bld.toString(), request, httpServletResponse);
      return;
    }

    // ttt2 2 clients can add the same userId simultaneously
    userDb.add(user);

    httpServletResponse.sendRedirect("/");
  }
 public String toXML() {
   StringBuilder sb = new StringBuilder("<httpSample");
   addAttribute(sb, "t", elapsedTime);
   addAttribute(sb, "lt", latency);
   addAttribute(sb, "ts", requestTimeStamp);
   addAttribute(sb, "s", success);
   addAttribute(sb, "lb", label);
   addAttribute(sb, "rc", returnCode);
   addAttribute(sb, "rm", returnMessage);
   addAttribute(sb, "tn", sampleName);
   addAttribute(sb, "dt", dataType);
   addAttribute(sb, "by", responseContentLength);
   sb.append(" />");
   return sb.toString();
 }
Exemplo n.º 8
0
 public static String showRequestHeaders(HttpServletRequest req) {
   StringBuilder sbuff = new StringBuilder();
   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");
       }
     }
   }
   return sbuff.toString();
 }
Exemplo n.º 9
0
 private String getAuthorizeUrl() {
   StringBuilder url = new StringBuilder();
   url.append(this.service_.getAuthorizationEndpoint());
   boolean hasQuery = url.toString().indexOf('?') != -1;
   url.append(hasQuery ? '&' : '?')
       .append("client_id=")
       .append(Utils.urlEncode(this.service_.getClientId()))
       .append("&redirect_uri=")
       .append(Utils.urlEncode(this.service_.getGenerateRedirectEndpoint()))
       .append("&scope=")
       .append(Utils.urlEncode(this.scope_))
       .append("&response_type=code")
       .append("&state=")
       .append(Utils.urlEncode(this.oAuthState_));
   return url.toString();
 }
  /**
   * A more elegant string representing all users that this bookmark "belongs" to.
   *
   * @return the string.
   */
  public String getCommaDelimitedList(Collection<String> strings) {
    StringBuilder buf = new StringBuilder();
    for (String string : strings) {
      buf.append(string);
      buf.append(",");
    }

    String returnStr = buf.toString();
    if (returnStr.endsWith(",")) {
      returnStr = returnStr.substring(0, returnStr.length() - 1);
    }

    if (!SparkUtil.hasLength(returnStr)) {
      returnStr = "&nbsp;";
    }
    return returnStr;
  }
Exemplo n.º 11
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    // Actual logic goes here.

    // System.out.print("Test");

    StringBuilder sb = new StringBuilder();
    try (BufferedReader reader = request.getReader()) {
      String line;
      while ((line = reader.readLine()) != null) {
        sb.append(line).append('\n');
      }
    }

    try {
      JSONObject jsonObject = new JSONObject(sb.toString());

      JSONObject message = jsonObject.getJSONObject("message");
      String command = message.getString("text");
      if (BotHelper.command(command, "/echo")) {
        functions.echo(jsonObject);
      } else if (BotHelper.command(command, "/engage")) {
        functions.engage(jsonObject);
      } else if (BotHelper.command(command, "/debug")) {
        functions.debugjson(jsonObject);
      } else if (BotHelper.command(command, "/amazon")) {
        functions.searchAmazon(jsonObject);
      } else if (BotHelper.command(command, "/decide")) {
        functions.decide(jsonObject);
      } else if (BotHelper.command(command, "/ohkadsewasessenwirheute")) {
        functions.ohkadsewasessenwirheute(jsonObject);
      } else if (BotHelper.command(command, "/ohmagischekadse")) {
        functions.ohmagischekadse(jsonObject);
      } else if (BotHelper.command(command, "/otherchat")) {
        functions.otherChat(jsonObject);
      } else if ((BotHelper.command(command, "/help")) || (BotHelper.command(command, "/?"))) {
        functions.help(jsonObject);
      } else {
        functions.unknown(jsonObject);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 @SuppressWarnings("unchecked")
 private String getRequestLabel(HttpServletRequest request) {
   StringBuilder sb = new StringBuilder();
   sb.append(request.getServletPath().substring(1));
   String methodToCall = request.getParameter("methodToCall");
   if (methodToCall != null) {
     addMethodToCall(sb, methodToCall);
   } else {
     Enumeration<String> nameEnum = request.getParameterNames();
     while (nameEnum.hasMoreElements()) {
       String parmName = nameEnum.nextElement();
       if (parmName.startsWith("methodToCall.")) {
         addMethodToCall(sb, parmName.substring("methodToCall.".length()));
         break;
       }
     }
   }
   return sb.toString();
 }
Exemplo n.º 13
0
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   PrintWriter out = response.getWriter();
   StringBuilder sb = new StringBuilder();
   sb.append("<html>");
   sb.append("<body>");
   sb.append("<h1>Hi! Click the button below to turn on the server!</h1>");
   sb.append("<form ACTION=\"/wake/perform\" METHOD=\"POST\">");
   sb.append("<input name=\"send\"  type=\"submit\"  value=\"Wake Server\" />");
   sb.append("</form>");
   sb.append("</body>");
   sb.append("</html>");
   out.println(sb.toString());
 }
Exemplo n.º 14
0
 void requestToken(String authorizationCode) {
   try {
     String url = this.service_.getTokenEndpoint();
     StringBuilder ss = new StringBuilder();
     ss.append("grant_type=authorization_code")
         .append("&client_id=")
         .append(Utils.urlEncode(this.service_.getClientId()))
         .append("&client_secret=")
         .append(Utils.urlEncode(this.service_.getClientSecret()))
         .append("&redirect_uri=")
         .append(Utils.urlEncode(this.service_.getGenerateRedirectEndpoint()))
         .append("&code=")
         .append(authorizationCode);
     HttpClient client = new HttpClient(this);
     client.setTimeout(15);
     client
         .done()
         .addListener(
             this,
             new Signal2.Listener<Exception, HttpMessage>() {
               public void trigger(Exception event1, HttpMessage event2) {
                 OAuthProcess.this.handleToken(event1, event2);
               }
             });
     Method m = this.service_.getTokenRequestMethod();
     if (m == Method.Get) {
       boolean hasQuery = url.indexOf('?') != -1;
       url += (hasQuery ? '&' : '?') + ss.toString();
       client.get(url);
     } else {
       HttpMessage post = new HttpMessage();
       post.setHeader("Content-Type", "application/x-www-form-urlencoded");
       post.addBodyText(ss.toString());
       client.post(url, post);
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 15
0
  /**
   * Constructor.
   *
   * @param rq request
   * @param rs response
   * @param servlet calling servlet instance
   * @throws IOException I/O exception
   */
  public HTTPContext(
      final HttpServletRequest rq, final HttpServletResponse rs, final BaseXServlet servlet)
      throws IOException {

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

    method = rq.getMethod();

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

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

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

    // overwrite credentials with session-specific data
    final String auth = req.getHeader(AUTHORIZATION);
    if (auth != null) {
      final String[] values = auth.split(" ");
      if (values[0].equals(BASIC)) {
        final String[] cred = org.basex.util.Base64.decode(values[1]).split(":", 2);
        if (cred.length != 2) throw new LoginException(NOPASSWD);
        user = cred[0];
        pass = cred[1];
      } else {
        throw new LoginException(WHICHAUTH, values[0]);
      }
    }
  }
Exemplo n.º 16
0
 String srvUrlStem(String host) {
   if (host == null) {
     return null;
   }
   StringBuilder sb = new StringBuilder();
   sb.append(reqURL.getProtocol());
   sb.append("://");
   sb.append(host);
   sb.append(':');
   sb.append(reqURL.getPort());
   return sb.toString();
 }
Exemplo n.º 17
0
  /** @throws IOException If failed. */
  private void initDefaultPage() throws IOException {
    assert dfltPage == null;

    InputStream in = getClass().getResourceAsStream("rest.html");

    if (in != null) {
      LineNumberReader rdr = new LineNumberReader(new InputStreamReader(in));

      try {
        StringBuilder buf = new StringBuilder(2048);

        for (String line = rdr.readLine(); line != null; line = rdr.readLine()) {
          buf.append(line);

          if (!line.endsWith(" ")) buf.append(" ");
        }

        dfltPage = buf.toString();
      } finally {
        U.closeQuiet(rdr);
      }
    }
  }
Exemplo n.º 18
0
 /**
  * Connects an implementation to start an authentication process to a signal.
  *
  * <p>If JavaScript is available, this method connects a JavaScript function to the <code>signal
  * </code>, otherwise {@link OAuthProcess#startAuthenticate() startAuthenticate()} is connected to
  * <code>signal</code>.
  */
 public void connectStartAuthenticate(AbstractEventSignal s) {
   if (WApplication.getInstance().getEnvironment().hasJavaScript()) {
     StringBuilder js = new StringBuilder();
     js.append("function(object, event) {")
         .append("Wt3_2_3.PopupWindow(Wt3_2_3")
         .append(",")
         .append(WWebWidget.jsStringLiteral(this.getAuthorizeUrl()))
         .append(", ")
         .append(this.service_.getPopupWidth())
         .append(", ")
         .append(this.service_.getPopupHeight())
         .append(");")
         .append("}");
     s.addListener(js.toString());
   }
   s.addListener(
       this,
       new Signal.Listener() {
         public void trigger() {
           OAuthProcess.this.startAuthenticate();
         }
       });
 }
Exemplo n.º 19
0
 private void crawlPluginRegistries() {
   StringBuilder sb = new StringBuilder();
   for (ArchivalUnit au : pluginMgr.getAllRegistryAus()) {
     sb.append(au.getName());
     sb.append(": ");
     try {
       startCrawl(au, true, false);
       sb.append("Queued.");
     } catch (CrawlManagerImpl.NotEligibleException e) {
       sb.append("Failed: ");
       sb.append(e.getMessage());
     }
     sb.append("\n");
   }
   statusMsg = sb.toString();
 }
Exemplo n.º 20
0
 /**
  * Replace occurrences of "%ab" with the character represented by the hex value. Strings of
  * escaped characters are treated as UTF-8 byte sequences and decoded appropriately.
  */
 private static String decode(String s) {
   int length = s.length();
   StringBuilder str = new StringBuilder(length);
   Matcher matcher = PATTERN.matcher(s);
   int offset = 0;
   byte[] bb = null;
   while (matcher.find(offset)) {
     int count = matcher.groupCount();
     for (int i = 0; i < count; i++) {
       String match = matcher.group(0);
       int num = match.length() / 3;
       if (bb == null || bb.length < num) {
         bb = new byte[num];
       }
       for (int j = 0; j < num; j++) {
         int head = j * 3 + 1;
         int tail = head + 2;
         bb[j] = (byte) Integer.parseInt(match.substring(head, tail), 16);
       }
       try {
         String text = new String(bb, "UTF-8");
         str.append(s.substring(offset, matcher.start()));
         str.append(text);
       } catch (UnsupportedEncodingException e) {
         // NOTE: This should *never* be thrown because all
         //       JVMs are required to support UTF-8. I mean,
         //       the strings in the .class file are all in
         //       a modified UTF-8, for pete's sake! :)
       }
     }
     offset = matcher.end();
   }
   if (offset < length) {
     str.append(s.substring(offset));
   }
   return str.toString();
 }
Exemplo n.º 21
0
  public String toString() {
    StringBuilder sb = new StringBuilder();

    sb.append(getClass().getSimpleName());
    sb.append("[");
    sb.append(_contextUri);

    if (_queryString != null) sb.append("?").append(_queryString);

    sb.append("]");

    return sb.toString();
  }
Exemplo n.º 22
0
 // !!! IDEA reports this as unused, but it is called from JSP
 public static String getStyle(LoginInfo loginInfo) {
   StringBuilder bld = new StringBuilder();
   bld.append("<style media=\"screen\" type=\"text/css\">\n\n");
   if (loginInfo == null) {
     bld.append(Config.getConfig().defaultStyle);
   } else {
     bld.append(loginInfo.style); // ttt3 detect broken styles and return default
   }
   bld.append("</style>\n");
   return bld.toString();
 }
Exemplo n.º 23
0
  public static String showSecurity(HttpServletRequest req, String role) {
    StringBuilder sbuff = new StringBuilder();

    sbuff.append("Security Info\n");
    sbuff.append(" req.getRemoteUser(): ").append(req.getRemoteUser()).append("\n");
    sbuff.append(" req.getUserPrincipal(): ").append(req.getUserPrincipal()).append("\n");
    sbuff
        .append(" req.isUserInRole(")
        .append(role)
        .append("):")
        .append(req.isUserInRole(role))
        .append("\n");
    sbuff.append(" ------------------\n");

    return sbuff.toString();
  }
Exemplo n.º 24
0
 /**
  * Construct servlet URL, with params as necessary. Avoid generating a hostname different from
  * that used in the original request, or browsers will prompt again for login
  */
 String srvURLFromStem(String stem, ServletDescr d, String params) {
   if (d.isPathIsUrl()) {
     return d.getPath();
   }
   StringBuilder sb = new StringBuilder(80);
   if (stem != null) {
     sb.append(stem);
     if (stem.charAt(stem.length() - 1) != '/') {
       sb.append('/');
     }
   } else {
     // ensure absolute path even if no scheme/host/port
     sb.append('/');
   }
   sb.append(d.getPath());
   if (params != null) {
     sb.append('?');
     sb.append(params);
   }
   return sb.toString();
 }
Exemplo n.º 25
0
  @Nullable
  public String getMapping() {
    final StringBuilder sb = new StringBuilder();

    for (Map.Entry<Pattern, ScopeMapping> patternAndMapping : _patternToMapping.entrySet()) {
      if (patternAndMapping.getKey() != null) {
        if (sb.length() > 0) {
          sb.append(",\n");
        }
        sb.append(patternAndMapping.getKey())
            .append('>')
            .append(patternAndMapping.getValue().getDefaultName());
      }
    }

    return sb.length() > 0 ? sb.toString() : null;
  }
Exemplo n.º 26
0
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    String longAddr = null, shortAddr, s, transactionKey = null;
    int count;
    boolean ignorable = false;

    synchronized (simultaneousRequestsByShortIPAddr) {
      if (totalSimultaneousRequests >= maxTotalSimultaneousRequests) {
        log.error(
            "This system has exceeded the maxTotalSimultaneousRequests limit of "
                + maxTotalSimultaneousRequests);
        log.error(simultaneousRequestsByShortIPAddr);
        for (String str : simultaneousRequests) log.error(str);
        ((HttpServletResponse) response).setStatus(HttpURLConnection.HTTP_UNAVAILABLE);
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        writer.println("<html><body><h1>Service Temporarily Unavailable</h1>");
        writer.println(
            "The system is experiencing a severe load and is temporarily unable to accept new requests");
        if (contactInfo != null)
          writer.println("<p>Contact " + contactInfo + " for more information</p>");
        writer.println("</body></html>");
        writer.close();
        return;
      }
      if (addressInHeader != null) {
        @SuppressWarnings("unchecked")
        Enumeration<String> addrs = ((HttpServletRequest) request).getHeaders(addressInHeader);
        while (addrs.hasMoreElements()) {
          longAddr = addrs.nextElement();
          if (longAddr == null) {
            if (++addressInHeaderErrorCount < 10)
              log.error("Expected a " + addressInHeader + " header but got null");
            continue;
          }
          if (longAddr.lastIndexOf('.') >= 0) break;
        }
      }
      if (longAddr == null) longAddr = request.getRemoteAddr();
      int i = longAddr.lastIndexOf('.');
      if (i < 0) {
        log.error("bogus IP address: '" + longAddr + "'");
        longAddr = "0.0.0.0";
      }
      shortAddr = longAddr.substring(0, i); // trim off 4th number group
      // that lets us spot requests from clusters
      s = equivalentAddresses.get(shortAddr); // map one short addr to another?
      if (s != null) shortAddr = s;
      if (ignorableAddresses.contains(shortAddr)) {
        ignorable = true;
      } else {
        Integer icount = simultaneousRequestsByShortIPAddr.get(shortAddr);
        if (icount != null) count = icount;
        else count = 0;

        int maxSimultaneousRequests =
            (maxTotalSimultaneousRequests - totalSimultaneousRequests) / 4;
        if (maxSimultaneousRequests == 0) maxSimultaneousRequests = 1;
        if (count >= maxSimultaneousRequests) {
          log.error(
              "IP addr "
                  + shortAddr
                  + ".* has exceeded "
                  + maxSimultaneousRequests
                  + " simultaneous requests!");
          log.error("maxTotalSimultaneousRequests=" + maxTotalSimultaneousRequests);
          log.error("totalSimultaneousRequests=" + totalSimultaneousRequests);
          for (String str : simultaneousRequests) log.error(str);
          //
          // ((HttpServletResponse)response).setStatus(HttpURLConnection.HTTP_TOO_MANY_REQUESTS); //
          // someday
          ((HttpServletResponse) response).setStatus(429); // too many requests
          response.setContentType("text/html");
          PrintWriter writer = response.getWriter();
          writer.println(
              "<html><head><title>Too Many Requests</title></head><body><h1>Too Many Requests</h1>");
          writer.println(
              "You have exceeded the maximum simultaneous request value of "
                  + maxSimultaneousRequests);
          writer.println("<p>This message and your IP address have been logged and reported</p>");
          if (contactInfo != null)
            writer.println("<p>Contact " + contactInfo + " for more information</p>");
          writer.println("</body></html>");
          writer.close();
          return;
        }
        simultaneousRequestsByShortIPAddr.put(shortAddr, count + 1);
        icount = totalRequests.get(shortAddr);
        if (icount != null) count = icount;
        else count = 0;
        totalRequests.put(shortAddr, count + 1);
        totalSimultaneousRequests++;
        transactionKey =
            new StringBuilder((new Date(System.currentTimeMillis())).toString())
                .append('|')
                .append(shortAddr)
                .append('|')
                .append(((HttpServletRequest) request).getQueryString())
                .toString();
        simultaneousRequests.add(transactionKey);
      }
    }

    try {
      HttpServletResponseWrapper wrapper =
          new HttpServletResponseWrapper((HttpServletResponse) response);
      chain.doFilter(request, wrapper);
    } finally {
      if (!ignorable)
        synchronized (simultaneousRequestsByShortIPAddr) {
          totalSimultaneousRequests--;
          simultaneousRequests.remove(transactionKey);
          count = simultaneousRequestsByShortIPAddr.get(shortAddr);
          if (count == 1) // prune them from the table
          simultaneousRequestsByShortIPAddr.remove(shortAddr);
          else simultaneousRequestsByShortIPAddr.put(shortAddr, count - 1);
        }
    }

    Calendar c = new GregorianCalendar();
    int hour = c.get(Calendar.HOUR_OF_DAY);
    if (hour == 0 && nextReportingHour == 24) { // new day!
      // you could reset your daily limits table here
      nextReportingHour = 0;
    }

    if (hour >= nextReportingHour) { // generate the hourly report
      // you could reset your hourly limits table here
      nextReportingHour = hour + 1;

      if (log.isInfoEnabled()) {
        HashMap<String, Integer> map = new LinkedHashMap<String, Integer>();
        List<String> yourMapKeys = new ArrayList<String>(totalRequests.keySet());
        List<Integer> yourMapValues = new ArrayList<Integer>(totalRequests.values());
        TreeSet<Integer> sortedSet = new TreeSet<Integer>(yourMapValues);
        Integer[] sortedArray = sortedSet.descendingSet().toArray(new Integer[0]);
        int size = sortedArray.length;

        for (int i = 0; i < size; i++)
          map.put(yourMapKeys.get(yourMapValues.indexOf(sortedArray[i])), sortedArray[i]);
        Iterator<String> it = map.keySet().iterator();
        String key;
        StringBuilder sb = new StringBuilder("Top 10 users in the last hour");
        for (int i = 0; i < 10 && it.hasNext(); i++) {
          key = it.next();
          sb.append("\n    ").append(key).append(" : ").append(map.get(key));
        }
        log.info(sb);
      }
      totalRequests.clear();
    }
  }
  @Override
  protected boolean checkEnforce(ServletContext context) throws IOException {
    /*
     * Rely on the SolrResourceLoader to locate the solr home directory.
     */

    int httpsPort = getHttpsPort();

    if (httpsPort > -1) {
      setHttpsPort(httpsPort);
    }

    String solrHome = SolrResourceLoader.locateSolrHome();

    if (logger.isDebugEnabled()) {
      logger.debug("solrHome:" + solrHome);
    }

    /*
     * Find the active cores.
     */
    List<File> cores = new ArrayList();
    findCores(new File(solrHome), cores);

    /*
     * Get the alfresco.secureComms value for each core.
     */
    Set<String> secureCommsSet = new HashSet();
    for (File core : cores) {
      collectSecureComms(core, secureCommsSet);
    }

    /*
     * alfresco.secureComms values should be in sync for each core
     */

    if (secureCommsSet.size() > 1) {
      StringBuilder buf = new StringBuilder();
      int i = 0;
      for (String s : secureCommsSet) {
        if (i > 0) {
          buf.append(" | ");
        }
        buf.append(s);
        i++;
      }

      throw new IOException(
          "More then one distinct value found for alfresco.secureComms:"
              + buf.toString()
              + ". All alfresco.secureComms values must be set to the same value.");
    }

    if (secureCommsSet.size() == 0) {
      // No secureComms were found.
      return false;
    }

    String secureComms = secureCommsSet.iterator().next();

    if (logger.isDebugEnabled()) {
      logger.debug("secureComms:" + secureComms);
    }

    if ("none".equals(secureComms)) {
      return false;
    } else {
      return true;
    }
  }
Exemplo n.º 28
0
  public StringBuilder listToCSV(List list) {
    StringBuilder csv = new StringBuilder();
    csv.append(
        "Work Product,,Name,State,Owner,Plan Estimate,Task Estimate,Task Remaining,Time Spent\n");

    for (int i = 0; i < list.size(); i++) {
      Map map = (Map) list.get(i);
      String type = (String) map.get("type");
      String formattedId = (String) map.get("formattedId");
      String name = (String) map.get("name");
      String taskStatus = (String) map.get("taskStatus");
      String owner = (String) map.get("owner");
      String planEstimate = (String) map.get("planEstimate");
      String taskEstimateTotal = (String) map.get("taskEstimateTotal");
      String taskRemainingTotal = (String) map.get("taskRemainingTotal");
      String taskTimeSpentTotal = (String) map.get("taskTimeSpentTotal");

      if ("task".equals(type)) {
        csv.append("," + formattedId + ",");
      } else if ("userstory".equals(type)) {
        csv.append(formattedId + ",,");
      } else if ("iteration".equals(type)) {
        csv.append(",,");
      }

      if (planEstimate == null) {
        planEstimate = "";
      }

      if (taskEstimateTotal == null) {
        taskEstimateTotal = "";
      }

      if (taskRemainingTotal == null) {
        taskRemainingTotal = "";
      }

      csv.append("\"" + name + "\",");
      csv.append(taskStatus + ",");
      csv.append(owner + ",");
      csv.append(planEstimate + ",");
      csv.append(taskEstimateTotal + ",");
      csv.append(taskRemainingTotal + ",");
      csv.append(taskTimeSpentTotal + "\n");
    }

    return csv;
  }
Exemplo n.º 29
0
  public StringBuilder listToCSVForUserView(List list) {
    StringBuilder csv = new StringBuilder();

    csv.append(
        "Project,Iteration,Work Product,Name,State,Owner,Task Estimate,Task Remaining,Time Spent\n");

    for (int i = 0; i < list.size(); i++) {
      Map map = (Map) list.get(i);
      String projectName = (String) map.get("projectName");
      String iterationName = (String) map.get("iterationName");
      String formattedId = (String) map.get("taskFormattedId");
      String taskName = (String) map.get("taskName");
      String taskState = (String) map.get("taskState");
      String owner = (String) map.get("owner");
      String taskEstimate = (String) map.get("taskEstimate");
      String taskRemaining = (String) map.get("taskRemaining");
      String taskTimeSpent = (String) map.get("hours");

      if (taskEstimate == null) {
        taskEstimate = "";
      }

      if (taskRemaining == null) {
        taskRemaining = "";
      }

      csv.append("" + projectName + ",");
      csv.append("\"" + iterationName + "\",");
      csv.append(formattedId + ",");
      csv.append(taskName + ",");
      csv.append(taskState + ",");
      csv.append(owner + ",");
      csv.append(taskEstimate + ",");
      csv.append(taskRemaining + ",");
      csv.append(taskTimeSpent + "\n");
    }

    return csv;
  }
 private ByteArrayOutputStream getCsvData(
     JSONArray src, JSONArray store, HttpServletRequest request) throws ServiceException {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   StringBuilder resSB = new StringBuilder();
   JSONObject temp = null;
   int fieldListLength = 0;
   try {
     String header = "";
     temp =
         new JSONObject(
             "{data:[Project Start,Baseline Start,Actual Start,"
                 + "Start Variance,Project Finish,Baseline Finish,Actual Finish,Finish Variance,"
                 + "Scheduled,Baseline,Variance,Remaining,Actual,Scheduled,Baseline,Variance,"
                 + "Remaining,Actual,Scheduled,Baseline,Variance,Remaining,Actual,Percent Complete,"
                 + "Task not yet Started,Task in progress,Task Completed,Parent Tasks, Total Tasks]}");
     JSONArray colHeader = temp.getJSONArray("data");
     temp =
         new JSONObject(
             "{data:[Project Start Date,Baseline Start Date,Project Actual Start Date,"
                 + "Start Variance,Project End Date,Baseline End Date,Project End Date,End Variance,"
                 + "Scheduled Duration,Baseline Duration,Duration Variance,Remaining Duration,"
                 + "Actual Duration,Scheduled Cost,Baseline Cost,Cost Variance,Remaining Cost,Actual Cost,"
                 + "Scheduled Work,Baseline Work,Work Variance,Remaining Work,Actual Work,Percent Complete,"
                 + "Unstarted Tasks,Inprogress Tasks,Completed Tasks,Parent Tasks,Total Tasks]}");
     JSONArray fieldList = temp.getJSONArray("data");
     fieldListLength = fieldList.length();
     for (int i = 0; i < src.length(); i++) {
       colHeader.put(src.getJSONObject(i).getString("type"));
       fieldList.put("count");
     }
     fieldList.put("Total Resources");
     colHeader.put("Total Resources");
     for (int i = 0; i < colHeader.length(); i++) {
       header += "\"" + colHeader.get(i).toString() + "\",";
     }
     header = header.substring(0, (header.length() - 1));
     header += "\n";
     resSB.append(header);
     String dataIndexArrStr[] = new String[fieldList.length()];
     for (int i = 0; i < fieldList.length(); i++) dataIndexArrStr[i] = fieldList.get(i).toString();
     for (int i = 0; i < store.length(); i++) {
       temp = store.getJSONObject(i);
       String dstr = "";
       for (int j = 0; j < fieldListLength; j++)
         dstr += "\"" + temp.getString(dataIndexArrStr[j]) + "\",";
       dstr = dstr.substring(0, (dstr.length() - 1));
       dstr += "\n";
       resSB.append(dstr);
     }
     for (int i = 0; i < src.length(); i++) {
       temp = src.getJSONObject(i);
       String dstr = "";
       dstr += "\"" + temp.getString("count") + "\",";
       dstr = dstr.substring(0, (dstr.length() - 1));
       resSB.append(dstr);
     }
     String dstr = "";
     dstr += "\"" + store.getJSONObject(0).getString("Total Resources") + "\",";
     resSB.append(dstr);
     baos.write(resSB.toString().getBytes());
     baos.close();
   } catch (IOException ex) {
     throw ServiceException.FAILURE("ExportProjectReport.getCsvData", ex);
   } catch (JSONException e) {
     throw ServiceException.FAILURE("ExportProjectReport.getCsvData", e);
   } catch (Exception e) {
     throw ServiceException.FAILURE("ExportProjectReport.getCsvData", e);
   }
   return baos;
 }