List of usage examples for com.google.gson JsonArray size
public int size()
From source file:be.iminds.iot.dianne.nn.util.DianneJSONConverter.java
License:Open Source License
private static ModuleDTO parseModuleJSON(JsonObject jsonModule) { UUID id = UUID.fromString(jsonModule.get("id").getAsString()); String type = jsonModule.get("type").getAsString(); UUID[] next = null, prev = null; Map<String, String> properties = new HashMap<String, String>(); if (jsonModule.has("next")) { if (jsonModule.get("next").isJsonArray()) { JsonArray jsonNext = jsonModule.get("next").getAsJsonArray(); next = new UUID[jsonNext.size()]; int i = 0; Iterator<JsonElement> it = jsonNext.iterator(); while (it.hasNext()) { JsonElement e = it.next(); next[i++] = UUID.fromString(e.getAsString()); }/*from ww w. j ava 2 s. c om*/ } else { next = new UUID[1]; next[0] = UUID.fromString(jsonModule.get("next").getAsString()); } } if (jsonModule.has("prev")) { if (jsonModule.get("prev").isJsonArray()) { JsonArray jsonPrev = jsonModule.get("prev").getAsJsonArray(); prev = new UUID[jsonPrev.size()]; int i = 0; Iterator<JsonElement> it = jsonPrev.iterator(); while (it.hasNext()) { JsonElement e = it.next(); prev[i++] = UUID.fromString(e.getAsString()); } } else { prev = new UUID[1]; prev[0] = UUID.fromString(jsonModule.get("prev").getAsString()); } } // TODO this uses the old model where properties where just stored as flatmap for (Entry<String, JsonElement> property : jsonModule.entrySet()) { String key = property.getKey(); if (key.equals("id") || key.equals("type") || key.equals("prev") || key.equals("next")) { continue; // this is only for module-specific properties } properties.put(property.getKey(), property.getValue().getAsString()); } // TODO evolve to a separate "properties" item if (jsonModule.has("properties")) { JsonObject jsonProperties = jsonModule.get("properties").getAsJsonObject(); for (Entry<String, JsonElement> jsonProperty : jsonProperties.entrySet()) { String key = jsonProperty.getKey(); String value = jsonProperty.getValue().getAsString(); properties.put(key, value); } } ModuleDTO dto = new ModuleDTO(id, type, next, prev, properties); return dto; }
From source file:bisq.desktop.main.dao.governance.result.VoteResultView.java
License:Open Source License
private JsonElement getVotingHistoryJson() { JsonArray cyclesArray = new JsonArray(); sortedCycleListItemList.sorted(Comparator.comparing(CycleListItem::getCycleStartTime)) .forEach(cycleListItem -> { JsonObject cycleJson = new JsonObject(); // No domain data, taken from UI model // TODO move the data structure needed for UI to core and use as pure domain model and use that here cycleJson.addProperty("cycleIndex", cycleListItem.getCycleIndex()); cycleJson.addProperty("cycleDateTime", cycleListItem.getCycleDateTime(false)); cycleJson.addProperty("votesCount", cycleListItem.getNumVotesAsString()); cycleJson.addProperty("voteWeight", cycleListItem.getMeritAndStake()); cycleJson.addProperty("issuance", cycleListItem.getIssuance()); cycleJson.addProperty("startTime", cycleListItem.getCycleStartTime()); cycleJson.addProperty("totalAcceptedVotes", cycleListItem.getResultsOfCycle().getNumAcceptedVotes()); cycleJson.addProperty("totalRejectedVotes", cycleListItem.getResultsOfCycle().getNumRejectedVotes()); JsonArray proposalsArray = new JsonArray(); List<EvaluatedProposal> evaluatedProposals = cycleListItem.getResultsOfCycle() .getEvaluatedProposals(); evaluatedProposals.sort(Comparator.comparingLong(o -> o.getProposal().getCreationDate())); evaluatedProposals.forEach(evaluatedProp -> { JsonObject proposalJson = new JsonObject(); proposalJson.addProperty("isAccepted", evaluatedProp.isAccepted() ? "Accepted" : "Rejected"); // Proposal Proposal proposal = evaluatedProp.getProposal(); proposalJson.addProperty("proposal.name", proposal.getName()); proposalJson.addProperty("proposal.link", proposal.getLink()); proposalJson.addProperty("proposal.version", proposal.getVersion()); proposalJson.addProperty("proposal.creationDate", proposal.getCreationDate()); proposalJson.addProperty("proposal.txId", proposal.getTxId()); proposalJson.addProperty("proposal.txType", proposal.getTxType().name()); proposalJson.addProperty("proposal.quorumParam", proposal.getQuorumParam().name()); proposalJson.addProperty("proposal.thresholdParam", proposal.getThresholdParam().name()); proposalJson.addProperty("proposal.proposalType", proposal.getType().name()); if (proposal.getExtraDataMap() != null) proposalJson.addProperty("proposal.extraDataMap", proposal.getExtraDataMap().toString()); switch (proposal.getType()) { case UNDEFINED: break; case COMPENSATION_REQUEST: CompensationProposal compensationProposal = (CompensationProposal) proposal; proposalJson.addProperty("proposal.requestedBsq", compensationProposal.getRequestedBsq().getValue()); proposalJson.addProperty("proposal.bsqAddress", compensationProposal.getBsqAddress()); break; case REIMBURSEMENT_REQUEST: ReimbursementProposal reimbursementProposal = (ReimbursementProposal) proposal; proposalJson.addProperty("proposal.requestedBsq", reimbursementProposal.getRequestedBsq().getValue()); proposalJson.addProperty("proposal.bsqAddress", reimbursementProposal.getBsqAddress()); break; case CHANGE_PARAM: ChangeParamProposal changeParamProposal = (ChangeParamProposal) proposal; Param param = changeParamProposal.getParam(); proposalJson.addProperty("proposal.param", param.name()); proposalJson.addProperty("proposal.param.defaultValue", param.getDefaultValue()); proposalJson.addProperty("proposal.param.type", param.getParamType().name()); proposalJson.addProperty("proposal.param.maxDecrease", param.getMaxDecrease()); proposalJson.addProperty("proposal.param.maxIncrease", param.getMaxIncrease()); proposalJson.addProperty("proposal.paramValue", changeParamProposal.getParamValue()); break; case BONDED_ROLE: RoleProposal roleProposal = (RoleProposal) proposal; Role role = roleProposal.getRole(); proposalJson.addProperty("proposal.requiredBondUnit", roleProposal.getRequiredBondUnit()); proposalJson.addProperty("proposal.unlockTime", roleProposal.getUnlockTime()); proposalJson.addProperty("proposal.role.uid", role.getUid()); proposalJson.addProperty("proposal.role.name", role.getName()); proposalJson.addProperty("proposal.role.link", role.getLink()); BondedRoleType bondedRoleType = role.getBondedRoleType(); proposalJson.addProperty("proposal.bondedRoleType", bondedRoleType.name()); // bondedRoleType enum must not change anyway so we don't print it break; case CONFISCATE_BOND: ConfiscateBondProposal confiscateBondProposal = (ConfiscateBondProposal) proposal; proposalJson.addProperty("proposal.lockupTxId", confiscateBondProposal.getLockupTxId()); break; case GENERIC: // No extra fields break; case REMOVE_ASSET: RemoveAssetProposal removeAssetProposal = (RemoveAssetProposal) proposal; proposalJson.addProperty("proposal.tickerSymbol", removeAssetProposal.getTickerSymbol()); break; }//w w w.jav a 2 s.co m ProposalVoteResult proposalVoteResult = evaluatedProp.getProposalVoteResult(); proposalJson.addProperty("stakeOfAcceptedVotes", proposalVoteResult.getStakeOfAcceptedVotes()); proposalJson.addProperty("stakeOfRejectedVotes", proposalVoteResult.getStakeOfRejectedVotes()); proposalJson.addProperty("numAcceptedVotes", proposalVoteResult.getNumAcceptedVotes()); proposalJson.addProperty("numRejectedVotes", proposalVoteResult.getNumRejectedVotes()); proposalJson.addProperty("numIgnoredVotes", proposalVoteResult.getNumIgnoredVotes()); proposalJson.addProperty("numActiveVotes", proposalVoteResult.getNumActiveVotes()); proposalJson.addProperty("quorum", proposalVoteResult.getQuorum()); proposalJson.addProperty("threshold", proposalVoteResult.getThreshold()); // Not part of pure domain data, but useful to add here // required quorum and threshold for cycle for proposal type proposalJson.addProperty("requiredQuorum", proposalService.getRequiredQuorum(proposal).value); proposalJson.addProperty("requiredThreshold", proposalService.getRequiredThreshold(proposal)); // TODO provide better domain object as now we loop inside the loop. Use lookup map instead.... JsonArray votesArray = new JsonArray(); evaluatedProposals.stream() .filter(evaluatedProposal -> evaluatedProposal.getProposal().equals(proposal)) .forEach(evaluatedProposal -> { List<DecryptedBallotsWithMerits> decryptedVotesForCycle = cycleListItem .getResultsOfCycle().getDecryptedVotesForCycle(); // Make sure the votes are sorted so we can easier compare json files from different users decryptedVotesForCycle.sort( Comparator.comparing(DecryptedBallotsWithMerits::getBlindVoteTxId)); decryptedVotesForCycle.forEach(decryptedBallotsWithMerits -> { JsonObject voteJson = new JsonObject(); // Domain data of decryptedBallotsWithMerits voteJson.addProperty("hashOfBlindVoteList", Utilities.bytesAsHexString( decryptedBallotsWithMerits.getHashOfBlindVoteList())); voteJson.addProperty("blindVoteTxId", decryptedBallotsWithMerits.getBlindVoteTxId()); voteJson.addProperty("voteRevealTxId", decryptedBallotsWithMerits.getVoteRevealTxId()); voteJson.addProperty("stake", decryptedBallotsWithMerits.getStake()); voteJson.addProperty("voteWeight", decryptedBallotsWithMerits.getMerit(daoStateService)); String voteResult = decryptedBallotsWithMerits .getVote(evaluatedProp.getProposalTxId()) .map(vote -> vote.isAccepted() ? "Accepted" : "Rejected") .orElse("Ignored"); voteJson.addProperty("vote", voteResult); votesArray.add(voteJson); }); }); proposalJson.addProperty("numberOfVotes", votesArray.size()); proposalJson.add("votes", votesArray); proposalsArray.add(proposalJson); }); cycleJson.addProperty("numberOfProposals", proposalsArray.size()); cycleJson.add("proposals", proposalsArray); cyclesArray.add(cycleJson); }); return cyclesArray; }
From source file:blusunrize.immersiveengineering.common.crafting.RecipeFactoryShapedIngredient.java
@Override public IRecipe parse(JsonContext context, JsonObject json) { String group = JsonUtils.getString(json, "group", ""); Map<Character, Ingredient> ingMap = Maps.newHashMap(); for (Entry<String, JsonElement> entry : JsonUtils.getJsonObject(json, "key").entrySet()) { if (entry.getKey().length() != 1) throw new JsonSyntaxException("Invalid key entry: '" + entry.getKey() + "' is an invalid symbol (must be 1 character only)."); if (" ".equals(entry.getKey())) throw new JsonSyntaxException("Invalid key entry: ' ' is a reserved symbol."); ingMap.put(entry.getKey().toCharArray()[0], CraftingHelper.getIngredient(entry.getValue(), context)); }/*from w w w. j a v a 2 s . c o m*/ ingMap.put(' ', Ingredient.EMPTY); JsonArray patternJ = JsonUtils.getJsonArray(json, "pattern"); if (patternJ.size() == 0) throw new JsonSyntaxException("Invalid pattern: empty pattern not allowed"); String[] pattern = new String[patternJ.size()]; for (int x = 0; x < pattern.length; ++x) { String line = JsonUtils.getString(patternJ.get(x), "pattern[" + x + "]"); if (x > 0 && pattern[0].length() != line.length()) throw new JsonSyntaxException("Invalid pattern: each row must be the same width"); pattern[x] = line; } ShapedPrimer primer = new ShapedPrimer(); primer.width = pattern[0].length(); primer.height = pattern.length; primer.mirrored = JsonUtils.getBoolean(json, "mirrored", true); primer.input = NonNullList.withSize(primer.width * primer.height, Ingredient.EMPTY); Set<Character> keys = Sets.newHashSet(ingMap.keySet()); keys.remove(' '); int x = 0; for (String line : pattern) for (char chr : line.toCharArray()) { Ingredient ing = ingMap.get(chr); if (ing == null) throw new JsonSyntaxException( "Pattern references symbol '" + chr + "' but it's not defined in the key"); primer.input.set(x++, ing); keys.remove(chr); } if (!keys.isEmpty()) throw new JsonSyntaxException("Key defines symbols that aren't used in pattern: " + keys); ItemStack result = CraftingHelper.getItemStack(JsonUtils.getJsonObject(json, "result"), context); RecipeShapedIngredient recipe = new RecipeShapedIngredient( group.isEmpty() ? null : new ResourceLocation(group), result, primer); if (JsonUtils.getBoolean(json, "quarter_turn", false)) recipe.allowQuarterTurn(); if (JsonUtils.getBoolean(json, "eighth_turn", false)) recipe.allowEighthTurn(); if (JsonUtils.hasField(json, "copy_nbt")) { if (JsonUtils.isJsonArray(json, "copy_nbt")) { JsonArray jArray = JsonUtils.getJsonArray(json, "copy_nbt"); int[] array = new int[jArray.size()]; for (int i = 0; i < array.length; i++) array[i] = jArray.get(i).getAsInt(); recipe.setNBTCopyTargetRecipe(array); } else recipe.setNBTCopyTargetRecipe(JsonUtils.getInt(json, "copy_nbt")); if (JsonUtils.hasField(json, "copy_nbt_predicate")) recipe.setNBTCopyPredicate(JsonUtils.getString(json, "copy_nbt_predicate")); } return recipe; }
From source file:bmw.assigment.BMWAssigment.java
/** * Recursive method to populate the data extracted from the Json file * /*from w w w . j a v a 2 s. c om*/ * @param employee * @return */ public static AbstractEmployee populateSubordinate(JsonObject employee) { AbstractEmployee emp = null; if (employee.has("_subordinates")) { emp = new Manager(employee.get("_name").getAsString(), employee.get("_salary").getAsLong()); JsonArray array = employee.getAsJsonArray("_subordinates"); for (int i = 0; i < array.size(); i++) { emp.addEmployee(populateSubordinate(array.get(i).getAsJsonObject())); } } else { emp = new Employee(employee.get("_name").getAsString(), employee.get("_salary").getAsLong()); } return emp; }
From source file:br.com.eventick.api.Event.java
License:Open Source License
/** * Retorna a lista de participantes {@link Attendee} do evento * @return uma {@link List} de {@link Attendee} * @throws IOException//from w w w .j a va2 s . com * @throws InterruptedException * @throws ExecutionException */ public void setAttendees() throws IOException, InterruptedException, ExecutionException { String fetchURL = String.format("%s/%d/attendees", URL, this.id); String json = api.getRequests().get(fetchURL, this.getApi().getToken()); JsonObject jsonObject = api.getGson().fromJson(json, JsonElement.class).getAsJsonObject(); JsonArray jsonArray = jsonObject.get("attendees").getAsJsonArray(); Attendee att; int i = 0; for (; i < jsonArray.size(); i++) { att = this.api.getGson().fromJson(jsonArray.get(i), Attendee.class); this.attendees.add(att); } }
From source file:br.com.eventick.api.Event.java
License:Open Source License
public void setTickets() throws IOException, InterruptedException, ExecutionException { String fetchURL = String.format("%s/%d", URL, this.id); String json = api.getRequests().get(fetchURL, this.getApi().getToken()); JsonObject jsonObject = api.getGson().fromJson(json, JsonElement.class).getAsJsonObject(); JsonArray jsonArray = jsonObject.get("tickets").getAsJsonArray(); Ticket tick;/*from w ww . j a v a2s .c o m*/ int i = 0; for (; i < jsonArray.size(); i++) { tick = this.api.getGson().fromJson(jsonArray.get(i), Ticket.class); this.tickets.add(tick); } }
From source file:br.com.eventick.api.EventickAPI.java
License:Open Source License
/** * Retorna a colecao de eventos do usuario * @return//from w ww .j a v a2 s .c om * @throws IOException * @throws InterruptedException * @throws ExecutionException */ public List<Event> getMyEvents() throws IOException, InterruptedException, ExecutionException { List<Event> collection = new ArrayList<Event>(); String fetchURL = String.format("%s/events", URL); String json = requests.get(fetchURL, this.getToken()); JsonObject jsonObject = gson.fromJson(json, JsonElement.class).getAsJsonObject(); JsonArray jsonArray = jsonObject.get("events").getAsJsonArray(); Event eve; int i = 0; for (; i < jsonArray.size(); i++) { eve = gson.fromJson(jsonArray.get(i), Event.class); collection.add(eve); } return collection; }
From source file:br.org.cesar.knot.lib.connection.KnotSocketIo.java
License:Open Source License
/** * This method return a list devices of the specific owner * * @param typeThing Generic type of list. * @param query Query to find devices * @param callbackResult List of devices * @throws KnotException <p>/* w ww . ja v a 2 s. c o m*/ * @see <ahttps://meshblu-socketio.readme.io/docs/devices </a> */ public <T extends AbstractThingDevice> void getDeviceList(final KnotList<T> typeThing, JSONObject query, final Event<List<T>> callbackResult) throws KnotException, SocketNotConnected, InvalidParametersException { if (isSocketConnected() && isSocketRegistered()) { if (typeThing != null && callbackResult != null) { if (query == null) { query = new JSONObject(); } mSocket.emit(EVENT_GET_DEVICES, query, new Ack() { @Override public void call(Object... args) { List<T> result = null; try { JsonElement jsonElement = new JsonParser().parse(args[FIRST_EVENT_RECEIVED].toString()); JsonObject jsonObject = jsonElement.getAsJsonObject(); if (jsonObject.get(ERROR) != null && !jsonObject.get(ERROR).isJsonNull()) { callbackResult.onEventError(new KnotException(jsonObject.get(ERROR).toString())); return; } JsonArray jsonArray = jsonElement.getAsJsonObject().getAsJsonArray(DEVICES); if (jsonArray != null || jsonArray.size() > 0) { result = mGson.fromJson(jsonArray, typeThing); } else { result = mGson.fromJson(EMPTY_JSON, typeThing); } callbackResult.onEventFinish((List<T>) result); } catch (Exception e) { callbackResult.onEventError(new KnotException(e)); } } }); } else { throw new InvalidParametersException("Invalid parameters"); } } else { throw new SocketNotConnected("Socket not ready or connected"); } }
From source file:br.org.cesar.knot.lib.connection.KnotSocketIo.java
License:Open Source License
/** * Get all data of the specific device//from w w w . ja v a 2s .c o m * * @param type List of abstracts objects * @param uuid UUid of device * @param deviceToken token of the device * @param knotQueryData Date query * @param callbackResult Callback for this method * @throws InvalidParametersException * @throws SocketNotConnected */ public <T extends AbstractThingData> void getData(final KnotList<T> type, String uuid, String deviceToken, KnotQueryData knotQueryData, final Event<List<T>> callbackResult) throws InvalidParametersException, SocketNotConnected { if (isSocketConnected() && isSocketRegistered() && knotQueryData != null) { if (uuid != null && callbackResult != null) { JSONObject dataToSend = new JSONObject(); int maxNumberOfItem = -1; try { dataToSend.put(UUID, uuid); dataToSend.put(TOKEN, deviceToken); if (knotQueryData.getStartDate() != null) { dataToSend.put(DATE_START, DateUtils.getTimeStamp(knotQueryData.getStartDate())); } if (knotQueryData.getFinishDate() != null) { dataToSend.put(DATE_FINISH, DateUtils.getTimeStamp(knotQueryData.getFinishDate())); } if (knotQueryData.getLimit() > 0) { maxNumberOfItem = knotQueryData.getLimit(); } dataToSend.put(LIMIT, maxNumberOfItem); } catch (JSONException e) { callbackResult.onEventError(new KnotException()); } mSocket.emit(EVENT_GET_DATA, dataToSend, new Ack() { @Override public void call(Object... args) { if (args != null && args.length > 0) { List<T> result = null; JsonElement jsonElement = new JsonParser().parse(args[FIRST_EVENT_RECEIVED].toString()); JsonArray jsonArray = jsonElement.getAsJsonObject().getAsJsonArray(DATA); if (jsonArray != null && jsonArray.size() > 0) { result = mGson.fromJson(jsonArray.toString(), type); } else { result = mGson.fromJson(EMPTY_JSON, type); } callbackResult.onEventFinish(result); } else { callbackResult.onEventError(new KnotException()); } } }); } else { throw new InvalidParametersException("Invalid parameters"); } } else { throw new SocketNotConnected("Socket not ready or connected"); } }
From source file:br.org.cesar.knot.lib.connection.ThingApi.java
License:Open Source License
/** * Get a specific device from Meshblu instance. * * @param device the device identifier (uuid) * @param clazz The class for this device. Meshblu works with any type of objects and * it is necessary deserialize the return to a valid object. * Note: The class parameter should be a extension of {@link AbstractThingDevice} * @return an object based on the class parameter * @throws KnotException KnotException/* w w w . jav a 2 s .c om*/ */ public <T extends AbstractThingDevice> T getDevice(String device, Class<T> clazz) throws InvalidDeviceOwnerStateException, KnotException { // Check if the current state of device owner is valid if (!isValidDeviceOwner()) { throw new InvalidDeviceOwnerStateException("The device owner is invalid or null"); } // Get the specific device from meshblue instance final String endPoint = mEndPoint + DEVICE_PATH + device; Request request = generateBasicRequestBuild(this.abstractDeviceOwner.getUuid(), this.abstractDeviceOwner.getToken(), endPoint).build(); try { Response response = mHttpClient.newCall(request).execute(); JsonElement jsonElement = new JsonParser().parse(response.body().string()); JsonArray jsonArray = jsonElement.getAsJsonObject().getAsJsonArray(JSON_DEVICES); if (jsonArray.size() == 0) { return null; } return mGson.fromJson(jsonArray.get(0).toString(), clazz); } catch (Exception e) { throw new KnotException(e); } }