List of usage examples for com.google.gson JsonElement getAsInt
public int getAsInt()
From source file:org.coinspark.wallet.CSAsset.java
License:Open Source License
private boolean parseJSONString(String JSONString) { if (JSONString == null) { return false; }/*from w ww .j a v a 2 s. c o m*/ if (JSONString.length() > 0) { try { JsonElement jelement = new JsonParser().parse(JSONString); JsonObject jresult = jelement.getAsJsonObject(); JsonElement jvalue; // All JSON strings - from asset web page and from asset database jvalue = jresult.get("name"); if (jvalue != null) { name = jvalue.getAsString(); } jvalue = jresult.get("name_short"); if (jvalue != null) { nameShort = jvalue.getAsString(); } jvalue = jresult.get("issuer"); if (jvalue != null) { issuer = jvalue.getAsString(); } jvalue = jresult.get("description"); if (jvalue != null) { description = jvalue.getAsString(); } jvalue = jresult.get("units"); if (jvalue != null) { units = jvalue.getAsString(); } jvalue = jresult.get("contract_url"); if (jvalue != null) { contractUrl = jvalue.getAsString(); } jvalue = jresult.get("coinspark_tracker_url"); if (jvalue != null) { if (jvalue.isJsonArray()) { JsonArray jarray = jvalue.getAsJsonArray(); if (jarray.size() > 0) { coinsparkTrackerUrls = new String[jarray.size()]; for (int i = 0; i < jarray.size(); i++) { JsonElement jvalueUrl = jarray.get(i); if (jvalueUrl != null) { coinsparkTrackerUrls[i] = CSUtils.addHttpIfMissing(jvalueUrl.getAsString()); } } } } else { coinsparkTrackerUrls = new String[] { CSUtils.addHttpIfMissing(jvalue.getAsString()) }; } } jvalue = jresult.get("issue_date"); if (jvalue != null) { issueDate = jvalue.getAsString(); } jvalue = jresult.get("expiry_date"); if (jvalue != null) { expiryDate = jvalue.getAsString(); } jvalue = jresult.get("interest_rate"); if (jvalue != null) { interestRate = jvalue.getAsDouble(); } jvalue = jresult.get("multiple"); if (jvalue != null) { multiple = jvalue.getAsDouble(); } jvalue = jresult.get("format"); if (jvalue != null) { format = jvalue.getAsString(); } jvalue = jresult.get("format_1"); if (jvalue != null) { format1 = jvalue.getAsString(); } jvalue = jresult.get("icon_url"); if (jvalue != null) { iconUrl = jvalue.getAsString(); } jvalue = jresult.get("image_url"); if (jvalue != null) { imageUrl = jvalue.getAsString(); } jvalue = jresult.get("feed_url"); if (jvalue != null) { feedUrl = jvalue.getAsString(); } jvalue = jresult.get("redemption_irl"); if (jvalue != null) { redemptionUrl = jvalue.getAsString(); } // From asset database only jvalue = jresult.get("asset_id"); if (jvalue != null) { assetID = jvalue.getAsInt(); } jvalue = jresult.get("date_created"); if (jvalue != null) { dateCreation = CSUtils.iso86012date(jvalue.getAsString()); } jvalue = jresult.get("asset_state"); if (jvalue != null) { assetState = CSAssetState.valueOf(jvalue.getAsString()); } jvalue = jresult.get("asset_source"); if (jvalue != null) { assetSource = CSAssetSource.valueOf(jvalue.getAsString()); } jvalue = jresult.get("asset_contract_state"); if (jvalue != null) { assetContractState = CSAssetContractState.valueOf(jvalue.getAsString()); } jvalue = jresult.get("gen_txid"); if (jvalue != null) { genTxID = jvalue.getAsString(); } jvalue = jresult.get("visible"); if (jvalue != null) { if (jvalue.getAsInt() == 0) { visible = false; } else { visible = true; } } jvalue = jresult.get("fsi_txid"); if (jvalue != null) { firstSpentTxID = jvalue.getAsString(); } jvalue = jresult.get("fsi_vout"); if (jvalue != null) { firstSpentVout = jvalue.getAsInt(); } jvalue = jresult.get("genesis"); if (jvalue != null) { genesis = new CoinSparkGenesis(); if (!genesis.decode(jvalue.getAsString())) { genesis = null; } } jvalue = jresult.get("asset_ref_block"); if (jvalue != null) { assetRef = new CoinSparkAssetRef(); assetRef.setBlockNum(jvalue.getAsInt()); jvalue = jresult.get("asset_ref_offset"); if (jvalue != null) { assetRef.setTxOffset(jvalue.getAsInt()); } jvalue = jresult.get("asset_ref_prefix"); if (jvalue != null) { assetRef.setTxIDPrefix(CSUtils.hex2Byte(jvalue.getAsString())); } } jvalue = jresult.get("valid_checked"); if (jvalue != null) { validChecked = CSUtils.iso86012date(jvalue.getAsString()); } jvalue = jresult.get("valid_failures"); if (jvalue != null) { validFailures = jvalue.getAsInt(); } jvalue = jresult.get("contract_path"); if (jvalue != null) { contractPath = jvalue.getAsString(); } jvalue = jresult.get("valid_contract_path"); if (jvalue != null) { validContractPath = jvalue.getAsString(); } jvalue = jresult.get("json_path"); if (jvalue != null) { jsonPath = jvalue.getAsString(); } jvalue = jresult.get("valid_json_path"); if (jvalue != null) { validJsonPathToSet = jvalue.getAsString(); } jvalue = jresult.get("contract_mime"); if (jvalue != null) { contractMimeType = CSUtils.CSMimeType.fromExtension(jvalue.getAsString()); } jvalue = jresult.get("valid_contract_mime"); if (jvalue != null) { validContractMimeType = CSUtils.CSMimeType.fromExtension(jvalue.getAsString()); } jvalue = jresult.get("image_path"); if (jvalue != null) { imagePath = jvalue.getAsString(); } jvalue = jresult.get("image_mime"); if (jvalue != null) { imageMimeType = CSUtils.CSMimeType.fromExtension(jvalue.getAsString()); } jvalue = jresult.get("icon_path"); if (jvalue != null) { iconPath = jvalue.getAsString(); } jvalue = jresult.get("icon_mime"); if (jvalue != null) { iconMimeType = CSUtils.CSMimeType.fromExtension(jvalue.getAsString()); } } catch (JsonSyntaxException ex) { assetValidationState = CSAssetState.ASSET_SPECS_NOT_PARSED; log.info("Asset details: Error while parsing JSON String " + JSONString); return false; } } else { return false; } if (!checkRequiredFields()) { assetValidationState = CSAssetState.REQUIRED_FIELD_MISSING; return false; } return true; }
From source file:org.commoncrawl.mapred.ec2.postprocess.crawldb.CrawlDBMergingReducer.java
License:Open Source License
/** * we need to extract source url from the JSON because it is not available via * the key/* ww w.java 2 s. c o m*/ * * @param jsonObject * @param keyType */ void setSourceURLFromJSONObject(JsonObject jsonObject, long keyType) { if (!_urlKeyForzen) { JsonElement sourceElement = jsonObject.get("source_url"); if (keyType == CrawlDBKey.Type.KEY_TYPE_CRAWL_STATUS.ordinal()) { _outputKeyString = sourceElement.getAsString(); _outputKeyURLObj = new GoogleURL(_outputKeyString); JsonElement httpResultElem = jsonObject.get("http_result"); if (httpResultElem != null) { int httpResult = httpResultElem.getAsInt(); if (httpResult >= 200 && httpResult <= 299) { if (sourceElement != null && _outputKeyString == null) { _outputKeyString = sourceElement.getAsString(); _outputKeyURLObj = new GoogleURL(_outputKeyString); if (_outputKeyURLObj.isValid()) _urlKeyForzen = true; } } } } else if (keyType == CrawlDBKey.Type.KEY_TYPE_MERGED_RECORD.ordinal()) { _outputKeyString = sourceElement.getAsString(); _outputKeyURLObj = new GoogleURL(_outputKeyString); _urlKeyForzen = true; } else if (keyType >= CrawlDBKey.Type.KEY_TYPE_HTML_LINK.ordinal() && keyType <= CrawlDBKey.Type.KEY_TYPE_RSS_LINK.ordinal()) { if (_outputKeyString == null) { JsonElement hrefElement = jsonObject.get("href"); if (sourceElement != null && hrefElement != null) { GoogleURL hrefSource = new GoogleURL(sourceElement.getAsString()); if (hrefSource.isValid()) { _outputKeyString = hrefElement.getAsString(); _outputKeyURLObj = new GoogleURL(_outputKeyString); } } } } } }
From source file:org.commoncrawl.mapred.ec2.postprocess.linkCollector.LinkMergerJob.java
License:Open Source License
@Override public void configure(JobConf job) { HashSet<Integer> onlyDoPartitions = null; String hack = job.get("hack"); if (hack != null) { onlyDoPartitions = new HashSet<Integer>(); JsonParser parser = new JsonParser(); JsonArray hackArray = parser.parse(hack).getAsJsonArray(); for (JsonElement element : hackArray) { onlyDoPartitions.add(element.getAsInt()); }//ww w.jav a 2s. com } _conf = job; try { _fs = FileSystem.get(_conf); int partitionId = _conf.getInt("mapred.task.partition", 0); if (onlyDoPartitions == null || onlyDoPartitions.contains(partitionId)) { Path redirectPath = new Path(FileOutputFormat.getWorkOutputPath(_conf), "redirect-" + NUMBER_FORMAT.format(partitionId)); _redirectWriter = SequenceFile.createWriter(_fs, _conf, redirectPath, TextBytes.class, TextBytes.class, CompressionType.BLOCK); } else { _skipPartition = true; } } catch (IOException e) { e.printStackTrace(); } }
From source file:org.couchbase.mock.control.handlers.OpfailCommandHandler.java
License:Apache License
@Override public CommandStatus execute(@NotNull CouchbaseMock mock, @NotNull Command command, @NotNull JsonObject payload) {//from www.j a va 2s . com ErrorCode eCode = ErrorCode.SUCCESS; boolean eCodeFound = false; JsonElement eServerList = null; if (payload.has("servers")) { eServerList = payload.get("servers"); } List<Integer> serverList = new LinkedList<Integer>(); if (eServerList != null) { for (JsonElement ix : eServerList.getAsJsonArray()) { serverList.add(ix.getAsInt()); } } int count = payload.get("count").getAsInt(); int iCode = payload.get("code").getAsInt(); for (ErrorCode rc : ErrorCode.values()) { if (iCode == rc.value()) { eCode = rc; eCodeFound = true; break; } } if (!eCodeFound) { return new CommandStatus().fail("Invalid error code"); } for (Bucket bucket : mock.getBuckets().values()) { MemcachedServer[] servers = bucket.getServers(); for (int ii = 0; ii < servers.length; ii++) { // In this case, size() is easier to read :) if (serverList.size() > 0 && !serverList.contains(ii)) { continue; } servers[ii].updateFailMakerContext(eCode, count); } } return new CommandStatus(); }
From source file:org.couchbase.mock.control.handlers.PersistenceCommandHandler.java
License:Apache License
private void executeReal(JsonObject payload, Command command) { final String value; long cas = 0; boolean onMaster; JsonElement eOnReplicas;/*from www .j a v a 2 s . c o m*/ Storage masterStore; List<Storage> stores = new ArrayList<Storage>(); onMaster = payload.get("OnMaster").getAsBoolean(); if (payload.has("CAS")) { cas = payload.get("CAS").getAsLong(); } if (payload.has("Value")) { value = payload.get("Value").getAsString(); } else { value = ""; } masterStore = vbi.getOwner().getStorage(); if (onMaster) { stores.add(masterStore); } // Figure out which replicas to affect eOnReplicas = payload.get("OnReplicas"); if (eOnReplicas.isJsonArray()) { // An array of indices to use: for (JsonElement ix : eOnReplicas.getAsJsonArray()) { MemcachedServer mc = vbi.getReplicas().get(ix.getAsInt()); Storage s = mc.getStorage(); if (!stores.contains(s)) { stores.add(s); } } } else { int maxReplicas = eOnReplicas.getAsInt(); int replicasSelected = 0; for (MemcachedServer server : vbi.getReplicas()) { if (replicasSelected == maxReplicas) { break; } if (!server.isActive()) { continue; } stores.add(server.getStorage()); replicasSelected++; } } Item source = masterStore.getCached(keySpec); Item newItem; if (source == null) { assert value != null; assert value.getBytes() != null; source = new Item(keySpec, 0, 0, value.getBytes(), null, cas); } if (cas < 0) { cas = (source.getCas() + 1) * 2; } if (cas != 0) { newItem = new Item(source.getKeySpec(), source.getFlags(), source.getExpiryTime(), value.getBytes(), source.getXattr(), cas); } else { newItem = new Item(source); } if (stores.size() == 0) { System.err.println("No stores available for key"); } for (Storage curStore : stores) { switch (command) { case PERSIST: case ENDURE: curStore.putPersisted(newItem); if (command == Command.PERSIST) { break; } // ENDURE fallthrough case CACHE: curStore.putCached(newItem); break; case PURGE: case UNPERSIST: curStore.removePersisted(keySpec); if (command == Command.UNPERSIST) { break; } case UNCACHE: curStore.removeCached(keySpec); break; default: throw new RuntimeException("Unrecognized command"); } } }
From source file:org.couchbase.mock.control.PersistenceCommandHandler.java
License:Apache License
private void executeReal() { String value = "1029384756"; long cas = 0; boolean onMaster; JsonElement eOnReplicas;/*from w w w . j av a 2s . com*/ Storage masterStore; List<Storage> stores = new ArrayList<Storage>(); onMaster = payload.get("OnMaster").getAsBoolean(); if (payload.has("CAS")) { cas = payload.get("CAS").getAsLong(); } if (payload.has("Value")) { value = payload.get("Value").getAsString(); } masterStore = vbi.getOwner().getStorage(); if (onMaster) { stores.add(masterStore); } // Figure out which replicas to affect eOnReplicas = payload.get("OnReplicas"); if (eOnReplicas.isJsonArray()) { // An array of indices to use: for (JsonElement ix : eOnReplicas.getAsJsonArray()) { MemcachedServer mc = vbi.getReplicas().get(ix.getAsInt()); Storage s = mc.getStorage(); if (!stores.contains(s)) { stores.add(s); } } } else { int maxReplicas = eOnReplicas.getAsInt(); int replicasSelected = 0; for (MemcachedServer server : vbi.getReplicas()) { if (replicasSelected == maxReplicas) { break; } if (!server.isActive()) { continue; } stores.add(server.getStorage()); replicasSelected++; } } Item source = masterStore.getCached(keySpec); Item newItem; if (source == null) { assert value != null; assert value.getBytes() != null; source = new Item(keySpec, 0, 0, value.getBytes(), cas); } if (cas < 0) { cas = (source.getCas() + 1) * 2; } if (cas != 0) { newItem = new Item(source.getKeySpec(), source.getFlags(), source.getExpiryTime(), value.getBytes(), cas); } else { newItem = new Item(source); } if (stores.size() == 0) { System.err.println("No stores available for key"); } for (Storage curStore : stores) { switch (command) { case PERSIST: case ENDURE: curStore.putPersisted(newItem); if (command == Command.PERSIST) { break; } // ENDURE fallthrough case CACHE: curStore.putCached(newItem); break; case PURGE: case UNPERSIST: curStore.removePersisted(keySpec); if (command == Command.UNPERSIST) { break; } case UNCACHE: curStore.removeCached(keySpec); break; default: throw new RuntimeException("Unrecognized command"); } } }
From source file:org.displaytag.model.CustomColumnData.java
License:Artistic License
private int getIntValue(JsonObject jsonObj, String name) { if (jsonObj.has(name)) { JsonElement e = jsonObj.get(name); return e != null ? e.getAsInt() : 0; }/*w w w .j a v a 2s. c o m*/ return 0; }
From source file:org.eclipse.scada.base.json.VariantJsonDeserializer.java
License:Open Source License
@Override public Variant deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { if (json.isJsonNull()) { return null; }//from w w w .jav a 2s . com if (json instanceof JsonPrimitive) { return decodeFromPrimitive(json); } if (json instanceof JsonObject) { final JsonObject jsonObj = (JsonObject) json; final JsonElement type = jsonObj.get(VariantJson.FIELD_TYPE); final JsonElement value = jsonObj.get(VariantJson.FIELD_VALUE); if (type == null || type.isJsonNull()) { if (value == null) { throw new JsonParseException(String.format("Variant encoded as object must have a field '%s'", VariantJson.FIELD_VALUE)); } return Variant.valueOf(value.getAsString()); } if (!type.isJsonPrimitive()) { throw new JsonParseException( String.format("Variant field '%s' must be a string containing the variant type (%s)", VariantJson.FIELD_TYPE, StringHelper.join(VariantType.values(), ", "))); } final String typeStr = type.getAsString(); if (typeStr.equals("NULL")) { return Variant.NULL; } if (value == null || value.isJsonNull()) { throw new JsonParseException(String.format( "The type '%s' does not support a null value. Use variant type NULL instead.", typeStr)); } if (value.isJsonObject() || value.isJsonArray()) { throw new JsonParseException( "The variant value must be a JSON primitive matching the type. Arrays and objects are not supported"); } switch (type.getAsString()) { case "BOOLEAN": return Variant.valueOf(value.getAsBoolean()); case "STRING": return Variant.valueOf(value.getAsString()); case "DOUBLE": return Variant.valueOf(value.getAsDouble()); case "INT32": return Variant.valueOf(value.getAsInt()); case "INT64": return Variant.valueOf(value.getAsLong()); default: throw new JsonParseException(String.format("Type '%s' is unknown (known types: %s)", StringHelper.join(VariantType.values(), ", "))); } } throw new JsonParseException("Unknown serialization of Variant type"); }
From source file:org.eclipse.smarthome.binding.tradfri.internal.model.TradfriLightData.java
License:Open Source License
public PercentType getBrightness() { PercentType result = null;/*from w ww . ja v a 2 s . c o m*/ JsonElement dimmer = attributes.get(DIMMER); if (dimmer != null) { result = TradfriColor.xyBrightnessToPercentType(dimmer.getAsInt()); } return result; }
From source file:org.eclipse.smarthome.binding.tradfri.internal.model.TradfriLightData.java
License:Open Source License
@SuppressWarnings("unused") public int getTransitionTime() { JsonElement transitionTime = attributes.get(TRANSITION_TIME); if (transitionTime != null) { return transitionTime.getAsInt(); } else {//from ww w . j a v a 2s. c om return 0; } }