Example usage for org.apache.commons.lang StringUtils length

List of usage examples for org.apache.commons.lang StringUtils length

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils length.

Prototype

public static int length(String str) 

Source Link

Document

Gets a String's length or 0 if the String is null.

Usage

From source file:org.b3log.symphony.processor.AdminProcessor.java

/**
 * Adds a product./*  ww  w  .  j a  v  a  2s .  com*/
 *
 * @param context the specified context
 * @param request the specified request
 * @param response the specified response
 * @throws Exception exception
 */
@RequestProcessing(value = "/admin/add-product", method = HTTPRequestMethod.POST)
@Before(adviceClass = { StopwatchStartAdvice.class, MallAdminCheck.class })
@After(adviceClass = StopwatchEndAdvice.class)
public void addProduct(final HTTPRequestContext context, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    final String category = request.getParameter(Product.PRODUCT_CATEGORY);
    final String description = request.getParameter(Product.PRODUCT_DESCRIPTION);
    final String name = request.getParameter(Product.PRODUCT_NAME);
    final String price = request.getParameter(Product.PRODUCT_PRICE);
    String imgURL = request.getParameter(Product.PRODUCT_IMG_URL);
    final String count = request.getParameter(Product.PRODUCT_COUNT);
    final String status = request.getParameter(Product.PRODUCT_STATUS);

    if (StringUtils.isBlank(imgURL)) {
        imgURL = "";
    }

    if (StringUtils.isBlank(category) || StringUtils.length(category) > 20) {
        final AbstractFreeMarkerRenderer renderer = new SkinRenderer();
        context.setRenderer(renderer);
        renderer.setTemplateName("admin/error.ftl");
        final Map<String, Object> dataModel = renderer.getDataModel();

        dataModel.put(Keys.MSG, langPropsService.get("invalidProductCategoryLabel"));

        filler.fillHeaderAndFooter(request, response, dataModel);

        return;
    }

    try {
        final JSONObject product = new JSONObject();
        product.put(Product.PRODUCT_CATEGORY, category);
        product.put(Product.PRODUCT_DESCRIPTION, description);
        product.put(Product.PRODUCT_NAME, name);
        product.put(Product.PRODUCT_PRICE, price);
        product.put(Product.PRODUCT_IMG_URL, imgURL);
        product.put(Product.PRODUCT_COUNT, count);
        product.put(Product.PRODUCT_STATUS, status);

        productMgmtService.addProduct(product);
    } catch (final Exception e) {
        final AbstractFreeMarkerRenderer renderer = new SkinRenderer();
        context.setRenderer(renderer);
        renderer.setTemplateName("admin/error.ftl");
        final Map<String, Object> dataModel = renderer.getDataModel();

        dataModel.put(Keys.MSG, e.getMessage());
        filler.fillHeaderAndFooter(request, response, dataModel);

        return;
    }

    response.sendRedirect(Latkes.getServePath() + "/admin/products");
}

From source file:org.b3log.symphony.processor.AdminProcessor.java

/**
 * Updates a product.//ww w  .j  a  v a  2  s  .c om
 *
 * @param context the specified context
 * @param request the specified request
 * @param response the specified response
 * @param productId the specified product id
 * @throws Exception exception
 */
@RequestProcessing(value = "/admin/product/{productId}", method = HTTPRequestMethod.POST)
@Before(adviceClass = { StopwatchStartAdvice.class, MallAdminCheck.class })
@After(adviceClass = StopwatchEndAdvice.class)
public void updateProduct(final HTTPRequestContext context, final HttpServletRequest request,
        final HttpServletResponse response, final String productId) throws Exception {
    final JSONObject product = productQueryService.getProduct(productId);

    final Enumeration<String> parameterNames = request.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        final String name = parameterNames.nextElement();
        final String value = request.getParameter(name);

        product.put(name, value);

        if (name.equals(Product.PRODUCT_STATUS) || name.equals(Product.PRODUCT_COUNT)) {
            product.put(name, Integer.valueOf(value));
        }

        if (name.equals(Product.PRODUCT_CATEGORY)) {
            final String category = value;
            if (StringUtils.isBlank(category) || StringUtils.length(category) > 20) {
                final AbstractFreeMarkerRenderer renderer = new SkinRenderer();
                context.setRenderer(renderer);
                renderer.setTemplateName("admin/error.ftl");
                final Map<String, Object> dataModel = renderer.getDataModel();

                dataModel.put(Keys.MSG, langPropsService.get("invalidProductCategoryLabel"));

                filler.fillHeaderAndFooter(request, response, dataModel);

                return;
            }
        }
    }

    productMgmtService.updateProduct(product);

    response.sendRedirect(Latkes.getServePath() + "/admin/products");
}

From source file:org.b3log.symphony.service.MailMgmtService.java

/**
 * Send weekly newsletter./*from  ww w .j  a v  a  2s  .c  o m*/
 */
public void sendWeeklyNewsletter() {
    final Calendar calendar = Calendar.getInstance();
    final int hour = calendar.get(Calendar.HOUR_OF_DAY);
    final int minute = calendar.get(Calendar.MINUTE);

    if (13 != hour || 55 > minute) {
        return;
    }

    if (weeklyNewsletterSending) {
        return;
    }

    weeklyNewsletterSending = true;
    LOGGER.info("Sending weekly newsletter....");

    final long now = System.currentTimeMillis();
    final long sevenDaysAgo = now - 1000 * 60 * 60 * 24 * 7;

    try {
        final int memberCount = optionRepository.get(Option.ID_C_STATISTIC_MEMBER_COUNT)
                .optInt(Option.OPTION_VALUE);
        final int userSize = memberCount / 7;

        // select receivers 
        final Query toUserQuery = new Query();
        toUserQuery.setCurrentPageNum(1).setPageCount(1).setPageSize(userSize)
                .setFilter(CompositeFilterOperator.and(
                        new PropertyFilter(UserExt.USER_SUB_MAIL_SEND_TIME, FilterOperator.LESS_THAN_OR_EQUAL,
                                sevenDaysAgo),
                        new PropertyFilter(UserExt.USER_LATEST_LOGIN_TIME, FilterOperator.LESS_THAN_OR_EQUAL,
                                sevenDaysAgo),
                        new PropertyFilter(UserExt.USER_SUB_MAIL_STATUS, FilterOperator.EQUAL,
                                UserExt.USER_SUB_MAIL_STATUS_ENABLED),
                        new PropertyFilter(UserExt.USER_STATUS, FilterOperator.EQUAL,
                                UserExt.USER_STATUS_C_VALID)))
                .addSort(Keys.OBJECT_ID, SortDirection.ASCENDING);
        final JSONArray receivers = userRepository.get(toUserQuery).optJSONArray(Keys.RESULTS);

        if (receivers.length() < 1) {
            LOGGER.info("No user need send newsletter");

            return;
        }

        final Set<String> toMails = new HashSet<>();

        final Transaction transaction = userRepository.beginTransaction();
        for (int i = 0; i < receivers.length(); i++) {
            final JSONObject user = receivers.optJSONObject(i);
            final String email = user.optString(User.USER_EMAIL);
            if (Strings.isEmail(email)) {
                toMails.add(email);

                user.put(UserExt.USER_SUB_MAIL_SEND_TIME, now);
                userRepository.update(user.optString(Keys.OBJECT_ID), user);
            }
        }
        transaction.commit();

        // send to admins by default
        final List<JSONObject> admins = userRepository.getAdmins();
        for (final JSONObject admin : admins) {
            toMails.add(admin.optString(User.USER_EMAIL));
        }

        // select nice articles
        final Query articleQuery = new Query();
        articleQuery.setCurrentPageNum(1).setPageCount(1)
                .setPageSize(Symphonys.getInt("sendcloud.batch.articleSize"))
                .setFilter(CompositeFilterOperator.and(
                        new PropertyFilter(Article.ARTICLE_CREATE_TIME, FilterOperator.GREATER_THAN_OR_EQUAL,
                                sevenDaysAgo),
                        new PropertyFilter(Article.ARTICLE_TYPE, FilterOperator.EQUAL,
                                Article.ARTICLE_TYPE_C_NORMAL),
                        new PropertyFilter(Article.ARTICLE_STATUS, FilterOperator.EQUAL,
                                Article.ARTICLE_STATUS_C_VALID)))
                .addSort(Article.ARTICLE_COMMENT_CNT, SortDirection.DESCENDING)
                .addSort(Article.REDDIT_SCORE, SortDirection.DESCENDING);
        final List<JSONObject> articles = CollectionUtils
                .jsonArrayToList(articleRepository.get(articleQuery).optJSONArray(Keys.RESULTS));

        articleQueryService.organizeArticles(UserExt.USER_AVATAR_VIEW_MODE_C_STATIC, articles);

        String mailSubject = "";
        int goodCnt = 0;
        for (final JSONObject article : articles) {
            String content = article.optString(Article.ARTICLE_CONTENT);

            content = Emotions.convert(content);
            content = Markdowns.toHTML(content);
            content = Jsoup.clean(Jsoup.parse(content).text(), Whitelist.basic());
            if (StringUtils.length(content) > 72) {
                content = StringUtils.substring(content, 0, 72) + "....";
            }

            article.put(Article.ARTICLE_CONTENT, content);

            final int gc = article.optInt(Article.ARTICLE_GOOD_CNT);
            if (gc >= goodCnt) {
                mailSubject = article.optString(Article.ARTICLE_TITLE);
                goodCnt = gc;
            }
        }

        // select nice users
        final int RANGE_SIZE = 64;
        final int SELECT_SIZE = 6;
        final Query userQuery = new Query();
        userQuery.setCurrentPageNum(1).setPageCount(1).setPageSize(RANGE_SIZE)
                .setFilter(new PropertyFilter(UserExt.USER_STATUS, FilterOperator.EQUAL,
                        UserExt.USER_STATUS_C_VALID))
                .addSort(UserExt.USER_ARTICLE_COUNT, SortDirection.DESCENDING)
                .addSort(UserExt.USER_COMMENT_COUNT, SortDirection.DESCENDING);
        final JSONArray rangeUsers = userRepository.get(userQuery).optJSONArray(Keys.RESULTS);
        final List<Integer> indices = CollectionUtils.getRandomIntegers(0, RANGE_SIZE, SELECT_SIZE);
        final List<JSONObject> users = new ArrayList<>();
        for (final Integer index : indices) {
            users.add(rangeUsers.getJSONObject(index));
        }

        for (final JSONObject selectedUser : users) {
            avatarQueryService.fillUserAvatarURL(UserExt.USER_AVATAR_VIEW_MODE_C_STATIC, selectedUser);
        }

        final Map<String, Object> dataModel = new HashMap<>();
        dataModel.put(Article.ARTICLES, (Object) articles);
        dataModel.put(User.USERS, (Object) users);

        final String fromName = langPropsService.get("symphonyEnLabel") + " "
                + langPropsService.get("weeklyEmailFromNameLabel", Latkes.getLocale());
        Mails.batchSendHTML(fromName, mailSubject, new ArrayList<>(toMails), Mails.TEMPLATE_NAME_WEEKLY,
                dataModel);

        LOGGER.info("Sent weekly newsletter [" + toMails.size() + "]");
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Sends weekly newsletter failed", e);
    } finally {
        weeklyNewsletterSending = false;
    }
}

From source file:org.b3log.symphony.util.Runes.java

/**
 * Gets chinese percentage of the specified string.
 *
 * @param str the specified string/*from  w ww  . j a v  a 2s . c o  m*/
 * @return percentage
 */
public static int getChinesePercent(final String str) {
    if (StringUtils.isBlank(str)) {
        return 0;
    }

    final Pattern p = Pattern.compile("([\u4e00-\u9fa5]+)");
    final Matcher m = p.matcher(str);
    final StringBuilder chineseBuilder = new StringBuilder();
    while (m.find()) {
        chineseBuilder.append(m.group(0));
    }

    return (int) Math
            .floor(StringUtils.length(chineseBuilder.toString()) / (double) StringUtils.length(str) * 100);
}

From source file:org.b3log.xiaov.service.QQService.java

public void onQQGroupMessage(final GroupMessage message) {
    final long groupId = message.getGroupId();

    final String content = message.getContent();
    final String userName = Long.toHexString(message.getUserId());
    // Push to forum
    String qqMsg = content.replaceAll("\\[\"face\",[0-9]+\\]", "");
    if (StringUtils.isNotBlank(qqMsg)) {
        qqMsg = "<p>" + qqMsg + "</p>";
        sendToForum(qqMsg, userName);// www  . j av  a2 s  .  c o m
    }

    String msg = "";
    if (StringUtils.contains(content, XiaoVs.QQ_BOT_NAME)
            || (StringUtils.length(content) > 6
            && (StringUtils.contains(content, "?") || StringUtils.contains(content, "") || StringUtils.contains(content, "")))) {
        msg = answer(content, userName);
    }

    if (StringUtils.isBlank(msg)) {
        return;
    }

    if (RandomUtils.nextFloat() >= 0.9) {
        Long latestAdTime = GROUP_AD_TIME.get(groupId);
        if (null == latestAdTime) {
            latestAdTime = 0L;
        }

        final long now = System.currentTimeMillis();

        if (now - latestAdTime > 1000 * 60 * 30) {
            msg = msg + "\n\n" + ADS.get(RandomUtils.nextInt(ADS.size())) + "";

            GROUP_AD_TIME.put(groupId, now);
        }
    }

    sendMessageToGroup(groupId, msg);
}

From source file:org.b3log.xiaov.service.QQService.java

public void onQQDiscussMessage(final DiscussMessage message) {
    final long discussId = message.getDiscussId();

    final String content = message.getContent();
    final String userName = Long.toHexString(message.getUserId());
    // Push to forum
    String qqMsg = content.replaceAll("\\[\"face\",[0-9]+\\]", "");
    if (StringUtils.isNotBlank(qqMsg)) {
        qqMsg = "<p>" + qqMsg + "</p>";
        sendToForum(qqMsg, userName);/*from w  w  w  .j a va  2 s .co  m*/
    }

    String msg = "";
    if (StringUtils.contains(content, XiaoVs.QQ_BOT_NAME)
            || (StringUtils.length(content) > 6
            && (StringUtils.contains(content, "?") || StringUtils.contains(content, "") || StringUtils.contains(content, "")))) {
        msg = answer(content, userName);
    }

    if (StringUtils.isBlank(msg)) {
        return;
    }

    if (RandomUtils.nextFloat() >= 0.9) {
        Long latestAdTime = DISCUSS_AD_TIME.get(discussId);
        if (null == latestAdTime) {
            latestAdTime = 0L;
        }

        final long now = System.currentTimeMillis();

        if (now - latestAdTime > 1000 * 60 * 30) {
            msg = msg + "\n\n" + ADS.get(RandomUtils.nextInt(ADS.size())) + "";

            DISCUSS_AD_TIME.put(discussId, now);
        }
    }

    sendMessageToDiscuss(discussId, msg);
}

From source file:org.batoo.jpa.core.impl.criteria.QueryImpl.java

private void dumpResultSet() throws SQLException {
    final int[] lengths = new int[this.labels.length];
    for (int i = 0; i < lengths.length; i++) {
        lengths[i] = this.max(lengths[i], StringUtils.length(this.labels[i]));
    }/*from w  w w. j  a v  a  2 s  .co m*/

    for (final Object[] data : this.data) {
        for (int i = 0; i < this.labels.length; i++) {
            final Object value = data[i];
            if (value != null) {
                lengths[i] = this.max(lengths[i], StringUtils.length(value.toString()));
            }
        }
    }

    int length = 1;
    for (final int l : lengths) {
        length += l + 3;
    }

    final StringBuffer dump = new StringBuffer("Query returned {0} row(s):\n");

    // the labels
    dump.append(StringUtils.repeat("-", length));
    dump.append("\n| ");

    for (int i = 0; i < this.labels.length; i++) {
        String strValue = StringUtils.abbreviate(this.labels[i], lengths[i]);
        strValue = StringUtils.rightPad(strValue, lengths[i]);

        dump.append(strValue);
        dump.append(" | ");
    }

    // the data
    dump.append("\n");
    dump.append(StringUtils.repeat("-", length));

    for (final Object[] data : this.data) {
        dump.append("\n| ");

        for (int i = 0; i < this.labels.length; i++) {
            final Object value = data[i];

            String strValue = value != null ? value.toString() : "!NULL!";
            strValue = StringUtils.abbreviate(strValue, lengths[i]);
            if (value instanceof Number) {
                strValue = StringUtils.leftPad(strValue, lengths[i]);
            } else {
                strValue = StringUtils.rightPad(strValue, lengths[i]);
            }

            dump.append(strValue);
            dump.append(" | ");
        }

    }

    dump.append("\n");
    dump.append(StringUtils.repeat("-", length));

    QueryImpl.LOG.debug(dump.toString(), this.data.size());
}

From source file:org.bigmouth.nvwa.utils.degist.DesUtils.java

public static String encrypt(String content, String key, byte[] iv) {
    try {//from   w  w w  .j ava2s.co  m
        if (StringUtils.length(key) != 8) {
            throw new IllegalArgumentException("Key must be 8 byte");
        }
        SecretKeySpec secretkey = new SecretKeySpec(key.getBytes(), "DES");
        IvParameterSpec zeroIv = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretkey, zeroIv);
        byte[] encryptedData = cipher.doFinal(content.getBytes());
        return Base64.encodeBase64String(encryptedData);
    } catch (Exception e) {
        LOGGER.error("encrypt:", e);
        return null;
    }
}

From source file:org.bigmouth.nvwa.utils.degist.DesUtils.java

public static String decrypt(String content, String key, byte[] iv) {
    try {/*w w w . j  a v  a2s.c om*/
        if (StringUtils.length(key) != 8) {
            throw new IllegalArgumentException("Key must be 8 byte");
        }
        byte[] contentBytes = Base64.decodeBase64(content);
        SecretKeySpec secretkey = new SecretKeySpec(key.getBytes(), "DES");
        IvParameterSpec zeroIv = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretkey, zeroIv);
        byte[] decryptedData = cipher.doFinal(contentBytes);
        return new String(decryptedData);
    } catch (Exception e) {
        LOGGER.error("decrypt:", e);
        return null;
    }
}

From source file:org.eclipse.jubula.rc.swt.tester.adapter.ComboAdapter.java

/**
 * Select the whole text of the textfield.
 *///from w w w  .jav a  2 s .c  om
public void selectAll() {
    click(new Integer(1));

    // fix for https://bxapps.bredex.de/bugzilla/show_bug.cgi?id=201
    // The keystroke "command + a" sometimes causes an "a" to be entered
    // into the text field instead of selecting all text (or having no 
    // effect).
    if (EnvironmentUtils.isMacOS()) {
        getEventThreadQueuer().invokeAndWait("combo.selectAll", //$NON-NLS-1$
                new IRunnable() {
                    public Object run() {
                        int textLength = StringUtils.length(m_combobox.getText());
                        m_combobox.setSelection(new Point(0, textLength));
                        return null;
                    }
                });
    } else {
        getRobot().keyStroke(getRobot().getSystemModifierSpec() + " A"); //$NON-NLS-1$
    }
}