List of usage examples for com.google.gson JsonArray get
public JsonElement get(int i)
From source file:br.org.cesar.knot.lib.connection.ThingApi.java
License:Open Source License
/** * Get a specific device's gateway from Meshblu instance. * * @param device the device identifier (uuid) * @param clazz The class for this device. Meshblu works with any type of objects and * it is necessary deserialize the return to a valid object. * Note: The class parameter should be a extension of {@link AbstractThingDevice} * @return an object based on the class parameter * @throws KnotException KnotException//from w w w. ja v a2s .c o m */ public <T extends AbstractThingDevice> T getDeviceGateway(String device, Class<T> clazz) throws InvalidDeviceOwnerStateException, KnotException { // Check if the current state of device owner is valid if (!isValidDeviceOwner()) { throw new InvalidDeviceOwnerStateException("The device owner is invalid or null"); } // Get a specific device's gateway from Meshblu instance. final String endPoint = mEndPoint + DEVICE_PATH + device + DEVICE_PROPERTY_PATH_GATEWAY; Request request = generateBasicRequestBuild(this.abstractDeviceOwner.getUuid(), this.abstractDeviceOwner.getToken(), endPoint).build(); try { Response response = mHttpClient.newCall(request).execute(); JsonElement jsonElement = new JsonParser().parse(response.body().string()); JsonArray jsonArray = jsonElement.getAsJsonObject().getAsJsonArray(JSON_DEVICES); if (jsonArray.size() == 0) { return null; } return mGson.fromJson(jsonArray.get(0).toString(), clazz); } catch (Exception e) { throw new KnotException(e); } }
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 www. jav a2 s. c om*/ 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.j a v a 2 s . c om*/ 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 w w . j av a2s . c o 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; }
From source file:brooklyn.entity.mesos.task.marathon.MarathonTaskImpl.java
License:Apache License
@Override public MarathonTaskLocation createLocation(Map<String, ?> flags) { Entity entity = getRunningEntity(); MesosSlave slave = getMesosCluster().getMesosSlave(getHostname()); SubnetTier subnet = slave.getSubnetTier(); Boolean sdn = config().get(MesosCluster.SDN_ENABLE); // Configure the entity subnet LOG.info("Configuring entity {} via subnet {}", entity, subnet); entity.config().set(SubnetTier.PORT_FORWARDING_MANAGER, subnet.getPortForwardManager()); entity.config().set(SubnetTier.PORT_FORWARDER, subnet.getPortForwarder()); entity.config().set(SubnetTier.SUBNET_CIDR, Cidr.UNIVERSAL); DockerUtils.configureEnrichers(subnet, entity); // Lookup mapped ports List<Map.Entry<Integer, Integer>> portBindings = (List) flags.get("portBindings"); Map<Integer, String> tcpMappings = MutableMap.of(); Optional<JsonElement> application = getApplicationJson(); if (application.isPresent()) { JsonArray tasks = application.get().getAsJsonObject().get("app").getAsJsonObject().get("tasks") .getAsJsonArray();// ww w .j av a 2 s . c o m for (JsonElement each : tasks) { JsonElement ports = each.getAsJsonObject().get("ports"); if (ports != null && !ports.isJsonNull()) { JsonArray array = ports.getAsJsonArray(); if (array.size() > 0) { for (int i = 0; i < array.size(); i++) { int hostPort = array.get(i).getAsInt(); int containerPort = portBindings.get(i).getKey(); String address = sdn ? sensors().get(Attributes.SUBNET_ADDRESS) : getId(); String target = address + ":" + containerPort; tcpMappings.put(hostPort, target); if (containerPort == 22) { // XXX should be a better way? sensors().set(DockerAttributes.DOCKER_MAPPED_SSH_PORT, HostAndPort.fromParts(getHostname(), hostPort).toString()); } } } } } } else { throw new IllegalStateException( "Cannot retrieve application details for " + sensors().get(APPLICATION_ID)); } // Create our wrapper location around the task Boolean useSsh = config().get(DockerAttributes.DOCKER_USE_SSH); LocationSpec<MarathonTaskLocation> spec = LocationSpec.create(MarathonTaskLocation.class) .parent(getMarathonFramework().getDynamicLocation()).configure(flags) .configure(DynamicLocation.OWNER, this).configure("entity", getRunningEntity()) .configure(CloudLocationConfig.WAIT_FOR_SSHABLE, "false") .configure(SshMachineLocation.DETECT_MACHINE_DETAILS, useSsh) .configure(SshMachineLocation.TCP_PORT_MAPPINGS, tcpMappings).displayName(getShortName()); if (useSsh) { spec.configure(SshMachineLocation.SSH_HOST, getHostname()) .configure(SshMachineLocation.SSH_PORT, getSshPort()).configure("address", getAddress()) .configure(LocationConfigKeys.USER, "root") // TODO from slave .configure(LocationConfigKeys.PASSWORD, "p4ssw0rd").configure(SshTool.PROP_PASSWORD, "p4ssw0rd") .configure(SshTool.PROP_HOST, getHostname()).configure(SshTool.PROP_PORT, getSshPort()) .configure(LocationConfigKeys.PRIVATE_KEY_DATA, (String) null) // TODO used to generate authorized_keys .configure(LocationConfigKeys.PRIVATE_KEY_FILE, (String) null); } MarathonTaskLocation location = getManagementContext().getLocationManager().createLocation(spec); sensors().set(DYNAMIC_LOCATION, location); sensors().set(LOCATION_NAME, location.getId()); // Record port mappings LOG.debug("Recording port mappings for {} at {}: {}", new Object[] { entity, location, tcpMappings }); for (Integer hostPort : tcpMappings.keySet()) { HostAndPort target = HostAndPort.fromString(tcpMappings.get(hostPort)); subnet.getPortForwarder().openPortForwarding(location, target.getPort(), Optional.of(hostPort), Protocol.TCP, Cidr.UNIVERSAL); subnet.getPortForwarder().openFirewallPort(entity, hostPort, Protocol.TCP, Cidr.UNIVERSAL); LOG.debug("Forwarded port: {} => {}", hostPort, target.getPort()); } LOG.info("New task location {} created", location); if (useSsh) { DockerUtils.addExtraPublicKeys(entity, location); } return location; }
From source file:brooklyn.event.feed.http.JsonFunctions.java
License:Apache License
public static <T> Function<JsonElement, List<T>> forEach(final Function<JsonElement, T> func) { return new Function<JsonElement, List<T>>() { @Override/*from w w w . j a v a 2s. c o m*/ public List<T> apply(JsonElement input) { JsonArray array = (JsonArray) input; List<T> result = Lists.newArrayList(); for (int i = 0; i < array.size(); i++) { result.add(func.apply(array.get(i))); } return result; } }; }
From source file:brooklyn.event.feed.http.JsonFunctions.java
License:Apache License
@SuppressWarnings("unchecked") public static <T> Function<JsonElement, T> cast(final Class<T> expected) { return new Function<JsonElement, T>() { @Override/* w ww . j ava 2s . c o m*/ public T apply(JsonElement input) { if (input == null) { return (T) null; } else if (input.isJsonNull()) { return (T) null; } else if (expected == boolean.class || expected == Boolean.class) { return (T) (Boolean) input.getAsBoolean(); } else if (expected == char.class || expected == Character.class) { return (T) (Character) input.getAsCharacter(); } else if (expected == byte.class || expected == Byte.class) { return (T) (Byte) input.getAsByte(); } else if (expected == short.class || expected == Short.class) { return (T) (Short) input.getAsShort(); } else if (expected == int.class || expected == Integer.class) { return (T) (Integer) input.getAsInt(); } else if (expected == long.class || expected == Long.class) { return (T) (Long) input.getAsLong(); } else if (expected == float.class || expected == Float.class) { return (T) (Float) input.getAsFloat(); } else if (expected == double.class || expected == Double.class) { return (T) (Double) input.getAsDouble(); } else if (expected == BigDecimal.class) { return (T) input.getAsBigDecimal(); } else if (expected == BigInteger.class) { return (T) input.getAsBigInteger(); } else if (Number.class.isAssignableFrom(expected)) { // TODO Will result in a class-cast if it's an unexpected sub-type of Number not handled above return (T) input.getAsNumber(); } else if (expected == String.class) { return (T) input.getAsString(); } else if (expected.isArray()) { JsonArray array = input.getAsJsonArray(); Class<?> componentType = expected.getComponentType(); if (JsonElement.class.isAssignableFrom(componentType)) { JsonElement[] result = new JsonElement[array.size()]; for (int i = 0; i < array.size(); i++) { result[i] = array.get(i); } return (T) result; } else { Object[] result = (Object[]) Array.newInstance(componentType, array.size()); for (int i = 0; i < array.size(); i++) { result[i] = cast(componentType).apply(array.get(i)); } return (T) result; } } else { throw new IllegalArgumentException("Cannot cast json element to type " + expected); } } }; }
From source file:ca.ualberta.cmput301w14t08.geochan.json.ThreadCommentOfflineJsonConverter.java
License:Apache License
private void recursiveDeserialize(JsonObject object, String id, ArrayList<Comment> list) { JsonParser parser = new JsonParser(); JsonArray array = parser.parse(object.get(id).getAsString()).getAsJsonArray(); for (int i = 0; i < array.size(); ++i) { list.add(GsonHelper.getOfflineGson().fromJson(array.get(i), Comment.class)); }//from w w w . j a v a 2 s . c om for (Comment comment : list) { ArrayList<Comment> childList = new ArrayList<Comment>(); recursiveDeserialize(object, comment.getId(), childList); comment.setChildren(childList); } }
From source file:ca.ualberta.cs.unter.util.GeoPointConverter.java
License:Apache License
@Override public GeoPoint deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { final JsonArray array = json.getAsJsonArray(); final JsonElement lonElement = array.get(0); final JsonElement latElement = array.get(1); final Double lon = lonElement.getAsDouble(); final Double lat = latElement.getAsDouble(); return new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6)); }
From source file:catalog.CloudantUtil.java
License:Apache License
/** * Only keep _id and _rev for each document in the JSON array. *//*from w w w .j a v a2s . co m*/ public static JsonArray updateDocsWithOnlyIdAndRev(JsonArray docs) { for (int i = 0; i < docs.size(); i++) { JsonElement id = docs.get(i).getAsJsonObject().get("id"); JsonElement rev = docs.get(i).getAsJsonObject().get("rev"); docs.get(i).getAsJsonObject().add("_id", id); docs.get(i).getAsJsonObject().add("_rev", rev); } return docs; }