private void mergeUpdate(JsonObject update, JsonObject master) { for (Map.Entry<String, JsonElement> attr : update.entrySet()) { if ((null == attr.getValue()) || attr.getValue().isJsonNull()) { // TODO use singleton to reduce memory footprint master.add(attr.getKey(), new JsonNull()); } assertCompatibility(master.get(attr.getKey()), attr.getValue()); if (attr.getValue() instanceof JsonPrimitive) { if (!master.has(attr.getKey()) || !master.get(attr.getKey()).equals(attr.getValue())) { master.add(attr.getKey(), attr.getValue()); } } else if (attr.getValue() instanceof JsonObject) { if (!master.has(attr.getKey()) || master.get(attr.getKey()).isJsonNull()) { // copy whole subtree master.add(attr.getKey(), attr.getValue()); } else { // recurse to merge attribute updates mergeUpdate( attr.getValue().getAsJsonObject(), master.get(attr.getKey()).getAsJsonObject()); } } else if (attr.getValue() instanceof JsonArray) { // TODO any way to correlate elements between arrays? will need concept of // element identity to merge elements master.add(attr.getKey(), attr.getValue()); } } }
private SegmentItem deserializeItem(JsonObject json, JsonDeserializationContext context) { if (!json.has("actions")) { throw new ProtectionParseException("Missing actions identifier"); } SegmentItem segment = new SegmentItem(); segment.types.addAll( deserializeAsArray( json.get("actions"), context, new TypeToken<ItemType>() {}, new TypeToken<List<ItemType>>() {}.getType())); json.remove("actions"); if (json.has("isAdjacent")) { segment.isAdjacent = json.get("isAdjacent").getAsBoolean(); json.remove("isAdjacent"); } if (json.has("clientUpdate")) { JsonObject jsonClientUpdate = json.get("clientUpdate").getAsJsonObject(); segment.clientUpdate = new ClientBlockUpdate( (Volume) context.deserialize(jsonClientUpdate.get("coords"), Volume.class)); if (jsonClientUpdate.has("directional")) { segment.directionalClientUpdate = jsonClientUpdate.get("directional").getAsBoolean(); } json.remove("clientUpdate"); } return segment; }
@Override public PluginManifest deserialize( final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { final PluginManifest pluginManifest = new PluginManifest(); final JsonObject result = json.getAsJsonObject(); if (!result.has("name")) { throw new IllegalArgumentException("No name present in manifest."); } if (!result.has("main")) { throw new IllegalArgumentException("No main present in manifest."); } if (result.has("disabled")) { final boolean disabled = result.get("disabled").getAsBoolean(); pluginManifest.setDisabled(disabled); } if (result.has("author")) { final String author = result.get("author").getAsString(); pluginManifest.setAuthor(author); } if (result.has("description")) { final String description = result.get("description").getAsString(); pluginManifest.setDescription(description); } final String name = result.get("name").getAsString(); final String mainClass = result.get("main").getAsString(); pluginManifest.setName(name); pluginManifest.setMainClass(mainClass); return pluginManifest; }
private static void readJsonFile() { try (JsonReader jsonReader = Json.createReader( new FileReader( Paths.get(System.getProperty("user.dir"), "target/myData.json").toString()))) { JsonStructure jsonStructure = jsonReader.read(); JsonValue.ValueType valueType = jsonStructure.getValueType(); if (valueType == JsonValue.ValueType.OBJECT) { JsonObject jsonObject = (JsonObject) jsonStructure; JsonValue firstName = jsonObject.get("firstName"); LOGGER.info("firstName=" + firstName); JsonValue emailAddresses = jsonObject.get("phoneNumbers"); if (emailAddresses.getValueType() == JsonValue.ValueType.ARRAY) { JsonArray jsonArray = (JsonArray) emailAddresses; for (int i = 0; i < jsonArray.size(); i++) { JsonValue jsonValue = jsonArray.get(i); LOGGER.info("emailAddress(" + i + "): " + jsonValue); } } } else { LOGGER.warning("First object is not of type " + JsonValue.ValueType.OBJECT); } } catch (FileNotFoundException e) { LOGGER.severe("Failed to open file: " + e.getMessage()); } }
@Override public HanabiraBoard deserialize( JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObject boardsJsonObject = json.getAsJsonObject().get("boards").getAsJsonObject(); Set<Map.Entry<String, JsonElement>> boardsSet = boardsJsonObject.entrySet(); if (boardsSet.size() > 1) { throw new IllegalArgumentException("Few board entries received for a request"); } Map.Entry<String, JsonElement> boardEntry = boardsSet.iterator().next(); boardKey = boardEntry.getKey(); JsonObject boardObject = boardEntry.getValue().getAsJsonObject(); int pages = boardObject.get("pages").getAsInt(); HanabiraBoard cachedBoard = Hanabira.getStem().findBoardByKey(boardKey); if (cachedBoard == null) { cachedBoard = new HanabiraBoard(boardKey, pages, null); Hanabira.getStem().saveBoard(cachedBoard); } else { cachedBoard.update(pages, null); } JsonElement pageElement = boardObject.get("page"); int page = (pageElement == null) ? 0 : pageElement.getAsInt(); List<Integer> threadsOnPageIds = new ArrayList<>(); for (JsonElement threadElement : boardObject.getAsJsonArray("threads")) { threadsOnPageIds.add( createThreadWithPosts(threadElement.getAsJsonObject(), boardKey).getThreadId()); } cachedBoard.updatePage(page, threadsOnPageIds); return cachedBoard; }
private SegmentBlock deserializeBlock(JsonObject json, JsonDeserializationContext context) { if (!json.has("actions")) { throw new ProtectionParseException("Missing actions identifier"); } SegmentBlock segment = new SegmentBlock(); segment.types.addAll( deserializeAsArray( json.get("actions"), context, new TypeToken<BlockType>() {}, new TypeToken<List<BlockType>>() {}.getType())); json.remove("actions"); if (json.has("meta")) { segment.meta = json.get("meta").getAsInt(); json.remove("meta"); } if (json.has("clientUpdate")) { segment.clientUpdate = new ClientBlockUpdate( (Volume) context.deserialize( json.get("clientUpdate").getAsJsonObject().get("coords"), Volume.class)); json.remove("clientUpdate"); } return segment; }
/** * Returns the information for the given node-id * * @param id the id of the host which connectivity information u want * @return NodeInfo object with all information * @throws FileNotFoundException * @throws Exception */ public NodeInfo getNodeConnectivityInfoForId(String id) throws FileNotFoundException, Exception { // reading and parsing the hostfile JsonReader reader = new JsonReader(new FileReader(fileHosts)); JsonParser parser = new JsonParser(); JsonArray hostsArray = parser.parse(reader).getAsJsonArray(); NodeInfo nodeInfo = null; // gernerating NodeInfo for id for (JsonElement obj : hostsArray) { JsonObject host = obj.getAsJsonObject(); try { String hostId = host.get(GraphManager.JSON_ID).getAsString(); if (hostId.equals(id)) { nodeInfo = new NodeInfo( hostId, host.get(GraphManager.JSON_HOSTNAME).getAsString(), Integer.valueOf(host.get(GraphManager.JSON_PORT).getAsString())); break; } } catch (Exception e) { throw new JsonParseException( "Fehler in der JSON-Konfigdatei: Bitte README.pdf fuer das richtige Format lesen"); } } if (nodeInfo == null) { throw new Exception("No connectivity info for id found"); } return nodeInfo; }
@Override public Flag deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); FlagType flagType = FlagType.valueOf(jsonObject.get("flagType").getAsString()); return new Flag(flagType, jsonObject.get("value").getAsString()); }
private static boolean parseProperty( JsonElement propertyElement, IConfigPropertyHolder property, Gson gson) { if (!(propertyElement instanceof JsonObject)) return true; JsonObject propertyNode = propertyElement.getAsJsonObject(); JsonElement value = propertyNode.get(VALUE_TAG); if (value == null) return true; try { Object parsedValue = gson.fromJson(value, property.getType()); property.setValue(parsedValue); } catch (Exception e) { Log.warn(e, "Failed to parse value of field %s:%s", property.category(), property.name()); return true; } JsonElement comment = propertyNode.get(COMMENT_TAG); final String expectedComment = property.comment(); if (comment == null) { return !Strings.isNullOrEmpty(expectedComment); } else if (comment.isJsonPrimitive()) { String commentValue = comment.getAsString(); return !expectedComment.equals(commentValue); } return true; }
public AbstractProperty(String name, String category, JsonObject data) { super(name, category); canRandomize = !(data.has("random") && data.get("random").isJsonPrimitive() && data.get("random").getAsJsonPrimitive().isBoolean() && !data.get("random").getAsBoolean()); }
/** * @param id the id of the node which neighbours you want to get * @return returns a list all neighbours for the given host id * @throws FileNotFoundException * @throws ParseException * @throws Exception */ public ArrayList<NodeInfo> getHostsListForId(String id) throws Exception { // Reading the graphfile File f = new File(this.fileGraph); FileReader in = new FileReader(f); // parsing the graphfile Parser graphParser = new Parser(); graphParser.parse(in); ArrayList<Graph> graphList = graphParser.getGraphs(); if (graphList.size() < 1) { throw new Exception("No graph in graphfile found."); } Graph graph = graphList.get(0); ArrayList<Edge> edges = graph.getEdges(); // getting all neighbours ArrayList<String> neighbours = new ArrayList<>(); for (Edge edge : edges) { String sourceId = edge.getSource().getNode().getId().getId(); String targetId = edge.getTarget().getNode().getId().getId(); if (sourceId.equals(id)) { neighbours.add(targetId); } else if (targetId.equals(id)) { neighbours.add(sourceId); } } // reading the host information File file = new File(this.fileHosts); Scanner input; ArrayList<NodeInfo> hosts = new ArrayList<>(); JsonReader reader = new JsonReader(new FileReader(fileHosts)); // parsing the host information Gson gson = new Gson(); JsonParser parser = new JsonParser(); JsonArray hostsArray = parser.parse(reader).getAsJsonArray(); // matching the hostinformation for the neighbours for (JsonElement obj : hostsArray) { JsonObject host = obj.getAsJsonObject(); String hostId = host.get(GraphManager.JSON_ID).getAsString(); if (neighbours.contains(hostId)) { if (!listContainsHost(hosts, hostId)) { hosts.add( new NodeInfo( host.get(GraphManager.JSON_ID).getAsString(), host.get(GraphManager.JSON_HOSTNAME).getAsString(), host.get(GraphManager.JSON_PORT).getAsInt())); } } } return hosts; }
private static void addFolder(FileSystem fs, Path p, JsonArray succeeded, JsonArray failed) { try { if (fs == null) return; for (FileStatus file : fs.listStatus(p)) { Path pfs = file.getPath(); if (file.isDir()) { addFolder(fs, pfs, succeeded, failed); } else { Key k = Key.make(pfs.toString()); long size = file.getLen(); Value val = null; if (pfs.getName().endsWith(Extensions.JSON)) { JsonParser parser = new JsonParser(); JsonObject json = parser.parse(new InputStreamReader(fs.open(pfs))).getAsJsonObject(); JsonElement v = json.get(Constants.VERSION); if (v == null) throw new RuntimeException("Missing version"); JsonElement type = json.get(Constants.TYPE); if (type == null) throw new RuntimeException("Missing type"); Class c = Class.forName(type.getAsString()); OldModel model = (OldModel) c.newInstance(); model.fromJson(json); } else if (pfs.getName().endsWith(Extensions.HEX)) { // Hex file? FSDataInputStream s = fs.open(pfs); int sz = (int) Math.min(1L << 20, size); // Read up to the 1st meg byte[] mem = MemoryManager.malloc1(sz); s.readFully(mem); // Convert to a ValueArray (hope it fits in 1Meg!) ValueArray ary = new ValueArray(k, 0).read(new AutoBuffer(mem)); val = new Value(k, ary, Value.HDFS); } else if (size >= 2 * ValueArray.CHUNK_SZ) { val = new Value( k, new ValueArray(k, size), Value.HDFS); // ValueArray byte wrapper over a large file } else { val = new Value(k, (int) size, Value.HDFS); // Plain Value val.setdsk(); } DKV.put(k, val); Log.info("PersistHdfs: DKV.put(" + k + ")"); JsonObject o = new JsonObject(); o.addProperty(Constants.KEY, k.toString()); o.addProperty(Constants.FILE, pfs.toString()); o.addProperty(Constants.VALUE_SIZE, file.getLen()); succeeded.add(o); } } } catch (Exception e) { Log.err(e); JsonObject o = new JsonObject(); o.addProperty(Constants.FILE, p.toString()); o.addProperty(Constants.ERROR, e.getMessage()); failed.add(o); } }
@Override public ColumnNameTypeValue deserialize( JsonElement element, Type type, JsonDeserializationContext ctx) throws JsonParseException { final JsonObject object = element.getAsJsonObject(); String name = null; ColumnType columnType = null; Object value = null; if (object != null && object.has(COLUMN_FIELD) && object.has(TYPE_FIELD)) { name = object.get(COLUMN_FIELD).getAsString(); columnType = ColumnType.valueOf(object.get(TYPE_FIELD).getAsString()); if (object.has(VALUE_FIELD)) { JsonElement jsonValue = object.get(VALUE_FIELD); switch (columnType) { case BOOLEAN: value = jsonValue.getAsBoolean(); break; case DOUBLE: value = jsonValue.getAsDouble(); break; case FLOAT: value = jsonValue.getAsFloat(); break; case INTEGER: value = jsonValue.getAsInt(); break; case LONG: value = jsonValue.getAsLong(); break; case STRING: value = jsonValue.getAsString(); break; default: break; } } else { log.warn("Column with name {} has no value", name); } if (log.isDebugEnabled()) { log.debug( "Values obtained into ColumnNameTypeValue deserialization: " + "NAME: {}, VALUE: {}, COLUMNTYPE: {}", name, value, columnType); } } else { log.warn( "Error deserializing ColumnNameTypeValue from json. JsonObject is not complete: {}", element); } return new ColumnNameTypeValue(name, columnType, value); }
private StringBuilder stats(StringBuilder sb, JsonElement json) { if (json == null) { return sb.append(" / / "); } else { JsonObject obj = json.getAsJsonObject(); return sb.append( String.format( "%4.1f / %4.1f / %4.1f", obj.get(MIN).getAsDouble(), obj.get(MAX).getAsDouble(), obj.get(MEAN).getAsDouble())); } }
@POST public JsonObject saveBook(final JsonObject book) { long id = System.nanoTime(); JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder(); JsonObject newBook = jsonObjectBuilder .add("bookId", id) .add("bookName", book.get("bookName")) .add("publisher", book.get("publisher")) .build(); BookResource.memoryBase.put(id, newBook); return newBook; }
private void setBuildStatus(CIBuild ciBuild, CIJob job) throws PhrescoException { S_LOGGER.debug("Entering Method CIManagerImpl.setBuildStatus(CIBuild ciBuild)"); S_LOGGER.debug("setBuildStatus() url = " + ciBuild.getUrl()); String buildUrl = ciBuild.getUrl(); String jenkinsUrl = job.getJenkinsUrl() + ":" + job.getJenkinsPort(); buildUrl = buildUrl.replaceAll( "localhost:" + job.getJenkinsPort(), jenkinsUrl); // display the jenkins running url in ci list String response = getJsonResponse(buildUrl + API_JSON); JsonParser parser = new JsonParser(); JsonElement jsonElement = parser.parse(response); JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonElement resultJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_RESULT); JsonElement idJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_ID); JsonElement timeJson = jsonObject.get(FrameworkConstants.CI_JOB_BUILD_TIME_STAMP); JsonArray asJsonArray = jsonObject.getAsJsonArray(FrameworkConstants.CI_JOB_BUILD_ARTIFACTS); if (jsonObject .get(FrameworkConstants.CI_JOB_BUILD_RESULT) .toString() .equals(STRING_NULL)) { // when build is result is not known ciBuild.setStatus(INPROGRESS); } else if (resultJson.getAsString().equals(CI_SUCCESS_FLAG) && asJsonArray.size() < 1) { // when build is success and zip relative path is not added in json ciBuild.setStatus(INPROGRESS); } else { ciBuild.setStatus(resultJson.getAsString()); // download path for (JsonElement jsonArtElement : asJsonArray) { String buildDownloadZip = jsonArtElement .getAsJsonObject() .get(FrameworkConstants.CI_JOB_BUILD_DOWNLOAD_PATH) .toString(); if (buildDownloadZip.endsWith(CI_ZIP)) { if (debugEnabled) { S_LOGGER.debug("download artifact " + buildDownloadZip); } ciBuild.setDownload(buildDownloadZip); } } } ciBuild.setId(idJson.getAsString()); String dispFormat = DD_MM_YYYY_HH_MM_SS; ciBuild.setTimeStamp(getDate(timeJson.getAsString(), dispFormat)); }
@Override public MoveStrategy deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); String type = jsonObject.get("type").getAsString(); JsonElement element = jsonObject.get("properties"); try { String thepackage = "bots."; return context.deserialize(element, Class.forName(thepackage + type)); } catch (ClassNotFoundException cnfe) { throw new JsonParseException("Unknown element type: " + type, cnfe); } }
private void parsePlugins(String context, QueryMetric queryMetric, JsonArray plugins) throws BeanValidationException, QueryException { for (int I = 0; I < plugins.size(); I++) { JsonObject pluginJson = plugins.get(I).getAsJsonObject(); JsonElement name = pluginJson.get("name"); if (name == null || name.getAsString().isEmpty()) throw new BeanValidationException( new SimpleConstraintViolation("plugins[" + I + "]", "must have a name"), context); String pluginContext = context + ".plugins[" + I + "]"; String pluginName = name.getAsString(); QueryPlugin plugin = m_pluginFactory.createQueryPlugin(pluginName); if (plugin == null) throw new BeanValidationException( new SimpleConstraintViolation(pluginName, "invalid query plugin name"), pluginContext); deserializeProperties(pluginContext, pluginJson, pluginName, plugin); validateObject(plugin, pluginContext); queryMetric.addPlugin(plugin); } }
private SegmentSpecialBlock deserializeSpecialBlock( JsonObject json, JsonDeserializationContext context) { SegmentSpecialBlock segment = new SegmentSpecialBlock(); if (json.has("meta")) { segment.meta = json.get("meta").getAsInt(); json.remove("meta"); } if (json.has("isAlwaysBreakable")) { segment.isAlwaysBreakable = json.get("isAlwaysBreakable").getAsBoolean(); json.remove("isAlwaysBreakable"); } return segment; }
private JsonElement get(final JsonObject wrapper, String memberName) { final JsonElement elem = wrapper.get(memberName); if (elem == null) throw new JsonParseException( "no '" + memberName + "' member found in what was expected to be an interface wrapper"); return elem; }
@Override public AppAudioSession deserialize( JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject jsonSession = jsonElement.getAsJsonObject(); AppAudioSession session = new AppAudioSession(); session.ID = jsonSession.get("ID").getAsString(); session.Name = jsonSession.get("Name").getAsString(); session.Volume = jsonSession.get("Volume").getAsInt(); session.Muted = jsonSession.get("Muted").getAsBoolean(); byte[] byt = Base64.decode(jsonSession.get("Icon").getAsString(), Base64.DEFAULT); session.Icon = BitmapFactory.decodeByteArray(byt, 0, byt.length); return session; }
@Then("^I parse the string and print keys and values$") public void i_parse_the_string_and_print_keys_and_values() throws Throwable { System.out.println(json); JsonParser parser = new JsonParser(); JsonObject myobject = (JsonObject) parser.parse(json); // Accessing the value of "desc" System.out.println(myobject.get("desc")); // Deserializing the value into JSONObject JsonObject descValue = (JsonObject) myobject.get("desc"); // Printing the someKey value using JsonObject System.out.println("SomeKey Value--" + descValue.get("someKey")); // Retrieving the JSON Element -- JsonElement can represent a string, array or other data types JsonElement someElement = descValue.get("someKey"); // Printing a value again System.out.println("SomeKey Value--" + someElement.getAsString()); }
public static void dumpJSON(JsonValue tree, String key, String depthPrefix) { if (key != null) logger.info(depthPrefix + "Key " + key + ": "); switch (tree.getValueType()) { case OBJECT: logger.info(depthPrefix + "OBJECT"); JsonObject object = (JsonObject) tree; for (String name : object.keySet()) dumpJSON(object.get(name), name, depthPrefix + " "); break; case ARRAY: logger.info(depthPrefix + "ARRAY"); JsonArray array = (JsonArray) tree; for (JsonValue val : array) dumpJSON(val, null, depthPrefix + " "); break; case STRING: JsonString st = (JsonString) tree; logger.info(depthPrefix + "STRING " + st.getString()); break; case NUMBER: JsonNumber num = (JsonNumber) tree; logger.info(depthPrefix + "NUMBER " + num.toString()); break; case TRUE: case FALSE: case NULL: logger.info(depthPrefix + tree.getValueType().toString()); break; } }
private void parseGroupBy(String context, QueryMetric queryMetric, JsonArray groupBys) throws QueryException, BeanValidationException { for (int J = 0; J < groupBys.size(); J++) { String groupContext = "group_by[" + J + "]"; JsonObject jsGroupBy = groupBys.get(J).getAsJsonObject(); JsonElement nameElement = jsGroupBy.get("name"); if (nameElement == null || nameElement.getAsString().isEmpty()) throw new BeanValidationException( new SimpleConstraintViolation(groupContext, "must have a name"), context); String name = nameElement.getAsString(); GroupBy groupBy = m_groupByFactory.createGroupBy(name); if (groupBy == null) throw new BeanValidationException( new SimpleConstraintViolation(groupContext + "." + name, "invalid group_by name"), context); deserializeProperties(context + "." + groupContext, jsGroupBy, name, groupBy); validateObject(groupBy, context + "." + groupContext); groupBy.setStartDate(queryMetric.getStartTime()); queryMetric.addGroupBy(groupBy); } }
public WxMpUserList deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject o = json.getAsJsonObject(); WxMpUserList wxMpUserList = new WxMpUserList(); wxMpUserList.setTotal(GsonHelper.getInteger(o, "total")); wxMpUserList.setCount(GsonHelper.getInteger(o, "count")); wxMpUserList.setNextOpenId(GsonHelper.getString(o, "next_openid")); if (!o.get("data").isJsonNull() && !o.get("data").getAsJsonObject().get("openid").isJsonNull()) { JsonArray data = o.get("data").getAsJsonObject().get("openid").getAsJsonArray(); for (int i = 0; i < data.size(); i++) { wxMpUserList.getOpenIds().add(GsonHelper.getAsString(data.get(i))); } } return wxMpUserList; }
public void processMessage(String message) { JsonParser parser = new JsonParser(); JsonObject messageJSON = (JsonObject) parser.parse(message); String postedURL = messageJSON.get("postedURL").getAsString(); AlchemyAPI alchemyObj = AlchemyAPI.GetInstanceFromString("5fc91e98eacfa5ebf83440e8c6a61d0f60fa380b"); // String URLString = // "http://www.huffingtonpost.com/2015/04/05/report-vegan-diet_n_7008156.html"; System.out.println("URL sent to URLGetAuthor AlchemyAPI --> " + postedURL); Document doc = null; try { doc = alchemyObj.URLGetAuthor(postedURL); } catch (XPathExpressionException | IOException | SAXException | ParserConfigurationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String convertDocToString = getStringFromDocument(doc); // System.out.println(convertDocToString); String alchemyAPIResult = null; try { alchemyAPIResult = returnResultFromXML(convertDocToString); } catch (SAXException | IOException | ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } // System.out.println(convertDocToString); System.out.println( "Output from URLGetAuthor AlchemyAPI: Author is --> " + alchemyAPIResult.toUpperCase()); JsonObject reply = new JsonObject(); reply.addProperty("Author", alchemyAPIResult.toUpperCase()); reply.addProperty("AlchemyBackend", "JavaAPI: " + toString()); SendOptions opts = SendOptions.builder().setQos(QOS.AT_LEAST_ONCE).build(); mqlightClient.send( PUBLISH_TOPIC, reply.toString(), null, opts, new CompletionListener<Void>() { public void onSuccess(NonBlockingClient client, Void context) { logger.log(Level.INFO, "Sent reply!"); } public void onError(NonBlockingClient client, Void context, Exception exception) { logger.log(Level.INFO, "Error!." + exception.toString()); } }, null); }
public WxCpUser deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject o = json.getAsJsonObject(); WxCpUser user = new WxCpUser(); user.setUserId(GsonHelper.getString(o, "userid")); user.setName(GsonHelper.getString(o, "name")); if (o.get("department") != null) { JsonArray departJsonArray = o.get("department").getAsJsonArray(); Integer[] departIds = new Integer[departJsonArray.size()]; int i = 0; for (JsonElement jsonElement : departJsonArray) { departIds[i++] = jsonElement.getAsInt(); } user.setDepartIds(departIds); } user.setPosition(GsonHelper.getString(o, "position")); user.setMobile(GsonHelper.getString(o, "mobile")); Integer gender = GsonHelper.getInteger(o, "gender"); if (new Integer(1).equals(gender)) { user.setGender("男"); } else if (new Integer(2).equals(gender)) { user.setGender("女"); } else { user.setGender("未知"); } user.setTel(GsonHelper.getString(o, "tel")); user.setEmail(GsonHelper.getString(o, "email")); user.setWeiXinId(GsonHelper.getString(o, "weixinid")); user.setAvatar(GsonHelper.getString(o, "avatar")); user.setStatus(GsonHelper.getInteger(o, "status")); if (GsonHelper.isNotNull(o.get("extattr"))) { JsonArray attrJsonElements = o.get("extattr").getAsJsonObject().get("attrs").getAsJsonArray(); for (JsonElement attrJsonElement : attrJsonElements) { WxCpUser.Attr attr = new WxCpUser.Attr( GsonHelper.getString(attrJsonElement.getAsJsonObject(), "name"), GsonHelper.getString(attrJsonElement.getAsJsonObject(), "value")); user.getExtAttrs().add(attr); } } return user; }
public static <V> Map<String, V> parseToMap(JsonObject jo) { Map<String, V> map = CollectionKit.newHashMap(); if (jo != null) { List<String> names = jo.names(); for (String name : names) { map.put(name, (V) jo.get(name)); } } return map; }
@Override public String build(Response response, JsonObject t, String contextName) { int n = t.get(Constants.TREE_COUNT).getAsInt(); StringBuilder sb = new StringBuilder(); if (n > 0) { sb.append("<h3>Trees</h3>"); sb.append(t.get(Constants.TREE_COUNT)).append(" trees with min/max/mean depth of "); stats(sb, t.get(TREE_DEPTH)).append(" and leaf of "); stats(sb, t.get(TREE_LEAVES)).append(".<br>"); for (int i = 0; i < n; ++i) { sb.append( RFTreeView.link(_modelKey.value(), i, _dataKey.value(), Integer.toString(i + 1))) .append(" "); } } else { sb.append("<h3>No trees yet...</h3>"); } return sb.toString(); }
/** * Gson invokes this call-back method during deserialization when it encounters a field of the * specified type. * * <p>In the implementation of this call-back method, you should consider invoking {@link * com.google.gson.JsonDeserializationContext#deserialize(com.google.gson.JsonElement, * java.lang.reflect.Type)} method to create objects for any non-trivial field of the returned * object. However, you should never invoke it on the the same type passing {@code jsonElement} * since that will cause an infinite loop (Gson will call your call-back method again). * * @param jsonElement The Json data being deserialized * @param typeOfT The type of the Object to deserialize to * @param context * @return a deserialized object of the specified type typeOfT which is a subclass of {@code T} * @throws com.google.gson.JsonParseException if jsonElement is not in the expected format of * {@code typeofT} */ @Override public EnergyValue deserialize( JsonElement jsonElement, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonEnergyValue = (JsonObject) jsonElement; if (jsonEnergyValue.get("type") != null && jsonEnergyValue.get("type").isJsonPrimitive() && jsonEnergyValue.get("value") != null && jsonEnergyValue.get("value").isJsonPrimitive()) { EnergyType energyType = EnergyType.getEnergyTypeFromOrdinal(jsonEnergyValue.get("type").getAsInt()); float energyValue = jsonEnergyValue.get("value").getAsFloat(); if (Float.compare(energyValue, 0f) > 0) { return new EnergyValue(energyValue, energyType); } } return null; }