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:com.feilong.taglib.display.sitemap.SiteMapURL.java

/**
 * ?url(?),?escape.//from w  w w. ja  v a2  s  .c om
 * 
 * @return the formatLoc
 * @throws IllegalArgumentException
 *             if Validator.isNullOrEmpty(loc) or formatLoc length >=2048
 * @see #loc
 * @see StringEscapeUtils#ESCAPE_XML
 * @see StringEscapeUtils#escapeXml(String)
 * @see StringEscapeUtils#unescapeXml(String)
 */
public String getFormatLoc() throws IllegalArgumentException {
    if (Validator.isNullOrEmpty(loc)) {
        throw new IllegalArgumentException("loc can't be null/empty!");
    }

    String formatLoc = StringEscapeUtils.escapeXml(loc);
    int length = formatLoc.length();
    if (length >= 2048) {
        throw new IllegalArgumentException("formatLoc's length:" + length + " can't >= 2048!");
    }
    return formatLoc;
}

From source file:com.thejustdo.util.Utils.java

/**
 * Formats a string to avoid any injection exploit by escaping the special
 * characters./* w  ww . j a v  a  2 s.  c  om*/
 *
 * @param s String to be modified.
 * @return Modified string.
 */
public static String escapeString(String s) {
    String answer;
    answer = StringEscapeUtils.escapeCsv(s);
    answer = StringEscapeUtils.escapeEcmaScript(answer);
    answer = StringEscapeUtils.escapeHtml3(answer);
    answer = StringEscapeUtils.escapeHtml4(answer);
    answer = StringEscapeUtils.escapeJava(answer);
    answer = StringEscapeUtils.escapeXml(answer);
    return answer;
}

From source file:edu.ucdenver.ccp.nlp.ae.dict_util.OboToDictionary.java

/**
     * Represent the OBO object as a XML dictionary string.
     * // w ww  .ja v  a 2  s. c  o  m
     * @param id
     *            the ID of the OBO object
     * @param oboObj
     *            the OBO object itself
     * @param synonymType
     * @return an XML-formatted string in the ConceptMapper Dictionary format.
     */
    private String oboToXml(String id, OBOClass oboObj) {

        StringBuffer buf = new StringBuffer();
        String name = oboObj.getName();

        // id without a name. Don't add to dictionary.
        if (name == null || name == "" || name == "<new term>") {
            logger.warn("oboToXML() null name: " + name);
            return "";
        }

        // single letter name? Don't add to dictionary
        if (filterSingleLetterTerms && name.length() <= 1) {
            logger.warn("oboToXML() short name: " + name);
            return "";
        }

        name = StringEscapeUtils.escapeXml(name);
        buf.append("<token id=\"" + id + "\"");
        buf.append(" canonical=\"" + name + "\"" + ">\n");

        Pattern endsWithActivityPattern = Pattern.compile("(.*)\\sactivity");
        {
            Matcher m = endsWithActivityPattern.matcher(name);
            if (m.matches()) {
                String enzyme = m.group(1);
                buildSynonymLine(enzyme, buf);
            }
        }

        buildSynonymLine(name, buf); // needed?
        if (name.contains("_")) {
            buildSynonymLine(name.replace('_', ' '), buf);
        }
        for (Object synObj : oboObj.getSynonyms()) {
            Synonym syn = (Synonym) synObj;
            if (synonymType.equals(SynonymType.ALL)
                    || (synonymType.equals(SynonymType.EXACT_ONLY) && syn.getScope() == syn.EXACT_SYNONYM)) {
                String synonymStr = StringEscapeUtils.escapeXml(syn.getText());
                buildSynonymLine(synonymStr, buf);
                if (name.contains("_")) {
                    buildSynonymLine(synonymStr.replace('_', ' '), buf);
                }
                Matcher m = endsWithActivityPattern.matcher(synonymStr);
                if (m.matches()) {
                    String enzyme = m.group(1);
                    buildSynonymLine(enzyme, buf);
                }
            }
        }

        buf.append("</token>\n");

        return buf.toString();
    }

From source file:jCMPL.CmplInstance.java

/**
 * Creates a CmplInstance string//from w w w  . j  a v  a2 s  .  c o  m
 *
 * @param cmplFileName CMPL file
 * @param optList List of the options
 * @param dataString CmplData string
 * @param jobId JobId
 * @return CmplInstance string
 * @throws CmplException
 */
protected String cmplInstanceStr(String cmplFileName, HashMap<Integer, String> optList, String dataString,
        String jobId) throws CmplException {
    File cmplFile = new File(cmplFileName);
    if (cmplFile.exists()) {
        if (!dataString.isEmpty()) {
            _cmplDataList.put("__cmplData__"
                    + cmplFile.getName().substring(0, cmplFile.getName().lastIndexOf('.')) + ".cdat",
                    dataString);
        }
    } else {
        throw new CmplException("CMPL file " + cmplFileName + " does not exist.");
    }

    try {
        boolean commentSection = false;
        int lineNr = 0;

        BufferedReader in = new BufferedReader(new FileReader(cmplFileName));

        String tmpName = "";
        String tmpName1 = "";

        ArrayList<String> lines = new ArrayList<String>();

        String tmpLine = "";
        while ((tmpLine = in.readLine()) != null) {
            lines.add(tmpLine);
        }
        in.close();

        for (String line : lines) {
            line = line.trim();

            if (line.startsWith("/*")) {
                commentSection = true;
                line = line.substring(0, line.indexOf("/*") - 1);
            }
            if (line.contains("*/")) {
                commentSection = false;
                line = line.substring(line.indexOf("*/") + 1);
            }
            if (commentSection) {
                continue;
            }

            if (line.startsWith("%data")) {
                if (line.contains(":")) {
                    tmpName = line.substring(5, line.indexOf(":")).trim();
                } else {
                    tmpName = line.substring(5).trim();
                }

                if (tmpName.isEmpty()) {
                    if (!dataString.isEmpty()) {
                        lines.set(lineNr,
                                line.replace("%data", "%data __cmplData__"
                                        + cmplFile.getName().substring(0, cmplFile.getName().lastIndexOf('.'))
                                        + ".cdat"));
                        tmpName = "__cmplData__";
                    } else {
                        tmpName = cmplFile.getName().substring(0, cmplFile.getName().lastIndexOf('.'))
                                + ".cdat";
                    }
                }

                if (!(_cmplDataList.containsKey(tmpName) || tmpName.equals("__cmplData__"))) {
                    tmpName1 = "";
                    if (cmplFile.getParent() == null) {
                        tmpName1 = cmplFile.getName().substring(0, cmplFile.getName().lastIndexOf('.'))
                                + ".cdat";
                    } else {
                        tmpName1 = cmplFile.getParent() + File.separator
                                + cmplFile.getName().substring(0, cmplFile.getName().lastIndexOf('.'))
                                + ".cdat";
                    }

                    BufferedReader cin = new BufferedReader(new FileReader(tmpName1));

                    String dline = "";
                    String tmpString = "";

                    while ((dline = cin.readLine()) != null) {
                        tmpString += dline;
                    }
                    cin.close();
                    _cmplDataList.put(tmpName1, tmpString);
                }
            }

            lineNr += 1;

        }

        _instStr.append("<?xml version = \"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
        _instStr.append("<CmplInstance version=\"1.0\">\n");
        _instStr.append("<general>\n");
        _instStr.append("<name>").append(cmplFile.getName()).append("</name>\n");
        _instStr.append("<jobId>").append(jobId).append("</jobId>\n");
        _instStr.append("</general>\n");

        if (optList.size() > 0) {
            _instStr.append("<options>\n");

            for (Map.Entry<Integer, String> o : optList.entrySet()) {
                _instStr.append("<opt>").append(o.getValue()).append("</opt>\n");
            }

            _instStr.append("</options>\n");
        }

        _instStr.append("<problemFiles>\n");
        _instStr.append("<file name=\"").append(cmplFile.getName()).append("\" type=\"cmplMain\">\n");

        String tmpStr = "";
        for (String line : lines) {
            tmpStr += line + "\n";
        }
        _instStr.append(StringEscapeUtils.escapeXml(tmpStr));

        _instStr.append("\n");
        _instStr.append("</file>\n");

        for (Map.Entry<String, String> e : _cmplDataList.entrySet()) {
            _instStr.append("<file name=\"").append(e.getKey()).append("\" type=\"cmplData\">\n");
            _instStr.append(StringEscapeUtils.escapeXml(e.getValue()));
            _instStr.append("\n");
            _instStr.append("</file>\n");
        }
        _instStr.append("</problemFiles>\n");
        _instStr.append("</CmplInstance>\n");

    } catch (IOException e

    ) {
        throw new CmplException("IO error : " + e);
    }

    return _instStr.toString();
}

From source file:edu.ucdenver.ccp.nlp.ae.dict_util.GeneInfoToDictionary.java

/**
 * Represent the concept as a XML dictionary string.
 * /*from www . ja va 2  s  .  c o  m*/
 * @param  the ID of the object
 * @param synonyms
 * @return an XML-formatted string in the ConceptMapper Dictionary format.
 */
private String createEntry(String id, String name) {

    StringBuilder buf = new StringBuilder();

    id = StringEscapeUtils.escapeXml(id);
    name = StringEscapeUtils.escapeXml(name);
    buf.append("<token id=\"" + id + "\"");
    buf.append(" canonical=\"" + name + "\"" + ">\n");

    if (idToSynonymMap.get(id) != null) {
        for (String s : idToSynonymMap.get(id)) {

            if (synonymToIdMap.get(s).size() < 3) {
                buildSynonymLine(s, buf);
                if (s.contains("_")) {
                    buildSynonymLine(s.replace('_', ' '), buf);
                }
            }
        }
    }

    buf.append("</token>\n");

    return buf.toString();
}

From source file:at.gv.egovernment.moa.id.protocols.saml1.GetAuthenticationDataService.java

/**
 * Takes a <code>lt;samlp:Request&gt;</code> containing a 
 * <code>SAML artifact</code> and returns the corresponding 
 * authentication data <code>lt;saml:Assertion&gt;</code> 
 * (obtained from the <code>AuthenticationServer</code>),
 * enclosed in a <code>lt;samlp:Response&gt;</code>.
 * <br/>Bad requests are mapped into various <code>lt;samlp:StatusCode&gt;</code>s,
 * possibly containing enclosed sub-<code>lt;samlp:StatusCode&gt;</code>s.
 * The status codes are defined in the SAML specification.
 * // w ww.j  ava2 s  .  c  o m
 * @param requests request elements of type <code>lt;samlp:Request&gt;</code>;
 *              only 1 request element is allowed
 * @return response element of type <code>lt;samlp:Response&gt;</code>,
 *               packed into an <code>Element[]</code>
 * @throws AxisFault thrown when an error occurs in assembling the 
 *                <code>lt;samlp:Response&gt;</code>
 */
public Element[] Request(Element[] requests) throws AxisFault {

    Element request = requests[0];
    Element[] responses = new Element[1];
    String requestID = "";
    String statusCode = "";
    String subStatusCode = null;
    String statusMessageCode = null;
    String statusMessage = null;
    String samlAssertion = "";
    if (requests.length > 1) {
        // more than 1 request given as parameter
        statusCode = "samlp:Requester";
        subStatusCode = "samlp:TooManyResponses";
        statusMessageCode = "1201";
    } else {
        try {
            DOMUtils.validateElement(request, ALL_SCHEMA_LOCATIONS, null);
            NodeList samlArtifactList = XPathUtils.selectNodeList(request, "samlp:AssertionArtifact");
            if (samlArtifactList.getLength() == 0) {
                // no SAML artifact given in request
                statusCode = "samlp:Requester";
                statusMessageCode = "1202";
            } else if (samlArtifactList.getLength() > 1) {
                // too many SAML artifacts given in request
                statusCode = "samlp:Requester";
                subStatusCode = "samlp:TooManyResponses";
                statusMessageCode = "1203";
            }

            else {
                Element samlArtifactElem = (Element) samlArtifactList.item(0);
                requestID = request.getAttribute("RequestID");
                String samlArtifact = DOMUtils.getText(samlArtifactElem);
                SAML1AuthenticationServer saml1server = SAML1AuthenticationServer.getInstace();

                try {

                    samlAssertion = saml1server.getSaml1AuthenticationData(samlArtifact);

                    // success
                    statusCode = "samlp:Success";
                    statusMessageCode = "1200";
                }

                catch (ClassCastException ex) {

                    try {
                        Throwable error = saml1server.getErrorResponse(samlArtifact);
                        statusCode = "samlp:Responder";

                        ErrorResponseUtils errorUtils = ErrorResponseUtils.getInstance();

                        if (error instanceof MOAIDException) {
                            statusMessageCode = ((MOAIDException) error).getMessageId();
                            statusMessage = StringEscapeUtils.escapeXml(((MOAIDException) error).getMessage());

                        } else {
                            statusMessage = StringEscapeUtils.escapeXml(error.getMessage());
                        }
                        subStatusCode = errorUtils.getResponseErrorCode(error);

                    } catch (Exception e) {
                        //no authentication data for given SAML artifact
                        statusCode = "samlp:Requester";
                        subStatusCode = "samlp:ResourceNotRecognized";
                        statusMessage = ex.toString();
                    }

                }

                catch (AuthenticationException ex) {
                    //no authentication data for given SAML artifact
                    statusCode = "samlp:Requester";
                    subStatusCode = "samlp:ResourceNotRecognized";
                    statusMessage = ex.toString();
                }
            }
        } catch (Throwable t) {
            // invalid request format
            statusCode = "samlp:Requester";
            statusMessageCode = "1204";
        }
    }

    try {
        String responseID = Random.nextRandom();
        String issueInstant = DateTimeUtils.buildDateTimeUTC(Calendar.getInstance());

        if (statusMessage == null)
            statusMessage = MOAIDMessageProvider.getInstance().getMessage(statusMessageCode, null);
        responses[0] = new SAMLResponseBuilder().build(responseID, requestID, issueInstant, statusCode,
                subStatusCode, statusMessage, samlAssertion);

    } catch (MOAIDException e) {
        AxisFault fault = AxisFault.makeFault(e);
        fault.setFaultDetail(new Element[] { e.toErrorResponse() });
        throw fault;
    } catch (Throwable t) {
        MOAIDException e = new MOAIDException("1299", null, t);
        AxisFault fault = AxisFault.makeFault(e);
        fault.setFaultDetail(new Element[] { e.toErrorResponse() });
        throw fault;
    }
    return responses;
}

From source file:edu.ucdenver.ccp.nlp.ae.dict_util.GeneInfoToDictionary.java

private String buildSynonymLine(String name, StringBuilder buf) {
    if (filterSingleLetterTerms && name.length() <= 1) {
        return "";
    }/*ww  w .  ja  v  a2 s. c o  m*/
    name = StringEscapeUtils.escapeXml(name);

    buf.append("\t<variant base=\"");
    buf.append(name);
    buf.append("\"/>\n");

    return buf.toString();
}

From source file:edu.lternet.pasta.portal.search.AuthorSearch.java

/**
 * Parses the Solr query results using regular expression matching (as
 * opposed to XML parsing)//w  ww. j  a  v  a  2s  .  c o  m
 * 
 * @param xml             the Solr query results, an XML document string
 * @param fieldName       the field name to parse out of the XML, e.g. "author"
 * @return                a String array of field values parsed from the XML
 */
private static String[] parseQueryResults(String xml, String fieldName) {
    String[] values = null;
    final String patternStr = String.format("^\\s*<%s>(.+)</%s>\\s*$", fieldName, fieldName);
    Pattern pattern = Pattern.compile(patternStr);
    TreeSet<String> valueSet = new TreeSet<String>();

    if (xml != null) {
        String[] lines = xml.split("\n");
        for (String line : lines) {
            Matcher matcher = pattern.matcher(line);
            if (matcher.matches()) {
                String capturedValue = matcher.group(1).trim();
                String unescapedXML = StringEscapeUtils.unescapeXml(capturedValue);
                String trimmedXML = unescapedXML.replace("\r", " ").replace("\n", " ").replaceAll("\\s+", " ")
                        .trim();
                String escapedXML = StringEscapeUtils.escapeXml(trimmedXML);
                valueSet.add(escapedXML);
            }
        }

        values = valueSet.toArray(new String[valueSet.size()]);
    }

    return values;
}

From source file:net.jeremybrooks.readsy.bo.ReadsyDataFile.java

/**
 * Write the file./*from   ww w .j  av  a 2 s. c  o m*/
 * The current contents of this object will be written to the file specified
 * when the object was created.  If the file already exists, it will be
 * replaced.
 *
 * @throws IOException if any errors occur.
 */
public void write() throws IOException {
    // force version 1, which is the version this method writes
    this.root.setVersion(1);

    File f = this.root.getFile();
    BufferedWriter out = null;
    logger.debug("File is " + f.getAbsolutePath());
    try {
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8"));

        // THE FIRST PART OF THE FILE
        out.write(XML_ELEMENT);
        out.write('\n');
        out.write("<document description=\"");
        out.write(this.root.getDescription());
        out.write("\" shortDescription=\"");
        out.write(this.root.getShortDescription());
        out.write("\" year=\"");
        out.write((new Integer(this.root.getYear())).toString());
        out.write("\" version=\"");
        out.write((new Integer(this.root.getVersion())).toString());
        out.write("\">");
        out.write('\n');
        logger.debug("Ready to write " + this.entryList.size() + " records.");
        for (ReadsyEntryElement entry : this.entryList) {
            out.write("<entry date=\"");
            out.write(entry.getDate());
            out.write("\">");
            out.write('\n');
            out.write("<heading>");
            out.write(StringEscapeUtils.escapeXml(entry.getHeading()));
            out.write("</heading>");
            out.write('\n');
            out.write("<text>");
            out.write(StringEscapeUtils.escapeXml(entry.getText()));
            out.write("</text>");
            out.write('\n');
            out.write("</entry>");
            out.write('\n');
        }

        logger.debug("Wrote entry list successfully.");

        out.write("</document>");
        out.write('\n');

        out.flush();

    } catch (Exception e) {
        logger.error("ERROR WRITING FILE " + f.getAbsolutePath(), e);
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        throw new IOException("Error writing file " + f.getAbsolutePath() + sw.toString());

    } finally {
        IOUtil.close(out);
    }
}

From source file:eionet.gdem.dto.ConversionResultDto.java

/**
 * Gets conversion log as HTML//from www  . j a v  a  2  s.co  m
 * @return
 */
public String getConversionLogAsHtml() {
    StringBuilder strBuilder = new StringBuilder();

    strBuilder.append("<div class=\"feedback\">");
    strBuilder.append("<h2>Conversion log</h2>");
    if (!Utils.isNullStr(getStatusDescription())) {
        strBuilder.append(getResultAsHtml());
    }
    if (!Utils.isNullStr(getSourceUrl())) {
        strBuilder.append(
                "<div>Converted file: <a href=\"" + getSourceUrl() + "\">" + getSourceUrl() + "</a></div>");
    }
    if (!Utils.isNullList(conversionLogs)) {
        strBuilder.append("<table class=\"datatable\">");
        strBuilder.append("<tr><th>Log level</th><th>Category</th><th>Log message</th></tr>");
        for (ConversionLogDto conversionLog : conversionLogs) {
            strBuilder.append("<tr><td");
            switch (conversionLog.getType()) {
            case CRITICAL:
                strBuilder.append(" style=\"color:red\"");
            case ERROR:
                strBuilder.append(" style=\"color:red\"");
            case WARNING:
                strBuilder.append(" style=\"color:orange\"");
            }
            strBuilder.append(">");
            strBuilder.append(conversionLog.getType());
            strBuilder.append("</td><td>");
            strBuilder.append(StringEscapeUtils.escapeXml(conversionLog.getCategory()));
            strBuilder.append("</td><td>");
            strBuilder.append(StringEscapeUtils.escapeXml(conversionLog.getMessage()));
            strBuilder.append("</td></tr>");
        }
        strBuilder.append("</table>");
    } else {
        strBuilder.append("<p>Conversion log not found.</p>");
    }
    strBuilder.append("</div>");
    return strBuilder.toString();
}