List of usage examples for com.google.gson JsonArray iterator
public Iterator<JsonElement> iterator()
From source file:org.indigo.heapsterprobe.HeapsterClient.java
License:Apache License
/** * This method accesses each metric available for a pod, in order to * monitor its current status./* ww w.j a va2 s . c o m*/ * @param podName String with the pod identifier. * @return Object with all the gathered metrics. */ public PodMetrics getPodMetrics(String podName) { // Separate Pod and Namespace String[] podSplit = podName.split("/"); String namespace = podSplit[0]; String pod = podSplit[1]; // List the metrics available for the pod String podUrl = baseHeapsterUrl + "/model/namespaces/" + namespace + "/pods/" + pod + "/"; System.out.println(podUrl + "metrics/"); WebTarget target = client.target(podUrl + "metrics/"); Invocation.Builder invocationBuilder = target.request(); Response response = invocationBuilder.get(); String message = response.readEntity(String.class); System.out.println(message); // Prepare the result variables int txErrors = -1; float txErrorsRate = -1.0f; int rxErrors = -1; float rxErrorsRate = -1.0f; float majorPageFaults = -1.0f; float pageFaults = -1.0f; int uptime = 0; // Get the metrics list checking all are available JsonElement jelement = new JsonParser().parse(message); JsonArray listArray = jelement.getAsJsonArray(); System.out.println("Number of metrics: " + listArray.size()); if (listArray.size() == 0) { return null; } HashMap<String, String> metricsList = new HashMap<String, String>(); Iterator<JsonElement> myIter = listArray.iterator(); while (myIter.hasNext()) { String currentMetric = myIter.next().getAsString(); System.out.println("Metric: " + currentMetric); String metricUrl = podUrl + "metrics/" + currentMetric + "/"; metricsList.put(currentMetric, metricUrl); } // Retrieve metrics // Retrieve Tx Errors if (metricsList.containsKey("network/tx_errors")) { JsonObject measurementObject = retrieveMetric(metricsList.get("network/tx_errors")); txErrors = measurementObject.get("value").getAsInt(); System.out.println("Tx Err Value: " + txErrors); } // Retrieve Tx Errors Rate if (metricsList.containsKey("network/tx_errors_rate")) { JsonObject measurementObject = retrieveMetric(metricsList.get("network/tx_errors_rate")); txErrorsRate = measurementObject.get("value").getAsFloat(); System.out.println("Tx Err Rate Value: " + txErrorsRate); } // Retrieve Rx Errors if (metricsList.containsKey("network/rx_errors")) { JsonObject measurementObject = retrieveMetric(metricsList.get("network/rx_errors")); rxErrors = measurementObject.get("value").getAsInt(); System.out.println("Rx Err Value: " + rxErrors); } // Retrieve Rx Errors Rate if (metricsList.containsKey("network/rx_errors_rate")) { JsonObject measurementObject = retrieveMetric(metricsList.get("network/rx_errors_rate")); rxErrorsRate = measurementObject.get("value").getAsFloat(); System.out.println("Rx Err Rate Value: " + rxErrorsRate); } // Retrieve Memory Major Fault Rate if (metricsList.containsKey("memory/major_page_faults_rate")) { JsonObject measurementObject = retrieveMetric(metricsList.get("memory/major_page_faults_rate")); majorPageFaults = measurementObject.get("value").getAsFloat(); System.out.println("Major Page Faults Rate Value: " + majorPageFaults); } // Retrieve Memory Fault Rate if (metricsList.containsKey("memory/page_faults_rate")) { JsonObject measurementObject = retrieveMetric(metricsList.get("memory/page_faults_rate")); pageFaults = measurementObject.get("value").getAsFloat(); System.out.println("Memory Page Faults Rate Value: " + pageFaults); } // Retrieve Uptime if (metricsList.containsKey("uptime")) { JsonObject measurementObject = retrieveMetric(metricsList.get("uptime")); uptime = measurementObject.get("value").getAsInt(); System.out.println("Uptime Value: " + uptime); } // Build result PodMetrics podResult = new PodMetrics(pod, namespace, txErrors, txErrorsRate, rxErrors, rxErrorsRate, majorPageFaults, pageFaults, uptime); return podResult; }
From source file:org.indigo.heapsterprobe.HeapsterClient.java
License:Apache License
/** * This method accesses each metric available for a container, in order to * monitor its current status./*from www .j a va 2 s . c o m*/ * @param podName String with the pod identifier. * @param namespace String with the namespace identifier * @param containerName String with the container identifier * @return Object with all the gathered metrics. */ public ContainerMetrics getContainerMetrics(String podName, String namespace, String containerName) { // List the metrics available for the pod String containerUrl = baseHeapsterUrl + "/model/namespaces/" + namespace + "/pods/" + podName + "/containers/" + containerName + "/"; System.out.println(containerUrl + "metrics/"); WebTarget target = client.target(containerUrl + "metrics/"); Invocation.Builder invocationBuilder = target.request(); Response response = invocationBuilder.get(); String message = response.readEntity(String.class); System.out.println(message); // Prepare the result variables float cpuUsageRate = -1.0f; long cpuUsage = -1L; int majorPageFaults = -1; int pageFaults = -1; float majorPageFaultsRate = -1.0f; float pageFaultsRate = -1.0f; int memoryUsage = -1; int workingSet = -1; int uptime = 0; // Get the metrics list checking all are available JsonElement jelement = new JsonParser().parse(message); JsonArray listArray = jelement.getAsJsonArray(); System.out.println("Number of metrics: " + listArray.size()); if (listArray.size() == 0) { return null; } HashMap<String, String> metricsList = new HashMap<String, String>(); Iterator<JsonElement> myIter = listArray.iterator(); while (myIter.hasNext()) { String currentMetric = myIter.next().getAsString(); System.out.println("Metric: " + currentMetric); String metricUrl = containerUrl + "metrics/" + currentMetric + "/"; metricsList.put(currentMetric, metricUrl); } // Retrieve metrics // Retrieve CPU Usage Rate if (metricsList.containsKey("cpu/usage_rate")) { JsonObject measurementObject = retrieveMetric(metricsList.get("cpu/usage_rate")); cpuUsageRate = measurementObject.get("value").getAsFloat(); System.out.println("CPU Usage Rate Value: " + cpuUsageRate); } // Retrieve CPU Usage if (metricsList.containsKey("cpu/usage")) { JsonObject measurementObject = retrieveMetric(metricsList.get("cpu/usage")); cpuUsage = measurementObject.get("value").getAsLong(); System.out.println("CPU USage Value: " + cpuUsage); } // Retrieve Memory Major Page Faults if (metricsList.containsKey("memory/major_page_faults")) { JsonObject measurementObject = retrieveMetric(metricsList.get("memory/major_page_faults")); majorPageFaults = measurementObject.get("value").getAsInt(); System.out.println("Memory Major Page Faults Value: " + majorPageFaults); } // Retrieve Memory Page Faults if (metricsList.containsKey("memory/page_faults")) { JsonObject measurementObject = retrieveMetric(metricsList.get("memory/page_faults")); pageFaults = measurementObject.get("value").getAsInt(); System.out.println("Memory Page Faults Value: " + pageFaults); } // Retrieve Memory Major Page Faults Rate if (metricsList.containsKey("memory/major_page_faults_rate")) { JsonObject measurementObject = retrieveMetric(metricsList.get("memory/major_page_faults_rate")); majorPageFaultsRate = measurementObject.get("value").getAsFloat(); System.out.println("Major Page Faults Rate Value: " + majorPageFaultsRate); } // Retrieve Memory Fault Rate if (metricsList.containsKey("memory/page_faults_rate")) { JsonObject measurementObject = retrieveMetric(metricsList.get("memory/page_faults_rate")); pageFaultsRate = measurementObject.get("value").getAsFloat(); System.out.println("Memory Page Faults Rate Value: " + pageFaultsRate); } // Retrieve Memory Fault Rate if (metricsList.containsKey("memory/usage")) { JsonObject measurementObject = retrieveMetric(metricsList.get("memory/usage")); memoryUsage = measurementObject.get("value").getAsInt(); System.out.println("Memory Usage Value: " + memoryUsage); } // Retrieve Working Set if (metricsList.containsKey("memory/working_set")) { JsonObject measurementObject = retrieveMetric(metricsList.get("memory/working_set")); workingSet = measurementObject.get("value").getAsInt(); System.out.println("Working Set Value: " + workingSet); } // Retrieve Uptime if (metricsList.containsKey("uptime")) { JsonObject measurementObject = retrieveMetric(metricsList.get("uptime")); uptime = measurementObject.get("value").getAsInt(); System.out.println("Uptime Value: " + uptime); } // Build result ContainerMetrics containerResult = new ContainerMetrics(containerName, cpuUsageRate, cpuUsage, majorPageFaults, pageFaults, majorPageFaultsRate, pageFaultsRate, memoryUsage, workingSet, uptime); return containerResult; }
From source file:org.indigo.occiprobe.openstack.CmdbClient.java
License:Apache License
/** * Using the created Jersey client, it invokes the CMDB REST API in * order to retrieve the full list of Cloud providers which are * currently available./*from www.j av a 2s. co m*/ * @return Strings array with the identifiers of the providers found. */ public String[] getProvidersList() { // Call to CMDB API WebTarget target = client.target(cmdbUrl + "/provider/list"); Invocation.Builder invocationBuilder = target.request(); Response response = invocationBuilder.get(); String message = response.readEntity(String.class); //System.out.println(message); // Retrieve the providers list JsonElement jelement = new JsonParser().parse(message); JsonObject parsedRes = jelement.getAsJsonObject(); JsonArray listArray = parsedRes.getAsJsonArray("rows"); ArrayList<String> providersList = new ArrayList<String>(); Iterator<JsonElement> myIter = listArray.iterator(); while (myIter.hasNext()) { JsonObject currentResource = myIter.next().getAsJsonObject(); String providerId = currentResource.get("id").getAsString(); providersList.add(providerId); } // Prepare the result providersList.trimToSize(); String[] resultList = new String[providersList.size()]; providersList.toArray(resultList); return resultList; }
From source file:org.indigo.occiprobe.openstack.CmdbClient.java
License:Apache License
/** * This method access the CMDB service in order to retrieve the available * data from a Cloud Provider (i.e. its location, provided services, etc.) * @param providerId Represents the identifier of the Cloud provider * @return An object with all the information retrieved *//* w w w .jav a2 s . c om*/ public CloudProviderInfo getProviderData(String providerId) { // Call to CMDB API String providerUrl = cmdbUrl + "/provider/id/" + providerId + "/has_many/services?include_docs=true"; WebTarget target = client.target(providerUrl); Invocation.Builder invocationBuilder = target.request(); Response response = invocationBuilder.get(); String message = response.readEntity(String.class); //System.out.println(message); // Retrieve the services list JsonElement jelement = new JsonParser().parse(message); JsonObject parsedRes = jelement.getAsJsonObject(); JsonArray listArray = parsedRes.getAsJsonArray("rows"); if (listArray.isJsonNull() || listArray.size() == 0) { return null; } String occiEndpoint = null; String keystoneEndpoint = null; int type = CloudProviderInfo.OPENNEBULA; boolean isMonitored = false; boolean isBeta = false; boolean isProduction = false; Iterator<JsonElement> myIter = listArray.iterator(); while (myIter.hasNext()) { JsonObject currentResource = myIter.next().getAsJsonObject(); JsonObject currentDoc = currentResource.get("doc").getAsJsonObject(); JsonObject currentData = currentDoc.get("data").getAsJsonObject(); String currentServiceType = currentData.get("service_type").getAsString(); String currentType = currentData.get("type").getAsString(); JsonElement jsonEndpoint = currentData.get("endpoint"); String currentEndpoint = null; if (jsonEndpoint == null || jsonEndpoint.isJsonNull()) { return null; } currentEndpoint = jsonEndpoint.getAsString(); if (currentServiceType.equalsIgnoreCase("eu.egi.cloud.vm-management.occi")) { occiEndpoint = currentEndpoint; JsonElement currentBeta = currentData.get("beta"); JsonElement currentProduction = currentData.get("in_production"); JsonElement currentMonitored = currentData.get("node_monitored"); // Retrieve the rest of info from the OCCI service if (currentBeta != null && currentBeta.getAsString().equalsIgnoreCase("Y")) { isBeta = true; } if (currentMonitored != null && currentMonitored.getAsString().equalsIgnoreCase("Y")) { isMonitored = true; } if (currentProduction != null && currentProduction.getAsString().equalsIgnoreCase("Y")) { isProduction = true; } } else if (currentServiceType.equalsIgnoreCase("eu.egi.cloud.vm-management.openstack")) { keystoneEndpoint = currentEndpoint; type = CloudProviderInfo.OPENSTACK; } } CloudProviderInfo myProvider = new CloudProviderInfo(providerId, occiEndpoint, keystoneEndpoint, type, isMonitored, isBeta, isProduction); return myProvider; }
From source file:org.jenkinsci.plugins.skytap.CreatePublishURLStep.java
License:Open Source License
private List<String> getVMIds(String confId) throws SkytapException { List<String> vmList = new ArrayList<String>(); // build request String reqUrl = "https://cloud.skytap.com/configurations/" + confId; HttpGet hg = SkytapUtils.buildHttpGetRequest(reqUrl, this.authCredentials); // extract vm ids String response = SkytapUtils.executeHttpRequest(hg); // check response for errors SkytapUtils.checkResponseForErrors(response); // get id and name of newly created template JsonParser parser = new JsonParser(); JsonElement je = parser.parse(response); JsonArray ja = (JsonArray) je.getAsJsonObject().get("vms"); Iterator iter = ja.iterator(); while (iter.hasNext()) { JsonElement vmElement = (JsonElement) iter.next(); String vmElementId = vmElement.getAsJsonObject().get("id").getAsString(); vmList.add(vmElementId);/*from w w w .j av a 2s .c om*/ JenkinsLogger.log("VM ID: " + vmElementId); } return vmList; }
From source file:org.jenkinsci.plugins.skytap.SkytapUtils.java
License:Open Source License
public static String getVMIDFromName(String confId, String vname, String authCredentials) throws SkytapException { // build url to retrieve vm object by name, so we can extract the id JenkinsLogger.log("Building request url ..."); StringBuilder sb = new StringBuilder("https://cloud.skytap.com/"); sb.append("configurations/"); sb.append(confId);/* ww w.j a v a2 s.c o m*/ sb.append("/vms"); String getVmIdURL = sb.toString(); // create request HttpGet hg = SkytapUtils.buildHttpGetRequest(getVmIdURL, authCredentials); // execute request String hgResponse = ""; hgResponse = SkytapUtils.executeHttpRequest(hg); // check for errors SkytapUtils.checkResponseForErrors(hgResponse); // find vm that matches name JsonParser parser = new JsonParser(); JsonElement je = parser.parse(hgResponse); JsonArray vmArray = je.getAsJsonArray(); JenkinsLogger.log("Iterating through vm array to match name: " + vname); Iterator iter = vmArray.iterator(); while (iter.hasNext()) { JsonObject vmObject = (JsonObject) iter.next(); JenkinsLogger.log(vmObject.toString()); String currentName = vmObject.get("name").getAsString(); JenkinsLogger.log("Found VM with name: " + currentName); if (currentName.equals(vname)) { JenkinsLogger.log("Name matched. Retrieving vm id."); String vid = vmObject.get("id").getAsString(); JenkinsLogger.log("VM ID: " + vid); return vid; } } // if we failed to match the name throw an exception throw new SkytapException("No vms were found matching name: " + vname); }
From source file:org.jenkinsci.plugins.skytap.SkytapUtils.java
License:Open Source License
/** * Utility method to extract errors, if any, from the Skytap json response, * and throw an exception which can be handled by the caller. * /* w w w . j av a 2 s. c o m*/ * @param response * @throws SkytapException */ public static void checkResponseForErrors(String response) throws SkytapException { // check skytap response body for errors JsonParser parser = new JsonParser(); JsonElement je = parser.parse(response); JsonObject jo = null; if (je.isJsonNull()) { return; } else if (je.isJsonArray()) { return; } je = parser.parse(response); jo = je.getAsJsonObject(); if (!(jo.has("error") || jo.has("errors"))) { return; } // handle case where skytap returns an array of errors if (jo.has("errors")) { String errorString = ""; JsonArray skytapErrors = (JsonArray) je.getAsJsonObject().get("errors"); Iterator itr = skytapErrors.iterator(); while (itr.hasNext()) { JsonElement errorElem = (JsonElement) itr.next(); String errMsg = errorElem.toString(); errorString += errMsg + "\n"; } throw new SkytapException(errorString); } if (jo.has("error")) { // handle case where 'error' element is null value if (jo.get("error").isJsonNull()) { return; } // handle case where 'error' element is a boolean OR quoted string if (jo.get("error").isJsonPrimitive()) { String error = jo.get("error").getAsString(); // handle boolean cases if (error.equals("false")) { return; } // TODO: find out where the error msg would be in this case if (error.equals("true")) { throw new SkytapException(error); } if (!error.equals("")) { throw new SkytapException(error); } } } }
From source file:org.jenkinsci.plugins.skytap.SkytapUtils.java
License:Open Source License
/** * Makes call to skytap to retrieve the id of a named project. * /*from ww w . jav a 2 s .com*/ * @param projName * @param authCredentials * @return projId */ public static String getProjectID(String projName, String authCredentials) { // build url StringBuilder sb = new StringBuilder("https://cloud.skytap.com"); sb.append("/projects"); // create http get HttpGet hg = SkytapUtils.buildHttpGetRequest(sb.toString(), authCredentials); // execute request String response; try { response = SkytapUtils.executeHttpRequest(hg); } catch (SkytapException e) { JenkinsLogger.error("Skytap Exception: " + e.getMessage()); return ""; } // response string will be a json array of all projects JsonParser parser = new JsonParser(); JsonElement je = parser.parse(response); JsonArray ja = je.getAsJsonArray(); Iterator itr = ja.iterator(); while (itr.hasNext()) { JsonElement projElement = (JsonElement) itr.next(); String projElementName = projElement.getAsJsonObject().get("name").getAsString(); if (projElementName.equals(projName)) { String projElementId = projElement.getAsJsonObject().get("id").getAsString(); return projElementId; } } JenkinsLogger.error("No project matching name \"" + projName + "\"" + " was found."); return ""; }
From source file:org.jenkinsci.plugins.skytap.SkytapUtils.java
License:Open Source License
/** * Executes a Skytap API call in order to get the network id of the network * whose name was provided by the user.//w w w .j ava 2 s.c om * * @param confId * @param netName * @return */ public static String getNetworkIdFromName(String confId, String netName, String authCredential) throws SkytapException { // build request url to get config info StringBuilder sb = new StringBuilder("https://cloud.skytap.com/"); sb.append("configurations/"); sb.append(confId); String reqUrl = sb.toString(); // create request HttpGet hg = SkytapUtils.buildHttpGetRequest(reqUrl, authCredential); // execute request String httpRespBody = ""; httpRespBody = SkytapUtils.executeHttpRequest(hg); SkytapUtils.checkResponseForErrors(httpRespBody); // parse the response, first get the array of networks JsonParser parser = new JsonParser(); JsonElement je = parser.parse(httpRespBody); JsonArray networkArray = (JsonArray) je.getAsJsonObject().get("networks"); JenkinsLogger.log("Searching configuration's networks for network: " + netName); Iterator itr = networkArray.iterator(); while (itr.hasNext()) { JsonElement networkElement = (JsonElement) itr.next(); String networkElementName = networkElement.getAsJsonObject().get("name").getAsString(); JenkinsLogger.log("Network Name: " + networkElementName); if (networkElementName.equals(netName)) { String networkElementId = networkElement.getAsJsonObject().get("id").getAsString(); JenkinsLogger.log("Network Name Matched."); JenkinsLogger.log("Network ID: " + networkElementId); return networkElementId; } } throw new SkytapException("No network matching name \"" + netName + "\"" + " is associated with configuration id " + confId + "."); }
From source file:org.kurento.room.client.KurentoRoomClient.java
License:Apache License
public Map<String, List<String>> joinRoom(String roomName, String userName, Boolean dataChannels) throws IOException { JsonObject params = new JsonObject(); params.addProperty(JOINROOM_ROOM_PARAM, roomName); params.addProperty(JOINROOM_USER_PARAM, userName); if (dataChannels != null) { params.addProperty(JOINROOM_DATACHANNELS_PARAM, dataChannels); }//w w w . ja va 2 s . co m JsonElement result = client.sendRequest(JOINROOM_METHOD, params); Map<String, List<String>> peers = new HashMap<String, List<String>>(); JsonArray jsonPeers = JsonRoomUtils.getResponseProperty(result, "value", JsonArray.class); if (jsonPeers.size() > 0) { Iterator<JsonElement> peerIt = jsonPeers.iterator(); while (peerIt.hasNext()) { JsonElement peer = peerIt.next(); String peerId = JsonRoomUtils.getResponseProperty(peer, JOINROOM_PEERID_PARAM, String.class); List<String> streams = new ArrayList<String>(); JsonArray jsonStreams = JsonRoomUtils.getResponseProperty(peer, JOINROOM_PEERSTREAMS_PARAM, JsonArray.class, true); if (jsonStreams != null) { Iterator<JsonElement> streamIt = jsonStreams.iterator(); while (streamIt.hasNext()) { streams.add(JsonRoomUtils.getResponseProperty(streamIt.next(), JOINROOM_PEERSTREAMID_PARAM, String.class)); } } peers.put(peerId, streams); } } return peers; }