Example usage for com.google.gson JsonObject getAsJsonObject

List of usage examples for com.google.gson JsonObject getAsJsonObject

Introduction

In this page you can find the example usage for com.google.gson JsonObject getAsJsonObject.

Prototype

public JsonObject getAsJsonObject(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonObject.

Usage

From source file:com.arangodb.entity.EntityFactory.java

License:Apache License

public static <T> String toJsonString(T obj, boolean includeNullValue) {
    if (obj != null && obj.getClass().equals(BaseDocument.class)) {
        String tmp = includeNullValue ? gsonNull.toJson(obj) : gson.toJson(obj);
        JsonParser jsonParser = new JsonParser();
        JsonElement jsonElement = jsonParser.parse(tmp);
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        JsonObject result = jsonObject.getAsJsonObject("properties");
        JsonElement keyObject = jsonObject.get("_key");
        if (keyObject != null && keyObject.getClass() != JsonNull.class) {
            result.add("_key", jsonObject.get("_key"));
        }//  www  .j  a  va 2s . c  om
        JsonElement handleObject = jsonObject.get("_id");
        if (handleObject != null && handleObject.getClass() != JsonNull.class) {
            result.add("_id", jsonObject.get("_id"));
        }
        // JsonElement revisionValue = jsonObject.get("documentRevision");
        // result.add("_rev", revisionValue);
        return result.toString();
    }
    return includeNullValue ? gsonNull.toJson(obj) : gson.toJson(obj);
}

From source file:com.atlauncher.data.loaders.forge.DownloadsTypeAdapter.java

License:Open Source License

@Override
public Downloads deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    DownloadsItem artifact = null;/*from  www. ja  v a 2 s.  co  m*/

    final JsonObject rootJsonObject = json.getAsJsonObject();

    if (rootJsonObject.has("artifact")) {
        final JsonObject artifactObject = rootJsonObject.getAsJsonObject("artifact");
        artifact = Gsons.DEFAULT_ALT.fromJson(artifactObject, DownloadsItem.class);
    }

    return new Downloads(artifact);
}

From source file:com.atlauncher.data.mojang.DownloadsTypeAdapter.java

License:Open Source License

@Override
public Downloads deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    DownloadsItem artifact = null;/*  w ww. jav  a 2s .  c  o m*/
    Map<String, DownloadsItem> classifiers = new HashMap<String, DownloadsItem>();

    final JsonObject rootJsonObject = json.getAsJsonObject();

    if (rootJsonObject.has("artifact")) {
        final JsonObject artifactObject = rootJsonObject.getAsJsonObject("artifact");
        artifact = Gsons.DEFAULT_ALT.fromJson(artifactObject, DownloadsItem.class);
    }

    if (rootJsonObject.has("classifiers")) {
        final JsonObject classifiersObject = rootJsonObject.getAsJsonObject("classifiers");

        Set<Entry<String, JsonElement>> entrySet = classifiersObject.entrySet();

        for (Map.Entry<String, JsonElement> entry : entrySet) {
            classifiers.put(entry.getKey(),
                    Gsons.DEFAULT_ALT.fromJson(entry.getValue().getAsJsonObject(), DownloadsItem.class));
        }
    }

    return new Downloads(artifact, classifiers);
}

From source file:com.azure.webapi.LoginManager.java

License:Open Source License

/**
 * Creates a User based on a Windows Azure Mobile Service JSON object
 * containing a UserId and Authentication Token
 * //from   w w  w  . j av a2s.c om
 * @param json
 *            JSON object used to create the User
 * @return The created user if it is a valid JSON object. Null otherwise
 * @throws MobileServiceException
 */
private MobileServiceUser createUserFromJSON(JsonObject json) throws MobileServiceException {
    if (json == null) {
        throw new IllegalArgumentException("json can not be null");
    }

    // If the JSON object is valid, create a MobileServiceUser object
    if (json.has(USER_JSON_PROPERTY)) {
        JsonObject jsonUser = json.getAsJsonObject(USER_JSON_PROPERTY);

        if (!jsonUser.has(USERID_JSON_PROPERTY)) {
            throw new JsonParseException(USERID_JSON_PROPERTY + " property expected");
        }
        String userId = jsonUser.get(USERID_JSON_PROPERTY).getAsString();

        MobileServiceUser user = new MobileServiceUser(userId);

        if (!json.has(TOKEN_JSON_PARAMETER)) {
            throw new JsonParseException(TOKEN_JSON_PARAMETER + " property expected");
        }

        user.setAuthenticationToken(json.get(TOKEN_JSON_PARAMETER).getAsString());
        return user;
    } else {
        // If the JSON contains an error property show it, otherwise raise
        // an error with JSON content
        if (json.has("error")) {
            throw new MobileServiceException(json.get("error").getAsString());
        } else {
            throw new JsonParseException(json.toString());
        }
    }
}

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  .  j av  a  2 s  .  c o  m
            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 JsonObject getAccessStatistic(String keyForUser, int howManyHrsBack) throws RiakCSException {
    if (endpointIsS3())
        throw new RiakCSException("Not supported by AWS S3");

    JsonObject result = null;

    try {//from   w  w  w . j ava 2 s.c  om
        iso8601DateFormat.setTimeZone(new SimpleTimeZone(0, "GMT"));

        Date endTime = new Date(System.currentTimeMillis());
        Date startTime = new Date(System.currentTimeMillis() - (howManyHrsBack * 60 * 60 * 1000));

        StringBuilder path = new StringBuilder();
        path.append("/usage");
        path.append("/");
        path.append(keyForUser);
        path.append("/aj");
        path.append("/");
        path.append(iso8601DateFormat.format(startTime));
        path.append("/");
        path.append(iso8601DateFormat.format(endTime));

        CommunicationLayer comLayer = getCommunicationLayer();

        URL url = comLayer.generateCSUrl(path.toString());
        HttpURLConnection connection = comLayer.makeCall(CommunicationLayer.HttpMethod.GET, url, null,
                EMPTY_STRING_MAP);

        InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream(), "UTF-8");
        result = new JsonParser().parse(inputStreamReader).getAsJsonObject();
        result = result.getAsJsonObject("Access");

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

    return result;
}

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

License:Open Source License

public JsonObject getStorageStatistic(String keyForUser, int howManyHrsBack) throws RiakCSException {
    if (endpointIsS3())
        throw new RiakCSException("Not supported by AWS S3");

    JsonObject result = null;

    try {/* www .  j  a  v  a  2 s  . com*/
        iso8601DateFormat.setTimeZone(new SimpleTimeZone(0, "GMT"));

        Date endTime = new Date(System.currentTimeMillis());
        Date startTime = new Date(System.currentTimeMillis() - (howManyHrsBack * 60 * 60 * 1000));

        StringBuilder path = new StringBuilder();
        path.append("/usage");
        path.append("/");
        path.append(keyForUser);
        path.append("/bj");
        path.append("/");
        path.append(iso8601DateFormat.format(startTime));
        path.append("/");
        path.append(iso8601DateFormat.format(endTime));

        CommunicationLayer comLayer = getCommunicationLayer();

        URL url = comLayer.generateCSUrl(path.toString());
        HttpURLConnection connection = comLayer.makeCall(CommunicationLayer.HttpMethod.GET, url, null,
                EMPTY_STRING_MAP);

        InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream(), "UTF-8");
        result = new JsonParser().parse(inputStreamReader).getAsJsonObject();
        result = result.getAsJsonObject("Storage");

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

    return result;
}

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 {//  ww w.  ja  va 2 s  .c om
        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 boolean matches(Map<String, String> properties, JsonObject permutation) {
    String strongName = permutation.get("permutation").getAsString();
    JsonObject permProperties = permutation.getAsJsonObject("properties");
    for (Map.Entry<String, JsonElement> property : permProperties.entrySet()) {
        String expected = property.getValue().getAsString();
        String actual = properties.get(property.getKey());
        if (actual != null && !expected.equals(actual)) {
            logger.finest("Rejecting " + strongName + ", expected property '" + property.getValue() + "' "
                    + "with value '" + expected + "', found '" + actual + "'");
            return false;
        }/*from   w  ww  .j  av  a2  s.  c  o  m*/
    }
    return true;
}

From source file:com.bekwam.resignator.model.ConfigurationJSONAdapter.java

License:Apache License

private List<Profile> deserializeProfiles(JsonArray profiles) {

    List<Profile> ps = new ArrayList<>();

    for (JsonElement e : profiles) {

        JsonObject profileObj = (JsonObject) e;
        String profileName = profileObj.get("profileName").getAsString();

        Boolean rs = Boolean.FALSE;
        if (profileObj.get("replaceSignatures") != null) {
            rs = profileObj.get("replaceSignatures").getAsBoolean();
        }//from w ww .  j  a  v a2s.c o  m

        SigningArgumentsType argsType = SigningArgumentsType.JAR;
        if (profileObj.get("argsType") != null) {
            String at = profileObj.get("argsType").getAsString();
            if (StringUtils.equalsIgnoreCase(at, String.valueOf(SigningArgumentsType.FOLDER))) {
                argsType = SigningArgumentsType.FOLDER;
            }
        }

        Profile p = new Profile(profileName, rs, argsType);

        //
        // SourceFile part
        //
        JsonObject sourceObj = profileObj.getAsJsonObject("sourceFile");
        if (sourceObj != null) {
            JsonElement sfe = sourceObj.get("fileName");
            if (sfe != null) {
                SourceFile sf = new SourceFile(sfe.getAsString());
                p.setSourceFile(Optional.of(sf));
            }
        }

        //
        // TargetFile part
        //
        JsonObject targetObj = profileObj.getAsJsonObject("targetFile");
        if (sourceObj != null) {
            JsonElement tfe = targetObj.get("fileName");
            if (tfe != null) {
                TargetFile tf = new TargetFile(tfe.getAsString());
                p.setTargetFile(Optional.of(tf));
            }
        }

        //
        // JarsignerConfig part
        //
        JsonObject jcObj = profileObj.getAsJsonObject("jarsignerConfig");
        if (jcObj != null) {

            String alias = "";
            String storepass = "";
            String keypass = "";
            String keystore = "";
            Boolean verbose = false;

            JsonElement ae = jcObj.get("alias");
            if (ae != null) {
                alias = ae.getAsString();
            }

            JsonElement spe = jcObj.get("storepass");
            if (spe != null) {
                storepass = spe.getAsString();
            }

            JsonElement kpe = jcObj.get("keypass");
            if (kpe != null) {
                keypass = kpe.getAsString();
            }

            JsonElement kse = jcObj.get("keystore");
            if (kse != null) {
                keystore = kse.getAsString();
            }

            JsonElement ve = jcObj.get("verbose");
            if (ve != null) {
                verbose = ve.getAsBoolean();
            }

            JarsignerConfig jc = new JarsignerConfig(alias, "", "", keystore, verbose);
            jc.setEncryptedKeypass(keypass);
            jc.setEncryptedStorepass(storepass);

            p.setJarsignerConfig(Optional.of(jc));
        }

        ps.add(p);
    }

    return ps;
}