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

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

Introduction

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

Prototype

public static String substringBefore(String str, String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

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

/**
 * Gets the request tag from the specified request URI.
 * /*ww  w .java 2 s. co  m*/
 * @param requestURI the specified request URI
 * @return tag
 */
private static String getTagArticlesPagedTag(final String requestURI) {
    String tagAndPageNum = requestURI.substring((Latkes.getContextPath() + "/articles/tags/").length());

    if (!tagAndPageNum.endsWith("/")) {
        tagAndPageNum += "/";
    }

    return StringUtils.substringBefore(tagAndPageNum, "/");
}

From source file:org.b3log.solo.processor.console.ArticleConsole.java

/**
 * Gets articles(by crate date descending) by the specified request json
 * object./* ww w.  j av a 2 s .c om*/
 *
 * <p>
 * The request URI contains the pagination arguments. For example, the 
 * request URI is /console/articles/status/published/1/10/20, means the
 * current page is 1, the page size is 10, and the window size is 20.
 * </p>
 *
 * <p>
 * Renders the response with a json object, for example,
 * <pre>
 * {
 *     "sc": boolean,
 *     "pagination": {
 *         "paginationPageCount": 100,
 *         "paginationPageNums": [1, 2, 3, 4, 5]
 *     },
 *     "articles": [{
 *         "oId": "",
 *         "articleTitle": "",
 *         "articleCommentCount": int,
 *         "articleCreateTime"; long,
 *         "articleViewCount": int,
 *         "articleTags": "tag1, tag2, ....",
 *         "articlePutTop": boolean,
 *         "articleIsPublished": boolean
 *      }, ....]
 * }
 * </pre>, order by article update date and sticky(put top).
 * </p>
 *
 * @param request the specified http servlet request
 * @param response the specified http servlet response
 * @param context the specified http request context
 * @throws Exception exception
 */
@RequestProcessing(value = ARTICLES_URI_PREFIX + "status/*"
        + Requests.PAGINATION_PATH_PATTERN, method = HTTPRequestMethod.GET)
public void getArticles(final HttpServletRequest request, final HttpServletResponse response,
        final HTTPRequestContext context) throws Exception {
    if (!userUtils.isLoggedIn(request, response)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);

    try {
        String path = request.getRequestURI()
                .substring((Latkes.getContextPath() + ARTICLES_URI_PREFIX + "status/").length());
        final String status = StringUtils.substringBefore(path, "/");
        path = path.substring((status + "/").length());

        final boolean published = "published".equals(status) ? true : false;

        final JSONObject requestJSONObject = Requests.buildPaginationRequest(path);
        requestJSONObject.put(Article.ARTICLE_IS_PUBLISHED, published);

        final JSONArray excludes = new JSONArray();
        excludes.put(Article.ARTICLE_CONTENT);
        excludes.put(Article.ARTICLE_UPDATE_DATE);
        excludes.put(Article.ARTICLE_CREATE_DATE);
        excludes.put(Article.ARTICLE_AUTHOR_EMAIL);
        excludes.put(Article.ARTICLE_HAD_BEEN_PUBLISHED);
        excludes.put(Article.ARTICLE_IS_PUBLISHED);
        excludes.put(Article.ARTICLE_RANDOM_DOUBLE);
        requestJSONObject.put(Keys.EXCLUDES, excludes);

        final JSONObject result = articleQueryService.getArticles(requestJSONObject);

        result.put(Keys.STATUS_CODE, true);
        renderer.setJSONObject(result);
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);

        final JSONObject jsonObject = QueryResults.defaultResult();
        renderer.setJSONObject(jsonObject);
        jsonObject.put(Keys.MSG, langPropsService.get("getFailLabel"));
    }
}

From source file:org.b3log.solo.processor.ErrorProcessor.java

/**
 * Shows the user template page./*w  w  w  .j  a  v  a  2  s  .  c om*/
 * 
 * @param context the specified context
 * @param request the specified HTTP servlet request
 * @param response the specified HTTP servlet response
 * @throws IOException io exception 
 */
@RequestProcessing(value = "/error/*.html", method = HTTPRequestMethod.GET)
public void showErrorPage(final HTTPRequestContext context, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException {
    final String requestURI = request.getRequestURI();
    String templateName = StringUtils.substringAfterLast(requestURI, "/");
    templateName = StringUtils.substringBefore(templateName, ".") + ".ftl";
    LOGGER.log(Level.FINE, "Shows error page[requestURI={0}, templateName={1}]",
            new Object[] { requestURI, templateName });

    final ConsoleRenderer renderer = new ConsoleRenderer();
    context.setRenderer(renderer);
    renderer.setTemplateName("error" + File.separatorChar + templateName);

    final Map<String, Object> dataModel = renderer.getDataModel();

    try {
        final Map<String, String> langs = langPropsService.getAll(Locales.getLocale(request));
        dataModel.putAll(langs);
        final JSONObject preference = preferenceQueryService.getPreference();

        filler.fillBlogHeader(request, dataModel, preference);
        filler.fillBlogFooter(dataModel, preference);

        dataModel.put(Common.LOGIN_URL, userService.createLoginURL(Common.ADMIN_INDEX_URI));
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);

        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (final IOException ex) {
            LOGGER.severe(ex.getMessage());
        }
    }
}

From source file:org.b3log.solo.processor.UserTemplateProcessor.java

/**
 * Shows the user template page.//from  w  w  w. j  a va2  s  .  com
 * 
 * @param context the specified context
 * @param request the specified HTTP servlet request
 * @param response the specified HTTP servlet response
 * @throws IOException io exception 
 */
@RequestProcessing(value = "/*.html", method = HTTPRequestMethod.GET)
public void showPage(final HTTPRequestContext context, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException {
    final String requestURI = request.getRequestURI();
    String templateName = StringUtils.substringAfterLast(requestURI, "/");
    templateName = StringUtils.substringBefore(templateName, ".") + ".ftl";
    LOGGER.log(Level.FINE, "Shows page[requestURI={0}, templateName={1}]",
            new Object[] { requestURI, templateName });

    final AbstractFreeMarkerRenderer renderer = new FrontRenderer();
    context.setRenderer(renderer);
    renderer.setTemplateName(templateName);

    final Map<String, Object> dataModel = renderer.getDataModel();

    final Template template = Templates.getTemplate((String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME),
            templateName);
    if (null == template) {
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);

            return;
        } catch (final IOException ex) {
            LOGGER.severe(ex.getMessage());
        }
    }

    try {
        final Map<String, String> langs = langPropsService.getAll(Locales.getLocale(request));
        dataModel.putAll(langs);
        final JSONObject preference = preferenceQueryService.getPreference();

        dataModel.put(Keys.PAGE_TYPE, PageTypes.USER_TEMPLATE);
        filler.fillBlogHeader(request, dataModel, preference);
        filler.fillUserTemplate(template, dataModel, preference);
        filler.fillBlogFooter(dataModel, preference);
        Skins.fillSkinLangs(preference.optString(Preference.LOCALE_STRING),
                (String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), dataModel);

        request.setAttribute(PageCaches.CACHED_OID, "No id");
        request.setAttribute(PageCaches.CACHED_TITLE, requestURI);
        request.setAttribute(PageCaches.CACHED_TYPE, langs.get(PageTypes.USER_TEMPLATE.getLangeLabel()));
        request.setAttribute(PageCaches.CACHED_LINK, requestURI);
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);

        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (final IOException ex) {
            LOGGER.severe(ex.getMessage());
        }
    }
}

From source file:org.b3log.solo.service.ImportService.java

private JSONObject parseArticle(final String fileName, String fileContent) {
    fileContent = StringUtils.trim(fileContent);
    String frontMatter = StringUtils.substringBefore(fileContent, "---");
    if (StringUtils.isBlank(frontMatter)) {
        fileContent = StringUtils.substringAfter(fileContent, "---");
        frontMatter = StringUtils.substringBefore(fileContent, "---");
    }/* ww w  .j  a v  a  2 s  .  c  om*/

    final JSONObject ret = new JSONObject();
    final Yaml yaml = new Yaml();
    Map elems;

    try {
        elems = (Map) yaml.load(frontMatter);
    } catch (final Exception e) {
        // treat it as plain markdown
        ret.put(Article.ARTICLE_TITLE, StringUtils.substringBeforeLast(fileName, "."));
        ret.put(Article.ARTICLE_CONTENT, fileContent);
        ret.put(Article.ARTICLE_ABSTRACT, Article.getAbstract(fileContent));
        ret.put(Article.ARTICLE_TAGS_REF, DEFAULT_TAG);
        ret.put(Article.ARTICLE_IS_PUBLISHED, true);
        ret.put(Article.ARTICLE_COMMENTABLE, true);
        ret.put(Article.ARTICLE_VIEW_PWD, "");

        return ret;
    }

    String title = (String) elems.get("title");
    if (StringUtils.isBlank(title)) {
        title = StringUtils.substringBeforeLast(fileName, ".");
    }
    ret.put(Article.ARTICLE_TITLE, title);

    String content = StringUtils.substringAfter(fileContent, frontMatter);
    if (StringUtils.startsWith(content, "---")) {
        content = StringUtils.substringAfter(content, "---");
        content = StringUtils.trim(content);
    }
    ret.put(Article.ARTICLE_CONTENT, content);

    final String abs = parseAbstract(elems, content);
    ret.put(Article.ARTICLE_ABSTRACT, abs);

    final Date date = parseDate(elems);
    ret.put(Article.ARTICLE_CREATED, date.getTime());

    final String permalink = (String) elems.get("permalink");
    if (StringUtils.isNotBlank(permalink)) {
        ret.put(Article.ARTICLE_PERMALINK, permalink);
    }

    final List<String> tags = parseTags(elems);
    final StringBuilder tagBuilder = new StringBuilder();
    for (final String tag : tags) {
        tagBuilder.append(tag).append(",");
    }
    tagBuilder.deleteCharAt(tagBuilder.length() - 1);
    ret.put(Article.ARTICLE_TAGS_REF, tagBuilder.toString());

    ret.put(Article.ARTICLE_IS_PUBLISHED, true);
    ret.put(Article.ARTICLE_COMMENTABLE, true);
    ret.put(Article.ARTICLE_VIEW_PWD, "");

    return ret;
}

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

/**
 * Shows admin point charge records./*w  ww.j av a2  s .c  o  m*/
 *
 * @param context the specified context
 * @param request the specified request
 * @param response the specified response
 * @throws Exception exception
 */
@RequestProcessing(value = "/admin/charge-records", method = HTTPRequestMethod.GET)
@Before(adviceClass = { StopwatchStartAdvice.class, MallAdminCheck.class })
@After(adviceClass = { CSRFToken.class, StopwatchEndAdvice.class })
public void showChargeRecords(final HTTPRequestContext context, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    final AbstractFreeMarkerRenderer renderer = new SkinRenderer();
    context.setRenderer(renderer);
    renderer.setTemplateName("admin/charge-records.ftl");
    final Map<String, Object> dataModel = renderer.getDataModel();

    String pageNumStr = request.getParameter("p");
    if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
        pageNumStr = "1";
    }

    final int pageNum = Integer.valueOf(pageNumStr);
    final int pageSize = Symphonys.PAGE_SIZE;

    final JSONObject result = pointtransferQueryService.getChargeRecords(pageNum, pageSize);
    final List<JSONObject> results = (List<JSONObject>) result.opt(Keys.RESULTS);
    for (final JSONObject record : results) {
        final String toUserId = record.optString(Pointtransfer.TO_ID);
        final JSONObject toUser = userQueryService.getUser(toUserId);
        record.put(User.USER_NAME, toUser.optString(User.USER_NAME));
        record.put(UserExt.USER_REAL_NAME, toUser.optString(UserExt.USER_REAL_NAME));

        final String handlerId = StringUtils.substringAfterLast(record.optString(Pointtransfer.DATA_ID), "-");
        final JSONObject handler = userQueryService.getUser(handlerId);
        record.put(Common.HANDLER_NAME, handler.optString(User.USER_NAME));
        record.put(Common.HANDLER_REAL_NAME, handler.optString(UserExt.USER_REAL_NAME));

        record.put(Pointtransfer.TIME, new Date(record.optLong(Pointtransfer.TIME)));
        record.put(Common.MONEY, StringUtils.substringBefore(record.optString(Pointtransfer.DATA_ID), "-"));
    }

    dataModel.put(Keys.RESULTS, results);

    final long chargePointSum = pointtransferQueryService.getChargePointSum();
    final int pointExchangeUnit = Symphonys.getInt("pointExchangeUnit");
    dataModel.put(Common.CHARGE_SUM, chargePointSum / pointExchangeUnit);

    final JSONObject pagination = result.optJSONObject(Pagination.PAGINATION);
    final int pageCount = pagination.optInt(Pagination.PAGINATION_PAGE_COUNT);
    final JSONArray pageNums = pagination.optJSONArray(Pagination.PAGINATION_PAGE_NUMS);
    dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.opt(0));
    dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.opt(pageNums.length() - 1));
    dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
    dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
    dataModel.put(Pagination.PAGINATION_PAGE_NUMS, CollectionUtils.jsonArrayToList(pageNums));

    filler.fillHeaderAndFooter(request, response, dataModel);
}

From source file:org.bdval.tools.convert.maqcii.CornellDataFormatter.java

/**
 * Extract the cornell model id from the predictions MODEL_FILENAME_PREFIX column in the
 * prediction data./*from  w ww  .ja va 2 s  . c om*/
 *
 * @param predictionData the line of prediction data.
 * @return the cornell model id
 */
public static String extractCornellModelId(final Map<String, String> predictionData) {
    final String modelFilenamePrefix = predictionData.get("modelFilenamePrefix");
    final String[] parts = StringUtils.split(modelFilenamePrefix, '-');
    final String modelId = parts[parts.length - 1];
    return StringUtils.substringBefore(modelId, ".zip");
}

From source file:org.beanfuse.collection.Order.java

public Order(String property) {
    if (StringUtils.contains(property, ",")) {
        throw new RuntimeException("user parser for multiorder");
    }//from   ww w  .ja v  a  2s.c o  m
    if (StringUtils.contains(property, " desc")) {
        this.ascending = false;
        this.property = StringUtils.substringBefore(property, " desc");
    } else {
        if (StringUtils.contains(property, " asc")) {
            this.property = StringUtils.substringBefore(property, " asc");
        } else {
            this.property = property;
        }
        this.ascending = true;
    }
    this.property = this.property.trim();
}

From source file:org.beanfuse.struts2.plugin.result.DefaultResultBuilder.java

public Result build(String resultCode, ActionConfig actionConfig, ActionContext context) {
    String path = null;/*from   w ww . ja v a2  s  .co  m*/
    ResultTypeConfig resultTypeConfig = null;
    Map params = new HashMap();
    log.debug("result code:{} for actionConfig:{}", resultCode, actionConfig);
    if (null == resultTypeConfigs) {
        PackageConfig pc = configuration.getPackageConfig(actionConfig.getPackageName());
        this.resultTypeConfigs = pc.getAllResultTypeConfigs();
    }
    // prefix
    // TODO jsp,vm,ftl
    if (!StringUtils.contains(resultCode, ':')) {
        String className = context.getActionInvocation().getProxy().getAction().getClass().getName();
        String methodName = context.getActionInvocation().getProxy().getMethod();
        if (StringUtils.isEmpty(resultCode)) {
            resultCode = "index";
        }
        StringBuilder buf = new StringBuilder();
        buf.append(viewMapper.getViewPath(className, methodName, resultCode));
        buf.append('.');
        buf.append(profileService.getProfile(className).getViewExtension());
        path = buf.toString();
        resultTypeConfig = (ResultTypeConfig) resultTypeConfigs.get("freemarker");
    } else {
        String prefix = StringUtils.substringBefore(resultCode, ":");
        resultTypeConfig = (ResultTypeConfig) resultTypeConfigs.get(prefix);
        String redirectParamStr = null;
        if (prefix.startsWith("redirect")) {
            redirectParamStr = ServletActionContext.getRequest().getParameter("params");
        }
        Action action = (Action) ActionContext.getContext().getContextMap().get("dispatch_action");
        if (null != action) {
            if (null != action.getClazz()) {
                action.setName(actionNameBuilder.build(action.getClazz().getName()));
            }
            if (StringUtils.isBlank(action.getName())) {
                String t_path = ServletActionContext.getRequest().getServletPath();
                if (StringUtils.isBlank(t_path)) { // webspheret_pathworkaround
                    t_path = ServletActionContext.getRequest().getRequestURI();
                    t_path = t_path.substring(t_path.indexOf('/', 1));
                    action.setName(t_path);
                } else
                    action.setName(t_path);
            }
            path = buildAction(action, params, redirectParamStr);
        } else {
            path = buildAction(StringUtils.substringAfter(resultCode, ":"), params, redirectParamStr);
        }

    }
    return buildResult(path, resultCode, resultTypeConfig, context, params);
}

From source file:org.beanfuse.struts2.plugin.result.DefaultResultBuilder.java

/**
 * ??//from   w w w .  ja v  a  2s.  c om
 * 
 * @param path
 * @param param
 * @param redirectParamStr
 * @return
 */
private String buildAction(String path, Map<String, Object> param, String redirectParamStr) {
    String newPath = path;
    if (path.startsWith("?")) {
        newPath = ServletActionContext.getRequest().getServletPath() + path;
    }
    // ????
    if (null != redirectParamStr) {
        if (newPath.indexOf('?') == -1) {
            newPath += ('?' + redirectParamStr.substring(1));
        } else {
            newPath += redirectParamStr;
        }
    }
    String paramString = StringUtils.substringAfter(newPath, "?");
    if (null != paramString) {
        Map requestParams = new HashMap();
        paramString = StringUtils.replace(paramString, "?", "");
        String[] paramPairs = StringUtils.split(paramString, "&");
        for (int i = 0; i < paramPairs.length; i++) {
            String name = StringUtils.substringBefore(paramPairs[i], "=");
            String value = StringUtils.substringAfter(paramPairs[i], "=");
            if (name == "method") {
                param.put("method", value);
            }
            requestParams.put(name, value);
        }
        if (!requestParams.isEmpty()) {
            param.put("requestParameters", requestParams);
        }
    }
    return addNamespaceAction(newPath, param);
}