index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/adapters
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/adapters/tapestry/TapestryArrayAdapter.java
|
package ai.bizone.jsontransform.adapters.tapestry;
import ai.bizone.jsontransform.adapters.JsonAdapterHelpers;
import ai.bizone.jsontransform.adapters.JsonArrayAdapter;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.json.JSONObject;
import java.util.stream.Stream;
public class TapestryArrayAdapter extends JsonArrayAdapter<Object, JSONArray, JSONObject> {
@Override
public JSONArray create() {
return new JSONArray();
}
@Override
public JSONArray create(int capacity) {
// no capacity at this version
return new JSONArray();
}
@Override
public void add(JSONArray array, String value) {
array.add(value == null ? JSONObject.NULL : value);
}
@Override
public void add(JSONArray array, Number value) {
array.add(value == null ? JSONObject.NULL : value);
}
@Override
public void add(JSONArray array, Boolean value) {
array.add(value == null ? JSONObject.NULL : value);
}
@Override
public void add(JSONArray array, Character value) {
array.add(value == null ? JSONObject.NULL : value.toString());
}
@Override
public void add(JSONArray array, Object value) {
array.add(value == null ? JSONObject.NULL : value);
}
@Override
public void add(JSONArray array, JSONArray value) {
array.add(value == null ? JSONObject.NULL : value);
}
@Override
public void set(JSONArray array, int index, Object value) {
if (array.size() > index || JsonAdapterHelpers.trySetArrayAtOOB(this, array, index, value == null ? JSONObject.NULL : value, null)) {
array.put(index, value == null ? JSONObject.NULL : value);
}
}
@Override
public Object remove(JSONArray array, int index) {
return array.remove(index);
}
@Override
public Object get(JSONArray array, int index) {
return array.get(index);
}
@Override
public int size(JSONArray array) {
return array.size();
}
@Override
public boolean is(Object value) {
return value instanceof JSONArray;
}
@Override
public Stream<Object> stream(JSONArray array, boolean parallel) {
return array.stream();
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/adapters
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/adapters/tapestry/TapestryHelpers.java
|
package ai.bizone.jsontransform.adapters.tapestry;
import ai.bizone.jsontransform.adapters.JsonAdapterHelpers;
import ai.bizone.jsontransform.adapters.pojo.PojoHelpers;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.spi.json.TapestryJsonProvider;
import com.jayway.jsonpath.spi.mapper.TapestryMappingProvider;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.json.JSONObject;
import org.json.JSONString;
import java.lang.reflect.Array;
import java.util.*;
public class TapestryHelpers {
static Configuration getJsonPathConfig() {
return new Configuration.ConfigurationBuilder()
.jsonProvider(new TapestryJsonProvider())
.mappingProvider(new TapestryMappingProvider())
.options(Set.of(
Option.SUPPRESS_EXCEPTIONS
))
.build();
}
/**
* Wraps and unwraps values for JsonSmartJsonAdapter processing
* @param object object to convert
* @param unwrap if true, will convert JSONObject.NULL to null, otherwise will convert null values to JSONObject.NULL
*/
public static Object convert(Object object, boolean unwrap, boolean reduceBigDecimals) {
if (object == null || JSONObject.NULL.equals(object)) {
return unwrap ? null : JSONObject.NULL;
}
// number
if (object instanceof Number n) {
return JsonAdapterHelpers.unwrapNumber(n, reduceBigDecimals);
}
// boolean | string
if (object instanceof Boolean ||
object instanceof String) {
return object;
}
// special case: char
if (object instanceof Character) {
return object.toString();
}
// array
if (object instanceof Iterable<?> i) {
var result = unwrap ? new ArrayList<>() : new JSONArray();
for (var item : i) {
result.add(convert(item, unwrap, reduceBigDecimals));
}
return result;
} else if (object.getClass().isArray()) {
var result = unwrap ? new ArrayList<>() : new JSONArray();
var length = Array.getLength(object);
for (var i = 0; i < length; i++) {
result.add(convert(Array.get(object, i), unwrap, reduceBigDecimals));
}
return result;
}
// object
var result = unwrap ? new HashMap<String, Object>() : new JSONObject();
if (object instanceof Map<?, ?> m) {
// - map
for (var entry : m.entrySet()) {
result.put(entry.getKey().toString(), convert(entry.getValue(), unwrap, reduceBigDecimals));
}
} else {
// - class type
PojoHelpers.getAllFields(object.getClass()).forEach(field -> {
try {
field.setAccessible(true);
result.put(field.getName(), convert(field.get(object), unwrap, reduceBigDecimals));
} catch (IllegalAccessException e) {
// e.printStackTrace();
}
});
}
return result;
}
public static int getContentsHashCode(Object object) {
if (object == JSONObject.NULL || object == null)
return 0;
if (object instanceof JSONObject jo) {
return jo.toCompactString().hashCode();
}
if (object instanceof JSONArray ja) {
return ja.toCompactString().hashCode();
}
if (object instanceof JSONString js) {
return js.toString().hashCode();
}
return object.hashCode();
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/adapters
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/adapters/tapestry/TapestryJsonAdapter.java
|
package ai.bizone.jsontransform.adapters.tapestry;
import ai.bizone.jsontransform.adapters.JsonAdapter;
import ai.bizone.jsontransform.adapters.jsonorg.JsonOrgHelpers;
import ai.bizone.jsontransform.adapters.pojo.PojoJsonTransformer;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.spi.mapper.MappingException;
import org.apache.tapestry5.json.*;
import java.math.BigDecimal;
import java.util.ArrayList;
public class TapestryJsonAdapter extends JsonAdapter<Object, JSONArray, JSONObject> {
public TapestryJsonAdapter() {
super(
TapestryObjectAdapter::new,
TapestryArrayAdapter::new,
TapestryHelpers.getJsonPathConfig()
);
}
@Override
public boolean is(Object value) {
return value == null || // this should be mitigated on insertion
JSONObject.NULL.equals(value) ||
value instanceof JSONCollection ||
value instanceof JSONString ||
value instanceof String ||
value instanceof Number ||
value instanceof Boolean;
}
@Override
public boolean isJsonString(Object value) {
return value instanceof String || value instanceof JSONString;
}
@Override
public boolean isJsonNumber(Object value) {
return value instanceof Number;
}
@Override
public boolean isJsonBoolean(Object value) {
return value instanceof Boolean;
}
@Override
public boolean isNull(Object value) {
return value == null || JSONObject.NULL.equals(value);
}
@Override
public Object jsonNull() {
return JSONObject.NULL;
}
@Override
public Object wrap(Object value) {
return TapestryHelpers.convert(value, false, false);
}
@Override
public Object unwrap(Object value, boolean reduceBigDecimals) {
return TapestryHelpers.convert(value, true, reduceBigDecimals);
}
@Override
@SuppressWarnings("unchecked")
public <T> T deserialize(Object value, Class<T> targetType) {
if(value == null){
return null;
}
if (targetType.isAssignableFrom(value.getClass())) {
return (T) value;
}
try {
if (targetType.isAssignableFrom(ArrayList.class) && isJsonArray(value)) {
return jsonPathConfiguration.mappingProvider().map(value, targetType, jsonPathConfiguration);
}
var unwrappedValue = unwrap(value, false);
return PojoJsonTransformer.getAdapter().deserialize(unwrappedValue, targetType);
} catch (Exception e) {
throw new MappingException(e);
}
}
@Override
public Object parse(String value) {
var wrapper = "[" + value + "]";
return new JSONArray(wrapper).get(0);
}
@Override
public Object clone(Object value) {
return wrap(value);
}
@Override
public Number getNumber(Object value) {
if (value instanceof Number n) {
return n;
}
if (value instanceof String s) {
return new BigDecimal(s);
}
if (value instanceof JSONString js) {
return new BigDecimal(js.toString());
}
return null;
}
@Override
public BigDecimal getNumberAsBigDecimal(Object value) {
if (value instanceof BigDecimal b) {
return b;
}
if (value instanceof Number n) {
return new BigDecimal(n.toString());
}
if (value instanceof String s) {
return new BigDecimal(s);
}
if (value instanceof JSONString js) {
return new BigDecimal(js.toString());
}
return null;
}
@Override
public Boolean getBoolean(Object value) {
if (value instanceof Boolean b) {
return b;
}
if (value instanceof String s) {
return Boolean.valueOf(s);
}
if (value instanceof JSONString js) {
return Boolean.valueOf(js.toString());
}
return null;
}
@Override
public DocumentContext getDocumentContext(Object payload, Iterable<String> options) {
if (isNull(payload)) {
return NullDocumentContext.INSTANCE;
}
return super.getDocumentContext(payload, options);
}
@Override
public boolean nodesComparable() {
return false;
}
@Override
public boolean areEqual(Object value, Object other) {
if (value instanceof JSONObject jo) {
return other instanceof JSONObject o && jo.toMap().equals(o.toMap());
}
if (value instanceof JSONArray ja) {
if (!(other instanceof JSONArray o) || o.size() != ja.size()) {
return false;
}
for (var i = 0 ; i < ja.size() ; i++) {
if (!areEqual(ja.get(i), o.get(i))) {
return false;
}
}
return true;
}
if (value instanceof JSONString vjs) {
return other instanceof JSONString ojs && vjs.toString().equals(ojs.toString());
}
return super.areEqual(value, other);
}
@Override
public int hashCode(Object value) {
return TapestryHelpers.getContentsHashCode(value);
}
@Override
public String toString(Object value) {
if (value == null || JSONObject.NULL.equals(value)) {
return JSONObject.NULL.toString();
}
if (value instanceof JSONCollection c) {
return c.toCompactString();
}
if (value instanceof JSONString js) {
return js.toJSONString();
}
if (value instanceof String s) {
var container = new JSONArray();
container.add(s);
var arrJson = container.toCompactString();
return arrJson.substring(1, arrJson.length() - 1); // remove starting and ending [, ]
}
if (value instanceof Boolean || value instanceof Number) {
return getAsString(value);
}
var wrapped = wrap(value);
return toString(wrapped);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/adapters
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/adapters/tapestry/TapestryJsonTransformer.java
|
package ai.bizone.jsontransform.adapters.tapestry;
import ai.bizone.jsontransform.JsonTransformer;
import ai.bizone.jsontransform.JsonTransformerConfiguration;
import ai.bizone.jsontransform.TransformerFunctionsAdapter;
public class TapestryJsonTransformer extends JsonTransformer {
public static TapestryJsonAdapter DEFAULT_ADAPTER = new TapestryJsonAdapter();
public static TapestryJsonAdapter getAdapter() {
var currentAdapter = JsonTransformerConfiguration.get().getAdapter();
if (currentAdapter instanceof TapestryJsonAdapter a) {
return a;
}
return DEFAULT_ADAPTER;
}
public TapestryJsonTransformer(final Object definition) {
super(definition, getAdapter());
}
public TapestryJsonTransformer(final Object definition, TransformerFunctionsAdapter functionsAdapter) {
super(definition, getAdapter(), functionsAdapter);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/adapters
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/adapters/tapestry/TapestryJsonTransformerConfiguration.java
|
package ai.bizone.jsontransform.adapters.tapestry;
import ai.bizone.jsontransform.JsonTransformerConfiguration;
public class TapestryJsonTransformerConfiguration extends JsonTransformerConfiguration {
public TapestryJsonTransformerConfiguration() {
super(new TapestryJsonAdapter());
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/adapters
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/adapters/tapestry/TapestryObjectAdapter.java
|
package ai.bizone.jsontransform.adapters.tapestry;
import ai.bizone.jsontransform.adapters.JsonObjectAdapter;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.json.JSONObject;
import java.util.Map;
import java.util.Set;
public class TapestryObjectAdapter extends JsonObjectAdapter<Object, JSONArray, JSONObject> {
@Override
public JSONObject create() {
return new JSONObject();
}
@Override
public void add(JSONObject object, String key, String value) {
object.put(key, value == null ? JSONObject.NULL : value);
}
@Override
public void add(JSONObject object, String key, Number value) {
object.put(key, value == null ? JSONObject.NULL : value);
}
@Override
public void add(JSONObject object, String key, Boolean value) {
object.put(key, value == null ? JSONObject.NULL : value);
}
@Override
public void add(JSONObject object, String key, Character value) {
object.put(key, value == null ? JSONObject.NULL : value);
}
@Override
public void add(JSONObject object, String key, Object value) {
object.put(key, value == null ? JSONObject.NULL : value);
}
@Override
public void add(JSONObject object, String key, JSONArray value) {
object.put(key, value == null ? JSONObject.NULL : value);
}
@Override
public Object remove(JSONObject object, String key) {
return object.remove(key);
}
@Override
public boolean has(JSONObject object, String key) {
return object.containsKey(key);
}
@Override
public Object get(JSONObject object, String key) {
return object.has(key) ? object.get(key) : null;
}
@Override
public int size(JSONObject object) {
return object.size();
}
@Override
public boolean is(Object value) {
return value instanceof JSONObject;
}
@Override
public Set<Map.Entry<String, Object>> entrySet(JSONObject object) {
return object.entrySet();
}
@Override
public Set<String> keySet(JSONObject object) {
return object.keySet();
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/formats/FormatDeserializer.java
|
package ai.bizone.jsontransform.formats;
public interface FormatDeserializer {
Object deserialize(String input);
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/formats/FormatSerializer.java
|
package ai.bizone.jsontransform.formats;
public interface FormatSerializer {
String serialize(Object body);
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/formats
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/formats/csv/CsvFormat.java
|
package ai.bizone.jsontransform.formats.csv;
import ai.bizone.jsontransform.adapters.JsonAdapter;
import ai.bizone.jsontransform.formats.FormatDeserializer;
import ai.bizone.jsontransform.formats.FormatSerializer;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class CsvFormat implements FormatSerializer, FormatDeserializer {
private static final String COMMA = ",";
private static final String DEFAULT_SEPARATOR = COMMA;
private static final String DOUBLE_QUOTES = "\"";
private static final String EMBEDDED_DOUBLE_QUOTES = "\"\"";
private static final String NEW_LINE_UNIX = "\n";
private static final char LINE_FEED = '\n';
private static final char CARRIAGE_RETURN = '\r';
private static final String NEW_LINE_WINDOWS = "\r\n";
/**
* Formatter -
* if names provided it will use it as header row (unless noHeaders) and expose only those fields (if objects)
* if names not provided, it will use the names of the first object and expose all those fields for the rest
* Parser -
* if names provided it will extract only those fields
* if noHeaders is set, it will use these names to map the row values by their indices
*/
final Collection<String> names;
/**
* When used in formatter, it means the headers row will not be written
* When used in parser, it means that the output of parsing will be an array of arrays (unless names is specified)
*/
final boolean noHeaders;
/**
* Formatting will quote all values
*/
final boolean forceQuote;
/**
* What separator to format with or expect to parse with
*/
final String separator;
private final JsonAdapter<?, ?, ?> adapter;
public CsvFormat(JsonAdapter<?, ?, ?> adapter, List<String> names, Boolean noHeaders, Boolean forceQuote, String separator) {
this.adapter = adapter;
this.names = names;
this.noHeaders = noHeaders != null && noHeaders;
this.forceQuote = forceQuote != null && forceQuote;
this.separator = separator != null ? separator : DEFAULT_SEPARATOR;
}
public CsvFormat(JsonAdapter<?, ?, ?> adapter) {
this(adapter, null, null, null, null);
}
private Iterable<?> asIterable(Object value) {
if (adapter.isJsonObject(value)) {
return null;
}
if (adapter.isJsonArray(value)) {
return adapter.asIterable(value);
}
if (value instanceof Iterable<?> iter) {
return iter;
}
if (value instanceof Object[] oa) {
return Arrays.asList(oa);
}
return null;
}
public void appendEscaped(StringBuilder sb, Object val) {
String value;
if (val == null) {
value = "";
} else if (adapter.is(val)) {
value = adapter.getAsString(val);
} else {
value = val.toString();
}
if (forceQuote ||
value.contains(COMMA) ||
value.contains(DOUBLE_QUOTES) ||
value.contains(NEW_LINE_UNIX) ||
value.contains(NEW_LINE_WINDOWS) ||
value.startsWith(" ") ||
value.endsWith(" ")) {
sb.append(DOUBLE_QUOTES);
sb.append(value.replace(DOUBLE_QUOTES, EMBEDDED_DOUBLE_QUOTES));
sb.append(DOUBLE_QUOTES);
} else {
sb.append(value);
}
}
public void appendHeaders(StringBuilder sb, Collection<String> headers) {
if (noHeaders) return;
var first = true;
for (String name : headers) {
if (!first) {
sb.append(separator);
} else {
first = false;
}
appendEscaped(sb, name);
}
sb.append("\n");
}
public void appendRow(StringBuilder sb, Collection<String> names, Object value) {
// check for special case of array of arrays
Iterable<?> iter = asIterable(value);
if (iter == null) {
// this is a normal case of array of objects
if (!adapter.isJsonObject(value))
return;
var first = true;
for (String name : names) {
if (!first) {
sb.append(separator);
} else {
first = false;
}
appendEscaped(sb, adapter.get(value, name));
}
} else {
var first = true;
for (Object val : iter) {
if (!first) {
sb.append(separator);
} else {
first = false;
}
appendEscaped(sb, val);
}
}
sb.append("\n");
}
@Override
public String serialize(Object payload) {
StringBuilder sb = new StringBuilder();
var headers = names;
if (headers != null) {
appendHeaders(sb, headers);
}
// go through the items
if (payload instanceof Iterable<?> iter) {
if (headers == null) {
var it = iter.iterator();
if (it.hasNext()) {
var first = it.next();
if (first != null && adapter.isJsonObject(first)) {
headers = adapter.keySet(first);
appendHeaders(sb, headers);
}
}
}
for (Object x : iter) {
appendRow(sb, headers, x);
}
} else if (payload.getClass().isArray()) {
var len = Array.getLength(payload);
if (headers == null && len > 0) {
var first = Array.get(payload, 0);
if (first != null && adapter.isJsonObject(first)) {
headers = adapter.keySet(first);
appendHeaders(sb, headers);
}
}
for (var i = 0; i < len; i++) {
appendRow(sb, headers, Array.get(payload, i));
}
} else {
throw new Error("Unsupported object type to be formatted as CSV");
}
return sb.toString();
}
private class CsvParserContext {
public boolean inQuotes = false;
public Object names = null;
public boolean namesRead = false;
public Collection<String> extractNames = null;
}
void accumulate(CsvParserContext context, Object results, Object values) {
if (adapter.isEmpty(results) && !context.namesRead && !noHeaders) {
context.names = values;
context.namesRead = true;
return;
}
if (noHeaders && names == null) {
adapter.add(results, values); // set item as an array of values
return;
}
// there are names, make a map
if (context.names != null) {
var item = adapter.createObject();
int i;
for (i = 0; i < adapter.size(context.names); i++) {
var name = adapter.getAsString(adapter.get(context.names, i));
if ((context.extractNames == null || context.extractNames.contains(name)) &&
adapter.size(values) > i) {
adapter.add(item, name, adapter.get(values, i));
}
}
// TODO: make it conditional
// more values than names
for (; i < adapter.size(values); i++) {
if (!adapter.has(item, "$" + i)) {
adapter.add(item, "$" + i, adapter.get(values, i));
}
}
adapter.add(results, item);
}
}
@Override
public Object deserialize(String input) {
var result = adapter.createArray();
var context = new CsvParserContext();
if (noHeaders && names != null) {
context.names = adapter.createArray();
names.forEach(item -> adapter.add(context.names, item));
}
context.extractNames = names;
var len = input.length();
var row = adapter.createArray();
var cell = new StringBuilder();
var offset = 0;
while (offset < len) {
// always take current one and next one (offset may skip 1 or 2 depending on char sequence)
final int cur = input.codePointAt(offset);
var curSize = Character.charCount(cur);
final int next = offset + curSize < len ? input.codePointAt(offset + curSize) : -1;
var curAndNextSize = curSize + Character.charCount(next);
if (cur == separator.codePointAt(0)) {
if (context.inQuotes) {
cell.append(separator);
} else {
adapter.add(row, cell.toString());
cell.setLength(0);
}
offset += curSize;
} else if ( (cur == CARRIAGE_RETURN && next == LINE_FEED) || cur == LINE_FEED) {
var unix = cur == LINE_FEED;
var eof = offset + (unix ? curSize : curAndNextSize) == len;
if (!eof) {
if (context.inQuotes) {
cell.append(unix ? NEW_LINE_UNIX : NEW_LINE_WINDOWS);
} else {
adapter.add(row, cell.toString());
cell.setLength(0);
accumulate(context, result, row);
row = adapter.createArray();
}
}
offset += unix ? curSize : curAndNextSize;
} else if (cur == '"' && next == '"') { // span.startsWith(EMBEDDED_DOUBLE_QUOTES)) {
if (context.inQuotes) {
cell.append(DOUBLE_QUOTES);
offset += curAndNextSize;
} else if (cell.isEmpty()) {
// consider only the first one
context.inQuotes = !context.inQuotes;
offset += curSize;
} else {
cell.append(DOUBLE_QUOTES);
offset += curSize;
}
} else if (cur == '"') { // span.startsWith(DOUBLE_QUOTES)) {
context.inQuotes = !context.inQuotes;
offset += curSize;
} else if (!context.inQuotes && (cur == ' ' || cur == '\t')) { // (span.codePointAt(0) == ' ' || span.codePointAt(0) == '\t')) {
// ignore
offset += curSize;
} else {
cell.append(Character.toString(cur));
offset += curSize;
}
}
if (!adapter.isEmpty(result) || !cell.isEmpty()) {
adapter.add(row, cell.toString());
accumulate(context, result, row);
}
return result;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/formats
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/formats/formurlencoded/FormUrlEncodedFormat.java
|
package ai.bizone.jsontransform.formats.formurlencoded;
import ai.bizone.jsontransform.adapters.JsonAdapter;
import ai.bizone.jsontransform.formats.FormatDeserializer;
import ai.bizone.jsontransform.formats.FormatSerializer;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.StringTokenizer;
public class FormUrlEncodedFormat implements FormatSerializer, FormatDeserializer {
private final JsonAdapter<?, ?, ?> adapter;
public FormUrlEncodedFormat(JsonAdapter<?, ?, ?> adapter) {
this.adapter = adapter;
}
private void appendEntry(StringBuilder sb, String origKey, Object jeValue) {
var key = URLEncoder.encode(origKey, StandardCharsets.UTF_8);
sb.append('&').append(key);
var originalValue = adapter.getAsString(jeValue);
if (originalValue != null) {
var value = URLEncoder.encode(originalValue, StandardCharsets.UTF_8);
sb.append("=").append(value);
}
}
@Override
public String serialize(Object payload) {
try {
if (payload == null) return null;
var wrapped = adapter.wrap(payload);
if (!adapter.isJsonObject(wrapped)) {
return null;
}
var sb = new StringBuilder();
for (var kv : adapter.entrySet(wrapped)) {
var key = kv.getKey();
var value = kv.getValue();
if (adapter.isJsonArray(value)) {
for (var jeValue : adapter.asIterable(value)) {
appendEntry(sb, key, jeValue);
}
} else {
appendEntry(sb, key, value);
}
}
return !sb.isEmpty() ? sb.substring(1) : "";
}
catch (Throwable te) {
throw new RuntimeException(te);
}
}
private static String parseName(String s, StringBuilder sb) {
sb.setLength(0);
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '+':
sb.append(' ');
break;
case '%':
try {
sb.append((char) Integer.parseInt(s.substring(i+1, i+3),
16));
i += 2;
} catch (NumberFormatException e) {
throw new IllegalArgumentException();
} catch (StringIndexOutOfBoundsException e) {
String rest = s.substring(i);
sb.append(rest);
if (rest.length() == 2) {
i++;
}
}
break;
default:
sb.append(c);
break;
}
}
return sb.toString();
}
@Override
public Object deserialize(String input) {
if (input == null) {
throw new IllegalArgumentException();
}
var jo = adapter.createObject();
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(input, "&");
while (st.hasMoreTokens()) {
var key = st.nextToken();
String val;
var pos = key.indexOf('=');
if (pos > -1) {
val = parseName(key.substring(pos + 1), sb);
key = parseName(key.substring(0, pos), sb);
} else {
val = "true";
}
if (!adapter.has(jo, key)) {
adapter.add(jo, key, val);
adapter.add(jo, key + "$$", adapter.createArray());
}
adapter.add(adapter.get(jo, key + "$$"), val);
}
return jo;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/formats
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/formats/json/JsonFormat.java
|
package ai.bizone.jsontransform.formats.json;
import ai.bizone.jsontransform.adapters.JsonAdapter;
import ai.bizone.jsontransform.formats.FormatDeserializer;
import ai.bizone.jsontransform.formats.FormatSerializer;
public class JsonFormat implements FormatSerializer, FormatDeserializer {
private final JsonAdapter<?, ?, ?> adapter;
public JsonFormat(JsonAdapter<?, ?, ?> adapter) {
this.adapter = adapter;
}
@Override
public String serialize(Object payload) {
if (payload == null) return adapter.jsonNull().toString();
if (adapter.is(payload))
return payload.toString();
return adapter.toString(payload);
}
@Override
public Object deserialize(String input) {
return adapter.parse(input);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/formats
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/formats/xml/JsonOrg.java
|
package ai.bizone.jsontransform.formats.xml;
import ai.bizone.jsontransform.adapters.JsonAdapter;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonOrg {
private final JsonAdapter<?, ?, ?> adapter;
public JsonOrg(JsonAdapter<?, ?, ?> adapter) {
this.adapter = adapter;
}
public Object toJsonElement(Object value) {
Object jeValue = null;
if (JSONObject.NULL.equals(value)) {
jeValue = adapter.jsonNull();
} else if (value instanceof JSONObject propertyValue) {
jeValue = toJsonObject(propertyValue);
} else if (value instanceof JSONArray propertyArrayValue) {
jeValue = toJsonArray(propertyArrayValue);
} else if (value instanceof Character c) {
jeValue = adapter.wrap(c);
} else if (value instanceof String s) {
jeValue = adapter.wrap(s);
} else if (value instanceof Boolean b) {
jeValue = adapter.wrap(b);
} else if (value instanceof Number n) {
jeValue = adapter.wrap(n);
}
return jeValue;
}
public Object toJsonArray(JSONArray ja) {
var result = adapter.createArray();
ja.forEach(value -> adapter.add(result, toJsonElement(value)));
return result;
}
public Object toJsonObject(JSONObject jo) {
var results = adapter.createObject();
for (String key : jo.keySet()) {
adapter.add(results, key, toJsonElement(jo.get(key)));
}
return results;
}
public Object toJSONElement(Object value) {
if (value instanceof JSONArray || value instanceof JSONObject || JSONObject.NULL.equals(value)) {
return value;
}
if (adapter.is(value)) {
if (adapter.isNull(value)) {
return JSONObject.NULL;
}
if (adapter.isJsonArray(value)) {
return toJSONArray(value);
}
if (adapter.isJsonObject(value)) {
return toJSONObject(value);
}
return adapter.unwrap(value, true);
}
return JSONObject.wrap(value);
}
public JSONArray toJSONArray(Object ja) {
var result = new JSONArray();
for (var value: adapter.asIterable(ja)) {
result.put(toJSONElement(value));
}
return result;
}
public JSONObject toJSONObject(Object jo) {
var results = new JSONObject();
for (String key : adapter.keySet(jo)) {
results.put(key, toJSONElement(adapter.get(jo, key)));
}
return results;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/formats
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/formats/xml/XmlFormat.java
|
package ai.bizone.jsontransform.formats.xml;
import ai.bizone.jsontransform.adapters.JsonAdapter;
import ai.bizone.jsontransform.formats.FormatDeserializer;
import ai.bizone.jsontransform.formats.FormatSerializer;
import org.json.XMLParserConfiguration;
import org.json.XMLXsiTypeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
public class XmlFormat implements FormatSerializer, FormatDeserializer {
static final Logger log = LoggerFactory.getLogger(XmlFormat.class);
static private final boolean DEFAULT_KEEP_STRINGS = false;
/** rename "content" to "$content" (every non-tag values between any opening and closing tags) */
static private final String DEFAULT_CDATA_TAG_NAME = "$content";
static private final boolean DEFAULT_CONVERT_NIL_TO_NULL = false;
static private final Map<String, XMLXsiTypeConverter<?>> DEFAULT_XSI_TYPE_MAP = Collections.emptyMap();
static private final Set<String> DEFAULT_FORCE_LIST = Collections.emptySet();
private final JsonOrg jsonOrg;
private final javax.xml.transform.Transformer xslt; // function of 'xslt' field
private final XMLParserConfiguration config;
private final JsonAdapter<?, ?, ?> adapter;
public XmlFormat(JsonAdapter<?, ?, ?> adapter,
String xslt,
final Boolean keepStrings,
final String cDataTagName,
final Boolean convertNilAttributeToNull,
final Map<String, XMLXsiTypeConverter<?>> xsiTypeMap,
final Set<String> forceList) {
this.adapter = adapter;
this.xslt = createXSLTTransformer(xslt);
this.config = new XMLParserConfiguration()
.withKeepStrings(keepStrings != null ? keepStrings : DEFAULT_KEEP_STRINGS)
.withcDataTagName(cDataTagName != null ? cDataTagName : DEFAULT_CDATA_TAG_NAME)
.withConvertNilAttributeToNull(convertNilAttributeToNull != null ? convertNilAttributeToNull : DEFAULT_CONVERT_NIL_TO_NULL)
.withXsiTypeMap(xsiTypeMap != null ? xsiTypeMap : DEFAULT_XSI_TYPE_MAP)
.withForceList(forceList != null ? forceList : DEFAULT_FORCE_LIST);
this.jsonOrg = new JsonOrg(adapter);
}
public XmlFormat(JsonAdapter<?, ?, ?> adapter, String xslt) {
this(adapter, xslt, null, null, null, null, null);
}
public XmlFormat(JsonAdapter<?, ?, ?> adapter) {
this(adapter, null, null, null, null, null, null);
}
public static javax.xml.transform.Transformer createXSLTTransformer(String xslt) {
if (xslt == null) return null;
javax.xml.transform.Transformer transformer = null;
try {
// prepare xslt source
var xsltReader = new StringReader(xslt);
var xsltSource = new StreamSource(xsltReader);
transformer = TransformerFactory.newInstance().newTransformer(xsltSource);
} catch (Throwable te) {
log.error("Failed parsing XSLT", te);
}
return transformer;
}
public String obj2xml(Object input, String rootName) {
var json = adapter.toString(input);
// pass to org.json
var jo = new org.json.JSONObject(json);
var xml = org.json.XML.toString(jo);
return rootName != null && !rootName.isBlank() ? "<" + rootName + ">" + xml + "</" + rootName + ">"
: xml;
}
public static String indentXml(String input) throws TransformerException {
var transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
return xmlTransform(input, transformer);
}
public static String xmlTransform(String input, javax.xml.transform.Transformer transformer) {
try {
var xmlReader = new StringReader(input);
var xmlSource = new StreamSource(xmlReader);
// prepare output stream
var outWriter = new StringWriter();
var result = new StreamResult(outWriter);
// transform
transformer.transform(xmlSource, result);
// return result
return outWriter.getBuffer().toString();
}
catch (Throwable te) {
log.warn("Failed formatting to XML using provided input and XSLT", te);
throw new RuntimeException(te);
}
}
@Override
public String serialize(Object payload) {
if (xslt == null) {
log.warn("There is no (or invalid) XSLT for this formatter");
return null;
}
var inputXml = obj2xml(payload, "root");
return xmlTransform(inputXml, xslt);
}
@Override
public Object deserialize(String input) {
if (input == null) return null;
var jsonOrgObject = org.json.XML.toJSONObject(input, config);
return jsonOrg.toJsonObject(jsonOrgObject);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/formats
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/formats/yaml/YamlFormat.java
|
package ai.bizone.jsontransform.formats.yaml;
import ai.bizone.jsontransform.adapters.JsonAdapter;
import ai.bizone.jsontransform.formats.FormatDeserializer;
import ai.bizone.jsontransform.formats.FormatSerializer;
import org.snakeyaml.engine.v2.api.Dump;
import org.snakeyaml.engine.v2.api.DumpSettings;
import org.snakeyaml.engine.v2.api.Load;
import org.snakeyaml.engine.v2.api.LoadSettings;
import org.snakeyaml.engine.v2.common.FlowStyle;
public class YamlFormat implements FormatSerializer, FormatDeserializer {
private final LoadSettings loadSettings;
private final DumpSettings dumpSettings;
private final JsonAdapter<?, ?, ?> adapter;
public YamlFormat(JsonAdapter<?, ?, ?> adapter) {
this.adapter = adapter;
this.loadSettings = LoadSettings.builder()
.build();
this.dumpSettings = DumpSettings.builder()
.setDefaultFlowStyle(FlowStyle.BLOCK)
.setMultiLineFlow(true)
.setIndent(2)
.setIndicatorIndent(2) // array indention
.setIndentWithIndicator(true)
.setCanonical(false)
.build();
}
@Override
public Object deserialize(String input) {
var load = new Load(loadSettings);
var yamlOutput = load.loadFromString(input);
return adapter.wrap(yamlOutput);
}
@Override
public String serialize(Object body) {
var dump = new Dump(dumpSettings);
return dump.dumpToString(adapter.is(body) ? adapter.unwrap(body, true) : body);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionAnd.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
public class TransformerFunctionAnd extends TransformerFunction {
public TransformerFunctionAnd() {
super();
}
@Override
public Object apply(FunctionContext context) {
var adapter = context.getAdapter();
var value = context.getJsonElementStreamer(null);
if (value == null) {
return false;
}
return value.stream().allMatch(adapter::isTruthy);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionAt.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionAt extends TransformerFunction {
public TransformerFunctionAt() {
super(FunctionDescription.of(
Map.of("index", ArgumentType.of(ArgType.Number).position(0))
));
}
@Override
public Object apply(FunctionContext context) {
var value = context.getJsonElementStreamer(null);
if (value == null || value.knownAsEmpty()) {
return null;
}
var index = context.getInteger("index");
if (index == null) {
return null;
}
if (index == 0) {
return value.stream().findFirst().orElse(null);
}
if (index > 0) {
return value.stream(index.longValue(), null).findFirst().orElse(null);
}
// negative
var arr = value.toJsonArray();
var adapter = context.getAdapter();
return adapter.get(arr, adapter.size(arr) + index);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionAvg.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
public class TransformerFunctionAvg extends TransformerFunction {
public TransformerFunctionAvg() {
super(FunctionDescription.of(
Map.of(
"default", ArgumentType.of(ArgType.Number).position(0).defaultValue(BigDecimal.ZERO),
"by", ArgumentType.of(ArgType.Any).position(1))
));
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null || streamer.knownAsEmpty())
return null;
var hasBy = context.has("by");
var by = context.getJsonElement( "by", false);
var _default = Objects.requireNonNullElse(context.getBigDecimal("default"), BigDecimal.ZERO);
var size = new AtomicInteger(0);
var identity = BigDecimal.valueOf(0, FunctionHelpers.MAX_SCALE);
var adapter = context.getAdapter();
var result = streamer.stream()
.map(t -> {
size.getAndIncrement();
var res = hasBy ? context.transformItem(by, t) : t;
return adapter.isNull(res) ? _default : adapter.getNumberAsBigDecimal(res);
})
.reduce(identity, BigDecimal::add)
.divide(BigDecimal.valueOf(size.get()), FunctionHelpers.MAX_SCALE_ROUNDING);
return result;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionBase64.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
public class TransformerFunctionBase64 extends TransformerFunction {
static final Logger log = LoggerFactory.getLogger(TransformerFunctionBase64.class);
public TransformerFunctionBase64() {
super(FunctionDescription.of(
Map.of(
"action", ArgumentType.of(ArgType.String).position(0).defaultValue("ENCODE"),
"rfc", ArgumentType.of(ArgType.String).position(1).defaultValue("BASIC"),
"without_padding", ArgumentType.of(ArgType.Boolean).position(2).defaultValue(false),
"charset", ArgumentType.of(ArgType.String).position(3).defaultValue("UTF-8")
)
));
}
@Override
public Object apply(FunctionContext context) {
var str = context.getString(null);
if (str == null) {
return null;
}
// parse arguments
var encode = context.getEnum("action").charAt(0) == 'E'; // E / Enc / Encode (anything else like d / dec / decode is for decoding)
var rfc = context.getEnum("rfc"); // B = basic / U = url / M = mime
var withoutPadding = context.getBoolean("without_padding", false);
var charset = context.getEnum("charset");
String result;
try {
if (encode) {
var encoder = rfc.charAt(0) == 'M' ? Base64.getMimeEncoder() :
rfc.charAt(0) == 'U' ? Base64.getUrlEncoder() : Base64.getEncoder();
if (withoutPadding) {
encoder = encoder.withoutPadding();
}
result = new String(encoder.encode(str.getBytes(charset)), StandardCharsets.US_ASCII);
} else {
var decoder = rfc.charAt(0) == 'M' ? Base64.getMimeDecoder() :
rfc.charAt(0) == 'U' ? Base64.getUrlDecoder() : Base64.getDecoder();
// padding isn't relevant in this implementation
result = new String(decoder.decode(str), charset);
}
}
catch (UnsupportedEncodingException e) {
log.warn(context.getAlias() + " failed", e);
return null;
}
return result;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionBoolean.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionBoolean extends TransformerFunction {
public TransformerFunctionBoolean() {
super(FunctionDescription.of(
Map.of(
"style", ArgumentType.of(ArgType.String).position(0).defaultValue("JAVA")
)
));
}
@Override
public Object apply(FunctionContext context) {
var jsStyle = "JS".equals(context.getEnum("style"));
var adapter = context.getAdapter();
return adapter.isTruthy(context.getUnwrapped(null), jsStyle);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionCidrTest.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import java.math.BigInteger;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class TransformerFunctionCidrTest extends TransformerFunction {
public TransformerFunctionCidrTest() {
super(FunctionDescription.of(
Map.of(
"cidr", ArgumentType.of(ArgType.String).position(0)
)
));
}
private record IpRanges(List<String> ipv4, List<String> ipv6) {}
private static final Map<String, IpRanges> PREDEFINED;
static {
PREDEFINED = Map.of(
"loopback", new IpRanges(
List.of("127.0.0.0/8"), // RFC 3330
List.of("::1/128") // RFC 2373
),
"linklocal", new IpRanges(
List.of("169.254.0.0/16"), // RFC 3927 (2.1)
List.of("fe80::/10") // RFC 2462
),
"multicast", new IpRanges(
List.of("224.0.0.0/4"), // RFC 3171 (Class D)
List.of("ff00::/8") // RFC 2373
),
"unspecified", new IpRanges(
List.of("0.0.0.0/8"),
List.of("::0/128")
),
"private", new IpRanges(
List.of("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"), // RFC 1918
List.of("fe80::/10", "fc00::/7")
),
"reserved", new IpRanges(
Arrays.asList( // RFCs 5735, 5737, 2544, 1700
"192.0.0.0/24",
"192.0.2.0/24",
"192.88.99.0/24",
"198.18.0.0/15",
"198.51.100.0/24",
"203.0.113.0/24",
"240.0.0.0/4" // (Class E)
),
Arrays.asList(
"2001::/23", // RFC 3849
"2001:db8::/32" // RFC 2928
)
)
);
}
/**
* Converts an IPv4 address string to its 32-bit unsigned integer representation, stored in a Long.
*/
private static Long toLong(String ipV4) {
String[] octets = ipV4.split("\\.");
if (octets.length != 4) {
return null;
}
try {
long result = 0L;
result |= Long.parseLong(octets[0]) << 24;
result |= Long.parseLong(octets[1]) << 16;
result |= Long.parseLong(octets[2]) << 8;
result |= Long.parseLong(octets[3]);
return result & 0xFFFFFFFFL; // Mask to get the unsigned 32-bit value
} catch (NumberFormatException e) {
return null;
}
}
/**
* Tests if an IPv4 address is within a given CIDR subnet.
*/
private static boolean testV4(String ipV4Address, String cidrSubnet) {
try {
String address;
int netmask;
if (cidrSubnet.contains("/")) {
String[] cidr = cidrSubnet.split("/");
if (cidr.length != 2) return false;
address = cidr[0];
try {
netmask = Integer.parseInt(cidr[1]);
} catch (NumberFormatException e) {
return false;
}
} else {
address = cidrSubnet;
netmask = 32;
}
if (netmask < 0 || netmask > 32) return false;
Long networkLong = toLong(address);
if (networkLong == null) return false;
Long ipLong = toLong(ipV4Address);
if (ipLong == null) return false;
if (netmask == 0) return true;
// A right shift isolates the network portion of the address for comparison.
return (networkLong >> (32 - netmask)) == (ipLong >> (32 - netmask));
} catch (Exception e) {
return false;
}
}
/**
* Converts an IPv6 address string to its 128-bit BigInteger representation.
*/
private static BigInteger toBigInt(String ipV6) {
String[] parts = ipV6.split("::", -1);
if (parts.length > 2) {
throw new IllegalArgumentException("Invalid IPv6 address: multiple '::' segments found");
}
List<String> left = parts[0].isEmpty() ? new ArrayList<>() : new ArrayList<>(Arrays.asList(parts[0].split(":")));
List<String> right = (parts.length < 2 || parts[1].isEmpty()) ? new ArrayList<>() : new ArrayList<>(Arrays.asList(parts[1].split(":")));
int numZeroBlocks = 8 - (left.size() + right.size());
if (numZeroBlocks < 0) {
throw new IllegalArgumentException("Invalid IPv6 address: too many segments");
}
var zeroBlocks = Collections.nCopies(numZeroBlocks, "0");
var fullAddressBlocks = Stream.concat(left.stream(), Stream.concat(zeroBlocks.stream(), right.stream())).toList();
var result = BigInteger.ZERO;
for (String block : fullAddressBlocks) {
if (!block.matches("^[0-9a-fA-F]{1,4}$")) {
throw new IllegalArgumentException("Invalid IPv6 segment");
}
result = result.shiftLeft(16).or(new BigInteger(block, 16));
}
return result;
}
/**
* Tests if an IPv6 address is within a given CIDR subnet.
*/
private static boolean testV6(String ipV6Address, String cidrSubnet) {
try {
String[] parts = cidrSubnet.split("/", 2);
if (parts.length != 2) return false;
String networkStr = parts[0];
int prefix = Integer.parseInt(parts[1]);
if (prefix < 0 || prefix > 128) return false;
if (prefix == 0) return true;
BigInteger addressBigInt = toBigInt(ipV6Address);
BigInteger networkBigInt = toBigInt(networkStr);
// Create a 128-bit mask by shifting -1 (all ones) left.
BigInteger mask = new BigInteger("-1").shiftLeft(128 - prefix);
return addressBigInt.and(mask).equals(networkBigInt.and(mask));
} catch (Exception e) {
return false;
}
}
@Override
public Object apply(FunctionContext context) {
var ipAddress = context.getString(null);
if (ipAddress == null || ipAddress.isEmpty()) {
return false;
}
var cidrInput = context.getString("cidr");
if (cidrInput == null || cidrInput.isEmpty()) {
return false;
}
cidrInput = cidrInput.trim().toLowerCase();
boolean isV6 = ipAddress.contains(":");
List<String> cidrs;
if (PREDEFINED.containsKey(cidrInput)) {
IpRanges ranges = PREDEFINED.get(cidrInput);
cidrs = isV6 ? ranges.ipv6 : ranges.ipv4;
} else {
// Split by comma and trim whitespace from each resulting string
cidrs = Arrays.stream(cidrInput.split(","))
.map(String::trim)
.collect(Collectors.toList());
}
if (isV6) {
return cidrs.stream().anyMatch(cidr -> testV6(ipAddress, cidr));
} else {
return cidrs.stream().anyMatch(cidr -> testV4(ipAddress, cidr));
}
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionCoalesce.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
public class TransformerFunctionCoalesce extends TransformerFunction {
public TransformerFunctionCoalesce() {
super();
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null || streamer.knownAsEmpty()) return null;
var adapter = context.getAdapter();
return streamer.stream()
.filter(itm -> !adapter.isNull(itm))
.findFirst()
.orElse(null);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionConcat.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
import ai.bizone.jsontransform.JsonElementStreamer;
import java.util.stream.Stream;
public class TransformerFunctionConcat extends TransformerFunction {
public TransformerFunctionConcat() {
super();
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null) return null;
var adapter = context.getAdapter();
return JsonElementStreamer.fromTransformedStream(context, streamer.stream()
.flatMap(itm -> {
if (adapter.isNull(itm)) {
return Stream.empty();
} else if (adapter.isJsonArray(itm)) {
return adapter.stream(itm);
}
return Stream.of(itm);
}));
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionCsv.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.formats.csv.CsvFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/*
* @see CsvFormat for arguments explanation
* For tests
* @see TransformerFunctionCsvTest
*/
public class TransformerFunctionCsv extends TransformerFunction {
static final Logger logger = LoggerFactory.getLogger(TransformerFunctionCsv.class);
public TransformerFunctionCsv() {
super(FunctionDescription.of(
Map.of(
"no_headers", ArgumentType.of(ArgType.Boolean).position(0).defaultValue(false),
"force_quote", ArgumentType.of(ArgType.Boolean).position(1).defaultValue(false),
"separator", ArgumentType.of(ArgType.String).position(2).defaultValue(","),
"names", ArgumentType.of(ArgType.Array).position(3)
)
));
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
try {
if (streamer == null)
return null;
var names = context.getJsonArray("names");
var noHeaders = context.getBoolean("no_headers");
var forceQuote = context.getBoolean("force_quote");
var separator = context.getString("separator");
List<String> namesList = null;
var adapter = context.getAdapter();
if (names != null) {
var stringStream = (Stream<String>) adapter.stream(names).map(context::getAsString);
namesList = stringStream.collect(Collectors.toList());
}
return new CsvFormat(
adapter,
namesList,
noHeaders,
forceQuote,
separator)
.serialize(streamer.toJsonArray());
} catch (Exception e) {
logger.warn(context.getAlias() + " failed", e);
return null;
}
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionCsvParse.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.formats.csv.CsvFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.stream.Collectors;
/*
* @see CsvFormat for arguments explanation
* For tests
* @see TransformerFunctionCsvParseTest
*/
public class TransformerFunctionCsvParse extends TransformerFunction {
static final Logger logger = LoggerFactory.getLogger(TransformerFunctionCsvParse.class);
public TransformerFunctionCsvParse() {
super(FunctionDescription.of(
Map.of(
"no_headers", ArgumentType.of(ArgType.Boolean).position(0).defaultValue(false),
"separator", ArgumentType.of(ArgType.String).position(1).defaultValue(","),
"names", ArgumentType.of(ArgType.Array).position(2)
)
));
}
@Override
public Object apply(FunctionContext context) {
var csv = context.getString(null);
try {
if (csv == null)
return null;
var names = context.getJsonArray("names");
var noHeaders = context.getBoolean("no_headers");
var separator = context.getString("separator");
var adapter = context.getAdapter();
return new CsvFormat(adapter,
names == null
? null
: adapter.stream(names)
.map(context::getAsString)
.collect(Collectors.toList()),
noHeaders,
false, // not relevant for deserialization
separator)
.deserialize(csv);
} catch (Exception e) {
logger.warn(context.getAlias() + " failed", e);
return null;
}
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionDate.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.math.BigDecimal;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
public class TransformerFunctionDate extends TransformerFunction {
public static final DateTimeFormatter ISO_INSTANT_0 = new DateTimeFormatterBuilder().appendInstant(0).toFormatter();
public static final DateTimeFormatter ISO_INSTANT_3 = new DateTimeFormatterBuilder().appendInstant(3).toFormatter();
public static final DateTimeFormatter ISO_INSTANT_6 = new DateTimeFormatterBuilder().appendInstant(6).toFormatter();
public static final DateTimeFormatter ISO_INSTANT_9 = new DateTimeFormatterBuilder().appendInstant(9).toFormatter();
public TransformerFunctionDate() {
super(FunctionDescription.of(
Map.of(
"format", ArgumentType.of(ArgType.String).position(0).defaultValue("ISO"),
"digits", ArgumentType.of(ArgType.Number).position(1).defaultValue(-1),
"units", ArgumentType.of(ArgType.String).position(1),
"amount", ArgumentType.of(ArgType.Number).position(2).defaultValue(0L),
"resolution", ArgumentType.of(ArgType.String).position(1).defaultValue("UNIX"),
"pattern", ArgumentType.of(ArgType.String).position(1),
"timezone", ArgumentType.of(ArgType.String).position(2).defaultValue("UTC"),
"zone", ArgumentType.of(ArgType.String).position(1).defaultValue("UTC"),
"end", ArgumentType.of(ArgType.String).position(2)
)
));
}
static final DateTimeFormatter ISO_DATE = new DateTimeFormatterBuilder()
// date and offset
.append(DateTimeFormatter.ISO_DATE)
// default values for hour and minute
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.toFormatter()
.withZone(ZoneId.of("UTC"));
static final DateTimeFormatter ISO_TIME = new DateTimeFormatterBuilder()
// date and offset
.append(DateTimeFormatter.ISO_TIME)
// default values for hour and minute
.parseDefaulting(ChronoField.YEAR, 1970)
.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.toFormatter().withZone(ZoneId.of("UTC"));
static Instant parseInstant(Object value) {
if (value instanceof Instant i)
return i;
if (value instanceof Date d)
return d.toInstant();
if (value instanceof String s) {
if (s.contains("T"))
return DateTimeFormatter.ISO_INSTANT.parse(s, Instant::from);
else if (s.contains(":"))
return ISO_TIME.parse(s, Instant::from);
else if (s.contains("-"))
return ISO_DATE.parse(s, Instant::from);
value = Long.parseLong(s);
}
if (value instanceof Number n) {
if (n.longValue() < 2671726769L)
return Instant.ofEpochSecond(n.longValue());
return Instant.ofEpochMilli(n.longValue());
}
return Instant.parse(value.toString());
}
static Instant calendarAddToDate(Instant instant, int field, int amount) {
var c = Calendar.getInstance();
c.setTime(Date.from(instant));
c.add(field, amount);
return c.getTime().toInstant();
}
@Override
public Object apply(FunctionContext context) {
var unwrapped = context.getUnwrapped(null);
if (unwrapped == null) {
return null;
}
var instant = parseInstant(unwrapped);
return switch (context.getEnum("format")) {
case "ISO" -> switch (context.getInteger("digits")) {
case 0 -> ISO_INSTANT_0.format(instant); // no second fractions
case 3 -> ISO_INSTANT_3.format(instant); // milliseconds
case 6 -> ISO_INSTANT_6.format(instant); // microseconds
case 9 -> ISO_INSTANT_9.format(instant); // nanoseconds
default -> DateTimeFormatter.ISO_INSTANT.format(instant);
};
case "GMT" -> DateTimeFormatter.RFC_1123_DATE_TIME.format(
ZonedDateTime.ofInstant(instant, ZoneId.of("GMT")));
case "ADD" -> switch (ChronoUnit.valueOf(context.getEnum("units"))) {
case NANOS, MICROS, MILLIS, SECONDS, MINUTES, HOURS, HALF_DAYS, DAYS ->
DateTimeFormatter.ISO_INSTANT.format(instant.plus(context.getLong("amount"), ChronoUnit.valueOf(context.getEnum("units"))));
case MONTHS -> DateTimeFormatter.ISO_INSTANT.format(calendarAddToDate(instant, Calendar.MONTH, context.getInteger("amount")));
case YEARS -> DateTimeFormatter.ISO_INSTANT.format(calendarAddToDate(instant, Calendar.YEAR, context.getInteger("amount")));
default -> DateTimeFormatter.ISO_INSTANT.format(instant);
};
case "SUB" -> switch (ChronoUnit.valueOf(context.getEnum("units"))) {
case NANOS, MICROS, MILLIS, SECONDS, MINUTES, HOURS, HALF_DAYS, DAYS ->
DateTimeFormatter.ISO_INSTANT.format(instant.minus(context.getLong("amount"), ChronoUnit.valueOf(context.getEnum("units"))));
case MONTHS -> DateTimeFormatter.ISO_INSTANT.format(calendarAddToDate(instant, Calendar.MONTH, -context.getInteger("amount")));
case YEARS -> DateTimeFormatter.ISO_INSTANT.format(calendarAddToDate(instant, Calendar.YEAR, -context.getInteger("amount")));
default -> DateTimeFormatter.ISO_INSTANT.format(instant);
};
case "DATE" -> DateTimeFormatter.ISO_INSTANT.format(instant).substring(0, 10);
case "DIFF" -> {
var end = parseInstant(context.getUnwrapped("end"));
var units = ChronoUnit.valueOf(context.getEnum("units"));
if (ChronoUnit.MONTHS.equals(units)) {
var endLocalDate = LocalDate.ofInstant(end, ZoneId.of("UTC"));
var startLocalDate = LocalDate.ofInstant(instant, ZoneId.of("UTC"));
yield BigDecimal.valueOf(Period.between(startLocalDate, endLocalDate).toTotalMonths());
} else if (ChronoUnit.YEARS.equals(units)) {
var endLocalDate = LocalDate.ofInstant(end, ZoneId.of("UTC"));
var startLocalDate = LocalDate.ofInstant(instant, ZoneId.of("UTC"));
yield BigDecimal.valueOf(Period.between(startLocalDate, endLocalDate).getYears());
} else {
yield BigDecimal.valueOf(instant.until(end, units));
}
}
case "EPOCH" -> switch (context.getEnum("resolution")) {
case "MS" -> BigDecimal.valueOf(instant.toEpochMilli());
default -> BigDecimal.valueOf(instant.getEpochSecond());
};
case "FORMAT" -> DateTimeFormatter.ofPattern(context.getString("pattern"))
.withZone(ZoneId.of(context.getString("timezone").trim(), ZoneId.SHORT_IDS))
.format(instant);
case "ZONE" -> DateTimeFormatter.ISO_OFFSET_DATE_TIME
.withZone(ZoneId.of(context.getString("zone").trim(), ZoneId.SHORT_IDS))
.format(instant);
default -> null;
};
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionDecimal.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.math.RoundingMode;
import java.util.Map;
public class TransformerFunctionDecimal extends TransformerFunction {
public TransformerFunctionDecimal() {
super(FunctionDescription.of(
Map.of(
"scale", ArgumentType.of(ArgType.Number).position(0).defaultValue(-1),
"rounding", ArgumentType.of(ArgType.String).position(1).defaultValue("HALF_UP")
)
));
}
@Override
public Object apply(FunctionContext context) {
var result = context.getBigDecimal(null);
if (result == null) return null;
var scale = context.getInteger("scale");
var roundingMode = context.getEnum("rounding");
if (scale == FunctionHelpers.NO_SCALE && result.scale() > FunctionHelpers.MAX_SCALE) {
scale = FunctionHelpers.MAX_SCALE;
}
if (scale > -1) {
result = result.setScale(scale, RoundingMode.valueOf(roundingMode));
}
return result;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionDigest.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HexFormat;
import java.util.Map;
public class TransformerFunctionDigest extends TransformerFunction {
public TransformerFunctionDigest() {
super(FunctionDescription.of(
Map.of(
"algorithm", ArgumentType.of(ArgType.String).position(0).defaultValue("SHA-1"),
"format", ArgumentType.of(ArgType.String).position(1).defaultValue("BASE64")
)
));
}
@Override
public Object apply(FunctionContext context) {
var str = context.getString(null);
if (str == null) {
return null;
}
var algorithm = context.getEnum("algorithm");
try {
var digest = MessageDigest.getInstance(algorithm).digest(str.getBytes());
return switch (context.getEnum("format")) {
case "BASE64" -> Base64.getEncoder().encodeToString(digest);
case "BASE64URL" -> Base64.getUrlEncoder().encodeToString(digest);
default -> HexFormat.of().formatHex(digest);
};
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionDistinct.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.adapters.JsonAdapter;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.JsonElementStreamer;
import java.util.Map;
public class TransformerFunctionDistinct extends TransformerFunction {
public TransformerFunctionDistinct() {
super(FunctionDescription.of(
Map.of(
"by", ArgumentType.of(ArgType.Any).position(0)
)
));
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null) return null;
var hasBy = context.has("by");
var adapter = context.getAdapter();
if (hasBy) {
var by = context.getJsonElement( "by", false);
return JsonElementStreamer.fromTransformedStream(context, streamer.stream()
.map(item -> {
var toDistinctBy = context.transformItem(by, item);
return new EquatableTuple<>(adapter, item, toDistinctBy);
})
.distinct()
.map(EquatableTuple::unwrap)
);
} else if (!adapter.nodesComparable()) {
return JsonElementStreamer.fromTransformedStream(context, streamer.stream()
.map(item -> new EquatableTuple<>(adapter, item, item))
.distinct()
.map(EquatableTuple::unwrap));
} else {
return JsonElementStreamer.fromTransformedStream(context, streamer.stream().distinct());
}
}
private record EquatableTuple<T, R>(JsonAdapter<?,?,?> adapter, T value, R compareValue) {
@Override
public boolean equals(Object o) {
if (!(o instanceof EquatableTuple<?, ?> lct)) {
return false;
}
return adapter.areEqual(lct.compareValue, this.compareValue);
}
@Override
public int hashCode() {
return adapter.hashCode(this.compareValue);
}
public T unwrap() {
return value;
}
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionEntries.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.JsonElementStreamer;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
import java.util.concurrent.atomic.AtomicInteger;
public class TransformerFunctionEntries extends TransformerFunction {
public TransformerFunctionEntries() {
super();
}
@Override
public Object apply(FunctionContext context) {
var input = context.getJsonElement(null);
var adapter = context.getAdapter();
if (adapter.isJsonArray(input)) {
var i = new AtomicInteger(0);
return JsonElementStreamer.fromTransformedStream(context, adapter.stream(input)
.map(a -> {
var entry = adapter.createArray(2);
adapter.add(entry, i.getAndIncrement());
adapter.add(entry, a);
return entry;
}));
}
if (adapter.isJsonObject(input)) {
return JsonElementStreamer.fromTransformedStream(context, adapter.entrySet(input)
.stream()
.map(e -> {
var entry = adapter.createArray(2);
adapter.add(entry, e.getKey());
adapter.add(entry, e.getValue());
return entry;
}));
}
return null;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionEq.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionEq extends TransformerFunction {
public TransformerFunctionEq() {
super(FunctionDescription.of(
Map.of(
"value", ArgumentType.of(ArgType.Any).position(0),
"strict", ArgumentType.of(ArgType.Boolean).position(1).defaultValue(false)
)
));
}
@Override
public Object apply(FunctionContext context) {
var adapter = context.getAdapter();
var value = context.getJsonElement("value");
var strict = context.has("strict") && context.getBoolean("strict");
var compareValue = !strict && adapter.isJsonNumber(value)
? FunctionHelpers.nullableBigDecimalJsonPrimitive(adapter, () -> context.getBigDecimal(null))
: context.getJsonElement(null);
return adapter.areEqual(value, compareValue);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionEval.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
public class TransformerFunctionEval extends TransformerFunction {
public TransformerFunctionEval() {
super();
}
@Override
public Object apply(FunctionContext context) {
var eval = context.getJsonElement(null,true);
return context.transform(context.getPath() + "/.", eval, true);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionEvery.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionEvery extends TransformerFunction {
public TransformerFunctionEvery() {
super(FunctionDescription.of(
Map.of(
"by", ArgumentType.of(ArgType.Any).position(0)
)
));
}
@Override
public Object apply(FunctionContext context) {
var adapter = context.getAdapter();
var streamer = context.getJsonElementStreamer(null);
if (streamer == null) {
return false;
}
var by = context.getJsonElement("by", false);
return streamer.stream()
.map(x -> context.transformItem(by, x))
.allMatch(adapter::isTruthy);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionFilter.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.JsonElementStreamer;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public class TransformerFunctionFilter extends TransformerFunction {
public TransformerFunctionFilter() {
super(FunctionDescription.of(
Map.of(
"by", ArgumentType.of(ArgType.Any).position(0)
)
));
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null)
return null;
var by = context.getJsonElement("by", false);
var index = new AtomicInteger(0);
var adapter = context.getAdapter();
return JsonElementStreamer.fromTransformedStream(context, streamer.stream()
.filter(item -> {
var condition = context.transformItem(by, item, index.getAndIncrement());
return adapter.isTruthy(condition);
}));
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionFind.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public class TransformerFunctionFind extends TransformerFunction {
public TransformerFunctionFind() {
super(FunctionDescription.of(
Map.of(
"by", ArgumentType.of(ArgType.Any).position(0)
)));
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null)
return null;
var hasBy = context.has("by");
var by = context.getJsonElement("by", false);
var index = new AtomicInteger(0);
var adapter = context.getAdapter();
return streamer.stream()
.filter(item -> {
if (!hasBy) {
return adapter.isTruthy(item);
}
var condition = context.transformItem(by, item, index.getAndIncrement());
return adapter.isTruthy(condition);
})
.findFirst()
.orElse(null);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionFindIndex.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Iterator;
import java.util.Map;
public class TransformerFunctionFindIndex extends TransformerFunction {
public TransformerFunctionFindIndex() {
super(FunctionDescription.of(
Map.of(
"by", ArgumentType.of(ArgType.Any).position(0)
)));
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null)
return null;
var hasBy = context.has("by");
var by = context.getJsonElement("by", false);
var adapter = context.getAdapter();
var i = 0;
boolean found = false;
for (Iterator<?> iter = streamer.stream().iterator(); iter.hasNext();) {
var item = iter.next();
if (!hasBy) {
if (adapter.isTruthy(item)) {
found = true;
break;
}
}
var condition = context.transformItem(by, item, i++);
if (adapter.isTruthy(condition)) {
found = true;
break;
}
}
return found ? i - 1 : -1;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionFlat.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.JsonElementStreamer;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
import java.util.Objects;
import java.util.stream.Stream;
public class TransformerFunctionFlat extends TransformerFunction {
public TransformerFunctionFlat() {
super();
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null) return null;
var adapter = context.getAdapter();
return JsonElementStreamer.fromTransformedStream(context, streamer.stream()
.flatMap(itm -> {
if (adapter.isNull(itm)) {
return Stream.empty();
} else if (adapter.isJsonArray(itm)) {
return adapter.stream(itm);
}
return Stream.of(itm);
})
.filter(Objects::nonNull));
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionFlatten.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionFlatten extends TransformerFunction {
public TransformerFunctionFlatten() {
super(FunctionDescription.of(
Map.of(
"target", ArgumentType.of(ArgType.Object).position(0),
"prefix", ArgumentType.of(ArgType.String).position(1),
"array_prefix", ArgumentType.of(ArgType.String).position(2).defaultValue("$")
)
));
}
@Override
public Object apply(FunctionContext context) {
var jeTarget = context.getJsonElement("target");
Object target;
var adapter = context.getAdapter();
if (adapter.isJsonObject(jeTarget)) {
target = jeTarget;
} else {
target = adapter.createObject();
}
return flatten(context, context.getJsonElement(null, true), target, context.getString("prefix"),
context.getString("array_prefix"));
}
private Object flatten(FunctionContext context, Object source, Object target, String prefix, String arrayPrefix) {
var adapter = context.getAdapter();
if (adapter.isNull(source)) {
return target;
}
if (adapter.isJsonObject(source)) {
adapter.entrySet(source)
.forEach(es -> flatten(context, es.getValue(), target,
prefix == null ? es.getKey() : (prefix + "." + es.getKey()), arrayPrefix));
} else if (adapter.isJsonArray(source)) {
if (arrayPrefix != null) {
var size = adapter.size(source);
for (var i = 0; i < size; i++) {
flatten(context, adapter.get(source, i), target, (prefix == null ? "" : (prefix + ".")) + arrayPrefix + i, arrayPrefix);
}
} else if (prefix != null) {
adapter.add(target, prefix, source);
}
} else {
if (prefix == null || prefix.isBlank()) {
return source;
}
adapter.add(target, prefix, source);
}
return target;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionForm.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
import ai.bizone.jsontransform.formats.formurlencoded.FormUrlEncodedFormat;
public class TransformerFunctionForm extends TransformerFunction {
public TransformerFunctionForm() {
super();
}
@Override
public Object apply(FunctionContext context) {
// TODO: how to create the format once?
return new FormUrlEncodedFormat(context.getAdapter()).serialize(context.getUnwrapped(null));
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionFormParse.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
import ai.bizone.jsontransform.formats.formurlencoded.FormUrlEncodedFormat;
public class TransformerFunctionFormParse extends TransformerFunction {
public TransformerFunctionFormParse() {
super();
}
@Override
public Object apply(FunctionContext context) {
// TODO: how to create the format once?
return new FormUrlEncodedFormat(context.getAdapter()).deserialize(context.getString(null));
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionGroup.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.adapters.JsonAdapter;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.ArrayList;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
public class TransformerFunctionGroup extends TransformerFunction {
public TransformerFunctionGroup() {
super(FunctionDescription.of(
Map.of(
"by", ArgumentType.of(ArgType.Any).position(0),
"order", ArgumentType.of(ArgType.String).position(1).defaultValue("ASC"),
"type", ArgumentType.of(ArgType.String).position(2).defaultValue("AUTO"),
"then", ArgumentType.of(ArgType.Array).position(3)
)
));
}
private Object add(JsonAdapter<?, ?, ?> adapter, Object root, CompareBy by) {
var elem = new AtomicReference<>(root);
var byby = by.by;
var bybySize = byby.size();
for (var i = 0; i < bybySize - 1; i++) {
var byKey = byby.get(i);
// when adding a grouping key, fallback on empty string if null
var key = adapter.isNull(byKey) ? "" : adapter.getAsString(byKey);
var val = adapter.get(root, key);
elem.set(Objects.requireNonNullElseGet(adapter.isJsonObject(val) ? val : null, () -> {
var jo = adapter.createObject();
adapter.add(elem.get(), key, jo);
return jo;
}));
}
var byKey = byby.get(bybySize - 1);
// when adding a grouping key, fallback on empty string if null
var key = adapter.isNull(byKey) ? "" : adapter.getAsString(byKey);
var jArr = Objects.requireNonNullElseGet(
adapter.get(elem.get(), key),
adapter::createArray);
adapter.add(jArr, by.value);
adapter.add(elem.get(), key, jArr);
return root;
}
@Override
public Object apply(FunctionContext context) {
var adapter = context.getAdapter();
var value = context.getJsonElementStreamer(null);
if (value == null) {
return adapter.createObject();
}
var type = context.getEnum("type");
var order = context.getEnum("order");
var by = context.getJsonElement("by", false);
if (adapter.isNull(by)) {
return adapter.createObject();
}
var chain = new ArrayList<>();
var comparator = CompareBy.createByComparator(adapter, 0, type);
if ("DESC".equalsIgnoreCase(order)) {
comparator = comparator.reversed();
}
chain.add(by);
var thenArr = context.has("then") ? context.getJsonArray("then", false) : null;
if (thenArr != null) {
var thenArrSize = adapter.size(thenArr);
for (var i = 0; i < thenArrSize; i++) {
var thenObj = adapter.get(thenArr, i);
var thenType = adapter.has(thenObj, "type") ? context.getAsString(adapter.get(thenObj, "type")).trim() : null;
var thenOrder = adapter.get(thenObj,"order");
var thenComparator = CompareBy.createByComparator(adapter,i + 1, thenType);
var thenDescending = !adapter.isNull(thenOrder) && context.getAsString(thenOrder).equalsIgnoreCase("DESC");
if (thenDescending) {
thenComparator = thenComparator.reversed();
}
comparator = comparator.thenComparing(thenComparator);
chain.add(adapter.get(thenObj,"by"));
}
}
var result = adapter.createObject();
value.stream()
.map(item -> {
var cb = new CompareBy(item);
cb.by = new ArrayList<>();
for (var jsonElement : chain) {
var byKey = context.transformItem(jsonElement, item);
cb.by.add(byKey == null ? adapter.jsonNull() : byKey);
}
return cb;
})
.sorted(comparator)
.forEachOrdered(itm -> add(adapter, result, itm));
return result;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionGt.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionGt extends TransformerFunction {
public TransformerFunctionGt() {
super(FunctionDescription.of(
Map.of(
"value", ArgumentType.of(ArgType.Any).position(0),
"strict", ArgumentType.of(ArgType.Boolean).position(1).defaultValue(false)
)
));
}
@Override
public Object apply(FunctionContext context) {
var adapter = context.getAdapter();
var value = context.getJsonElement("value");
var strict = context.has("strict") && context.getBoolean("strict");
var compareValue = !strict && adapter.isJsonNumber(value)
? FunctionHelpers.nullableBigDecimalJsonPrimitive(adapter, () -> context.getBigDecimal(null))
: context.getJsonElement(null);
var comparison = adapter.compareTo(value, compareValue);
return comparison != null && comparison > 0;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionGte.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionGte extends TransformerFunction {
public TransformerFunctionGte() {
super(FunctionDescription.of(
Map.of(
"value", ArgumentType.of(ArgType.Any).position(0),
"strict", ArgumentType.of(ArgType.Boolean).position(1).defaultValue(false)
)
));
}
@Override
public Object apply(FunctionContext context) {
var adapter = context.getAdapter();
var value = context.getJsonElement("value");
var strict = context.has("strict") && context.getBoolean("strict");
var compareValue = !strict && adapter.isJsonNumber(value)
? FunctionHelpers.nullableBigDecimalJsonPrimitive(adapter, () -> context.getBigDecimal(null))
: context.getJsonElement(null);
var comparison = adapter.compareTo(value, compareValue);
return comparison != null && comparison >= 0;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionIf.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionIf extends TransformerFunction {
public TransformerFunctionIf() {
super(FunctionDescription.of(
Map.of(
"then", ArgumentType.of(ArgType.Any).position(0),
"else", ArgumentType.of(ArgType.Any).position(1)
)
));
}
@Override
public Object apply(FunctionContext context) {
boolean condition;
var adapter = context.getAdapter();
if (context.has("then")) {
var value = context.getJsonElement(null);
if (adapter.isTruthy(value)) {
return context.getJsonElement("then", true);
} else if (context.has("else")) {
return context.getJsonElement("else", true);
}
} else {
var arr = context.getJsonArray(null);
if (arr == null || adapter.size(arr) < 2)
return null;
var cje = adapter.get(arr, 0);
if (adapter.isNull(cje)) {
condition = false;
} else if (adapter.isJsonBoolean(cje)) {
condition = adapter.getBoolean(cje);
} else {
condition = adapter.isTruthy(context.transform(context.getPathFor(0), cje));
}
if (condition) {
return context.transform(context.getPathFor(1), adapter.get(arr, 1));
} else if (adapter.size(arr) > 2) {
return context.transform(context.getPathFor(2), adapter.get(arr, 2));
}
}
return null; // default falsy value
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionIn.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionIn extends TransformerFunction {
public TransformerFunctionIn() {
super(FunctionDescription.of(
Map.of(
"value", ArgumentType.of(ArgType.Any).position(0)
)
));
}
@Override
public Object apply(FunctionContext context) {
var value = context.getJsonElement("value");
var collection = context.getJsonElementStreamer(null);
var adapter = context.getAdapter();
return collection != null && collection.stream().anyMatch(other -> adapter.areEqual(value, other));
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionIndexOf.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public class TransformerFunctionIndexOf extends TransformerFunction {
public TransformerFunctionIndexOf() {
super(FunctionDescription.of(
Map.of(
"of", ArgumentType.of(ArgType.Any).position(0)
)));
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null)
return null;
var of = context.getJsonElement("of");
var index = new AtomicInteger(0);
var adapter = context.getAdapter();
return streamer.stream()
.sequential()
.peek(item -> index.incrementAndGet())
.anyMatch(item -> adapter.areEqual(item, of)) ? index.get() - 1 : -1;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionIs.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.math.BigDecimal;
import java.util.Map;
public class TransformerFunctionIs extends TransformerFunction {
public TransformerFunctionIs() {
super(FunctionDescription.of(
Map.of(
"op", ArgumentType.of(ArgType.String).position(0),
"that", ArgumentType.of(ArgType.Any).position(1),
"in", ArgumentType.of(ArgType.Array),
"nin", ArgumentType.of(ArgType.Array),
"eq", ArgumentType.of(ArgType.Any),
"neq", ArgumentType.of(ArgType.Any),
"gt", ArgumentType.of(ArgType.Any),
"gte", ArgumentType.of(ArgType.Any),
"lt", ArgumentType.of(ArgType.Any),
"lte", ArgumentType.of(ArgType.Any)
)
));
}
private Object nullableBigDecimalJsonPrimitive(FunctionContext context, BigDecimal number) {
var adapter = context.getAdapter();
return number == null ? adapter.jsonNull() : adapter.wrap(number);
}
@Override
public Object apply(FunctionContext context) {
var value = context.getJsonElement(null);
var adapter = context.getAdapter();
if (context.has("op")) {
var op = context.getEnum("op");
Object that = null;
// if operator is not in/nin then prepare the "that" argument which is a JsonElement
if (!"IN".equals(op) && !"NIN".equals(op)) {
that = adapter.isJsonNumber(value)
? nullableBigDecimalJsonPrimitive(context, context.getBigDecimal("that"))
: context.getJsonElement("that");
}
return switch (op) {
case "IN" -> {
var in = context.getJsonElementStreamer("that");
yield in != null && in.stream().anyMatch(other -> adapter.areEqual(value, other));
}
case "NIN" -> {
var nin = context.getJsonElementStreamer("that");
yield nin != null && nin.stream().noneMatch(other -> adapter.areEqual(value, other));
}
case "GT",">" -> {
var comparison = adapter.compareTo(value, that);
yield comparison != null && comparison > 0;
}
case "GTE",">=" -> {
var comparison = adapter.compareTo(value, that);
yield comparison != null && comparison >= 0;
}
case "LT","<" -> {
var comparison = adapter.compareTo(value, that);
yield comparison != null && comparison < 0;
}
case "LTE","<=" -> {
var comparison = adapter.compareTo(value, that);
yield comparison != null && comparison <= 0;
}
case "EQ","=","==" -> adapter.areEqual(value, that);
case "NEQ","!=","<>" -> !adapter.areEqual(value, that);
default -> false;
};
}
var result = true;
if (context.has("in")) {
var in = context.getJsonElementStreamer("in");
result = in != null && in.stream().anyMatch(other -> adapter.areEqual(value, other));
}
if (result && context.has("nin")) {
var nin = context.getJsonElementStreamer("nin");
result = nin != null && nin.stream().noneMatch(other -> adapter.areEqual(value, other));
}
if (result && context.has("gt")) {
var gt = context.getJsonElement("gt");
var comparison = adapter.compareTo(value, gt);
result = comparison != null && comparison > 0;
}
if (result && context.has("gte")) {
var gte = context.getJsonElement("gte");
var comparison = adapter.compareTo(value, gte);
result = comparison != null && comparison >= 0;
}
if (result && context.has("lt")) {
var lt = context.getJsonElement("lt");
var comparison = adapter.compareTo(value, lt);
result = comparison != null && comparison < 0;
}
if (result && context.has("lte")) {
var lte = context.getJsonElement("lte");
var comparison = adapter.compareTo(value, lte);
result = comparison != null && comparison <= 0;
}
if (result && context.has("eq")) {
var eq = context.getJsonElement("eq");
result = adapter.areEqual(value, eq);
}
if (result && context.has("neq")) {
var neq = context.getJsonElement("neq");
result = !adapter.areEqual(value, neq);
}
return result;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionIsNull.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
public class TransformerFunctionIsNull extends TransformerFunction {
public TransformerFunctionIsNull() {
super();
}
@Override
public Object apply(FunctionContext context) {
var value = context.getJsonElement(null, true);
return context.getAdapter().isNull(value);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionJoin.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
public class TransformerFunctionJoin extends TransformerFunction {
public TransformerFunctionJoin() {
super(FunctionDescription.of(
Map.of(
"delimiter", ArgumentType.of(ArgType.String).position(0).defaultValue(""),
"prefix", ArgumentType.of(ArgType.String).position(1).defaultValue(""),
"suffix", ArgumentType.of(ArgType.String).position(2).defaultValue(""),
"keep_nulls", ArgumentType.of(ArgType.Boolean).position(3).defaultValue(false)
)
));
}
@Override
public Object apply(FunctionContext context) {
var arr = context.getJsonElementStreamer(null);
var delimiter = context.getString("delimiter");
var prefix = Optional.ofNullable(context.getString("prefix")).orElse("");
var suffix = Optional.ofNullable(context.getString("suffix")).orElse("");
var stream = arr.stream().map(context::getAsString);
if (!context.getBoolean("keep_nulls")) {
stream = stream.filter(Objects::nonNull);
}
return stream.collect(Collectors.joining(delimiter, prefix, suffix));
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionJsonParse.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
public class TransformerFunctionJsonParse extends TransformerFunction {
public TransformerFunctionJsonParse() {
super();
}
@Override
public Object apply(FunctionContext context) {
var str = context.getString(null);
if (str == null) {
return null;
}
return context.getAdapter().parse(str);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionJsonPatch.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.manipulation.JsonPatch;
import java.util.Map;
public class TransformerFunctionJsonPatch extends TransformerFunction {
public TransformerFunctionJsonPatch() {
super(FunctionDescription.of(
Map.of(
"ops", ArgumentType.of(ArgType.Array).position(0)
)
));
}
@Override
public Object apply(FunctionContext context) {
var source = context.getJsonElement(null);
if (source == null) {
return null;
}
return new JsonPatch(context.getAdapter()).patch(context.getJsonArray("ops"), source);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionJsonPath.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.*;
public class TransformerFunctionJsonPath extends TransformerFunction {
public TransformerFunctionJsonPath() {
super(FunctionDescription.of(
Map.of(
"path", ArgumentType.of(ArgType.String).position(0),
"options", ArgumentType.of(ArgType.Array).position(1)
)
));
}
@Override
public Object apply(FunctionContext context) {
var source = context.getJsonElement(null);
if (source == null) {
return null;
}
var path = context.getString("path");
if (path == null) {
return null;
}
var adapter = context.getAdapter();
var optionsArray = context.getJsonArray("options");
List<String> options = null;
if (optionsArray != null && !adapter.isEmpty(optionsArray)) {
options = new ArrayList<>();
for (var option : adapter.asIterable(optionsArray)) {
options.add(adapter.getAsString(option));
}
}
return adapter.getDocumentContext(source, options).read(path);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionJsonPointer.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.manipulation.JsonPointer;
import java.util.Map;
public class TransformerFunctionJsonPointer extends TransformerFunction {
public TransformerFunctionJsonPointer() {
super(FunctionDescription.of(
Map.of(
"op", ArgumentType.of(ArgType.String).position(0).defaultValue("GET"),
"pointer", ArgumentType.of(ArgType.String).position(1),
"value", ArgumentType.of(ArgType.Any).position(2)
)
));
}
@Override
public Object apply(FunctionContext context) {
var source = context.getJsonElement(null);
if (source == null) {
return null;
}
var pointer = context.getString("pointer");
if (pointer == null) {
return null;
}
var op = context.getEnum("op");
var jsonPointer = new JsonPointer(context.getAdapter());
return switch (op) {
case "GET" -> jsonPointer.get(source, pointer);
case "SET" -> jsonPointer.set(source, pointer, context.getJsonElement("value"));
case "REMOVE" -> jsonPointer.remove(source, pointer);
default -> null;
};
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionJwtParse.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.Base64;
public class TransformerFunctionJwtParse extends TransformerFunction {
private static final Logger logger = LoggerFactory.getLogger(TransformerFunctionJwtParse.class);
public TransformerFunctionJwtParse() {
super();
}
@Override
public Object apply(FunctionContext context) {
var jwt = context.getString(null);
try {
final int dot1 = jwt.indexOf(".");
if (dot1 == -1) {
throw new ParseException("Invalid serialized JWT object: Missing part delimiters", 0);
}
final int dot2 = jwt.indexOf(".", dot1 + 1);
if (dot2 == -1) {
throw new ParseException("Invalid serialized KWT object: Missing second delimiter", 0);
}
var encodedClaimsString = jwt.substring(dot1 + 1, dot2);
var claimsString = new String(Base64.getUrlDecoder().decode(encodedClaimsString), StandardCharsets.UTF_8);
if (claimsString.startsWith("{") && claimsString.endsWith("}")) {
return context.getAdapter().parse(claimsString);
} else {
return claimsString;
}
} catch (Exception e) {
logger.warn("parseAnyJWT - Failed parsing JWT", e);
return null;
}
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionLength.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.JsonElementStreamer;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionLength extends TransformerFunction {
public TransformerFunctionLength() {
super(FunctionDescription.of(
Map.of(
"type", ArgumentType.of(ArgType.String).position(0).defaultValue("AUTO"),
"default_zero", ArgumentType.of(ArgType.Boolean).position(1).defaultValue(false)
)
));
}
@Override
public Object apply(FunctionContext context) {
var type = context.getEnum("type");
var defaultZero = context.getBoolean("default_zero");
var adapter = context.getAdapter();
switch (type) {
case "STRING" -> {
var je = context.getJsonElement(null);
if (adapter.isJsonString(je)) {
return context.getAsString(je).length();
}
}
case "ARRAY" -> {
var obj = context.get(null);
if (obj instanceof JsonElementStreamer jes) {
return jes.stream().count();
}
if (obj != null) {
var el = context.getAdapter().wrap(obj);
if (adapter.isJsonArray(el)) {
return adapter.size(el);
}
}
}
case "OBJECT" -> {
var obj = context.getJsonElement(null);
if (adapter.isJsonObject(obj)) {
return adapter.size(obj);
}
}
default -> {
// AUTO (or null)
var obj = context.get(null);
if (obj instanceof JsonElementStreamer jes) {
return jes.stream().count();
}
var je = context.getAdapter().wrap(obj);
if (adapter.isJsonObject(je) || adapter.isJsonArray(je)) {
return adapter.size(je);
}
if (adapter.isJsonString(obj)) {
return context.getAsString(obj).length();
}
}
}
return defaultZero ? 0 : null;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionLong.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
public class TransformerFunctionLong extends TransformerFunction {
public TransformerFunctionLong() {
super();
}
@Override
public Object apply(FunctionContext context) {
return context.getLong(null);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionLookup.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.JsonElementStreamer;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public class TransformerFunctionLookup extends TransformerFunction {
public TransformerFunctionLookup() {
super(FunctionDescription.of(
Map.of(
"using", ArgumentType.of(ArgType.Array).position(0),
"to", ArgumentType.of(ArgType.Any).position(1)
)
));
}
private static class UsingEntry {
public Object with;
public String as;
public Object on;
public UsingEntry(Object with, String as, Object on) {
this.with = with;
this.as = as;
this.on = on;
}
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null)
return null;
var usingArray = context.getJsonArray("using", false);
if (usingArray == null)
return null;
// prepare matches map (this will be used in each iteration to create the merged item)
var matches = new HashMap<String, Object>();
var usingMap = new HashMap<Integer, UsingEntry>();
var adapter = context.getAdapter();
var usingArraySize = adapter.size(usingArray);
for (var w = 0; w < usingArraySize; w++) {
// prepare matches map
var using = adapter.get(usingArray, w);
var asDef = adapter.get(using, "as");
if (adapter.isNull(asDef))
continue; // as - null
var as = context.getAsString(asDef);
matches.put("##" + as, null);
// collect using
var withDef = adapter.get(using, "with");
if (adapter.isNull(withDef))
continue; // with - null
var with = context.transform(context.getPathFor("with"), withDef);
if (!adapter.isJsonArray(with))
continue; // with - not array
usingMap.put(w, new UsingEntry(with, as, adapter.get(using, "on")));
}
var to = context.has("to") ? context.getJsonElement("to", false) : null; // we don't transform definitions to prevent premature evaluation
var index = new AtomicInteger(0);
return JsonElementStreamer.fromTransformedStream(context, streamer.stream().map(item1 -> {
var i = index.getAndIncrement();
for (var w = 0; w < usingArraySize; w++) {
if (!usingMap.containsKey(w)) continue;
var e = usingMap.get(w);
Object match = null;
var withSize = adapter.size(e.with);
for (var j = 0; j < withSize; j++) {
var item2 = adapter.get(e.with, j);
var conditionResult = context.transformItem(e.on, item1, i, "##" + e.as, item2);
if (adapter.isTruthy(conditionResult)) {
match = item2;
break;
}
}
matches.put("##" + e.as, match);
}
if (to == null) {
if (adapter.isJsonObject(item1)) {
var merged = item1;
for (var val : matches.values()) {
if (!adapter.isJsonObject(val))
continue; // edge case - tried to merge with an item which is not an object
merged = adapter.merge(merged, val);
}
return merged;
} else {
// edge case - tried to merge to an item which is not an object
return item1;
}
} else {
return context.transformItem(to, item1, i, matches);
}
}));
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionLower.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
public class TransformerFunctionLower extends TransformerFunction {
public TransformerFunctionLower() {
super();
}
@Override
public Object apply(FunctionContext context) {
var result = context.getString(null);
return result == null ? null : result.toLowerCase();
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionLt.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionLt extends TransformerFunction {
public TransformerFunctionLt() {
super(FunctionDescription.of(
Map.of(
"value", ArgumentType.of(ArgType.Any).position(0),
"strict", ArgumentType.of(ArgType.Boolean).position(1).defaultValue(false)
)
));
}
@Override
public Object apply(FunctionContext context) {
var adapter = context.getAdapter();
var value = context.getJsonElement("value");
var strict = context.has("strict") && context.getBoolean("strict");
var compareValue = !strict && adapter.isJsonNumber(value)
? FunctionHelpers.nullableBigDecimalJsonPrimitive(adapter, () -> context.getBigDecimal(null))
: context.getJsonElement(null);
var comparison = adapter.compareTo(value, compareValue);
return comparison != null && comparison < 0;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionLte.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionLte extends TransformerFunction {
public TransformerFunctionLte() {
super(FunctionDescription.of(
Map.of(
"value", ArgumentType.of(ArgType.Any).position(0),
"strict", ArgumentType.of(ArgType.Boolean).position(1).defaultValue(false)
)
));
}
@Override
public Object apply(FunctionContext context) {
var adapter = context.getAdapter();
var value = context.getJsonElement("value");
var strict = context.has("strict") && context.getBoolean("strict");
var compareValue = !strict && adapter.isJsonNumber(value)
? FunctionHelpers.nullableBigDecimalJsonPrimitive(adapter, () -> context.getBigDecimal(null))
: context.getJsonElement(null);
var comparison = adapter.compareTo(value, compareValue);
return comparison != null && comparison <= 0;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionMap.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.JsonElementStreamer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
public class TransformerFunctionMap extends TransformerFunction {
static final Logger logger = LoggerFactory.getLogger(TransformerFunctionMap.class);
public TransformerFunctionMap() {
super(FunctionDescription.of(
Map.of(
"to", ArgumentType.of(ArgType.Any).position(0)
)
));
}
@Override
public Object apply(FunctionContext context) {
Stream<?> inputStream;
Object to;
if (context.has("to")) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null)
return null;
inputStream = streamer.stream();
to = context.getJsonElement("to", false); // we don't transform definitions to prevent premature evaluation
} else {
// [ input, to ]
var arr = context.getJsonArray(null, false); // we don't transform definitions to prevent premature evaluation
if (arr == null)
return null;
var adapter = context.getAdapter();
var inputEl = context.transform(context.getPathFor(0), adapter.get(arr, 0));
if (!adapter.isJsonArray(inputEl)) {
logger.warn("{} was not specified with an array of items", context.getAlias());
return null;
}
inputStream = adapter.stream(inputEl);
to = adapter.get(arr, 1);
}
var i = new AtomicInteger(0);
return JsonElementStreamer.fromTransformedStream(context, inputStream
.map(x -> context.transformItem(to, x, i.getAndIncrement()))
);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionMatch.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
import java.util.regex.Pattern;
public class TransformerFunctionMatch extends TransformerFunction {
public TransformerFunctionMatch() {
super(FunctionDescription.of(
Map.of(
"pattern", ArgumentType.of(ArgType.String).position(0),
"group", ArgumentType.of(ArgType.Number).position(1).defaultValue(0)
)
));
}
@Override
public Object apply(FunctionContext context) {
var str = context.getString(null);
if (str == null) {
return null;
}
var patternString = context.getString("pattern");
if (patternString == null) {
return null;
}
var matcher = Pattern.compile(patternString).matcher(str);
if (!matcher.find())
return null; // not found
var group = context.getInteger("group");
return matcher.group(group);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionMatchAll.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.ArrayList;
import java.util.Map;
import java.util.regex.Pattern;
public class TransformerFunctionMatchAll extends TransformerFunction {
public TransformerFunctionMatchAll() {
super(FunctionDescription.of(
Map.of(
"pattern", ArgumentType.of(ArgType.String).position(0),
"group", ArgumentType.of(ArgType.Number).position(1).defaultValue(0)
)
));
}
@Override
public Object apply(FunctionContext context) {
var str = context.getString(null);
if (str == null) {
return null;
}
var patternString = context.getString("pattern");
if (patternString == null) {
return null;
}
var matcher = Pattern.compile(patternString).matcher(str);
var group = context.getInteger("group");
var allMatches = new ArrayList<>();
while (matcher.find()) {
allMatches.add(matcher.group(group));
}
return allMatches.size() == 0 ? null : allMatches ;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionMath.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;
public class TransformerFunctionMath extends TransformerFunction {
static final Logger logger = LoggerFactory.getLogger(TransformerFunctionMath.class);
public TransformerFunctionMath() {
super(FunctionDescription.of(
Map.of(
"op1", ArgumentType.of(ArgType.Number).position(0 /* or 1 */).defaultValue(BigDecimal.ZERO),
"op", ArgumentType.of(ArgType.String).position(1 /* or 0 */).defaultValue("0"),
"op2", ArgumentType.of(ArgType.Number).position(2).defaultValue(BigDecimal.ZERO)
)
));
}
@Override
public Object apply(FunctionContext context) {
var value = context.getJsonArray(null);
String parsedOp;
MathOp op;
BigDecimal op1;
BigDecimal op2;
if (value != null) {
var adapter = context.getAdapter();
var size = adapter.size(value);
if (size <= 1) return null; // invalid input
var arg0 = adapter.get(value, 0);
var arg1 = adapter.get(value, 1);
parsedOp = context.getAsString(arg0);
op = parseMathOp(parsedOp) ;
if (size > 2 && op == MathOp.UNKNOWN) {
parsedOp = context.getAsString(arg1);
op = parseMathOp(parsedOp);
op1 = adapter.getNumberAsBigDecimal(arg0);
} else {
op1 = adapter.getNumberAsBigDecimal(arg1);
}
op2 = size < 3 ? BigDecimal.ZERO : adapter.getNumberAsBigDecimal(adapter.get(value, 2));
} else {
// order of arguments ( op1, op, op2 )
parsedOp = context.getEnum("op1");
op = parseMathOp(parsedOp);
if (op == MathOp.UNKNOWN) {
// op was not detected as the first argument, so we assume it is in the second argument
// -> op1, op, [op2]
parsedOp = context.getEnum("op");
op = parseMathOp(parsedOp);
op1 = context.getBigDecimal("op1");
op2 = context.getBigDecimal("op2");
} else {
var mainArgValue = context.getUnwrapped(null);
if (mainArgValue != null) {
// we set operand 1 as main argument value for the sake of functions with only one operand
// -> op, [op2] : op1
op1 = new BigDecimal(mainArgValue.toString());
op2 = context.getBigDecimal("op");
} else {
// -> op, op1, op2
op1 = context.getBigDecimal("op");
op2 = context.getBigDecimal("op2");
}
}
}
if (op == MathOp.UNKNOWN) {
logger.warn("{} was specified with an unknown op ({})", context.getAlias(), parsedOp);
return null;
}
var result = eval(op, op1, op2);
if (result == null) {
return null;
}
// cap scale at max
if (result.scale() > FunctionHelpers.MAX_SCALE) {
result = result.setScale(FunctionHelpers.MAX_SCALE, FunctionHelpers.MAX_SCALE_ROUNDING);
}
return result;
}
enum MathOp {
ADDITION,
SUBTRACTION,
MULTIPLICATION,
DIVISION,
INTEGER_DIVISION,
MODULU,
POWER,
SQUARE_ROOT,
MIN,
MAX,
ROUND,
FLOOR,
CEIL,
ABSOLUTE,
NEGATION,
SIGNUM,
BITAND,
BITOR,
BITXOR,
SHIFT_LEFT,
SHIFT_RIGHT,
UNKNOWN
}
static MathOp parseMathOp(String value) {
return switch (value.toUpperCase()) {
case "+", "ADD" -> MathOp.ADDITION;
case "-", "SUB", "SUBTRACT" -> MathOp.SUBTRACTION;
case "*", "MUL", "MULTIPLY" -> MathOp.MULTIPLICATION;
case "/", "DIV", "DIVIDE" -> MathOp.DIVISION;
case "//", "INTDIV" -> MathOp.INTEGER_DIVISION;
case "%", "MOD", "REMAINDER" -> MathOp.MODULU;
case "^", "**", "POW", "POWER" -> MathOp.POWER;
case "&", "AND" -> MathOp.BITAND;
case "|", "OR" -> MathOp.BITOR;
case "~", "XOR" -> MathOp.BITXOR;
case "<<", "SHL" -> MathOp.SHIFT_LEFT;
case ">>", "SHR" -> MathOp.SHIFT_RIGHT;
case "MIN" -> MathOp.MIN;
case "MAX" -> MathOp.MAX;
case "SQRT" -> MathOp.SQUARE_ROOT;
case "ROUND" -> MathOp.ROUND;
case "FLOOR" -> MathOp.FLOOR;
case "CEIL" -> MathOp.CEIL;
case "ABS" -> MathOp.ABSOLUTE;
case "NEG", "NEGATE" -> MathOp.NEGATION;
case "SIG", "SIGNUM" -> MathOp.SIGNUM;
default -> MathOp.UNKNOWN;
};
}
static BigDecimal eval(MathOp op, BigDecimal op1, BigDecimal op2) {
return switch (op) {
// 2 operands
case ADDITION -> op1.add(op2, FunctionHelpers.DEFAULT_MATH_CONTEXT);
case SUBTRACTION -> op1.subtract(op2, FunctionHelpers.DEFAULT_MATH_CONTEXT);
case MULTIPLICATION -> op1.multiply(op2, FunctionHelpers.DEFAULT_MATH_CONTEXT);
case DIVISION -> op1.divide(op2, FunctionHelpers.DEFAULT_MATH_CONTEXT);
case INTEGER_DIVISION -> op1.divideToIntegralValue(op2, FunctionHelpers.DEFAULT_MATH_CONTEXT);
case MODULU -> op1.remainder(op2, FunctionHelpers.DEFAULT_MATH_CONTEXT);
case POWER -> op1.pow(op2.intValue(), FunctionHelpers.DEFAULT_MATH_CONTEXT);
case MIN -> op1.min(op2);
case MAX -> op1.max(op2);
// only one operand
case SQUARE_ROOT -> op1.sqrt(FunctionHelpers.DEFAULT_MATH_CONTEXT);
case ROUND -> op1.setScale(op2.intValue(), RoundingMode.HALF_UP);
case FLOOR -> op1.setScale(op2.intValue(), RoundingMode.FLOOR);
case CEIL -> op1.setScale(op2.intValue(), RoundingMode.CEILING);
case ABSOLUTE -> op1.abs();
case NEGATION -> op1.negate();
case SIGNUM -> new BigDecimal(op1.signum());
// bitwise
case BITAND -> new BigDecimal(op1.toBigInteger().and(op2.toBigInteger()), FunctionHelpers.DEFAULT_MATH_CONTEXT);
case BITOR -> new BigDecimal(op1.toBigInteger().or(op2.toBigInteger()), FunctionHelpers.DEFAULT_MATH_CONTEXT);
// special case where only 1 op (~x) acts as NOT (op2 acts like ~0)
case BITXOR -> new BigDecimal(op2 == null ? op1.toBigInteger().not() : op1.toBigInteger().xor(op2.toBigInteger()), FunctionHelpers.DEFAULT_MATH_CONTEXT);
case SHIFT_LEFT -> new BigDecimal(op1.toBigInteger().shiftLeft(op2.intValue()), FunctionHelpers.DEFAULT_MATH_CONTEXT);
case SHIFT_RIGHT -> new BigDecimal(op1.toBigInteger().shiftRight(op2.intValue()), FunctionHelpers.DEFAULT_MATH_CONTEXT);
default -> null;
};
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionMax.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.ArrayList;
import java.util.Map;
public class TransformerFunctionMax extends TransformerFunction {
public TransformerFunctionMax() {
super(FunctionDescription.of(
Map.of(
"default", ArgumentType.of(ArgType.Object).position(0),
"by", ArgumentType.of(ArgType.Any).position(2),
"type", ArgumentType.of(ArgType.String).position(1).defaultValue("AUTO")
)
));
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null || streamer.knownAsEmpty())
return null;
var hasBy = context.has("by");
var type = context.getEnum("type");
var def = context.getJsonElement("default",true);
var adapter = context.getAdapter();
if (!hasBy) {
var comparator = FunctionHelpers.createComparator(adapter, type);
var result = streamer.stream()
.map(t -> adapter.isNull(t) ? def : t)
.max(comparator);
return result.isPresent() ? adapter.getAs(type, result.get()) : adapter.jsonNull();
} else {
var by = context.getJsonElement("by", false);
var comparator = CompareBy.createByComparator(adapter, 0, type);
var result = streamer.stream()
.map(item -> {
var cb = new CompareBy(item);
var t = context.transformItem(by, item);
cb.by = new ArrayList<>();
cb.by.add(adapter.isNull(t) ? def : t);
return cb;
})
.max(comparator);
return result.isPresent() ? adapter.getAs(type, result.get().value) : adapter.jsonNull();
}
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionMerge.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.adapters.JsonAdapter;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
import java.util.stream.Stream;
public class TransformerFunctionMerge extends TransformerFunction {
public TransformerFunctionMerge() {
super(FunctionDescription.of(
Map.of(
"deep", ArgumentType.of(ArgType.Boolean).position(0).defaultValue(false),
"arrays", ArgumentType.of(ArgType.Boolean).position(1).defaultValue(false)
)
));
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null || streamer.knownAsEmpty())
return null;
var deep = context.getBoolean("deep");
var arrays = context.getBoolean("arrays");
var options = new JsonAdapter.JsonMergeOptions(deep, arrays);
var adapter = context.getAdapter();
var result = adapter.createObject();
return ((Stream<Object>)streamer.stream())
.reduce(result, (acc, value) -> adapter.merge(acc, value, options));
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionMin.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.ArrayList;
import java.util.Map;
public class TransformerFunctionMin extends TransformerFunction {
public TransformerFunctionMin() {
super(FunctionDescription.of(
Map.of(
"default", ArgumentType.of(ArgType.Object).position(0),
"by", ArgumentType.of(ArgType.Any).position(2),
"type", ArgumentType.of(ArgType.String).position(1).defaultValue("AUTO")
)
));
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null || streamer.knownAsEmpty())
return null;
var hasBy = context.has("by");
var type = context.getEnum("type");
var def = context.getJsonElement("default", true);
var adapter = context.getAdapter();
if (!hasBy) {
var comparator = FunctionHelpers.createComparator(adapter, type);
var result = streamer.stream()
.map(t -> adapter.isNull(t) ? def : t)
.min(comparator);
return result.isPresent() ? adapter.getAs(type, result.get()) : adapter.jsonNull();
} else {
var by = context.getJsonElement("by", false);
var comparator = CompareBy.createByComparator(adapter, 0, type);
var result = streamer.stream()
.map(item -> {
var cb = new CompareBy(item);
var t = context.transformItem(by, item);
cb.by = new ArrayList<>();
cb.by.add(adapter.isNull(t) ? def : t);
return cb;
})
.min(comparator);
return result.isPresent() ? adapter.getAs(type, result.get().value) : adapter.jsonNull();
}
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionNeq.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionNeq extends TransformerFunction {
public TransformerFunctionNeq() {
super(FunctionDescription.of(
Map.of(
"value", ArgumentType.of(ArgType.Any).position(0),
"strict", ArgumentType.of(ArgType.Boolean).position(1).defaultValue(false)
)
));
}
@Override
public Object apply(FunctionContext context) {
var adapter = context.getAdapter();
var value = context.getJsonElement("value");
var strict = context.has("strict") && context.getBoolean("strict");
var compareValue = !strict && adapter.isJsonNumber(value)
? FunctionHelpers.nullableBigDecimalJsonPrimitive(adapter, () -> context.getBigDecimal(null))
: context.getJsonElement(null);
return !adapter.areEqual(value, compareValue);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionNin.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionNin extends TransformerFunction {
public TransformerFunctionNin() {
super(FunctionDescription.of(
Map.of(
"value", ArgumentType.of(ArgType.Any).position(0)
)
));
}
@Override
public Object apply(FunctionContext context) {
var value = context.getJsonElement("value");
var collection = context.getJsonElementStreamer(null);
var adapter = context.getAdapter();
return collection != null && collection.stream().noneMatch(other -> adapter.areEqual(value, other));
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionNormalize.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Map;
import java.util.regex.Pattern;
public class TransformerFunctionNormalize extends TransformerFunction {
// * source strings (ends with _S) are after decomposition and removal of marks
// ** if target character is more than one letter,
// use _ instead and add it as a separate mapping in the exceptions map (ends with _E)
static final String LatinExANonComposed_S = "ĐđĦħŁłŊŋŒœŦŧ";
static final String LatinExANonComposed_T = "DdHhLlNn__Tt";
static final Map<String, String> LatinExANonComposed_E = Map.ofEntries(
Map.entry("Œ", "OE"), Map.entry("œ", "oe")
);
static final String LatinExBNonComposed_S = "ƀƁƄƅƆƇƈƉƊƑƒƓƕƗƘƙƚOoƤƥƦƧƨƫƬƭƳƴƵƶÆæǤǥǶǷØøȡȤȥȴȵȶȺȻȼȽȾȿɀɃɄɅɆɇɈɉɊɋɌɍɎɏ";
static final String LatinExBNonComposed_T = "bBbbCCcDDFfGhIKklOoPpRSstTtYyZz__GgHpOodZzlntACcLTszBUAEeJjQqRrYy";
static final Map<String, String> LatinExBNonComposed_E = Map.ofEntries(
Map.entry("Æ", "AE"), Map.entry("æ", "ae")
);
static final String Latin1SNonComposed_S = "Ð";
static final String Latin1SNonComposed_T = "D";
static final Map<String, String> Latin1SNonComposed_E = Map.ofEntries(
);
static final Pattern ReplacementsPattern;
static final Map<String, String> ReplacementsMap;
static {
ReplacementsPattern = Pattern.compile(
String.format("[%s]", String.join("", LatinExANonComposed_S, LatinExBNonComposed_S, Latin1SNonComposed_S)));
var entries = new ArrayList<Map.Entry<String, String>>();
addAllEntries(entries, LatinExANonComposed_S, LatinExANonComposed_T, LatinExANonComposed_E);
addAllEntries(entries, LatinExBNonComposed_S, LatinExBNonComposed_T, LatinExBNonComposed_E);
addAllEntries(entries, Latin1SNonComposed_S, Latin1SNonComposed_T, Latin1SNonComposed_E);
ReplacementsMap = Map.ofEntries(entries.toArray(Map.Entry[]::new));
}
private static void addAllEntries(ArrayList<Map.Entry<String, String>> entries, String source, String target, Map<String, String> exceptions) {
var sourceArray = source.codePoints().toArray();
for (var i = 0; i < sourceArray.length; i++) {
var sourceChar = Character.toString(sourceArray[i]);
var targetChar = Character.toString(target.codePointAt(i));
if (!targetChar.equals("_")) {
entries.add(Map.entry(sourceChar, targetChar));
} else if (exceptions.containsKey(sourceChar)) {
entries.add(Map.entry(sourceChar, exceptions.get(sourceChar)));
}
}
}
public TransformerFunctionNormalize() {
super(FunctionDescription.of(
Map.of(
"form", ArgumentType.of(ArgType.String).position(0).defaultValue("NFKD"),
"post_operation", ArgumentType.of(ArgType.String).position(1).defaultValue("ROBUST")
)
));
}
@Override
public Object apply(FunctionContext context) {
var str = context.getString(null);
if (str == null) {
return null;
}
if (str.isBlank()) return str; // short-circuit for blank strings
var normalizerForm = Normalizer.Form.valueOf(context.getEnum("form"));
str = Normalizer.normalize(str, normalizerForm);
var postOperation = context.getEnum("post_operation");
if (postOperation.equalsIgnoreCase("ROBUST")) {
// replace separators with space (and remove leading and trailing white spaces)
str = str.replaceAll("\\p{Z}", " ").strip();
// remove all diacritical marks
str = str.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
str = str.replaceAll("[·\\p{Lm}]+", ""); // solves decomposition of ʼn Ŀ ŀ
// do other replacements
str = ReplacementsPattern.matcher(str).replaceAll(result -> ReplacementsMap.get(result.group()));
}
return str;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionNot.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionNot extends TransformerFunction {
public TransformerFunctionNot() {
super(FunctionDescription.of(
Map.of(
"style", ArgumentType.of(ArgType.String).position(0).defaultValue("JAVA")
)
));
}
@Override
public Object apply(FunctionContext context) {
var jsStyle = "JS".equals(context.getEnum("style"));
var adapter = context.getAdapter();
return !adapter.isTruthy(context.get(null), jsStyle);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionNumberFormat.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;
import java.util.Map;
public class TransformerFunctionNumberFormat extends TransformerFunction {
public TransformerFunctionNumberFormat() {
super(FunctionDescription.of(
Map.of(
"type", ArgumentType.of(ArgType.String).position(0).defaultValue("NUMBER"),
"locale", ArgumentType.of(ArgType.String).position(1),
"compact_style", ArgumentType.of(ArgType.String).position(2).defaultValue("SHORT"),
"pattern", ArgumentType.of(ArgType.String).position(2).defaultValue("#0.00"),
"grouping", ArgumentType.of(ArgType.String).position(3),
"decimal", ArgumentType.of(ArgType.String).position(4),
"radix", ArgumentType.of(ArgType.Number).position(1).defaultValue(10),
"currency", ArgumentType.of(ArgType.String).position(2)
)
));
}
@Override
public Object apply(FunctionContext context) {
var type = context.getEnum("type");
var input = context.getBigDecimal(null);
if ("BASE".equals(type)) {
return input.toBigInteger().toString(context.getInteger("radix"));
}
var locale = context.getEnum("locale");
var resolvedLocale = FunctionHelpers.isNullOrEmpty(locale)
? FunctionHelpers.DEFAULT_LOCALE
: Locale.forLanguageTag(locale);
var formatter = switch (type) {
case "DECIMAL" -> FunctionHelpers.getDecimalFormatter(
resolvedLocale,
context.getString("pattern"),
context.getString("grouping"),
context.getString("decimal")
);
case "CURRENCY" -> getCurrencyFormatter(
resolvedLocale,
context.getString("currency")
);
case "PERCENT" -> NumberFormat.getPercentInstance(resolvedLocale);
case "INTEGER" -> NumberFormat.getIntegerInstance(resolvedLocale);
case "COMPACT" -> NumberFormat.getCompactNumberInstance(
resolvedLocale,
NumberFormat.Style.valueOf(context.getEnum("compact_style"))
);
default -> NumberFormat.getNumberInstance(FunctionHelpers.DEFAULT_LOCALE);
};
return formatter.format(input);
}
private NumberFormat getCurrencyFormatter(Locale resolvedLocale, String currency) {
var nf = NumberFormat.getCurrencyInstance(resolvedLocale);
if (!FunctionHelpers.isNullOrEmpty(currency)) {
nf.setCurrency(Currency.getInstance(currency));
}
return nf;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionNumberParse.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Locale;
import java.util.Map;
public class TransformerFunctionNumberParse extends TransformerFunction {
public TransformerFunctionNumberParse() {
super(FunctionDescription.of(
Map.of(
"pattern", ArgumentType.of(ArgType.String).position(0).defaultValue("#0.00"),
"locale", ArgumentType.of(ArgType.String).position(1),
"grouping", ArgumentType.of(ArgType.String).position(2),
"decimal", ArgumentType.of(ArgType.String).position(3),
"radix", ArgumentType.of(ArgType.Number).position(1).defaultValue(10)
)
));
}
@Override
public Object apply(FunctionContext context) {
var str = context.getString(null);
if (str == null) {
return null;
}
var pattern = context.getString("pattern");
if (pattern == null) {
return new BigDecimal(str);
}
if ("BASE".equals(pattern)) {
var radix = context.getInteger("radix");
return new BigDecimal(new BigInteger(str, radix));
}
var locale = context.getString("locale");
var resolvedLocale = FunctionHelpers.isNullOrEmpty(locale)
? FunctionHelpers.DEFAULT_LOCALE
: Locale.forLanguageTag(locale);
var grouping = context.getString("grouping");
var decimal = context.getString("decimal");
var formatter = FunctionHelpers.getDecimalFormatter(resolvedLocale, pattern, grouping, decimal);
try {
return formatter.parse(str);
} catch (Throwable t) {
throw t instanceof RuntimeException ex ? ex : new RuntimeException(t);
}
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionObject.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
public class TransformerFunctionObject extends TransformerFunction {
public TransformerFunctionObject() {
super();
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
var adapter = context.getAdapter();
var result = adapter.createObject();
if (streamer != null) {
streamer.stream().forEach(entry -> {
if (adapter.isJsonArray(entry)) {
var size = adapter.size(entry);
if (size > 1) {
var key = adapter.get(entry, 0);
if (!adapter.isNull(key)) {
adapter.add(result, context.getAsString(key), adapter.get(entry, 1));
}
}
}
});
}
return result;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionOr.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
public class TransformerFunctionOr extends TransformerFunction {
public TransformerFunctionOr() {
super();
}
@Override
public Object apply(FunctionContext context) {
var value = context.getJsonElementStreamer(null);
var adapter = context.getAdapter();
return value.stream().anyMatch(adapter::isTruthy);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionPad.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionPad extends TransformerFunction {
public TransformerFunctionPad() {
super(FunctionDescription.of(
Map.of(
"direction", ArgumentType.of(ArgType.String).position(0),
"width", ArgumentType.of(ArgType.Number).position(1),
"pad_string", ArgumentType.of(ArgType.String).position(2).defaultValue("0")
)
));
}
@Override
public Object apply(FunctionContext context) {
var res = context.getString(null);
if (res == null)
return null;
var direction = context.getEnum("direction");
var width = context.getInteger("width");
if (direction == null || width == null || res.length() >= width) {
return res;
}
var paddingSize = width - res.length();
var padding = context.getString("pad_string").repeat(paddingSize);
if (padding.length() > paddingSize) { // in case padding string is more than one character
padding = padding.substring(0, paddingSize);
}
StringBuilder sb = new StringBuilder();
if ("LEFT".equalsIgnoreCase(direction) || "START".equalsIgnoreCase(direction)) {
sb.append(padding).append(res);
} else if ("RIGHT".equalsIgnoreCase(direction) || "END".equalsIgnoreCase(direction)) {
sb.append(res).append(padding);
}
return sb.toString();
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionPartition.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class TransformerFunctionPartition extends TransformerFunction {
public TransformerFunctionPartition() {
super(FunctionDescription.of(
Map.of(
"size", ArgumentType.of(ArgType.Number).position(0).defaultValue(100)
)
));
}
@Override
public Object apply(FunctionContext context) {
var value = context.getJsonArray(null);
if (value == null) {
return null;
}
var size = context.getInteger("size");
var adapter = context.getAdapter();
var list = adapter.createArray();
IntStream.range(0, adapter.size(value))
.boxed()
.collect(Collectors.groupingBy(e -> e / size, Collectors.mapping(
i -> adapter.get(value, i),
Collectors.toList())))
.values().forEach(x -> {
var subList = adapter.createArray();
x.forEach(item -> adapter.add(subList, item));
adapter.add(list, subList);
});
return list;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionPathJoin.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class TransformerFunctionPathJoin extends TransformerFunction {
private static final String POSIX_SEPARATOR = "/";
private static final String WINDOWS_SEPARATOR = "\\";
private static final String WINDOWS_SEPARATOR_ESC = "\\\\";
private static Pattern normalizePatternFactory(String s) {
return Pattern.compile("([^." + s + "]+\\.|[^" + s + "]*[^." + s + "]|[^" + s + "]{3,})" + s + "\\.\\.($|" + s + ")");
}
private static final Pattern POSIX_DEDUPE_PATTERN = Pattern.compile(POSIX_SEPARATOR + "{2,}");
private static final Pattern POSIX_DIRUP_PATTERN = normalizePatternFactory(POSIX_SEPARATOR);
private static final Pattern POSIX_TRAILING_PATTERN = Pattern.compile(POSIX_SEPARATOR + "+$");
private static final Pattern POSIX_SAMEDIR_PATTERN = Pattern.compile(POSIX_SEPARATOR + "([.]" + POSIX_SEPARATOR + ")+");
private static final Pattern POSIX_SAMEDIR_START_PATTERN = Pattern.compile("^[.]" + POSIX_SEPARATOR);
private static final Pattern WINDOWS_DEDUPE_PATTERN = Pattern.compile(WINDOWS_SEPARATOR_ESC + "{2,}");
private static final Pattern WINDOWS_DIRUP_PATTERN = normalizePatternFactory(WINDOWS_SEPARATOR_ESC);
private static final Pattern WINDOWS_TRAILING_PATTERN = Pattern.compile(WINDOWS_SEPARATOR_ESC + "+$");
private static final Pattern WINDOWS_SAMEDIR_PATTERN = Pattern.compile(WINDOWS_SEPARATOR_ESC + "([.]" + WINDOWS_SEPARATOR_ESC + ")+");
private static final Pattern WINDOWS_SAMEDIR_START_PATTERN = Pattern.compile("^[.]" + WINDOWS_SEPARATOR_ESC);
public TransformerFunctionPathJoin() {
super(FunctionDescription.of(
Map.of(
"type", ArgumentType.of(ArgType.String).position(0).defaultValue("POSIX")
)
));
}
private static String normalizePath(String rawPath, String separator, boolean isURL) {
var path = separator + rawPath;
var isWin = separator.equals(WINDOWS_SEPARATOR);
var escSep = isWin ? WINDOWS_SEPARATOR_ESC : separator; // need to escape for patterns replacement
path = (isWin ? WINDOWS_DEDUPE_PATTERN : POSIX_DEDUPE_PATTERN).matcher(path).replaceAll(escSep); // dedupe all repeating separators
// normalize dir-up
var normalizer = isWin ? WINDOWS_DIRUP_PATTERN : POSIX_DIRUP_PATTERN;
while (path.contains("..") && path.indexOf(separator + "..") != 0) {
var lengthBefore = path.length();
path = normalizer.matcher(path).replaceAll("");
if (lengthBefore == path.length()) {
break; // did nothing then break
}
}
if (path.indexOf(separator + ".." + separator) == 0 || path.equals(separator + "..")) {
throw new Error("Invalid path \"" + rawPath + "\"");
}
path = (isWin ? WINDOWS_TRAILING_PATTERN : POSIX_TRAILING_PATTERN).matcher(path).replaceAll(""); // remove trailing separators
path = (isWin ? WINDOWS_SAMEDIR_PATTERN : POSIX_SAMEDIR_PATTERN).matcher(path).replaceAll(escSep);
path = (isWin ? WINDOWS_SAMEDIR_START_PATTERN : POSIX_SAMEDIR_START_PATTERN).matcher(path).replaceAll(escSep);
return isURL ? path : path.substring(1);
}
@Override
public Object apply(FunctionContext context) {
var arr = context.getJsonElementStreamer(null);
if (arr == null) {
return null;
}
var type = context.getEnum("type"); // should be either "/" or "\"
var separator = type.equals("WINDOWS") ? WINDOWS_SEPARATOR : POSIX_SEPARATOR;
var stream = arr.stream()
.map(context::getAsString)
.filter(x -> x != null && !x.isEmpty());
var isURL = "URL".equals(type);
if (isURL) {
stream = stream.map(x -> URLEncoder.encode(x, StandardCharsets.UTF_8));
}
var path = stream.collect(Collectors.joining(separator));
return normalizePath(path, separator, isURL);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionRandom.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Random;
public class TransformerFunctionRandom extends TransformerFunction {
final Random random = new Random();
public TransformerFunctionRandom() {
super(FunctionDescription.of(
Map.of(
"min", ArgumentType.of(ArgType.Number).position(0).defaultValue(BigDecimal.ZERO),
"max", ArgumentType.of(ArgType.Number).position(1).defaultValue(BigDecimal.ONE)
)
));
}
@Override
public Object apply(FunctionContext context) {
BigDecimal min;
BigDecimal max;
if (context.has("min")) {
min = context.getBigDecimal("min");
max = context.getBigDecimal("max");
} else {
var arr = context.getJsonArray(null);
var adapter = context.getAdapter();
var length = adapter.size(arr);
min = length > 0 ? adapter.getNumberAsBigDecimal(adapter.get(arr, 0)) : null;
max = length > 1 ? adapter.getNumberAsBigDecimal(adapter.get(arr, 1)) : null;
}
// sanity check
if (min == null || max == null || max.compareTo(min) < 0) {
return null;
}
var rand = BigDecimal.valueOf(random.nextDouble());
var diff = max.subtract(min);
var result = min.add(diff.multiply(rand, FunctionHelpers.DEFAULT_MATH_CONTEXT));
// cap scale at max
if (result.scale() > FunctionHelpers.MAX_SCALE) {
result = result.setScale(FunctionHelpers.MAX_SCALE, FunctionHelpers.MAX_SCALE_ROUNDING);
}
return result;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionRange.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.JsonElementStreamer;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
public class TransformerFunctionRange extends TransformerFunction {
public TransformerFunctionRange() {
super(FunctionDescription.of(
Map.of(
"start", ArgumentType.of(ArgType.Number).position(0),
"end", ArgumentType.of(ArgType.Number).position(1),
"step", ArgumentType.of(ArgType.Number).position(2).defaultValue(BigDecimal.ONE)
)
));
}
@Override
public Object apply(FunctionContext context) {
BigDecimal start;
BigDecimal end;
BigDecimal step;
if (context.has("start")) {
start = context.getBigDecimal("start");
end = context.getBigDecimal("end");
step = context.getBigDecimal("step");
} else {
var arr = context.getJsonArray(null);
var adapter = context.getAdapter();
var length = adapter.size(arr);
start = length > 0 ? adapter.getNumberAsBigDecimal(adapter.get(arr, 0)) : null;
end = length > 1 ? adapter.getNumberAsBigDecimal(adapter.get(arr, 1)) : null;
step = length > 2 ? adapter.getNumberAsBigDecimal(adapter.get(arr, 2)) : BigDecimal.ONE;
}
// sanity check
if (start == null ||
end == null ||
(end.compareTo(start) < 0 && step.signum() > 0) ||
(end.compareTo(start) > 0 && step.signum() < 0)
) {
return null;
}
var size = end.subtract(start).divideToIntegralValue(step).add(BigDecimal.ONE).intValue();
var value = new AtomicReference<>(start);
return JsonElementStreamer.fromTransformedStream(context,
Stream.generate(() -> value.getAndUpdate(next -> next.add(step))).limit(size)
);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionRaw.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
public class TransformerFunctionRaw extends TransformerFunction {
public TransformerFunctionRaw() {
super();
}
@Override
public Object apply(FunctionContext context) {
return context.getJsonElement(null, false);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionReduce.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
public class TransformerFunctionReduce extends TransformerFunction {
public TransformerFunctionReduce() {
super(FunctionDescription.of(
Map.of(
"to", ArgumentType.of(ArgType.Any).position(0),
"identity", ArgumentType.of(ArgType.Any).position(1)
)
));
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null)
return null;
var identity = context.getJsonElement("identity");
var to = context.getJsonElement("to", false);
var i = new AtomicInteger(0);
return ((Stream<Object>)streamer.stream())
.reduce(identity, (acc, x) -> context.transformItem(to, x, i.getAndIncrement(), "##accumulator", acc));
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionRepeat.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.JsonElementStreamer;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
import java.util.stream.Stream;
public class TransformerFunctionRepeat extends TransformerFunction {
public TransformerFunctionRepeat() {
super(FunctionDescription.of(
Map.of(
"count", ArgumentType.of(ArgType.Number).position(0)
)
));
}
@Override
public Object apply(FunctionContext context) {
var value = context.getJsonElement(null);
if (value == null) {
return null;
}
var count = context.getInteger("count");
if (count == null || count < 0) {
return null;
}
return JsonElementStreamer.fromTransformedStream(context,
Stream.generate(() -> value).limit(count)
);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionReplace.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionReplace extends TransformerFunction {
public TransformerFunctionReplace() {
super(FunctionDescription.of(
Map.of(
"find", ArgumentType.of(ArgType.String).position(0).defaultValue(""),
"replacement", ArgumentType.of(ArgType.String).position(1).defaultValue(""),
"type", ArgumentType.of(ArgType.String).position(2).defaultValue("STRING"),
"from", ArgumentType.of(ArgType.Number).position(3).defaultValue(0)
)
));
}
private static String replaceOnce(String value, String find, String replacement, Integer fromIndex) {
int index = value.indexOf(find, fromIndex);
if (index == -1) {
return value;
}
return value.substring(0, index)
.concat(replacement)
.concat(value.substring(index + find.length()));
}
@Override
public Object apply(FunctionContext context) {
var str = context.getString(null);
if (str == null) {
return null;
}
var find = context.getString("find");
if (find == null) {
return str;
}
var replacement = context.getString("replacement");
var from = context.getInteger("from");
var validFrom = from > 0 && str.length() > from;
return switch (context.getEnum("type")) {
case "FIRST" -> replaceOnce(str, find, replacement, validFrom ? from : 0);
case "REGEX" -> validFrom
? str.substring(0, from) + str.substring(from).replaceAll(find, replacement)
: str.replaceAll(find, replacement);
case "REGEX-FIRST" -> validFrom
? str.substring(0, from) + str.substring(from).replaceFirst(find, replacement)
: str.replaceFirst(find, replacement);
default -> validFrom
? str.substring(0, from) + str.substring(from).replace(find, replacement)
: str.replace(find, replacement);
};
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionReverse.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
import ai.bizone.jsontransform.JsonElementStreamer;
public class TransformerFunctionReverse extends TransformerFunction {
public TransformerFunctionReverse() {
super();
}
private <T> int compare(T a, T b) {
return -1;
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null) {
return null;
}
return JsonElementStreamer.fromTransformedStream(context, streamer.stream().sorted(this::compare));
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionSlice.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.JsonElementStreamer;
import java.util.Map;
public class TransformerFunctionSlice extends TransformerFunction {
public TransformerFunctionSlice() {
super(FunctionDescription.of(
Map.of(
"begin", ArgumentType.of(ArgType.Number).position(0).defaultValue(0),
"end", ArgumentType.of(ArgType.Number).position(1)
)
));
}
@Override
public Object apply(FunctionContext context) {
var adapter = context.getAdapter();
var value = context.getJsonElementStreamer(null);
var begin = context.getInteger("begin");
var end = context.getInteger("end");
if (begin >= 0) {
if (end == null) {
// // slice() / slice(1)
return begin == 0 ? value : JsonElementStreamer.fromTransformedStream(context, value.stream(begin.longValue(), null));
}
if (end >= 0) {
if (end <= begin) {
// slice(3, 1) -- can't have indexes not in order, result is empty
return adapter.createArray();
}
// slice(1, 3)
return JsonElementStreamer.fromTransformedStream(context, value.stream(begin.longValue(), end.longValue() - begin.longValue()));
}
// slice(1, -2)
var result = adapter.createArray();
// at least skip the start index and then convert to array
value.stream(begin.longValue(), null).forEach(item -> adapter.add(result, item));
for (int i = 0; i < -end; i++) {
adapter.remove(result, adapter.size(result) - 1);
}
return result;
}
// begin < 0
if (end != null && end >= 0) {
// slice(-1, 3) -- if begin is negative, end must be negative too, result is empty
return adapter.createArray();
}
// end == null || end < 0
// slice(-1) / slice(-3, -1)
// any negative indices means that we now need to convert the stream to an array to determine the size
var arr = value.toJsonArray();
var arrSize = adapter.size(arr);
var result = adapter.createArray();
for (int i = arrSize + begin; i < arrSize + (end == null ? 0 : end) ; i++) {
adapter.add(result, adapter.get(arr, i));
}
return result;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionSome.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionSome extends TransformerFunction {
public TransformerFunctionSome() {
super(FunctionDescription.of(
Map.of(
"by", ArgumentType.of(ArgType.Any).position(0)
)
));
}
@Override
public Object apply(FunctionContext context) {
var adapter = context.getAdapter();
var streamer = context.getJsonElementStreamer(null);
if (streamer == null) {
return false;
}
var by = context.getJsonElement("by", false);
return streamer.stream()
.map(x -> context.transformItem(by, x))
.anyMatch(adapter::isTruthy);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionSort.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.JsonElementStreamer;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Map;
public class TransformerFunctionSort extends TransformerFunction {
public TransformerFunctionSort() {
super(FunctionDescription.of(
Map.of(
"by", ArgumentType.of(ArgType.Any).position(0),
"order", ArgumentType.of(ArgType.String).position(1).defaultValue("ASC"),
"type", ArgumentType.of(ArgType.String).position(2).defaultValue("AUTO"),
"then", ArgumentType.of(ArgType.Array).position(3)
)
));
}
@Override
public Object apply(FunctionContext context) {
var arr = context.getJsonElementStreamer(null);
if (arr == null) {
return null;
}
var type = context.getEnum("type");
var order = context.getEnum("order");
var descending = "DESC".equals(order);
var adapter = context.getAdapter();
if (!context.has("by")) {
// does not have sort "by" (can sort inside the stream)
Comparator<Object> comparator = FunctionHelpers.createComparator(adapter, type);
return JsonElementStreamer.fromTransformedStream(context, arr.stream()
.sorted(descending ? comparator.reversed() : comparator)
);
} else {
var by = context.getJsonElement( "by", false);
var chain = new ArrayList<>();
var comparator = CompareBy.createByComparator(adapter, 0, type);
if (descending) comparator = comparator.reversed();
chain.add(by);
var thenArr = context.has("then") ? context.getJsonArray("then", false) : null;
if (thenArr != null) {
var size = adapter.size(thenArr);
for (var i = 0; i < size; i++) {
var thenObj = adapter.get(thenArr, i);
var thenType = adapter.has(thenObj, "type") ? context.getAsString(adapter.get(thenObj, "type")).trim() : null;
var thenOrder = adapter.get(thenObj,"order");
var thenComparator = CompareBy.createByComparator(adapter,i + 1, thenType);
var thenDescending = !adapter.isNull(thenOrder) && context.getAsString(thenOrder).equalsIgnoreCase("DESC");
if (thenDescending) {
thenComparator = thenComparator.reversed();
}
comparator = comparator.thenComparing(thenComparator);
chain.add(adapter.get(thenObj,"by"));
}
}
return JsonElementStreamer.fromTransformedStream(context, arr.stream()
.map(item -> {
var cb = new CompareBy(item);
cb.by = new ArrayList<>();
for (var jsonElement : chain) {
cb.by.add(context.transformItem(jsonElement, item));
}
return cb;
})
.sorted(comparator)
.map(itm -> itm.value));
}
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionSplit.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionSplit extends TransformerFunction {
public TransformerFunctionSplit() {
super(FunctionDescription.of(
Map.of(
"delimiter", ArgumentType.of(ArgType.String).position(0).defaultValue(""),
"limit", ArgumentType.of(ArgType.Number).position(1).defaultValue(0)
)
));
}
@Override
public Object apply(FunctionContext context) {
var str = context.getString(null);
if (str == null) {
return null;
}
return str.split(context.getString("delimiter"), context.getInteger("limit"));
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionStddev.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
public class TransformerFunctionStddev extends TransformerFunction {
public TransformerFunctionStddev() {
super(FunctionDescription.of(
Map.of(
"default", ArgumentType.of(ArgType.Number).position(0).defaultValue(BigDecimal.ZERO),
"by", ArgumentType.of(ArgType.Any).position(1),
"population", ArgumentType.of(ArgType.Boolean).position(2).defaultValue(false)
)
));
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null || streamer.knownAsEmpty())
return null;
var hasBy = context.has("by");
var by = context.getJsonElement( "by", false);
var population = context.getBoolean( "population");
var _default = Objects.requireNonNullElse(context.getBigDecimal("default"), BigDecimal.ZERO);
var size = new AtomicInteger(0);
var adapter = context.getAdapter();
var values = streamer.stream()
.map(t -> {
size.getAndIncrement();
var res = hasBy ? context.transformItem(by, t) : t;
return adapter.isNull(res) ? _default : adapter.getNumberAsBigDecimal(res);
}).toList();
var identity = BigDecimal.valueOf(0, FunctionHelpers.MAX_SCALE);
var avg = values.stream().reduce(identity, BigDecimal::add)
.divide(BigDecimal.valueOf(size.get()), FunctionHelpers.MAX_SCALE_ROUNDING);
var sumOfSquares = values.stream()
.map(val -> val.subtract(avg).pow(2))
.reduce(identity, BigDecimal::add);
var variance = sumOfSquares.divide(BigDecimal.valueOf(size.get() - (population ? 0 : 1)), FunctionHelpers.MAX_SCALE_ROUNDING);
var result = variance.sqrt(FunctionHelpers.DEFAULT_MATH_CONTEXT);
// cap scale at max
if (result.scale() > FunctionHelpers.MAX_SCALE) {
result = result.setScale(FunctionHelpers.MAX_SCALE, FunctionHelpers.MAX_SCALE_ROUNDING);
}
return result;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionString.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionString extends TransformerFunction {
public TransformerFunctionString() {
super(FunctionDescription.of(
Map.of(
"json", ArgumentType.of(ArgType.Boolean).position(0).defaultValue(false)
)
));
}
@Override
public Object apply(FunctionContext context) {
var value = context.getUnwrapped(null);
if (context.getBoolean("json")) {
// although gson.toJson will return "null" eventually, this is quicker
if (value == null) {
return "null";
}
var adapter = context.getAdapter();
return adapter.toString(value);
}
return context.getAsString(value);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionSubstring.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionSubstring extends TransformerFunction {
public TransformerFunctionSubstring() {
super(FunctionDescription.of(
Map.of(
"begin", ArgumentType.of(ArgType.Number).position(0).defaultValue(0),
"end", ArgumentType.of(ArgType.Number).position(1)
)
));
}
@Override
public Object apply(FunctionContext context) {
var str = context.getString(null);
if (str == null) {
return null;
}
var length = str.length();
var beginIndex = context.getInteger("begin");
if (beginIndex == null) {
return str;
}
if (beginIndex < 0) {
beginIndex = Math.max(0, length + beginIndex);
}
var endValue = context.getInteger("end");
if (endValue == null) {
return str.substring(beginIndex);
}
var endIndex = Math.min(endValue, length);
if (endIndex < 0) {
endIndex = Math.max(0, length + endIndex);
}
return str.substring(beginIndex, endIndex);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionSum.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Objects;
public class TransformerFunctionSum extends TransformerFunction {
public TransformerFunctionSum() {
super(FunctionDescription.of(
Map.of(
"default", ArgumentType.of(ArgType.Number).position(0).defaultValue(BigDecimal.ZERO),
"by", ArgumentType.of(ArgType.Any).position(1)
)
));
}
@Override
public Object apply(FunctionContext context) {
var streamer = context.getJsonElementStreamer(null);
if (streamer == null || streamer.knownAsEmpty())
return null;
var hasBy = context.has("by");
var by = context.getJsonElement("by", false);
var def = Objects.requireNonNullElse(context.getBigDecimal("default"), BigDecimal.ZERO);
var adapter = context.getAdapter();
var result = streamer.stream()
.map(t -> {
var res = hasBy ? context.transformItem(by, t) : t;
return adapter.isNull(res) ? def : adapter.getNumberAsBigDecimal(res);
})
.reduce(BigDecimal.ZERO, BigDecimal::add);
// cap scale at max
if (result.scale() > FunctionHelpers.MAX_SCALE) {
result = result.setScale(FunctionHelpers.MAX_SCALE, FunctionHelpers.MAX_SCALE_ROUNDING);
}
return result;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionSwitch.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
public class TransformerFunctionSwitch extends TransformerFunction {
static final Logger logger = LoggerFactory.getLogger(TransformerFunctionSwitch.class);
public TransformerFunctionSwitch() {
super(FunctionDescription.of(
Map.of(
"cases", ArgumentType.of(ArgType.Object).position(0),
"default", ArgumentType.of(ArgType.Any).position(1)
)
));
}
@Override
public Object apply(FunctionContext context) {
var alias = context.getAlias();
var value = context.getString(null);
var adapter = context.getAdapter();
var caseMap = context.getJsonElement("cases");
if (!adapter.isJsonObject(caseMap)) {
logger.warn("{}.cases was not specified with an object as case map", alias);
return null;
}
return adapter.has(caseMap, value)
? adapter.get(caseMap, value)
: context.getJsonElement("default");
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionTemplate.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.ParameterResolver;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.template.ParameterDefaultResolveOptions;
import ai.bizone.jsontransform.template.TextTemplate;
import java.util.Map;
import static ai.bizone.jsontransform.functions.common.FunctionContext.pathOfVar;
public class TransformerFunctionTemplate extends TransformerFunction {
private static final Object DOLLAR = "$";
public TransformerFunctionTemplate() {
super(FunctionDescription.of(
Map.of(
"payload", ArgumentType.of(ArgType.Any).position(0),
"default_resolve", ArgumentType.of(ArgType.String).position(1).defaultValue(ParameterDefaultResolveOptions.UNIQUE.name()),
"url_encode", ArgumentType.of(ArgType.Boolean).position(2).defaultValue(false)
)
));
}
@Override
public Object apply(FunctionContext context) {
var input = context.getString(null);
if (input == null) {
return null;
}
var adapter = context.getAdapter();
var defaultResolveValue = context.getEnum("default_resolve");
var defaultResolver = ParameterDefaultResolveOptions.valueOf(defaultResolveValue);
var urlEncode = context.getBoolean("url_encode");
var currentResolver = context.getResolver();
ParameterResolver resolver = currentResolver;
var payload = context.getJsonElement("payload");
if (!adapter.isNull(payload)) {
var dc = adapter.getDocumentContext(payload);
resolver = name -> {
if (pathOfVar("##current", name)) {
return dc.read(DOLLAR + name.substring(9));
}
return currentResolver.get(name);
};
}
var tt = TextTemplate.get(input, defaultResolver);
return tt.render(resolver, adapter, urlEncode);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionTest.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
import java.util.regex.Pattern;
public class TransformerFunctionTest extends TransformerFunction {
public TransformerFunctionTest() {
super(FunctionDescription.of(
Map.of(
"pattern", ArgumentType.of(ArgType.String).position(0)
)
));
}
@Override
public Object apply(FunctionContext context) {
var str = context.getString(null);
if (str == null) {
return false;
}
var patternString = context.getString("pattern");
if (patternString == null) {
return false;
}
return Pattern.compile(patternString).matcher(str).find();
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionTransform.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionTransform extends TransformerFunction {
public TransformerFunctionTransform() {
super(FunctionDescription.of(
Map.of(
"to", ArgumentType.of(ArgType.Any).position(0)
)
));
}
@Override
public Object apply(FunctionContext context) {
var input = context.getJsonElement(null);
var to = context.getJsonElement("to", false);
return context.transformItem(to, input);
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionTrim.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionTrim extends TransformerFunction {
public TransformerFunctionTrim() {
super(FunctionDescription.of(
Map.of(
"type", ArgumentType.of(ArgType.String).position(0).defaultValue("BOTH")
)
));
}
@Override
public Object apply(FunctionContext context) {
var str = context.getString(null);
if (str == null) {
return null;
}
return switch (context.getEnum("type")) {
case "START" -> str.stripLeading();
case "END" -> str.stripTrailing();
case "INDENT" -> str.stripIndent();
case "JAVA" -> str.trim();
default -> str.strip();
};
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionUnflatten.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.*;
import ai.bizone.jsontransform.functions.common.*;
import java.util.Map;
public class TransformerFunctionUnflatten extends TransformerFunction {
public TransformerFunctionUnflatten() {
super(FunctionDescription.of(
Map.of(
"target", ArgumentType.of(ArgType.Object).position(0),
"path", ArgumentType.of(ArgType.String).position(1)
)
));
}
@Override
public Object apply(FunctionContext context) {
Object target;
var adapter = context.getAdapter();
var targetValue = context.getJsonElement("target");
if (adapter.isJsonObject(targetValue)) {
target = targetValue;
} else {
target = adapter.createObject();
}
var source = context.getJsonElement(null, true);
var path = context.getString("path", true);
if (adapter.isJsonObject(source)) {
adapter.entrySet(source)
.forEach(ke -> adapter.mergeInto(target, ke.getValue(),
(path != null ? path + '.' : "") + ke.getKey()));
}
return target;
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionUpper.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
public class TransformerFunctionUpper extends TransformerFunction {
public TransformerFunctionUpper() {
super();
}
@Override
public Object apply(FunctionContext context) {
var result = context.getString(null);
return result == null ? null : result.toUpperCase();
}
}
|
0
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform
|
java-sources/ai/bizone/json-transform/1.3.1/ai/bizone/jsontransform/functions/TransformerFunctionUriParse.java
|
package ai.bizone.jsontransform.functions;
import ai.bizone.jsontransform.functions.common.FunctionContext;
import ai.bizone.jsontransform.functions.common.TransformerFunction;
import ai.bizone.jsontransform.formats.formurlencoded.FormUrlEncodedFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
import java.net.URISyntaxException;
public class TransformerFunctionUriParse extends TransformerFunction {
static final Logger log = LoggerFactory.getLogger(TransformerFunctionUriParse.class);
public TransformerFunctionUriParse() {
super();
}
@Override
public Object apply(FunctionContext context) {
var str = context.getString(null);
if (str == null) {
return null;
}
try {
var adapter = context.getAdapter();
var result = adapter.createObject();
URI uri = new URI(str);
adapter.add(result, "scheme", uri.getScheme());
var userInfo = uri.getUserInfo();
if (userInfo != null) {
adapter.add(result, "user_info", userInfo);
}
adapter.add(result, "authority", uri.getAuthority());
var port = uri.getPort();
adapter.add(result, "host", port > -1 ? uri.getHost() + ":" + port : uri.getHost());
adapter.add(result, "hostname", uri.getHost());
if (port > -1) {
adapter.add(result, "port", port);
}
adapter.add(result, "path", uri.getPath());
var queryString = uri.getQuery();
if (queryString != null) {
// TODO: how to create the format once?
var formUrlFormat = new FormUrlEncodedFormat(adapter);
adapter.add(result, "query", formUrlFormat.deserialize(queryString));
adapter.add(result, "query_raw", queryString);
}
var fragment = uri.getFragment();
if (fragment != null) {
adapter.add(result, "fragment", fragment);
}
return result;
} catch (URISyntaxException e) {
log.warn("Failed parsing uri", e);
return null;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.