Example usage for com.google.gson JsonObject getAsJsonPrimitive

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

Introduction

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

Prototype

public JsonPrimitive getAsJsonPrimitive(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonPrimitive element.

Usage

From source file:fi.vtt.nubomedia.kurento.Ar3DHandler.java

License:Open Source License

private void start(final WebSocketSession session, JsonObject jsonMessage) {
    try {/*w ww . jav  a  2  s  .co m*/
        UserSession user = new UserSession();
        MediaPipeline pipeline = kurento.createMediaPipeline();
        System.err.println("STATS A:" + pipeline.getLatencyStats());
        pipeline.setLatencyStats(true);
        System.err.println("STATS B:" + pipeline.getLatencyStats());
        user.setMediaPipeline(pipeline);
        //pipelines.put(session.getId(), pipeline);
        webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).build();

        user.setWebRtcEndpoint(webRtcEndpoint);
        users.put(session.getId(), user);

        // ICE candidates
        webRtcEndpoint.addOnIceCandidateListener(new EventListener<OnIceCandidateEvent>() {
            @Override
            public void onEvent(OnIceCandidateEvent event) {
                JsonObject response = new JsonObject();
                response.addProperty("id", "iceCandidate");
                response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
                try {
                    synchronized (session) {
                        session.sendMessage(new TextMessage(response.toString()));
                    }
                } catch (IOException e) {
                    log.debug(e.getMessage());
                }
            }
        });

        arFilter = new ArMarkerdetector.Builder(pipeline).build();
        if (jsonFile == null) {
            System.err.println("json from browser");
            arFilter.setArThing(createArThings(jsonMessage.getAsJsonPrimitive("augmentables").getAsString()));
        } else {
            System.err.println("json from file");
            arFilter.setArThing(createArThings(getFile(jsonFile)));
        }

        arFilter.enableTickEvents(true);
        arFilter.enableAugmentation(true);
        arFilter.setMarkerPoseFrequency(false, 1);
        arFilter.setMarkerPoseFrameFrequency(false, 10);
        arFilter.enableMarkerCountEvents(false);
        arFilter.addMarkerCountListener(new EventListener<MarkerCountEvent>() {
            @Override
            public void onEvent(MarkerCountEvent event) {
                String result = String.format("Marker %d count:%d (diff:%d): {}", event.getMarkerId(),
                        event.getMarkerCount(), event.getMarkerCountDiff());
                log.debug(result, event);
            }
        });

        arFilter.addTickListener(new EventListener<TickEvent>() {
            @Override
            public void onEvent(TickEvent event) {
                //String result = String.format("Tick msg %s time:%d : {}", event.getMsg(), event.getTickTimestamp());
                //log.debug(result, event);
                smart(event.getMsg(), event.getTickTimestamp());
            }
        });

        arFilter.addMarkerPoseListener(new EventListener<MarkerPoseEvent>() {
            @Override
            public void onEvent(MarkerPoseEvent event) {
                //Just print content of event

                log.debug("\nMarkerPoseEvent: " + event);
                log.debug("frameId: " + event.getSequenceNumber());
                //log.debug("timestamp: " + event.getTimestamp());                     
                log.debug("width:" + event.getWidth() + " height:" + event.getHeight());

                log.debug("matrixProjection:" + event.getMatrixProjection());
                List poses = event.getMarkerPose();

                if (poses != null) {
                    for (int z = 0; z < poses.size(); z++) {
                        org.kurento.jsonrpc.Props props = (org.kurento.jsonrpc.Props) poses.get(z);
                        for (org.kurento.jsonrpc.Prop prop : props) {
                            java.util.ArrayList<Float> list;
                            switch (prop.getName()) {
                            case "matrixModelview":
                                list = (java.util.ArrayList<Float>) prop.getValue();
                                log.debug("matrixModelview:" + list);
                                break;
                            case "markerId":
                                log.debug("\n\nThe MarkerId = " + prop.getValue());
                                break;
                            default:
                                break;
                            }
                        }
                    }
                }
                log.debug("Got MarkerPoseEvent: ", event);
            }
        });

        webRtcEndpoint.connect(arFilter);
        arFilter.connect(webRtcEndpoint);
        System.err.println("jsonMessage: " + jsonMessage);
        System.err.println("jsonMessage.get(sdpOffer): " + jsonMessage.get("sdpOffer"));
        String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
        String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer);

        JsonObject response = new JsonObject();
        response.addProperty("id", "startResponse");
        response.addProperty("sdpAnswer", sdpAnswer);
        //session.sendMessage(new TextMessage(response.toString()));

        synchronized (session) {
            session.sendMessage(new TextMessage(response.toString()));
        }

        webRtcEndpoint.gatherCandidates();
        out = new PrintWriter("smart.txt");

    } 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  .j  a  v  a  2  s  . com*/
    }

    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));
    }//from w ww .  j av 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  ww.j a  v  a2s  .com
        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 va2  s  . c  om

    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;
    }//w  ww  .  j a  v  a2  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.ItemStackSnapshot.java

License:Open Source License

/**
 * Loads a snapshot from a JSON export./*ww  w.j  a  v a 2  s.  com*/
 *
 * @param json The JSON data.
 *
 * @return A snapshot with these data inside.
 */
@SuppressWarnings("unchecked")
public static ItemStackSnapshot fromJSON(final JsonObject json) {
    try {
        return new ItemStackSnapshot(Material.getMaterial(json.getAsJsonPrimitive("id").getAsString()),
                json.getAsJsonPrimitive("Damage").getAsShort(), json.getAsJsonPrimitive("Count").getAsInt(),
                jsonToNative(json.getAsJsonObject("NBT")));
    } catch (IllegalStateException e) {
        PluginLogger.error("Unable to load malformed item stack snapshot: {0}", e, json.toString());
        return null;
    }
}

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./*w ww.ja  v a  2 s.  c om*/
 *
 * @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:fr.zcraft.MultipleInventories.snaphots.PlayerSnapshot.java

License:Open Source License

private static PotionEffect potionEffectFromJSON(final JsonObject json) {
    final JsonPrimitive color = json.get("color").isJsonNull() ? null : json.getAsJsonPrimitive("color");

    return new PotionEffect(PotionEffectType.getByName(json.getAsJsonPrimitive("type").getAsString()),
            isNull(json, "duration") ? 1 : json.getAsJsonPrimitive("duration").getAsInt(),
            isNull(json, "amplifier") ? 1 : json.getAsJsonPrimitive("amplifier").getAsInt(),
            !isNull(json, "ambient") && json.getAsJsonPrimitive("ambient").getAsBoolean(),
            isNull(json, "has-particles") || json.getAsJsonPrimitive("has-particles").getAsBoolean(),
            color != null && !color.isJsonNull() ? Color.fromRGB(color.getAsInt()) : null);
}

From source file:fr.zcraft.zbanque.network.packets.PacketPlayOutPing.java

License:Open Source License

@Override
public void onResponse(JsonElement data) {
    boolean invalidResponse = false;

    if (!data.isJsonObject())
        invalidResponse = true;/*from   ww  w. j  a  v  a2  s  . c  o  m*/

    JsonObject object = data.getAsJsonObject();
    if (object.get("version") == null || !object.get("version").isJsonPrimitive())
        invalidResponse = true;

    if (invalidResponse) {
        PluginLogger.error("Strange response received from the /ping endpoint: {0}", data);
        PluginLogger.warning("Cannot check the webservice version, the networking system may not work!");
        return;
    }

    String version = object.getAsJsonPrimitive("version").getAsString();

    PluginLogger.info("WebService contacted successfully - remote version: {0}", version);
    if (!version.startsWith(ZBanque.WEBSERVICE_COMPATIBLE_VERSION))
        PluginLogger.warning("Remote major version is not the same as the plugin version, errors may occur.");

    ZBanque.get().setWebServiceEnabled(true);
}