package za.co.taulite.tools.smppclient;
|
|
import com.google.gson.*;
|
|
import java.lang.reflect.Type;
|
import java.text.ParseException;
|
import java.text.SimpleDateFormat;
|
import java.util.Base64;
|
import java.util.Date;
|
|
|
public class MshellUtils {
|
public static String base64EnFromBytes(byte[] data) {
|
if (data == null) {
|
return null;
|
}
|
try {
|
Base64.Encoder encoder = Base64.getEncoder();
|
String encryptedString = encoder.encodeToString(data);
|
return encryptedString;
|
} catch (Exception ex) {
|
throw new RuntimeException("Base64 encoding failed", ex);
|
}
|
}
|
|
public static String base64Dec(String text) {
|
try {
|
Base64.Decoder decoder = Base64.getDecoder();
|
String decrypted = new String(decoder.decode(text));
|
return decrypted;
|
} catch (Exception ex) {
|
throw new RuntimeException("Base64 decoding failed", ex);
|
}
|
}
|
|
public static byte[] base64DecToBytes(String text) {
|
if (text == null) {
|
return null;
|
}
|
|
try {
|
Base64.Decoder decoder = Base64.getDecoder();
|
return decoder.decode(text);
|
} catch (Exception ex) {
|
throw new RuntimeException("Base64 decoding failed", ex);
|
}
|
}
|
|
public static Date parseDate(Object value) {
|
if (value == null) {
|
return null;
|
}
|
|
if (value instanceof Date) {
|
return (Date)value;
|
}
|
|
if (value instanceof Long) {
|
return new Date((Long)value);
|
}
|
|
if (value instanceof String) {
|
var str = (String) value;
|
if (str.matches("yyyy-MM-dd'T'HH:mm:ss.SSSZ")) {
|
try {
|
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse(str);
|
} catch (ParseException ex) {
|
throw new RuntimeException("Failed to parse date " + value);
|
}
|
}
|
}
|
|
return null; // TODO: implement ultimate date parser
|
}
|
|
public static final Gson GSON_EXCLUDE_NULLS = new GsonBuilder()
|
.registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> {
|
if (json.getAsJsonPrimitive().isNumber()) {
|
return new Date(json.getAsJsonPrimitive().getAsLong());
|
} else {
|
return parseDate(json.getAsJsonPrimitive().getAsString());
|
}
|
})
|
.registerTypeAdapter(Date.class, (JsonSerializer<Date>) (date, type, jsonSerializationContext) -> new JsonPrimitive(date.getTime()))
|
.registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64TypeAdapter())
|
.setPrettyPrinting()
|
.create();
|
|
private static class ByteArrayToBase64TypeAdapter implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> {
|
public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
|
return base64DecToBytes(json.getAsString());
|
}
|
|
public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
|
return new JsonPrimitive(base64EnFromBytes(src));
|
}
|
}
|
|
public static <T> T parseJson(String json, Class<T> clazz) {
|
return GSON_EXCLUDE_NULLS.fromJson(json, clazz);
|
}
|
}
|