List of usage examples for com.google.gson JsonArray get
public JsonElement get(int i)
From source file:com.graphhopper.json.FeatureJsonDeserializer.java
License:Apache License
@Override public JsonFeature deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { try {//from w w w.j a v a 2s. c o m JsonObject obj = json.getAsJsonObject(); String id, strType = null; Map<String, Object> properties = null; BBox bbox = null; Geometry geometry = null; // TODO ensure uniqueness if (obj.has("id")) id = obj.get("id").getAsString(); else id = UUID.randomUUID().toString(); if (obj.has("properties")) { properties = context.deserialize(obj.get("properties"), Map.class); } if (obj.has("bbox")) bbox = parseBBox(obj.get("bbox").getAsJsonArray()); if (obj.has("geometry")) { JsonObject geometryJson = obj.get("geometry").getAsJsonObject(); if (geometryJson.has("coordinates")) { if (!geometryJson.has("type")) throw new IllegalArgumentException("No type for non-empty coordinates specified"); strType = context.deserialize(geometryJson.get("type"), String.class); if ("Point".equals(strType)) { JsonArray arr = geometryJson.get("coordinates").getAsJsonArray(); double lon = arr.get(0).getAsDouble(); double lat = arr.get(1).getAsDouble(); if (arr.size() == 3) geometry = new Point(lat, lon, arr.get(2).getAsDouble()); else geometry = new Point(lat, lon); } else if ("MultiPoint".equals(strType)) { geometry = parseLineString(geometryJson); } else if ("LineString".equals(strType)) { geometry = parseLineString(geometryJson); } else { throw new IllegalArgumentException("Coordinates type " + strType + " not yet supported"); } } } return new JsonFeature(id, strType, bbox, geometry, properties); } catch (Exception ex) { throw new JsonParseException("Problem parsing JSON feature " + json); } }
From source file:com.graphhopper.json.FeatureJsonDeserializer.java
License:Apache License
LineString parseLineString(JsonObject geometry) { JsonArray arr = geometry.get("coordinates").getAsJsonArray(); boolean is3D = arr.size() == 0 || arr.get(0).getAsJsonArray().size() == 3; LineString lineString = new LineString(arr.size(), is3D); for (int i = 0; i < arr.size(); i++) { JsonArray pointArr = arr.get(i).getAsJsonArray(); double lon = pointArr.get(0).getAsDouble(); double lat = pointArr.get(1).getAsDouble(); if (pointArr.size() == 3) lineString.add(lat, lon, pointArr.get(2).getAsDouble()); else// w ww. j a va 2s . co m lineString.add(lat, lon); } return lineString; }
From source file:com.graphhopper.json.FeatureJsonDeserializer.java
License:Apache License
private BBox parseBBox(JsonArray arr) { // The value of the bbox member must be a 2*n array where n is the number of dimensions represented // in the contained geometries, with the lowest values for all axes followed by the highest values. // The axes order of a bbox follows the axes order of geometries => lon,lat,ele if (arr.size() == 6) { double minLon = arr.get(0).getAsDouble(); double minLat = arr.get(1).getAsDouble(); double minEle = arr.get(2).getAsDouble(); double maxLon = arr.get(3).getAsDouble(); double maxLat = arr.get(4).getAsDouble(); double maxEle = arr.get(5).getAsDouble(); return new BBox(minLon, maxLon, minLat, maxLat, minEle, maxEle); } else if (arr.size() == 4) { double minLon = arr.get(0).getAsDouble(); double minLat = arr.get(1).getAsDouble(); double maxLon = arr.get(2).getAsDouble(); double maxLat = arr.get(3).getAsDouble(); return new BBox(minLon, maxLon, minLat, maxLat); } else {/*from w ww .ja v a 2s.c o m*/ throw new IllegalArgumentException( "Illegal array dimension (" + arr.size() + ") of bbox " + arr.toString()); } }
From source file:com.graphhopper.json.geo.FeatureJsonDeserializer.java
License:Apache License
@Override public JsonFeature deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { try {//from w ww.j a v a2s.com JsonFeature feature = new JsonFeature(); JsonObject obj = json.getAsJsonObject(); // TODO ensure uniqueness if (obj.has("id")) feature.id = obj.get("id").getAsString(); else feature.id = UUID.randomUUID().toString(); if (obj.has("properties")) { Map<String, Object> map = context.deserialize(obj.get("properties"), Map.class); feature.properties = map; } if (obj.has("bbox")) feature.bbox = parseBBox(obj.get("bbox").getAsJsonArray()); if (obj.has("geometry")) { JsonObject geometry = obj.get("geometry").getAsJsonObject(); if (geometry.has("coordinates")) { if (!geometry.has("type")) throw new IllegalArgumentException("No type for non-empty coordinates specified"); String strType = context.deserialize(geometry.get("type"), String.class); feature.type = strType; if ("Point".equals(strType)) { JsonArray arr = geometry.get("coordinates").getAsJsonArray(); double lon = arr.get(0).getAsDouble(); double lat = arr.get(1).getAsDouble(); if (arr.size() == 3) feature.geometry = new Point(lat, lon, arr.get(2).getAsDouble()); else feature.geometry = new Point(lat, lon); } else if ("MultiPoint".equals(strType)) { feature.geometry = parseLineString(geometry); } else if ("LineString".equals(strType)) { feature.geometry = parseLineString(geometry); } else { throw new IllegalArgumentException("Coordinates type " + strType + " not yet supported"); } } } return feature; } catch (Exception ex) { throw new JsonParseException("Problem parsing JSON feature " + json); } }
From source file:com.grarak.cafntracker.Tracker.java
License:Apache License
private Tracker(int port, String api, ArrayList<Repo> repos) throws IOException { File idsFile = new File("ids.json"); if (idsFile.exists()) { String content = Utils.readFile(idsFile); JsonArray array = new JsonParser().parse(content).getAsJsonArray(); for (int i = 0; i < array.size(); i++) { mIds.add(array.get(i).getAsString().trim()); }/* ww w.ja v a 2 s . c om*/ } for (Repo repo : repos) { try { repo.script_content = Utils.resourceFileReader( getClass().getClassLoader().getResourceAsStream("parsers/" + repo.content_script)); } catch (IOException ignored) { Log.e(TAG, "Failed to read " + repo.content_script); return; } } new Thread(() -> { while (true) { for (Repo repo : repos) { File file = new File("repos/" + repo.name); if (!file.exists()) { Log.i(TAG, "Cloning " + repo.name); try { Utils.executeProcess("git clone " + repo.link + " " + file.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "Failed cloning " + repo.name); } } try { String tags = Utils.executeProcess("git -C " + file.getAbsolutePath() + " tag"); repo.tags = Arrays.asList(tags.split("\\r?\\n")); Log.i(TAG, repo.tags.size() + " tags found for " + repo.name); } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "Failed getting tags from " + repo.name); } try { Log.i(TAG, "Sleeping"); Thread.sleep(10000); Utils.executeProcess("git -C " + file.getAbsolutePath() + " fetch origin"); String tags = Utils.executeProcess("git -C " + file.getAbsolutePath() + " tag"); List<String> curTags = Arrays.asList(tags.split("\\r?\\n")); List<String> newTags = curTags.stream() .filter(tag -> !repo.tags.contains(tag) && !tag.startsWith("android-")) .collect(Collectors.toList()); for (String newTag : newTags) { File parserScript = new File("parse_script.sh"); Utils.writeFile(repo.script_content, parserScript, false); Utils.executeProcess("chmod a+x " + parserScript.getAbsolutePath()); String content = Utils.executeProcess( parserScript.getAbsolutePath() + " " + file.getAbsolutePath() + " " + newTag); for (String id : mIds) { try { Request.post(id, api, repo.name, content, newTag, String.format(repo.tag_link, newTag)); } catch (Exception e) { e.printStackTrace(); Log.i(TAG, "Failed to send post request to " + id); } } } } catch (Exception e) { e.printStackTrace(); Log.i(TAG, "Failed to update tags for " + repo.name); } } } }).start(); Log.i(TAG, "Start listening on port " + port); SSLServerSocketFactory ssf = loadKeyStore().getServerSocketFactory(); SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(port); while (true) { try { SSLSocket socket = (SSLSocket) s.accept(); String address = socket.getRemoteSocketAddress().toString(); Log.i(TAG, "Connected to " + address); DataInputStream dataInputStream = new DataInputStream(socket.getInputStream()); byte[] buffer = new byte[8192]; dataInputStream.read(buffer); String id = new String(buffer).trim(); Log.i(TAG, id); JsonArray repoList = new JsonArray(); for (Repo repo : repos) { JsonObject repoObject = new JsonObject(); repoObject.addProperty("name", repo.name); repoObject.addProperty("content_name", repo.content_name); repoList.add(repoObject); } DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream()); dataOutputStream.write(repoList.toString().getBytes()); if (!mIds.contains(id)) { mIds.add(id); JsonArray array = new JsonArray(); mIds.forEach(array::add); Utils.writeFile(array.toString(), idsFile, false); } dataInputStream.close(); socket.close(); } catch (IOException ignored) { Log.e(TAG, "Failed to connect to client"); } } }
From source file:com.grarak.cafntracker.Tracker.java
License:Apache License
public static void main(String[] args) { if (args.length != 2) { showUsage();//from w ww . j a v a 2 s .c om return; } int port; try { port = Integer.parseInt(args[0]); } catch (NumberFormatException ignored) { showUsage(); return; } String apiKey = args[1]; String repos; try { repos = Utils.resourceFileReader(Tracker.class.getClassLoader().getResourceAsStream("repos.json")); } catch (IOException ignored) { Log.e(TAG, "Couldn't read repos.json form resources"); return; } JsonArray repoArray = new JsonParser().parse(repos).getAsJsonArray(); ArrayList<Repo> repoSet = new ArrayList<>(); for (int i = 0; i < repoArray.size(); i++) { JsonObject repoObject = repoArray.get(i).getAsJsonObject(); repoSet.add(new Repo(repoObject.get("name").getAsString(), repoObject.get("link").getAsString(), repoObject.get("tag_link").getAsString(), repoObject.get("content_name").getAsString(), repoObject.get("content_parser").getAsString())); } try { new Tracker(port, apiKey, repoSet); } catch (IOException e) { e.printStackTrace(); Log.e(TAG, "Failed to start server at port " + port); } }
From source file:com.gst.accounting.journalentry.serialization.JournalEntryCommandFromApiJsonDeserializer.java
License:Apache License
/** * @param comments//from w ww.j a v a 2s . c o m * @param topLevelJsonElement * @param locale */ private SingleDebitOrCreditEntryCommand[] populateCreditsOrDebitsArray(final JsonObject topLevelJsonElement, final Locale locale, SingleDebitOrCreditEntryCommand[] debitOrCredits, final String paramName) { final JsonArray array = topLevelJsonElement.get(paramName).getAsJsonArray(); debitOrCredits = new SingleDebitOrCreditEntryCommand[array.size()]; for (int i = 0; i < array.size(); i++) { final JsonObject creditElement = array.get(i).getAsJsonObject(); final Set<String> parametersPassedInForCreditsCommand = new HashSet<>(); final Long glAccountId = this.fromApiJsonHelper.extractLongNamed("glAccountId", creditElement); final String comments = this.fromApiJsonHelper.extractStringNamed("comments", creditElement); final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalNamed("amount", creditElement, locale); debitOrCredits[i] = new SingleDebitOrCreditEntryCommand(parametersPassedInForCreditsCommand, glAccountId, amount, comments); } return debitOrCredits; }
From source file:com.gst.accounting.producttoaccountmapping.service.ProductToGLAccountMappingHelper.java
License:Apache License
/** * Saves the payment type to Fund source mappings for a particular * product/product type (also populates the changes array if passed in) * /* www. ja va 2 s . c o m*/ * @param command * @param element * @param productId * @param changes */ public void savePaymentChannelToFundSourceMappings(final JsonCommand command, final JsonElement element, final Long productId, final Map<String, Object> changes, final PortfolioProductType portfolioProductType) { final JsonArray paymentChannelMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element); if (paymentChannelMappingArray != null) { if (changes != null) { changes.put(LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), command.jsonFragment( LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue())); } for (int i = 0; i < paymentChannelMappingArray.size(); i++) { final JsonObject jsonObject = paymentChannelMappingArray.get(i).getAsJsonObject(); final Long paymentTypeId = jsonObject.get(LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_TYPE.getValue()) .getAsLong(); final Long paymentSpecificFundAccountId = jsonObject .get(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue()).getAsLong(); savePaymentChannelToFundSourceMapping(productId, paymentTypeId, paymentSpecificFundAccountId, portfolioProductType); } } }
From source file:com.gst.accounting.producttoaccountmapping.service.ProductToGLAccountMappingHelper.java
License:Apache License
/** * Saves the Charge to Income / Liability account mappings for a particular * product/product type (also populates the changes array if passed in) * //ww w .j ava 2s . co m * @param command * @param element * @param productId * @param changes */ public void saveChargesToIncomeOrLiabilityAccountMappings(final JsonCommand command, final JsonElement element, final Long productId, final Map<String, Object> changes, final PortfolioProductType portfolioProductType, final boolean isPenalty) { String arrayName; if (isPenalty) { arrayName = LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTY_INCOME_ACCOUNT_MAPPING.getValue(); } else { arrayName = LOAN_PRODUCT_ACCOUNTING_PARAMS.FEE_INCOME_ACCOUNT_MAPPING.getValue(); } final JsonArray chargeToIncomeAccountMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed(arrayName, element); if (chargeToIncomeAccountMappingArray != null) { if (changes != null) { changes.put(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEE_INCOME_ACCOUNT_MAPPING.getValue(), command.jsonFragment(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEE_INCOME_ACCOUNT_MAPPING.getValue())); } for (int i = 0; i < chargeToIncomeAccountMappingArray.size(); i++) { final JsonObject jsonObject = chargeToIncomeAccountMappingArray.get(i).getAsJsonObject(); final Long chargeId = jsonObject.get(LOAN_PRODUCT_ACCOUNTING_PARAMS.CHARGE_ID.getValue()) .getAsLong(); final Long incomeAccountId = jsonObject .get(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_ACCOUNT_ID.getValue()).getAsLong(); saveChargeToFundSourceMapping(productId, chargeId, incomeAccountId, portfolioProductType, isPenalty); } } }
From source file:com.gst.accounting.producttoaccountmapping.service.ProductToGLAccountMappingHelper.java
License:Apache License
/** * @param command/*from www . j av a 2 s. c o m*/ * @param element * @param productId * @param changes */ public void updateChargeToIncomeAccountMappings(final JsonCommand command, final JsonElement element, final Long productId, final Map<String, Object> changes, final PortfolioProductType portfolioProductType, final boolean isPenalty) { // find all existing payment Channel to Fund source Mappings List<ProductToGLAccountMapping> existingChargeToIncomeAccountMappings; String arrayFragmentName; if (isPenalty) { existingChargeToIncomeAccountMappings = this.accountMappingRepository .findAllPenaltyToIncomeAccountMappings(productId, portfolioProductType.getValue()); arrayFragmentName = LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTY_INCOME_ACCOUNT_MAPPING.getValue(); } else { existingChargeToIncomeAccountMappings = this.accountMappingRepository .findAllFeeToIncomeAccountMappings(productId, portfolioProductType.getValue()); arrayFragmentName = LOAN_PRODUCT_ACCOUNTING_PARAMS.FEE_INCOME_ACCOUNT_MAPPING.getValue(); } final JsonArray chargeToIncomeAccountMappingArray = this.fromApiJsonHelper .extractJsonArrayNamed(arrayFragmentName, element); /** * Variable stores a map representation of charges (key) and their * associated income Id's (value) extracted from the passed in * Jsoncommand **/ final Map<Long, Long> inputChargeToIncomeAccountMap = new HashMap<>(); /*** * Variable stores all charges which have already been mapped to Income * Accounts in the system **/ final Set<Long> existingCharges = new HashSet<>(); if (chargeToIncomeAccountMappingArray != null) { if (changes != null) { changes.put(arrayFragmentName, command.jsonFragment(arrayFragmentName)); } for (int i = 0; i < chargeToIncomeAccountMappingArray.size(); i++) { final JsonObject jsonObject = chargeToIncomeAccountMappingArray.get(i).getAsJsonObject(); final Long chargeId = jsonObject.get(LOAN_PRODUCT_ACCOUNTING_PARAMS.CHARGE_ID.getValue()) .getAsLong(); final Long incomeAccountId = jsonObject .get(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_ACCOUNT_ID.getValue()).getAsLong(); inputChargeToIncomeAccountMap.put(chargeId, incomeAccountId); } // If input map is empty, delete all existing mappings if (inputChargeToIncomeAccountMap.size() == 0) { this.accountMappingRepository.deleteInBatch(existingChargeToIncomeAccountMappings); } /** * Else, <br/> * update existing mappings OR <br/> * delete old mappings (which are already present, but not passed in * as a part of Jsoncommand)<br/> * Create new mappings for charges that are passed in as a part of * the Jsoncommand but not already present * **/ else { for (final ProductToGLAccountMapping chargeToIncomeAccountMapping : existingChargeToIncomeAccountMappings) { final Long currentCharge = chargeToIncomeAccountMapping.getCharge().getId(); existingCharges.add(currentCharge); // update existing mappings (if required) if (inputChargeToIncomeAccountMap.containsKey(currentCharge)) { final Long newGLAccountId = inputChargeToIncomeAccountMap.get(currentCharge); if (newGLAccountId != chargeToIncomeAccountMapping.getGlAccount().getId()) { final GLAccount glAccount; if (isPenalty) { glAccount = getAccountByIdAndType( LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_ACCOUNT_ID.getValue(), GLAccountType.INCOME, newGLAccountId); } else { List<GLAccountType> allowedAccountTypes = getAllowedAccountTypesForFeeMapping(); glAccount = getAccountByIdAndType( LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_ACCOUNT_ID.getValue(), allowedAccountTypes, newGLAccountId); } chargeToIncomeAccountMapping.setGlAccount(glAccount); this.accountMappingRepository.save(chargeToIncomeAccountMapping); } } // deleted payment type else { this.accountMappingRepository.delete(chargeToIncomeAccountMapping); } } // create new mappings final Set<Long> incomingCharges = inputChargeToIncomeAccountMap.keySet(); incomingCharges.removeAll(existingCharges); // incomingPaymentTypes now only contains the newly added // payment Type mappings for (final Long newCharge : incomingCharges) { final Long newGLAccountId = inputChargeToIncomeAccountMap.get(newCharge); saveChargeToFundSourceMapping(productId, newCharge, newGLAccountId, portfolioProductType, isPenalty); } } } }