List of usage examples for com.google.gson JsonElement getAsJsonObject
public JsonObject getAsJsonObject()
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 ww w . j a v a 2s .co m .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();/*w ww. ja v a 2 s. com*/ 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.monitoring.zabbix.ZabbixPollConfig.java
License:Apache License
public ZabbixPollConfig(AttributeSensor<T> sensor) { super(sensor); // Add onSuccess method to extract the last value of the item // FIXME Fix generics onSuccess((Function) HttpValueFunctions.chain(HttpValueFunctions.jsonContents(), new Function<JsonElement, JsonElement>() { @Override/*from w w w .ja v a2 s .com*/ public JsonElement apply(@Nullable JsonElement input) { Preconditions.checkNotNull(input, "JSON input"); return input.getAsJsonObject().get("result").getAsJsonArray().get(0).getAsJsonObject() .get("lastvalue"); } }, JsonFunctions.cast(getSensor().getType()))); }
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 ww w. j av a2s . c om 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/* w w w .j ava2s. c o 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
/** returns a function which traverses the supplied path of entries in a json object (maps of maps of maps...), * @throws NoSuchElementException if any path is not present as a key in that map */ public static Function<JsonElement, JsonElement> walk(final Iterable<String> elements) { // could do this instead, pointing at Maybe for this, and for walkN, but it's slightly less efficient // return Functionals.chain(MaybeFunctions.<JsonElement>wrap(), walkM(elements), MaybeFunctions.<JsonElement>get()); return new Function<JsonElement, JsonElement>() { @Override// w w w . ja va 2s .co m public JsonElement apply(JsonElement input) { JsonElement curr = input; for (String element : elements) { JsonObject jo = curr.getAsJsonObject(); curr = jo.get(element); if (curr == null) throw new NoSuchElementException( "No element '" + element + " in JSON, when walking " + elements); } return curr; } }; }
From source file:brooklyn.event.feed.http.JsonFunctions.java
License:Apache License
/** as {@link #walk(Iterable))} but if any element is not found it simply returns null */ public static Function<JsonElement, JsonElement> walkN(final Iterable<String> elements) { return new Function<JsonElement, JsonElement>() { @Override/*from ww w. jav a 2s.c o m*/ public JsonElement apply(JsonElement input) { JsonElement curr = input; for (String element : elements) { if (curr == null) return null; JsonObject jo = curr.getAsJsonObject(); curr = jo.get(element); } return curr; } }; }
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); }//from ww w . j a v a2s .co m 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:brooklyn.networking.cloudstack.CloudstackNew40FeaturesClient.java
License:Apache License
protected String waitForJobCompletion(int statusCode, InputStream payload, String message) throws InterruptedException { if (statusCode < 200 || statusCode >= 300) { String payloadStr = null; try {// ww w .jav a2s . co m payloadStr = Streams.readFullyString(payload); } catch (Exception e) { Exceptions.propagateIfFatal(e); LOG.debug("On HttpResponse failure, failed to get string payload; continuing with reporting error", e); } throw new RuntimeException( "Error " + statusCode + ": " + message + (payloadStr != null ? "; " + payloadStr : "")); } JsonElement jr = json(payload); LOG.debug(pretty(jr)); String responseId; String jobId; try { JsonObject jobfields = jr.getAsJsonObject().entrySet().iterator().next().getValue().getAsJsonObject(); JsonElement responseIdJson = jobfields.get("id"); responseId = responseIdJson != null ? responseIdJson.getAsString() : null; jobId = jobfields.get("jobid").getAsString(); } catch (NullPointerException | NoSuchElementException | IllegalStateException e) { // TODO Not good using exceptions for normal control flow; but easiest way to handle // problems in unexpected json structure. throw new IllegalStateException("Problem parsing job response: " + jr.toString()); } do { AsyncJob<Object> job = getAsyncJobClient().getAsyncJob(jobId); LOG.debug("waiting: " + job); if (job.hasFailed()) throw new IllegalStateException("Failed job: " + job); if (job.hasSucceed()) { Status status = job.getStatus(); if (Status.FAILED.equals(status)) throw new IllegalStateException("Failed job: " + job); if (Status.SUCCEEDED.equals(status)) return responseId; } Thread.sleep(1000); } while (true); }
From source file:brooklyn.networking.cloudstack.CloudstackNew40FeaturesClient.java
License:Apache License
public String getFirstVpcOfferingId() { Multimap<String, String> params = ArrayListMultimap.create(); params.put("command", "listVPCOfferings"); 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 offers = json(response); LOG.debug("LIST VPC OFFERS\n" + pretty(offers)); String id = offers.getAsJsonObject().get("listvpcofferingsresponse").getAsJsonObject().get("vpcoffering") .getAsJsonArray().get(0).getAsJsonObject().get("id").getAsString(); LOG.debug(" using first VPC offering ID: " + id); return id;/*from w w w . jav a2 s . c om*/ }