List of usage examples for com.google.gson JsonArray iterator
public Iterator<JsonElement> iterator()
From source file:com.razza.apps.iosched.server.schedule.model.DataExtractor.java
License:Open Source License
public JsonObject extractFromDataSources(JsonDataSources sources) { usedTags = new HashSet<String>(); usedSpeakers = new HashSet<String>(); JsonObject result = new JsonObject(); result.add(OutputJsonKeys.MainTypes.rooms.name(), extractRooms(sources)); JsonArray speakers = extractSpeakers(sources); JsonArray tags = extractTags(sources); result.add(OutputJsonKeys.MainTypes.video_library.name(), extractVideoSessions(sources)); result.add(OutputJsonKeys.MainTypes.sessions.name(), extractSessions(sources)); // Remove tags that are not used on any session (b/14419126) Iterator<JsonElement> tagsIt = tags.iterator(); while (tagsIt.hasNext()) { JsonElement tag = tagsIt.next(); String tagName = DataModelHelper.get(tag.getAsJsonObject(), OutputJsonKeys.Tags.tag).getAsString(); if (!usedTags.contains(tagName)) { tagsIt.remove();/*w w w .jav a2 s . c o m*/ } } // Remove speakers that are not used on any session: Iterator<JsonElement> it = speakers.iterator(); while (it.hasNext()) { JsonElement el = it.next(); String id = DataModelHelper.get(el.getAsJsonObject(), OutputJsonKeys.Speakers.id).getAsString(); if (!usedSpeakers.contains(id)) { it.remove(); } } result.add(OutputJsonKeys.MainTypes.speakers.name(), speakers); result.add(OutputJsonKeys.MainTypes.tags.name(), tags); return result; }
From source file:com.samsung.sjs.constraintsolver.OperatorModel.java
License:Apache License
public OperatorModel() { Reader reader = new InputStreamReader(OperatorModel.class.getResourceAsStream("/operators.json")); JsonParser parser = new JsonParser(); JsonElement element = parser.parse(reader); if (element.isJsonArray()) { JsonArray jsa = element.getAsJsonArray(); for (Iterator<JsonElement> it = jsa.iterator(); it.hasNext();) { JsonElement operatorEntry = it.next(); if (operatorEntry.isJsonObject()) { JsonObject jso = operatorEntry.getAsJsonObject(); for (Entry<String, JsonElement> entry : jso.entrySet()) { String operatorName = entry.getKey(); JsonElement value = entry.getValue(); if (value.isJsonArray()) { JsonArray elements = value.getAsJsonArray(); for (Iterator<JsonElement> it2 = elements.iterator(); it2.hasNext();) { JsonElement element2 = it2.next(); if (element2.isJsonObject()) { JsonObject object = element2.getAsJsonObject(); JsonElement jsonElement = object.get("operand"); if (jsonElement != null) { String op = jsonElement.getAsString(); String result = object.get("result").getAsString(); String prefix = object.get("isprefix").getAsString(); boolean isPrefix; if (prefix.equals("true")) { isPrefix = true; } else if (prefix.equals("false")) { isPrefix = false; } else { throw new Error( "unrecognized value for prefix status of unary operator: " + prefix); }/*from w ww. j a va 2 s . c o m*/ if (!unaryOperatorMap.containsKey(operatorName)) { unaryOperatorMap.put(operatorName, new ArrayList<UnOpTypeCase>()); } List<UnOpTypeCase> cases = unaryOperatorMap.get(operatorName); cases.add(new UnOpTypeCase(toType(op), toType(result), isPrefix)); } else { String left = object.get("left").getAsString(); String right = object.get("right").getAsString(); String result = object.get("result").getAsString(); if (!infixOperatorMap.containsKey(operatorName)) { infixOperatorMap.put(operatorName, new ArrayList<InfixOpTypeCase>()); } List<InfixOpTypeCase> cases = infixOperatorMap.get(operatorName); cases.add(new InfixOpTypeCase(toType(left), toType(right), toType(result))); } } } } } } else { throw new Error("JsonObject expected"); } } } else { throw new Error("JsonArray expected"); } }
From source file:com.sap.dirigible.repository.ext.security.SecurityUpdater.java
License:Open Source License
private void executeAccessUpdate(Connection connection, String scDefinition, HttpServletRequest request) throws SQLException, IOException, SecurityException { JsonArray scDefinitionArray = parseAccess(scDefinition); for (Iterator<?> iter = scDefinitionArray.iterator(); iter.hasNext();) { JsonObject locationObject = (JsonObject) iter.next(); String locationName = locationObject.get(NODE_LOCATION).getAsString(); //$NON-NLS-1$ JsonArray rolesArray = locationObject.get(NODE_ROLES).getAsJsonArray(); //$NON-NLS-1$ for (Iterator<?> iter2 = rolesArray.iterator(); iter2.hasNext();) { JsonObject rolesObject = (JsonObject) iter2.next(); String roleName = rolesObject.get(NODE_ROLE).getAsString(); //$NON-NLS-1$ updateRole(locationName, roleName, request); }//from w ww . j a v a2 s . c om } }
From source file:com.savoirtech.json.processor.JsonComparisonProcessor.java
License:Apache License
/** * Walk all of the fields within the JSON arrays given, comparing each. * * @param pathToArray path to the array elements being compared. * @param templateArr template, or expected, array. * @param actualArr actual array./*from ww w.java 2 s . c om*/ * @return result of the comparison indicating whether the JSON matches, and providing a cause * description when they do no match. */ private JsonComparatorResult walkJsonArray(String pathToArray, JsonArray templateArr, JsonArray actualArr) { boolean match = true; String errorMessage = null; String errorPath = null; // // Make sure the arrays are the same size; otherwise, there's no need to check the contents. // if (templateArr.size() == actualArr.size()) { // // Loop over the array elements and compare each. // Iterator<JsonElement> actualArrayIterator = actualArr.iterator(); Iterator<JsonElement> templateArrayIterator = templateArr.iterator(); int position = 0; while ((match) && (actualArrayIterator.hasNext())) { JsonElement templateArrayEle = templateArrayIterator.next(); JsonElement actualArrayEle = actualArrayIterator.next(); String valuePath = pathToArray + "[" + position + "]"; // Perform a deep comparison of the array entries. JsonComparatorResult childResult = this.walkAndCompare(valuePath, templateArrayEle, actualArrayEle); match = childResult.isMatch(); errorMessage = childResult.getErrorMessage(); errorPath = childResult.getErrorPath(); position++; } } else { match = false; errorMessage = "array size mismatch: path='" + pathToArray + "'; actualSize=" + actualArr.size() + "; expectedSize=" + templateArr.size(); errorPath = pathToArray; } return new JsonComparatorResult(true, match, errorMessage, errorPath); }
From source file:com.savoirtech.json.rules.impl.ArrayAsSetRule.java
License:Apache License
private JsonComparatorResult compareArraysAsSets(String path, JsonArray expectedArray, JsonArray actualArray, RuleChildComparator childComparator) { boolean matches = true; String errorMessage = null;// w w w . ja v a 2 s.c om String errorPath = null; // First simply check the size; if they don't match, the sets cannot be equivalent. if (expectedArray.size() != actualArray.size()) { errorMessage = "set comparison: sizes do not match at path " + path + ": expectedCount=" + expectedArray.size() + "; actualCount=" + actualArray.size(); return new JsonComparatorResult(true, false, errorMessage, path); } // // For each actual value, find an expected value that matches. Then remove the expected value // from the remaining set of expected values, so each is only matched once. // Set<JsonElement> remainingSet = new HashSet<JsonElement>(); expectedArray.iterator().forEachRemaining(remainingSet::add); Iterator<JsonElement> actualElementIterator = actualArray.iterator(); int position = 0; while ((matches) && (!remainingSet.isEmpty())) { JsonElement nextActual = actualElementIterator.next(); // // Check whether this current actual element matches any in the remaining template set. // String accessor = "[" + position + "]"; String childPath = path + accessor; JsonElement matchingEle = this.compareOneSetEle(childPath, nextActual, remainingSet, childComparator); // // If matched, remove the matched element from the remaining set so it won't be matched again. // Otherwise, the comparison is a failure. // if (matchingEle != null) { remainingSet.remove(matchingEle); } else { matches = false; errorMessage = "set comparison: failed to find match for path " + childPath; errorPath = childPath; } position++; } return new JsonComparatorResult(true, matches, errorMessage, errorPath); }
From source file:com.simiacryptus.mindseye.network.util.PolynomialNetwork.java
License:Apache License
/** * To int array int [ ]./*ww w . j a va 2 s . co m*/ * * @param dims the dims * @return the int [ ] */ @Nonnull public static int[] toIntArray(@Nonnull final JsonArray dims) { @Nonnull final int[] x = new int[dims.size()]; int j = 0; for (@Nonnull final Iterator<JsonElement> i = dims.iterator(); i.hasNext();) { x[j++] = i.next().getAsInt(); } return x; }
From source file:com.steve_rizzo.uuidutils.Utils.java
License:Open Source License
public static void main(String[] args) { boolean isRunning = true; while (isRunning) { Scanner scanner = new Scanner(System.in); System.out.println("Would you like to see [CURRENT] or [PAST] info?"); String input = scanner.nextLine(); if (input.equalsIgnoreCase("current") || (input.equalsIgnoreCase("past"))) { switch (input.toUpperCase()) { case "CURRENT": System.out.println("Enter a user's name: "); input = scanner.nextLine(); try { String webData = readUrl("https://api.mojang.com/users/profiles/minecraft/" + input); Gson gson = new Gson(); JsonObject uuidData = gson.fromJson(webData, JsonObject.class); String uuid = uuidData.get("id").getAsString(); String name = uuidData.get("name").getAsString(); if ((webData != null) && (uuid != null)) { linebreaker();/*from w w w . j av a2s . co m*/ System.out.println("Name: " + name); System.out.println("UUID: " + uuid); linebreaker(); // Restart application. System.out.println("Restarting application ..."); Thread.sleep(1500); clearCommands(); } else { linebreaker(); System.out.println("ERROR: Data could not be found."); linebreaker(); // Restart application. System.out.println("Restarting application ..."); Thread.sleep(1500); clearCommands(); } } catch (Exception e) { e.printStackTrace(); // Restart application. System.out.println("Restarting application ..."); try { Thread.sleep(1500); } catch (InterruptedException ex) { ex.printStackTrace(); } clearCommands(); } break; case "PAST": System.out.println("Enter a user's name: "); input = scanner.nextLine(); try { String webData = readUrl("https://api.mojang.com/users/profiles/minecraft/" + input); Gson gson = new Gson(); JsonObject uuidData = gson.fromJson(webData, JsonObject.class); String uuid = ""; if (uuidData != null) { uuid = uuidData.get("id").getAsString(); } if (!uuid.equals("")) { String namesData = readUrl("https://api.mojang.com/user/profiles/" + uuid + "/names"); JsonArray pastNames = gson.fromJson(namesData, JsonArray.class); linebreaker(); System.out.println("Previous names of [" + input + "] - (" + uuid + ") " + "Are: \n"); int i = 0; Iterator<JsonElement> iterator = pastNames.iterator(); while (iterator.hasNext()) { i++; JsonElement element = gson.fromJson(iterator.next(), JsonElement.class); JsonObject nameObj = element.getAsJsonObject(); String name = nameObj.get("name").getAsString(); System.out.println(i + ". " + name + "\n"); } linebreaker(); // Restart application. System.out.println("Restarting application ..."); Thread.sleep(1500); clearCommands(); } else { sendErrorMessage("This player could not be found."); // Restart application. System.out.println("Restarting application ..."); Thread.sleep(1500); clearCommands(); } } catch (Exception e) { e.printStackTrace(); // Restart application. System.out.println("Restarting application ..."); try { Thread.sleep(1500); } catch (InterruptedException ex) { ex.printStackTrace(); } clearCommands(); } break; } } else { try { sendErrorMessage("You had to enter 'CURRENT' or 'PAST' to view details."); // Restart application. System.out.println("Restarting application ..."); Thread.sleep(1500); clearCommands(); } catch (Exception exc) { exc.printStackTrace(); // Restart application. System.out.println("Restarting application ..."); try { Thread.sleep(1500); } catch (InterruptedException ex) { ex.printStackTrace(); } clearCommands(); } } } }
From source file:com.synflow.cx.internal.instantiation.properties.InstancePropertiesChecker.java
License:Open Source License
/** * This method creates a clocks object from the entity's clocks and the instance's clocks. * /*from w ww . j a va 2s.c om*/ * @param entityClocks * array of entity's clocks * @param instanceClocks * array of instance's clocks * @return a clocks object */ private JsonObject makeClocksObject(JsonArray entityClocks, JsonArray instanceClocks) { JsonObject clocks = new JsonObject(); if (entityClocks.size() == 0) { // when the entity declares no clocks (combinational) // we associate no clocks return clocks; } Iterator<JsonElement> it = instanceClocks.iterator(); for (JsonElement clock : entityClocks) { String clockName = clock.getAsString(); if (it.hasNext()) { clocks.add(clockName, it.next()); } else { if (instanceClocks.size() == 1) { // support repetition of one clock clocks.add(clockName, instanceClocks.get(0)); } else { // not enough clocks given // this is verified and caught by validateClocks // with a !it.hasNext() test. break; } } } while (it.hasNext()) { // too many clocks given // the NO_CLOCK string is not a valid identifier, only used internally clocks.add(NO_CLOCK, it.next()); } return clocks; }
From source file:com.synflow.cx.internal.instantiation.properties.InstancePropertiesChecker.java
License:Open Source License
/** * Validates the given clocks object.//w w w .ja v a 2 s. c o m * * @param clocks * a clocks object * @param parentClocks * a list of parent clocks * @param entityClocks * a list of entity clocks */ private void validateClocks(JsonObject clocks, JsonArray parentClocks, JsonArray entityClocks) { int size = entityClocks.size(); int got = 0; Iterator<JsonElement> it = entityClocks.iterator(); for (Entry<String, JsonElement> pair : clocks.entrySet()) { String clockName = pair.getKey(); if (NO_CLOCK.equals(clockName)) { // no more clocks after this one => mismatch in number of clocks got = clocks.entrySet().size(); break; } if (!it.hasNext()) { // no more entity clocks => mismatch in number of clocks break; } // check we use a valid entity clock name String expected = it.next().getAsString(); if (!clockName.equals(expected)) { handler.addError(clocks, "given clock name '" + clockName + "' does not match entity's clock '" + expected + "'"); } // check value JsonElement value = pair.getValue(); if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isString()) { got++; if (!Iterables.contains(parentClocks, value)) { handler.addError(value, "given clock name '" + value.getAsString() + "' does not appear in parent's clocks " + parentClocks); } } else { handler.addError(value, "invalid clock value: " + value.toString()); } } if (got < size) { String msg = "not enough clocks given, expected " + size + " clocks, got " + got; handler.addError(clocks, msg); } else if (got > size) { String msg = "too many clocks given, expected " + size + " clocks, got " + got; handler.addError(clocks, msg); } }
From source file:com.tesla.framework.common.util.json.JSONHelper.java
License:Apache License
/** * @param element/* w w w.j a va2s . c om*/ * @return ?element???? * elementlist */ @NonNull public static List<JsonObject> toJsonObjects(@NonNull JsonElement element) { Preconditions.checkNotNull(element); if (element.isJsonNull()) return Collections.emptyList(); List<JsonObject> list = new ArrayList<>(); if (element.isJsonObject()) { list.add((JsonObject) element); return list; } if (element.isJsonArray()) { JsonArray arr = (JsonArray) element; Iterator<JsonElement> itr = arr.iterator(); while (itr.hasNext()) { JsonElement e = itr.next(); list.addAll(toJsonObjects(e)); } return list; } return list; }