org.opensearch.ml.common.utils.StringUtils Maven / Gradle / Ivy
The newest version!
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.opensearch.ml.common.utils;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.BooleanUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import lombok.extern.log4j.Log4j2;
@Log4j2
public class StringUtils {
public static final String DEFAULT_ESCAPE_FUNCTION = "\n String escape(def input) { \n"
+ " if (input.contains(\"\\\\\")) {\n input = input.replace(\"\\\\\", \"\\\\\\\\\");\n }\n"
+ " if (input.contains(\"\\\"\")) {\n input = input.replace(\"\\\"\", \"\\\\\\\"\");\n }\n"
+ " if (input.contains('\r')) {\n input = input = input.replace('\r', '\\\\r');\n }\n"
+ " if (input.contains(\"\\\\t\")) {\n input = input.replace(\"\\\\t\", \"\\\\\\\\\\\\t\");\n }\n"
+ " if (input.contains('\n')) {\n input = input.replace('\n', '\\\\n');\n }\n"
+ " if (input.contains('\b')) {\n input = input.replace('\b', '\\\\b');\n }\n"
+ " if (input.contains('\f')) {\n input = input.replace('\f', '\\\\f');\n }\n"
+ " return input;"
+ "\n }\n";
public static final Gson gson;
static {
gson = new Gson();
}
public static final String TO_STRING_FUNCTION_NAME = ".toString()";
public static boolean isValidJsonString(String Json) {
try {
new JSONObject(Json);
} catch (JSONException ex) {
try {
new JSONArray(Json);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
public static boolean isJson(String json) {
try {
if (!isValidJsonString(json)) {
return false;
}
// This is to cover such edge case "[]\""
gson.fromJson(json, Object.class);
return true;
} catch (JsonSyntaxException ex) {
return false;
}
}
public static String toUTF8(String rawString) {
ByteBuffer buffer = StandardCharsets.UTF_8.encode(rawString);
String utf8EncodedString = StandardCharsets.UTF_8.decode(buffer).toString();
return utf8EncodedString;
}
public static Map fromJson(String jsonStr, String defaultKey) {
Map result;
JsonElement jsonElement = JsonParser.parseString(jsonStr);
if (jsonElement.isJsonObject()) {
result = gson.fromJson(jsonElement, Map.class);
} else if (jsonElement.isJsonArray()) {
List