Example usage for com.google.gson JsonArray size

List of usage examples for com.google.gson JsonArray size

Introduction

In this page you can find the example usage for com.google.gson JsonArray size.

Prototype

public int size() 

Source Link

Document

Returns the number of elements in the array.

Usage

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

License:Open Source License

/**
 * Subset.//  w ww . java2s . c o m
 *
 * @param source the source
 * @param deps the deps
 * @param aces the aces
 * @param jPathArray the j path array
 * @return the json element
 */
private JsonElement subset(JsonElement source, JsonObject deps, JsonObject aces, JsonArray jPathArray) {
    JsonElement finalValue = null;
    if (jPathArray.size() == 0) {
        finalValue = getField(source, jPathArray, deps, aces);
    } else {
        JsonElement first = getFirst(jPathArray);
        if (isArray(first)) {
            finalValue = new JsonObject();
            for (JsonElement jsonElement : jPathArray) {
                JsonArray pathArray = asJsonArray(jsonElement);
                JsonElement subset = getField(source, pathArray, deps, aces);
                set(finalValue.getAsJsonObject(), pathArray, subset, aces);
            }
            finalValue = finalValue.getAsJsonObject().get(MystiqueConstants.RESULT);
        } else {
            finalValue = getField(source, jPathArray, deps, aces);
        }
    }
    return finalValue;
}

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

License:Open Source License

/**
 * Gets the field./*from w w  w . j  a v  a  2  s . c om*/
 *
 * @param source the source
 * @param jPath the j path
 * @param deps the deps
 * @param aces the aces
 * @return the field
 */
public JsonElement getField(JsonElement source, JsonArray jPath, JsonObject deps, JsonObject aces) {
    JsonElement field = null;
    try {
        field = source;
        if (null != jPath) {
            for (int count = 0; count < jPath.size(); count++) {
                JsonElement path = jPath.get(count);
                if (isNumber(path)) {
                    field = get(field, path);
                } else {
                    String key = asString(path);
                    if (count == 0 && MystiqueConstants.AT_DEPS.equals(key)) {
                        field = deps;
                        continue;
                    }
                    String ace = getAce(key);
                    if (null != ace) {
                        field = aces.get(ace);
                        continue;
                    }
                    path = getPathField(path, aces);
                    field = get(field, path);
                }
            }
        }
    }
    /** Would throw an exception for any invalid path, which is logged and ignored */
    catch (RuntimeException e) {
        log.warn(String.format("Error getting field from source for %s - %s. Skipping the same", jPath,
                e.getMessage()), e);
        field = null;
    }
    return field;
}

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

License:Open Source License

/**
 * Sets the field of a json source./*from  w  w  w .  j  a v  a  2 s  .co 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.util.gson.lever.JsonLever.java

License:Open Source License

/**
 * Sets the json element at the specified jpath.
 *
 * @param source the source//from  w w w .  j  a v a 2  s. c  om
 * @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

/**
 * Gets the subset json from a source json.
 *
 * @param source the json source which can be Object, Array or a Primitive
 * @param jPathArray the array of jPaths defining the full qualified json paths to the required
 *     fields/*from  w w w .  j  a va 2  s. co  m*/
 * @return the json subset
 */
public JsonElement subset(JsonElement source, JsonArray jPathArray) {
    JsonElement finalValue = JsonNull.INSTANCE;
    if (jPathArray.size() == 0) {
        finalValue = source;
    } else {
        finalValue = new JsonObject();
        for (JsonElement jsonElement : jPathArray) {
            JsonElement subset = JsonNull.INSTANCE;
            if (isArray(jsonElement)) {
                JsonArray pathArray = asJsonArray(jsonElement);
                subset = get(source, pathArray);
                finalValue = set(finalValue, pathArray, subset);
            } else if (isString(jsonElement)) {
                String jpath = asString(jsonElement);
                subset = get(source, jpath);
                finalValue = set(finalValue, jpath, subset);
            } else {
                finalValue = JsonNull.INSTANCE;
                break;
            }
        }
    }
    return finalValue;
}

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 ww  w.j  a  v a  2  s .c o m
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.basho.riakcs.client.impl.RiakCSClientImpl.java

License:Open Source License

private void addAdditionalACLImpl(String bucketName, String objectKey, JsonObject acl) throws Exception {
    StringBuilder aclText = new StringBuilder();

    aclText.append("<AccessControlPolicy>");
    aclText.append("<Owner><ID>").append(acl.getAsJsonObject("owner").get("id").getAsString()).append("</ID>");
    aclText.append("<DisplayName>").append(acl.getAsJsonObject("owner").get("displayName").getAsString())
            .append("</DisplayName></Owner>");
    aclText.append("<AccessControlList>");

    JsonArray grantsList = acl.getAsJsonArray("grantsList");
    for (int pt = 0; pt < grantsList.size(); pt++) {
        JsonObject grant = grantsList.get(pt).getAsJsonObject();

        aclText.append("<Grant><Permission>").append(grant.getAsJsonObject("permission").getAsString())
                .append("</Permission>");
        aclText.append("<Grantee");
        aclText.append(" ").append("xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'");

        if (grant.getAsJsonObject("grantee").has("id")) {
            aclText.append(" xsi:type='CanonicalUser'>");
            aclText.append("<ID>").append(grant.getAsJsonObject("grantee").get("id").getAsString())
                    .append("</ID>");
        } else {//from   ww  w .jav  a  2  s. c  om
            aclText.append(" xsi:type='AmazonCustomerByEmail'>");
            aclText.append("<EmailAddress>")
                    .append(grant.getAsJsonObject("grantee").get("emailAddress").getAsString())
                    .append("</EmailAddress>");
        }

        aclText.append("</Grantee>");
        aclText.append("</Grant>");
    }
    aclText.append("</AccessControlList>");
    aclText.append("</AccessControlPolicy>");

    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("acl", null);

    InputStream dataInputStream = new ByteArrayInputStream(aclText.toString().getBytes("UTF-8"));

    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/xml");

    CommunicationLayer comLayer = getCommunicationLayer();

    URL url = comLayer.generateCSUrl(bucketName, objectKey, parameters);
    comLayer.makeCall(CommunicationLayer.HttpMethod.PUT, url, dataInputStream, headers);
}

From source file:com.basho.riakcs.client.impl.RiakCSClientImpl.java

License:Open Source License

public void removeContentOfBucket(String bucketName) throws RiakCSException {

    JsonObject response = listObjects(bucketName, false);
    JsonArray resultList = response.getAsJsonArray("objectList");

    //         if (debugModeEnabled) System.out.println("Number of Objects to delete: "+ resultList.length() + "\n");
    System.out.println("Number of Objects to delete: " + resultList.size() + "\n");

    for (int pt = 0; pt < resultList.size(); pt++) {
        String key = resultList.get(pt).getAsJsonObject().get("key").getAsString();
        deleteObject(bucketName, key);/*ww w  .j a va2 s. c  o m*/
    }
}

From source file:com.basho.riakcs.client.impl.RiakCSClientImpl.java

License:Open Source License

public static void copyBucketBetweenSystems(RiakCSClient fromSystem, String fromBucket, RiakCSClient toSystem,
        String toBucket) throws RiakCSException {
    try {//from   w ww.  ja v  a 2s .  c o  m
        JsonObject response = fromSystem.listObjectNames(fromBucket);
        JsonArray resultList = response.getAsJsonArray("objectList");

        System.out.println("Number of Objects to transfer: " + resultList.size() + "\n");

        for (int pt = 0; pt < resultList.size(); pt++) {
            String key = resultList.get(pt).getAsJsonObject().get("key").getAsString();
            File tempFile = File.createTempFile("cscopy-", ".bin");

            //Retrieve Object
            FileOutputStream outputStream = new FileOutputStream(tempFile);
            JsonObject objectData = fromSystem.getObject(fromBucket, key, outputStream);
            outputStream.close();

            //Upload Object
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", objectData.get("contenttype").getAsString());

            Map<String, String> metadata = null;
            if (objectData.has("metadata") && !objectData.getAsJsonObject("metadata").entrySet().isEmpty()) {
                metadata = new HashMap<String, String>();

                Set<Map.Entry<String, JsonElement>> metadataRaw = objectData.getAsJsonObject("metadata")
                        .entrySet();

                for (Map.Entry<String, JsonElement> entry : metadataRaw) {
                    metadata.put(entry.getKey(), entry.getValue().getAsString());
                }
            }

            FileInputStream inputStream = new FileInputStream(tempFile);
            toSystem.createObject(toBucket, key, inputStream, headers, metadata);
            inputStream.close();

            tempFile.delete();
        }

    } catch (Exception e) {
        throw new RiakCSException(e);
    }
}

From source file:com.bedatadriven.rebar.appcache.server.DefaultSelectionServlet.java

License:Apache License

private String computePermutation(HttpServletRequest req, JsonArray permutationMap) throws ServletException {

    Map<String, String> properties = computeProperties(req);
    Set<String> matches = new HashSet<>();

    for (int i = 0; i != permutationMap.size(); ++i) {
        JsonObject permutation = (JsonObject) permutationMap.get(i);
        if (matches(properties, permutation)) {
            matches.add(permutation.get("permutation").getAsString());
        }/* www .j  a v a 2 s. co m*/
    }

    if (matches.size() == 1) {
        return matches.iterator().next();
    } else {
        return null;
    }
}