Example usage for org.apache.commons.lang3 StringEscapeUtils unescapeHtml4

List of usage examples for org.apache.commons.lang3 StringEscapeUtils unescapeHtml4

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringEscapeUtils unescapeHtml4.

Prototype

public static final String unescapeHtml4(final String input) 

Source Link

Document

Unescapes a string containing entity escapes to a string containing the actual Unicode characters corresponding to the escapes.

Usage

From source file:org.lockss.plugin.RegistryArchivalUnit.java

String recomputeRegName() {
    if (!isStarted()) {
        // This can get invoked (seveeral times, mostly from logging) before
        // enough mechanism has started to make it possible to resolve the CuUrl
        // below.
        return null;
    }/*  w w  w .j a  v a2  s .c om*/
    try {
        CachedUrl cu = makeCachedUrl(m_registryUrl);
        if (cu == null)
            return null;
        URL cuUrl = CuUrl.fromCu(cu);
        Parser parser = new Parser(cuUrl.toString());
        NodeList nodelst = parser.extractAllNodesThatMatch(new NodeClassFilter(TitleTag.class));
        Node nodes[] = nodelst.toNodeArray();
        recomputeRegName = false;
        if (nodes.length < 1)
            return null;
        // Get the first title found
        TitleTag tag = (TitleTag) nodes[0];
        if (tag == null)
            return null;
        return StringEscapeUtils.unescapeHtml4(tag.getTitle());
    } catch (MalformedURLException e) {
        log.warning("recomputeRegName", e);
        return null;
    } catch (ParserException e) {
        if (e.getThrowable() instanceof FileNotFoundException) {
            log.warning("recomputeRegName: " + e.getThrowable().toString());
        } else {
            log.warning("recomputeRegName", e);
        }
        return null;
    }
}

From source file:org.lockss.servlet.ServeContent.java

/**
 * Handle a request// ww w.ja  v  a 2s. c  o  m
 * @throws IOException
 */
public void lockssHandleRequest() throws IOException {
    if (!pluginMgr.areAusStarted()) {
        displayNotStarted();
        return;
    }
    accessLogInfo = null;

    enabledPluginsOnly = !"no".equalsIgnoreCase(getParameter("filterPlugins"));

    url = getParameter("url");
    String auid = getParameter("auid");
    versionStr = getParameter("version");

    au = explicitAu = null; // redundant, just making sure

    if (!StringUtil.isNullString(url)) {
        if (StringUtil.isNullString(auid)) {
            if (isMementoRequest()) {

                // Error, because Memento requests must have auid.
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Requests containing a \"version\" parameter must also include "
                                + "\"auid\" and \"url\" parameters; \"auid\" is missing.");
                return;
            }
        } else {
            explicitAu = pluginMgr.getAuFromId(auid);
            au = explicitAu;
        }
        if (log.isDebug2())
            log.debug2("Url req, raw: " + url);
        // handle html-encoded URLs with characters like &amp;
        // that can appear as links embedded in HTML pages
        url = StringEscapeUtils.unescapeHtml4(url);
        requestType = AccessLogType.Url;
        //this is a partial replicate of proxy_handler post logic here
        if (HttpRequest.__POST.equals(req.getMethod()) && processForms) {
            log.debug2("POST request found!");
            FormUrlHelper helper = new FormUrlHelper(url.toString());
            Enumeration en = req.getParameterNames();
            while (en.hasMoreElements()) {
                String name = (String) en.nextElement();
                // filter out LOCKSS specific params
                if (!"url".equals(name) && !"auid".equals(name) && !"version".equals(name)) {
                    String vals[] = req.getParameterValues(name);
                    for (String val : vals) {
                        helper.add(name, val);
                    }
                }
            }
            helper.sortKeyValues();
            org.mortbay.util.URI postUri = new org.mortbay.util.URI(helper.toEncodedString());
            // We only want to override the post request by proxy if we cached it during crawling.
            CachedUrl cu = pluginMgr.findCachedUrl(postUri.toString());
            if (cu != null) {
                url = postUri.toString();
                if (log.isDebug2())
                    log.debug2("Setting url to:" + url);
            }
        }
        if (minimallyEncodeUrl) {
            String unencUrl = url;
            url = UrlUtil.minimallyEncodeUrl(url);
            if (!url.equals(unencUrl)) {
                log.debug2("Encoded " + unencUrl + " to " + url);
            }
        }
        if (normalizeUrl) {
            String normUrl;
            if (au != null) {
                try {
                    normUrl = UrlUtil.normalizeUrl(url, au);
                } catch (PluginBehaviorException e) {
                    log.warning("Couldn't site-normalize URL: " + url, e);
                    normUrl = UrlUtil.normalizeUrl(url);
                }
            } else {
                normUrl = UrlUtil.normalizeUrl(url);
            }
            if (normUrl != url) {
                log.debug2("Normalized " + url + " to " + normUrl);
                url = normUrl;
            }
        }
        handleUrlRequest();
        return;
    }

    /*
     * Memento requests must provide URL; OpenURL requests are not Memento
     * requests, and vice versa.
     */
    if (isMementoRequest()) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "Requests containing a \"version\" parameter must also include "
                        + "\"auid\" and \"url\" parameters.");
        return;
    }

    // perform special handling for an OpenUrl
    try {
        OpenUrlInfo resolved = OpenUrlResolver.noOpenUrlInfo;

        // If any params, pass them all to OpenUrl resolver
        Map<String, String> pmap = getParamsAsMap();
        if (!pmap.isEmpty()) {
            if (log.isDebug3())
                log.debug3("Resolving OpenUrl: " + pmap);
            resolved = openUrlResolver.resolveOpenUrl(pmap);
            requestType = AccessLogType.OpenUrl;
        }

        // if there are multiple results, present choices
        if (resolved.size() > 1) {
            handleMultiOpenUrlInfo(resolved);
            return;
        }

        // if there is only one result, present it
        url = resolved.getResolvedUrl();
        if ((url != null) || (resolved.getResolvedTo() != ResolvedTo.NONE)) {
            // record type of access for logging
            accessLogInfo = resolved.getResolvedTo().toString();
            handleOpenUrlInfo(resolved);
            return;
        }

        // redirect to the OpenURL corresponding to the specified auid;
        // ensures that the corresponding OpenURL is available to the client.
        if (auid != null) {
            String openUrlQueryString = openUrlResolver.getOpenUrlQueryForAuid(auid);
            if (openUrlQueryString != null) {
                StringBuffer sb = req.getRequestURL();
                sb.append("?");
                sb.append(openUrlQueryString);
                resp.sendRedirect(sb.toString());
                return;
            }
            // If open URL resultion fails fall back to first start page
            au = pluginMgr.getAuFromId(auid);
            if (au != null) {
                Collection<String> starts = au.getStartUrls();
                if (!starts.isEmpty()) {
                    url = starts.iterator().next();
                    handleUrlRequest();
                    return;
                }
            }
        }

        log.debug3("Unknown request");
    } catch (RuntimeException ex) {
        log.warning("Couldn't handle unknown request", ex);
    }
    // Maybe should display a message here if URL is unknown format.  But
    // this is also the default case for the bare ServeContent URL, which
    // should generate an index with no message.
    displayIndexPage();
    requestType = AccessLogType.None;
    logAccess("200 index page");
}

From source file:org.lol.reddit.fragments.CommentListingFragment.java

@Override
public void onCommentListingRequestPostDownloaded(final RedditPreparedPost post) {

    final Context context = getSupportActivity();

    if (mPost == null) {

        mPost = post;// w  ww  .  j  a va 2s  .  c o m

        final RedditPostHeaderView postHeader = new RedditPostHeaderView(getSupportActivity(),
                CommentListingFragment.this.mPost);
        listHeaderPost.addView(postHeader);

        if (post.parsedSelfText != null) {
            final ViewGroup selfText = post.parsedSelfText.buildView(getSupportActivity(), null,
                    14f * commentFontScale, mShowLinkButtons);
            selfText.setFocusable(false);
            selfText.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);

            final int paddingPx = General.dpToPixels(context, 10);
            listHeaderSelftext.addView(selfText);
            listHeaderSelftext.setPadding(paddingPx, paddingPx, paddingPx, paddingPx);
            listHeaderNotifications.setBackgroundColor(Color.argb(35, 128, 128, 128));
        }

        if (!General.isTablet(context, PreferenceManager.getDefaultSharedPreferences(context))) {
            getSupportActivity().getSupportActionBar().setTitle(StringEscapeUtils.unescapeHtml4(post.title));
        }
    }
}

From source file:org.lol.reddit.fragments.CommentListingFragment.java

@Override
public boolean onContextItemSelected(MenuItem item) {

    final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

    if (info.position <= 0) {
        return false;
    }//from   w  ww  .j  a  v a  2  s .  co m

    final Object selectedObject = lv.getAdapter().getItem(info.position);

    if (!(selectedObject instanceof RedditCommentListItem)
            || !((RedditCommentListItem) selectedObject).isComment()) {
        return false;
    }

    final Action action = Action.values()[item.getItemId()];
    final RedditPreparedComment comment = ((RedditCommentListItem) selectedObject).asComment();

    switch (action) {

    case UPVOTE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.UPVOTE);
        break;

    case DOWNVOTE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.DOWNVOTE);
        break;

    case UNVOTE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.UNVOTE);
        break;

    case SAVE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.SAVE);
        break;

    case UNSAVE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.UNSAVE);
        break;

    case REPORT:

        new AlertDialog.Builder(getSupportActivity()).setTitle(R.string.action_report)
                .setMessage(R.string.action_report_sure)
                .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        comment.action(getSupportActivity(), RedditAPI.RedditAction.REPORT);
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();

        break;

    case REPLY: {
        final Intent intent = new Intent(getSupportActivity(), CommentReplyActivity.class);
        intent.putExtra("parentIdAndType", comment.idAndType);
        startActivity(intent);
        break;
    }

    case EDIT: {
        final Intent intent = new Intent(getSupportActivity(), CommentEditActivity.class);
        intent.putExtra("commentIdAndType", comment.idAndType);
        intent.putExtra("commentText", StringEscapeUtils.unescapeHtml4(comment.src.body));
        startActivity(intent);
        break;
    }

    case COMMENT_LINKS:
        final HashSet<String> linksInComment = comment.computeAllLinks();

        if (linksInComment.isEmpty()) {
            General.quickToast(getSupportActivity(), R.string.error_toast_no_urls_in_comment);

        } else {

            final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]);

            final AlertDialog.Builder builder = new AlertDialog.Builder(getSupportActivity());
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(getSupportActivity(), linksArr[which], false);
                    dialog.dismiss();
                }
            });

            final AlertDialog alert = builder.create();
            alert.setTitle(R.string.action_comment_links);
            alert.setCanceledOnTouchOutside(true);
            alert.show();
        }

        break;

    case SHARE:

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comment by " + comment.src.author + " on Reddit");

        // TODO this currently just dumps the markdown
        mailer.putExtra(Intent.EXTRA_TEXT, StringEscapeUtils.unescapeHtml4(comment.src.body));
        startActivityForResult(
                Intent.createChooser(mailer, getSupportActivity().getString(R.string.action_share)), 1);

        break;

    case COPY:

        ClipboardManager manager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        // TODO this currently just dumps the markdown
        manager.setText(StringEscapeUtils.unescapeHtml4(comment.src.body));
        break;

    case COLLAPSE:
        if (comment.getBoundView() != null) {
            handleCommentVisibilityToggle(comment.getBoundView());
        } else {
            General.quickToast(getSupportActivity(), "Error: Comment is no longer visible.");
        }
        break;

    case USER_PROFILE:
        LinkHandler.onLinkClicked(getSupportActivity(), new UserProfileURL(comment.src.author).toString());
        break;

    case PROPERTIES:
        CommentPropertiesDialog.newInstance(comment.src).show(getSupportActivity());
        break;

    case GO_TO_COMMENT: {
        PostCommentListingURL url = new PostCommentListingURL(null, comment.src.link_id, comment.idAlone, null,
                null, null);
        LinkHandler.onLinkClicked(getSupportActivity(), url.toString());
        break;
    }

    case CONTEXT: {
        PostCommentListingURL url = new PostCommentListingURL(null, comment.src.link_id, comment.idAlone, 3,
                null, null);
        LinkHandler.onLinkClicked(getSupportActivity(), url.toString());
        break;
    }
    }

    return true;
}

From source file:org.lol.reddit.fragments.CommentPropertiesDialog.java

@Override
protected void prepare(Activity context, LinearLayout items) {

    final RedditComment comment = getArguments().getParcelable("comment");

    items.addView(propView(context, "ID", comment.name, false));

    items.addView(propView(context, R.string.props_author, comment.author, false));

    if (comment.author_flair_text != null && comment.author_flair_text.length() > 0) {
        items.addView(propView(context, R.string.props_author_flair, comment.author_flair_text, false));
    }/*from  w w  w  .  j  a  v  a2 s. c  o  m*/

    items.addView(propView(context, R.string.props_created,
            RRTime.formatDateTime(comment.created_utc * 1000, context), false));

    if (comment.edited instanceof Long) {
        items.addView(propView(context, R.string.props_edited,
                RRTime.formatDateTime((Long) comment.edited * 1000, context), false));
    } else {
        items.addView(propView(context, R.string.props_edited, R.string.props_never, false));
    }

    items.addView(propView(context, R.string.props_score, String.valueOf(comment.ups - comment.downs), false));

    items.addView(propView(context, R.string.props_subreddit, comment.subreddit, false));

    if (comment.body != null && comment.body.length() > 0) {
        items.addView(propView(context, R.string.props_body_markdown,
                StringEscapeUtils.unescapeHtml4(comment.body), false));
    }
}

From source file:org.lol.reddit.fragments.PostListingFragment.java

private void onSubredditReceived() {

    final String subtitle;

    if (postListingURL.getOrder() == null || postListingURL.getOrder() == PostListingController.Sort.HOT) {
        if (subreddit.subscribers == null) {
            subtitle = getString(R.string.header_subscriber_count_unknown);
        } else {//from ww  w  . j a va 2s  . c o m
            subtitle = NumberFormat.getNumberInstance(Locale.getDefault()).format(subreddit.subscribers) + " "
                    + getString(R.string.header_subscriber_count);
        }

    } else {
        subtitle = postListingURL.humanReadableUrl();
    }

    getSupportActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            setHeader(StringEscapeUtils.unescapeHtml4(subreddit.title), subtitle);
            getSupportActivity().invalidateOptionsMenu();
        }
    });

}

From source file:org.lol.reddit.fragments.PostPropertiesDialog.java

@Override
protected void prepare(Activity context, LinearLayout items) {

    final RedditPost post = getArguments().getParcelable("post");

    items.addView(// w  w w.  java  2s.  c o  m
            propView(context, R.string.props_title, StringEscapeUtils.unescapeHtml4(post.title.trim()), true));
    items.addView(propView(context, R.string.props_author, post.author, false));
    items.addView(propView(context, R.string.props_url, StringEscapeUtils.unescapeHtml4(post.url), false));
    items.addView(propView(context, R.string.props_created,
            RRTime.formatDateTime(post.created_utc * 1000, context), false));

    if (post.edited instanceof Long) {
        items.addView(propView(context, R.string.props_edited,
                RRTime.formatDateTime((Long) post.edited * 1000, context), false));
    } else {
        items.addView(propView(context, R.string.props_edited, R.string.props_never, false));
    }

    items.addView(propView(context, R.string.props_subreddit, post.subreddit, false));
    items.addView(propView(context, R.string.props_score, String.valueOf(post.score), false));
    items.addView(propView(context, R.string.props_num_comments, String.valueOf(post.num_comments), false));

    if (post.selftext != null && post.selftext.length() > 0) {
        items.addView(propView(context, R.string.props_self_markdown,
                StringEscapeUtils.unescapeHtml4(post.selftext), false));
    }
}

From source file:org.lol.reddit.reddit.prepared.RedditPreparedComment.java

public RedditPreparedComment(final Context context, final RedditComment comment, final long timestamp,
        final boolean needsUpdating, final RedditPreparedPost parentPost, final RedditAccount user,
        final EnumSet<PrefsUtility.AppearanceCommentHeaderItems> headerItems) {

    this.src = comment;
    this.parentPost = parentPost;
    this.headerItems = headerItems;

    // TODO custom time

    // TODO don't fetch these every time
    final TypedArray appearance = context.obtainStyledAttributes(new int[] { R.attr.rrCommentHeaderBoldCol,
            R.attr.rrCommentHeaderAuthorCol, R.attr.rrPostSubtitleUpvoteCol, R.attr.rrPostSubtitleDownvoteCol,
            R.attr.rrFlairBackCol, R.attr.rrFlairTextCol, R.attr.rrGoldBackCol, R.attr.rrGoldTextCol });

    rrCommentHeaderBoldCol = appearance.getColor(0, 255);
    rrCommentHeaderAuthorCol = appearance.getColor(1, 255);
    rrPostSubtitleUpvoteCol = appearance.getColor(2, 255);
    rrPostSubtitleDownvoteCol = appearance.getColor(3, 255);
    rrFlairBackCol = appearance.getColor(4, 0);
    rrFlairTextCol = appearance.getColor(5, 255);
    rrGoldBackCol = appearance.getColor(6, 0);
    rrGoldTextCol = appearance.getColor(7, 255);

    body = MarkdownParser.parse(StringEscapeUtils.unescapeHtml4(comment.body).toCharArray());
    if (comment.author_flair_text != null) {
        flair = StringEscapeUtils.unescapeHtml4(comment.author_flair_text);
    } else {// w  w  w .  j  a  v a 2 s.co m
        flair = null;
    }

    idAlone = comment.id;
    idAndType = comment.name;

    if (comment.likes == null) {
        voteDirection = 0;
    } else {
        voteDirection = Boolean.TRUE.equals(comment.likes) ? 1 : -1;
    }

    saved = Boolean.TRUE.equals(comment.saved);

    lastChange = timestamp;
    if (src.likes != null) {
        RedditChangeDataManager.getInstance(context).update(src.link_id, user, this, true);
    } else if (needsUpdating) {
        RedditChangeDataManager.getInstance(context).update(src.link_id, user, this, false);
    }

    rebuildHeader(context);
}

From source file:org.lol.reddit.reddit.prepared.RedditPreparedMessage.java

public RedditPreparedMessage(final Context context, final RedditMessage message, final long timestamp) {

    this.src = message;

    // TODO custom time

    final TypedArray appearance = context.obtainStyledAttributes(
            new int[] { R.attr.rrCommentHeaderBoldCol, R.attr.rrCommentHeaderAuthorCol, });

    int rrCommentHeaderBoldCol = appearance.getColor(0, 255);
    int rrCommentHeaderAuthorCol = appearance.getColor(1, 255);

    body = MarkdownParser.parse(StringEscapeUtils.unescapeHtml4(message.body).toCharArray());

    idAndType = message.name;/*from  ww  w.  jav  a 2 s  .c om*/

    final BetterSSB sb = new BetterSSB();

    if (src.author == null) {
        sb.append("[" + context.getString(R.string.general_unknown) + "]",
                BetterSSB.FOREGROUND_COLOR | BetterSSB.BOLD, rrCommentHeaderAuthorCol, 0, 1f);
    } else {
        sb.append(src.author, BetterSSB.FOREGROUND_COLOR | BetterSSB.BOLD, rrCommentHeaderAuthorCol, 0, 1f);
    }

    sb.append("   ", 0);
    sb.append(RRTime.formatDurationFrom(context, src.created_utc * 1000L),
            BetterSSB.FOREGROUND_COLOR | BetterSSB.BOLD, rrCommentHeaderBoldCol, 0, 1f);

    header = sb.get();
}

From source file:org.lol.reddit.reddit.prepared.RedditPreparedPost.java

public RedditPreparedPost(final Context context, final CacheManager cm, final int listId, final RedditPost post,
        final long timestamp, final boolean showSubreddit, final boolean updateNeeded,
        final boolean showThumbnails, final boolean precacheImages, final RedditAccount user,
        final boolean parseSelfText) {

    this.src = post;
    this.showSubreddit = showSubreddit;

    if (post.title == null) {
        title = "[null]";
    } else {/*from   w  w w. j  a  va  2s  .  com*/
        title = StringEscapeUtils.unescapeHtml4(post.title.replace('\n', ' ')).trim();
    }

    idAlone = post.id;
    idAndType = post.name;
    url = StringEscapeUtils.unescapeHtml4(post.url);
    commentCount = post.num_comments;

    if (post.likes == null) {
        voteDirection = 0;
    } else {
        voteDirection = Boolean.TRUE.equals(post.likes) ? 1 : -1;
    }

    this.saved = post.saved;
    this.hidden = post.hidden;
    this.stickied = post.stickied;

    imageUrl = LinkHandler.getImageUrl(url);
    thumbnailUrl = post.thumbnail;
    hasThumbnail = showThumbnails && (hasThumbnail(post) || imageUrl != null);

    // TODO parameterise
    final int thumbnailWidth = General.dpToPixels(context, 64);

    if (hasThumbnail && hasThumbnail(post)) {
        downloadThumbnail(context, thumbnailWidth, cm, listId, false);
    }

    if (imageUrl != null && precacheImages) {
        downloadThumbnail(context, thumbnailWidth, cm, listId, true);
    }

    // TODO precache comments (respect settings)

    lastChange = timestamp;
    if (voteDirection != 0 || saved || hidden) {
        RedditChangeDataManager.getInstance(context).update("posts", user, this, true);
    } else if (updateNeeded) {
        RedditChangeDataManager.getInstance(context).update("posts", user, this, false);
    }

    rebuildSubtitle(context);

    if (parseSelfText && src.is_self && src.selftext != null && src.selftext.trim().length() > 0) {
        parsedSelfText = MarkdownParser.parse(StringEscapeUtils.unescapeHtml4(post.selftext).toCharArray());
    } else {
        parsedSelfText = null;
    }
}