Example usage for com.google.common.xml XmlEscapers xmlContentEscaper

List of usage examples for com.google.common.xml XmlEscapers xmlContentEscaper

Introduction

In this page you can find the example usage for com.google.common.xml XmlEscapers xmlContentEscaper.

Prototype

public static Escaper xmlContentEscaper() 

Source Link

Document

Returns an Escaper instance that escapes special characters in a string so it can safely be included in an XML document as element content.

Usage

From source file:org.robotframework.ide.eclipse.main.plugin.refactoring.Changes.java

static IPath escapeXmlCharacters(final IPath path) {
    return Path.fromPortableString(XmlEscapers.xmlContentEscaper().escape(path.toPortableString()));
}

From source file:com.google.template.soy.xliffmsgplugin.XliffGenerator.java

/**
 * Generates the output XLIFF file content for a given SoyMsgBundle.
 *
 * @param msgBundle The SoyMsgBundle to process.
 * @param sourceLocaleString The source language/locale string of the messages.
 * @param targetLocaleString The target language/locale string of the messages (optional). If
 *     specified, the resulting XLIFF file will specify this target language and will contain
 *     empty 'target' tags. If not specified, the resulting XLIFF file will not contain target
 *     language and will not contain 'target' tags.
 * @return The generated XLIFF file content.
 *//*from   w  w w .jav  a2s.  c o m*/
static CharSequence generateXliff(SoyMsgBundle msgBundle, String sourceLocaleString,
        @Nullable String targetLocaleString) {

    Escaper attributeEscaper = XmlEscapers.xmlAttributeEscaper();
    Escaper contentEscaper = XmlEscapers.xmlContentEscaper();

    boolean hasTarget = targetLocaleString != null && targetLocaleString.length() > 0;

    IndentedLinesBuilder ilb = new IndentedLinesBuilder(2);
    ilb.appendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    ilb.appendLine("<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\">");
    ilb.increaseIndent();
    ilb.appendLineStart("<file original=\"SoyMsgBundle\" datatype=\"x-soy-msg-bundle\"",
            " xml:space=\"preserve\"", " source-language=\"", attributeEscaper.escape(sourceLocaleString),
            "\"");
    if (hasTarget) {
        ilb.appendParts(" target-language=\"", attributeEscaper.escape(targetLocaleString), "\"");
    }
    ilb.appendLineEnd(">");
    ilb.increaseIndent();
    ilb.appendLine("<body>");
    ilb.increaseIndent();

    for (SoyMsg msg : msgBundle) {

        // Begin 'trans-unit'.
        ilb.appendLineStart("<trans-unit id=\"", Long.toString(msg.getId()), "\"");
        String contentType = msg.getContentType();
        if (contentType != null && contentType.length() > 0) {
            String xliffDatatype = CONTENT_TYPE_TO_XLIFF_DATATYPE_MAP.get(contentType);
            if (xliffDatatype == null) {
                xliffDatatype = contentType; // just use the contentType string
            }
            ilb.appendParts(" datatype=\"", attributeEscaper.escape(xliffDatatype), "\"");
        }
        ilb.appendLineEnd(">");
        ilb.increaseIndent();

        // Source.
        ilb.appendLineStart("<source>");
        for (SoyMsgPart msgPart : msg.getParts()) {
            if (msgPart instanceof SoyMsgRawTextPart) {
                String rawText = ((SoyMsgRawTextPart) msgPart).getRawText();
                ilb.append(contentEscaper.escape(rawText));
            } else {
                String placeholderName = ((SoyMsgPlaceholderPart) msgPart).getPlaceholderName();
                ilb.appendParts("<x id=\"", attributeEscaper.escape(placeholderName), "\"/>");
            }
        }
        ilb.appendLineEnd("</source>");

        // Target.
        if (hasTarget) {
            ilb.appendLine("<target/>");
        }

        // Description and meaning.
        String desc = msg.getDesc();
        if (desc != null && desc.length() > 0) {
            ilb.appendLine("<note priority=\"1\" from=\"description\">", contentEscaper.escape(desc),
                    "</note>");
        }
        String meaning = msg.getMeaning();
        if (meaning != null && meaning.length() > 0) {
            ilb.appendLine("<note priority=\"1\" from=\"meaning\">", contentEscaper.escape(meaning), "</note>");
        }

        // End 'trans-unit'.
        ilb.decreaseIndent();
        ilb.appendLine("</trans-unit>");
    }

    ilb.decreaseIndent();
    ilb.appendLine("</body>");
    ilb.decreaseIndent();
    ilb.appendLine("</file>");
    ilb.decreaseIndent();
    ilb.appendLine("</xliff>");

    return ilb;
}

From source file:org.eobjects.analyzer.beans.codec.XmlEncoderTransformer.java

@Override
public String[] transform(final InputRow inputRow) {
    final String value = inputRow.getValue(column);
    if (value == null) {
        return new String[1];
    }/*from  ww w.  j a  v a2  s.  c o  m*/
    final Escaper escaper;
    if (targetFormat == TargetFormat.Content) {
        escaper = XmlEscapers.xmlContentEscaper();
    } else {
        escaper = XmlEscapers.xmlAttributeEscaper();
    }
    final String escaped = escaper.escape(value);
    return new String[] { escaped };
}

From source file:org.roda.core.common.MetadataFileUtils.java

public static String escapeContent(String value) {
    return XmlEscapers.xmlContentEscaper().escape(value);
}

From source file:org.n52.sos.encode.XmlStreamWriter.java

@Override
protected void chars(String chars, boolean escape) throws XMLStreamException {
    if (escape) {
        chars = XmlEscapers.xmlContentEscaper().escape(chars);
    }/*  w  ww.  ja v  a 2  s .co  m*/
    getXmlWriter().writeCharacters(chars);
}

From source file:io.sarl.lang.mwe2.externalspec.AbstractXmlHighlightingFragment2.java

/** Create a tag with a value.
 *
 * @param tag the name of the tag./*from  w w w .  ja v  a2 s  . c  o  m*/
 * @param value the value.
 * @param nameValuePairs the parameters of the tag (name-value pairs).
 */
protected void valuedTag(String tag, String value, String... nameValuePairs) {
    StringBuilder line = new StringBuilder();
    line.append(indent());
    line.append("<").append(tag); //$NON-NLS-1$
    for (int i = 0; i < nameValuePairs.length; i = i + 2) {
        line.append(" "); //$NON-NLS-1$
        line.append(nameValuePairs[i]);
        line.append("=\""); //$NON-NLS-1$
        line.append(XmlEscapers.xmlAttributeEscaper().escape(nameValuePairs[i + 1]));
        line.append("\""); //$NON-NLS-1$
    }
    line.append(">"); //$NON-NLS-1$
    String escapedValue = XmlEscapers.xmlContentEscaper().escape(value);
    line.append(escapedValue);
    if (escapedValue.endsWith(getCodeConfig().getLineDelimiter())) {
        line.append(indent());
    }
    line.append("</").append(tag).append(">"); //$NON-NLS-1$ //$NON-NLS-2$
    this.lines.add(line.toString());
}

From source file:org.n52.sos.encode.XmlEventWriter.java

@Override
protected void chars(String chars, boolean escape) throws XMLStreamException {
    if (escape) {
        chars = XmlEscapers.xmlContentEscaper().escape(chars);
    }//from   w  w  w. j  a  v a2s .co  m
    getXmlWriter().add(getXmlEventFactory().createCharacters(chars));
}

From source file:org.languagetool.dev.archive.RuleSimplifier.java

private String getRegex(PatternRule rule) {
    StringBuilder sb = new StringBuilder();
    List<PatternToken> tokens = rule.getPatternTokens();
    boolean hasCSParts = tokens.stream().anyMatch(PatternToken::isCaseSensitive);
    boolean allCSParts = tokens.stream().allMatch(PatternToken::isCaseSensitive);
    for (PatternToken patternToken : rule.getPatternTokens()) {
        String str = patternToken.getString();
        boolean setAllParenthesis = containsBackRef(rule.getMessage())
                || containsBackRef(rule.getSuggestionsOutMsg());
        if (hasCSParts && !allCSParts && !patternToken.isCaseSensitive()) {
            sb.append("(?i:");
            appendTokenString(sb, str, setAllParenthesis);
            sb.append(")");
        } else {/*from   www. ja  v a  2 s  .  com*/
            appendTokenString(sb, str, setAllParenthesis);
        }
        sb.append(" ");
    }
    String escapedRegex = XmlEscapers.xmlContentEscaper().escape(sb.toString().trim());
    if (allCSParts) {
        return "<regexp case_sensitive='yes'>" + escapedRegex + "</regexp>";
    }
    return "<regexp>" + escapedRegex + "</regexp>";
}

From source file:net.java.sip.communicator.impl.history.HistoryWriterImpl.java

/**
 * Adds new record to the current history document
 * when the record property name ends with _CDATA this is removed from the
 * property name and a CDATA text node is created to store the text value
 *
 * @param propertyNames String[]//from w w  w .  ja v a  2  s  .  c  o m
 * @param propertyValues String[]
 * @param date Date
 * @param maxNumberOfRecords the maximum number of records to keep or
 * value of -1 to ignore this param.
 * @throws InvalidParameterException
 * @throws IOException
 */
private void addRecord(String[] propertyNames, String[] propertyValues, Date date, int maxNumberOfRecords)
        throws InvalidParameterException, IOException {
    // Synchronized to assure that two concurrent threads can insert records
    // safely.
    synchronized (this.docCreateLock) {
        if (this.currentDoc == null || this.currentDocElements > MAX_RECORDS_PER_FILE) {
            this.createNewDoc(date, this.currentDoc == null);
        }
    }

    synchronized (this.currentDoc) {
        Node root = this.currentDoc.getFirstChild();
        synchronized (root) {
            // if we have setting for max number of records,
            // check the number and when exceed them, remove the first one
            if (maxNumberOfRecords > -1 && this.currentDocElements >= maxNumberOfRecords) {
                // lets remove the first one
                removeFirstRecord(root);
            }

            Element elem = this.currentDoc.createElement("record");
            SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
            elem.setAttribute("timestamp", sdf.format(date));

            for (int i = 0; i < propertyNames.length; i++) {
                String propertyName = propertyNames[i];

                if (propertyName.endsWith(CDATA_SUFFIX)) {
                    if (propertyValues[i] != null) {
                        propertyName = propertyName.replaceFirst(CDATA_SUFFIX, "");

                        Element propertyElement = this.currentDoc.createElement(propertyName);

                        Text value = this.currentDoc.createCDATASection(XmlEscapers.xmlContentEscaper()
                                .escape(propertyValues[i].replaceAll("\0", " ")));
                        propertyElement.appendChild(value);

                        elem.appendChild(propertyElement);
                    }
                } else {
                    if (propertyValues[i] != null) {
                        Element propertyElement = this.currentDoc.createElement(propertyName);

                        Text value = this.currentDoc.createTextNode(XmlEscapers.xmlContentEscaper()
                                .escape(propertyValues[i].replaceAll("\0", " ")));
                        propertyElement.appendChild(value);

                        elem.appendChild(propertyElement);
                    }
                }
            }

            root.appendChild(elem);
            this.currentDocElements++;
        }
    }

    // write changes
    synchronized (this.docWriteLock) {
        if (historyImpl.getHistoryServiceImpl().isCacheEnabled())
            this.historyImpl.writeFile(this.currentFile);
        else
            this.historyImpl.writeFile(this.currentFile, this.currentDoc);
    }
}

From source file:com.google.testing.junit.runner.model.XmlWriter.java

/**
 * Writes the given characters as the content of the element. Closes the
 * element if it is currently open./*from www.  ja  va 2s.co  m*/
 *
 * @param text String to append to the current content of the element
 * @throws IOException
 */
public void writeCharacters(String text) throws IOException {
    closeElement();
    if (text == null || text.isEmpty()) {
        return;
    }
    writer.write(XmlEscapers.xmlContentEscaper().escape(text));
}