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:fi.vtt.nubomedia.kurento.Ar3DHandler.java

License:Open Source License

private void pose(WebSocketSession session, JsonObject jsonMessage) {
    try {/*from   ww w .  j a  va 2 s  .  c  o m*/
        System.err.println("json POSE from browser");

        String json = jsonMessage.getAsJsonPrimitive("pose").getAsString();
        System.err.println("json:\n" + json);
        JsonObject jsonObjects = gson.fromJson(json, JsonObject.class);

        JsonArray jsonArray = jsonObjects.getAsJsonArray("pose");
        Iterator<JsonElement> itr = jsonArray.iterator();
        while (itr.hasNext()) {
            JsonElement jsonElm = itr.next();
            if (jsonElm.isJsonNull()) {
                System.err.println("Really Skip null");
                continue;
            }
            System.err.println("Got: " + jsonElm);

            JsonObject jsonObject = jsonElm.getAsJsonObject();
            int id = jsonObject.get("id").getAsInt();
            int type = jsonObject.get("type").getAsInt();
            //String id = jsonObject.get("id").getAsString();
            //String type = jsonObject.get("type").getAsString();
            float value = jsonObject.get("value").getAsFloat();
            System.err.println("" + id + "#" + type + "#" + value);
            if (arFilter != null) {
                arFilter.setPose(id, type, value);
            } else {
                System.err.println("Start the filter first");
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
        sendError(session, t.getMessage());
    }
}

From source file:filesync.io.json.PreferencesSerializer.java

License:Open Source License

@Override
public Preferences deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject object = (JsonObject) json;
    File indexesLocation = new File(object.getAsJsonPrimitive("indexesLocation").getAsString());

    IndexList indexes = new IndexList();
    JsonArray indexesArray = object.getAsJsonArray("indexes");
    for (JsonElement index : indexesArray) {
        File indexLocation = new File(indexesLocation, index.getAsString() + ".json");
        try (FileReader reader = new FileReader(indexLocation)) {
            indexes.add(new IndexBuilder().fromJson(reader, SyncIndex.class));
        } catch (IOException ex) {
            log.log(Level.SEVERE, ex.getMessage(), ex);
        }/*from  w  ww .  ja  v  a  2 s.  c om*/
    }

    boolean prereleases = object.getAsJsonPrimitive("prereleases").getAsBoolean();
    return new Preferences(indexesLocation, indexes, prereleases);
}

From source file:filesync.io.json.SyncDirectorySerializer.java

License:Open Source License

@Override
public SyncDirectory deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject object = (JsonObject) json;
    String name = object.getAsJsonPrimitive("name").getAsString();
    long size = object.getAsJsonPrimitive("size").getAsLong();
    long lastModified = object.getAsJsonPrimitive("lastModified").getAsLong();
    boolean added = object.getAsJsonPrimitive("added").getAsBoolean();

    SyncDirectory dir = new SyncDirectory(name, size, lastModified, added);
    JsonArray array = object.getAsJsonArray("files");
    for (JsonElement file : array) {
        dir.add(new IndexBuilder().fromJson(file, SyncFile.class));
    }/* w  ww  .j a v a  2  s.  com*/

    return dir;
}

From source file:filesync.io.json.SyncFileSerializer.java

License:Open Source License

@Override
public SyncFile deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject object = (JsonObject) json;
    String name = object.getAsJsonPrimitive("name").getAsString();
    long size = object.getAsJsonPrimitive("size").getAsLong();
    long lastModified = object.getAsJsonPrimitive("lastModified").getAsLong();
    boolean added = object.getAsJsonPrimitive("added").getAsBoolean();

    if (object.has("files")) {
        SyncDirectory dir = new SyncDirectory(name, size, lastModified, added);
        JsonArray array = object.getAsJsonArray("files");
        for (JsonElement file : array) {
            dir.add(new IndexBuilder().fromJson(file, SyncFile.class));
        }/*  w  w  w. ja v  a 2  s  .  c  om*/
        return dir;
    } else {
        return new SyncFile(name, size, lastModified, added);
    }
}

From source file:filesync.io.json.SyncIndexSerializer.java

License:Open Source License

@Override
public SyncIndex deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject object = (JsonObject) json;
    String name = object.getAsJsonPrimitive("name").getAsString();

    JsonArray directoriesArray = object.getAsJsonArray("directories");
    List<File> directories = new ArrayList<>();
    for (JsonElement path : directoriesArray) {
        directories.add(new File(path.getAsString()));
    }/*from  w  w w.j  a v a  2  s.  c  o  m*/

    SyncIndex dir = new SyncIndex(name, directories);
    dir.setSize(object.getAsJsonPrimitive("size").getAsLong());
    dir.setLastModified(object.getAsJsonPrimitive("lastModified").getAsLong());
    dir.setSchedule(new Gson().fromJson(object.get("schedule"), SyncSchedule.class));

    JsonArray filesArray = object.getAsJsonArray("files");
    for (JsonElement file : filesArray) {
        dir.add(new IndexBuilder().fromJson(file, SyncFile.class));
    }

    return dir;
}

From source file:fr.ribesg.blob.command.minecraft.MCNameCommand.java

License:GNU General Public License

@Override
public boolean exec(final Server server, final Channel channel, final Source user, final String primaryArgument,
        final String[] args) {
    final Receiver receiver = channel == null ? user : channel;

    if (args.length != 1) {
        return false;
    }// www .j av  a 2 s.  c  o m

    final String userName = args[0];
    String escapedUserName = IrcUtil.preventPing(userName);

    if (!MC_USER_REGEX.matcher(userName).matches()) {
        receiver.sendMessage(Codes.RED + '"' + userName + "\" is not a valid Minecraft username");
        return true;
    }

    String realName;
    String uuid = "???";
    try {
        final String resultString = WebUtil.post("https://api.mojang.com/profiles/page/1", "application/json",
                String.format("{\"name\":\"%s\",\"agent\":\"minecraft\"}", userName));
        final JsonObject result = new JsonParser().parse(resultString).getAsJsonObject();
        final JsonArray profiles = result.getAsJsonArray("profiles");
        if (profiles.size() < 1) {
            receiver.sendMessage("The username " + Codes.BOLD + escapedUserName + Codes.RESET + " is "
                    + Codes.BOLD + Codes.LIGHT_GREEN + "available");
            return true;
        } else if (profiles.size() > 1) {
            receiver.sendMessage(
                    Codes.RED + "Name '" + escapedUserName + "' matches multiple account, not supported yet");
            Log.error("Name '" + userName + "' matches multiple account, not supported yet");
            return true;
        } else {
            final JsonObject profile = profiles.get(0).getAsJsonObject();
            realName = profile.getAsJsonPrimitive("name").getAsString();
            escapedUserName = IrcUtil.preventPing(realName);
            uuid = profile.getAsJsonPrimitive("id").getAsString();
            if (uuid.length() != 32) {
                receiver.sendMessage(Codes.RED + "Incorrect UUID");
                Log.error("Incorrect UUID: " + uuid);
            } else {
                uuid = uuid.substring(0, 8) + '-' + uuid.substring(8, 12) + '-' + uuid.substring(12, 16) + '-'
                        + uuid.substring(16, 20) + '-' + uuid.substring(20, 32);
            }
        }
    } catch (final Exception e) {
        receiver.sendMessage(Codes.RED + "Failed to get realName");
        Log.error("Failed to get realName", e);
    }

    final boolean hasPaid;
    try {
        final String result = WebUtil.get("https://minecraft.net/haspaid.jsp?user=" + userName).trim();
        switch (result) {
        case "true":
            hasPaid = true;
            break;
        case "false":
            hasPaid = false;
            break;
        default:
            throw new Exception("Unknown result: " + result);
        }
    } catch (final Exception e) {
        receiver.sendMessage(Codes.RED + "Failed to get hasPaid state");
        Log.error("Failed to get hasPaid state", e);
        return true;
    }

    if (hasPaid) {
        receiver.sendMessage("The username " + Codes.BOLD + escapedUserName + Codes.RESET + " (" + Codes.BOLD
                + uuid + Codes.RESET + ") is " + Codes.BOLD + Codes.RED + "taken" + Codes.RESET + " and "
                + Codes.BOLD + Codes.RED + "premium");
    } else {
        receiver.sendMessage("The username " + Codes.BOLD + escapedUserName + Codes.RESET + " is " + Codes.BOLD
                + Codes.RED + "taken" + Codes.RESET + " but " + Codes.BOLD + Codes.YELLOW + "not premium");
    }
    return true;
}

From source file:fr.zcraft.MultipleInventories.snaphots.PlayerSnapshot.java

License:Open Source License

/**
 * Constructs a snapshot from a JSON export (including {@link
 * ItemStackSnapshot item snapshots} in the inventories).
 *
 * @param json The JSON export./*from w  w  w . j a v a2  s  .  com*/
 *
 * @return The snapshot.
 */
public static PlayerSnapshot fromJSON(final JsonObject json) {
    final JsonArray jsonArmor = json.getAsJsonArray("armor");
    final ItemStackSnapshot[] armor = new ItemStackSnapshot[jsonArmor.size()];

    for (int i = 0; i < jsonArmor.size(); i++) {
        final JsonElement armorItem = jsonArmor.get(i);
        armor[i] = armorItem.isJsonObject() ? ItemStackSnapshot.fromJSON(armorItem.getAsJsonObject()) : null;
    }

    final JsonArray jsonEffects = json.get("effects").isJsonArray() ? json.getAsJsonArray("effects")
            : new JsonArray();
    final List<PotionEffect> effects = Streams.stream(jsonEffects)
            .filter(jsonEffect -> jsonEffect != null && jsonEffect.isJsonObject())
            .map(jsonEffect -> potionEffectFromJSON(jsonEffect.getAsJsonObject())).collect(Collectors.toList());

    return new PlayerSnapshot(isNull(json, "level") ? 0 : json.getAsJsonPrimitive("level").getAsInt(),
            isNull(json, "exp") ? 0.0f : json.getAsJsonPrimitive("exp").getAsFloat(),
            isNull(json, "expTotal") ? 0 : json.getAsJsonPrimitive("expTotal").getAsInt(),
            isNull(json, "foodLevel") ? 20 : json.getAsJsonPrimitive("foodLevel").getAsInt(),
            isNull(json, "exhaustion") ? 0f : json.getAsJsonPrimitive("exhaustion").getAsFloat(),
            isNull(json, "saturation") ? 5f : json.getAsJsonPrimitive("saturation").getAsFloat(),
            isNull(json, "health") ? 20.0 : json.getAsJsonPrimitive("health").getAsDouble(),
            isNull(json, "maxHealth") ? 20.0 : json.getAsJsonPrimitive("maxHealth").getAsDouble(),
            inventoryFromJSON(json.getAsJsonObject("inventory")),
            inventoryFromJSON(json.getAsJsonObject("enderChest")), armor, effects);
}

From source file:gate.crowdsource.ne.EntityAnnotationResultsImporter.java

License:Open Source License

@Override
public void execute() throws ExecutionException {
    if (isInterrupted())
        throw new ExecutionInterruptedException();
    interrupted = false;//from  w ww.j a v  a2 s  . c  om
    try {
        if (jobId == null || jobId.longValue() <= 0) {
            throw new ExecutionException("Job ID must be provided");
        }

        AnnotationSet tokens = getDocument().getAnnotations(tokenASName).get(tokenAnnotationType);
        AnnotationSet snippetAnnotations = getDocument().getAnnotations(snippetASName)
                .get(snippetAnnotationType);
        AnnotationSet resultAS = getDocument().getAnnotations(resultASName);
        List<Annotation> allSnippets = Utils.inDocumentOrder(snippetAnnotations);

        for (Annotation snippet : allSnippets) {
            if (isInterrupted())
                throw new ExecutionInterruptedException();
            Object unitId = snippet.getFeatures().get(resultAnnotationType + "_unit_id");
            if (unitId != null) {
                if (!(unitId instanceof Long)) {
                    unitId = Long.valueOf(unitId.toString());
                }
                // find any existing result annotations within the span of this snippet
                // so we can avoid creating another annotation from this judgment if
                // one already exists
                AnnotationSet existingResults = Utils.getContainedAnnotations(resultAS, snippet,
                        resultAnnotationType);
                // tokens under this snippet
                List<Annotation> snippetTokens = Utils
                        .inDocumentOrder(Utils.getContainedAnnotations(tokens, snippet));

                JsonArray judgments = crowdFlowerClient.getJudgments(jobId, ((Long) unitId).longValue());

                if (judgments != null) {
                    for (JsonElement judgmentElt : judgments) {
                        JsonObject judgment = judgmentElt.getAsJsonObject();
                        JsonObject data = judgment.getAsJsonObject("data");
                        JsonArray answer = data.getAsJsonArray("answer");
                        Long judgmentId = judgment.get("id").getAsLong();
                        Double trust = judgment.get("trust").getAsDouble();
                        Long workerId = judgment.get("worker_id").getAsLong();
                        String comment = null;
                        if (data.get("comment") != null) {
                            if (data.get("comment").isJsonPrimitive()) {
                                comment = data.get("comment").getAsString().trim();
                                if ("".equals(comment)) {
                                    comment = null;
                                }
                            }
                        }
                        if (answer != null && answer.size() > 0) {
                            // judgment says there are some entities to annotate.  Look for
                            // sequences of consecutive token indices and create one result
                            // annotation for each such sequence
                            int startTok = 0;
                            int curTok = startTok;
                            while (curTok < answer.size()) {
                                // we've reached the end of an annotation if either
                                // (a) we want to annotate each token individually anyway or 
                                // (b) we're on the last element of answer or
                                // (c) the next element is not this+1
                                if (!annotateSpans || curTok == answer.size() - 1
                                        || (answer.get(curTok).getAsInt() + 1) != answer.get(curTok + 1)
                                                .getAsInt()) {
                                    Long startOffset = snippetTokens.get(answer.get(startTok).getAsInt())
                                            .getStartNode().getOffset();
                                    Long endOffset = snippetTokens.get(answer.get(curTok).getAsInt())
                                            .getEndNode().getOffset();
                                    startTok = curTok + 1;
                                    // check whether there's already an annotation at this location for this judgment
                                    AnnotationSet existingEntities = existingResults.getContained(startOffset,
                                            endOffset);
                                    boolean found = false;
                                    for (Annotation a : existingEntities) {
                                        if (judgmentId.equals(a.getFeatures().get(JUDGMENT_ID_FEATURE_NAME))) {
                                            found = true;
                                            break;
                                        }
                                    }
                                    if (!found) {
                                        // no existing annotation found, create one
                                        try {
                                            FeatureMap features = Utils.featureMap(JUDGMENT_ID_FEATURE_NAME,
                                                    judgmentId, "trust", trust, "worker_id", workerId);
                                            if (comment != null) {
                                                features.put("comment", comment);
                                            }
                                            resultAS.add(startOffset, endOffset, resultAnnotationType,
                                                    features);
                                        } catch (InvalidOffsetException e) {
                                            throw new ExecutionException(
                                                    "Invalid offset obtained from existing annotation!", e);
                                        }
                                    }
                                }
                                curTok++;
                            }
                        }
                    }
                } else {
                    log.warn("Unit " + unitId + " has no judgments");
                }

            } else {
                log.warn("Found " + snippetAnnotationType + " annotation with no " + UNIT_ID_FEATURE_NAME
                        + " feature, ignoring");
            }
        }

    } finally {
        interrupted = false;
    }
}

From source file:geomesa.example.twitter.ingest.TwitterParser.java

License:Apache License

private SimpleFeature convertToFeature(final JsonObject obj, final SimpleFeatureBuilder builder,
        final GeometryFactory factory, final DateTimeFormatter df) {
    builder.reset();//from   w w  w .j a  v a 2s . c  om

    // user info
    final JsonObject user = obj.getAsJsonObject(USER);
    final String userName = user.getAsJsonPrimitive(USER_NAME).getAsString();
    final String userId = user.getAsJsonPrimitive(USER_ID).getAsString();
    builder.set(TwitterFeatureIngester.FEAT_USER_NAME, utf8(userName));
    builder.set(TwitterFeatureIngester.FEAT_USER_ID, userId);

    builder.set(TwitterFeatureIngester.FEAT_TEXT, utf8(obj.get(TEXT).getAsString()));

    // geo info
    final boolean hasGeoJson = obj.has(COORDS_GEO_JSON) && obj.get(COORDS_GEO_JSON) != JsonNull.INSTANCE;
    if (hasGeoJson) {
        final JsonObject geo = obj.getAsJsonObject(COORDS_GEO_JSON);
        final JsonArray coords = geo.getAsJsonArray(COORDS);
        double lat = coords.get(0).getAsDouble();
        double lon = coords.get(1).getAsDouble();

        if (lon != 0.0 && lat != 0.0) {
            final Coordinate coordinate = new Coordinate(lat, lon);
            final Geometry g = new Point(new CoordinateArraySequence(new Coordinate[] { coordinate }), factory);
            builder.set(TwitterFeatureIngester.FEAT_GEOM, g);
        }
    }

    // time and id
    final String tweetId = obj.get(TWEET_ID).getAsString();
    final Date date = df.parseDateTime(obj.get(CREATED_AT).getAsString()).toDate();
    builder.set(TwitterFeatureIngester.FEAT_TWEET_ID, tweetId);
    builder.set(TwitterFeatureIngester.FEAT_DTG, date);

    if (useExtendedFeatures) {
        conditionalSetString(builder, obj, FEAT_IS_RETWEET);
        conditionalSetString(builder, obj, FEAT_SOURCE);
        conditionalSetString(builder, obj, FEAT_RETWEETS);
        conditionalSetString(builder, obj, FEAT_IN_REPLY_TO_USER_ID);
        conditionalSetString(builder, obj, FEAT_IN_REPLY_TO_USER_NAME);
        conditionalSetString(builder, obj, FEAT_IN_REPLY_TO_STATUS);
        conditionalSetString(builder, obj, FEAT_FILTER_LEVEL);
        conditionalSetString(builder, obj, FEAT_LANGUAGE);
        conditionalSetString(builder, obj, FEAT_WITHHELD_COPYRIGHT);
        conditionalSetString(builder, obj, FEAT_WITHHELD_SCOPE);
        conditionalSetArray(builder, obj, FEAT_WITHHELD_COUNTRIES);

        JsonElement entities = obj.get("entities");
        if (entities != null && entities != JsonNull.INSTANCE) {
            JsonObject e = (JsonObject) entities;
            conditionalSetObjectArray(builder, e, FEAT_HASHTAGS, "text");
            conditionalSetObjectArray(builder, e, FEAT_URLS, "url");
            conditionalSetObjectArray(builder, e, FEAT_SYMBOLS, "text");
            conditionalSetObjectArray(builder, e, FEAT_USER_MENTIONS, "id");
            conditionalSetObjectArray(builder, e, FEAT_MEDIA, "media_url");
        }
    }

    return builder.buildFeature(tweetId);
}

From source file:geomesa.example.twitter.ingest.TwitterParser.java

License:Apache License

private void fillFeature(final JsonObject obj, final SimpleFeature sf, final GeometryFactory factory,
        final DateTimeFormatter df) {

    // user info/*from   www  .jav  a 2  s. c om*/
    final JsonObject user = obj.getAsJsonObject(USER);
    final String userName = user.getAsJsonPrimitive(USER_NAME).getAsString();
    final String userId = user.getAsJsonPrimitive(USER_ID).getAsString();
    sf.setAttribute(TwitterFeatureIngester.FEAT_USER_NAME, utf8(userName));
    sf.setAttribute(TwitterFeatureIngester.FEAT_USER_ID, userId);

    sf.setAttribute(TwitterFeatureIngester.FEAT_TEXT, utf8(obj.get(TEXT).getAsString()));

    // geo info
    final boolean hasGeoJson = obj.has(COORDS_GEO_JSON) && obj.get(COORDS_GEO_JSON) != JsonNull.INSTANCE;
    if (hasGeoJson) {
        final JsonObject geo = obj.getAsJsonObject(COORDS_GEO_JSON);
        final JsonArray coords = geo.getAsJsonArray(COORDS);
        double lat = coords.get(0).getAsDouble();
        double lon = coords.get(1).getAsDouble();

        if (lon != 0.0 && lat != 0.0) {
            final Coordinate coordinate = new Coordinate(lat, lon);
            final Geometry g = new Point(new CoordinateArraySequence(new Coordinate[] { coordinate }), factory);
            sf.setAttribute(TwitterFeatureIngester.FEAT_GEOM, g);
        }
    }

    // time and id
    final String tweetId = obj.get(TWEET_ID).getAsString();
    final Date date = df.parseDateTime(obj.get(CREATED_AT).getAsString()).toDate();
    sf.setAttribute(TwitterFeatureIngester.FEAT_TWEET_ID, tweetId);
    sf.setAttribute(TwitterFeatureIngester.FEAT_DTG, date);

    if (useExtendedFeatures) {
        conditionalSetString(sf, obj, FEAT_IS_RETWEET);
        conditionalSetString(sf, obj, FEAT_SOURCE);
        conditionalSetString(sf, obj, FEAT_RETWEETS);
        conditionalSetString(sf, obj, FEAT_IN_REPLY_TO_USER_ID);
        conditionalSetString(sf, obj, FEAT_IN_REPLY_TO_USER_NAME);
        conditionalSetString(sf, obj, FEAT_IN_REPLY_TO_STATUS);
        conditionalSetString(sf, obj, FEAT_FILTER_LEVEL);
        conditionalSetString(sf, obj, FEAT_LANGUAGE);
        conditionalSetString(sf, obj, FEAT_WITHHELD_COPYRIGHT);
        conditionalSetString(sf, obj, FEAT_WITHHELD_SCOPE);
        conditionalSetArray(sf, obj, FEAT_WITHHELD_COUNTRIES);

        JsonElement entities = obj.get("entities");
        if (entities != null && entities != JsonNull.INSTANCE) {
            JsonObject e = (JsonObject) entities;
            conditionalSetObjectArray(sf, e, FEAT_HASHTAGS, "text");
            conditionalSetObjectArray(sf, e, FEAT_URLS, "url");
            conditionalSetObjectArray(sf, e, FEAT_SYMBOLS, "text");
            conditionalSetObjectArray(sf, e, FEAT_USER_MENTIONS, "id");
            conditionalSetObjectArray(sf, e, FEAT_MEDIA, "media_url");
        }
    }

    //((FeatureIdImpl)sf.getIdentifier()).setID(Long.toString(tweetId));
    //sf.getUserData().put(Hints.USE_PROVIDED_FID, Boolean.TRUE);
}