Example usage for com.google.gson JsonObject get

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

Introduction

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

Prototype

public JsonElement get(String memberName) 

Source Link

Document

Returns the member with the specified name.

Usage

From source file:br.org.cesar.knot.lib.connection.KnotSocketIo.java

License:Open Source License

/**
 * Update an existent device/*  w  w w.  j  av a2s .c o  m*/
 *
 * @param device         the identifier of device (uuid)
 * @param callbackResult Callback for this method
 * @throws KnotException
 * @throws SocketNotConnected
 * @throws InvalidParametersException <p>
 *                                    Check the reference on @see <a https://meshblu-socketio.readme.io/docs/update</a>
 */
public <T extends AbstractThingDevice> void updateDevice(final T device, final Event<T> callbackResult)
        throws SocketNotConnected, InvalidParametersException {

    if (isSocketConnected() && isSocketRegistered()) {
        if (device != null && callbackResult != null) {
            String json = mGson.toJson(device);

            JSONObject deviceToUpdate = null;
            try {
                deviceToUpdate = new JSONObject(json);
            } catch (JSONException e) {
                throw new InvalidParametersException("Invalid parameters. Please, check your device object");
            }

            if (deviceToUpdate != null) {

                mSocket.emit(EVENT_UPDATE_DEVICE, deviceToUpdate, new Ack() {
                    @Override
                    public void call(Object... args) {
                        //Get First element of the array
                        if (args.length > 0 && args[FIRST_EVENT_RECEIVED] != null) {
                            JsonElement jsonElement = new JsonParser()
                                    .parse(args[FIRST_EVENT_RECEIVED].toString());
                            JsonObject jsonObject = jsonElement.getAsJsonObject();
                            if (jsonObject.get(ERROR) != null) {
                                callbackResult
                                        .onEventError(new KnotException(jsonObject.get(ERROR).toString()));
                            } else {
                                T result = (T) mGson.fromJson(args[FIRST_EVENT_RECEIVED].toString(),
                                        device.getClass());
                                callbackResult.onEventFinish(result);
                            }

                        } else {
                            callbackResult.onEventError(new KnotException("Failed to update file"));
                        }
                    }
                });
            }
        } else {
            throw new InvalidParametersException("Invalid parameters");
        }
    } else {
        throw new SocketNotConnected("Socket not ready or connected");
    }
}

From source file:br.org.cesar.knot.lib.connection.KnotSocketIo.java

License:Open Source License

/**
 * Method used to claim a specif device;
 *
 * @param device         device Wanted//from ww w .  j  av a 2  s . co m
 * @param callbackResult Callback for this method
 * @throws SocketNotConnected
 * @throws InvalidParametersException
 * @throws JSONException
 */
public <T extends AbstractThingDevice> void claimDevice(final T device, final Event<Boolean> callbackResult)
        throws SocketNotConnected, InvalidParametersException, JSONException {

    if (isSocketConnected() && isSocketRegistered()) {
        if (device != null && callbackResult != null) {
            JSONObject uuidDevice = new JSONObject();
            uuidDevice.put(UUID, device);

            mSocket.emit(EVENT_CLAIM_DEVICE, uuidDevice, new Ack() {
                @Override
                public void call(Object... args) {
                    if (args != null && args.length > 0) {
                        JsonElement jsonElement = new JsonParser().parse(args[FIRST_EVENT_RECEIVED].toString());
                        JsonObject jsonObject = jsonElement.getAsJsonObject();
                        if (jsonObject.get(ERROR) != null && !jsonObject.get(ERROR).isJsonNull()) {
                            callbackResult.onEventError(new KnotException(jsonObject.get(ERROR).toString()));
                        } else {
                            callbackResult.onEventFinish(true);
                        }
                    } else {
                        callbackResult.onEventError(new KnotException("Error in reading the result"));
                    }
                }
            });
        } else {
            throw new InvalidParametersException("Invalid parameters");
        }
    } else {
        throw new SocketNotConnected("Socket not ready or connected");
    }

}

From source file:br.org.cesar.knot.lib.connection.KnotSocketIo.java

License:Open Source License

/**
 * This method returns a instance of the device
 *
 * @param typeClass      The specific genericized type of src.
 * @param uuid           The device identification to find a device on server
 * @param callbackResult Callback for this method
 * @param <T>            the type of the desired object
 * @throws JSONException/*from   w ww . j  ava2s .  c om*/
 */
public <T extends AbstractThingDevice> void getDevice(final T typeClass, String uuid,
        final Event<T> callbackResult) throws JSONException, InvalidParametersException, SocketNotConnected {

    if (isSocketConnected() && isSocketRegistered()) {
        if (typeClass != null && callbackResult != null && uuid != null) {

            JSONObject uuidDevice = new JSONObject();
            uuidDevice.put(UUID, uuid);

            mSocket.emit(EVENT_GET_DEVICE, uuidDevice, new Ack() {
                @Override
                public void call(Object... args) {

                    if (args != null && args.length > 0) {

                        JsonElement jsonElement = new JsonParser().parse(args[FIRST_EVENT_RECEIVED].toString());
                        JsonObject jsonObject = jsonElement.getAsJsonObject();
                        if (jsonObject.get(ERROR) != null && !jsonObject.get(ERROR).isJsonNull()) {
                            callbackResult.onEventError(new KnotException(jsonObject.get(ERROR).toString()));
                        } else if (jsonObject.get(FROM) != null) {
                            JsonObject json = jsonObject.get(DEVICE).getAsJsonObject();
                            try {
                                T result = (T) mGson.fromJson(json.toString(), typeClass.getClass());
                                callbackResult.onEventFinish(result);
                            } catch (Exception e) {
                                callbackResult.onEventError(new KnotException("Error in reading the result"));
                            }
                        } else {
                            callbackResult.onEventError(new KnotException("Unknown error"));
                        }
                    } else {
                        callbackResult.onEventError(new KnotException("Error in reading the result"));
                    }
                }
            });

        } else {
            throw new InvalidParametersException("Invalid parameters");
        }
    } else {
        throw new SocketNotConnected("Socket not ready or connected");
    }

}

From source file:br.org.cesar.knot.lib.connection.KnotSocketIo.java

License:Open Source License

/**
 * This method return a list devices of the specific owner
 *
 * @param typeThing      Generic type of list.
 * @param query          Query to find devices
 * @param callbackResult List of devices
 * @throws KnotException <p>/*from ww  w. j av a  2  s .  co  m*/
 * @see <ahttps://meshblu-socketio.readme.io/docs/devices </a>
 */
public <T extends AbstractThingDevice> void getDeviceList(final KnotList<T> typeThing, JSONObject query,
        final Event<List<T>> callbackResult)
        throws KnotException, SocketNotConnected, InvalidParametersException {
    if (isSocketConnected() && isSocketRegistered()) {
        if (typeThing != null && callbackResult != null) {

            if (query == null) {
                query = new JSONObject();
            }

            mSocket.emit(EVENT_GET_DEVICES, query, new Ack() {
                @Override
                public void call(Object... args) {
                    List<T> result = null;
                    try {
                        JsonElement jsonElement = new JsonParser().parse(args[FIRST_EVENT_RECEIVED].toString());
                        JsonObject jsonObject = jsonElement.getAsJsonObject();

                        if (jsonObject.get(ERROR) != null && !jsonObject.get(ERROR).isJsonNull()) {
                            callbackResult.onEventError(new KnotException(jsonObject.get(ERROR).toString()));
                            return;
                        }

                        JsonArray jsonArray = jsonElement.getAsJsonObject().getAsJsonArray(DEVICES);

                        if (jsonArray != null || jsonArray.size() > 0) {
                            result = mGson.fromJson(jsonArray, typeThing);
                        } else {
                            result = mGson.fromJson(EMPTY_JSON, typeThing);
                        }
                        callbackResult.onEventFinish((List<T>) result);
                    } catch (Exception e) {
                        callbackResult.onEventError(new KnotException(e));
                    }
                }
            });
        } else {
            throw new InvalidParametersException("Invalid parameters");
        }
    } else {
        throw new SocketNotConnected("Socket not ready or connected");
    }
}

From source file:br.ufg.inf.es.saep.sandbox.dominio.infraestrutura.ValorDeserializer.java

License:Creative Commons License

@Override
public Valor deserialize(JsonElement jsonElement, Type type,
        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    byte tipo = jsonObject.get("tipo").getAsByte();
    JsonElement valor = jsonObject.get("valor");

    if (tipo == Valor.STRING) {
        return new Valor(valor.getAsString());
    } else if (tipo == REAL) {
        return new Valor(valor.getAsFloat());
    } else if (tipo == LOGICO) {
        return new Valor(valor.getAsBoolean());
    } else if (tipo == DATA) {
        return Valor.dataFromString(valor.getAsString());
    }//from  w w w . j av  a 2  s  . co m

    return null;
}

From source file:br.unicamp.cst.bindings.soar.JSoarCodelet.java

License:Open Source License

public ArrayList<Object> getCommandsJSON(String package_with_beans_classes) {
    ArrayList<Object> commandList = new ArrayList<Object>();
    JsonObject templist = getJsoar().getOutputLinkJSON();
    Set<Map.Entry<String, JsonElement>> set = templist.entrySet();
    Iterator<Entry<String, JsonElement>> it = set.iterator();
    while (it.hasNext()) {
        Entry<String, JsonElement> entry = it.next();
        String key = entry.getKey();
        JsonObject commandtype = entry.getValue().getAsJsonObject();
        try {//from  w  ww. j  a v a  2 s .  c o  m
            Class type = Class.forName(package_with_beans_classes + "." + key);
            Object command = type.newInstance();
            type.cast(command);
            for (Field field : type.getFields()) {
                if (commandtype.has(field.getName())) {
                    if (commandtype.get(field.getName()).getAsJsonPrimitive().isNumber()) {
                        field.set(command, commandtype.get(field.getName()).getAsFloat());

                    } else if (commandtype.get(field.getName()).getAsJsonPrimitive().isBoolean()) {
                        field.set(command, commandtype.get(field.getName()).getAsBoolean());

                    } else {
                        field.set(command, commandtype.get(field.getName()).getAsString());
                    }
                }
            }
            commandList.add(command);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return commandList;
}

From source file:br.unicamp.cst.bindings.soar.SOARPlugin.java

License:Open Source License

public JsonObject getOutputLinkJSON() {
    JsonObject json = new JsonObject();
    try {/*from w  w  w. j  a  v  a2 s .  c o  m*/
        if (getAgent() != null) {
            List<Wme> Commands = getOutputLink_WME();
            setOutputLinkAsString(getWMEStringOutput());
            for (Wme command : Commands) {
                String commandType = command.getAttribute().toString();
                json.add(commandType, new JsonObject());
                String parameter = command.getAttribute().toString();
                String parvalue = command.getValue().toString();
                Iterator<Wme> children = command.getChildren();
                while (children.hasNext()) {
                    Wme child = children.next();
                    parameter = child.getAttribute().toString();
                    parvalue = child.getValue().toString();
                    Float floatvalue = tryParseFloat(parvalue);
                    if (floatvalue != null) {
                        json.get(commandType).getAsJsonObject().addProperty(parameter, floatvalue);
                    } else {
                        json.get(commandType).getAsJsonObject().addProperty(parameter, parvalue);
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.severe("Error while creating SOAR Kernel" + e);
    }
    setJsonOutputLinkAsString(json.toString());
    return (json);
}

From source file:brooklyn.entity.mesos.framework.MesosFrameworkImpl.java

License:Apache License

public List<String> scanTasks(JsonArray frameworks) {
    String frameworkId = sensors().get(FRAMEWORK_ID);
    Entity mesosCluster = sensors().get(MESOS_CLUSTER);
    LOG.debug("Periodic scanning of framework tasks: frameworkId={}, mesosCluster={}", frameworkId,
            mesosCluster);/*from w  w w . j  a  v  a 2 s . c  o  m*/

    for (int i = 0; i < frameworks.size(); i++) {
        JsonObject framework = frameworks.get(i).getAsJsonObject();
        if (frameworkId.equals(framework.get("id").getAsString())) {
            JsonArray completed = framework.getAsJsonArray("completed_tasks");
            JsonArray tasks = framework.getAsJsonArray("tasks");
            sensors().set(MESOS_COMPLETED_TASKS, completed.size());
            sensors().set(MESOS_RUNNING_TASKS, tasks.size());

            List<String> taskNames = MutableList.<String>of();
            for (int j = 0; j < tasks.size(); j++) {
                JsonObject json = tasks.get(j).getAsJsonObject();
                String id = json.get("id").getAsString();
                String name = json.get("name").getAsString();
                String state = json.get("state").getAsString();

                Optional<Entity> taskEntity = Iterables.tryFind(sensors().get(FRAMEWORK_TASKS).getMembers(),
                        Predicates.compose(Predicates.equalTo(id),
                                EntityFunctions.attribute(MesosTask.TASK_ID)));
                MesosTask task = null;
                if (taskEntity.isPresent()) {
                    // Only interested in tasks for our own use of Marathon.
                    // Tasks that other people create we'll ignore.
                    task = (MesosTask) taskEntity.get();
                }
                if (task != null) {
                    taskNames.add(name);
                    task.sensors().set(MesosTask.TASK_ID, id);
                    task.sensors().set(MesosTask.TASK_STATE, state);
                }
            }

            Set<String> taskNamesSet = Sets.newHashSet(taskNames);
            for (Entity member : ImmutableList.copyOf(getTaskCluster().getMembers())) {
                final String name = member.sensors().get(MesosTask.TASK_NAME);
                if (name != null) {
                    boolean found = taskNamesSet.contains(name);
                    if (found)
                        continue;
                }

                // Stop and then remove the task as it is no longer running, unless ON_FIRE
                //
                // TODO Aled worries about this: if task has gone, then MarathonTask polling
                // the task's URL will fail, setting the serviceUp to false, setting it 
                // on-fire. What will ever remove the task on a graceful shutdown of a container?
                // Or is that handled elsewhere?
                Lifecycle state = member.sensors().get(Attributes.SERVICE_STATE_ACTUAL);
                if (Lifecycle.ON_FIRE.equals(state) || Lifecycle.STARTING.equals(state)) {
                    continue;
                } else if (Lifecycle.STOPPING.equals(state) || Lifecycle.STOPPED.equals(state)) {
                    getTaskCluster().removeMember(member);
                    getTaskCluster().removeChild(member);
                    Entities.unmanage(member);
                } else {
                    ServiceStateLogic.setExpectedState(member, Lifecycle.STOPPING);
                }
            }
            return taskNames;
        }
    }
    // not found
    return null;
}

From source file:brooklyn.entity.mesos.MesosClusterImpl.java

License:Apache License

public List<String> scanFrameworks(JsonArray frameworks) {
    List<String> frameworkNames = MutableList.<String>of();
    for (int i = 0; i < frameworks.size(); i++) {
        JsonObject task = frameworks.get(i).getAsJsonObject();
        String id = task.get("id").getAsString();
        JsonElement pidObj = task.get("pid");
        String pid = null;// w w  w.  java2 s . co m
        if (pidObj != null && !pidObj.isJsonNull()) {
            pid = pidObj.getAsString();
        }
        String name = task.get("name").getAsString();
        String url = task.get("webui_url").getAsString();
        frameworkNames.add(name);

        Optional<Entity> entity = Iterables.tryFind(sensors().get(MESOS_FRAMEWORKS).getMembers(), Predicates
                .compose(Predicates.equalTo(id), EntityFunctions.attribute(MesosFramework.FRAMEWORK_ID)));
        if (entity.isPresent())
            continue;

        EntitySpec<? extends MesosFramework> frameworkSpec = EntitySpec
                .create(FRAMEWORKS.containsKey(name) ? FRAMEWORKS.get(name)
                        : EntitySpec.create(MesosFramework.class))
                .configure(MesosFramework.FRAMEWORK_ID, id).configure(MesosFramework.FRAMEWORK_PID, pid)
                .configure(MesosFramework.FRAMEWORK_NAME, name).configure(MesosFramework.FRAMEWORK_URL, url)
                .configure(MesosFramework.MESOS_CLUSTER, this)
                .displayName(String.format("%s Framework", Strings.toInitialCapOnly(name)));
        MesosFramework added = sensors().get(MESOS_FRAMEWORKS).addMemberChild(frameworkSpec);
        added.start(ImmutableList.<Location>of());
    }
    return frameworkNames;
}

From source file:brooklyn.entity.mesos.MesosClusterImpl.java

License:Apache License

public List<String> scanSlaves(JsonArray slaves) throws UnknownHostException {
    List<String> slaveIds = MutableList.<String>of();
    for (int i = 0; i < slaves.size(); i++) {
        JsonObject slave = slaves.get(i).getAsJsonObject();
        boolean active = slave.get("active").getAsBoolean();
        String id = slave.get("id").getAsString();
        String hostname = slave.get("hostname").getAsString();
        Double registered = slave.get("registered_time").getAsDouble();
        Group group = sensors().get(MESOS_SLAVES);

        Optional<Entity> entity = Iterables.tryFind(group.getMembers(), Predicates
                .compose(Predicates.equalTo(id), EntityFunctions.attribute(MesosSlave.MESOS_SLAVE_ID)));
        if (entity.isPresent()) {
            Entity found = entity.get();
            found.sensors().set(MesosSlave.SLAVE_ACTIVE, active);
            if (!active) {
                Lifecycle state = found.sensors().get(Attributes.SERVICE_STATE_ACTUAL);
                if (Lifecycle.ON_FIRE.equals(state) || Lifecycle.STARTING.equals(state)) {
                    continue;
                } else if (Lifecycle.STOPPING.equals(state) || Lifecycle.STOPPED.equals(state)) {
                    group.removeMember(found);
                    group.removeChild(found);
                    Entities.unmanage(found);
                } else {
                    ServiceStateLogic.setExpectedState(found, Lifecycle.STOPPING);
                }/*from w ww  .  j  a va2 s  .  co  m*/
            }
        } else if (active) {
            LocationSpec<SshMachineLocation> spec = LocationSpec.create(SshMachineLocation.class)
                    .configure(SshMachineLocation.SSH_HOST, hostname)
                    .configure("address", InetAddress.getByName(hostname)).displayName(hostname);
            if (config().get(MESOS_SLAVE_ACCESSIBLE)) {
                spec.configure(CloudLocationConfig.WAIT_FOR_SSHABLE, "true")
                        .configure(SshMachineLocation.DETECT_MACHINE_DETAILS, true)
                        .configure(SshMachineLocation.SSH_PORT, config().get(MesosSlave.SLAVE_SSH_PORT))
                        .configure(LocationConfigKeys.USER, config().get(MesosSlave.SLAVE_SSH_USER))
                        .configure(LocationConfigKeys.PASSWORD, config().get(MesosSlave.SLAVE_SSH_PASSWORD))
                        .configure(SshTool.PROP_PASSWORD, config().get(MesosSlave.SLAVE_SSH_PASSWORD))
                        .configure(SshTool.PROP_PORT, config().get(MesosSlave.SLAVE_SSH_PORT))
                        .configure(LocationConfigKeys.PRIVATE_KEY_DATA,
                                config().get(MesosSlave.SLAVE_SSH_PRIVATE_KEY_DATA))
                        .configure(LocationConfigKeys.PRIVATE_KEY_FILE,
                                config().get(MesosSlave.SLAVE_SSH_PRIVATE_KEY_FILE));
            } else {
                spec.configure(CloudLocationConfig.WAIT_FOR_SSHABLE, "false")
                        .configure(SshMachineLocation.DETECT_MACHINE_DETAILS, false);
            }
            SshMachineLocation machine = getManagementContext().getLocationManager().createLocation(spec);

            // Setup port forwarding
            MarathonPortForwarder portForwarder = new MarathonPortForwarder();
            portForwarder.setManagementContext(getManagementContext());

            EntitySpec<MesosSlave> slaveSpec = EntitySpec.create(MesosSlave.class)
                    .configure(MesosSlave.MESOS_SLAVE_ID, id)
                    .configure(MesosSlave.REGISTERED_AT, registered.longValue())
                    .configure(MesosSlave.MESOS_CLUSTER, this).displayName("Mesos Slave (" + hostname + ")");
            MesosSlave added = sensors().get(MESOS_SLAVES).addMemberChild(slaveSpec);
            added.sensors().set(MesosSlave.SLAVE_ACTIVE, active);
            added.sensors().set(MesosSlave.HOSTNAME, hostname);
            added.sensors().set(MesosSlave.ADDRESS, hostname);

            added.start(ImmutableList.of(machine));
            portForwarder.init(hostname, this);

            // Setup subnet tier
            SubnetTier subnetTier = added.addChild(
                    EntitySpec.create(SubnetTier.class).configure(SubnetTier.PORT_FORWARDER, portForwarder)
                            .configure(SubnetTier.SUBNET_CIDR, Cidr.UNIVERSAL));
            Entities.start(subnetTier, ImmutableList.of(machine));
            added.sensors().set(MesosSlave.SUBNET_TIER, subnetTier);
        }

        if (active)
            slaveIds.add(id);
    }
    return slaveIds;
}