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

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

Introduction

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

Prototype

public static boolean startsWith(String str, String prefix) 

Source Link

Document

Check if a String starts with a specified prefix.

Usage

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

/**
 * tagArticlesRSS.//from  w ww .j  a  v  a 2  s  .  c o m
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void tagArticlesRSS() throws Exception {
    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/tag-articles-rss.do");
    when(request.getMethod()).thenReturn("GET");
    final JSONObject tag = getTagRepository().get(new Query()).optJSONArray(Keys.RESULTS).optJSONObject(0);
    when(request.getQueryString()).thenReturn("tag=" + tag.optString(Keys.OBJECT_ID));

    final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
    dispatcherServlet.init();

    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);

    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(printWriter);

    dispatcherServlet.service(request, response);

    final String content = stringWriter.toString();
    Assert.assertTrue(StringUtils.startsWith(content, "<?xml version=\"1.0\""));
}

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

/**
 * rpc//from ww  w. ja  v a2  s .com
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void metaWeblog() throws Exception {
    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/apis/metaweblog");
    when(request.getMethod()).thenReturn("POST");

    //        Date date = (Date) DateFormatUtils.ISO_DATETIME_FORMAT.parseObject("2004-05-03T17:30:08");
    Date date = DateUtils.parseDate("20040503T17:30:08",
            new String[] { "yyyyMMdd'T'HH:mm:ss", "yyyyMMdd'T'HH:mm:ss'Z'" });

    final class MockServletInputStream extends ServletInputStream {

        private ByteArrayInputStream stream;

        public MockServletInputStream(byte[] data) {
            stream = new ByteArrayInputStream(data);
        }

        public int read() throws IOException {
            return stream.read();
        }

        @Override
        public boolean isFinished() {
            return false;
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setReadListener(ReadListener readListener) {
        }
    }
    StringBuilder sb = new StringBuilder();
    sb.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>").append("<methodCall>")
            .append("<methodName>metaWeblog.newPost</methodName>").append("<params>").append("<param>")
            .append("<value><int>11</int></value>").append("</param>").append("<param>")
            .append("<value><string>test@gmail.com</string></value>").append("</param>").append("<param>")
            .append("<value><string>pass</string></value>").append("</param>").append("<param>")
            .append("<value>").append("<struct>").append("<member>").append("<name>dateCreated</name>")
            .append("<value><dateTime.iso8601>20040503T17:30:08</dateTime.iso8601></value>").append("</member>")
            .append("<member>").append("<name>title</name>").append("<value><string>title</string></value>")
            .append("</member>").append("<member>").append("<name>description</name>")
            .append("<value><string>description</string></value>").append("</member>").append("</struct>")
            .append("</value>").append("</param>").append("<param>")
            .append("<value><boolean>1</boolean></value>").append("</param>").append("</params>")
            .append("</methodCall>");
    when(request.getInputStream()).thenReturn(new MockServletInputStream(sb.toString().getBytes()));

    final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
    dispatcherServlet.init();

    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);

    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(printWriter);

    dispatcherServlet.service(request, response);

    final String content = stringWriter.toString();
    System.out.println("xxxxxcontent:" + content);
    Assert.assertTrue(StringUtils.startsWith(content, "<?xml version=\"1.0\""));
}

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

/**
 * blogArticlesAtom.// w w w  .j a v  a  2s .com
 *
 * @throws Exception exception
 */
@Test(dependsOnMethods = "init")
public void blogArticlesAtom() throws Exception {
    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/sitemap.xml");
    when(request.getMethod()).thenReturn("GET");

    final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
    dispatcherServlet.init();

    final StringWriter stringWriter = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(stringWriter);

    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getWriter()).thenReturn(printWriter);

    dispatcherServlet.service(request, response);

    final String content = stringWriter.toString();
    Assert.assertTrue(StringUtils.startsWith(content, "<?xml version=\"1.0\""));
}

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, "---");
    }/*from   www. j a  v  a 2s .  com*/

    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.solo.util.Markdowns.java

/**
 * Converts the specified markdown text to HTML.
 *
 * @param markdownText the specified markdown text
 * @return converted HTML, returns {@code null} if the specified markdown text is "" or {@code null}, returns
 * "Markdown error" if exception//from   w w w.  ja  v a  2 s.  c  o m
 */
public static String toHTML(final String markdownText) {
    if (Strings.isEmptyOrNull(markdownText)) {
        return "";
    }

    final PegDownProcessor pegDownProcessor = new PegDownProcessor(Extensions.ALL, 5000);
    String ret = pegDownProcessor.markdownToHtml(markdownText);

    if (!StringUtils.startsWith(ret, "<p>")) {
        ret = "<p>" + ret + "</p>";
    }

    return ret;
}

From source file:org.b3log.symphony.processor.advice.CSRFCheck.java

@Override
public void doAdvice(final HTTPRequestContext context, final Map<String, Object> args)
        throws RequestProcessAdviceException {
    final HttpServletRequest request = context.getRequest();

    final JSONObject exception = new JSONObject();
    exception.put(Keys.MSG, langPropsService.get("csrfCheckFailedLabel"));
    exception.put(Keys.STATUS_CODE, false);

    // 1. Check Referer
    final String referer = request.getHeader("Referer");
    if (!StringUtils.startsWith(referer, Latkes.getServePath())) {
        throw new RequestProcessAdviceException(exception);
    }//  ww  w .  j  a  v a 2s. co m

    // 2. Check Token
    final String clientToken = request.getHeader(Common.CSRF_TOKEN);
    final String serverToken = Sessions.getCSRFToken(request);

    if (!StringUtils.equals(clientToken, serverToken)) {
        throw new RequestProcessAdviceException(exception);
    }
}

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

/**
 * Updates user profiles./*from w ww.j  a v a 2  s  . c  om*/
 *
 * @param context the specified context
 * @param request the specified request
 * @param response the specified response
 * @throws Exception exception
 */
@RequestProcessing(value = "/settings/profiles", method = HTTPRequestMethod.POST)
@Before(adviceClass = { LoginCheck.class, CSRFCheck.class, UpdateProfilesValidation.class })
public void updateProfiles(final HTTPRequestContext context, final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    context.renderJSON();

    final JSONObject requestJSONObject = (JSONObject) request.getAttribute(Keys.REQUEST);

    final String userRealName = requestJSONObject.optString(UserExt.USER_REAL_NAME);
    final String userTags = requestJSONObject.optString(UserExt.USER_TAGS);
    final String userURL = requestJSONObject.optString(User.USER_URL);
    final String userQQ = requestJSONObject.optString(UserExt.USER_QQ);
    final String userIntro = requestJSONObject.optString(UserExt.USER_INTRO);
    final String userAvatarURL = requestJSONObject.optString(UserExt.USER_AVATAR_URL);
    final String userTeam = requestJSONObject.optString(UserExt.USER_TEAM);
    final boolean userJoinPointRank = requestJSONObject.optBoolean(UserExt.USER_JOIN_POINT_RANK);
    final boolean userJoinUsedPointRank = requestJSONObject.optBoolean(UserExt.USER_JOIN_USED_POINT_RANK);

    final JSONObject user = userQueryService.getCurrentUser(request);

    user.put(UserExt.USER_REAL_NAME, userRealName);
    user.put(UserExt.USER_TAGS, userTags);
    user.put(User.USER_URL, userURL);
    user.put(UserExt.USER_QQ, userQQ);
    user.put(UserExt.USER_INTRO, userIntro.replace("<", "&lt;").replace(">", "&gt"));
    user.put(UserExt.USER_AVATAR_TYPE, UserExt.USER_AVATAR_TYPE_C_UPLOAD);
    user.put(UserExt.USER_TEAM, userTeam);
    user.put(UserExt.USER_JOIN_POINT_RANK,
            userJoinPointRank ? UserExt.USER_JOIN_POINT_RANK_C_JOIN : UserExt.USER_JOIN_POINT_RANK_C_NOT_JOIN);
    user.put(UserExt.USER_JOIN_USED_POINT_RANK, userJoinUsedPointRank ? UserExt.USER_JOIN_USED_POINT_RANK_C_JOIN
            : UserExt.USER_JOIN_USED_POINT_RANK_C_NOT_JOIN);

    if (Symphonys.getBoolean("qiniu.enabled")) {
        if (!StringUtils.startsWith(userAvatarURL, Symphonys.get("qiniu.domain"))) {
            user.put(UserExt.USER_AVATAR_URL, Symphonys.get("defaultThumbnailURL"));
        } else {
            user.put(UserExt.USER_AVATAR_URL, Symphonys.get("qiniu.domain") + "/avatar/"
                    + user.optString(Keys.OBJECT_ID) + "?" + new Date().getTime());
        }
    } else {
        user.put(UserExt.USER_AVATAR_URL, userAvatarURL);
    }

    try {
        userMgmtService.updateProfiles(user);

        context.renderTrueResult();
    } catch (final ServiceException e) {
        context.renderMsg(e.getMessage());
    }
}

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

/**
 * Converts the specified markdown text to HTML.
 *
 * @param markdownText the specified markdown text
 * @return converted HTML, returns an empty string "" if the specified markdown text is "" or {@code null}, returns
 * 'markdownErrorLabel' if exception/* w w w  . j  ava  2  s  . c  o m*/
 */
public static String toHTML(final String markdownText) {
    if (Strings.isEmptyOrNull(markdownText)) {
        return "";
    }

    final String cachedHTML = getHTML(markdownText);
    if (null != cachedHTML) {
        return cachedHTML;
    }

    final ExecutorService pool = Executors.newSingleThreadExecutor();
    final long[] threadId = new long[1];

    final Callable<String> call = () -> {
        threadId[0] = Thread.currentThread().getId();

        String html = LANG_PROPS_SERVICE.get("contentRenderFailedLabel");

        if (MARKED_AVAILABLE) {
            html = toHtmlByMarked(markdownText);
            if (!StringUtils.startsWith(html, "<p>")) {
                html = "<p>" + html + "</p>";
            }
        } else {
            com.vladsch.flexmark.ast.Node document = PARSER.parse(markdownText);
            html = RENDERER.render(document);
            if (!StringUtils.startsWith(html, "<p>")) {
                html = "<p>" + html + "</p>";
            }
        }

        final Document doc = Jsoup.parse(html);
        final List<org.jsoup.nodes.Node> toRemove = new ArrayList<>();
        doc.traverse(new NodeVisitor() {
            @Override
            public void head(final org.jsoup.nodes.Node node, int depth) {
                if (node instanceof org.jsoup.nodes.TextNode) {
                    final org.jsoup.nodes.TextNode textNode = (org.jsoup.nodes.TextNode) node;
                    final org.jsoup.nodes.Node parent = textNode.parent();

                    if (parent instanceof Element) {
                        final Element parentElem = (Element) parent;

                        if (!parentElem.tagName().equals("code")) {
                            String text = textNode.getWholeText();
                            boolean nextIsBr = false;
                            final org.jsoup.nodes.Node nextSibling = textNode.nextSibling();
                            if (nextSibling instanceof Element) {
                                nextIsBr = "br".equalsIgnoreCase(((Element) nextSibling).tagName());
                            }

                            if (null != userQueryService) {
                                try {
                                    final Set<String> userNames = userQueryService.getUserNames(text);
                                    for (final String userName : userNames) {
                                        text = text.replace('@' + userName + (nextIsBr ? "" : " "),
                                                "@<a href='" + Latkes.getServePath() + "/member/" + userName
                                                        + "'>" + userName + "</a> ");
                                    }
                                    text = text.replace("@participants ",
                                            "@<a href='https://hacpai.com/article/1458053458339' class='ft-red'>participants</a> ");
                                } finally {
                                    JdbcRepository.dispose();
                                }
                            }

                            if (text.contains("@<a href=")) {
                                final List<org.jsoup.nodes.Node> nodes = Parser.parseFragment(text, parentElem,
                                        "");
                                final int index = textNode.siblingIndex();

                                parentElem.insertChildren(index, nodes);
                                toRemove.add(node);
                            } else {
                                textNode.text(Pangu.spacingText(text));
                            }
                        }
                    }
                }
            }

            @Override
            public void tail(org.jsoup.nodes.Node node, int depth) {
            }
        });

        toRemove.forEach(node -> node.remove());

        doc.select("pre>code").addClass("hljs");
        doc.select("a").forEach(a -> {
            String src = a.attr("href");
            if (!StringUtils.startsWithIgnoreCase(src, Latkes.getServePath())) {
                try {
                    src = URLEncoder.encode(src, "UTF-8");
                } catch (final Exception e) {
                }
                a.attr("href", Latkes.getServePath() + "/forward?goto=" + src);
                a.attr("target", "_blank");
            }
        });
        doc.outputSettings().prettyPrint(false);

        String ret = doc.select("body").html();
        ret = StringUtils.trim(ret);

        // cache it
        putHTML(markdownText, ret);

        return ret;
    };

    Stopwatchs.start("Md to HTML");
    try {
        final Future<String> future = pool.submit(call);

        return future.get(MD_TIMEOUT, TimeUnit.MILLISECONDS);
    } catch (final TimeoutException e) {
        LOGGER.log(Level.ERROR, "Markdown timeout [md=" + markdownText + "]");
        Callstacks.printCallstack(Level.ERROR, new String[] { "org.b3log" }, null);

        final Set<Thread> threads = Thread.getAllStackTraces().keySet();
        for (final Thread thread : threads) {
            if (thread.getId() == threadId[0]) {
                thread.stop();

                break;
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Markdown failed [md=" + markdownText + "]", e);
    } finally {
        pool.shutdownNow();

        Stopwatchs.end();
    }

    return LANG_PROPS_SERVICE.get("contentRenderFailedLabel");
}

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

/**
 * Initializes QQ client.//from w  w w . ja v  a2  s .  com
 */
public void initQQClient() {
    LOGGER.info("??");

    xiaoV = new SmartQQClient(new MessageCallback() {
        @Override
        public void onMessage(final Message message) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(500 + RandomUtils.nextInt(1000));

                        final String content = message.getContent();
                        final String key = XiaoVs.getString("qq.bot.key");
                        if (!StringUtils.startsWith(content, key)) { // ?????
                            // ??
                            xiaoV.sendMessageToFriend(message.getUserId(), XIAO_V_INTRO);

                            return;
                        }

                        final String msg = StringUtils.substringAfter(content, key);
                        LOGGER.info("Received admin message: " + msg);
                        sendToPushQQGroups(msg);
                    } catch (final Exception e) {
                        LOGGER.log(Level.ERROR, "XiaoV on group message error", e);
                    }
                }
            }).start();
        }

        @Override
        public void onGroupMessage(final GroupMessage message) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(500 + RandomUtils.nextInt(1000));

                        onQQGroupMessage(message);
                    } catch (final Exception e) {
                        LOGGER.log(Level.ERROR, "XiaoV on group message error", e);
                    }
                }
            }).start();
        }

        @Override
        public void onDiscussMessage(final DiscussMessage message) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(500 + RandomUtils.nextInt(1000));

                        onQQDiscussMessage(message);
                    } catch (final Exception e) {
                        LOGGER.log(Level.ERROR, "XiaoV on group message error", e);
                    }
                }
            }).start();
        }
    });

    // Load groups & disscusses
    reloadGroups();
    reloadDiscusses();

    LOGGER.info("??");

    if (MSG_ACK_ENABLED) { // ???
        LOGGER.info("??https://github.com/b3log/xiaov/issues/3");

        xiaoVListener = new SmartQQClient(new MessageCallback() {
            @Override
            public void onMessage(final Message message) {
                try {
                    Thread.sleep(500 + RandomUtils.nextInt(1000));
                    final String content = message.getContent();
                    final String key = XiaoVs.getString("qq.bot.key");
                    if (!StringUtils.startsWith(content, key)) { // ??
                        // ??
                        xiaoVListener.sendMessageToFriend(message.getUserId(), XIAO_V_LISTENER_INTRO);

                        return;
                    }

                    final String msg = StringUtils.substringAfter(content, key);
                    LOGGER.info("Received admin message: " + msg);
                    sendToPushQQGroups(msg);
                } catch (final Exception e) {
                    LOGGER.log(Level.ERROR, "XiaoV on group message error", e);
                }
            }

            @Override
            public void onGroupMessage(final GroupMessage message) {
                final String content = message.getContent();

                if (GROUP_SENT_MSGS.contains(content)) { // indicates message received
                    GROUP_SENT_MSGS.remove(content);
                }
            }

            @Override
            public void onDiscussMessage(final DiscussMessage message) {
                final String content = message.getContent();

                if (DISCUSS_SENT_MSGS.contains(content)) { // indicates message received
                    DISCUSS_SENT_MSGS.remove(content);
                }
            }
        });

        LOGGER.info("??");
    }

    LOGGER.info("? QQ ??");
}

From source file:org.bigmouth.nvwa.zookeeper.config.ZkPropertyPlaceholderConfigurer.java

private Properties convert(byte[] data) {
    Properties properties = new Properties();
    String string = null;//from www.  ja v  a 2 s  . c om
    try {
        string = new String(data, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        string = new String(data);
    }

    if (StringUtils.isNotBlank(string)) {
        String[] items = StringUtils.split(string, ITEM_SPLIT);
        for (String item : items) {
            if (StringUtils.isBlank(item)) {
                continue;
            }
            if (StringUtils.startsWith(item, "#")) {
                continue;
            }
            int index = StringUtils.indexOf(item, PROPERTY_SPLIT);
            String key = StringUtils.substring(item, 0, index);
            String value = StringUtils.substring(item, index + 1);
            properties.put(StringUtils.trim(key), StringUtils.trim(value));
        }
    }
    return properties;
}