Example usage for org.jsoup.safety Whitelist none

List of usage examples for org.jsoup.safety Whitelist none

Introduction

In this page you can find the example usage for org.jsoup.safety Whitelist none.

Prototype

public static Whitelist none() 

Source Link

Document

This whitelist allows only text nodes: all HTML will be stripped.

Usage

From source file:com.lloydtorres.stately.helpers.SparkleHelper.java

/**
 * Basic HTML formatter that returns a styled version of the string.
 * @param content Target content//  www .  jav  a2s . c  om
 * @return Styled spanned object
 */
public static Spanned getHtmlFormatting(String content) {
    String holder = Jsoup.clean(content, Whitelist.none().addTags("br"));
    holder = holder.replace("'", "'");
    holder = holder.replace("&", "&");
    return fromHtml(holder);
}

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

/**
 * Shows opensearch.xml./*from w  w w .j  av  a 2s  .  com*/
 *
 * @param context the specified context
 */
@RequestProcessing(value = "/opensearch.xml", method = HttpMethod.GET)
public void showOpensearchXML(final RequestContext context) {
    final TextXmlRenderer renderer = new TextXmlRenderer();
    context.setRenderer(renderer);

    try {
        final InputStream resourceAsStream = SearchProcessor.class.getResourceAsStream("/opensearch.xml");
        String content = IOUtils.toString(resourceAsStream, "UTF-8");
        final JSONObject preference = preferenceQueryService.getPreference();
        content = StringUtils.replace(content, "${blogTitle}",
                Jsoup.clean(preference.optString(Option.ID_C_BLOG_TITLE), Whitelist.none()));
        content = StringUtils.replace(content, "${blogSubtitle}",
                Jsoup.clean(preference.optString(Option.ID_C_BLOG_SUBTITLE), Whitelist.none()));
        content = StringUtils.replace(content, "${servePath}", Latkes.getServePath());

        renderer.setContent(content);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Shows opensearch.xml failed", e);
    }
}

From source file:org.b3log.symphony.event.CommentUpdateNotifier.java

@Override
public void action(final Event<JSONObject> event) throws EventException {
    final JSONObject data = event.getData();
    LOGGER.log(Level.TRACE, "Processing an event [type={0}, data={1}]", event.getType(), data);

    try {//from w w w  . j a  v a2s .  c o m
        final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE);
        final JSONObject originalComment = data.getJSONObject(Comment.COMMENT);

        final boolean isDiscussion = originalArticle
                .optInt(Article.ARTICLE_TYPE) == Article.ARTICLE_TYPE_C_DISCUSSION;
        if (isDiscussion) {
            return;
        }

        if (Comment.COMMENT_ANONYMOUS_C_PUBLIC != originalComment.optInt(Comment.COMMENT_ANONYMOUS)) {
            return;
        }

        final String commenterId = originalComment.optString(Comment.COMMENT_AUTHOR_ID);
        final JSONObject commenter = userQueryService.getUser(commenterId);
        final String commenterName = commenter.optString(User.USER_NAME);
        final String commentContent = originalComment.optString(Comment.COMMENT_CONTENT);

        String cc = shortLinkQueryService.linkArticle(commentContent);
        cc = shortLinkQueryService.linkTag(cc);
        cc = Emotions.convert(cc);
        cc = Markdowns.toHTML(cc);
        cc = Markdowns.clean(cc, "");

        // Timeline
        String articleTitle = Jsoup.parse(originalArticle.optString(Article.ARTICLE_TITLE)).text();
        articleTitle = Emotions.convert(articleTitle);
        final String articlePermalink = Latkes.getServePath()
                + originalArticle.optString(Article.ARTICLE_PERMALINK);

        final JSONObject timeline = new JSONObject();
        timeline.put(Common.USER_ID, commenterId);
        timeline.put(Common.TYPE, Comment.COMMENT);
        String content = langPropsService.get("timelineCommentUpdateLabel");
        content = content.replace("{user}", "<a target='_blank' rel='nofollow' href='" + Latkes.getServePath()
                + "/member/" + commenterName + "'>" + commenterName + "</a>");
        content = content
                .replace("{article}", "<a target='_blank' rel='nofollow' href='" + articlePermalink + "'>"
                        + articleTitle + "</a>")
                .replace("{comment}", cc.replaceAll("<p>", "").replaceAll("</p>", ""));

        content = Jsoup.clean(content, Whitelist.none().addAttributes("a", "href", "rel", "target"));
        timeline.put(Common.CONTENT, content);

        if (StringUtils.isNotBlank(content)) {
            timelineMgmtService.addTimeline(timeline);
        }
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Sends the comment update notification failed", e);
    }
}

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

/**
 * Gets article preview content./*from  w  w w. j  av  a  2  s . c  o  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.CommentQueryService.java

/**
 * Gets the latest comments with the specified fetch size.
 *
 * <p>/*from   w  w  w  .jav a 2 s . c o m*/
 * The returned comments content is plain text.
 * </p>
 *
 * @param fetchSize the specified fetch size
 * @return the latest comments, returns an empty list if not found
 * @throws ServiceException service exception
 */
public List<JSONObject> getLatestComments(final int fetchSize) throws ServiceException {
    final Query query = new Query().addSort(Comment.COMMENT_CREATE_TIME, SortDirection.DESCENDING)
            .setCurrentPageNum(1).setPageSize(fetchSize).setPageCount(1);
    try {
        final JSONObject result = commentRepository.get(query);
        final List<JSONObject> ret = CollectionUtils
                .<JSONObject>jsonArrayToList(result.optJSONArray(Keys.RESULTS));

        for (final JSONObject comment : ret) {
            comment.put(Comment.COMMENT_CREATE_TIME, comment.optLong(Comment.COMMENT_CREATE_TIME));
            final String articleId = comment.optString(Comment.COMMENT_ON_ARTICLE_ID);
            final JSONObject article = articleRepository.get(articleId);
            comment.put(Comment.COMMENT_T_ARTICLE_TITLE,
                    Emotions.clear(article.optString(Article.ARTICLE_TITLE)));
            comment.put(Comment.COMMENT_T_ARTICLE_PERMALINK, article.optString(Article.ARTICLE_PERMALINK));

            final String commenterId = comment.optString(Comment.COMMENT_AUTHOR_ID);
            final JSONObject commenter = userRepository.get(commenterId);

            if (UserExt.USER_STATUS_C_INVALID == commenter.optInt(UserExt.USER_STATUS)
                    || Comment.COMMENT_STATUS_C_INVALID == comment.optInt(Comment.COMMENT_STATUS)) {
                comment.put(Comment.COMMENT_CONTENT, langPropsService.get("commentContentBlockLabel"));
            }

            if (Article.ARTICLE_TYPE_C_DISCUSSION == article.optInt(Article.ARTICLE_TYPE)) {
                comment.put(Comment.COMMENT_CONTENT, "....");
            }

            String content = comment.optString(Comment.COMMENT_CONTENT);
            content = Emotions.clear(content);
            content = Jsoup.clean(content, Whitelist.none());
            if (StringUtils.isBlank(content)) {
                comment.put(Comment.COMMENT_CONTENT, "....");
            } else {
                comment.put(Comment.COMMENT_CONTENT, content);
            }

            final String commenterEmail = comment.optString(Comment.COMMENT_AUTHOR_EMAIL);
            final String avatarURL = avatarQueryService.getAvatarURL(commenterEmail);
            commenter.put(UserExt.USER_AVATAR_URL, avatarURL);

            comment.put(Comment.COMMENT_T_COMMENTER, commenter);
        }

        return ret;
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Gets user comments failed", e);
        throw new ServiceException(e);
    }
}

From source file:org.eclipse.skalli.commons.HtmlUtils.java

/**
 * Returns <code>true</code> if the  given string contains any HTML tags.
 *
 * @param s  the string to check./*from   ww w . j a  va2  s.co  m*/
 */
public static boolean containsTags(String s) {
    if (StringUtils.isBlank(s)) {
        return false;
    }
    return !Jsoup.isValid(s, Whitelist.none());
}

From source file:org.eclipse.skalli.core.extension.ProjectDescriptionValidator.java

@SuppressWarnings("nls")
@Override//ww w  .jav a 2 s  .c  om
public SortedSet<Issue> validate(UUID entity, ExtensionEntityBase extension, Severity minSeverity) {
    SortedSet<Issue> issues = new TreeSet<Issue>();
    Project project = (Project) extension;

    String description = project.getDescription();
    if (description == null) {
        description = StringUtils.EMPTY;
    }

    Whitelist whitelist = null;
    String fatalMessage = null;
    String format = project.getDescriptionFormat();
    if ("html".equals(format)) {
        whitelist = HtmlUtils.getWhiteList();
        fatalMessage = TXT_ALLOWED_TAGS;
    } else {
        whitelist = Whitelist.none();
        fatalMessage = TXT_NO_TAGS_ALLOWED;
    }
    if (!Jsoup.isValid(description, whitelist)) {
        issues.add(newIssue(Severity.FATAL, entity, fatalMessage));
    }

    if (Severity.WARNING.compareTo(minSeverity) <= 0 && StringUtils.isBlank(description)) {
        issues.add(newIssue(Severity.WARNING, entity, TXT_DESCRIPTION_EMPTY));
    } else {
        int descriptionLength = description.length();
        if (Severity.INFO.compareTo(minSeverity) <= 0 && descriptionLength < DESCRIPTION_RECOMMENDED_LENGHT) {
            issues.add(newIssue(Severity.INFO, entity, TXT_DESCRIPTION_SHORT));
        }
    }

    return issues;
}

From source file:org.openecomp.sdc.common.util.ValidationUtils.java

public static String removeHtmlTags(String str) {
    return Jsoup.clean(str, Whitelist.none());
}

From source file:util.Seeks.java

/**
 * Performs a query to a Seeks server. The query must be natural text. 
 * The query will get UTF-8 encoded an embedded in a search URL to a random
 * Seeks server. In case of an unresponsive Seeks server, it will retry to
 * query (other) Seeks server./*from   w w w . j a v  a 2 s  .  co  m*/
 **/
public List<SeeksForm> search(final String query) {

    // http://seeks-project.info/wiki/index.php/API-0.4.0

    final List<SeeksForm> result = new ArrayList<SeeksForm>();
    final List<SeeksForm> firstPriority = new ArrayList<SeeksForm>();
    final List<SeeksForm> secondPriority = new ArrayList<SeeksForm>();
    final List<SeeksForm> thirdPriority = new ArrayList<SeeksForm>();

    // List of randomly shuffled numbers between a min and max. Contains no duplicates.
    final ListIterator<Integer> shuffledNumbers = getRandomNumber(0,
            ReadSystemConfigurations.getSeeksServer().length);

    // read in the first server from randomly shuffled list
    int nextServerNumber = shuffledNumbers.next();

    try {

        final Http http = new Http();
        String json = null;
        int maxRetry = 0;

        // repeat requests until we get a response or reach the max number of retries
        while ((json == null || "".equals(json)) && maxRetry < 2) {
            json = http.getContent(composeSearch(query, nextServerNumber), Connect.TIMEOUT_3.getValue(),
                    Connect.TRIES_1.getValue(), "utf-8");
            maxRetry++;
            // use next server if there are more, if not reuse existing server.
            if (shuffledNumbers.hasNext()) {
                nextServerNumber = shuffledNumbers.next();
            }
        }

        // we still may get back a null/empty answer
        if (json != null && !"".equals(json)) {

            final JsonElement jsonRoot = new JsonParser().parse(json);

            final JsonArray jsonSnippets = jsonRoot.getAsJsonObject().getAsJsonArray("snippets");

            for (final JsonElement jsonElement : jsonSnippets) {
                final SeeksForm record = new SeeksForm();
                // we should always have an ID
                record.setId(jsonElement.getAsJsonObject().get("id").getAsString());
                // we should always have a title
                record.setTitle(org.apache.commons.lang.StringEscapeUtils.unescapeHtml(Jsoup
                        .clean(jsonElement.getAsJsonObject().get("title").getAsString(), Whitelist.none()))); // clean possible HTML entities
                // we should always have an URL
                record.setUrl(jsonElement.getAsJsonObject().get("url").getAsString());
                // type may be null
                if (jsonElement.getAsJsonObject().get("type") != null) {
                    record.setType(jsonElement.getAsJsonObject().get("type").getAsString());
                }
                // summary may be null
                if (jsonElement.getAsJsonObject().get("summary") != null) {
                    record.setSummary(jsonElement.getAsJsonObject().get("summary").getAsString());
                }

                // improving existing relevance sorting
                if ("file".equals(record.getType()) && compareTitle(record, query)) {
                    firstPriority.add(record);
                } else if (compareTitle(record, query)) {
                    secondPriority.add(record);
                } else {
                    thirdPriority.add(record);
                }
            }
        }

    } catch (final Exception e) {
        LOG.error(e.toString());
    } finally {
        // create order:
        // type "file" and matching title
        result.addAll(firstPriority);
        // matching title
        result.addAll(secondPriority);
        // the rest
        result.addAll(thirdPriority);
    }

    return result;
}