@Test
  public void testBasic() throws Exception {
    ServiceHandler handler = new ServiceHandler();
    Service service = new Service();
    handler.registerWebService(service);

    Request baseRequest = org.easymock.classextension.EasyMock.createMock(Request.class);
    HttpServletRequest request = createMock(HttpServletRequest.class);
    HttpServletResponse response = createMock(HttpServletResponse.class);

    expect(baseRequest.isHandled()).andReturn(false);
    expect(request.getMethod()).andReturn("GET");
    expect(request.getPathInfo()).andReturn("/");
    expect(request.getParameter("bar")).andReturn("bar2");
    expect(request.getParameter("baz")).andReturn(null);
    expect(request.getHeader("Content-Length")).andReturn("103");
    expect(response.isCommitted()).andReturn(false).anyTimes();
    baseRequest.setHandled(true);

    org.easymock.classextension.EasyMock.replay(baseRequest);
    replay(request, response);
    handler.handle(null, baseRequest, request, response);
    org.easymock.classextension.EasyMock.verify(baseRequest);
    verify(request, response);
  }
  private void getMessage(final Request jettyRequest, final HttpServletResponse response)
      throws IOException {
    // Validation should be done on client side already
    final String topic = jettyRequest.getParameter("topic");
    final int partition = Integer.parseInt(jettyRequest.getParameter("partition"));
    final String group = jettyRequest.getParameter("group");
    final long offset = Long.parseLong(jettyRequest.getParameter("offset"));
    final int maxSize = Integer.parseInt(jettyRequest.getParameter("maxsize"));

    try {
      final GetCommand getCommand =
          this.convert2GetCommand(topic, partition, group, offset, maxSize);
      final ResponseCommand responseCommand =
          this.commandProcessor.processGetCommand(getCommand, null, false);
      if (responseCommand instanceof DataCommand) {
        response.setStatus(HttpStatus.Success);
        response.getOutputStream().write(((DataCommand) responseCommand).getData());
      } else {
        response.setStatus(((BooleanCommand) responseCommand).getCode());
        response.getWriter().write(((BooleanCommand) responseCommand).getErrorMsg());
      }
    } catch (final Throwable e) {
      logger.error("Could not get message from position " + offset, e);
      response.setStatus(HttpStatus.InternalServerError);
      response.getWriter().write(e.getMessage());
    }
  }
  private void handleChangeSettingsPost(Request request, HttpServletResponse httpServletResponse)
      throws Exception {

    LoginInfo loginInfo = userHelpers.getLoginInfo(request);
    if (loginInfo == null) {
      WebUtils.redirectToError("Couldn't determine the current user", request, httpServletResponse);
      return;
    }

    String stringItemsPerPage = request.getParameter(PARAM_ITEMS_PER_PAGE);
    try {
      loginInfo.itemsPerPage = Integer.parseInt(stringItemsPerPage);
    } catch (Exception e) {
      showResult(
          "Error trying to set the items per page. Expected integer value but got "
              + stringItemsPerPage,
          PATH_SETTINGS,
          request,
          httpServletResponse);
      return;
    }
    loginInfo.style = request.getParameter(PARAM_STYLE);
    loginInfo.feedDateFormat =
        request.getParameter(PARAM_FEED_DATE_FORMAT); // ttt2 validate, better in JSP

    loginInfoDb.add(loginInfo);

    // httpServletResponse.sendRedirect(PATH_SETTINGS);
    showResult("Settings changed", "/", request, httpServletResponse);
  }
Esempio n. 4
0
  /**
   * Handle a request.
   *
   * @param target The target of the request - either a URI or a name.
   * @param baseRequest The original unwrapped request object.
   * @param request The request either as the {@link Request} object or a wrapper of that request.
   * @param response The response as the {@link org.eclipse.jetty.server.Response} object or a
   *     wrapper of that request.
   * @throws IOException in case of IO error.
   */
  @SuppressWarnings("unchecked")
  @Override
  public void handle(
      String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    if (baseRequest.isHandled()) {
      return;
    }
    Route route = findRoute(request.getMethod(), request.getPathInfo());
    if (route == null) {
      return;
    }

    Object param = getRouteParam(request, route);
    try {
      beginTransaction();
      Response<?> handlerResponse =
          route.handle(param, new RouteParameters(route.getRouteParams(request.getPathInfo())));
      commitTransaction();
      writeHttpResponse(request, response, handlerResponse);
    } catch (HttpErrorException httpError) {
      commitTransaction();
      writeHttpError(response, httpError);
    } catch (Exception exception) {
      rollBackTransaction();
      writeInternalError(response, exception);
    }
    baseRequest.setHandled(true);
  }
    /* @Override */
    public void handle(
        String pathInContext,
        org.eclipse.jetty.server.Request request,
        HttpServletRequest httpRequest,
        HttpServletResponse httpResponse)
        throws IOException, ServletException {

      final boolean expectGet = (httpRequest.getHeader("x-expect-get") != null);
      final boolean expectPost = (httpRequest.getHeader("x-expect-post") != null);
      if (expectGet) {
        final String method = request.getMethod();
        if (!"GET".equals(method)) {
          httpResponse.sendError(500, "Incorrect method.  Expected GET, received " + method);
          return;
        }
        httpResponse.setStatus(200);
        httpResponse.getOutputStream().write("OK".getBytes());
        httpResponse.getOutputStream().flush();
        return;
      } else if (expectPost) {
        final String method = request.getMethod();
        if (!"POST".equals(method)) {
          httpResponse.sendError(500, "Incorrect method.  Expected POST, received " + method);
          return;
        }
        httpResponse.setStatus(200);
        httpResponse.getOutputStream().write("OK".getBytes());
        httpResponse.getOutputStream().flush();
        return;
      }

      String header = httpRequest.getHeader("x-redirect");
      if (header != null) {
        // format for header is <status code>|<location url>
        String[] parts = header.split("@");
        int redirectCode;
        try {
          redirectCode = Integer.parseInt(parts[0]);
        } catch (Exception ex) {
          ex.printStackTrace();
          httpResponse.sendError(500, "Unable to parse redirect code");
          return;
        }
        httpResponse.setStatus(redirectCode);
        if (httpRequest.getHeader("x-negative") == null) {
          httpResponse.addHeader("x-expect-get", "true");
        } else {
          httpResponse.addHeader("x-expect-post", "true");
        }
        httpResponse.setContentLength(0);
        httpResponse.addHeader("Location", parts[1] + counter.getAndIncrement());
        httpResponse.getOutputStream().flush();
        return;
      }

      httpResponse.sendError(500);
      httpResponse.getOutputStream().flush();
      httpResponse.getOutputStream().close();
    }
Esempio n. 6
0
 @Override
 public void log(Request request, Response response) {
   if (logger.isDebugEnabled()) {
     logger.debug(
         "%s %s %s",
         request.getMethod(), request.getUri().toString(), request.getProtocol().toString());
   }
 }
 public Authentication register(Request request, SamlSession samlSession) {
   Authentication authentication = request.getAuthentication();
   if (!(authentication instanceof KeycloakAuthentication)) {
     UserIdentity userIdentity = createIdentity(samlSession);
     authentication = createAuthentication(userIdentity, request);
     request.setAuthentication(authentication);
   }
   return authentication;
 }
 private void updateResponses(Request request) {
   final int response = request.getResponse().getStatus() / 100;
   if (response >= 1 && response <= 5) {
     responses[response - 1].mark();
   }
   activeRequests.dec();
   final long elapsedTime = System.currentTimeMillis() - request.getTimeStamp();
   requests.update(elapsedTime, TimeUnit.MILLISECONDS);
   requestTimer(request.getMethod()).update(elapsedTime, TimeUnit.MILLISECONDS);
 }
Esempio n. 9
0
  @Test
  public void testMalformedPathInfoReturnsError() throws IOException {
    Request baseRequest = createMock(Request.class);
    expect(baseRequest.getPathInfo()).andReturn("/..upADirectory");
    replayAll();

    TraceHandlerDelegate traceHandler = new TraceHandlerDelegate();
    assertNull(traceHandler.getDataForRequest(baseRequest));

    verifyAll();
  }
  public JettySamlSessionStore getTokenStore(
      Request request, HttpFacade facade, SamlDeployment resolvedDeployment) {
    JettySamlSessionStore store = (JettySamlSessionStore) request.getAttribute(TOKEN_STORE_NOTE);
    if (store != null) {
      return store;
    }
    store = createJettySamlSessionStore(request, facade, resolvedDeployment);

    request.setAttribute(TOKEN_STORE_NOTE, store);
    return store;
  }
Esempio n. 11
0
  public void handle(
      String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    if (response.isCommitted() || baseRequest.isHandled()) {
      return;
    }

    baseRequest.setHandled(true);

    response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    response.sendRedirect("/realtime");
  }
Esempio n. 12
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("/");
  }
  @Test
  public void testHandler()
      throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    LessCompilerHandler handler = new LessCompilerHandler();

    Request requestJetty = mock(Request.class);

    when(requestJetty.isHandled()).thenReturn(true);

    handler.handle(null, requestJetty, requestJetty, null);

    verify(requestJetty).isHandled();
  }
Esempio n. 14
0
 @Override // !!! note that this gets called for missing pages, but not if exceptions are thrown;
           // exceptions are handled separately
 public void handle(
     String target,
     Request request,
     HttpServletRequest httpServletRequest,
     HttpServletResponse httpServletResponse)
     throws IOException {
   request.setHandled(true);
   httpServletResponse
       .getWriter()
       .println(
           String.format("<h1>Page doesn't exist: %s</h1>", request.getUri().getDecodedPath()));
 }
Esempio n. 15
0
 @Override
 public void doHandle(
     String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
     throws IOException, ServletException {
   LOG.debug("jettyhandler, handle();");
   try {
     // wrap the request so 'getInputStream()' can be called multiple times
     filter.doFilter(new HttpRequestWrapper(request), response, null);
     baseRequest.setHandled(true);
   } catch (NotConsumedException ignore) {
     // TODO : Not use an exception in order to be faster.
     baseRequest.setHandled(false);
   }
 }
Esempio n. 16
0
  private void handleChangePasswordPost(Request request, HttpServletResponse httpServletResponse)
      throws Exception {

    LoginInfo loginInfo = userHelpers.getLoginInfo(request);
    if (loginInfo == null) {
      WebUtils.redirectToError("Couldn't determine the current user", request, httpServletResponse);
      return;
    }

    String userId = loginInfo.userId;
    String stringCrtPassword = request.getParameter(PARAM_CURRENT_PASSWORD);
    String stringNewPassword = request.getParameter(PARAM_PASSWORD);
    String stringNewPasswordConfirm = request.getParameter(PARAM_PASSWORD_CONFIRM);

    if (!stringNewPassword.equals(stringNewPasswordConfirm)) {
      showResult(
          "Mismatch between password and password confirmation",
          PATH_SETTINGS,
          request,
          httpServletResponse);
      return;
    }

    User user =
        userDb.get(
            userId); // ttt1 crashes for wrong ID; 2013.07.20 - no longer have an idea what this is
                     // about
    if (user == null) {
      WebUtils.redirectToError("Couldn't find the current user", request, httpServletResponse);
      return;
    }

    if (!user.checkPassword(stringCrtPassword)) {
      showResult("Incorrect current password", PATH_SETTINGS, request, httpServletResponse);
      return;
    }

    SecureRandom secureRandom = new SecureRandom();
    String salt = "" + secureRandom.nextLong();
    byte[] password = User.computeHashedPassword(stringNewPassword, salt);
    user.salt = salt;
    user.password = password;

    // ttt3 2 clients can change the password simultaneously
    userDb.add(user);

    // httpServletResponse.sendRedirect(PATH_SETTINGS);
    showResult("Password changed", PATH_SETTINGS, request, httpServletResponse);
  }
Esempio n. 17
0
 public void handle(
     String s,
     org.eclipse.jetty.server.Request r,
     HttpServletRequest request,
     HttpServletResponse response)
     throws IOException, ServletException {
   if ("GET".equalsIgnoreCase(request.getMethod())) {
     response.addHeader("target", r.getHttpURI().getPath());
     response.setStatus(HttpServletResponse.SC_OK);
   } else {
     // this handler is to handle POST request
     response.sendError(HttpServletResponse.SC_FORBIDDEN);
   }
   r.setHandled(true);
 }
  public String newNonce(Request request) {
    long ts = request.getTimeStamp();
    long sk = _nonceSecret;

    byte[] nounce = new byte[24];
    for (int i = 0; i < 8; i++) {
      nounce[i] = (byte) (ts & 0xff);
      ts = ts >> 8;
      nounce[8 + i] = (byte) (sk & 0xff);
      sk = sk >> 8;
    }

    byte[] hash = null;
    try {
      MessageDigest md = MessageDigest.getInstance("MD5");
      md.reset();
      md.update(nounce, 0, 16);
      hash = md.digest();
    } catch (Exception e) {
      Log.warn(e);
    }

    for (int i = 0; i < hash.length; i++) {
      nounce[8 + i] = hash[i];
      if (i == 23) {
        break;
      }
    }

    return new String(B64Code.encode(nounce));
  }
Esempio n. 19
0
    public void handle(
        String target,
        Request baseRequest,
        HttpServletRequest request,
        HttpServletResponse response)
        throws IOException, ServletException {
      if (!H2O.ARGS.ldap_login) {
        return;
      }

      String loginName = request.getUserPrincipal().getName();
      if (!loginName.equals(H2O.ARGS.user_name)) {
        Log.warn(
            "Login name ("
                + loginName
                + ") does not match cluster owner name ("
                + H2O.ARGS.user_name
                + ")");
        sendResponseError(
            response,
            HttpServletResponse.SC_UNAUTHORIZED,
            "Login name does not match cluster owner name");
        baseRequest.setHandled(true);
      }
    }
 /* ------------------------------------------------------------ */
 protected boolean checkSecurity(Request request) {
   switch (request.getDispatcherType()) {
     case REQUEST:
     case ASYNC:
       return true;
     case FORWARD:
       if (isCheckWelcomeFiles()
           && request.getAttribute("org.eclipse.jetty.server.welcome") != null) {
         request.removeAttribute("org.eclipse.jetty.server.welcome");
         return true;
       }
       return false;
     default:
       return false;
   }
 }
Esempio n. 21
0
  @Override
  public void handle(
      String target, Request request, HttpServletRequest httpRequest, HttpServletResponse response)
      throws IOException, ServletException {
    response.setContentType(Const.JSON);
    Service service = getService(request);
    Module module = getModule(request, service);

    GetVersionData data = new GetVersionData();

    Future artifactFuture =
        executorService.submit(
            new ReadModuleArtifactVersionsRunnable(service, module, data, moduleArtifactHelper));
    Future configFuture =
        executorService.submit(
            new ReadModuleConfigVersionsRunnable(module, data, moduleConfigHelper));

    while (!artifactFuture.isDone() || !configFuture.isDone()) {
      try {
        Thread.sleep(100);
      } catch (InterruptedException ex) {
      }
    }

    toJson(response, data);
    response.setStatus(200);
    request.setHandled(true);
  }
Esempio n. 22
0
  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);
    }
  }
Esempio n. 23
0
 private void addLoginParams(Request request, LoginInfo loginInfo) {
   MultiMap<String> params = new MultiMap<>();
   if (loginInfo != null && loginInfo.rememberAccount) {
     params.put(PARAM_USER_ID, loginInfo.userId);
   }
   request.setParameters(params);
 }
Esempio n. 24
0
 @Override
 public void customize(final EndPoint endpoint, final Request request) throws IOException {
   if (this.forceHttps) {
     request.setScheme("https");
     super.customize(endpoint, request);
   }
 }
  @Override
  protected void completeOAuthAuthentication(
      final KeycloakPrincipal<RefreshableKeycloakSecurityContext> skp) {
    principal = skp;
    final RefreshableKeycloakSecurityContext securityContext = skp.getKeycloakSecurityContext();
    final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext);
    OidcKeycloakAccount account =
        new OidcKeycloakAccount() {

          @Override
          public Principal getPrincipal() {
            return skp;
          }

          @Override
          public Set<String> getRoles() {
            return roles;
          }

          @Override
          public KeycloakSecurityContext getKeycloakSecurityContext() {
            return securityContext;
          }
        };
    request.setAttribute(KeycloakSecurityContext.class.getName(), securityContext);
    this.tokenStore.saveAccountInfo(account);
  }
  /** {@inheritDoc} */
  @Override
  public void handle(String target, Request req, HttpServletRequest srvReq, HttpServletResponse res)
      throws IOException, ServletException {
    if (log.isDebugEnabled())
      log.debug("Handling request [target=" + target + ", req=" + req + ", srvReq=" + srvReq + ']');

    if (target.startsWith("/ignite")) {
      processRequest(target, srvReq, res);

      req.setHandled(true);
    } else if (target.startsWith("/favicon.ico")) {
      if (favicon == null) {
        res.setStatus(HttpServletResponse.SC_NOT_FOUND);

        req.setHandled(true);

        return;
      }

      res.setStatus(HttpServletResponse.SC_OK);

      res.setContentType("image/x-icon");

      res.getOutputStream().write(favicon);
      res.getOutputStream().flush();

      req.setHandled(true);
    } else {
      if (dfltPage == null) {
        res.setStatus(HttpServletResponse.SC_NOT_FOUND);

        req.setHandled(true);

        return;
      }

      res.setStatus(HttpServletResponse.SC_OK);

      res.setContentType("text/html");

      res.getWriter().write(dfltPage);
      res.getWriter().flush();

      req.setHandled(true);
    }
  }
 public void handle(
     String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
     throws IOException, ServletException {
   response.setContentType("text/html;charset=utf-8");
   response.setStatus(HttpServletResponse.SC_OK);
   baseRequest.setHandled(true);
   response.getWriter().println("<h1>Hello World</h1>");
 }
  @Override
  public void handle(
      String path,
      Request request,
      HttpServletRequest httpRequest,
      HttpServletResponse httpResponse)
      throws IOException, ServletException {

    activeDispatches.inc();

    final long start;
    final HttpChannelState state = request.getHttpChannelState();
    if (state.isInitial()) {
      // new request
      activeRequests.inc();
      start = request.getTimeStamp();
    } else {
      // resumed request
      start = System.currentTimeMillis();
      activeSuspended.dec();
      if (state.getState() == State.DISPATCHED) {
        asyncDispatches.mark();
      }
    }

    try {
      super.handle(path, request, httpRequest, httpResponse);
    } finally {
      final long now = System.currentTimeMillis();
      final long dispatched = now - start;

      activeDispatches.dec();
      dispatches.update(dispatched, TimeUnit.MILLISECONDS);

      if (state.isSuspended()) {
        if (state.isInitial()) {
          state.addListener(listener);
        }
        activeSuspended.inc();
      } else if (state.isInitial()) {
        requests.update(dispatched, TimeUnit.MILLISECONDS);
        updateResponses(request);
      }
      // else onCompletion will handle it.
    }
  }
Esempio n. 29
0
 @Override
 public void log(Request request, Response response) {
   if (_ignorePathMap != null && _ignorePathMap.getMatch(request.getRequestURI()) != null) return;
   int status = response.getStatus();
   long written = response.getContentLength();
   transmitter.queue(
       new AccessLogJettyAdapter(request, status, written, _preferProxiedForAddress));
 }
    public void handle(
        String target,
        Request baseRequest,
        HttpServletRequest request,
        HttpServletResponse response)
        throws IOException, ServletException {
      if (baseRequest.isHandled()) {
        return;
      }
      _counter.increment();

      response.setContentType("text/plain");
      response.setStatus(HttpServletResponse.SC_OK);
      PrintWriter writer = response.getWriter();
      writer.println("===TEST RESPONSE===");
      baseRequest.setHandled(true);
    }