List of usage examples for com.google.gson JsonArray get
public JsonElement get(int i)
From source file:com.ibm.devops.dra.AbstractDevOpsAction.java
License:Open Source License
/** * Get a list of policies that belong to an org * @param token//from w w w. ja v a2s .c o m * @param orgName * @return */ public static ListBoxModel getPolicyList(String token, String orgName, String toolchainName, String environment, Boolean debug_mode) { // get all jenkins job ListBoxModel emptybox = new ListBoxModel(); emptybox.add("", "empty"); String url = choosePoliciesUrl(environment); try { url = url.replace("{org_name}", URLEncoder.encode(orgName, "UTF-8").replaceAll("\\+", "%20")); url = url.replace("{toolchain_name}", URLEncoder.encode(toolchainName, "UTF-8").replaceAll("\\+", "%20")); if (debug_mode) { LOGGER.info("GET POLICIES URL:" + url); } CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); httpGet = addProxyInformation(httpGet); httpGet.setHeader("Authorization", token); CloseableHttpResponse response = null; response = httpClient.execute(httpGet); String resStr = EntityUtils.toString(response.getEntity()); if (debug_mode) { LOGGER.info("RESPONSE FROM GET POLICIES URL:" + response.getStatusLine().toString()); } if (response.getStatusLine().toString().contains("200")) { // get 200 response JsonParser parser = new JsonParser(); JsonElement element = parser.parse(resStr); JsonArray jsonArray = element.getAsJsonArray(); ListBoxModel model = new ListBoxModel(); for (int i = 0; i < jsonArray.size(); i++) { JsonObject obj = jsonArray.get(i).getAsJsonObject(); String name = String.valueOf(obj.get("name")).replaceAll("\"", ""); model.add(name, name); } if (debug_mode) { LOGGER.info("POLICY LIST:" + model); LOGGER.info("#######################"); } return model; } else { if (debug_mode) { LOGGER.info("RETURNED STATUS CODE OTHER THAN 200. RESPONSE: " + response.getStatusLine().toString()); } return emptybox; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return emptybox; }
From source file:com.ibm.g11n.pipeline.client.ServiceAccount.java
License:Open Source License
/** * Returns an instance of ServiceAccount for a JsonArray in the VCAP_SERVICES environment. * <p>//from w w w .j a va 2s. c o m * This method is called from {@link #getInstanceByVcapServices(String, String)}. * * @param jsonArray * The candidate JSON array which may include valid credentials. * @param serviceInstanceName * The name of IBM Globalization Pipeline service instance, or null * designating the first available service instance. * @return An instance of ServiceAccount. This method returns null if no matching service * instance name was found (when serviceInstanceName is null), or no valid * credential data was found. */ private static ServiceAccount parseToServiceAccount(JsonArray jsonArray, String serviceInstanceName) { ServiceAccount account = null; for (int i = 0; i < jsonArray.size(); i++) { JsonObject gpObj = jsonArray.get(i).getAsJsonObject(); if (serviceInstanceName != null) { // When service instance name is specified, // this method returns only a matching entry JsonPrimitive name = gpObj.getAsJsonPrimitive("name"); if (name == null || !serviceInstanceName.equals(name.getAsString())) { continue; } } JsonObject credentials = gpObj.getAsJsonObject("credentials"); if (credentials == null) { continue; } JsonPrimitive jsonUrl = credentials.getAsJsonPrimitive("url"); JsonPrimitive jsonInstanceId = credentials.getAsJsonPrimitive("instanceId"); JsonPrimitive jsonUserId = credentials.getAsJsonPrimitive("userId"); JsonPrimitive jsonPassword = credentials.getAsJsonPrimitive("password"); if (jsonUrl != null && jsonInstanceId != null && jsonUserId != null & jsonPassword != null) { account = getInstance(jsonUrl.getAsString(), jsonInstanceId.getAsString(), jsonUserId.getAsString(), jsonPassword.getAsString()); logger.config("A ServiceAccount is created from VCAP_SERVICES: url=" + jsonUrl + ", instanceId=" + jsonInstanceId + ", userId=" + jsonUserId + ", password=***"); break; } } return account; }
From source file:com.ibm.g11n.pipeline.resfilter.GlobalizeJsResource.java
License:Open Source License
/** * The override of addBundleStrings is necessary because globalizejs treats arrays of strings * as a single long string, with each piece separated by a space, rather than treating it like * a real JSON array.// w w w. java2 s .c o m */ @Override protected int addBundleStrings(JsonObject obj, String keyPrefix, Bundle bundle, int sequenceNum) { for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { String key = entry.getKey(); JsonElement value = entry.getValue(); if (value.isJsonObject()) { sequenceNum = addBundleStrings(value.getAsJsonObject(), encodeResourceKey(keyPrefix, key, false), bundle, sequenceNum); } else if (value.isJsonArray()) { JsonArray ar = value.getAsJsonArray(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ar.size(); i++) { JsonElement arrayEntry = ar.get(i); if (arrayEntry.isJsonPrimitive() && arrayEntry.getAsJsonPrimitive().isString()) { if (i > 0) { sb.append(" "); // } sb.append(arrayEntry.getAsString()); } else { throw new IllegalResourceFormatException( "Arrays must contain only strings in a globalizejs resource."); } } sequenceNum++; bundle.addResourceString(encodeResourceKey(keyPrefix, key, true), sb.toString(), sequenceNum); } else if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) { throw new IllegalResourceFormatException("The value of JSON element " + key + " is not a string."); } else { sequenceNum++; bundle.addResourceString(encodeResourceKey(keyPrefix, key, true), value.getAsString(), sequenceNum); } } return sequenceNum; }
From source file:com.ibm.g11n.pipeline.resfilter.impl.GlobalizeJsResource.java
License:Open Source License
/** * The override of addBundleStrings is necessary because globalizejs treats arrays of strings * as a single long string, with each piece separated by a space, rather than treating it like * a real JSON array.//from www .java2 s .c o m */ @Override protected int addBundleStrings(JsonObject obj, String keyPrefix, LanguageBundleBuilder bb, int sequenceNum) throws ResourceFilterException { for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { String key = entry.getKey(); JsonElement value = entry.getValue(); if (value.isJsonObject()) { sequenceNum = addBundleStrings(value.getAsJsonObject(), encodeResourceKey(keyPrefix, key, false), bb, sequenceNum); } else if (value.isJsonArray()) { JsonArray ar = value.getAsJsonArray(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < ar.size(); i++) { JsonElement arrayEntry = ar.get(i); if (arrayEntry.isJsonPrimitive() && arrayEntry.getAsJsonPrimitive().isString()) { if (i > 0) { sb.append(" "); // } sb.append(arrayEntry.getAsString()); } else { throw new IllegalResourceFormatException( "Arrays must contain only strings in a globalizejs resource."); } } sequenceNum++; bb.addResourceString(encodeResourceKey(keyPrefix, key, true), sb.toString(), sequenceNum); } else if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) { throw new IllegalResourceFormatException("The value of JSON element " + key + " is not a string."); } else { sequenceNum++; bb.addResourceString(encodeResourceKey(keyPrefix, key, true), value.getAsString(), sequenceNum); } } return sequenceNum; }
From source file:com.ibm.g11n.pipeline.resfilter.impl.JsonResource.java
License:Open Source License
protected int addBundleStrings(JsonObject obj, String keyPrefix, LanguageBundleBuilder bb, int sequenceNum) throws ResourceFilterException { for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { String key = entry.getKey(); JsonElement value = entry.getValue(); if (value.isJsonObject()) { sequenceNum = addBundleStrings(value.getAsJsonObject(), encodeResourceKey(keyPrefix, key, false), bb, sequenceNum);/*w ww .j av a2 s.c o m*/ } else if (value.isJsonArray()) { JsonArray ar = value.getAsJsonArray(); for (int i = 0; i < ar.size(); i++) { JsonElement arrayEntry = ar.get(i); String arrayKey = encodeResourceKey(keyPrefix, key, false) + "[" + Integer.toString(i) + "]"; if (arrayEntry.isJsonPrimitive() && arrayEntry.getAsJsonPrimitive().isString()) { sequenceNum++; bb.addResourceString(ResourceString.with(arrayKey, arrayEntry.getAsString()) .sequenceNumber(sequenceNum)); } else { sequenceNum = addBundleStrings(arrayEntry.getAsJsonObject(), arrayKey, bb, sequenceNum); } } } else if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) { throw new IllegalResourceFormatException("The value of JSON element " + key + " is not a string."); } else { sequenceNum++; bb.addResourceString( ResourceString.with(encodeResourceKey(keyPrefix, key, true), value.getAsString()) .sequenceNumber(sequenceNum)); } } return sequenceNum; }
From source file:com.ibm.g11n.pipeline.resfilter.impl.JsonResource.java
License:Open Source License
@Override public void write(OutputStream outStream, LanguageBundle languageBundle, FilterOptions options) throws IOException, ResourceFilterException { // extracts key value pairs in original sequence order List<ResourceString> resStrings = languageBundle.getSortedResourceStrings(); JsonObject output = new JsonObject(); JsonObject top_level;// ww w.ja v a2 s . c o m if (this instanceof GlobalizeJsResource) { String resLanguageCode = languageBundle.getEmbeddedLanguageCode(); if (resLanguageCode == null || resLanguageCode.isEmpty()) { throw new ResourceFilterException( "Missing resource language code in the specified language bundle."); } top_level = new JsonObject(); top_level.add(resLanguageCode, output); } else { top_level = output; } for (ResourceString res : resStrings) { String key = res.getKey(); List<KeyPiece> keyPieces = splitKeyPieces(key); JsonElement current = output; for (int i = 0; i < keyPieces.size(); i++) { if (i + 1 < keyPieces.size()) { // There is structure under this // key piece if (current.isJsonObject()) { JsonObject currentObject = current.getAsJsonObject(); if (!currentObject.has(keyPieces.get(i).keyValue)) { if (keyPieces.get(i + 1).keyType == JsonToken.BEGIN_ARRAY) { currentObject.add(keyPieces.get(i).keyValue, new JsonArray()); } else { currentObject.add(keyPieces.get(i).keyValue, new JsonObject()); } } current = currentObject.get(keyPieces.get(i).keyValue); } else { JsonArray currentArray = current.getAsJsonArray(); Integer idx = Integer.valueOf(keyPieces.get(i).keyValue); for (int arrayIndex = currentArray.size(); arrayIndex <= idx; arrayIndex++) { currentArray.add(JsonNull.INSTANCE); } if (currentArray.get(idx).isJsonNull()) { if (keyPieces.get(i + 1).keyType == JsonToken.BEGIN_ARRAY) { currentArray.set(idx, new JsonArray()); } else { currentArray.set(idx, new JsonObject()); } } current = currentArray.get(idx); } } else { // This is the leaf node if (keyPieces.get(i).keyType == JsonToken.BEGIN_ARRAY) { JsonArray currentArray = current.getAsJsonArray(); Integer idx = Integer.valueOf(keyPieces.get(i).keyValue); JsonPrimitive e = new JsonPrimitive(res.getValue()); for (int arrayIndex = currentArray.size(); arrayIndex <= idx; arrayIndex++) { currentArray.add(JsonNull.INSTANCE); } current.getAsJsonArray().set(idx, e); } else { current.getAsJsonObject().addProperty(keyPieces.get(i).keyValue, res.getValue()); } } } } try (OutputStreamWriter writer = new OutputStreamWriter(new BufferedOutputStream(outStream), StandardCharsets.UTF_8)) { new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(top_level, writer); } }
From source file:com.ibm.gaas.ServiceAccount.java
License:Open Source License
/** * Returns an instance of ServiceAccount from the VCAP_SERVICES environment * variable. When <code>serviceInstanceName</code> is null, this method returns * a ServiceAccount for the first valid IBM Globlization service instance. * If <code>serviceInstanceName</code> is not null, this method look up a * matching service entry, and returns a ServiceAccount for the matching entry. * If <code>serviceInstanceName</code> is not null and there is no match, * this method returns null.//from w ww. j a v a 2 s.c o m * * @param serviceInstanceName * The name of the IBM Globalization service instance, or null * designating the first available service instance. * @return An instance of ServiceAccount for the specified service instance * name, or null. */ private static ServiceAccount getInstanceByVcapServices(String serviceInstanceName) { Map<String, String> env = System.getenv(); String vcapServices = env.get("VCAP_SERVICES"); if (vcapServices == null) { return null; } ServiceAccount account = null; try { JsonObject obj = new JsonParser().parse(vcapServices).getAsJsonObject(); JsonArray gaasArray = obj.getAsJsonArray(GAAS_SERVICE_NAME); if (gaasArray != null) { for (int i = 0; i < gaasArray.size(); i++) { JsonObject gaasEntry = gaasArray.get(i).getAsJsonObject(); if (serviceInstanceName != null) { // When service instance name is specified, // this method returns only a matching entry JsonPrimitive name = gaasEntry.getAsJsonPrimitive("name"); if (name == null || !serviceInstanceName.equals(name.getAsString())) { continue; } } JsonObject credentials = gaasEntry.getAsJsonObject("credentials"); if (credentials == null) { continue; } JsonPrimitive jsonUri = credentials.getAsJsonPrimitive("uri"); JsonPrimitive jsonApiKey = credentials.getAsJsonPrimitive("api_key"); if (jsonUri != null && jsonApiKey != null) { logger.info( "A ServiceAccount is created from VCAP_SERVICES: uri=" + jsonUri + ", api_key=***"); account = getInstance(jsonUri.getAsString(), jsonApiKey.getAsString()); break; } } } } catch (JsonParseException e) { // Fall through - will return null } return account; }
From source file:com.ibm.internal.iotf.devicemgmt.handler.DeviceUpdateRequestHandler.java
License:Open Source License
/** * This method handles all the update requests from IBM Watson IoT Platform *//*from ww w .j a va 2 s .c o m*/ @Override public void handleRequest(JsonObject jsonRequest) { final String METHOD = "handleRequest"; List<Resource> fireRequiredResources = new ArrayList<Resource>(); JsonArray fields = null; ResponseCode rc = ResponseCode.DM_UPDATE_SUCCESS; JsonObject response = new JsonObject(); JsonObject d = (JsonObject) jsonRequest.get("d"); if (d != null) { fields = (JsonArray) d.get("fields"); if (fields != null) { /** * update the fields in actual device object */ JsonArray resFields = new JsonArray(); for (int i = 0; i < fields.size(); i++) { JsonObject obj = (JsonObject) fields.get(i); if (obj.get("field") != null) { String key = obj.get("field").getAsString(); JsonObject value = (JsonObject) obj.get("value"); boolean success = false; try { Resource resource = getDMClient().getDeviceData().getResource(key); if (resource != null) { success = updateField(resource, value); fireRequiredResources.add(resource); } } catch (Exception e) { LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Exception in updating field " + key + " value " + value, e); if (e.getMessage() != null) response.add("message", new JsonPrimitive(e.getMessage())); } if (success == false) { resFields.add(new JsonPrimitive(key)); rc = ResponseCode.DM_NOT_FOUND; } } } if (resFields.size() != 0) { JsonObject json = new JsonObject(); json.add("fields", resFields); response.add("d", json); } } } response.add("rc", new JsonPrimitive(rc.getCode())); response.add("reqId", jsonRequest.get("reqId")); respond(response); // Lets fire the property change event now - this will notify the // device code if they are listening to Task task = this.new Task(fireRequiredResources); executor.execute(task); }
From source file:com.ibm.internal.iotf.devicemgmt.handler.ObserveRequestHandler.java
License:Open Source License
/** * Handles the observe request from IBM Watson IoT Platform */// ww w . j a v a 2s . c o m @Override protected void handleRequest(JsonObject jsonRequest) { JsonObject response = new JsonObject(); JsonArray responseArray = new JsonArray(); JsonObject d = (JsonObject) jsonRequest.get("d"); JsonArray fields = (JsonArray) d.get("fields"); for (int i = 0; i < fields.size(); i++) { JsonObject field = fields.get(i).getAsJsonObject(); String name = field.get("field").getAsString(); JsonObject fieldResponse = new JsonObject(); Resource resource = getDMClient().getDeviceData().getResource(name); if (resource != null) { resource.addPropertyChangeListener(Resource.ChangeListenerType.INTERNAL, this); fieldsMap.put(name, resource); } fieldResponse.addProperty("field", name); JsonElement value = resource.toJsonObject(); fieldResponse.add("value", value); responseMap.put(name, value); responseArray.add(fieldResponse); } JsonObject responseFileds = new JsonObject(); responseFileds.add("fields", responseArray); response.add("d", responseFileds); response.add("reqId", jsonRequest.get("reqId")); response.add("rc", new JsonPrimitive(ResponseCode.DM_SUCCESS.getCode())); respond(response); }
From source file:com.ibm.internal.iotf.devicemgmt.handler.ObserveRequestHandler.java
License:Open Source License
void cancel(JsonArray fields) { final String METHOD = "cancel"; LoggerUtility.fine(CLASS_NAME, METHOD, "Cancel observation for " + fields); for (int i = 0; i < fields.size(); i++) { JsonObject obj = (JsonObject) fields.get(i); String name = obj.get("field").getAsString(); Resource resource = fieldsMap.remove(name); if (null != resource) { resource.removePropertyChangeListener(this); responseMap.remove(name);/* w ww. jav a2s .c o m*/ } } }