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);
  }
  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 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("/");
  }
  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);
  }
  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 getOffset(final Request jettyRequest, final HttpServletResponse response)
      throws IOException {
    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"));

    try {
      final OffsetCommand offsetCommand =
          this.convert2OffsetCommand(topic, partition, group, offset);
      final ResponseCommand responseCommand =
          this.commandProcessor.processOffsetCommand(offsetCommand, null);
      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 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);
    }
  }
 @Override
 protected void doHandle(
     String target,
     Request baseRequest,
     HttpServletRequest request,
     HttpServletResponse response,
     XMLStreamWriter writer)
     throws IOException {
   String suiteId = baseRequest.getParameter("suiteId");
   if (suiteId == null) {
     response.setStatus(HttpServletResponse.SC_MULTIPLE_CHOICES);
     response.getWriter().append("Must specify a suite using parameter suiteId");
   } else {
     WebAgentTestSuite s = cache.getSuite(suiteId);
     if (s == null) {
       response.setStatus(HttpServletResponse.SC_NOT_FOUND);
       response.getWriter().append("Could not find a test suite " + suiteId);
     } else {
       try {
         handleForSuite(response, s);
       } catch (PropertyException pe) {
         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
         log.error(
             "Failed to serialize test suite to xml, PropertyException, probably your Marshaller "
                 + "implementation does not support the property com.sun.xml.internal.bind.xmlHeaders",
             pe);
       } catch (Exception e) {
         response.setStatus(
             HttpServletResponse
                 .SC_INTERNAL_SERVER_ERROR); // client may not see this if we have already written
                                             // output
         log.error("Failed to serialize test suite to xml", e);
       }
     }
   }
 }
  private void putMessage(final Request jettyRequest, final HttpServletResponse response)
      throws IOException {
    final String topic = jettyRequest.getParameter("topic");
    try {
      // Validation should be done on client side already
      final int partition = Integer.parseInt(jettyRequest.getParameter("partition"));
      final int flag = Integer.parseInt(jettyRequest.getParameter("flag"));
      int checkSum = -1;
      if (StringUtils.isNotBlank(jettyRequest.getParameter("checksum"))) {
        checkSum = Integer.parseInt(jettyRequest.getParameter("checksum"));
      }
      // This stream should be handle by Jetty server and therefore it is
      // out of scope here without care close
      final InputStream inputStream = jettyRequest.getInputStream();
      final int dataLength = Integer.parseInt(jettyRequest.getParameter("length"));
      final byte[] data = new byte[dataLength];

      inputStream.read(data);
      this.doResponseHeaders(response, "text/plain");
      final PutCommand putCommand = this.convert2PutCommand(topic, partition, data, flag, checkSum);
      this.commandProcessor.processPutCommand(
          putCommand,
          null,
          new PutCallback() {

            @Override
            public void putComplete(final ResponseCommand resp) {
              final BooleanCommand responseCommand = (BooleanCommand) resp;
              response.setStatus(responseCommand.getCode());
              try {
                response.getWriter().write(responseCommand.getErrorMsg());
              } catch (final IOException e) {
                logger.error("Write response failed", e);
              }
            }
          });

    } catch (final Exception e) {
      logger.error("Put message failed", e);
      response.setStatus(HttpStatus.InternalServerError);
      response.getWriter().write(e.getMessage());
    }
  }
示例#10
0
  public void handle(
      String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("text/html;charset=utf-8");
    response.getWriter().println("<h1>ScienceBox!</h1>");

    response.getWriter().println("current temperature: " + tempControl.getLastReading() + "<br>");
    response.getWriter().println("current humidity: " + humidityControl.getLastReading() + "<br>");
    response.getWriter().println("target temperature: " + tempControl.getTargetReading() + "<br>");
    response.getWriter().println("target humidity: " + humidityControl.getTargetReading() + "<br>");

    if (baseRequest.getParameter(Grammar.TOKEN_CONTROL_TEMPERATURE) != null) {
      double new_target =
          Double.parseDouble(baseRequest.getParameter(Grammar.TOKEN_CONTROL_TEMPERATURE));
      response.getWriter().println("new target temperature: " + new_target + "<br>");
      tempControl.setTargetReading(new Hardware.TypedValue(Hardware.DataType.CELSIUS, new_target));
    }

    if (baseRequest.getParameter(Grammar.TOKEN_CONTROL_HUMIDITY) != null) {
      double new_target =
          Double.parseDouble(baseRequest.getParameter(Grammar.TOKEN_CONTROL_HUMIDITY));
      response.getWriter().println("new target humidity: " + new_target + "<br>");
      humidityControl.setTargetReading(
          new Hardware.TypedValue(Hardware.DataType.PERCENT, new_target));
    }

    if (baseRequest.getParameter(Grammar.TOKEN_HARDWARE_FAN) != null) {
      double new_setting = Double.parseDouble(baseRequest.getParameter(Grammar.TOKEN_HARDWARE_FAN));
      fan.onNewSetting(new Hardware.TypedValue(Hardware.DataType.ON_OFF, new_setting));
      fan.onNewSetting(new Hardware.TypedValue(Hardware.DataType.ON_OFF, new_setting));
    }

    baseRequest.setHandled(true);
  }
  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("/");
  }