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.apache.streams.neo4j.CypherQueryGraphHelper.java

private String getActorTargetEdgePropertyCreater(Map<String, Object> map) {
    StringBuilder builder = new StringBuilder();
    builder.append("{ ");
    List<String> parts = new ArrayList<>();
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        if (entry.getValue() instanceof String) {
            String propVal = (String) (entry.getValue());
            if (!entry.getKey().contains(".")) {
                parts.add("`" + entry.getKey() + "`: '" + StringEscapeUtils.escapeJava(propVal) + "'");
            } else if (entry.getKey().startsWith("object.") && !entry.getKey().contains(".id")) {
                parts.add("`" + entry.getKey().substring("object.".length()) + "`: '"
                        + StringEscapeUtils.escapeJava(propVal) + "'");
            }//from   w w  w  .  j av  a  2 s . c  o m
        }
    }
    builder.append(String.join(", ", parts));
    builder.append(" }");
    return builder.toString();
}

From source file:org.ballerinalang.composer.service.ballerina.parser.service.BallerinaParserService.java

public static JsonElement generateJSON(Node node, Map<String, Node> anonStructs)
        throws InvocationTargetException, IllegalAccessException {
    if (node == null) {
        return JsonNull.INSTANCE;
    }//w ww .j  a v a  2  s.  co m
    Set<Method> methods = ClassUtils.getAllInterfaces(node.getClass()).stream()
            .flatMap(aClass -> Arrays.stream(aClass.getMethods())).collect(Collectors.toSet());
    JsonObject nodeJson = new JsonObject();

    JsonArray wsJsonArray = new JsonArray();
    Set<Whitespace> ws = node.getWS();
    if (ws != null && !ws.isEmpty()) {
        for (Whitespace whitespace : ws) {
            JsonObject wsJson = new JsonObject();
            wsJson.addProperty("ws", whitespace.getWs());
            wsJson.addProperty("i", whitespace.getIndex());
            wsJson.addProperty("text", whitespace.getPrevious());
            wsJson.addProperty("static", whitespace.isStatic());
            wsJsonArray.add(wsJson);
        }
        nodeJson.add("ws", wsJsonArray);
    }
    Diagnostic.DiagnosticPosition position = node.getPosition();
    if (position != null) {
        JsonObject positionJson = new JsonObject();
        positionJson.addProperty("startColumn", position.getStartColumn());
        positionJson.addProperty("startLine", position.getStartLine());
        positionJson.addProperty("endColumn", position.getEndColumn());
        positionJson.addProperty("endLine", position.getEndLine());
        nodeJson.add("position", positionJson);
    }

    /* Virtual props */

    JsonArray type = getType(node);
    if (type != null) {
        nodeJson.add(SYMBOL_TYPE, type);
    }
    if (node.getKind() == NodeKind.INVOCATION) {
        assert node instanceof BLangInvocation : node.getClass();
        BLangInvocation invocation = (BLangInvocation) node;
        if (invocation.symbol != null && invocation.symbol.kind != null) {
            nodeJson.addProperty(INVOCATION_TYPE, invocation.symbol.kind.toString());
        }
    }

    for (Method m : methods) {
        String name = m.getName();

        if (name.equals("getWS") || name.equals("getPosition")) {
            continue;
        }

        String jsonName;
        if (name.startsWith("get")) {
            jsonName = toJsonName(name, 3);
        } else if (name.startsWith("is")) {
            jsonName = toJsonName(name, 2);
        } else {
            continue;
        }

        Object prop = m.invoke(node);

        /* Literal class - This class is escaped in backend to address cases like "ss\"" and 8.0 and null */
        if (node.getKind() == NodeKind.LITERAL && "value".equals(jsonName)) {
            if (prop instanceof String) {
                nodeJson.addProperty(jsonName, '"' + StringEscapeUtils.escapeJava((String) prop) + '"');
                nodeJson.addProperty(UNESCAPED_VALUE, String.valueOf(prop));
            } else {
                nodeJson.addProperty(jsonName, String.valueOf(prop));
            }
            continue;
        }

        if (node.getKind() == NodeKind.ANNOTATION && node instanceof BLangAnnotation) {
            JsonArray attachmentPoints = new JsonArray();
            ((BLangAnnotation) node).getAttachPoints().stream().map(AttachPoint::getValue)
                    .map(JsonPrimitive::new).forEach(attachmentPoints::add);
            nodeJson.add("attachmentPoints", attachmentPoints);
        }
        // TODO: revisit logic for user defined types
        //            if (node.getKind() == NodeKind.USER_DEFINED_TYPE && jsonName.equals("typeName")) {
        //                IdentifierNode typeNode = (IdentifierNode) prop;
        //                Node structNode;
        //                if (typeNode.getValue().startsWith("$anonStruct$") &&
        //                        (structNode = anonStructs.remove(typeNode.getValue())) != null) {
        //                    JsonObject anonStruct = generateJSON(structNode, anonStructs).getAsJsonObject();
        //                    anonStruct.addProperty("anonStruct", true);
        //                    nodeJson.add("anonStruct", anonStruct);
        //                    continue;
        //                }
        //            }

        if (prop instanceof List && jsonName.equals("types")) {
            // Currently we don't need any Symbols for the UI. So skipping for now.
            continue;
        }

        /* Node classes */
        if (prop instanceof Node) {
            nodeJson.add(jsonName, generateJSON((Node) prop, anonStructs));
        } else if (prop instanceof List) {
            List listProp = (List) prop;
            JsonArray listPropJson = new JsonArray();
            nodeJson.add(jsonName, listPropJson);
            for (Object listPropItem : listProp) {
                if (listPropItem instanceof Node) {
                    /* Remove top level anon func and struct */
                    if (node.getKind() == NodeKind.COMPILATION_UNIT) {
                        if (listPropItem instanceof BLangFunction
                                && (((BLangFunction) listPropItem)).name.value.startsWith("$lambda$")) {
                            continue;
                        }
                    }
                    listPropJson.add(generateJSON((Node) listPropItem, anonStructs));
                } else {
                    logger.debug("Can't serialize " + jsonName + ", has a an array of " + listPropItem);
                }
            }

            /* Runtime model classes */
        } else if (prop instanceof Set && jsonName.equals("flags")) {
            Set flags = (Set) prop;
            for (Flag flag : Flag.values()) {
                nodeJson.addProperty(StringUtils.lowerCase(flag.toString()), flags.contains(flag));
            }
        } else if (prop instanceof Set) {
            // TODO : limit this else if to getInputs getOutputs of transform.
            Set vars = (Set) prop;
            JsonArray listVarJson = new JsonArray();
            nodeJson.add(jsonName, listVarJson);
            for (Object obj : vars) {
                listVarJson.add(obj.toString());
            }
        } else if (prop instanceof NodeKind) {
            String kindName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, prop.toString());
            nodeJson.addProperty(jsonName, kindName);
        } else if (prop instanceof OperatorKind) {
            nodeJson.addProperty(jsonName, prop.toString());

            /* Generic classes */
        } else if (prop instanceof String) {
            nodeJson.addProperty(jsonName, (String) prop);
        } else if (prop instanceof Number) {
            nodeJson.addProperty(jsonName, (Number) prop);
        } else if (prop instanceof Boolean) {
            nodeJson.addProperty(jsonName, (Boolean) prop);
        } else if (prop instanceof Enum) {
            nodeJson.addProperty(jsonName, StringUtils.lowerCase(((Enum) prop).name()));
        } else if (prop instanceof int[]) {
            int[] intArray = ((int[]) prop);
            JsonArray intArrayPropJson = new JsonArray();
            nodeJson.add(jsonName, intArrayPropJson);
            for (int intProp : intArray) {
                intArrayPropJson.add(intProp);
            }
        } else if (prop != null) {
            nodeJson.addProperty(jsonName, prop.toString());
            String message = "Node " + node.getClass().getSimpleName() + " contains unknown type prop: "
                    + jsonName + " of type " + prop.getClass();
            logger.error(message);
        }
    }
    return nodeJson;
}

From source file:org.ballerinalang.config.ConfigProcessor.java

private static BConfig parseRuntimeParams(Map<String, String> runtimeParams) {
    StringBuilder stringBuilder = new StringBuilder();
    runtimeParams.forEach((key, val) -> stringBuilder.append(key).append('=')
            // TODO: need to handle this in a better way
            .append('\"').append(StringEscapeUtils.escapeJava(val)).append('\"').append('\n'));
    ANTLRInputStream runtimeConfigsStream = new ANTLRInputStream(stringBuilder.toString());
    BConfig runtimeConfigEntries = new BConfig();
    ParseTreeWalker treeWalker = new ParseTreeWalker();
    treeWalker.walk(new BConfigLangListener(runtimeConfigEntries),
            TomlProcessor.parseTomlContent(runtimeConfigsStream, null));
    return runtimeConfigEntries;
}

From source file:org.ballerinalang.langserver.compiler.format.TextDocumentFormatUtil.java

/**
 * Generate json representation for the given node.
 *
 * @param node              Node to get the json representation
 * @param anonStructs       Map of anonymous structs
 * @param symbolMetaInfoMap symbol meta information map
 * @return {@link JsonElement}          Json Representation of the node
 * @throws JSONGenerationException when Json error occurs
 *///from   w  w  w  . j a  v a2  s .c  o m
public static JsonElement generateJSON(Node node, Map<String, Node> anonStructs,
        Map<BLangNode, List<SymbolMetaInfo>> symbolMetaInfoMap) throws JSONGenerationException {
    if (node == null) {
        return JsonNull.INSTANCE;
    }
    Set<Method> methods = ClassUtils.getAllInterfaces(node.getClass()).stream()
            .flatMap(aClass -> Arrays.stream(aClass.getMethods())).collect(Collectors.toSet());
    JsonObject nodeJson = new JsonObject();

    JsonArray wsJsonArray = new JsonArray();
    Set<Whitespace> ws = node.getWS();
    if (ws != null && !ws.isEmpty()) {
        for (Whitespace whitespace : ws) {
            JsonObject wsJson = new JsonObject();
            wsJson.addProperty("ws", whitespace.getWs());
            wsJson.addProperty("i", whitespace.getIndex());
            wsJson.addProperty("text", whitespace.getPrevious());
            wsJson.addProperty("static", whitespace.isStatic());
            wsJsonArray.add(wsJson);
        }
        nodeJson.add("ws", wsJsonArray);
    }
    Diagnostic.DiagnosticPosition position = node.getPosition();
    if (position != null) {
        JsonObject positionJson = new JsonObject();
        positionJson.addProperty("startColumn", position.getStartColumn());
        positionJson.addProperty("startLine", position.getStartLine());
        positionJson.addProperty("endColumn", position.getEndColumn());
        positionJson.addProperty("endLine", position.getEndLine());
        nodeJson.add("position", positionJson);
    }

    /* Virtual props */

    // Add UUID for each node.
    nodeJson.addProperty("id", UUID.randomUUID().toString());

    // Add the visible endpoints for a given node
    if (symbolMetaInfoMap.containsKey(node)) {
        List<SymbolMetaInfo> endpointMetaList = symbolMetaInfoMap.get(node);
        JsonArray endpoints = new JsonArray();
        endpointMetaList.forEach(symbolMetaInfo -> endpoints.add(symbolMetaInfo.getJson()));
        nodeJson.add("VisibleEndpoints", endpoints);
    }

    JsonArray type = getType(node);
    if (type != null) {
        nodeJson.add(SYMBOL_TYPE, type);
    }
    if (node.getKind() == NodeKind.INVOCATION) {
        assert node instanceof BLangInvocation : node.getClass();
        BLangInvocation invocation = (BLangInvocation) node;
        if (invocation.symbol != null && invocation.symbol.kind != null) {
            nodeJson.addProperty(INVOCATION_TYPE, invocation.symbol.kind.toString());
        }
    }

    for (Method m : methods) {
        String name = m.getName();

        if (name.equals("getWS") || name.equals("getPosition")) {
            continue;
        }

        String jsonName;
        if (name.startsWith("get")) {
            jsonName = toJsonName(name, 3);
        } else if (name.startsWith("is")) {
            jsonName = toJsonName(name, 2);
        } else {
            continue;
        }

        Object prop = null;
        try {
            prop = m.invoke(node);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new JSONGenerationException("Error occurred while generating JSON", e);
        }

        /* Literal class - This class is escaped in backend to address cases like "ss\"" and 8.0 and null */
        if ((node.getKind() == NodeKind.LITERAL || node.getKind() == NodeKind.NUMERIC_LITERAL)
                && "value".equals(jsonName)) {
            if (prop instanceof String) {
                nodeJson.addProperty(jsonName, '"' + StringEscapeUtils.escapeJava((String) prop) + '"');
                nodeJson.addProperty(UNESCAPED_VALUE, String.valueOf(prop));
            } else {
                nodeJson.addProperty(jsonName, String.valueOf(prop));
            }
            continue;
        }

        if (node.getKind() == NodeKind.ANNOTATION && node instanceof BLangAnnotation) {
            JsonArray attachmentPoints = new JsonArray();
            ((BLangAnnotation) node).getAttachPoints().stream().map(AttachPoint::getValue)
                    .map(JsonPrimitive::new).forEach(attachmentPoints::add);
            nodeJson.add("attachmentPoints", attachmentPoints);
        }

        if (prop instanceof List && jsonName.equals("types")) {
            // Currently we don't need any Symbols for the UI. So skipping for now.
            continue;
        }

        /* Node classes */
        if (prop instanceof Node) {
            nodeJson.add(jsonName, generateJSON((Node) prop, anonStructs, symbolMetaInfoMap));
        } else if (prop instanceof List) {
            List listProp = (List) prop;
            JsonArray listPropJson = new JsonArray();
            nodeJson.add(jsonName, listPropJson);
            for (Object listPropItem : listProp) {
                if (listPropItem instanceof Node) {
                    /* Remove top level anon func and struct */
                    if (node.getKind() == NodeKind.COMPILATION_UNIT) {
                        if (listPropItem instanceof BLangFunction
                                && (((BLangFunction) listPropItem)).name.value.startsWith("$lambda$")) {
                            continue;
                        }
                    }
                    listPropJson.add(generateJSON((Node) listPropItem, anonStructs, symbolMetaInfoMap));
                } else if (listPropItem instanceof BLangRecordVarRef.BLangRecordVarRefKeyValue) {
                    listPropJson.add(generateJSON(
                            ((BLangRecordVarRef.BLangRecordVarRefKeyValue) listPropItem).getVariableName(),
                            anonStructs, symbolMetaInfoMap));
                    listPropJson.add(generateJSON(
                            ((BLangRecordVarRef.BLangRecordVarRefKeyValue) listPropItem).getBindingPattern(),
                            anonStructs, symbolMetaInfoMap));
                } else if (listPropItem instanceof BLangRecordVariable.BLangRecordVariableKeyValue) {
                    listPropJson.add(generateJSON(
                            ((BLangRecordVariable.BLangRecordVariableKeyValue) listPropItem).getKey(),
                            anonStructs, symbolMetaInfoMap));
                    listPropJson.add(generateJSON(
                            ((BLangRecordVariable.BLangRecordVariableKeyValue) listPropItem).getValue(),
                            anonStructs, symbolMetaInfoMap));
                } else if (listPropItem instanceof String) {
                    listPropJson.add((String) listPropItem);
                } else {
                    logger.debug("Can't serialize " + jsonName + ", has a an array of " + listPropItem);
                }
            }
            /* Runtime model classes */
        } else if (prop instanceof Set && jsonName.equals("flags")) {
            Set flags = (Set) prop;
            for (Flag flag : Flag.values()) {
                nodeJson.addProperty(StringUtils.lowerCase(flag.toString()), flags.contains(flag));
            }
        } else if (prop instanceof Set) {
            // TODO : limit this else if to getInputs getOutputs of transform.
            Set vars = (Set) prop;
            JsonArray listVarJson = new JsonArray();
            nodeJson.add(jsonName, listVarJson);
            for (Object obj : vars) {
                listVarJson.add(obj.toString());
            }
        } else if (prop instanceof NodeKind) {
            String kindName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, prop.toString());
            nodeJson.addProperty(jsonName, kindName);
        } else if (prop instanceof OperatorKind) {
            nodeJson.addProperty(jsonName, prop.toString());
            /* Generic classes */
        } else if (prop instanceof String) {
            nodeJson.addProperty(jsonName, (String) prop);
        } else if (prop instanceof Number) {
            nodeJson.addProperty(jsonName, (Number) prop);
        } else if (prop instanceof Boolean) {
            nodeJson.addProperty(jsonName, (Boolean) prop);
        } else if (prop instanceof Enum) {
            nodeJson.addProperty(jsonName, StringUtils.lowerCase(((Enum) prop).name()));
        } else if (prop instanceof int[]) {
            int[] intArray = ((int[]) prop);
            JsonArray intArrayPropJson = new JsonArray();
            nodeJson.add(jsonName, intArrayPropJson);
            for (int intProp : intArray) {
                intArrayPropJson.add(intProp);
            }
        } else if (prop != null) {
            nodeJson.addProperty(jsonName, prop.toString());
        }
    }
    return nodeJson;
}

From source file:org.ballerinalang.test.service.grpc.sample.GrpcBaseTest.java

@BeforeGroups(value = "grpc-test", alwaysRun = true)
public void start() throws BallerinaTestException {
    String privateKey = StringEscapeUtils.escapeJava(
            Paths.get("src", "test", "resources", "certsAndKeys", "private.key").toAbsolutePath().toString());
    String publicCert = StringEscapeUtils.escapeJava(
            Paths.get("src", "test", "resources", "certsAndKeys", "public.crt").toAbsolutePath().toString());
    int[] requiredPorts = new int[] { 9090, 9092, 9095, 9096, 9098, 9099, 9100, 9101, 8085, 9317, 9102, 9103,
            9104, 9105 };/*from  w w  w .j  av a2s .  c om*/

    String balFile = new File(
            "src" + File.separator + "test" + File.separator + "resources" + File.separator + "grpc")
                    .getAbsolutePath();
    String[] args = new String[] { "-e", "certificate.key=" + privateKey, "-e", "public.cert=" + publicCert };
    serverInstance = new BServerInstance(balServer);
    serverInstance.startServer(balFile, "grpcservices", args, requiredPorts);
}

From source file:org.ballerinalang.test.service.grpc.sample.GrpcMutualSslWithCertsTest.java

@Test
public void testMutualSSLWithcerts() throws IOException {
    Path balFilePath = Paths.get("src", "test", "resources", "grpc", "clients", "grpc_ssl_client.bal");
    String privateKey = StringEscapeUtils.escapeJava(
            Paths.get("src", "test", "resources", "certsAndKeys", "private.key").toAbsolutePath().toString());
    String publicCert = StringEscapeUtils.escapeJava(
            Paths.get("src", "test", "resources", "certsAndKeys", "public.crt").toAbsolutePath().toString());
    Map<String, String> runtimeParams = new HashMap<>();
    runtimeParams.put("client.certificate.key", privateKey);
    runtimeParams.put("client.public.cert", publicCert);
    registry.initRegistry(runtimeParams, null, null);
    result = BCompileUtil.compile(balFilePath.toAbsolutePath().toString());
    final String serverMsg = "Hello WSO2";
    BValue[] responses = BRunUtil.invoke(result, "testUnarySecuredBlockingWithCerts", new BValue[] {});
    Assert.assertEquals(responses.length, 1);
    Assert.assertTrue(responses[0] instanceof BString);
    BString responseValues = (BString) responses[0];
    Assert.assertEquals(responseValues.stringValue(), serverMsg);
}

From source file:org.ballerinalang.test.service.http.HttpBaseTest.java

@BeforeGroups(value = "http-test", alwaysRun = true)
public void start() throws BallerinaTestException {
    int[] requiredPorts = new int[] { 9090, 9224, 9091, 9092, 9093, 9094, 9095, 9096, 9097, 9098, 9099, 9100,
            9101, 9102, 9103, 9104, 9105, 9106, 9107, 9108, 9109, 9110, 9111, 9112, 9113, 9114, 9115, 9116,
            9117, 9118, 9119, 9217, 9218, 9219, 9220, 9221, 9222, 9223, 9225, 9226, 9227, 9228, 9229 };
    String balFile = Paths.get("src", "test", "resources", "http").toAbsolutePath().toString();
    String privateKey = StringEscapeUtils.escapeJava(
            Paths.get("src", "test", "resources", "certsAndKeys", "private.key").toAbsolutePath().toString());
    String publicCert = StringEscapeUtils.escapeJava(
            Paths.get("src", "test", "resources", "certsAndKeys", "public.crt").toAbsolutePath().toString());
    String[] args = new String[] { "-e", "certificate.key=" + privateKey, "-e", "public.cert=" + publicCert };
    serverInstance = new BServerInstance(balServer);
    serverInstance.startServer(balFile, "httpservices", args, requiredPorts);
}

From source file:org.ballerinalang.test.service.http.sample.MutualSSLWithCerts.java

@Test(description = "Test mutual ssl")
public void testMutualSSLWithCerts() throws Exception {
    String serverResponse = "Response received";
    String privateKey = StringEscapeUtils.escapeJava(
            Paths.get("src", "test", "resources", "certsAndKeys", "private.key").toAbsolutePath().toString());
    String publicCert = StringEscapeUtils.escapeJava(
            Paths.get("src", "test", "resources", "certsAndKeys", "public.crt").toAbsolutePath().toString());

    String balFile = Paths.get("src", "test", "resources", "mutualSSL", "ssl_client.bal").toAbsolutePath()
            .toString();/*from www  .j  av a2  s  .  c  om*/

    String[] flags = { "-e", "certificate.key=" + privateKey, "-e", "public.cert=" + publicCert };

    BMainInstance ballerinaClient = new BMainInstance(balServer);
    LogLeecher clientLeecher = new LogLeecher(serverResponse);
    ballerinaClient.runMain(balFile, flags, null, new LogLeecher[] { clientLeecher });
    clientLeecher.waitForText(20000);
}

From source file:org.ballerinalang.test.socket.SocketBaseTest.java

@BeforeGroups(value = "socket-test", alwaysRun = true)
public void start() throws BallerinaTestException {
    executor = Executors.newSingleThreadExecutor();
    MockSocketServer mockSocketServer = new MockSocketServer();
    executor.execute(mockSocketServer);/*from   w w  w .  j a v  a 2 s.  c  om*/
    String privateKey = StringEscapeUtils.escapeJava(
            Paths.get("src", "test", "resources", "certsAndKeys", "private.key").toAbsolutePath().toString());
    String publicCert = StringEscapeUtils.escapeJava(
            Paths.get("src", "test", "resources", "certsAndKeys", "public.crt").toAbsolutePath().toString());
    int[] requiredPorts = new int[] { 58291, MockSocketServer.SERVER_PORT, 61598 };

    String balFile = new File(
            "src" + File.separator + "test" + File.separator + "resources" + File.separator + "socket")
                    .getAbsolutePath();
    String[] args = new String[] { "-e", "certificate.key=" + privateKey, "-e", "public.cert=" + publicCert };
    serverInstance = new BServerInstance(balServer);
    serverInstance.startServer(balFile, "services", args, requiredPorts);
}

From source file:org.beryx.vbundle.chart.html.HtmlChartContentPane.java

public String getContent() {
    if (optFile.isSelected()) {
        String filePath = txtFile.getText().replace('\\', '/');
        Path path = Paths.get(filePath);
        Path pathUserDir = Paths.get(System.getProperty("user.dir").replace('\\', '/'));
        if (path.startsWith(pathUserDir)) {
            path = pathUserDir.relativize(path);
        }/*from w w  w.ja v a  2 s. c  o m*/
        return "file('" + path.toString().replace('\\', '/') + "')";
    } else if (optUrl.isSelected()) {
        return "url('" + txtUrl.getText() + "')";
    } else {
        return "\"" + StringEscapeUtils.escapeJava(txtInline.getText()) + "\"";
    }
}