private void handleOpenArticle(
     Request request, HttpServletResponse httpServletResponse, String target) throws Exception {
   try {
     int k1 = target.indexOf('/', 1);
     int k2 = target.indexOf('/', k1 + 1);
     String feedId = target.substring(k1 + 1, k2);
     String strSeq = target.substring(k2 + 1);
     int seq = Integer.parseInt(strSeq);
     Article article = articleDb.get(feedId, seq);
     LoginInfo loginInfo = userHelpers.getLoginInfo(request);
     // ttt2 using the link from a non-authenticated browser causes a NPE; maybe do something
     // better, e.g. sign up
     ReadArticlesColl readArticlesColl = readArticlesCollDb.get(loginInfo.userId, feedId);
     if (readArticlesColl == null) {
       readArticlesColl = new ReadArticlesColl(loginInfo.userId, feedId);
     }
     if (!readArticlesColl.isRead(seq)) {
       readArticlesColl.markRead(seq, Config.getConfig().maxSizeForReadArticles);
       readArticlesCollDb.add(readArticlesColl);
     }
     String s =
         URIUtil.encodePath(article.url)
             .replace("%3F", "?")
             .replace("%23", "#"); // ttt2 see how to do this right
     httpServletResponse.sendRedirect(s);
   } catch (Exception e) {
     WebUtils.showResult(
         String.format("Failed to get article for path %s. %s", target, e),
         "/",
         request,
         httpServletResponse);
   }
 }
示例#2
0
  /** Inits the. */
  public static synchronized void init() {
    if (inited) {
      return;
    }

    _conf = Config.getConfig();

    /** initialize app command */
    Command.init();

    /** initialize the RSA key, hardcode 2048 bits */
    TConn.pub_key = SystemConfig.s("pub_key", null);
    if (TConn.pub_key == null) {
      Key k = RSA.generate(2048);
      TConn.pri_key = k.pri_key;
      TConn.pub_key = k.pub_key;

      /** set back in database */
      SystemConfig.setConfig("pri_key", TConn.pri_key);
      SystemConfig.setConfig("pub_key", TConn.pub_key);
    } else {

      /** get from the database */
      TConn.pri_key = SystemConfig.s("pri_key", null);
    }

    inited = true;
  }
 // !!! 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();
 }
  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 List<DisplayField> getFieldValues() {
   ArrayList<DisplayField> list = new ArrayList<DisplayField>();
   EmailFields emailFields = Config.getConfig().getEmailFields();
   for (EmailField field : emailFields.getAvailableFields().values()) {
     if (field.getShowInResults() != EmailField.ShowInResults.NORESULTS) {
       try {
         EmailFieldValue efv = searchResult.getFieldValue(field.getName());
         list.add(DisplayField.getDisplayField(efv, locale, false));
       } catch (MessageSearchException mse) {
         logger.debug("failed to retrieve field value from message: " + mse.getMessage());
       }
     }
   }
   return list;
 }
示例#6
0
  /**
   * Instantiates a new MDC server.
   *
   * @param host the host
   * @param port the port
   */
  protected MDCServer(String host, int port) {
    _conf = Config.getConfig();

    address = (host == null) ? new InetSocketAddress(port) : new InetSocketAddress(host, port);

    /** initialize app command */
    Command.init();

    /** initialize the connection center */
    TConnCenter.init(_conf, port);

    synchronized (_conf) {
      /** load public key from database */
      TConn.pub_key = SystemConfig.s("pub_key", null);
      TConn.pri_key = SystemConfig.s("pri_key", null);

      /** initialize the RSA key, hardcode 2048 bits */
      if (TConn.pub_key == null
          || TConn.pri_key == null
          || "".equals(TConn.pub_key)
          || "".equals(TConn.pri_key)) {
        /** print out the old state */
        log.warn(
            "the pub_key or pri_key missed, the old state are pub_key:["
                + TConn.pub_key
                + "], pri_key:["
                + TConn.pri_key
                + "]");

        Key k = RSA.generate(2048);
        TConn.pri_key = k.pri_key;
        TConn.pub_key = k.pub_key;

        /** print out the new public key */
        log.warn("create new RSA key pair, pub_key:[" + TConn.pub_key + ']');

        /** set back in database */
        SystemConfig.setConfig("pri_key", TConn.pri_key);
        SystemConfig.setConfig("pub_key", TConn.pub_key);
      }

      MAX_SIZE = SystemConfig.i("mdc.max_size", MAX_SIZE);
    }
  }
  public static synchronized List<SearchResultBean> getSearchResultBeans(
      List<Search.Result> results, Locale locale) {
    List<SearchResultBean> searchResultBeans = new LinkedList<SearchResultBean>();
    try {
      for (Search.Result result : results) {
        searchResultBeans.add(new SearchResultBean(result, locale));
      }
      while (searchResultBeans.size() < Config.getConfig().getSearch().getMaxSearchResults()) {
        searchResultBeans.add(new SearchResultBean());
      }
    } catch (java.util.ConcurrentModificationException ce) {
      // bit of a hack to say the least

      try {
        Thread.sleep(50);
      } catch (Exception e) {
      }
      return getSearchResultBeans(results, locale);
    }
    return searchResultBeans;
  }
  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);
    }
  }
  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("/");
  }