Example usage for com.google.gson JsonElement getAsJsonArray

List of usage examples for com.google.gson JsonElement getAsJsonArray

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsJsonArray.

Prototype

public JsonArray getAsJsonArray() 

Source Link

Document

convenience method to get this element as a JsonArray .

Usage

From source file:com.balajeetm.mystique.core.JsonMystique.java

License:Open Source License

/**
 * Gets the fields.//w  ww  . j a v a 2s . c  o m
 *
 * @param source the source
 * @param dependencies the dependencies
 * @param aces the aces
 * @param path the path
 * @param fields the fields
 * @return the fields
 */
private Boolean getFields(JsonElement source, JsonObject dependencies, JsonObject aces, JsonArray path,
        List<JsonElement> fields) {
    Boolean isLoopy = Boolean.FALSE;
    if (null != path) {
        if (path.size() > 0) {
            for (JsonElement jsonElement : path) {
                if (jsonElement.isJsonArray()) {
                    JsonArray fromArray = jsonElement.getAsJsonArray();
                    isLoopy = isLoopy || jsonLever.updateFields(source, dependencies, aces, fields, fromArray);
                    // Once isloopy, the loop doesn't execute anymore
                } else {
                    isLoopy = isLoopy || jsonLever.updateFields(source, dependencies, aces, fields, path);
                    break;
                }
            }
        } else {
            isLoopy = isLoopy || jsonLever.updateFields(source, dependencies, aces, fields, path);
        }
    }
    return isLoopy;
}

From source file:com.balajeetm.mystique.core.lever.MystiqueLever.java

License:Open Source License

/**
 * Gets the subset./* ww w.jav  a2 s  .  c  o  m*/
 *
 * @param source the source
 * @param deps the deps
 * @param aces the aces
 * @param valueObject the value object
 * @return the subset
 */
public JsonElement subset(JsonElement source, JsonObject deps, JsonObject aces, JsonElement valueObject) {
    JsonElement finalValue = null;
    if (valueObject.isJsonArray()) {
        finalValue = subset(source, deps, aces, valueObject.getAsJsonArray());
    } else if (isString(valueObject)) {
        finalValue = subset(source, deps, aces, getJpath(valueObject));
    } else if (isObject(valueObject)) {
        // This is a turn
        JsonObject valueJson = valueObject.getAsJsonObject();
        MystTurn mystique = factory().getMystTurn(valueJson);
        finalValue = mystique.transform(Lists.newArrayList(source), deps, aces, valueJson, new JsonObject());
    }
    return finalValue;
}

From source file:com.balajeetm.mystique.core.lever.MystiqueLever.java

License:Open Source License

/**
 * Sets the field of a json source./*from  w ww .  j  a v a  2  s . c  o m*/
 *
 * @param resultWrapper the json object that wraps the result json. The result is wrapped to
 *     ensure it passed across by reference and fields are updated appropriately
 * @param to the jPath json array defining the full qualified json path to the destination field
 *     where the value must be set
 * @param value the json value that needs to be set to the destination. This can be an Object,
 *     Array or a Primitive
 * @param aces the pre-processed dependency list in the form of key value pair (json)
 * @param optional the flag that determines if a null value must be set in the destination. If
 *     optional is TRUE, null values are not set in the destination
 * @return the json result wraper object which contains the result in the field called "result"
 */
public JsonObject set(JsonObject resultWrapper, JsonArray to, JsonElement value, JsonObject aces,
        Boolean optional) {

    /**
     * Holding a mutex on result wrapper and not making the method synchronized because, when
     * multiple unrelated threads might be calling mystique for transformation. The resource of
     * contention is only the result wrapper
     */
    synchronized (resultWrapper) {
        if (optional && isNull(value)) {
            // Do Not update result wrapper
            return resultWrapper;
        }
        if (isNotNull(to)) {
            JsonElement result = resultWrapper.get(MystiqueConstants.RESULT);
            JsonElement field = result;
            if (to.size() > 0) {
                JsonElement previousPath = null;
                JsonElement currentPath = null;
                Iterator<JsonElement> iterator = to.iterator();
                if (iterator.hasNext()) {
                    previousPath = getPathField(iterator.next(), aces);
                }

                while (iterator.hasNext()) {
                    currentPath = getPathField(iterator.next(), aces);

                    // get the field
                    field = getRepleteField(field, previousPath, currentPath);
                    result = updateResult(result, field);
                    field = isNumber(previousPath) ? field.getAsJsonArray().get(previousPath.getAsInt())
                            : field.getAsJsonObject().get(previousPath.getAsString());
                    previousPath = currentPath;
                }

                field = setField(field, previousPath, value);
                result = updateResult(result, field);
            } else {
                result = merge(result, value);
            }
            resultWrapper.add(MystiqueConstants.RESULT, result);
        }
        return resultWrapper;
    }
}

From source file:com.balajeetm.mystique.core.LoopySpell.java

License:Open Source License

@Override
public JsonElement cast(MystTurn mystique) {
    JsonElement transform = JsonNull.INSTANCE;
    if (CollectionUtils.isNotEmpty(source)) {
        transform = new JsonArray();
        List<CompletableFuture<JsonElement>> cfs = new ArrayList<>();
        JsonArray jsonArray = source.get(0).getAsJsonArray();
        for (JsonElement jsonElement : jsonArray) {

            CompletableFuture<JsonElement> transformElement = CompletableFuture.supplyAsync(() -> mystique
                    .transform(Lists.newArrayList(jsonElement), dependencies, aces, turn, resultWrapper))
                    .exceptionally(e -> {
                        String msg = String.format(
                                "Error transforming one of the elements in the array for %s - %s", turn,
                                e.getMessage());
                        logger.info(msg, e);
                        return JsonNull.INSTANCE;
                    });/*from   ww  w.  j  a  v a2 s  .com*/
            cfs.add(transformElement);
        }

        for (CompletableFuture<JsonElement> completableFuture : cfs) {
            JsonElement element = null;
            try {
                element = completableFuture.get();
            } catch (InterruptedException | ExecutionException e) {
                String msg = String.format(
                        "Error getting transformed element for one of the elements in the array for %s - %s",
                        turn, e.getMessage());
                logger.info(msg, e);
                element = JsonNull.INSTANCE;
            }
            Boolean optional = jsonLever.asBoolean(turn.get(MystiqueConstants.OPTIONAL), Boolean.FALSE);
            if (jsonLever.isNotNull(element) || !optional) {
                transform.getAsJsonArray().add(element);
            }
        }
    }
    return transform;
}

From source file:com.balajeetm.mystique.core.module.GsonSerialiser.java

License:Open Source License

@Override
public void serialize(JsonElement value, JsonGenerator gen, SerializerProvider provider) throws IOException {
    if (jsonLever.isNull(value)) {
        gen.writeNull();//from   www. j  av  a2s .c  om
    } else if (jsonLever.isObject(value)) {
        gen.writeStartObject();
        JsonObject jsonObject = value.getAsJsonObject();
        for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            gen.writeFieldName(entry.getKey());
            serialize(entry.getValue(), gen, provider);
        }
        gen.writeEndObject();
    } else if (jsonLever.isArray(value)) {
        gen.writeStartArray();
        JsonArray jsonArray = value.getAsJsonArray();
        for (JsonElement jsonElement : jsonArray) {
            serialize(jsonElement, gen, provider);
        }
        gen.writeEndArray();
    } else if (jsonLever.isPrimitive(value)) {
        JsonPrimitive jsonPrimitive = value.getAsJsonPrimitive();
        if (jsonPrimitive.isBoolean()) {
            gen.writeBoolean(jsonPrimitive.getAsBoolean());
        }
        if (jsonPrimitive.isNumber()) {
            Number nnode = jsonPrimitive.getAsNumber();
            if (nnode instanceof LazilyParsedNumber) {
                gen.writeNumber(nnode.toString());
            } else if (nnode instanceof Integer) {
                gen.writeNumber(nnode.intValue());
            } else if (nnode instanceof Short) {
                gen.writeNumber(nnode.shortValue());
            } else if (nnode instanceof BigInteger || nnode instanceof Long) {
                gen.writeNumber(nnode.longValue());
            } else if (nnode instanceof Float) {
                gen.writeNumber(nnode.floatValue());
            } else if (nnode instanceof Double || nnode instanceof BigDecimal) {
                gen.writeNumber(nnode.doubleValue());
            }
        }
        if (jsonPrimitive.isString()) {
            gen.writeString(jsonPrimitive.getAsString());
        }
    }
}

From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java

License:Open Source License

/**
 * Gets the json element in the specified jpath.
 *
 * @param source the source/*from   w  w w  .  ja v  a2 s. c o  m*/
 * @param jpath the fully qualified json path to the field required. eg get({'a': {'b': {'c': [1,
 *     2, 3, 4]}}}, ["a", "b" "c", 1]) is '2'. Array indexes need to be specified as numerals.
 *     Strings are always presumed to be field names.
 * @return the json element returns 'Null' for any invalid path return the source if the input
 *     jpath is '.'
 */
public JsonElement get(JsonElement source, JsonArray jpath) {
    JsonElement result = JsonNull.INSTANCE;
    if (isNotNull(jpath)) {
        result = source;
        for (JsonElement path : jpath) {
            try {
                if (isNumber(path)) {
                    result = result.getAsJsonArray().get(path.getAsInt());
                } else {
                    result = result.getAsJsonObject().get(path.getAsString());
                }
            } catch (Exception e) {
                return JsonNull.INSTANCE;
            }
        }
    }

    return result;
}

From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java

License:Open Source License

/**
 * Sets the json element at the specified jpath.
 *
 * @param source the source//from   ww  w  . jav a2s . c o m
 * @param jpath the fully qualified json path to the field required. eg set({'a': {'b': {'c': [1,
 *     2, 3, 4]}}}, ["a", "b" "c", 1, 5]) is {'a': {'b': {'c': [1, 5, 3, 4]}}}. Array indexes need
 *     to be specified as numerals. Strings are always presumed to be field names.
 * @param value the value
 * @return the json element
 */
public JsonElement set(JsonElement source, JsonArray jpath, JsonElement value) {
    JsonElement result = JsonNull.INSTANCE;
    if (isNotNull(jpath)) {
        result = source;
        JsonElement field = result;
        if (jpath.size() > 0) {
            JsonElement previousPath = null;
            JsonElement currentPath = null;
            Iterator<JsonElement> iterator = jpath.iterator();
            if (iterator.hasNext()) {
                previousPath = iterator.next();
            }

            while (iterator.hasNext()) {
                currentPath = iterator.next();
                // get the field
                field = getRepleteField(field, previousPath, currentPath);
                result = updateResult(result, field);
                field = isNumber(previousPath) ? field.getAsJsonArray().get(previousPath.getAsInt())
                        : field.getAsJsonObject().get(previousPath.getAsString());
                previousPath = currentPath;
            }

            field = setField(field, previousPath, value);
        }
    }
    return result;
}

From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java

License:Open Source License

/**
 * Returns the source json as a json array if possible. Else returns the default json
 *
 * @param source the source json element
 * @param defaultArray the default array
 * @return the source json as a json array
 *///  w w  w  . j  ava 2  s.c  o  m
public JsonArray asJsonArray(JsonElement source, JsonArray defaultArray) {
    return isArray(source) ? source.getAsJsonArray() : defaultArray;
}

From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java

License:Open Source License

/**
 * A recursive merge of two json elements.
 *
 * @param source1 the first json element
 * @param source2 the second json element
 * @param mergeArray the flag to denote if arrays should be merged
 * @return the recursively merged json element
 *//*from   w  w w . j a  va  2s.  c  om*/
public JsonElement merge(JsonElement source1, JsonElement source2, Boolean mergeArray) {
    mergeArray = null == mergeArray ? Boolean.FALSE : mergeArray;
    JsonElement result = JsonNull.INSTANCE;
    source1 = asJsonElement(source1, JsonNull.INSTANCE);
    source2 = asJsonElement(source2, JsonNull.INSTANCE);
    if (source1.getClass().equals(source2.getClass())) {
        if (source1.isJsonObject()) {
            JsonObject obj1 = asJsonObject(source1);
            JsonObject obj2 = asJsonObject(source2);
            result = obj1;
            JsonObject resultObj = result.getAsJsonObject();
            for (Entry<String, JsonElement> entry : obj1.entrySet()) {
                String key = entry.getKey();
                JsonElement value1 = entry.getValue();
                JsonElement value2 = obj2.get(key);
                JsonElement merge = merge(value1, value2, mergeArray);
                resultObj.add(key, merge);
            }
            for (Entry<String, JsonElement> entry : obj2.entrySet()) {
                String key = entry.getKey();
                if (!resultObj.has(key)) {
                    resultObj.add(key, entry.getValue());
                }
            }
        } else if (source1.isJsonArray()) {
            result = new JsonArray();
            JsonArray resultArray = result.getAsJsonArray();
            JsonArray array1 = asJsonArray(source1);
            JsonArray array2 = asJsonArray(source2);
            int index = 0;
            int a1size = array1.size();
            int a2size = array2.size();

            if (!mergeArray) {
                for (; index < a1size && index < a2size; index++) {
                    resultArray.add(merge(array1.get(index), array2.get(index), mergeArray));
                }
            }

            for (; index < a1size; index++) {
                resultArray.add(array1.get(index));
            }

            index = mergeArray ? 0 : index;

            for (; index < a2size; index++) {
                resultArray.add(array2.get(index));
            }

        } else {
            result = source1 != null ? source1 : source2;
        }
    } else {
        result = isNotNull(source1) ? source1 : source2;
    }
    return result;
}

From source file:com.balajeetm.mystique.util.gson.lever.JsonLever.java

License:Open Source License

/**
 * Sets the field.//w w w  .j ava 2  s .c o  m
 *
 * @param field the field
 * @param path the path
 * @param value the value
 * @return the json element
 */
protected JsonElement setField(JsonElement field, JsonElement path, JsonElement value) {
    if (isNumber(path)) {
        JsonArray jArray = asJsonArray(field.getAsJsonArray(), new JsonArray());
        int index = path.getAsInt();
        repleteArray(jArray, index, JsonNull.class);
        jArray.set(index, value);
        field = jArray;
    } else {
        JsonObject jObject = asJsonObject(field, new JsonObject());
        jObject.add(path.getAsString(), value);
        field = jObject;
    }
    return field;
}