public static UIComponent addTransient(
      FacesContext context, ServletRequest req, UIComponent parent, String prevId, Class childClass)
      throws Exception {
    if (context == null) context = FacesContext.getCurrentInstance();

    if (parent == null) {
      UIComponentClassicTagBase parentTag =
          (UIComponentClassicTagBase) req.getAttribute("caucho.jsf.parent");

      parent = parentTag.getComponentInstance();

      BodyContent body = parentTag.getBodyContent();

      if (body != null) addVerbatim(parent, body);
    }

    UIComponent child = null;
    ;

    if (child == null) child = (UIComponent) childClass.newInstance();

    child.setTransient(true);

    addChild(parent, prevId, child);

    return child;
  }
Exemple #2
0
 @Override
 public void doFilter(
     @Nonnull ServletRequest request,
     @Nonnull ServletResponse response,
     @Nonnull FilterChain chain)
     throws IOException, ServletException {
   final StopWatch stopWatch = new StopWatch();
   request.setAttribute(CURRENT_REQUEST_STOP_WATCH_ATTRIBUTE_NAME, stopWatch);
   final ScopeMapping globalMapping = _patternToMapping.get(null);
   final ScopeMapping specificMapping =
       request instanceof HttpServletRequest
           ? getMappingFor(((HttpServletRequest) request).getRequestURI())
           : null;
   try {
     chain.doFilter(request, response);
   } finally {
     request.removeAttribute(CURRENT_REQUEST_STOP_WATCH_ATTRIBUTE_NAME);
     final Duration duration = stopWatch.getCurrentDuration();
     final ServletHealthInterceptor interceptor = _interceptor;
     if (interceptor == null
         || interceptor.isRecordAllowed(request, globalMapping, specificMapping)) {
       globalMapping.record(null, duration);
       if (specificMapping != null) {
         final String targetName =
             interceptor != null
                 ? interceptor.getSpecificTargetName(request, specificMapping)
                 : null;
         specificMapping.record(targetName, duration);
       }
     }
   }
 }
  public static UIComponent addFacet(
      FacesContext context,
      ServletRequest req,
      UIComponent parent,
      String facetName,
      ValueExpression binding,
      Class childClass)
      throws Exception {
    if (context == null) context = FacesContext.getCurrentInstance();

    if (parent == null) {
      UIComponentClassicTagBase parentTag =
          (UIComponentClassicTagBase) req.getAttribute("caucho.jsf.parent");

      parent = parentTag.getComponentInstance();
    }

    UIComponent child = null;

    if (binding != null) child = (UIComponent) binding.getValue(context.getELContext());

    if (child == null) child = (UIComponent) childClass.newInstance();

    if (parent != null) parent.getFacets().put(facetName, child);

    if (binding != null) binding.setValue(context.getELContext(), child);

    return child;
  }
  public static UIComponent addPersistent(
      FacesContext context,
      ServletRequest req,
      UIComponent parent,
      ValueExpression binding,
      Class childClass)
      throws Exception {
    if (context == null) context = FacesContext.getCurrentInstance();

    if (parent == null) {
      UIComponentClassicTagBase parentTag =
          (UIComponentClassicTagBase) req.getAttribute("caucho.jsf.parent");

      parent = parentTag.getComponentInstance();

      BodyContent body = parentTag.getBodyContent();

      addVerbatim(parent, body);
    }

    UIComponent child = null;

    if (binding != null) child = (UIComponent) binding.getValue(context.getELContext());

    if (child == null) {
      child = (UIComponent) childClass.newInstance();

      // jsf/3251
      if (binding != null) binding.setValue(context.getELContext(), child);
    }

    if (parent != null) parent.getChildren().add(child);

    return child;
  }
  public static UIComponent findPersistent(
      FacesContext context, ServletRequest req, UIComponent parent, String id) throws Exception {
    if (context == null) context = FacesContext.getCurrentInstance();

    BodyContent body = null;

    if (parent == null) {
      UIComponentClassicTagBase parentTag =
          (UIComponentClassicTagBase) req.getAttribute("caucho.jsf.parent");

      parent = parentTag.getComponentInstance();

      body = parentTag.getBodyContent();
    }

    if (parent != null) {
      List<UIComponent> children = parent.getChildren();
      int size = children.size();

      String prevId = null;
      for (int i = 0; i < size; i++) {
        UIComponent child = children.get(i);

        if (id.equals(child.getId())) {
          if (body != null) addVerbatim(parent, prevId, body);

          return child;
        }

        if (child.getId() != null) prevId = child.getId();
      }
    }

    return null;
  }
Exemple #6
0
 @Nullable
 public static Duration findCurrentRequestDurationOf(@Nonnull ServletRequest request) {
   final Object plainStopWatch = request.getAttribute(CURRENT_REQUEST_STOP_WATCH_ATTRIBUTE_NAME);
   return plainStopWatch instanceof StopWatch
       ? ((StopWatch) plainStopWatch).getCurrentDuration()
       : null;
 }
Exemple #7
0
  /**
   * Login as the admin user so that a yazd user account can be administered.
   *
   * <p>Includes body of tag if admin user was authorized based on the yazd.tag.properties
   * yazd.admin.username and yazd.admin.password, and a valid yazd username was found in the HTTP
   * input parameter "username".
   *
   * @throws JspException on system level error
   * @return <b>SKIP_BODY</b> on failure to authorize as admin user or user to administer could not
   *     be found, <b>EVAL_BODY_INCLUDE</b> if admin succeeded
   */
  public final int doStartTag() throws JspException {
    // Initialize YazdState
    js = (YazdState) pageContext.getAttribute("yazdUserState", PageContext.SESSION_SCOPE);
    if (js == null) {
      throw new JspException("Yazd admin tag could not get yazd state.");
    }

    // Initialize YazdRequest
    jr = (YazdRequest) pageContext.getAttribute("yazdUserRequest", PageContext.REQUEST_SCOPE);
    if (jr == null) {
      throw new JspException("Yazd admin tag could not get yazd request.");
    }

    // Get username and password of admin
    String username = TagPropertyManager.getTagProperty("yazd.admin.username");
    String password = TagPropertyManager.getTagProperty("yazd.admin.password");
    if (username == null || username.length() == 0 || password == null || password.length() == 0)
      return SKIP_BODY;

    // Get admin user authorization
    try {
      auth = AuthorizationFactory.getAuthorization(username, password);
    } catch (UnauthorizedException ue) {
      return SKIP_BODY;
    }

    // Get the user to administer from the "username" HTTP input parameter
    ServletRequest req = pageContext.getRequest();
    String tmp;
    if ((tmp = req.getParameter("username")) != null) return SKIP_BODY;

    try {
      ForumFactory ff = ForumFactory.getInstance(auth);
      ProfileManager pm = ff.getProfileManager();
      user = pm.getUser(tmp);
    } catch (Exception e) {
    }

    if (user == null) {
      jr.addError("User \"" + tmp + "\" not found");
      return SKIP_BODY;
    }

    return EVAL_BODY_INCLUDE;
  }
Exemple #8
0
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

    // Skip oauth for local connections
    if (!"127.0.0.1".equals(servletRequest.getRemoteAddr())) {
      // Read the OAuth parameters from the request
      OAuthServletRequest request = new OAuthServletRequest(httpRequest);
      OAuthParameters params = new OAuthParameters();
      params.readRequest(request);

      String consumerKey = params.getConsumerKey();

      // Set the secret(s), against which we will verify the request
      OAuthSecrets secrets = new OAuthSecrets();
      secrets.setConsumerSecret(m_tokenStore.getToken(consumerKey));

      // Check that the timestamp has not expired
      String timestampStr = params.getTimestamp();
      if (timestampStr == null) {
        logger.warn("Missing OAuth headers");
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing OAuth headers");
        return;
      }

      long msgTime = Util.parseLong(timestampStr) * 1000L; // Message time is in seconds
      long currentTime = System.currentTimeMillis();

      // if the message is older than 5 min it is no good
      if (Math.abs(msgTime - currentTime) > 300000) {
        logger.warn(
            "OAuth message time out, msg time: " + msgTime + " current time: " + currentTime);
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Message expired");
        return;
      }

      // Verify the signature
      try {
        if (!OAuthSignature.verify(request, params, secrets)) {
          logger.warn("Invalid OAuth signature");

          httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid OAuth signature");
          return;
        }
      } catch (OAuthSignatureException e) {
        logger.warn("OAuth exception", e);

        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid OAuth request");
        return;
      }
    }

    filterChain.doFilter(servletRequest, servletResponse);
  }
  public void service(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {

    // Get print writer.
    PrintWriter pw = response.getWriter();

    // Get enumeration of parameter names.
    Enumeration e = request.getParameterNames();

    // Display parameter names and values.
    while (e.hasMoreElements()) {
      String pname = (String) e.nextElement();
      pw.print(pname + " = ");
      String pvalue = request.getParameter(pname);
      pw.println(pvalue);
    }
    pw.close();
  }
  /**
   * Parses HTTP parameters in an appropriate format and return back map of values to predefined
   * list of names.
   *
   * @param req Request.
   * @return Map of parsed parameters.
   */
  @SuppressWarnings({"unchecked"})
  private Map<String, Object> parameters(ServletRequest req) {
    Map<String, String[]> params = req.getParameterMap();

    if (F.isEmpty(params)) return Collections.emptyMap();

    Map<String, Object> map = U.newHashMap(params.size());

    for (Map.Entry<String, String[]> entry : params.entrySet())
      map.put(entry.getKey(), parameter(entry.getValue()));

    return map;
  }
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    String userAddy = request.getRemoteHost();
    filterConf.getServletContext().log("Vistor User IP: " + userAddy);
    /*
    // Get the IP address of client machine.
    String ipAddress = request.getRemoteAddr();

    // Log the IP address and current timestamp.
    System.out.println("IP "+ ipAddress + ", Time " + new Date().toString());
    */
    chain.doFilter(request, response);
  }
  public static UIComponent findFacet(
      FacesContext context, ServletRequest req, UIComponent parent, String facetName)
      throws Exception {
    if (context == null) FacesContext.getCurrentInstance();

    if (parent == null) {
      UIComponentClassicTagBase parentTag =
          (UIComponentClassicTagBase) req.getAttribute("caucho.jsf.parent");

      parent = parentTag.getComponentInstance();
    }

    if (parent != null) return parent.getFacet(facetName);
    else return null;
  }
  @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();
    }
  }
  /**
   * @param req Request.
   * @return Command.
   */
  @Nullable
  GridRestCommand command(ServletRequest req) {
    String cmd = req.getParameter("cmd");

    return cmd == null ? null : GridRestCommand.fromKey(cmd.toLowerCase());
  }
  /**
   * Creates REST request.
   *
   * @param cmd Command.
   * @param params Parameters.
   * @return REST request.
   * @throws GridException If creation failed.
   */
  @Nullable
  private GridRestRequest createRequest(
      GridRestCommand cmd, Map<String, Object> params, ServletRequest req) throws GridException {
    GridRestRequest restReq;

    switch (cmd) {
      case CACHE_GET:
      case CACHE_GET_ALL:
      case CACHE_PUT:
      case CACHE_PUT_ALL:
      case CACHE_REMOVE:
      case CACHE_REMOVE_ALL:
      case CACHE_ADD:
      case CACHE_CAS:
      case CACHE_METRICS:
      case CACHE_REPLACE:
      case CACHE_DECREMENT:
      case CACHE_INCREMENT:
      case CACHE_APPEND:
      case CACHE_PREPEND:
        {
          GridRestCacheRequest restReq0 = new GridRestCacheRequest();

          restReq0.cacheName((String) params.get("cacheName"));
          restReq0.key(params.get("key"));
          restReq0.value(params.get("val"));
          restReq0.value2(params.get("val2"));

          Object val1 = params.get("val1");

          if (val1 != null) restReq0.value(val1);

          restReq0.cacheFlags(intValue("cacheFlags", params, 0));
          restReq0.ttl(longValue("exp", params, null));
          restReq0.initial(longValue("init", params, null));
          restReq0.delta(longValue("delta", params, null));

          if (cmd == CACHE_GET_ALL || cmd == CACHE_PUT_ALL || cmd == CACHE_REMOVE_ALL) {
            List<Object> keys = values("k", params);
            List<Object> vals = values("v", params);

            if (keys.size() < vals.size())
              throw new GridException(
                  "Number of keys must be greater or equals to number of values.");

            Map<Object, Object> map = U.newHashMap(keys.size());

            Iterator<Object> keyIt = keys.iterator();
            Iterator<Object> valIt = vals.iterator();

            while (keyIt.hasNext()) map.put(keyIt.next(), valIt.hasNext() ? valIt.next() : null);

            restReq0.values(map);
          }

          restReq = restReq0;

          break;
        }

      case TOPOLOGY:
      case NODE:
        {
          GridRestTopologyRequest restReq0 = new GridRestTopologyRequest();

          restReq0.includeMetrics(Boolean.parseBoolean((String) params.get("mtr")));
          restReq0.includeAttributes(Boolean.parseBoolean((String) params.get("attr")));

          restReq0.nodeIp((String) params.get("ip"));

          restReq0.nodeId(uuidValue("id", params));

          restReq = restReq0;

          break;
        }

      case EXE:
      case RESULT:
      case NOOP:
        {
          GridRestTaskRequest restReq0 = new GridRestTaskRequest();

          restReq0.taskId((String) params.get("id"));
          restReq0.taskName((String) params.get("name"));

          restReq0.params(values("p", params));

          restReq0.async(Boolean.parseBoolean((String) params.get("async")));

          restReq0.timeout(longValue("timeout", params, 0L));

          restReq = restReq0;

          break;
        }

      case LOG:
        {
          GridRestLogRequest restReq0 = new GridRestLogRequest();

          restReq0.path((String) params.get("path"));

          restReq0.from(intValue("from", params, -1));
          restReq0.to(intValue("to", params, -1));

          restReq = restReq0;

          break;
        }

      case VERSION:
        {
          restReq = new GridRestRequest();

          break;
        }

      default:
        throw new GridException("Invalid command: " + cmd);
    }

    restReq.address(new InetSocketAddress(req.getRemoteAddr(), req.getRemotePort()));

    restReq.command(cmd);

    if (params.containsKey("gridgain.login") || params.containsKey("gridgain.password")) {
      GridSecurityCredentials cred =
          new GridSecurityCredentials(
              (String) params.get("gridgain.login"), (String) params.get("gridgain.password"));

      restReq.credentials(cred);
    }

    String clientId = (String) params.get("clientId");

    try {
      if (clientId != null) restReq.clientId(UUID.fromString(clientId));
    } catch (Exception ignored) {
      // Ignore invalid client id. Rest handler will process this logic.
    }

    String destId = (String) params.get("destId");

    try {
      if (destId != null) restReq.destinationId(UUID.fromString(destId));
    } catch (IllegalArgumentException ignored) {
      // Don't fail - try to execute locally.
    }

    String sesTokStr = (String) params.get("sessionToken");

    try {
      if (sesTokStr != null) restReq.sessionToken(U.hexString2ByteArray(sesTokStr));
    } catch (IllegalArgumentException ignored) {
      // Ignore invalid session token.
    }

    return restReq;
  }