Example usage for com.google.gson JsonObject getAsJsonArray

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

Introduction

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

Prototype

public JsonArray getAsJsonArray(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonArray.

Usage

From source file:com.avapira.bobroreader.hanabira.entity.HanabiraEntity.java

License:Open Source License

private static HanabiraThread createThreadWithPosts(JsonObject threadObject, @Nullable String boardKey) {
    int threadId = threadObject.get("thread_id").getAsInt();
    LocalDateTime modifiedDate = extractLocatDateTime(threadObject.get("last_modified"));

    HanabiraThread thread = Hanabira.getStem().findThreadById(threadId);
    boolean oldThread = thread != null;
    if (oldThread) {
        if (modifiedDate == null || !thread.isUpToDate(modifiedDate)) {
            // update thread meta
            thread.setPostsCount(threadObject.get("posts_count").getAsInt());
            thread.setArchived(threadObject.get("archived").getAsBoolean());
            thread.setFilesCount(threadObject.get("files_count").getAsInt());
            thread.setTitle(threadObject.get("title").getAsString());
            thread.setLastHit(extractLocatDateTime(threadObject.get("last_hit")));
            thread.setModifiedDate(modifiedDate);
        }/* ww  w  . j  av a  2 s.  c  o  m*/
    } else {
        // brand new thread
        int displayId = threadObject.get("display_id").getAsInt();
        boolean archived = threadObject.get("archived").getAsBoolean();
        int postsCount = threadObject.get("posts_count").getAsInt();
        int filesCount = threadObject.get("files_count").getAsInt();
        String title = threadObject.get("title").getAsString();
        int boardId = boardKey != null ? HanabiraBoard.Info.getIdForKey(boardKey)
                : threadObject.get("board_id").getAsInt();
        boolean autosage = threadObject.get("autosage").getAsBoolean();
        LocalDateTime lastHit = extractLocatDateTime(threadObject.get("last_hit"));

        thread = new HanabiraThread(displayId, threadId, modifiedDate, postsCount, filesCount, boardId,
                archived, title, autosage, lastHit);
        Hanabira.getStem().saveThread(thread, boardKey);
    }

    // cache posts
    for (JsonElement postElement : threadObject.getAsJsonArray("posts")) {
        createAndSavePost(postElement.getAsJsonObject(), threadId, boardKey);
    }

    if (!oldThread) {
        // set thread creation date
        HanabiraPost opPost = Hanabira.getStem().findPostByDisplayId(boardKey, thread.getDisplayId());
        if (opPost == null || !opPost.isOp()) {
            throw new InputMismatchException("Op post not received");
        }
        thread.setCreatedDate(opPost.getCreatedDate());
    }
    return thread;
}

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 www .j  ava 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);/*from  ww  w .j a  va 2 s . com*/
    }
}

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 va2 s.  co  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.bekwam.resignator.model.ConfigurationJSONAdapter.java

License:Apache License

@Override
public Configuration deserialize(JsonElement jsonElement, Type type,
        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {

    if (logger.isDebugEnabled()) {
        logger.debug("[DESERIALIZE]");
    }//from  w ww.ja  va 2s  . c  o  m

    JsonObject obj = (JsonObject) jsonElement;

    JsonElement apElement = obj.get("activeProfile");
    String ap = "";
    if (apElement != null) {
        ap = apElement.getAsString();
    }

    JsonElement jdkElem = obj.get("jdkHome");
    String jdkHome = "";
    if (jdkElem != null) {
        jdkHome = jdkElem.getAsString();
    }

    JsonElement hpElem = obj.get("hashedPassword");
    String hp = "";
    if (hpElem != null) {
        hp = hpElem.getAsString();
    }

    JsonElement ludElem = obj.get("lastUpdatedDate");
    String lud = "";
    LocalDateTime lastUpdatedDate = null;
    if (ludElem != null) {
        lud = ludElem.getAsString();
        if (StringUtils.isNotEmpty(lud)) {
            lastUpdatedDate = LocalDateTime.parse(lud, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        }
    }

    JsonArray recentProfiles = obj.getAsJsonArray("recentProfiles");
    JsonArray profiles = obj.getAsJsonArray("profiles");

    if (logger.isDebugEnabled()) {
        logger.debug("[DESERIALIZE] rp={}, ap={}, jdkHome={}, keytool={}, profiles={}",
                recentProfiles.toString(), ap, jdkHome, profiles.toString());
    }

    Configuration conf = new Configuration();
    conf.setActiveProfile(Optional.of(ap));
    conf.setJDKHome(Optional.of(jdkHome));
    conf.getRecentProfiles().addAll(deserializeRecentProfiles(recentProfiles));
    conf.getProfiles().addAll(deserializeProfiles(profiles));
    conf.setHashedPassword(Optional.of(hp));
    conf.setLastUpdatedDateTime(Optional.ofNullable(lastUpdatedDate));
    return conf;
}

From source file:com.bizosys.dataservice.dao.WriteToXls.java

License:Apache License

public static void main(String[] args) throws Exception {

    String json = " { \"values\" : [ { \"name\" : \"ravi\" , \"id\" : \"334\" }, { \"name\" : \"kumar\" , \"id\" : \"335\" } ] }";
    JsonParser parser = new JsonParser();
    JsonObject o = (JsonObject) parser.parse(json);

    JsonArray values = o.getAsJsonArray("values");

    Set<Map.Entry<String, JsonElement>> entrySet = null;

    List<Object[]> records = new ArrayList<Object[]>();
    List<Object> cols = new ArrayList<Object>();

    List<String> labels = new ArrayList<String>();
    boolean isFirst = true;
    for (JsonElement elem : values) {
        JsonObject obj = elem.getAsJsonObject();
        entrySet = obj.entrySet();/*from w  w w  .  ja va 2 s  . c o  m*/
        cols.clear();
        if (isFirst) {
            for (Map.Entry<String, JsonElement> entry : entrySet) {
                labels.add(entry.getKey());
            }
            isFirst = false;
        }

        for (String aLabel : labels) {
            cols.add(obj.get(aLabel).getAsString());
        }
        records.add(cols.toArray());
    }

    OutputStream out = null;
    out = new FileOutputStream(new File("/tmp/test.xlsx"));
    WriteToXls writerXls = new WriteToXls(out, 0, 0);
    writerXls.write(records);
}

From source file:com.brainardphotography.gravatar.contact.PCContactLoader.java

License:Apache License

@Override
public PCContact loadContact(Reader reader) throws IOException {
    JsonElement element = jsonParser.parse(reader);
    JsonObject object = element.getAsJsonObject();
    JsonArray entries = object.getAsJsonArray("entry");

    if (entries.size() > 0)
        return gson.fromJson(entries.get(0), PCContact.class);

    return null;//from  w ww.j  a  v  a  2 s .co m
}

From source file:com.canoo.dolphin.impl.codec.CreatePresentationModelEncoder.java

License:Apache License

@Override
public CreatePresentationModelCommand decode(JsonObject jsonObject) {
    Assert.requireNonNull(jsonObject, "jsonObject");

    try {/*from w w  w  .  j a v a2 s. c o m*/
        final CreatePresentationModelCommand command = new CreatePresentationModelCommand();

        command.setPmId(jsonObject.getAsJsonPrimitive(PM_ID).getAsString());
        command.setPmType(jsonObject.getAsJsonPrimitive(PM_TYPE).getAsString());
        command.setClientSideOnly(false);

        final JsonArray jsonArray = jsonObject.getAsJsonArray(PM_ATTRIBUTES);
        final List<Map<String, Object>> attributes = new ArrayList<>();
        for (final JsonElement jsonElement : jsonArray) {
            final JsonObject attribute = jsonElement.getAsJsonObject();
            final HashMap<String, Object> map = new HashMap<>();
            map.put("propertyName", attribute.getAsJsonPrimitive(ATTRIBUTE_NAME).getAsString());
            map.put("id", attribute.getAsJsonPrimitive(ATTRIBUTE_ID).getAsString());
            final Object value = attribute.has(ATTRIBUTE_VALUE) ? decodeValue(attribute.get(ATTRIBUTE_VALUE))
                    : null;
            map.put("value", value);
            map.put("baseValue", value);
            map.put("qualifier", null);
            attributes.add(map);
        }
        command.setAttributes(attributes);

        return command;
    } catch (IllegalStateException | ClassCastException | NullPointerException ex) {
        throw new JsonParseException("Illegal JSON detected", ex);
    }
}

From source file:com.ccreanga.bitbucket.rest.client.http.responseparsers.PageParser.java

License:Apache License

@Override
public Page<T> apply(JsonElement jsonElement) {
    JsonObject json = jsonElement.getAsJsonObject();
    List<T> values = Parsers.listParser(valueParser).apply(json.getAsJsonArray("values"));

    return new Page<>(json.get("size").getAsInt(), json.get("limit").getAsInt(),
            optionalJsonBoolean(json, "isLastPage"), json.get("start").getAsInt(),
            (int) optionalJsonLong(json, "nextPageStart"), values);
}

From source file:com.ccreanga.bitbucket.rest.client.http.responseparsers.PathParser.java

License:Apache License

@Override
public Path apply(JsonElement json) {
    if (json == null || !json.isJsonObject()) {
        return null;
    }/*w  w  w .j  ava 2 s  . c om*/
    JsonObject jsonObject = json.getAsJsonObject();
    JsonArray array = jsonObject.getAsJsonArray("components");
    String[] components = new String[array.size()];
    Iterator<JsonElement> it = array.iterator();
    int i = 0;
    while (it.hasNext()) {
        components[i++] = it.next().getAsString();
    }

    return new Path(components);
}