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

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

Introduction

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

Prototype

public static final String escapeJava(final String input) 

Source Link

Document

Escapes the characters in a String using Java String rules.

Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)

So a tab becomes the characters '\\' and 't' .

The only difference between Java strings and JavaScript strings is that in JavaScript, a single quote and forward-slash (/) are escaped.

Example:

 input string: He didn't say, "Stop!" 

Usage

From source file:org.bonitasoft.platform.setup.command.configure.BundleConfigurator.java

protected static String getDatabaseConnectionUrlForPropertiesFile(DatabaseConfiguration configuration) {
    String url = getDatabaseConnectionUrl(configuration);
    if (H2.equals(configuration.getDbVendor())) {
        url = StringEscapeUtils.escapeJava(url);
    }//from  www  . j a  v  a2 s  .  c  o m
    return Matcher.quoteReplacement(url);
}

From source file:org.csstudio.archive.engine.server.json.JSONStructure.java

/**
 * Formats a string for JSON.//from  w  w w. ja v  a  2  s . c  om
 * @param str The string to format.
 * @return A correctly formatted string.
 */
protected String formatString(final String str) {
    return "\"" + StringEscapeUtils.escapeJava(str) + "\"";
}

From source file:org.displaytag.export.excel.ExcelUtils.java

/**
 * Escape certain values that are not permitted in excel cells.
 * @param rawValue the object value/*from   w  w w.j  a va  2 s  .c  om*/
 * @return the escaped value
 */
public static String escapeColumnValue(Object rawValue) {
    if (rawValue == null) {
        return null;
    }
    // str = Patterns.replaceAll(str, "(\\r\\n|\\r|\\n|\\n\\r)\\s*", "");
    String returnString = rawValue.toString();
    // escape the String to get the tabs, returns, newline explicit as \t \r \n
    returnString = StringEscapeUtils.escapeJava(StringUtils.trimToEmpty(returnString));
    // remove tabs, insert four whitespaces instead
    returnString = StringUtils.replace(StringUtils.trim(returnString), "\\t", "    ");
    // remove the return, only newline valid in excel
    returnString = StringUtils.replace(StringUtils.trim(returnString), "\\r", " ");
    // unescape so that \n gets back to newline
    returnString = StringEscapeUtils.unescapeJava(returnString);
    return returnString;
}

From source file:org.evosuite.junit.TestSuiteWriter.java

private void generateSetSystemProperties(StringBuilder bd, List<ExecutionResult> results) {

    if (!Properties.REPLACE_CALLS) {
        return;//  w  w w.  ja  va 2 s  .c  o m
    }

    bd.append(METHOD_SPACE);
    bd.append("public void setSystemProperties() {\n");
    bd.append(" \n");
    if (shouldResetProperties(results)) {
        /*
         * even if we set all the properties that were read, we still need
         * to reset everything to handle the properties that were written 
         */
        bd.append(BLOCK_SPACE);
        bd.append(getResetPropertiesCommand());
        bd.append(" \n");

        Set<String> readProperties = mergeProperties(results);
        for (String prop : readProperties) {
            bd.append(BLOCK_SPACE);
            String currentValue = System.getProperty(prop);
            String escaped_prop = StringEscapeUtils.escapeJava(prop);
            if (currentValue != null) {
                String escaped_currentValue = StringEscapeUtils.escapeJava(currentValue);
                bd.append("java.lang.System.setProperty(\"" + escaped_prop + "\", \"" + escaped_currentValue
                        + "\"); \n");
            } else {
                bd.append("java.lang.System.clearProperty(\"" + escaped_prop + "\"); \n");
            }
        }
    } else {
        bd.append(BLOCK_SPACE + "/*No java.lang.System property to set*/\n");
    }

    bd.append(METHOD_SPACE);
    bd.append("}\n");

}

From source file:org.evosuite.junit.writer.Scaffolding.java

private void generateSetSystemProperties(StringBuilder bd, List<ExecutionResult> results) {

    if (!Properties.REPLACE_CALLS) {
        return;/*from   w w  w  . j a v  a  2 s.co m*/
    }

    bd.append(METHOD_SPACE);
    bd.append("public static void setSystemProperties() {\n");
    bd.append(" \n");
    if (TestSuiteWriterUtils.shouldResetProperties(results)) {
        /*
         * even if we set all the properties that were read, we still need
         * to reset everything to handle the properties that were written
         */
        bd.append(BLOCK_SPACE);
        bd.append(getResetPropertiesCommand());
        bd.append(" \n");

        Set<String> readProperties = TestSuiteWriterUtils.mergeProperties(results);
        for (String prop : readProperties) {
            String currentValue = java.lang.System.getProperty(prop);
            String escaped_prop = StringEscapeUtils.escapeJava(prop);
            if (currentValue != null) {
                String escaped_currentValue = StringEscapeUtils.escapeJava(currentValue);
                bd.append(BLOCK_SPACE);
                bd.append("java.lang.System.setProperty(\"" + escaped_prop + "\", \"" + escaped_currentValue
                        + "\"); \n");
            } else {
                /*
                 * In theory, we do not need to clear properties, as that is
                 * done with the reset to default. Avoiding doing the clear
                 * is not only good for readability (ie, less commands) but
                 * also to avoid crashes when properties are set based on
                 * SUT inputs. Eg, in classes like SassToCssBuilder in
                 * 108_liferay we ended up with hundreds of thousands set
                 * properties...
                 */
                // bd.append("java.lang.System.clearProperty(\"" +
                // escaped_prop + "\"); \n");
            }
        }
    } else {
        bd.append(BLOCK_SPACE + "/*No java.lang.System property to set*/\n");
    }

    bd.append(METHOD_SPACE);
    bd.append("}\n");

}

From source file:org.evosuite.testcase.TestCodeVisitor.java

/**
 * Returns a catch block for an exception that can be thrown by this
 * statement. The caught exception type is the actual class of the exception
 * object passed as parameter (or one of its superclass if the type is not
 * public). This method can be overridden to inject code in the catch block
 **///from  w  w  w.  java  2 s  . c om
public String generateCatchBlock(AbstractStatement statement, Throwable exception) {
    String result = "";

    Class<?> ex = getExceptionClassToUse(exception);

    // preparing the catch block
    if (!(exception instanceof RuntimeException) && !(exception instanceof Error)) {
        // This is a checked exception.
        if (statement.isDeclaredException(exception)) {
            result += " catch(" + getClassName(ex) + " e) {" + NEWLINE;
        } else {
            // A checked exception that is not declared cannot be thrown according to the JVM spec.
            // And yet, it is possible, which is probably a bug in Java. See class org.apache.commons.lang3.time.FastDatePrinter:
            //     @Override
            //     public <B extends Appendable> B format(final Date date, final B buf) {
            //        final Calendar c = newCalendar();  // hard code GregorianCalendar
            //        c.setTime(date);
            //        return applyRules(c, buf);
            //     }
            // Passing in a PipeWriter will lead to an IOException.
            // As a workaround, we'll just check for Throwable
            //
            result += " catch(" + getClassName(Throwable.class) + " e) {" + NEWLINE;
        }
    } else {
        result += " catch(" + getClassName(ex) + " e) {" + NEWLINE;
    }

    // adding the message of the exception
    String exceptionMessage;
    try {
        if (exception.getMessage() != null) {
            exceptionMessage = exception.getMessage().replace("*/", "*_/");
        } else {
            exceptionMessage = "no message in exception (getMessage() returned null)";
        }
    } catch (Exception exceptionThownExecutionGetMessage) {
        exceptionMessage = "no message (getMessage() has thrown an exception)";
    }

    String sourceClass = getSourceClassName(exception);

    if (sourceClass == null || isValidSource(sourceClass)) {
        /*
           do not print comments if it was a non-valid source.
           however, if source is undefined, then it should be OK
         */
        result += "   //" + NEWLINE;
        for (String msg : exceptionMessage.split("\n")) {
            result += "   // " + StringEscapeUtils.escapeJava(msg) + NEWLINE;
        }
        result += "   //" + NEWLINE;
    }

    if (sourceClass != null && isValidSource(sourceClass) && isExceptionToAssertThrownBy(ex)) {
        /*
           do not check source if it comes from a non-runtime evosuite
           class. this could happen if source is an instrumentation done
           during search which is not applied to runtime
         */

        //from class EvoAssertions
        result += "   verifyException(\"" + sourceClass + "\", e);" + NEWLINE;
    }

    // Add assertion on the message (feel free to remove the isRegression() Condition)
    if (Properties.isRegression() && exception.getMessage() != null) {
        result += "   assertTrue(e.getMessage().equals(\"" + StringEscapeUtils.escapeJava(exceptionMessage)
                + "\"));";
        result += "   \n";
    }

    result += "}" + NEWLINE;// closing the catch block
    return result;
}

From source file:org.evosuite.utils.NumberFormatter.java

/**
 * <p>//  w  w  w. j a v  a2 s . c  o  m
 * getNumberString
 * </p>
 * 
 * @param value
 *            a {@link java.lang.Object} object.
 * @return a {@link java.lang.String} object.
 */
public static String getNumberString(Object value) {
    if (value == null)
        return "null";
    else if (value.getClass().equals(char.class) || value.getClass().equals(Character.class)) {
        // StringEscapeUtils fails to escape a single quote char
        if (Character.valueOf('\'').equals(value)) {
            return "'\\\''";
        } else {
            return "'" + StringEscapeUtils.escapeJava(Character.toString((Character) value)) + "'";
        }
    } else if (value.getClass().equals(String.class)) {
        return "\"" + StringEscapeUtils.escapeJava((String) value) + "\"";
    } else if (value.getClass().equals(float.class) || value.getClass().equals(Float.class)) {
        if (value.toString().equals("" + Float.NaN))
            return "Float.NaN";
        else if (value.toString().equals("" + Float.NEGATIVE_INFINITY))
            return "Float.NEGATIVE_INFINITY";
        else if (value.toString().equals("" + Float.POSITIVE_INFINITY))
            return "Float.POSITIVE_INFINITY";
        else if (((Float) value) < 0F)
            return "(" + value + "F)";
        else
            return value + "F";
    } else if (value.getClass().equals(double.class) || value.getClass().equals(Double.class)) {
        if (value.toString().equals("" + Double.NaN))
            return "Double.NaN";
        else if (value.toString().equals("" + Double.NEGATIVE_INFINITY))
            return "Double.NEGATIVE_INFINITY";
        else if (value.toString().equals("" + Double.POSITIVE_INFINITY))
            return "Double.POSITIVE_INFINITY";
        else if (((Double) value) < 0.0)
            return "(" + value + ")";
        else
            return value.toString();
    } else if (value.getClass().equals(long.class) || value.getClass().equals(Long.class)) {
        if (((Long) value) < 0)
            return "(" + value + "L)";
        else
            return value + "L";
    } else if (value.getClass().equals(byte.class) || value.getClass().equals(Byte.class)) {
        if (((Byte) value) < 0)
            return "(byte) (" + value + ")";
        else
            return "(byte)" + value;
    } else if (value.getClass().equals(short.class) || value.getClass().equals(Short.class)) {
        if (((Short) value) < 0)
            return "(short) (" + value + ")";
        else
            return "(short)" + value;
    } else if (value.getClass().equals(int.class) || value.getClass().equals(Integer.class)) {
        int val = ((Integer) value).intValue();
        if (val == Integer.MAX_VALUE)
            return "Integer.MAX_VALUE";
        else if (val == Integer.MIN_VALUE)
            return "Integer.MIN_VALUE";
        else if (((Integer) value) < 0)
            return "(" + value + ")";
        else
            return "" + val;
    } else if (value.getClass().isEnum() || value instanceof Enum) {
        // java.util.concurrent.TimeUnit is an example where the enum
        // elements are anonymous inner classes, and then isEnum does
        // not return true apparently? So we check using instanceof as well.

        Class<?> clazz = value.getClass();
        String className = clazz.getSimpleName();
        while (clazz.getEnclosingClass() != null) {
            String enclosingName = clazz.getEnclosingClass().getSimpleName();
            className = enclosingName + "." + className;
            clazz = clazz.getEnclosingClass();
        }

        // We have to do this here to avoid a double colon in the TimeUnit example
        if (!className.endsWith("."))
            className += ".";
        try {
            if (value.getClass().getField(value.toString()) != null)
                return className + value;
            else if (((Enum<?>) value).name() != null)
                return className + ((Enum<?>) value).name();
            else
                return "Enum.valueOf(" + className + "class, \"" + value + "\")";
        } catch (Exception e) {
            if (((Enum<?>) value).name() != null)
                return className + ((Enum<?>) value).name();
            else
                return "Enum.valueOf(" + className + "class /* " + e + " */, \"" + value + "\")";
            // return className + "valueOf(\"" + value + "\")";
        }
    } else if (value.getClass().equals(Boolean.class)) {
        return value.toString();
    } else {
        // This should not happen
        assert (false);
        return value.toString();
    }
}

From source file:org.evosuite.utils.StringUtil.java

public static String getEscapedString(String original) {
    char[] charArray = StringEscapeUtils.escapeJava((String) original).toCharArray();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < charArray.length; ++i) {
        char a = charArray[i];
        if (a > 255) {
            sb.append("\\u");
            sb.append(Integer.toHexString(a));
        } else {/*  www .  j  a  v  a  2s  . com*/
            sb.append(a);
        }
    }
    return sb.toString();
}

From source file:org.framework.statemachine.state.Graph.java

private static String wrapSafeString(String label) {
    if (label.indexOf(',') >= 0) {
        if (label.length() > 14) {
            label = label.replaceAll(",", ",\n");
        }//  www . j  av a 2  s . c  o  m
    }
    label = "\"" + StringEscapeUtils.escapeJava(label) + "\"";
    return label;
}

From source file:org.grouplens.lenskit.eval.graph.GraphWriter.java

private String safeValue(Object obj) {
    String str = obj.toString();// w  ww.j a  v a  2s .co  m
    if (obj instanceof HTMLLabel || SAFE_VALUE.matcher(str).matches()) {
        return str;
    } else {
        return "\"" + StringEscapeUtils.escapeJava(str) + "\"";
    }
}