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

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

Introduction

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

Prototype

public static String substring(String str, int start, int end) 

Source Link

Document

Gets a substring from the specified String avoiding exceptions.

Usage

From source file:org.apache.ranger.plugin.util.RangerPerfTracer.java

public static RangerPerfTracer getPerfTracer(Log logger, String tag) {
    String data = "";
    String realTag = "";

    if (tag != null) {
        int indexOfTagEndMarker = StringUtils.indexOf(tag, tagEndMarker);
        if (indexOfTagEndMarker != -1) {
            realTag = StringUtils.substring(tag, 0, indexOfTagEndMarker);
            data = StringUtils.substring(tag, indexOfTagEndMarker);
        } else {//from  w w w .  j a  v  a  2 s  . c o m
            realTag = tag;
        }
    }
    return RangerPerfTracerFactory.getPerfTracer(logger, realTag, data);
}

From source file:org.apache.wiki.site.SiteGeneratorTest.java

/**
 * checks if a given line begins with a date or not.
 * /*from w w w .  ja  va 2  s  .  c  o m*/
 * @param line given line.
 * @return {@code true} if it does, {@code false} otherwise. 
 */
boolean lineBeginsWithDate(String line) {
    boolean begins = false;
    try {
        DateUtils.parseDate(StringUtils.substring(line, 0, 10), new String[] { "yyyy-mm-dd", "yyyy/mm/dd" });
        begins = true;
    } catch (ParseException e) {
        LOG.info("Not a date, so it's not a heading");
    }
    return begins;
}

From source file:org.artifactory.api.module.ModuleInfoUtils.java

/**
 * Constructs the module version pattern, starting from [baseRev] to [fileItegRev]
 *
 * @param itemPathPattern the item path containing all the tokens of a given repo layout
 * @return the tokens path representing the file name, empty string ("") in case of unsupported layout,
 *         Unsupported layout is one which [fileItegRev] is before [baseRev]
 *//*from  w  w w  .  j av a  2s .c om*/
private static String getModuleVersionPattern(String itemPathPattern) {
    String wrappedBaseRevisionToken = RepoLayoutUtils.wrapKeywordAsToken(RepoLayoutUtils.BASE_REVISION);
    String wrappedFileItegRevToken = RepoLayoutUtils
            .wrapKeywordAsToken(RepoLayoutUtils.FILE_INTEGRATION_REVISION);
    int baseRevStartPos = StringUtils.lastIndexOf(itemPathPattern, wrappedBaseRevisionToken);
    int fileItegRevEndPos = StringUtils.lastIndexOf(itemPathPattern, wrappedFileItegRevToken);
    int indexOfClosingOptionalBracket = StringUtils.indexOf(itemPathPattern, ")", fileItegRevEndPos);
    if (indexOfClosingOptionalBracket > 0) {
        fileItegRevEndPos = indexOfClosingOptionalBracket + 1;
    }
    if (fileItegRevEndPos >= baseRevStartPos) {
        return StringUtils.substring(itemPathPattern, baseRevStartPos, fileItegRevEndPos);
    }

    return "";
}

From source file:org.artifactory.storage.db.build.dao.BuildModulesDao.java

public int createBuildModule(BuildModule bm) throws SQLException {
    int res = jdbcHelper.executeUpdate("INSERT INTO build_modules VALUES(" + "?, ?, ?)", bm.getModuleId(),
            bm.getBuildId(), bm.getModuleNameId());
    for (ModuleProperty bmp : bm.getProperties()) {
        res += jdbcHelper.executeUpdate("INSERT INTO module_props VALUES(" + "?, ?, ?, ?)", bmp.getPropId(),
                bmp.getModuleId(), bmp.getPropKey(), StringUtils.substring(bmp.getPropValue(), 0, 2048));
    }/*w  ww.  j ava  2  s . com*/
    return res;
}

From source file:org.artifactory.storage.db.build.dao.BuildsDao.java

public int createBuild(BuildEntity b, BlobWrapper jsonBlob) throws SQLException {
    int res = jdbcHelper.executeUpdate(
            "INSERT INTO builds VALUES(" + "?, " + "?, ?, ?, " + "?, ?, ?," + "?, ?)", b.getBuildId(),
            b.getBuildName(), b.getBuildNumber(), b.getBuildDate(), b.getCiUrl(), b.getCreated(),
            b.getCreatedBy(), nullIfZero(b.getModified()), b.getModifiedBy());
    res += jdbcHelper.executeUpdate("INSERT INTO build_jsons VALUES(?,?)", b.getBuildId(), jsonBlob);
    int nbProps = b.getProperties().size();
    if (nbProps != 0) {
        for (BuildProperty bp : b.getProperties()) {
            String propValue = bp.getPropValue();
            if (propValue.length() > 2048) {
                log.info("Trimming property value to 2048 characters {}", bp.getPropKey());
                log.debug("Trimming property value to 2048 characters {}: {}", bp.getPropKey(),
                        bp.getPropValue());
                propValue = StringUtils.substring(propValue, 0, 2048);
            }/*  w w w  . ja  va 2s  .c  o  m*/
            res += jdbcHelper.executeUpdate("INSERT INTO build_props VALUES (?,?,?,?)", bp.getPropId(),
                    bp.getBuildId(), bp.getPropKey(), propValue);
        }
    }
    int nbPromotions = b.getPromotions().size();
    if (nbPromotions != 0) {
        for (BuildPromotionStatus bp : b.getPromotions()) {
            res += jdbcHelper.executeUpdate("INSERT INTO build_promotions VALUES (?,?,?,?,?,?,?)",
                    bp.getBuildId(), bp.getCreated(), bp.getCreatedBy(), bp.getStatus(), bp.getRepository(),
                    bp.getComment(), bp.getCiUser());
        }
    }
    return res;
}

From source file:org.artifactory.storage.db.fs.dao.PropertiesDao.java

public int create(NodeProperty property) throws SQLException {
    String propValue = nullIfEmpty(property.getPropValue());
    if (propValue != null && propValue.length() > PROP_VALUE_MAX_SIZE) {
        log.info("Trimming property value to 4000 characters '{}'", property.getPropKey());
        log.debug("Trimming property value to 4000 characters {}: {}", property.getPropKey(),
                property.getPropValue());
        propValue = StringUtils.substring(propValue, 0, PROP_VALUE_MAX_SIZE);
    }/*  ww w .  j  a  va  2  s. c  o  m*/
    return jdbcHelper.executeUpdate("INSERT INTO node_props VALUES(?, ?, ?, ?)", property.getPropId(),
            property.getNodeId(), property.getPropKey(), propValue);
}

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

/**
 * Gets article preview content.//from  www  .j a  v  a 2 s  .  co  m
 *
 * <p>
 * Renders the response with a json object, for example,
 * <pre>
 * {
 *     "html": ""
 * }
 * </pre>
 * </p>
 *
 * @param request the specified http servlet request
 * @param response the specified http servlet response
 * @param context the specified http request context
 * @param articleId the specified article id
 * @throws Exception exception
 */
@RequestProcessing(value = "/article/{articleId}/preview", method = HTTPRequestMethod.GET)
@Before(adviceClass = StopwatchStartAdvice.class)
@After(adviceClass = StopwatchEndAdvice.class)
public void getArticlePreviewContent(final HttpServletRequest request, final HttpServletResponse response,
        final HTTPRequestContext context, final String articleId) throws Exception {
    context.renderJSON(true).renderJSONValue("html", "");

    final JSONObject article = articleQueryService.getArticle(articleId);
    if (null == article) {
        context.renderFalseResult();

        return;
    }

    final int length = Integer.valueOf("150");
    String content = article.optString(Article.ARTICLE_CONTENT);
    final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID);
    final JSONObject author = userQueryService.getUser(authorId);

    if (null != author && UserExt.USER_STATUS_C_INVALID == author.optInt(UserExt.USER_STATUS)
            || Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)) {
        context.renderJSONValue("html", langPropsService.get("articleContentBlockLabel"));

        return;
    }

    final Set<String> userNames = userQueryService.getUserNames(content);
    final JSONObject currentUser = userQueryService.getCurrentUser(request);
    final String currentUserName = null == currentUser ? "" : currentUser.optString(User.USER_NAME);
    final String authorName = author.optString(User.USER_NAME);
    if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE)
            && !authorName.equals(currentUserName)) {
        boolean invited = false;
        for (final String userName : userNames) {
            if (userName.equals(currentUserName)) {
                invited = true;

                break;
            }
        }

        if (!invited) {
            String blockContent = langPropsService.get("articleDiscussionLabel");
            blockContent = blockContent.replace("{user}",
                    "<a href='" + Latkes.getServePath() + "/member/" + authorName + "'>" + authorName + "</a>");

            context.renderJSONValue("html", blockContent);

            return;
        }
    }

    content = Emotions.convert(content);
    content = Markdowns.toHTML(content);

    content = Jsoup.clean(content, Whitelist.none());
    if (content.length() >= length) {
        content = StringUtils.substring(content, 0, length) + " ....";
    }

    context.renderJSONValue("html", content);
}

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

private static byte[] baiduTTS(final String text, final String uid) {
    if (null == BAIDU_ACCESS_TOKEN) {
        refreshBaiduAccessToken();// w  w w .j  av  a 2s  .co m
    }

    if (null == BAIDU_ACCESS_TOKEN) {
        LOGGER.warn("Please configure [baidu.yuyin.*] in symphony.properties");

        return null;
    }

    try {
        final URL url = new URL("http://tsn.baidu.com/text2audio?grant_type=client_credentials" + "&client_id="
                + BAIDU_API_KEY + "&client_secret=" + BAIDU_SECRET_KEY);

        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        final OutputStream outputStream = conn.getOutputStream();
        IOUtils.write("tex=" + URLEncoder.encode(StringUtils.substring(text, 0, 1024), "UTF-8")
                + "&lan=zh&cuid=" + uid + "&spd=6&pit=6&ctp=1&tok=" + BAIDU_ACCESS_TOKEN, outputStream);
        IOUtils.closeQuietly(outputStream);

        final InputStream inputStream = conn.getInputStream();

        final int responseCode = conn.getResponseCode();
        final String contentType = conn.getContentType();

        if (HttpServletResponse.SC_OK != responseCode || !"audio/mp3".equals(contentType)) {
            final String msg = IOUtils.toString(inputStream);
            LOGGER.warn("Baidu Yuyin TTS failed: " + msg.toString());
            IOUtils.closeQuietly(inputStream);
            conn.disconnect();

            return null;
        }

        final byte[] ret = IOUtils.toByteArray(inputStream);
        IOUtils.closeQuietly(inputStream);
        conn.disconnect();

        return ret;
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Requires Baidu Yuyin access token failed", e);
    }

    return null;
}

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

/**
 * Send weekly newsletter.//from   www .  ja  va2s . 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.beanfuse.bean.converters.DateConverter.java

/**
 * ?<br>//www.  j  a  v a  2  s  .c  o  m
 * format 1: yyyy-MM-dd hh:mm:ss<br>
 * format 2: yyyyMMdd
 */
protected Object convertToDate(final Class type, final Object value) {
    if (StringUtils.isEmpty((String) value)) {
        return null;
    } else {
        String dateStr = (String) value;
        String[] times = StringUtils.split(dateStr, " ");
        String[] dateElems = null;
        if (StringUtils.contains(times[0], "-")) {
            dateElems = StringUtils.split(times[0], "-");
        } else {
            dateElems = new String[3];
            int yearIndex = "yyyy".length();
            dateElems[0] = StringUtils.substring(times[0], 0, yearIndex);
            dateElems[1] = StringUtils.substring(times[0], yearIndex, yearIndex + 2);
            dateElems[2] = StringUtils.substring(times[0], yearIndex + 2, yearIndex + 4);
        }
        Calendar gc = GregorianCalendar.getInstance();
        gc.set(Calendar.YEAR, NumberUtils.toInt(dateElems[0]));
        gc.set(Calendar.MONTH, NumberUtils.toInt(dateElems[1]) - 1);
        gc.set(Calendar.DAY_OF_MONTH, NumberUtils.toInt(dateElems[2]));
        if (times.length > 1 && StringUtils.isNotBlank(times[1])) {
            String[] timeElems = StringUtils.split(times[1], ":");
            if (timeElems.length > 0) {
                gc.set(Calendar.HOUR_OF_DAY, NumberUtils.toInt(timeElems[0]));
            }
            if (timeElems.length > 1) {
                gc.set(Calendar.MINUTE, NumberUtils.toInt(timeElems[1]));
            }
            if (timeElems.length > 2) {
                gc.set(Calendar.SECOND, NumberUtils.toInt(timeElems[2]));
            }
        }
        return gc.getTime();
    }
}