Example usage for com.google.gson JsonElement getAsString

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

Introduction

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

Prototype

public String getAsString() 

Source Link

Document

convenience method to get this element as a string value.

Usage

From source file:com.comapi.internal.network.model.messaging.ConversationEventsResponse.java

License:Open Source License

/**
 * Parse event and add to appropriate list.
 *
 * @param event  Json object to parse.//from w  w w .j a v a  2s  . com
 * @param parser Parser interface.
 * @param i      Number of event in the json array.
 */
private void parseEvent(JsonObject event, Parser parser, int i) {

    JsonElement nameJE = event.get(Event.KEY_NAME);

    if (nameJE != null) {

        String name = nameJE.getAsString();

        if (MessageSentEvent.TYPE.equals(name)) {
            MessageSentEvent parsed = parser.parse(event, MessageSentEvent.class);
            messageSent.add(parsed);
            map.put(i, parsed);
        } else if (MessageDeliveredEvent.TYPE.equals(name)) {
            MessageDeliveredEvent parsed = parser.parse(event, MessageDeliveredEvent.class);
            messageDelivered.add(parsed);
            map.put(i, parsed);
        } else if (MessageReadEvent.TYPE.equals(name)) {
            MessageReadEvent parsed = parser.parse(event, MessageReadEvent.class);
            messageRead.add(parsed);
            map.put(i, parsed);
        }
    }
}

From source file:com.comapi.internal.network.model.messaging.EventsQueryResponse.java

License:Open Source License

private void parseEvent(JsonObject event, Parser parser) {

    JsonElement nameJE = event.get(Event.KEY_NAME);

    if (nameJE != null) {

        String name = nameJE.getAsString();

        if (MessageSentEvent.TYPE.equals(name)) {
            messageSent.add(parser.parse(event, MessageSentEvent.class));
        } else if (MessageDeliveredEvent.TYPE.equals(name)) {
            messageDelivered.add(parser.parse(event, MessageDeliveredEvent.class));
        } else if (MessageReadEvent.TYPE.equals(name)) {
            messageRead.add(parser.parse(event, MessageReadEvent.class));
        } else if (ConversationUpdateEvent.TYPE.equals(name)) {
            conversationUpdate.add(parser.parse(event, ConversationUpdateEvent.class));
        } else if (ConversationDeleteEvent.TYPE.equals(name)) {
            conversationDelete.add(parser.parse(event, ConversationDeleteEvent.class));
        } else if (ConversationUndeleteEvent.TYPE.equals(name)) {
            conversationUnDelete.add(parser.parse(event, ConversationUndeleteEvent.class));
        } else if (ParticipantAddedEvent.TYPE.equals(name)) {
            participantAdded.add(parser.parse(event, ParticipantAddedEvent.class));
        } else if (ParticipantUpdatedEvent.TYPE.equals(name)) {
            participantUpdate.add(parser.parse(event, ParticipantUpdatedEvent.class));
        } else if (ParticipantRemovedEvent.TYPE.equals(name)) {
            participantRemoved.add(parser.parse(event, ParticipantRemovedEvent.class));
        }//from  w w  w  .ja va2s.  com
    }
}

From source file:com.comapi.internal.network.sockets.SocketEventDispatcher.java

License:Open Source License

@Override
public void onMessage(String text) {

    if (listener != null) {

        JsonObject event = parser.parse(text, JsonObject.class);

        if (event != null) {

            JsonElement nameElement = event.get(Event.KEY_NAME);

            if (nameElement != null) {

                String name = nameElement.getAsString();

                if (MessageSentEvent.TYPE.equals(name)) {
                    onMessageSent(parser.parse(event, MessageSentEvent.class));
                } else if (MessageDeliveredEvent.TYPE.equals(name)) {
                    onMessageDelivered(parser.parse(event, MessageDeliveredEvent.class));
                } else if (MessageReadEvent.TYPE.equals(name)) {
                    onMessageRead(parser.parse(event, MessageReadEvent.class));
                } else if (ParticipantAddedEvent.TYPE.equals(name)) {
                    onParticipantAdded(parser.parse(event, ParticipantAddedEvent.class));
                } else if (ParticipantUpdatedEvent.TYPE.equals(name)) {
                    onParticipantUpdated(parser.parse(event, ParticipantUpdatedEvent.class));
                } else if (ParticipantRemovedEvent.TYPE.equals(name)) {
                    onParticipantRemoved(parser.parse(event, ParticipantRemovedEvent.class));
                } else if (ConversationUpdateEvent.TYPE.equals(name)) {
                    onConversationUpdated(parser.parse(event, ConversationUpdateEvent.class));
                } else if (ConversationDeleteEvent.TYPE.equals(name)) {
                    onConversationDeleted(parser.parse(event, ConversationDeleteEvent.class));
                } else if (ConversationUndeleteEvent.TYPE.equals(name)) {
                    onConversationUndeleted(parser.parse(event, ConversationUndeleteEvent.class));
                } else if (SocketStartEvent.TYPE.equals(name)) {
                    onSocketStarted(parser.parse(event, SocketStartEvent.class));
                } else if (ProfileUpdateEvent.TYPE.equals(name)) {
                    onProfileUpdate(parser.parse(event, ProfileUpdateEvent.class));
                } else if (ParticipantTypingEvent.TYPE.equals(name)) {
                    onParticipantIsTyping(parser.parse(event, ParticipantTypingEvent.class));
                } else if (ParticipantTypingOffEvent.TYPE.equals(name)) {
                    onParticipantTypingOff(parser.parse(event, ParticipantTypingOffEvent.class));
                }/*from  www . j a  v  a  2 s  .  com*/
            }
        }
    }
}

From source file:com.confighub.api.repository.user.audit.DecryptAuditFile.java

License:Open Source License

@POST
@Path("/{account}/{repository}")
@Produces("application/json")
public Response get(@PathParam("account") String account, @PathParam("repository") String repositoryName,
        @FormParam("id") long id, @FormParam("revId") long revId, @FormParam("password") String password,
        @FormParam("oldPass") String oldPass, @FormParam("oldSpName") String oldSpName,
        @FormParam("ts") Long ts, @HeaderParam("Authorization") String token) {
    JsonObject json = new JsonObject();
    Store store = new Store();
    Gson gson = new Gson();

    try {/*from  w  w  w . j ava2  s.c  o  m*/

        int status = validate(account, repositoryName, token, store);
        if (0 != status)
            return Response.status(status).build();

        RepoFile file = store.getAuditConfigFile(user, repository, id, revId);
        if (null == file)
            throw new ConfigException(Error.Code.NOT_FOUND);

        SecurityProfile sp = file.getSecurityProfile();
        if (null != sp && !sp.isSecretValid(password))
            throw new ConfigException(Error.Code.INVALID_PASSWORD);

        if (file.isEncrypted())
            file.decryptFile(password);

        String dj = file.getDiffJson();
        if (Utils.isBlank(dj)) {
            json.addProperty("old", "");
        } else {
            JsonObject diffJson = new Gson().fromJson(dj, JsonObject.class);
            JsonElement oldContentEl = diffJson.get("content");

            if (null == oldContentEl) {
                json.addProperty("old", "");
            } else {
                if (diffJson.get("encrypted").getAsBoolean()) {
                    Date dateObj = DateTimeUtils.dateFromTsOrTag(null, ts, repository.getCreateDate());
                    SecurityProfile oldSp = store.getSecurityProfile(user, repository, dateObj, oldSpName);

                    String oldDecrypted = Encryption.decrypt(oldSp.getCipher(),
                            diffJson.get("content").getAsString().trim(),
                            Utils.isBlank(oldPass) ? password : oldPass);

                    json.addProperty("old", oldDecrypted);
                } else {
                    json.addProperty("old", oldContentEl.getAsString());
                }
            }
        }

        json.addProperty("content", file.getContent());
        json.addProperty("success", true);
        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } catch (ConfigException e) {
        e.printStackTrace();
        json.addProperty("success", false);
        json.addProperty("message", e.getMessage());

        return Response.ok(gson.toJson(json), MediaType.APPLICATION_JSON).build();
    } finally {
        store.close();
    }
}

From source file:com.contentful.java.cda.ResourceTypeAdapter.java

License:Apache License

private String getFieldAsString(JsonObject jsonObject, String name) {
    JsonElement value = jsonObject.get(name);
    if (value != null) {
        return value.getAsString();
    }//from   ww w  . j  av  a  2 s.  c om
    return null;
}

From source file:com.continusec.client.LogTreeHead.java

License:Apache License

/**
 * Create object from a Gson JsonObject.
 * @param o the Gson object./*  www  .j a  v  a 2s . c  o  m*/
 * @return the log tree hash.
 */
protected static LogTreeHead fromJsonObject(JsonObject o) {
    JsonElement e2 = o.get("tree_hash");
    if (e2.isJsonNull()) {
        return new LogTreeHead(o.get("tree_size").getAsInt(), null);
    } else {
        return new LogTreeHead(o.get("tree_size").getAsInt(), Base64.decodeBase64(e2.getAsString()));
    }
}

From source file:com.continuuity.weave.internal.json.JsonUtils.java

License:Apache License

/**
 * Returns a String representation of the given property.
 *//*from www  .j  av  a  2  s  . co m*/
public static String getAsString(JsonObject json, String property) {
    JsonElement jsonElement = json.get(property);
    if (jsonElement.isJsonNull()) {
        return null;
    }
    if (jsonElement.isJsonPrimitive()) {
        return jsonElement.getAsString();
    }
    return jsonElement.toString();
}

From source file:com.continuuity.weave.internal.json.LocalFileCodec.java

License:Open Source License

@Override
public LocalFile deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObj = json.getAsJsonObject();

    String name = jsonObj.get("name").getAsString();
    URI uri = URI.create(jsonObj.get("uri").getAsString());
    long lastModified = jsonObj.get("lastModified").getAsLong();
    long size = jsonObj.get("size").getAsLong();
    boolean archive = jsonObj.get("archive").getAsBoolean();
    JsonElement pattern = jsonObj.get("pattern");

    return new DefaultLocalFile(name, uri, lastModified, size, archive,
            (pattern == null || pattern.isJsonNull()) ? null : pattern.getAsString());
}

From source file:com.contrastsecurity.ide.eclipse.core.extended.ExtendedContrastSDK.java

License:Open Source License

public StoryResource getStory(String orgUuid, String traceId) throws IOException, UnauthorizedException {
    InputStream is = null;/*  www  . j a va2  s  .c  om*/
    InputStreamReader reader = null;
    try {
        String traceUrl = getTraceUrl(orgUuid, traceId);
        is = makeRequest(HttpMethod.GET, traceUrl);
        reader = new InputStreamReader(is);

        String inputString = IOUtils.toString(is, "UTF-8");
        StoryResource story = this.gson.fromJson(inputString, StoryResource.class);
        JsonObject object = (JsonObject) new JsonParser().parse(inputString);
        JsonObject storyObject = (JsonObject) object.get("story");
        if (storyObject != null) {
            JsonArray chaptersArray = (JsonArray) storyObject.get("chapters");
            List<Chapter> chapters = story.getStory().getChapters();
            if (chapters == null) {
                chapters = new ArrayList<>();
            } else {
                chapters.clear();
            }
            for (int i = 0; i < chaptersArray.size(); i++) {
                JsonObject member = (JsonObject) chaptersArray.get(i);
                Chapter chapter = gson.fromJson(member, Chapter.class);
                chapters.add(chapter);
                JsonObject properties = (JsonObject) member.get("properties");
                if (properties != null) {
                    Set<Entry<String, JsonElement>> entries = properties.entrySet();
                    Iterator<Entry<String, JsonElement>> iter = entries.iterator();
                    List<PropertyResource> propertyResources = new ArrayList<>();
                    chapter.setPropertyResources(propertyResources);
                    while (iter.hasNext()) {
                        Entry<String, JsonElement> prop = iter.next();
                        // String key = prop.getKey();
                        JsonElement entryValue = prop.getValue();
                        if (entryValue != null && entryValue.isJsonObject()) {
                            JsonObject obj = (JsonObject) entryValue;
                            JsonElement name = obj.get("name");
                            JsonElement value = obj.get("value");
                            if (name != null && value != null) {
                                PropertyResource propertyResource = new PropertyResource();
                                propertyResource.setName(name.getAsString());
                                propertyResource.setValue(value.getAsString());
                                propertyResources.add(propertyResource);
                            }
                        }
                    }
                }

            }
        }
        return story;
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(reader);
    }
}

From source file:com.couchbase.cbadmin.assets.Node.java

License:Open Source License

public Node(JsonObject def) throws RestApiException {
    JsonElement eTmp;
    String sTmp;/*w  ww .java2s  .co  m*/
    eTmp = def.get("hostname");
    if (eTmp == null) {
        throw new RestApiException("Expected 'hostname'", def);
    }
    sTmp = eTmp.getAsString();

    try {
        restUrl = new URL("http://" + sTmp + "/");
    } catch (MalformedURLException ex) {
        throw new RuntimeException(ex);
    }

    eTmp = def.get("couchApiBase");
    if (eTmp != null) {
        try {
            sTmp = eTmp.getAsString();
            couchUrl = new URL(sTmp);
        } catch (MalformedURLException ex) {
            throw new RuntimeException(ex);
        }
    }

    eTmp = def.get("version");
    if (eTmp == null) {
        throw new RestApiException("Expected 'version' in nodes JSON", def);
    }
    versionString = eTmp.getAsString();

    eTmp = def.get("otpNode");
    if (eTmp == null) {
        throw new RestApiException("Expected 'otpNode'", def);
    }
    NSOtpNode = eTmp.getAsString();

    eTmp = def.get("clusterCompatibility");
    if (eTmp != null) {
        clusterCompatVersion = eTmp.getAsInt();
    }

    eTmp = def.get("clusterMembership");
    if (eTmp != null) {
        sTmp = eTmp.getAsString();

        if (sTmp.equals("active")) {
            membership = Membership.ACTIVE;
        } else if (sTmp.equals("inactiveAdded")) {
            membership = Membership.INACTIVE_ADDED;

        } else if (sTmp.equals("inactiveFailed")) {
            membership = Membership.INACTIVE_FAILED;
        }
    }

    eTmp = def.get("status");
    if (eTmp != null) {
        sTmp = eTmp.getAsString();
        if (sTmp.equals("healthy")) {
            status = Status.HEALTHY;
        } else if (sTmp.equals("unhealthy")) {
            status = Status.UNHEALTHY;
        } else if (sTmp.equals("warmup")) {
            status = Status.WARMUP;
        }
    }
}