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:com.github.naoghuman.cm.model.matrix.MatrixModel.java

@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    this.setId(in.readLong());
    this.setGenerationTime(in.readLong());
    this.setTitle(StringEscapeUtils.unescapeHtml4(String.valueOf(in.readObject())));
    this.setDescription(StringEscapeUtils.unescapeHtml4(String.valueOf(in.readObject())));
}

From source file:com.wellsandwhistles.android.redditsp.reddit.api.RedditAPICommentAction.java

public static void onActionMenuItemSelected(final RedditRenderableComment renderableComment,
        final RedditCommentView commentView, final AppCompatActivity activity,
        final CommentListingFragment commentListingFragment, final RedditCommentAction action,
        final RedditChangeDataManager changeDataManager) {

    final RedditComment comment = renderableComment.getParsedComment().getRawComment();

    switch (action) {

    case UPVOTE:/* w w  w .  j  a v a  2 s.c om*/
        action(activity, comment, RedditAPI.ACTION_UPVOTE, changeDataManager);
        break;

    case DOWNVOTE:
        action(activity, comment, RedditAPI.ACTION_DOWNVOTE, changeDataManager);
        break;

    case UNVOTE:
        action(activity, comment, RedditAPI.ACTION_UNVOTE, changeDataManager);
        break;

    case SAVE:
        action(activity, comment, RedditAPI.ACTION_SAVE, changeDataManager);
        break;

    case UNSAVE:
        action(activity, comment, RedditAPI.ACTION_UNSAVE, changeDataManager);
        break;

    case REPORT:

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

        break;

    case REPLY: {
        final Intent intent = new Intent(activity, CommentReplyActivity.class);
        intent.putExtra(CommentReplyActivity.PARENT_ID_AND_TYPE_KEY, comment.getIdAndType());
        intent.putExtra(CommentReplyActivity.PARENT_MARKDOWN_KEY,
                StringEscapeUtils.unescapeHtml4(comment.body));
        activity.startActivity(intent);
        break;
    }

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

    case DELETE: {
        new AlertDialog.Builder(activity).setTitle(R.string.accounts_delete).setMessage(R.string.delete_confirm)
                .setPositiveButton(R.string.action_delete, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, final int which) {
                        action(activity, comment, RedditAPI.ACTION_DELETE, changeDataManager);
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();
        break;
    }

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

        if (linksInComment.isEmpty()) {
            General.quickToast(activity, 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(activity);
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(activity, 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.author + " on Reddit");

        // TODO this currently just dumps the markdown
        mailer.putExtra(Intent.EXTRA_TEXT, StringEscapeUtils.unescapeHtml4(comment.body) + "\r\n\r\n"
                + comment.getContextUrl().generateNonJsonUri().toString());

        activity.startActivityForResult(Intent.createChooser(mailer, activity.getString(R.string.action_share)),
                1);

        break;

    case COPY_TEXT: {
        ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        // TODO this currently just dumps the markdown
        manager.setText(StringEscapeUtils.unescapeHtml4(comment.body));
        break;
    }

    case COPY_URL: {
        ClipboardManager manager = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        // TODO this currently just dumps the markdown
        manager.setText(comment.getContextUrl().context(null).generateNonJsonUri().toString());
        break;
    }

    case COLLAPSE: {
        commentListingFragment.handleCommentVisibilityToggle(commentView);
        break;
    }

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

    case PROPERTIES:
        CommentPropertiesDialog.newInstance(comment).show(activity.getSupportFragmentManager(), null);
        break;

    case GO_TO_COMMENT: {
        LinkHandler.onLinkClicked(activity, comment.getContextUrl().context(null).toString());
        break;
    }

    case CONTEXT: {
        LinkHandler.onLinkClicked(activity, comment.getContextUrl().toString());
        break;
    }
    case ACTION_MENU:
        showActionMenu(activity, commentListingFragment, renderableComment, commentView, changeDataManager,
                comment.isArchived());
        break;

    case BACK:
        activity.onBackPressed();
        break;
    }
}

From source file:fr.mcc.ginco.rest.services.ImportRestService.java

/**
 * This method is called to import a SKOS thesaurus the @Produces({
 * MediaType.TEXT_HTML}) is no mistake : this rest service is used by an
 * ajax call and IE cannot display result if JSOn is returned
 *
 * @param body// ww  w .  java2 s.  c  o m
 * @param request
 * @return The imported thesaurus in JSOn string representig a
 * ExtJsonFormLoadData
 * @throws IOException
 */
@POST
@Path("/import")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_HTML)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String uploadFile(MultipartBody body, @Context HttpServletRequest request) throws IOException {
    Attachment file = body.getAttachment(ATTACHMENT_NAME);
    String content = file.getObject(String.class);
    String fileName = file.getDataHandler().getName();
    File tempdir = (File) servletContext.getAttribute("javax.servlet.context.tempdir");

    Map<Thesaurus, Set<Alignment>> importResult = skosImportService.importSKOSFile(content, fileName, tempdir);
    Thesaurus thesaurus = importResult.keySet().iterator().next();

    thesaurusIndexerService.indexThesaurus(thesaurus);

    ImportedThesaurusResponse response = new ImportedThesaurusResponse();
    response.setThesaurusTitle(thesaurus.getTitle());
    List<String> conceptsMissingAlignments = new ArrayList<String>();
    List<String> externalConceptIds = new ArrayList<String>();
    Set<Alignment> bannedAlignments = importResult.get(thesaurus);
    for (Alignment alignment : bannedAlignments) {
        conceptsMissingAlignments
                .add(thesaurusConceptService.getConceptLabel(alignment.getSourceConcept().getIdentifier()));
        externalConceptIds.add(alignment.getTargetConcepts().iterator().next().getExternalTargetConcept());
    }
    response.setConceptsMissingAlignments(conceptsMissingAlignments);
    response.setExternalConceptIds(externalConceptIds);
    ObjectMapper mapper = new ObjectMapper();
    String serialized = mapper.writeValueAsString(new ExtJsonFormLoadData(response));
    return StringEscapeUtils.unescapeHtml4(serialized);
}

From source file:com.github.naoghuman.cm.model.notes.NotesModel.java

@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    this.setId(in.readLong());
    this.setMatrixId(in.readLong());
    this.setGenerationTime(in.readLong());
    this.setNotes(StringEscapeUtils.unescapeHtml4(String.valueOf(in.readObject())));
}

From source file:com.kdmanalytics.toif.adaptor.SplintAdaptor.java

@Override
public ArrayList<Element> parse(File process, AdaptorOptions options, IFileResolver resolver,
        boolean[] validLines, boolean unknownCWE) throws ToifException {
    com.kdmanalytics.toif.framework.xmlElements.entities.File file = resolver.getDefaultFile();
    // new finding creator
    final FindingCreator creator = new FindingCreator(getProperties(), getAdaptorName(), unknownCWE);

    Scanner scanner = null;/* www. j a  va2  s.c  o  m*/
    try {
        scanner = new Scanner(new FileInputStream(process));
        // read from the csv file.
        while (scanner.hasNextLine()) {
            final String csvLine = scanner.nextLine();

            final String[] csvElements = csvLine.split(",");

            // Check if line is valid for parsing
            if (csvElements.length <= 2)
                continue;

            if ("preproc".equals(csvElements[2])) {
                continue;
            }
            // the first line of these csv files have the information of
            // what the values are. We dont need this.
            if ("Warning".equals(csvElements[0])) {
                continue;
            }

            if (csvElements.length < 8) {
                continue;
            }

            // continue if not same file.
            String csvFileName = new File(csvElements[4]).getName();
            String inputFileName = new File(file.getPath()).getName();
            if (!csvFileName.endsWith(inputFileName)) {
                continue;
            }

            // get the weakness description
            String msg = csvElements[7];
            if (msg.startsWith("\"")) {
                msg = msg.substring(1, msg.length());
            }
            if (msg.endsWith("\"")) {
                msg = msg.substring(0, msg.length() - 1);
            }

            if (msg.trim().startsWith("Parse Error")) {
                try {
                    writeToFile("splint: " + msg + "\n");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                continue;
            }

            // get the weakness id.
            final String id = csvElements[2];
            // get the linenumber of the weakness.
            final Integer lineNumber = Integer.valueOf(csvElements[5]);
            // this tool has no offset.
            final Integer offset = null;
            // get the position of the weakness.
            final Integer position = Integer.valueOf(csvElements[6]);

            // if there is a dataElement, use it.
            String dataElement = null;
            if (msg.split(":").length == 2) {
                dataElement = msg.split(":")[1].trim();
            }

            // if there are valid lines
            if (validLines != null) {
                if (lineNumber > 0) {
                    // return if the line number is greater than the array
                    // size.
                    if (lineNumber < validLines.length) {
                        if (validLines[lineNumber]) {
                            // pass the required information to the finding
                            // creator.
                            creator.create(StringEscapeUtils.unescapeHtml4(msg), id, lineNumber, offset,
                                    position, file, dataElement, null);
                        } else {
                            try {
                                FindingCreator.writeToFile("Splint: Not a valid line (uncompiled) "
                                        + file.getPath() + ":" + lineNumber + "\n");
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                }

            } else {
                // pass the required information to the finding creator.
                creator.create(StringEscapeUtils.unescapeHtml4(msg), id, lineNumber, offset, position, file,
                        dataElement, null);
            }

            // // pass the required information to the finding creator.
            // creator.create(StringEscapeUtils.unescapeHtml4(msg), id,
            // lineNumber, offset, position, file, dataElement, null);
            //
            //
            // // if there are valid lines
            // if (validLines != null)
            // {
            // // return if the line number is greater than the array size.
            // if (lineNumber < validLines.length)
            // {
            // if (validLines[lineNumber])
            // {
            // // create the finding.
            // creator.create(StringEscapeUtils.unescapeHtml4(msg), id,
            // lineNumber, offset, position, file, dataElement, null);
            // }
            // }
            //
            // }

        }

        // delete the file we made in the tmp directory.
        // tmpFile.delete();
    } catch (final FileNotFoundException e) {
        final String msg = "The tools output file could not be found. \"" + tmpFile.getAbsolutePath() + '"';
        LOG.error(msg, e);
        throw new ToifException(msg, e);
    } finally {
        if (scanner != null)
            scanner.close();
    }

    // return the elements from the finding creator.
    return creator.getElements();
}

From source file:com.nttec.everychan.chans.cirno.MikubaReader.java

private void handleFilter(int filterIndex) throws IOException {
    if (inDate && filterIndex != FILTER_ENDDATE)
        dateBuffer.setLength(0);//from w  ww .  ja  v a2 s  .c o  m
    switch (filterIndex) {
    case FILTER_THREAD_END:
        finalizeThread();
        break;
    case FILTER_ATTACHMENT:
        parseAttachment(readUntilSequence(FILTERS_CLOSE[filterIndex]));
        break;
    case FILTER_POSTNUMBER:
    case FILTER_POSTNUMBER_OP:
        currentPost.number = readUntilSequence(FILTERS_CLOSE[filterIndex]).trim().substring(1);
        break;
    case FILTER_SUBJECT:
        currentPost.subject = StringEscapeUtils.unescapeHtml4(readUntilSequence(FILTERS_CLOSE[filterIndex]))
                .trim();
        currentPost.subject = CryptoUtils.fixCloudflareEmails(currentPost.subject);
        inDate = true;
        break;
    case FILTER_ENDDATE:
        if (dateBuffer.length() > FILTERS_OPEN[FILTER_ENDDATE].length) {
            String date = dateBuffer.substring(0, dateBuffer.length() - FILTERS_OPEN[FILTER_ENDDATE].length)
                    .trim();
            if (date.length() > 0) {
                try {
                    currentPost.timestamp = DATEFORMAT.parse(date).getTime();
                } catch (Exception e) {
                    Logger.e(TAG, "cannot parse date; make sure you choose the right DateFormat for this chan",
                            e);
                }
            }
        }
        inDate = false;
        dateBuffer.setLength(0);
        break;
    case FILTER_START_COMMENT:
        skipUntilSequence(FILTERS_CLOSE[filterIndex]);
        currentPost.comment = readPostComment();
        finalizePost();
        break;
    }
}

From source file:com.sangupta.comparator.HTMLComparer.java

/**
 * Method to compare two given Jericho HTML parser {@link Source} objects
 * that represent an AST of the parsed HTML code
 * //from  w  ww.  j av  a  2  s.  co  m
 * @param source1
 *            the first AST
 * 
 * @param source2
 *            the second AST
 * 
 * @return <code>true</code> if the HTML structure and values are the same,
 *         <code>false</code> otherwise
 */
public static boolean compareHtml(Source source1, Source source2) {
    List<Tag> tags1 = source1.getAllTags();
    List<Tag> tags2 = source2.getAllTags();

    if (tags1.size() == 0 || tags2.size() == 0) {
        if (tags1.size() != tags2.size()) {
            System.out.println("Number of tags are zero in one of the sources.");
            return false;
        }
    }

    // compare all elements
    int index1 = 0;
    int index2 = 0;

    do {
        Tag tag1 = tags1.get(index1);
        Tag tag2 = tags2.get(index2);

        // element names
        if (!(tag1.getName().equals(tag2.getName()))) {
            System.out.println("Tag name mismatch: tag1=" + tag1.getBegin() + "; tag2=" + tag2.getBegin());
            System.out.println("Expected: " + tag1.getName() + "; Actual: " + tag2.getName());
            return false;
        }

        // element attributes
        if (tag1 instanceof StartTag) {
            if (!(tag2 instanceof StartTag)) {
                System.out.println("Tag not start tag: tag1=" + tag1.getBegin() + "; tag2=" + tag2.getBegin());
                return false;
            }

            StartTag st1 = (StartTag) tag1;
            StartTag st2 = (StartTag) tag2;

            boolean comment = false;
            if (st1.getStartTagType() == StartTagType.COMMENT) {
                index1++;
                comment = true;
            }

            if (st2.getStartTagType() == StartTagType.COMMENT) {
                index2++;
                comment = true;
            }

            if (!comment) {
                // match all attributes from tag1 to tag2
                if (!testAttributes(st1, st2)) {
                    return false;
                }

                // match all attributes from tag2 to tag1
                if (!testAttributes(st2, st1)) {
                    return false;
                }

                // checks for self-closing tags
                boolean se1 = st1.isSyntacticalEmptyElementTag();
                boolean se2 = st2.isSyntacticalEmptyElementTag();

                if ((se1 && !se2) || (!se1 && se2)) {
                    if (!se2) {
                        if (tags2.get(index2 + 1).getName().equals(tag1.getName())) {
                            index2++;
                        }
                    } else {
                        // do the other one
                        if (tags1.get(index1 + 1).getName().equals(tag2.getName())) {
                            index1++;
                        }
                    }
                }
            }

            // element values
            String content1 = st1.getElement().getTextExtractor().setIncludeAttributes(false).toString();
            String content2 = st2.getElement().getTextExtractor().setIncludeAttributes(false).toString();

            content1 = StringEscapeUtils.unescapeHtml4(content1);
            content2 = StringEscapeUtils.unescapeHtml4(content2);

            if (!(content1.equals(content2))) {
                System.out.println("Content mismatch: tag1=" + tag1.getBegin() + "; tag2=" + tag2.getBegin());
                System.out.println("C1: " + content1);
                System.out.println("C2: " + content2);
                return false;
            }

        }

        index1++;
        index2++;

        if (index1 >= tags1.size()) {
            break;
        }

        if (index2 >= tags2.size()) {
            break;
        }
    } while (true);

    return true;
}

From source file:net.sourceforge.jwbf.mediawiki.MediaWiki.java

public static String htmlUnescape(final String s) {
    return StringEscapeUtils.unescapeHtml4(s);
}

From source file:com.github.naoghuman.cm.model.glossary.GlossaryModel.java

@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    this.setId(in.readLong());
    this.setGenerationTime(in.readLong());
    this.setTitle(StringEscapeUtils.unescapeHtml4(String.valueOf(in.readObject())));
    this.setDescription(StringEscapeUtils.unescapeHtml4(String.valueOf(in.readObject())));
    this.setNotes(StringEscapeUtils.unescapeHtml4(String.valueOf(in.readObject())));
}

From source file:com.neocotic.blingaer.link.LinkServiceImpl.java

@Override
public String fetchTitle(String url) throws IllegalArgumentException {
    LOG.trace("Entered method - fetchTitle");

    if (validateUrl(url).hasErrors()) {
        throw new IllegalArgumentException("Invalid URL");
    }//from w ww  . jav a  2  s.c  o  m

    String content = null;
    Reader reader = null;

    try {
        reader = new InputStreamReader(new URL(url).openStream());

        content = IOUtils.toString(reader);

        reader.close();
    } catch (Exception e) {
        LOG.debug("Swallowed exception", e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    // Use URL if content could not be retrieved
    if (content == null) {
        return url;
    }

    // Attempts to extract charset declared in the HTML
    String charSet = null;
    Matcher matcher = Pattern.compile("/<meta[^>]*?charset=([^>]*?)\\/?>/is").matcher(content);

    while (matcher.find()) {
        charSet = StringUtils.trimToNull(matcher.group());
        break;
    }

    // Attempts to extract title declared in the HTML
    String title = null;
    matcher = Pattern.compile("/<title>(.*?)<\\/title>/is").matcher(content);

    while (matcher.find()) {
        title = StringUtils.trimToNull(matcher.group());
        break;
    }

    // If title wasn't found uses an error message (if applicable) or URL
    if (title == null) {
        title = (content.indexOf("Error") == 0) ? content : url;
    }

    // Attempts charset conversion to UTF-8
    try {
        if (charSet == null) {
            title = new String(title.getBytes(), "UTF-8");
        } else {
            title = new String(title.getBytes(charSet), "UTF-8");
        }
    } catch (UnsupportedEncodingException e) {
        LOG.debug("Swallowed exception", e);
    }

    // Removes HTML entities
    title = StringEscapeUtils.unescapeHtml4(title);

    // Removes all tags
    title = title.replaceAll("<(.|\\n)*?>", StringUtils.EMPTY);

    LOG.trace("Exiting method - fetchTitle");

    return title;
}