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:FstDotWriter.java

public void writeDotArc(int srcstate, int deststate, int input, int output) {
    //String isym = StringEscapeUtils.escapeXml(symmap.getsym(input)) ;
    String isym = StringEscapeUtils.escapeJava(symmap.getsym(input));
    if (isym.equals("\\\\")) {
        isym = "\\\\\\\\"; // literal backslash
    } else if (isym.startsWith("\\")) {
        isym = "\\" + isym;
    }/*from   ww w .  ja  v  a 2 s  .com*/
    //String osym = StringEscapeUtils.escapeXml(symmap.getsym(output)) ;
    String osym = StringEscapeUtils.escapeJava(symmap.getsym(output));
    if (osym.equals("\\\\")) {
        osym = "\\\\\\\\"; // literal backslash
    } else if (osym.startsWith("\\")) {
        osym = "\\" + osym;
    }
    try {
        out.write("  " + srcstate + " -> " + deststate + " [label = \"" + isym + ":" + osym + "\"] ;\n");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:au.org.ands.vocabs.toolkit.provider.publish.SISSVocPublishProvider.java

/** Add the additional properties as provided in the subtask
 * specification. Values are escaped using StringEscapeUtils.escapeJava()
 * to prevent nasty injection.//from  w ww  .  j  a  v a2s  . c  o m
 * @param subtask The specification of this publish subtask
 */
private void addAdditionalSpecProperties(final JsonNode subtask) {
    if (subtask.get(SPEC_SETTINGS_KEY) == null) {
        // No additional properties specified.
        return;
    }
    for (Iterator<Entry<String, JsonNode>> nodeIterator = subtask.get(SPEC_SETTINGS_KEY).fields(); nodeIterator
            .hasNext();) {
        Entry<String, JsonNode> specProperty = nodeIterator.next();
        logger.debug("addAdditionalSpecProperties replacing with" + " value: "
                + specProperty.getValue().textValue());
        specProperties.put(specProperty.getKey(),
                StringEscapeUtils.escapeJava(specProperty.getValue().textValue()));
    }
}

From source file:com.thinkbiganalytics.discovery.parsers.csv.CSVFileSchemaParser.java

private String stringForCharacter(String s) {
    if (StringUtils.isEmpty(s)) {
        return null;
    }/*w ww . j ava  2  s .c o  m*/
    Character c = s.charAt(0);

    switch (c) {
    case ';':
        return "\\;";
    case '\t':
        return "\\t";
    case '\'':
        return "\\\'";
    case '\\':
        return "\\\\";
    default:
        return StringEscapeUtils.escapeJava(c.toString());
    }
}

From source file:CSVTools.CsvToolsApi.java

/**
 * Escape a string/* w  w  w .ja  v  a  2  s .  com*/
 *
 * @param withQuoteCharacter
 * @return
 */
public String escapeQuotes(String withQuoteCharacter) {
    String output = withQuoteCharacter;
    if (withQuoteCharacter.contains("\"")) {
        output = StringEscapeUtils.escapeJava(withQuoteCharacter);
        output = output.replaceAll("'", "''");

    }

    return output;

}

From source file:com.amazonaws.samples.SamplesGenerator.java

private String formatPrimitiveValue(final String type, final String value) {
    if (type.equals("String")) {
        return String.format("\"%s\"", StringEscapeUtils.escapeJava(value));
    } else if (type.equals("Boolean")) {
        return value.toLowerCase();
    } else if (type.equals("Long")) {
        return value + "L";
    } else if (type.equals("Double")) {
        return value + "d";
    } else if (type.equals("Float")) {
        return value + "f";
    } else if (type.equals("Date")) {
        return String.format("new Date(\"%s\")", StringEscapeUtils.escapeJava(value));
    } else if (type.equals("ByteBuffer")) {
        return String.format("ByteBuffer.wrap(\"%s\".getBytes())", StringEscapeUtils.escapeJava(value));
    } else {/*from w w  w  . j av a  2s  .com*/
        return value;
    }
}

From source file:edu.harvard.i2b2.fhir.I2b2Util.java

@Deprecated
public static String getAllDataPDO(String i2b2User, String i2b2Token, String i2b2Url, String I2b2Domain,
        String project, String patientId, List<String> items) throws FhirCoreException {
    try {/* w  w w  .  jav a  2 s. c o m*/
        logger.trace("got params:" + i2b2User + "-" + i2b2Token + "-" + i2b2Url + "-" + I2b2Domain + "-"
                + project + "-" + patientId + "-" + items);
        String requestXml = IOUtils.toString(
                I2b2Util.class.getResourceAsStream("/i2b2query/i2b2RequestEmptyFilterForAPatient.xml"));

        String panelXml = "";
        int count = 0;
        for (String item : items) {
            count++;
            String singlePanelXml = IOUtils
                    .toString(I2b2Util.class.getResourceAsStream("/i2b2query/panel.xml"));

            item = StringEscapeUtils.escapeJava(item);
            singlePanelXml = replaceXMLString(singlePanelXml, "//panel/item/item_key", item);
            singlePanelXml = replaceXMLString(singlePanelXml, "//panel/panel_number", Integer.toString(count));
            panelXml += singlePanelXml;
            logger.trace("singlePanelXml:" + singlePanelXml);
        }
        //panelXml=StringEscapeUtils.unescapeXml(panelXml);

        requestXml = requestXml.replaceAll("PANEL", panelXml);

        requestXml = I2b2Util.insertI2b2ParametersInXml(requestXml, i2b2User, i2b2Token, i2b2Url, I2b2Domain,
                project);

        if (patientId != null)
            requestXml = requestXml.replaceAll("PATIENTID", patientId);

        String responseXml = WebServiceCall.run(i2b2Url + "/services/QueryToolService/pdorequest", requestXml);
        logger.trace("got response:" + responseXml);
        logger.trace("" + XQueryUtil.getStringSequence("//observation", responseXml).size());
        return responseXml;
    } catch (java.net.ConnectException e) {
        logger.error(e.getMessage(), e);
        throw new FhirCoreException(e);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}

From source file:com.kenshoo.freemarker.services.FreeMarkerService.java

/**
 * @param templateSourceCode// w w  w.j  a  v  a 2 s.  c  o  m
 *            The FTL to execute; not {@code null}.
 * @param dataModel
 *            The FreeMarker data-model to execute the template with; maybe {@code null}.
 * @param outputFormat
 *            The output format to execute the template with; maybe {@code null}.
 * @param locale
 *            The locale to execute the template with; maybe {@code null}.
 * @param timeZone
 *            The time zone to execute the template with; maybe {@code null}.
 * 
 * @return The result of the template parsing and evaluation. The method won't throw exception if that fails due to
 *         errors in the template provided, instead it indicates this fact in the response object. That's because
 *         this is a service for trying out the template language, so such errors are part of the normal operation.
 * 
 * @throws RejectedExecutionException
 *             If the service is overburden and thus doing the calculation was rejected.
 * @throws FreeMarkerServiceException
 *             If the calculation fails from a reason that's not a mistake in the template and doesn't fit the
 *             meaning of {@link RejectedExecutionException} either.
 */
public FreeMarkerServiceResponse calculateTemplateOutput(String templateSourceCode, Object dataModel,
        OutputFormat outputFormat, Locale locale, TimeZone timeZone) throws RejectedExecutionException {
    Objects.requireNonNull(templateExecutor, "templateExecutor was null - was postConstruct ever called?");

    final CalculateTemplateOutput task = new CalculateTemplateOutput(templateSourceCode, dataModel,
            outputFormat, locale, timeZone);
    Future<FreeMarkerServiceResponse> future = templateExecutor.submit(task);

    synchronized (task) {
        while (!task.isTemplateExecutionStarted() && !task.isTaskEnded() && !future.isDone()) {
            try {
                task.wait(50); // Timeout is needed to periodically check future.isDone()
            } catch (InterruptedException e) {
                throw new FreeMarkerServiceException("Template execution task was interrupted.", e);
            }
        }
    }

    try {
        return future.get(maxTemplateExecutionTime, TimeUnit.MILLISECONDS);
    } catch (ExecutionException e) {
        throw new FreeMarkerServiceException("Template execution task unexpectedly failed", e.getCause());
    } catch (InterruptedException e) {
        throw new FreeMarkerServiceException("Template execution task was interrupted.", e);
    } catch (TimeoutException e) {
        // Exactly one interruption should be enough, and it should abort template processing pretty much
        // immediately. But to be on the safe side we will interrupt in a loop, with a timeout.
        final long abortionLoopStartTime = System.currentTimeMillis();
        long timeLeft = ABORTION_LOOP_TIME_LIMIT;
        boolean templateExecutionEnded = false;
        do {
            synchronized (task) {
                Thread templateExecutorThread = task.getTemplateExecutorThread();
                if (templateExecutorThread == null) {
                    templateExecutionEnded = true;
                } else {
                    FreeMarkerInternalsAccessor.interruptTemplateProcessing(templateExecutorThread);
                    logger.debug(
                            "Trying to interrupt overly long template processing (" + timeLeft + " ms left).");
                }
            }
            if (!templateExecutionEnded) {
                try {
                    timeLeft = ABORTION_LOOP_TIME_LIMIT - (System.currentTimeMillis() - abortionLoopStartTime);
                    if (timeLeft > 0) {
                        Thread.sleep(ABORTION_LOOP_INTERRUPTION_DISTANCE);
                    }
                } catch (InterruptedException eInt) {
                    logger.error("Template execution abortion loop was interrupted", eInt);
                    timeLeft = 0;
                }
            }
        } while (!templateExecutionEnded && timeLeft > 0);

        if (templateExecutionEnded) {
            logger.debug("Long template processing has ended.");
            try {
                return future.get();
            } catch (InterruptedException | ExecutionException e1) {
                throw new FreeMarkerServiceException("Failed to get result from template executor task", e);
            }
        } else {
            throw new FreeMarkerServiceException(
                    "Couldn't stop long running template processing within " + ABORTION_LOOP_TIME_LIMIT
                            + " ms. It's possibly stuck forever. Such problems can exhaust the executor pool. "
                            + "Template (quoted): " + StringEscapeUtils.escapeJava(templateSourceCode));
        }
    }
}

From source file:com.thinkbiganalytics.spark.service.TransformService.java

/**
 * Converts the specified transformation request to a Scala script that can be executed by the script engine.
 *
 * @param request the transformation request
 * @return the Scala script// w w w  .  j  a v a  2  s .co m
 */
@Nonnull
String toScript(@Nonnull final TransformRequest request) {
    final StringBuilder script = new StringBuilder();
    script.append(
            "class Transform (destination: String, profiler: com.thinkbiganalytics.spark.dataprofiler.Profiler, sqlContext: org.apache.spark.sql.SQLContext, sparkContextService: com.thinkbiganalytics.spark.SparkContextService) extends ");
    script.append(transformScriptClass.getName());
    script.append("(destination, profiler, sqlContext, sparkContextService) {\n");

    script.append("override def dataFrame: org.apache.spark.sql.DataFrame = {");
    script.append(request.getScript());
    script.append("}\n");

    if (request.getParent() != null) {
        script.append("override def parentDataFrame: org.apache.spark.sql.DataFrame = {");
        script.append(request.getParent().getScript());
        script.append("}\n");
        script.append("override def parentTable: String = {\"");
        script.append(StringEscapeUtils.escapeJava(request.getParent().getTable()));
        script.append("\"}\n");
    }

    script.append("}\n");
    script.append("new Transform(tableName, profiler, sqlContext, sparkContextService).run()\n");

    return script.toString();
}

From source file:com.icegreen.greenmail.store.SimpleMessageAttributes.java

/**
 * Builds IMAP envelope String from pre-parsed data.
 *//* w  ww  .  j ava  2  s.c  o  m*/
String parseEnvelope() {
    List<String> response = new ArrayList<String>();
    //1. Date ---------------
    response.add(LB + Q + sentDateEnvelopeString + Q + SP);
    //2. Subject ---------------
    if (subject != null && (subject.length() != 0)) {
        response.add(Q + StringEscapeUtils.escapeJava(subject) + Q + SP);
    } else {
        response.add(NIL + SP);
    }
    //3. From ---------------
    if (from != null && from.length > 0) {
        response.add(LB);
        for (String aFrom : from) {
            response.add(parseAddress(aFrom));
        }
        response.add(RB);
    } else {
        response.add(NIL);
    }
    response.add(SP);
    //4. Sender ---------------
    if (sender != null && sender.length > 0) {
        //            if (DEBUG) getLogger().debug("parsingEnvelope - sender[0] is: " + sender[0]);
        //Check for Netscape feature - sender is local part only
        if (sender[0].indexOf('@') == -1) {
            response.add(LB + response.get(3) + RB); //first From address
        } else {
            response.add(LB);
            for (String aSender : sender) {
                response.add(parseAddress(aSender));
            }
            response.add(RB);
        }
    } else {
        if (from != null && from.length > 0) {
            response.add(LB + response.get(3) + RB); //first From address
        } else {
            response.add(NIL);
        }
    }
    response.add(SP);
    if (replyTo != null && replyTo.length > 0) {
        if (replyTo[0].indexOf('@') == -1) {
            response.add(LB + response.get(3) + RB); //first From address
        } else {
            response.add(LB);
            for (String aReplyTo : replyTo) {
                response.add(parseAddress(aReplyTo));
            }
            response.add(RB);
        }
    } else {
        if (from != null && from.length > 0) {
            response.add(LB + response.get(3) + RB); //first From address
        } else {
            response.add(NIL);
        }
    }
    response.add(SP);
    if (to != null && to.length > 0) {
        response.add(LB);
        for (String aTo : to) {
            response.add(parseAddress(aTo));
        }
        response.add(RB);
    } else {
        response.add(NIL);
    }
    response.add(SP);
    if (cc != null && cc.length > 0) {
        response.add(LB);
        for (String aCc : cc) {
            response.add(parseAddress(aCc));
        }
        response.add(RB);
    } else {
        response.add(NIL);
    }
    response.add(SP);
    if (bcc != null && bcc.length > 0) {
        response.add(LB);
        for (String aBcc : bcc) {
            response.add(parseAddress(aBcc));
        }
        response.add(RB);
    } else {
        response.add(NIL);
    }
    response.add(SP);
    if (inReplyTo != null && inReplyTo.length > 0) {
        response.add(inReplyTo[0]);
    } else {
        response.add(NIL);
    }
    response.add(SP);
    if (messageID != null && messageID.length > 0) {
        messageID[0] = StringEscapeUtils.escapeJava(messageID[0]);
        response.add(Q + messageID[0] + Q);
    } else {
        response.add(NIL);
    }
    response.add(RB);

    StringBuilder buf = new StringBuilder(16 * response.size());
    for (String aResponse : response) {
        buf.append(aResponse);
    }

    return buf.toString();
}

From source file:de.grobmeier.jjson.convert.JSONAnnotationEncoder.java

private void encodeString(String string, StringBuilder result, JSON annotation) {
    if (string == null) {
        result.append(NULL);/*from   w w  w  .ja va  2  s .  c  o m*/
    } else {
        result.append(QUOTE);

        result.append(StringEscapeUtils.escapeJava(string));

        result.append(QUOTE);
    }
}