List of usage examples for com.google.gson JsonObject getAsJsonPrimitive
public JsonPrimitive getAsJsonPrimitive(String memberName)
From source file:org.apache.fineract.portfolio.loanaccount.service.LoanChargeAssembler.java
License:Apache License
public Set<LoanCharge> fromParsedJson(final JsonElement element, Set<LoanDisbursementDetails> disbursementDetails) { JsonArray jsonDisbursement = this.fromApiJsonHelper.extractJsonArrayNamed("disbursementData", element); List<Long> disbursementChargeIds = new ArrayList<>(); if (jsonDisbursement != null && jsonDisbursement.size() > 0) { for (int i = 0; i < jsonDisbursement.size(); i++) { final JsonObject jsonObject = jsonDisbursement.get(i).getAsJsonObject(); if (jsonObject != null && jsonObject.getAsJsonPrimitive(LoanApiConstants.loanChargeIdParameterName) != null) { String chargeIds = jsonObject.getAsJsonPrimitive(LoanApiConstants.loanChargeIdParameterName) .getAsString();/*from ww w . ja v a2s.co m*/ if (chargeIds != null) { if (chargeIds.indexOf(",") != -1) { String[] chargeId = chargeIds.split(","); for (String loanChargeId : chargeId) { disbursementChargeIds.add(Long.parseLong(loanChargeId)); } } else { disbursementChargeIds.add(Long.parseLong(chargeIds)); } } } } } final Set<LoanCharge> loanCharges = new HashSet<>(); final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element); final Integer numberOfRepayments = this.fromApiJsonHelper .extractIntegerWithLocaleNamed("numberOfRepayments", element); final Long productId = this.fromApiJsonHelper.extractLongNamed("productId", element); final LoanProduct loanProduct = this.loanProductRepository.findOne(productId); if (loanProduct == null) { throw new LoanProductNotFoundException(productId); } final boolean isMultiDisbursal = loanProduct.isMultiDisburseLoan(); LocalDate expectedDisbursementDate = null; if (element.isJsonObject()) { final JsonObject topLevelJsonElement = element.getAsJsonObject(); final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement); final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); if (topLevelJsonElement.has("charges") && topLevelJsonElement.get("charges").isJsonArray()) { final JsonArray array = topLevelJsonElement.get("charges").getAsJsonArray(); for (int i = 0; i < array.size(); i++) { final JsonObject loanChargeElement = array.get(i).getAsJsonObject(); final Long id = this.fromApiJsonHelper.extractLongNamed("id", loanChargeElement); final Long chargeId = this.fromApiJsonHelper.extractLongNamed("chargeId", loanChargeElement); final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalNamed("amount", loanChargeElement, locale); final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerNamed("chargeTimeType", loanChargeElement, locale); final Integer chargeCalculationType = this.fromApiJsonHelper .extractIntegerNamed("chargeCalculationType", loanChargeElement, locale); final LocalDate dueDate = this.fromApiJsonHelper.extractLocalDateNamed("dueDate", loanChargeElement, dateFormat, locale); final Integer chargePaymentMode = this.fromApiJsonHelper .extractIntegerNamed("chargePaymentMode", loanChargeElement, locale); if (id == null) { final Charge chargeDefinition = this.chargeRepository .findOneWithNotFoundDetection(chargeId); if (chargeDefinition.isOverdueInstallment()) { final String defaultUserMessage = "Installment charge cannot be added to the loan."; throw new LoanChargeCannotBeAddedException("loanCharge", "overdue.charge", defaultUserMessage, null, chargeDefinition.getName()); } ChargeTimeType chargeTime = null; if (chargeTimeType != null) { chargeTime = ChargeTimeType.fromInt(chargeTimeType); } ChargeCalculationType chargeCalculation = null; if (chargeCalculationType != null) { chargeCalculation = ChargeCalculationType.fromInt(chargeCalculationType); } ChargePaymentMode chargePaymentModeEnum = null; if (chargePaymentMode != null) { chargePaymentModeEnum = ChargePaymentMode.fromInt(chargePaymentMode); } if (!isMultiDisbursal) { final LoanCharge loanCharge = LoanCharge.createNewWithoutLoan(chargeDefinition, principal, amount, chargeTime, chargeCalculation, dueDate, chargePaymentModeEnum, numberOfRepayments); loanCharges.add(loanCharge); } else { if (topLevelJsonElement.has("disbursementData") && topLevelJsonElement.get("disbursementData").isJsonArray()) { final JsonArray disbursementArray = topLevelJsonElement.get("disbursementData") .getAsJsonArray(); if (disbursementArray.size() > 0) { JsonObject disbursementDataElement = disbursementArray.get(0).getAsJsonObject(); expectedDisbursementDate = this.fromApiJsonHelper.extractLocalDateNamed( LoanApiConstants.disbursementDateParameterName, disbursementDataElement, dateFormat, locale); } } if (ChargeTimeType.DISBURSEMENT.getValue() .equals(chargeDefinition.getChargeTimeType())) { for (LoanDisbursementDetails disbursementDetail : disbursementDetails) { LoanTrancheDisbursementCharge loanTrancheDisbursementCharge = null; if (chargeDefinition.isPercentageOfApprovedAmount() && disbursementDetail.expectedDisbursementDateAsLocalDate() .equals(expectedDisbursementDate)) { final LoanCharge loanCharge = LoanCharge.createNewWithoutLoan( chargeDefinition, principal, amount, chargeTime, chargeCalculation, dueDate, chargePaymentModeEnum, numberOfRepayments); loanCharges.add(loanCharge); loanTrancheDisbursementCharge = new LoanTrancheDisbursementCharge( loanCharge, disbursementDetail); loanCharge .updateLoanTrancheDisbursementCharge(loanTrancheDisbursementCharge); } else { if (disbursementDetail.expectedDisbursementDateAsLocalDate() .equals(expectedDisbursementDate)) { final LoanCharge loanCharge = LoanCharge.createNewWithoutLoan( chargeDefinition, disbursementDetail.principal(), amount, chargeTime, chargeCalculation, disbursementDetail.expectedDisbursementDateAsLocalDate(), chargePaymentModeEnum, numberOfRepayments); loanCharges.add(loanCharge); loanTrancheDisbursementCharge = new LoanTrancheDisbursementCharge( loanCharge, disbursementDetail); loanCharge.updateLoanTrancheDisbursementCharge( loanTrancheDisbursementCharge); } } } } else if (ChargeTimeType.TRANCHE_DISBURSEMENT.getValue() .equals(chargeDefinition.getChargeTimeType())) { LoanTrancheDisbursementCharge loanTrancheDisbursementCharge = null; for (LoanDisbursementDetails disbursementDetail : disbursementDetails) { if (ChargeTimeType.TRANCHE_DISBURSEMENT.getValue() .equals(chargeDefinition.getChargeTimeType())) { final LoanCharge loanCharge = LoanCharge.createNewWithoutLoan( chargeDefinition, disbursementDetail.principal(), amount, chargeTime, chargeCalculation, disbursementDetail.expectedDisbursementDateAsLocalDate(), chargePaymentModeEnum, numberOfRepayments); loanCharges.add(loanCharge); loanTrancheDisbursementCharge = new LoanTrancheDisbursementCharge( loanCharge, disbursementDetail); loanCharge .updateLoanTrancheDisbursementCharge(loanTrancheDisbursementCharge); } } } else { final LoanCharge loanCharge = LoanCharge.createNewWithoutLoan(chargeDefinition, principal, amount, chargeTime, chargeCalculation, dueDate, chargePaymentModeEnum, numberOfRepayments); loanCharges.add(loanCharge); } } } else { final Long loanChargeId = id; final LoanCharge loanCharge = this.loanChargeRepository.findOne(loanChargeId); if (disbursementChargeIds.contains(loanChargeId) && loanCharge == null) { // throw new // LoanChargeNotFoundException(loanChargeId); } if (loanCharge != null) { loanCharge.update(amount, dueDate, numberOfRepayments); loanCharges.add(loanCharge); } } } } } return loanCharges; }
From source file:org.apache.nifi.stateless.core.StatelessFlow.java
License:Apache License
public static StatelessFlow createAndEnqueueFromJSON(final JsonObject args, final ClassLoader systemClassLoader, final File narWorkingDir) throws InitializationException, IOException, ProcessorInstantiationException, NiFiRegistryException { if (args == null) { throw new IllegalArgumentException("Flow arguments can not be null"); }//from w w w . j av a 2 s .c o m System.out.println("Running flow from json: " + args.toString()); if (!args.has(REGISTRY) || !args.has(BUCKETID) || !args.has(FLOWID)) { throw new IllegalArgumentException( "The following parameters must be provided: " + REGISTRY + ", " + BUCKETID + ", " + FLOWID); } final String registryurl = args.getAsJsonPrimitive(REGISTRY).getAsString(); final String bucketID = args.getAsJsonPrimitive(BUCKETID).getAsString(); final String flowID = args.getAsJsonPrimitive(FLOWID).getAsString(); int flowVersion = -1; if (args.has(FLOWVERSION)) { flowVersion = args.getAsJsonPrimitive(FLOWVERSION).getAsInt(); } boolean materializeContent = true; if (args.has(MATERIALIZECONTENT)) { materializeContent = args.getAsJsonPrimitive(MATERIALIZECONTENT).getAsBoolean(); } final List<String> failurePorts = new ArrayList<>(); if (args.has(FAILUREPORTS)) { args.getAsJsonArray(FAILUREPORTS).forEach(port -> failurePorts.add(port.getAsString())); } final SSLContext sslContext = getSSLContext(args); final VersionedFlowSnapshot snapshot = new RegistryUtil(registryurl, sslContext).getFlowByID(bucketID, flowID, flowVersion); final Map<VariableDescriptor, String> inputVariables = new HashMap<>(); final VersionedProcessGroup versionedGroup = snapshot.getFlowContents(); if (versionedGroup != null) { for (final Map.Entry<String, String> entry : versionedGroup.getVariables().entrySet()) { final String variableName = entry.getKey(); final String variableValue = entry.getValue(); inputVariables.put(new VariableDescriptor(variableName), variableValue); } } final Set<Parameter> parameters = new HashSet<>(); final Set<String> parameterNames = new HashSet<>(); if (args.has(PARAMETERS)) { final JsonElement parametersElement = args.get(PARAMETERS); final JsonObject parametersObject = parametersElement.getAsJsonObject(); for (final Map.Entry<String, JsonElement> entry : parametersObject.entrySet()) { final String parameterName = entry.getKey(); final JsonElement valueElement = entry.getValue(); if (parameterNames.contains(parameterName)) { throw new IllegalStateException("Cannot parse configuration because Parameter '" + parameterName + "' has been defined twice"); } parameterNames.add(parameterName); if (valueElement.isJsonObject()) { final JsonObject valueObject = valueElement.getAsJsonObject(); final boolean sensitive; if (valueObject.has(PARAMETER_SENSITIVE)) { sensitive = valueObject.get(PARAMETER_SENSITIVE).getAsBoolean(); } else { sensitive = false; } if (valueObject.has(PARAMETER_VALUE)) { final String value = valueObject.get(PARAMETER_VALUE).getAsString(); final ParameterDescriptor descriptor = new ParameterDescriptor.Builder().name(parameterName) .sensitive(sensitive).build(); final Parameter parameter = new Parameter(descriptor, value); parameters.add(parameter); } else { throw new IllegalStateException("Cannot parse configuration because Parameter '" + parameterName + "' does not have a value associated with it"); } } else { final String parameterValue = entry.getValue().getAsString(); final ParameterDescriptor descriptor = new ParameterDescriptor.Builder().name(parameterName) .build(); final Parameter parameter = new Parameter(descriptor, parameterValue); parameters.add(parameter); } } } final ParameterContext parameterContext = new StatelessParameterContext(parameters); final ExtensionManager extensionManager = ExtensionDiscovery.discover(narWorkingDir, systemClassLoader); final StatelessFlow flow = new StatelessFlow(snapshot.getFlowContents(), extensionManager, () -> inputVariables, failurePorts, materializeContent, sslContext, parameterContext); flow.enqueueFromJSON(args); return flow; }
From source file:org.apache.nifi.stateless.core.StatelessFlow.java
License:Apache License
public void enqueueFromJSON(final JsonObject json) { final JsonArray flowFiles; if (json.has(FLOWFILES)) { flowFiles = json.getAsJsonArray(FLOWFILES); } else {/*from w w w . j a v a 2s . c o m*/ return; } if (flowFiles.size() == 0) { return; } if (sourceComponent == null) { throw new IllegalStateException("Configuration specifies to inject " + flowFiles.size() + " FlowFiles into the flow, but the Flow does not contain an Input Port."); } final Queue<StatelessFlowFile> input = new LinkedList<>(); flowFiles.forEach(f -> { final JsonObject file = f.getAsJsonObject(); final String content = file.getAsJsonPrimitive(CONTENT).getAsString(); final Map<String, String> attributes = new HashMap<>(); file.entrySet().forEach(entry -> { if (!CONTENT.equals(entry.getKey())) { attributes.put(entry.getKey(), entry.getValue().getAsString()); } }); input.add(new StatelessFlowFile(content, attributes, sourceComponent.isMaterializeContent())); }); //enqueue data sourceComponent.enqueueAll(input); }
From source file:org.apache.openwhisk.example.maven.App.java
License:Apache License
public static JsonObject main(JsonObject args) { JsonObject response = new JsonObject(); if (args.has("text")) { String text = args.getAsJsonPrimitive("text").getAsString(); try {/*from w w w . j a v a2 s. c o m*/ Hasher hasher = Hashing.md5().newHasher(); hasher.putString(text.toString(), Charset.forName("UTF-8")); response.addProperty("text", text); response.addProperty("md5", hasher.hash().toString()); } catch (Exception e) { response.addProperty("Error", e.getMessage()); } } return response; }
From source file:org.apache.qpid.disttest.json.PropertyValueAdapter.java
License:Apache License
@Override public PropertyValue deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonNull()) { return null; } else if (json.isJsonPrimitive()) { Object result = null;/*from w w w . j av a 2s .com*/ JsonPrimitive primitive = json.getAsJsonPrimitive(); if (primitive.isString()) { result = primitive.getAsString(); } else if (primitive.isNumber()) { String asString = primitive.getAsString(); if (asString.indexOf('.') != -1 || asString.indexOf('e') != -1) { result = primitive.getAsDouble(); } else { result = primitive.getAsLong(); } } else if (primitive.isBoolean()) { result = primitive.getAsBoolean(); } else { throw new JsonParseException("Unsupported primitive value " + primitive); } return new SimplePropertyValue(result); } else if (json.isJsonArray()) { JsonArray array = json.getAsJsonArray(); List<Object> result = new ArrayList<Object>(array.size()); for (JsonElement element : array) { result.add(context.deserialize(element, Object.class)); } return new SimplePropertyValue(result); } else if (json.isJsonObject()) { JsonObject object = json.getAsJsonObject(); JsonElement defElement = object.getAsJsonPrimitive(DEF_FIELD); Class<?> classInstance = null; if (defElement != null) { try { classInstance = _factory.getPropertyValueClass(defElement.getAsString()); } catch (ClassNotFoundException e) { // ignore } } if (classInstance == null) { Map<String, Object> result = new HashMap<String, Object>(); for (Map.Entry<String, JsonElement> entry : object.entrySet()) { Object value = context.deserialize(entry.getValue(), Object.class); result.put(entry.getKey(), value); } return new SimplePropertyValue(result); } else { return context.deserialize(json, classInstance); } } else { throw new JsonParseException("Unsupported JSON type " + json); } }
From source file:org.broad.igv.ga4gh.Ga4ghAlignment.java
License:Open Source License
private String generateCigarString(JsonArray cigar) { StringBuffer cigarStr = new StringBuffer(); Iterator<JsonElement> iter = cigar.iterator(); while (iter.hasNext()) { JsonObject op = iter.next().getAsJsonObject(); cigarStr.append(op.getAsJsonPrimitive("operationLength").getAsString()); cigarStr.append(CigarMap.get(op.getAsJsonPrimitive("operation").getAsString())); }// w w w . j a v a2 s . co m return cigarStr.toString(); }
From source file:org.broad.igv.ga4gh.Ga4ghAlignmentReader.java
License:Open Source License
private void loadMetadata() throws IOException { String authKey = provider.apiKey; String baseURL = provider.baseURL; URL url = new URL(baseURL + "/readgroupsets/" + readsetId + (authKey == null ? "" : "?key=" + authKey)); // TODO -- field selection? Map<String, String> headers = new HashMap<String, String>(); String token = OAuthUtils.getInstance().getAccessToken(); if (token != null) { headers.put("Authorization", "Bearer " + token); }// www. java 2 s.c om String result = HttpUtils.getInstance().getContentsAsString(url, headers); JsonParser parser = new JsonParser(); JsonObject root = parser.parse(result).getAsJsonObject(); if (root.has("referenceSetId")) { String referenceSetId = root.getAsJsonPrimitive("referenceSetId").getAsString(); List<JsonObject> refererences = Ga4ghAPIHelper.searchReferences(provider, referenceSetId, 1000); sequenceNames = new ArrayList(); for (JsonObject refObject : refererences) { sequenceNames.add(refObject.getAsJsonPrimitive("name").getAsString()); } } }
From source file:org.broad.igv.ga4gh.Ga4ghAPIHelper.java
License:Open Source License
public static List<Ga4ghReadset> searchReadGroupsets(Ga4ghProvider provider, String datasetId, int maxResults) throws IOException { List<Ga4ghReadset> readsets = readsetCache.get(datasetId); if (readsets == null) { readsets = new ArrayList(); String genomeId = genomeIdMap.get(provider.getName() + " " + datasetId); // Hack until meta data on readsets is available // Loop through pages int maxPages = 100; JsonPrimitive pageToken = null;// ww w . ja v a2 s .c o m while (maxPages-- > 0) { String contentToPost = "{" + "\"datasetIds\": [\"" + datasetId + "\"]" + (pageToken == null ? "" : ", \"pageToken\": " + pageToken) + ", \"pageSize\":" + maxResults + "}"; String result = doPost(provider, "/readgroupsets/search", contentToPost, null, true); //"fields=readsets(id,name, fileData),nextPageToken"); if (result == null) return null; JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(result).getAsJsonObject(); Iterator<JsonElement> iter = obj.getAsJsonArray("readGroupSets").iterator(); while (iter.hasNext()) { JsonElement next = iter.next(); JsonObject jobj = next.getAsJsonObject(); String id = jobj.get("id").getAsString(); String name = jobj.get("name").getAsString(); readsets.add(new Ga4ghReadset(id, name, genomeId)); } if (readsets.size() >= maxResults) break; pageToken = obj.getAsJsonPrimitive("nextPageToken"); if (pageToken == null || pageToken.getAsString().equals("")) break; } Collections.sort(readsets, new Comparator<Ga4ghReadset>() { @Override public int compare(Ga4ghReadset o1, Ga4ghReadset o2) { return o1.getName().compareTo(o2.getName()); } }); readsetCache.put(datasetId, readsets); } return readsets; }
From source file:org.broad.igv.ga4gh.Ga4ghAPIHelper.java
License:Open Source License
public static List<JsonObject> searchReferences(Ga4ghProvider provider, String referenceSetId, int maxResults) throws IOException { List<JsonObject> references = referenceCache.get(referenceSetId); if (references == null) { references = new ArrayList(); // Loop through pages int maxPages = 100; JsonPrimitive pageToken = null;// w w w . j a v a2 s. c om while (maxPages-- > 0) { String contentToPost = "{" + "\"referenceSetId\": \"" + referenceSetId + "\"" + (pageToken == null ? "" : ", \"pageToken\": " + pageToken) + ", \"pageSize\":" + maxResults + "}"; String result = doPost(provider, "/references/search", contentToPost, null, true); //"fields=readsets(id,name, fileData),nextPageToken"); if (result == null) return null; JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(result).getAsJsonObject(); Iterator<JsonElement> iter = obj.getAsJsonArray("references").iterator(); while (iter.hasNext()) { JsonElement next = iter.next(); references.add(next.getAsJsonObject()); } if (references.size() >= maxResults) break; pageToken = obj.getAsJsonPrimitive("nextPageToken"); if (pageToken == null || pageToken.getAsString().equals("")) break; } referenceCache.put(referenceSetId, references); } return references; }
From source file:org.broad.igv.ga4gh.Ga4ghAPIHelper.java
License:Open Source License
public static List<Alignment> searchReads(Ga4ghProvider provider, String readGroupSetId, String chr, int start, int end, boolean handleError) throws IOException { List<Alignment> alignments = new ArrayList<Alignment>(10000); int maxPages = 10000; JsonPrimitive pageToken = null;//from w w w .j a va2s . c om StringBuffer result = new StringBuffer(); int counter = 0; while (maxPages-- > 0) { String contentToPost = "{" + "\"readGroupSetIds\": [\"" + readGroupSetId + "\"]" + ", \"referenceName\": \"" + chr + "\"" + ", \"start\": \"" + start + "\"" + ", \"end\": \"" + end + "\"" + ", \"pageSize\": \"10000\"" + (pageToken == null ? "" : ", \"pageToken\": " + pageToken) + "}"; String readString = doPost(provider, "/reads/search", contentToPost, "", handleError); if (readString == null) { return null; } JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(readString).getAsJsonObject(); JsonArray reads = obj.getAsJsonArray("alignments"); Iterator<JsonElement> iter = reads.iterator(); while (iter.hasNext()) { JsonElement next = iter.next(); Ga4ghAlignment alignment = new Ga4ghAlignment(next.getAsJsonObject()); alignments.add(alignment); } pageToken = obj.getAsJsonPrimitive("nextPageToken"); if (pageToken == null || pageToken.getAsString().equals("")) break; } return alignments; }