List of usage examples for com.google.gson JsonObject get
public JsonElement get(String memberName)
From source file:brooklyn.entity.monitoring.zabbix.ZabbixFeed.java
License:Apache License
@Override protected void preStart() { final Supplier<URI> baseUriProvider = getConfig(BASE_URI_PROVIDER); final Function<? super EntityLocal, String> uniqueHostnameGenerator = getConfig(UNIQUE_HOSTNAME_GENERATOR); final Integer groupId = getConfig(GROUP_ID); final Integer templateId = getConfig(TEMPLATE_ID); final Set<ZabbixPollConfig<?>> polls = getConfig(POLLS); log.info("starting zabbix feed for {}", entity); // TODO if supplier returns null, we may wish to defer initialization until url available? // TODO for https should we really trust all? final HttpClient httpClient = HttpTool.httpClientBuilder().trustAll() .clientConnectionManager(new ThreadSafeClientConnManager()) .reuseStrategy(new NoConnectionReuseStrategy()).uri(baseUriProvider.get()).build(); // Registration job, calls Zabbix host.create API final Callable<HttpToolResponse> registerJob = new Callable<HttpToolResponse>() { @Override// w ww . ja va 2s . com public HttpToolResponse call() throws Exception { if (!registered.get()) { // Find the first machine, if available Optional<Location> location = Iterables.tryFind(entity.getLocations(), Predicates.instanceOf(MachineLocation.class)); if (!location.isPresent()) { return null; // Do nothing until location is present } MachineLocation machine = (MachineLocation) location.get(); String host = uniqueHostnameGenerator.apply(entity); // Select address and port using port-forwarding if available String address = entity.getAttribute(Attributes.ADDRESS); Integer port = entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_PORT); if (machine instanceof SupportsPortForwarding) { Cidr management = entity.getConfig(BrooklynAccessUtils.MANAGEMENT_ACCESS_CIDR); HostAndPort forwarded = ((SupportsPortForwarding) machine).getSocketEndpointFor(management, port); address = forwarded.getHostText(); port = forwarded.getPort(); } // Fill in the JSON template and POST it byte[] body = JSON_HOST_CREATE .replace("{{token}}", entity.getConfig(ZabbixMonitored.ZABBIX_SERVER) .getAttribute(ZabbixServer.ZABBIX_TOKEN)) .replace("{{host}}", host).replace("{{ip}}", address) .replace("{{port}}", Integer.toString(port)) .replace("{{groupId}}", Integer.toString(groupId)) .replace("{{templateId}}", Integer.toString(templateId)) .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes(); return HttpTool.httpPost(httpClient, baseUriProvider.get(), ImmutableMap.of("Content-Type", "application/json"), body); } return null; } }; // The handler for the registration job PollHandler<? super HttpToolResponse> registrationHandler = new PollHandler<HttpToolResponse>() { @Override public void onSuccess(HttpToolResponse val) { if (registered.get() || val == null) { return; // Skip if we are registered already or no data from job } JsonObject response = HttpValueFunctions.jsonContents().apply(val).getAsJsonObject(); if (response.has("error")) { // Parse the JSON error object and log the message JsonObject error = response.get("error").getAsJsonObject(); String message = error.get("message").getAsString(); String data = error.get("data").getAsString(); log.warn("zabbix failed registering host - {}: {}", message, data); } else if (response.has("result")) { // Parse the JSON result object and save the hostId JsonObject result = response.get("result").getAsJsonObject(); String hostId = result.get("hostids").getAsJsonArray().get(0).getAsString(); // Update the registered status if not set if (registered.compareAndSet(false, true)) { entity.setAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID, hostId); log.info("zabbix registered host as id {}", hostId); } } else { throw new IllegalStateException(String .format("zabbix host registration returned invalid result: %s", response.toString())); } } @Override public boolean checkSuccess(HttpToolResponse val) { return (val.getResponseCode() == 200); } @Override public void onFailure(HttpToolResponse val) { log.warn("zabbix sever returned failure code: {}", val.getResponseCode()); } @Override public void onException(Exception exception) { log.warn("zabbix exception registering host", exception); } @Override public String toString() { return super.toString() + "[" + getDescription() + "]"; } @Override public String getDescription() { return "Zabbix rest poll"; } }; // Schedule registration attempt once per second getPoller().scheduleAtFixedRate(registerJob, registrationHandler, 1000l); // TODO make configurable // Create a polling job for each Zabbix metric for (final ZabbixPollConfig<?> config : polls) { Callable<HttpToolResponse> pollJob = new Callable<HttpToolResponse>() { @Override public HttpToolResponse call() throws Exception { if (registered.get()) { if (log.isTraceEnabled()) log.trace("zabbix polling {} for {}", entity, config); byte[] body = JSON_ITEM_GET .replace("{{token}}", entity.getConfig(ZabbixMonitored.ZABBIX_SERVER) .getAttribute(ZabbixServer.ZABBIX_TOKEN)) .replace("{{hostId}}", entity.getAttribute(ZabbixMonitored.ZABBIX_AGENT_HOSTID)) .replace("{{itemKey}}", config.getItemKey()) .replace("{{id}}", Integer.toString(id.incrementAndGet())).getBytes(); return HttpTool.httpPost(httpClient, baseUriProvider.get(), ImmutableMap.of("Content-Type", "application/json"), body); } else { throw new IllegalStateException("zabbix agent not yet registered"); } } }; // Schedule the Zabbix polling job AttributePollHandler<? super HttpToolResponse> pollHandler = new AttributePollHandler<HttpToolResponse>( config, entity, this); long minPeriod = Integer.MAX_VALUE; // TODO make configurable if (config.getPeriod() > 0) minPeriod = Math.min(minPeriod, config.getPeriod()); getPoller().scheduleAtFixedRate(pollJob, pollHandler, minPeriod); } }
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//from w w w. j a v a 2s .c o 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/* w w w .j a v a 2 s .co 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.event.feed.http.JsonFunctions.java
License:Apache License
/** as {@link #walk(Iterable))} but working with objects which {@link Maybe} contain {@link JsonElement}, * simply preserving a {@link Maybe#absent()} object if additional walks are requested upon it * (cf jquery) *//*from w ww . j a va 2s . co m*/ public static Function<Maybe<JsonElement>, Maybe<JsonElement>> walkM(final Iterable<String> elements) { return new Function<Maybe<JsonElement>, Maybe<JsonElement>>() { @Override public Maybe<JsonElement> apply(Maybe<JsonElement> input) { Maybe<JsonElement> curr = input; for (String element : elements) { if (curr.isAbsent()) return curr; JsonObject jo = curr.get().getAsJsonObject(); JsonElement currO = jo.get(element); if (currO == null) return Maybe.absent("No element '" + element + " in JSON, when walking " + elements); curr = Maybe.of(currO); } return curr; } }; }
From source file:brooklyn.networking.cloudstack.CloudstackNew40FeaturesClient.java
License:Apache License
public List<String> findVpcIdsNameMatchingRegex(String regex) throws InterruptedException { List<String> result = new ArrayList<String>(); JsonArray jr = listVpcsJson();//from ww w .j a v a 2 s .c o m if (jr == null) return result; Iterator<JsonElement> jvii = jr.iterator(); while (jvii.hasNext()) { JsonObject jvo = jvii.next().getAsJsonObject(); String name = jvo.get("name").getAsString(); if (name != null && name.matches(regex)) result.add(jvo.get("id").getAsString()); } LOG.debug("VPC's matching {}: {}, ", regex, result); return result; }
From source file:brooklyn.networking.cloudstack.CloudstackNew40FeaturesClient.java
License:Apache License
public String findVpcIdWithCidr(String cidr) { JsonArray jr = listVpcsJson();/*from w w w . j a v a2s. com*/ if (jr == null) return null; Iterator<JsonElement> jvii = jr.iterator(); List<String> cidrs = new ArrayList<String>(); while (jvii.hasNext()) { JsonObject jvo = jvii.next().getAsJsonObject(); String cidrV = jvo.get("cidr").getAsString(); if (cidrV != null && cidrV.equals(cidr)) { String vpcId = jvo.get("id").getAsString(); LOG.debug("found vpcId {} matching CIDR {}", vpcId, cidr); return vpcId; } cidrs.add(cidrV); } LOG.debug("Found VPC's with CIDR's {} but not {}", cidrs, cidr); return null; }
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 {// w w w .j a v a2 s .c om 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
/** * Create port-forward rule./*from w w w .j a v a 2s .c o m*/ * <p/> * like jclouds version, but takes the networkId which is mandatory for VPCs. * <p/> * Does <em>NOT</em> open any firewall. * * @return job id. */ public String createPortForwardRule(String networkId, String ipAddressId, Protocol protocol, int publicPort, String targetVmId, int privatePort) { // needed because jclouds doesn't support supplying tier ID (for VPC's) Multimap<String, String> params = ArrayListMultimap.create(); params.put("command", "createPortForwardingRule"); params.put("networkid", networkId); params.put("ipaddressid", ipAddressId); params.put("protocol", protocol.toString()); params.put("publicport", "" + publicPort); params.put("virtualmachineid", targetVmId); params.put("privateport", "" + privatePort); // params.put("openfirewall", "" + false); params.put("apiKey", this.apiKey); params.put("response", "json"); LOG.debug("createPortForwardingRule GET " + params); 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); // TODO does non-2xx response need to be handled separately ? JsonElement jr = json(response); LOG.debug("createPortForwardingRule GOT " + jr); try { JsonObject jobfields = jr.getAsJsonObject().entrySet().iterator().next().getValue().getAsJsonObject(); return 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 executing createPortForwardingRule(" + params + ")" + ": " + jr.toString()); } }
From source file:brooklyn.networking.cloudstack.CloudstackNew40FeaturesClient.java
License:Apache License
/** * Create port-forward rule for a VM.// w ww. j av a 2s.c o m * <p/> * Does <em>NOT</em> open any firewall. */ public String createPortForwardRuleForVm(String publicIpId, Protocol protocol, int publicPort, String targetVmId, int privatePort) { // needed because jclouds doesn't support CIDR // return cloudstackClient.getCloudstackGlobalClient().getFirewallClient(). // createPortForwardingRuleForVirtualMachine( // publicIpId, PortForwardingRule.Protocol.TCP, publicPort, targetVmId, privatePort). // getJobId(); Multimap<String, String> params = ArrayListMultimap.create(); params.put("command", "createPortForwardingRule"); params.put("ipaddressid", publicIpId); params.put("protocol", protocol.toString()); params.put("publicport", "" + publicPort); params.put("virtualmachineid", targetVmId); params.put("privateport", "" + privatePort); // params.put("openfirewall", "" + false); params.put("apiKey", this.apiKey); params.put("response", "json"); LOG.debug("createPortForwardingRule GET " + params); HttpRequest request = HttpRequest.builder().method("GET").endpoint(this.endpoint).addQueryParams(params) .addHeader("Accept", "application/json").build(); request = getQuerySigner().filter(request); request.getEndpoint().toString().replace("+", "%2B"); //request = request.toBuilder().endpoint(uriBuilder(request.getEndpoint()).query(decodedParams).build()).build(); HttpToolResponse response = HttpUtil.invoke(request); // TODO does non-2xx response need to be handled separately ? JsonElement jr = json(response); LOG.debug("createPortForwardingRule GOT " + jr); try { JsonObject jobfields = jr.getAsJsonObject().entrySet().iterator().next().getValue().getAsJsonObject(); return 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 executing createPortForwardingRule(" + params + ")" + ": " + jr.toString()); } }
From source file:brooklyn.networking.cloudstack.CloudstackNew40FeaturesClient.java
License:Apache License
public Maybe<String> findVpcIdFromNetworkId(final String networkId) { Multimap<String, String> params = ArrayListMultimap.create(); params.put("command", "listNetworks"); if (accAndDomain.isPresent()) { params.put("account", accAndDomain.get().account); params.put("domainid", accAndDomain.get().domainId); }//from ww w. java 2 s. 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 networks = json(response); LOG.debug("LIST NETWORKS\n" + pretty(networks)); //get the first network object Optional<JsonElement> matchingNetwork = Iterables.tryFind(networks.getAsJsonObject() .get("listnetworksresponse").getAsJsonObject().get("network").getAsJsonArray(), new Predicate<JsonElement>() { @Override public boolean apply(JsonElement jsonElement) { JsonObject contender = jsonElement.getAsJsonObject(); return contender.get("id").getAsString().equals(networkId); } }); if (matchingNetwork == null) { throw new NoSuchElementException("No network found matching " + networkId + "; networks: " + networks); } JsonElement vpcid = matchingNetwork.get().getAsJsonObject().get("vpcid"); if (vpcid == null) { return Maybe.absent("No vcpid for network " + networkId); } return Maybe.of(vpcid.getAsString()); }