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

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

Introduction

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

Prototype

@Deprecated
public static final String escapeXml(final String input) 

Source Link

Document

Escapes the characters in a String using XML entities.

For example: "bread" & "butter" => "bread" & "butter" .

Usage

From source file:fr.mcc.ginco.services.ThesaurusTermServiceImpl.java

@Transactional(readOnly = false)
@Override//from   w w w.  j  a v a 2s .co  m
public List<ThesaurusTerm> importSandBoxTerms(Map<String, Language> termLexicalValues, String thesaurusId,
        int defaultStatus) {
    List<ThesaurusTerm> updatedTerms = new ArrayList<ThesaurusTerm>();
    Thesaurus targetedThesaurus = thesaurusDAO.getById(thesaurusId);
    if (targetedThesaurus != null) {
        for (String term : termLexicalValues.keySet()) {
            ThesaurusTerm termToImport = new ThesaurusTerm();
            termToImport.setIdentifier(customGeneratorService.generate(ThesaurusTerm.class));
            termToImport.setLexicalValue(StringEscapeUtils.escapeXml(term));
            termToImport.setThesaurus(targetedThesaurus);
            termToImport.setLanguage(termLexicalValues.get(term));
            termToImport.setModified(DateUtil.nowDate());
            termToImport.setCreated(DateUtil.nowDate());
            termToImport.setStatus(defaultStatus);
            updatedTerms.add(thesaurusTermDAO.update(termToImport));
        }
    } else {
        throw new BusinessException("Unknown thesaurus", "unknown-thesaurus");
    }
    return updatedTerms;
}

From source file:io.wcm.tooling.commons.contentpackagebuilder.ContentPackage.java

/**
 * Read template file from classpath, replace variables and store it in the zip stream.
 * @param path Path// ww  w.  ja  v a  2s  .  co  m
 * @throws IOException
 */
private void buildTemplatedMetadataFile(String path) throws IOException {
    try (InputStream is = getClass().getResourceAsStream("/content-package-template/" + path)) {
        String xmlContent = IOUtils.toString(is);
        for (Map.Entry<String, Object> entry : metadata.getVars().entrySet()) {
            xmlContent = StringUtils.replace(xmlContent, "{{" + entry.getKey() + "}}",
                    StringEscapeUtils.escapeXml(entry.getValue().toString()));
        }
        zip.putNextEntry(new ZipEntry(path));
        try {
            zip.write(xmlContent.getBytes(Charsets.UTF_8));
        } finally {
            zip.closeEntry();
        }
    }
}

From source file:jongo.filter.DefaultFormatFilter.java

private String formatSuccessXMLResponse(final JongoSuccess response) {
    StringBuilder b = new StringBuilder("<response><success>");
    b.append(response.isSuccess());/*w w w.  j  av a 2  s .  c  om*/
    b.append("</success><resource>");
    b.append(response.getResource());
    b.append("</resource><rows>");
    for (Row r : response.getRows()) {
        b.append("<row roi=\"");
        b.append(r.getRoi());
        b.append("\"><cells>");
        for (String key : r.getCells().keySet()) {
            String val = StringEscapeUtils.escapeXml(r.getCells().get(key));
            b.append("<");
            b.append(key.toLowerCase());
            b.append(">");
            b.append(val);
            b.append("</");
            b.append(key.toLowerCase());
            b.append(">");
        }
        b.append("</cells></row>");
    }
    b.append("</rows></response>");
    return b.toString();
}

From source file:edu.jhu.hlt.concrete.ingesters.webposts.WebPostIngester.java

@Override
public Communication fromCharacterBasedFile(final Path path) throws IngestException {
    if (!Files.exists(path))
        throw new IngestException("No file at: " + path.toString());

    AnalyticUUIDGeneratorFactory f = new AnalyticUUIDGeneratorFactory();
    AnalyticUUIDGenerator g = f.create();
    Communication c = new Communication();
    c.setUuid(g.next());/*  ww w  .  j  a v a2  s .c om*/
    c.setType(this.getKind());
    c.setMetadata(TooledMetadataConverter.convert(this));

    try {
        ExistingNonDirectoryFile ef = new ExistingNonDirectoryFile(path);
        c.setId(ef.getName().split("\\.")[0]);
    } catch (NoSuchFileException | NotFileException e) {
        // might throw if path is a directory.
        throw new IngestException(path.toString() + " is not a file, or is a directory.");
    }

    String content;
    try (InputStream is = Files.newInputStream(path);
            BufferedInputStream bin = new BufferedInputStream(is, 1024 * 8 * 8);) {
        content = IOUtils.toString(bin, StandardCharsets.UTF_8);
        c.setText(content);
    } catch (IOException e) {
        throw new IngestException(e);
    }

    try (InputStream is = Files.newInputStream(path);
            BufferedInputStream bin = new BufferedInputStream(is, 1024 * 8 * 8);
            BufferedReader reader = new BufferedReader(new InputStreamReader(bin, StandardCharsets.UTF_8));) {
        XMLEventReader rdr = null;
        try {
            rdr = inF.createXMLEventReader(reader);

            // Below method moves the reader
            // to the headline end element.
            Section headline = this.handleBeginning(rdr, content, c);
            headline.setUuid(g.next());
            c.addToSectionList(headline);
            TextSpan sts = headline.getTextSpan();
            LOGGER.debug("headline text: {}", c.getText().substring(sts.getStart(), sts.getEnding()));

            int sectNumber = 1;
            int subSect = 0;

            int currOff = -1;
            // Big amounts of characters.
            while (rdr.hasNext()) {
                XMLEvent nextEvent = rdr.nextEvent();
                currOff = nextEvent.getLocation().getCharacterOffset();

                // First: see if document is going to end.
                // If yes: exit.
                if (nextEvent.isEndDocument())
                    break;

                // region
                // enables ingestion of quotes inside a usenet webpost.
                // by Tongfei Chen
                if (nextEvent.isStartElement()
                        && nextEvent.asStartElement().getName().equals(QName.valueOf("QUOTE"))) {
                    Attribute attrQuote = nextEvent.asStartElement()
                            .getAttributeByName(QName.valueOf("PREVIOUSPOST"));
                    String quote = StringEscapeUtils.escapeXml(attrQuote.getValue());
                    int location = attrQuote.getLocation().getCharacterOffset()
                            + "<QUOTE PREVIOUSPOST=\"".length();
                    Section quoteSection = new Section(g.next(), "quote")
                            .setTextSpan(new TextSpan(location, location + quote.length()));
                    c.addToSectionList(quoteSection);
                }
                // endregion

                // Check if start element.
                if (nextEvent.isCharacters()) {
                    Characters chars = nextEvent.asCharacters();
                    if (!chars.isWhiteSpace()) {
                        String fpContent = chars.getData();
                        LOGGER.debug("Character offset: {}", currOff);
                        LOGGER.debug("Character based data: {}", fpContent);

                        SimpleImmutableEntry<Integer, Integer> pads = trimSpacing(fpContent);
                        final int tsb = currOff + pads.getKey();

                        final int tse = currOff + fpContent.replace("\"", "&quot;").replace("<", "&lt;")
                                .replace(">", "&gt;").length() - (pads.getValue());
                        // MAINTAIN CORRECT TEXT SPAN
                        // CANNOT USE StringEscapeUtils.escapeXml because it will escape "'", which
                        // is not escaped in the data
                        // @tongfei

                        LOGGER.debug("Section text: {}", content.substring(tsb, tse));
                        TextSpan ts = new TextSpan(tsb, tse);
                        String sk;
                        if (subSect == 0)
                            sk = "poster";
                        else if (subSect == 1)
                            sk = "postdate";
                        else
                            sk = "post";

                        Section s = new Section();
                        s.setKind(sk);
                        s.setTextSpan(ts);
                        s.setUuid(g.next());
                        List<Integer> intList = new ArrayList<>();
                        intList.add(sectNumber);
                        intList.add(subSect);
                        s.setNumberList(intList);
                        c.addToSectionList(s);

                        subSect++;
                    }
                } else if (nextEvent.isEndElement()) {
                    EndElement ee = nextEvent.asEndElement();
                    currOff = ee.getLocation().getCharacterOffset();
                    QName name = ee.getName();
                    String localName = name.getLocalPart();
                    LOGGER.debug("Hit end element: {}", localName);
                    if (localName.equalsIgnoreCase(POST_LOCAL_NAME)) {
                        LOGGER.debug("Switching to new post.");
                        sectNumber++;
                        subSect = 0;
                    } else if (localName.equalsIgnoreCase(TEXT_LOCAL_NAME)) {
                        // done with document.
                        break;
                    }
                }
            }

            return c;

        } catch (XMLStreamException | ConcreteException | StringIndexOutOfBoundsException
                | ClassCastException x) {
            throw new IngestException(x);
        } finally {
            if (rdr != null)
                try {
                    rdr.close();
                } catch (XMLStreamException e) {
                    // not likely.
                    LOGGER.info("Error closing XMLReader.", e);
                }
        }
    } catch (IOException e) {
        throw new IngestException(e);
    }
}

From source file:de.micromata.genome.gwiki.controls.GWikiPageInfoActionBean.java

protected String buildBaseInfo() {
    XmlElement ta = getStandardTable();
    XmlNode changeId = code("");
    if (wikiContext.getWikiWeb().getAuthorization().isAllowToEdit(wikiContext, elementInfo) == true
            && wikiContext.getWikiWeb().getAuthorization().isAllowToCreate(wikiContext, elementInfo) == true
            && wikiContext.isAllowTo(GWikiAuthorizationRights.GWIKI_DELETEPAGES.name())) {
        changeId = element("div", //
                element("form", //
                        element("input",
                                attrs("type", "text", "size", "50", "value",
                                        StringEscapeUtils.escapeXml(elementInfo.getId()), "name", "newPageId")),
                        br(), //
                        element("input",
                                attrs("type", "submit", "class", "gwikiButton main", "name", "method_onRename",
                                        "value", translate("gwiki.page.edit.PageInfo.info.button.rename"))), //
                        element("script", code("")) //
                ));//from  www  . ja v a 2 s.c o  m
    }
    ta.nest(//
            tr(//
                    th(text(translate("gwiki.page.edit.PageInfo.info.label.pageId"))), //
                    td(text(elementInfo.getId()), changeId) //
            ), //
            tr(//
                    th(text(translate("gwiki.page.edit.PageInfo.info.label.title"))), //
                    td(text(wikiContext.getTranslatedProp(elementInfo.getTitle()))) //
            ), //
            tr( //
                    th(text(translate("gwiki.page.edit.PageInfo.info.label.author"))), //
                    td(text(elementInfo.getProps().getStringValue(CREATEDBY)))//
            ), //
            tr(//
                    th(text(translate("gwiki.page.edit.PageInfo.info.label.createdat"))), //
                    td(text(getDisplayDate(elementInfo.getProps().getDateValue(CREATEDAT)))) //
            ), //
            tr( //
                    th(text(translate("gwiki.page.edit.PageInfo.info.label.modifiedby"))), //
                    td(text(elementInfo.getProps().getStringValue(MODIFIEDBY)))//
            ), //
            tr(//
                    th(text(translate("gwiki.page.edit.PageInfo.info.label.modifiedat"))), //
                    td(text(getDisplayDate(elementInfo.getProps().getDateValue(MODIFIEDAT)))) //
            ) //
    );
    return getBoxFrame(translate("gwiki.page.edit.PageInfo.info.title"), ta).toString();
}

From source file:jongo.filter.DefaultFormatFilter.java

private String formatErrorXMLResponse(final JongoError response) {
    final StringBuilder b = new StringBuilder("<response><success>").append(response.isSuccess())
            .append("</success><message>").append(StringEscapeUtils.escapeXml(response.getMessage()))
            .append("</message>");
    if (response.getSqlCode() != null && response.getSqlState() != null) {
        b.append("<sqlState>").append(response.getSqlState()).append("</sqlState>");
        b.append("<sqlCode>").append(response.getSqlCode()).append("</sqlCode>");
    }/*w  w  w.ja v a  2s.c om*/
    b.append("</response>");
    return b.toString();
}

From source file:de.micromata.genome.gwiki.page.impl.wiki.macros.GWikiChildrenMacro.java

public static void renderSitemapChildren(GWikiContext wikiContext, GWikiElementInfo ei,
        String defaultChageFreq) {
    if (wikiContext.getWikiWeb().getAuthorization().isAllowToView(wikiContext, ei) == false) {
        return;/*from  w  ww. j a  va  2  s. c o m*/
    }
    if (ei.isNoToc() == true) {
        return;
    }
    wikiContext.getWikiWeb().getWikiConfig().getPublicURL();
    wikiContext.append("<url><loc>").append(wikiContext.globalUrl(ei.getId())).append("</loc>\n"); //
    Date d = ei.getModifiedAt();
    if (d != null) {
        wikiContext.append("<lastmod>").append(SITE_CONTENT_FORMAT.get().format(d)).append("</lastmod>");
    }
    if (StringUtils.isNotEmpty(defaultChageFreq) == true) {
        wikiContext.append("<changefreq>").append(StringEscapeUtils.escapeXml(defaultChageFreq))
                .append("</changefreq>\n");
    }

    wikiContext.append("</url>\n");

    List<GWikiElementInfo> cl = wikiContext.getElementFinder().getAllDirectChilds(ei);
    for (GWikiElementInfo ce : cl) {
        renderSitemapChildren(wikiContext, ce, defaultChageFreq);
    }
}

From source file:com.thoughtworks.selenium.SeleneseTestBaseVir.java

/**
 * Replace xml special characters.//w w  w .  j av  a  2s. c  om
 * 
 * @param text
 *            the text
 * @return the string
 */
public final String replaceXMLSpecialCharacters(final String text) {
    String replaced = text;

    replaced = StringEscapeUtils.escapeXml(replaced);
    replaced = replaced.replaceAll("", "&#187;");
    replaced = replaced.replaceAll("", "&#171;");
    replaced = replaced.replaceAll("", "&#8212;");
    replaced = replaced.replaceAll("", "&#8211;");
    replaced = replaced.replaceAll("", "&#163;");
    replaced = replaced.replaceAll("", "&#165;");
    replaced = replaced.replaceAll("", "&#8364;");

    return replaced;
}

From source file:com.wavemaker.commons.util.XMLWriter.java

public void addText(String in, boolean onNewLine) {
    if (in.trim().length() == 0) {
        return;/*from  www . j ava 2 s.  co m*/
    }

    finishIncompleteTag();
    if (onNewLine) {
        this.pw.print(sep);
        this.pw.print(getIndent());
    }
    this.pw.print(StringEscapeUtils.escapeXml(in.trim()));
}

From source file:annis.visualizers.iframe.partitur.PartiturVisualizer.java

@Override
public void writeOutput(VisualizerInput input, Writer writer) {
    try {/*  w  w w.jav a2s. co m*/

        nodes = input.getResult().getGraph().getNodes();
        token = input.getResult().getGraph().getTokens();

        // get partitur
        PartiturParser partitur = new PartiturParser(input.getResult().getGraph(), input.getNamespace());

        // check right to left
        boolean isRTL = checkRTL(input.getResult().getTokenList());

        List<String> tierNames = new LinkedList<String>(partitur.getKnownTiers());
        Collections.sort(tierNames);

        // get keys that are allowed to select
        LinkedHashSet<String> keys = new LinkedHashSet<String>();
        String mapping = input.getMappings().getProperty("annos");
        if (mapping == null) {
            // default to the alphabetical order
            keys.addAll(partitur.getNameslist());
        } else {
            String[] splitted = mapping.split(",");
            for (int k = 0; k < splitted.length; k++) {
                String s = splitted[k].trim();
                if (partitur.getNameslist().contains(s)) {
                    keys.add(s);
                }
            }
        }

        writer.append(
                "<!DOCTYPE html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
        writer.append("<link href=\"" + input.getResourcePath("jbar.css")
                + "\" rel=\"stylesheet\" type=\"text/css\" >");
        writer.append("<link href=\"" + input.getResourcePath("jquery.tooltip.css")
                + "\" rel=\"stylesheet\" type=\"text/css\" >");
        writer.append("<link href=\"" + input.getResourcePath("jquery.noty.css")
                + "\" rel=\"stylesheet\" type=\"text/css\" >");
        writer.append("<link href=\"" + input.getResourcePath("partitur.css")
                + "\" rel=\"stylesheet\" type=\"text/css\" >");
        writer.append("<script src=\"" + input.getResourcePath("jquery-1.7.1.min.js") + "\"></script>");
        writer.append("<script src=\"" + input.getResourcePath("jquery.jbar.js") + "\"></script>");
        writer.append("<script src=\"" + input.getResourcePath("jquery.tooltip.min.js") + "\"></script>");
        writer.append("<script src=\"" + input.getResourcePath("jquery.noty.js") + "\"></script>");
        writer.append("<script>");
        writer.append(convertToJavacSriptArray(new LinkedList<String>()));
        writer.append("\nvar levelNames = [");
        int i = 0;
        for (String levelName : tierNames) {
            if (keys.contains(levelName)) {
                writer.append((i++ > 0 ? ", " : "") + "\"" + levelName + "\"");
            }
        }
        writer.append("];\n</script>");
        writer.append("<script type=\"text/javascript\" src=\"" + input.getResourcePath("PartiturVisualizer.js")
                + "\"></script>");

        writer.append("</head>");
        writer.append("<body>\n");

        writer.append("<ul id=\"toolbar\"></ul>");
        writer.append("<div id=\"partiture\">");

        if (isRTL) {
            writer.append("<table class=\"partitur_table\" dir=\"rtl\">\n");
        } else {
            writer.append("<table class=\"partitur_table\")\">\n");
        }

        for (String tier : keys) {
            List<String> indexlist = new ArrayList<String>();

            for (List<PartiturParser.ResultElement> span : partitur.getResultlist()) {
                for (PartiturParser.ResultElement strr : span) {
                    if (strr.getName().equals(tier) && !indexlist.contains(strr.getId())) {
                        indexlist.add(strr.getId());
                    }
                }
            }

            String[] currentarray; //Saves annotation-ids of the current row

            while (!indexlist.isEmpty()) { //Create Rows until all Annotations fit in
                List<String> currentdontuselist = new LinkedList<String>(); //Lists all Annotations that should not be added to the current row
                writer.append("<tr class=\"level_" + tier + "\"><th>" + tier + "</th>"); //new row

                currentarray = new String[partitur.getResultlist().size()];
                for (int iterator3 = 0; iterator3 < partitur.getResultlist().size(); iterator3++) {
                    currentarray[iterator3] = null;
                }

                int spanCounter = 0;
                for (List<PartiturParser.ResultElement> span : partitur.getResultlist()) { //for each Token
                    for (PartiturParser.ResultElement annotationelement : span) { // for each Annotation annotationelement of that Token
                        if (indexlist.contains(annotationelement.getId())
                                && !currentdontuselist.contains(annotationelement.getId())) {
                            boolean neu = false; //Should the Annotation be added?
                            if (currentarray[spanCounter] == null) {
                                indexlist.remove(annotationelement.getId());
                                currentarray[spanCounter] = annotationelement.getId();
                                neu = true;
                            }
                            //get all other annotationelement.id (earlier Ids => dontuselist)
                            int span2Counter = 0;
                            for (List<PartiturParser.ResultElement> span2 : partitur.getResultlist()) {
                                for (PartiturParser.ResultElement strr2 : span2) {
                                    if (strr2.getId().equals(annotationelement.getId()) && neu) //{
                                    {
                                        if (currentarray[span2Counter] == null) {
                                            currentarray[span2Counter] = annotationelement.getId();
                                        }
                                    }
                                    if (span2Counter <= spanCounter
                                            && !currentdontuselist.contains(strr2.getId())) {
                                        currentdontuselist.add(strr2.getId());
                                    }
                                }
                                span2Counter++;
                            }
                            //break; //Not needed?
                        }
                    }
                    spanCounter++;
                }

                //Write Row
                int length = 1;
                for (int iterator5 = 0; iterator5 < currentarray.length; iterator5 += length) {
                    StringBuffer tokenIdsArray = new StringBuffer();
                    StringBuffer eventIdsArray = new StringBuffer();
                    boolean unused = true;
                    length = 1;
                    if (currentarray[iterator5] == null) { //empty entry
                        writer.append("<td></td>");
                    } else {
                        PartiturParser.ResultElement element = null;
                        HashSet<Integer> common = new HashSet<Integer>();
                        boolean found = false;
                        int outputSpanCounter = 0;
                        for (List<PartiturParser.ResultElement> outputSpan : partitur.getResultlist()) {
                            for (PartiturParser.ResultElement strr : outputSpan) {
                                if (strr.getId().equals(currentarray[iterator5])) {
                                    if (!found) {
                                        element = strr;
                                    }
                                    if (!common.contains(outputSpanCounter)) {
                                        common.add(outputSpanCounter);
                                    }
                                    found = true;
                                    if (unused) {
                                        tokenIdsArray.append("" + strr.getId() + "_" + outputSpanCounter);
                                        eventIdsArray
                                                .append(tier + "_" + strr.getId() + "_" + outputSpanCounter);
                                        unused = false;
                                    } else {
                                        tokenIdsArray.append("," + strr.getId() + "_" + outputSpanCounter);
                                        eventIdsArray.append(
                                                "," + tier + "_" + strr.getId() + "_" + outputSpanCounter);
                                    }
                                }
                            }
                            outputSpanCounter++;
                        }
                        for (int iterator7 = iterator5 + 1; iterator7 < currentarray.length; iterator7++) {
                            if (common.contains(iterator7)) {
                                length++;
                            } else {
                                break;
                            }
                        }

                        for (int iterator8 = 0; iterator8 < currentarray.length; iterator8++) {
                            if (common.contains(iterator8)) {
                                Long id = ((PartiturParser.Token) partitur.getToken().toArray()[iterator8])
                                        .getId();
                                if (unused) {
                                    tokenIdsArray.append("" + id);
                                    eventIdsArray.append(tier + "_" + id);
                                    unused = false;
                                } else {
                                    tokenIdsArray.append("," + id);
                                    eventIdsArray.append("," + tier + "_" + id);
                                }
                            }
                        }

                        String color = "black";
                        if (input.getMarkableExactMap().containsKey("" + element.getNodeId())) {
                            color = input.getMarkableExactMap().get("" + element.getNodeId());
                        }
                        if (found) {
                            writer.append("<td class=\"single_event\" " + "id=\"event_" + tier + "_"
                                    + element.getId() + "_" + iterator5 + "\" " + "style=\"color:" + color
                                    + ";\" " + "colspan=" + length + " " + "annis:tokenIds=\"" + tokenIdsArray
                                    + "\" " + "annis:eventIds=\"" + eventIdsArray + "\" " + "title=\""
                                    + partitur.namespaceForTier(tier) + ":" + tier + " = "
                                    + StringEscapeUtils.escapeXml(element.getValue()) + "\"  " //tier =tier, event.getValue()= element.name
                                    + "onMouseOver=\"toggleAnnotation(this, true);\" "
                                    + "onMouseOut=\"toggleAnnotation(this, false);\" "
                                    + addTimeAttribute(element.getNodeId()) + ">" + element.getValue()
                                    + "</td>");
                        } else {
                            writer.append("<td class=\"single_event\" >error</td>");
                        }
                    }
                }
                writer.append("</tr>"); //finish row
            }
        }

        // add token itself
        writer.append("<tr><th>tok</th>");

        for (PartiturParser.Token token : partitur.getToken()) {
            String color = "black";

            if (input.getMarkableExactMap().containsKey("" + token.getId())) {
                color = input.getMarkableExactMap().get("" + token.getId());
            }
            writer.append("<td class=\"tok\" style=\"color:" + color + ";\" " + "id=\"token_" + token.getId()
                    + "\" " + ">" + token.getValue() + "</td>");
        }
        writer.append("</tr>");

        writer.append("</table>\n");
        writer.append("</div>\n");
        writer.append("</body></html>");

    } catch (Exception ex) {
        log.error(null, ex);
        try {
            String annisLine = "";
            for (int i = 0; i < ex.getStackTrace().length; i++) {
                if (ex.getStackTrace()[i].getClassName().startsWith("annis.")) {
                    annisLine = ex.getStackTrace()[i].toString();
                }
            }

            writer.append("<html><body>Error occured (" + ex.getClass().getName() + "): "
                    + ex.getLocalizedMessage() + "<br/>" + annisLine + "</body></html>");
        } catch (IOException ex1) {
            log.error(null, ex1);
        }
    }
}