List of usage examples for com.google.gson JsonElement getAsJsonArray
public JsonArray getAsJsonArray()
From source file:brooklyn.entity.mesos.framework.MesosFrameworkImpl.java
License:Apache License
@Override public void connectSensors() { Duration scanInterval = config().get(MesosCluster.SCAN_INTERVAL); HttpFeed.Builder taskScanBuilder = HttpFeed.builder().entity(this).period(scanInterval) .baseUri(config().get(MesosCluster.MESOS_URL)) .credentialsIfNotNull(config().get(MesosCluster.MESOS_USERNAME), config().get(MesosCluster.MESOS_PASSWORD)) .poll(HttpPollConfig.forSensor(MESOS_TASK_LIST).description("Scan Tasks") .suburl("/master/state.json").onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("frameworks"), new Function<JsonElement, List<String>>() { @Override public List<String> apply(JsonElement frameworks) { return scanTasks(frameworks.getAsJsonArray()); }/*from w w w.j a v a 2 s .c o m*/ })) .onFailureOrException(Functions.<List<String>>constant(null))); taskScan = taskScanBuilder.build(); }
From source file:brooklyn.entity.mesos.MesosClusterImpl.java
License:Apache License
public void connectSensors() { sensors().set(Attributes.MAIN_URI, URI.create(config().get(MESOS_URL))); HttpFeed.Builder httpFeedBuilder = HttpFeed.builder().entity(this).period(1, TimeUnit.MINUTES) .baseUri(sensors().get(Attributes.MAIN_URI)) .credentialsIfNotNull(config().get(MESOS_USERNAME), config().get(MESOS_PASSWORD)) .poll(HttpPollConfig.forSensor(SERVICE_UP).suburl("/master/health") .onSuccess(HttpValueFunctions.responseCodeEquals(200)) .onFailureOrException(Functions.constant(Boolean.FALSE))) .poll(HttpPollConfig.forSensor(CLUSTER_NAME).suburl("/master/state.json") .onSuccess(HttpValueFunctions.jsonContents("cluster", String.class)) .onFailureOrException(Functions.constant(""))) .poll(HttpPollConfig.forSensor(CLUSTER_ID).suburl("/master/state.json") .onSuccess(HttpValueFunctions.jsonContents("id", String.class)) .onFailureOrException(Functions.constant(""))) .poll(HttpPollConfig.forSensor(MESOS_VERSION).suburl("/master/state.json") .onSuccess(HttpValueFunctions.jsonContents("version", String.class)) .onFailureOrException(Functions.constant(""))) .poll(HttpPollConfig.forSensor(CPUS_TOTAL).suburl("/system/stats.json") .onSuccess(HttpValueFunctions.jsonContents("cpus_total", Integer.class)) .onFailureOrException(Functions.constant(-1))) .poll(HttpPollConfig.forSensor(LOAD_1MIN).suburl("/system/stats.json") .onSuccess(HttpValueFunctions.jsonContents("avg_load_1min", Double.class)) .onFailureOrException(Functions.constant(-1.0d))) .poll(HttpPollConfig.forSensor(LOAD_5MIN).suburl("/system/stats.json") .onSuccess(HttpValueFunctions.jsonContents("avg_load_5min", Double.class)) .onFailureOrException(Functions.constant(-1.0d))) .poll(HttpPollConfig.forSensor(LOAD_15MIN).suburl("/system/stats.json") .onSuccess(HttpValueFunctions.jsonContents("avg_load_15min", Double.class)) .onFailureOrException(Functions.constant(-1.0d))) .poll(HttpPollConfig.forSensor(MEMORY_FREE_BYTES).suburl("/system/stats.json") .onSuccess(HttpValueFunctions.jsonContents("mem_free_bytes", Long.class)) .onFailureOrException(Functions.constant(-1L))) .poll(HttpPollConfig.forSensor(MEMORY_TOTAL_BYTES).suburl("/system/stats.json") .onSuccess(HttpValueFunctions.jsonContents("mem_total_bytes", Long.class)) .onFailureOrException(Functions.constant(-1L))); httpFeed = httpFeedBuilder.build();/*from w w w . j ava 2 s . c o m*/ Duration scanInterval = config().get(SCAN_INTERVAL); HttpFeed.Builder scanBuilder = HttpFeed.builder().entity(this).period(scanInterval) .baseUri(sensors().get(Attributes.MAIN_URI)) .credentialsIfNotNull(config().get(MESOS_USERNAME), config().get(MESOS_PASSWORD)) .poll(HttpPollConfig.forSensor(MESOS_SLAVE_LIST).description("Scan Cluster Slaves") .suburl("/master/state.json").onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("slaves"), new Function<JsonElement, List<String>>() { @Override public List<String> apply(JsonElement slaves) { try { return scanSlaves(slaves.getAsJsonArray()); } catch (UnknownHostException e) { throw Exceptions.propagate(e); } } })) .onFailureOrException(Functions.<List<String>>constant(null))) .poll(HttpPollConfig.forSensor(MESOS_FRAMEWORK_LIST).description("Scan Cluster Frameworks") .suburl("/master/state.json").onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("frameworks"), new Function<JsonElement, List<String>>() { @Override public List<String> apply(JsonElement frameworks) { return scanFrameworks(frameworks.getAsJsonArray()); } })) .onFailureOrException(Functions.<List<String>>constant(null))); scanner = scanBuilder.build(); }
From source file:brooklyn.entity.mesos.task.marathon.MarathonTaskImpl.java
License:Apache License
@Override public void connectSensors() { // TODO If we are not "mesos.task.managed", then we are just guessing at the appId. We may get // it wrong. If it's wrong then our uri will always give 404. We should not mark the task as // "serviceUp=false", and we should not clear the TASK_ID (which was correctly set in // MesosFramework.scanTasks, which is where this task came from in the first place). // The new behaviour of showing it as healthy (and not clearing the taskId, which caused // another instance to be automatically added!) is better than it was, but it definitely // needs more attention. final boolean managed = Boolean.TRUE.equals(sensors().get(MANAGED)); String uri = Urls.mergePaths(getFramework().sensors().get(MarathonFramework.FRAMEWORK_URL), "/v2/apps", sensors().get(APPLICATION_ID), "tasks"); HttpFeed.Builder httpFeedBuilder = HttpFeed.builder().entity(this).period(2000, TimeUnit.MILLISECONDS) .baseUri(uri)//from w w w . j a v a 2 s . com .credentialsIfNotNull( config().get(MesosCluster.MESOS_USERNAME), config().get(MesosCluster.MESOS_PASSWORD)) .header("Accept", "application/json") .poll(new HttpPollConfig<Boolean>(SERVICE_UP).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, Boolean>() { @Override public Boolean apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); return tasks.size() == 1; } })) .onFailureOrException(Functions.constant(managed ? Boolean.FALSE : true))) .poll(new HttpPollConfig<Long>(TASK_STARTED_AT).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, Long>() { @Override public Long apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); for (JsonElement each : tasks) { JsonElement startedAt = each.getAsJsonObject().get("startedAt"); if (startedAt != null && !startedAt.isJsonNull()) { return Time.parseDate(startedAt.getAsString()).getTime(); } } return null; } })) .onFailureOrException(Functions.<Long>constant(-1L))) .poll(new HttpPollConfig<Long>(TASK_STAGED_AT).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, Long>() { @Override public Long apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); for (JsonElement each : tasks) { JsonElement stagedAt = each.getAsJsonObject().get("stagedAt"); if (stagedAt != null && !stagedAt.isJsonNull()) { return Time.parseDate(stagedAt.getAsString()).getTime(); } } return null; } })) .onFailureOrException(Functions.<Long>constant(-1L))) .poll(new HttpPollConfig<String>(Attributes.HOSTNAME).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, String>() { @Override public String apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); for (JsonElement each : tasks) { JsonElement host = each.getAsJsonObject().get("host"); if (host != null && !host.isJsonNull()) { return host.getAsString(); } } return null; } })) .onFailureOrException(Functions.<String>constant(null))) .poll(new HttpPollConfig<String>(TASK_ID).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, String>() { @Override public String apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); for (JsonElement each : tasks) { JsonElement id = each.getAsJsonObject().get("id"); if (id != null && !id.isJsonNull()) { return id.getAsString(); } } return null; } })) .onFailureOrException( (Function) Functions.<Object>constant(managed ? null : FeedConfig.UNCHANGED))) .poll(new HttpPollConfig<String>(Attributes.ADDRESS).suppressDuplicates(true) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walk("tasks"), new Function<JsonElement, String>() { @Override public String apply(JsonElement input) { JsonArray tasks = input.getAsJsonArray(); for (JsonElement each : tasks) { JsonElement host = each.getAsJsonObject().get("host"); if (host != null && !host.isJsonNull()) { try { return InetAddress.getByName(host.getAsString()) .getHostAddress(); } catch (UnknownHostException uhe) { Exceptions.propagate(uhe); } } } return null; } })) .onFailureOrException(Functions.<String>constant(null))); httpFeed = httpFeedBuilder.build(); }
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();//from ww w . ja va 2s. 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.entity.nosql.couchbase.CouchbaseClusterImpl.java
License:Apache License
public void createBucket(final Entity primaryNode, final String bucketName, final String bucketType, final Integer bucketPort, final Integer bucketRamSize, final Integer bucketReplica) { DynamicTasks.queueIfPossible(/*from w w w .j a v a 2s .co m*/ TaskBuilder.<Void>builder().name("Creating bucket " + bucketName).body(new Callable<Void>() { @Override public Void call() throws Exception { DependentConfiguration.waitInTaskForAttributeReady(CouchbaseClusterImpl.this, CouchbaseCluster.BUCKET_CREATION_IN_PROGRESS, Predicates.equalTo(false)); if (CouchbaseClusterImpl.this.resetBucketCreation.get() != null) { CouchbaseClusterImpl.this.resetBucketCreation.get().stop(); } setAttribute(CouchbaseCluster.BUCKET_CREATION_IN_PROGRESS, true); HostAndPort hostAndPort = BrooklynAccessUtils.getBrooklynAccessibleAddress(primaryNode, primaryNode.getAttribute(CouchbaseNode.COUCHBASE_WEB_ADMIN_PORT)); CouchbaseClusterImpl.this.resetBucketCreation.set(HttpFeed.builder() .entity(CouchbaseClusterImpl.this).period(500, TimeUnit.MILLISECONDS) .baseUri(String.format("http://%s/pools/default/buckets/%s", hostAndPort, bucketName)) .credentials(primaryNode.getConfig(CouchbaseNode.COUCHBASE_ADMIN_USERNAME), primaryNode.getConfig(CouchbaseNode.COUCHBASE_ADMIN_PASSWORD)) .poll(new HttpPollConfig<Boolean>(BUCKET_CREATION_IN_PROGRESS) .onSuccess(Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walkN("nodes"), new Function<JsonElement, Boolean>() { @Override public Boolean apply(JsonElement input) { // Wait until bucket has been created on all nodes and the couchApiBase element has been published (indicating that the bucket is useable) JsonArray servers = input.getAsJsonArray(); if (servers.size() != CouchbaseClusterImpl.this.getMembers() .size()) { return true; } for (JsonElement server : servers) { Object api = server.getAsJsonObject() .get("couchApiBase"); if (api == null || Strings.isEmpty(String.valueOf(api))) { return true; } } return false; } })) .onFailureOrException(new Function<Object, Boolean>() { @Override public Boolean apply(Object input) { if (input instanceof brooklyn.util.http.HttpToolResponse) { if (((brooklyn.util.http.HttpToolResponse) input) .getResponseCode() == 404) { return true; } } if (input instanceof Throwable) Exceptions.propagate((Throwable) input); throw new IllegalStateException( "Unexpected response when creating bucket:" + input); } })) .build()); // TODO: Bail out if bucket creation fails, to allow next bucket to proceed Entities.invokeEffectorWithArgs(CouchbaseClusterImpl.this, primaryNode, CouchbaseNode.BUCKET_CREATE, bucketName, bucketType, bucketPort, bucketRamSize, bucketReplica); DependentConfiguration.waitInTaskForAttributeReady(CouchbaseClusterImpl.this, CouchbaseCluster.BUCKET_CREATION_IN_PROGRESS, Predicates.equalTo(false)); if (CouchbaseClusterImpl.this.resetBucketCreation.get() != null) { CouchbaseClusterImpl.this.resetBucketCreation.get().stop(); } return null; } }).build()).orSubmitAndBlock(); }
From source file:brooklyn.entity.nosql.couchbase.CouchbaseNodeSshDriver.java
License:Apache License
private Iterable<String> getNodesHostAndPort() { Function<JsonElement, Iterable<String>> getNodesAsList = new Function<JsonElement, Iterable<String>>() { @Override//from w w w. jav a2 s . co m public Iterable<String> apply(JsonElement input) { if (input == null) { return Collections.emptyList(); } Collection<String> names = Lists.newArrayList(); JsonArray nodes = input.getAsJsonArray(); for (JsonElement element : nodes) { // NOTE: the 'hostname' element also includes the port names.add(element.getAsJsonObject().get("hostname").toString().replace("\"", "")); } return names; } }; HttpToolResponse nodesResponse = getApiResponse( String.format("http://%s:%s/pools/nodes", getHostname(), getWebPort())); return Functionals.chain(HttpValueFunctions.jsonContents(), JsonFunctions.walkN("nodes"), getNodesAsList) .apply(nodesResponse); }
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/*from w ww.ja va 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:brooklyn.networking.cloudstack.CloudstackNew40FeaturesClient.java
License:Apache License
protected JsonArray listVpcsJson() { Multimap<String, String> params = ArrayListMultimap.create(); params.put("command", "listVPCs"); if (accAndDomain.isPresent()) { params.put("account", accAndDomain.get().account); params.put("domainid", accAndDomain.get().domainId); }/*ww w .j a v a2s . c om*/ params.put("apiKey", this.apiKey); params.put("response", "json"); HttpRequest request = HttpRequest.builder().method("GET").endpoint(this.endpoint).addQueryParams(params) .addHeader("Accept", "application/json").build(); request = getQuerySigner().filter(request); HttpToolResponse response = HttpUtil.invoke(request); JsonElement jr = json(response); LOG.debug(pretty(jr)); JsonElement vpcs = jr.getAsJsonObject().get("listvpcsresponse").getAsJsonObject().get("vpc"); return vpcs == null ? null : vpcs.getAsJsonArray(); }
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:ca.uhn.fhir.jpa.util.jsonpatch.CopyOperation.java
License:Apache License
@Override public JsonElement apply(JsonElement original) { JsonElement result = duplicate(original); JsonElement item = path.head().navigate(result); JsonElement data = mySourcePath.head().navigate(original); if (item.isJsonObject()) { item.getAsJsonObject().add(path.tail(), data); } else if (item.isJsonArray()) { JsonArray array = item.getAsJsonArray(); int index = (path.tail().equals("-")) ? array.size() : Integer.valueOf(path.tail()); List<JsonElement> temp = new ArrayList<JsonElement>(); Iterator<JsonElement> iter = array.iterator(); while (iter.hasNext()) { JsonElement stuff = iter.next(); iter.remove();/*ww w . j a v a 2 s. co m*/ temp.add(stuff); } temp.add(index, data); for (JsonElement stuff : temp) { array.add(stuff); } } return result; }