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; } }
@Override public String getString(int index, String defaultValue) { JsonString value = (JsonString) list.get(index); if (value != null) { return value.getString(); } else { return defaultValue; } }
@Override public Address parseAddress(JsonObject json) { JsonArray results = json.getJsonArray("results"); if (!results.isEmpty()) { Address address = new Address(); JsonObject result = (JsonObject) results.get(0); JsonArray components = result.getJsonArray("address_components"); for (JsonObject component : components.getValuesAs(JsonObject.class)) { String value = component.getString("short_name"); typesLoop: for (JsonString type : component.getJsonArray("types").getValuesAs(JsonString.class)) { switch (type.getString()) { case "street_number": address.setHouse(value); break typesLoop; case "route": address.setStreet(value); break typesLoop; case "locality": address.setSettlement(value); break typesLoop; case "administrative_area_level_2": address.setDistrict(value); break typesLoop; case "administrative_area_level_1": address.setState(value); break typesLoop; case "country": address.setCountry(value); break typesLoop; case "postal_code": address.setPostcode(value); break typesLoop; default: break; } } } return address; } return null; }
private Object jsonValueToObject(JsonValue jsonValue) { switch (jsonValue.getValueType()) { case FALSE: return Boolean.FALSE; case TRUE: return Boolean.TRUE; case NULL: return null; case STRING: { JsonString casted = (JsonString) jsonValue; return casted.getString(); } case NUMBER: { JsonNumber number = (JsonNumber) jsonValue; if (number.isIntegral()) { try { long l = number.longValueExact(); if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) { return l; } return number.intValueExact(); } catch (ArithmeticException ex) { return number.bigIntegerValueExact(); } } return number.doubleValue(); } case ARRAY: { assert jsonValue instanceof JsonArray; return (JsonArray) jsonValue; } case OBJECT: default: throw new AssertionError(jsonValue + " is not accepted as a column value"); } }
ObservableList<Question> getObservableList() throws IOException { String url = "http://api.stackexchange.com/2.2/search?tagged=javafx&site=stackoverflow"; URL host = new URL(url); JsonReader jr = Json.createReader(new GZIPInputStream(host.openConnection().getInputStream())); JsonObject jsonObject = jr.readObject(); JsonArray jsonArray = jsonObject.getJsonArray("items"); ObservableList<Question> answer = FXCollections.observableArrayList(); jsonArray .iterator() .forEachRemaining( (JsonValue e) -> { JsonObject obj = (JsonObject) e; JsonString name = obj.getJsonObject("owner").getJsonString("display_name"); JsonString quest = obj.getJsonString("title"); JsonNumber jsonNumber = obj.getJsonNumber("creation_date"); Question q = new Question(name.getString(), quest.getString(), jsonNumber.longValue() * 1000); answer.add(q); }); return answer; }
/** * http://docs.oracle.com/middleware/1213/wls/WLPRG/java-api-for-json-proc.htm#WLPRG1061 * * @param tree * @param key */ public static Object navigateTree(JsonValue tree, String key) { Object ret = null; if (key != null) System.out.print("Key " + key + ": "); switch (tree.getValueType()) { case OBJECT: System.out.println("OBJECT"); JsonObject object = (JsonObject) tree; for (String name : object.keySet()) navigateTree(object.get(name), name); break; case ARRAY: System.out.println("ARRAY"); JsonArray array = (JsonArray) tree; for (JsonValue val : array) navigateTree(val, null); break; case STRING: JsonString st = (JsonString) tree; System.out.println("STRING " + st.getString()); break; case NUMBER: JsonNumber num = (JsonNumber) tree; System.out.println("NUMBER " + num.toString()); break; case TRUE: System.out.println("TRUE"); case FALSE: System.out.println("FALSE"); case NULL: System.out.println(tree.getValueType().toString()); break; } return ret; }
public void logController(String topic, MqttMessage mqttMessage) { // get deviceId String[] split = topic.split("log/"); String deviceId = split[1]; // parse log try { JsonReader reader = Json.createReader(new StringReader(mqttMessage.toString())); JsonObject jsonMessage = reader.readObject(); String logType = jsonMessage.getString("type"); switch (logType) { case LOG_NORMAL: int temperature = 0; int timer = jsonMessage.getInt("time"); try { temperature = jsonMessage.getInt("temperature"); } catch (Exception se1) { // @todo: warning break; } JsonString subDeviceId = jsonMessage.getJsonString("subId"); if (subDeviceId == null) sessionHandle.drawTemperature(deviceId, timer, temperature); else sessionHandle.drawTemperature(deviceId, timer, temperature, subDeviceId.toString()); break; case LOG_WARNING: timer = jsonMessage.getInt("time"); subDeviceId = jsonMessage.getJsonString("subId"); int subdeviceNo = jsonMessage.getInt("number"); String deviceState = jsonMessage.getString("value"); String msg; switch (subdeviceNo) { case 1: msg = ("0".equals(deviceState)) ? "Button release" : "Button clicked"; break; case 2: msg = ("0".equals(deviceState)) ? "Cửa cuốn được cuộn lên" : "Đang thả cửa cuốn"; break; default: msg = DEFAULT_ALERT_MSG; break; } if (subDeviceId == null) sessionHandle.doAlert(deviceId, timer, msg); else sessionHandle.doAlert(deviceId, timer, msg, subDeviceId.toString()); break; case LOG_CONTROL: String state = jsonMessage.getString("light"); subdeviceNo = jsonMessage.getInt("no"); sessionHandle.updateLightState(deviceId, subdeviceNo, state); break; case LOG_ACK: subdeviceNo = jsonMessage.getInt("number"); deviceState = jsonMessage.getString("value"); state = ("0".equals(deviceState)) ? "off" : "on"; sessionHandle.ackLightState(deviceId, subdeviceNo, state); break; case LOG_DEVICE_STATUS: JsonArray lstDevice = jsonMessage.getJsonArray("status"); System.out.println("Update status:"); for (int i = 0; i < lstDevice.size(); i++) { JsonObject device = (JsonObject) lstDevice.get(i); System.out.println(device.toString()); subdeviceNo = device.getInt("no"); int intState = device.getInt("value"); state = (intState == 0) ? "off" : "on"; sessionHandle.updateLightState(deviceId, subdeviceNo, state); } sessionHandle.finishUpdateDeviceStatus(); break; default: } } catch (Exception ex) { System.out.println("Parse error"); System.out.println(topic); System.out.println(mqttMessage); System.out.println(ex.getMessage()); } }
private static boolean loadATMSwitchConfig(String connId) throws Exception { InputStream is = null; boolean isLoadedFlag = false; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); is = classLoader.getResource(atmSwitchConfigFileName).openStream(); if (is == null) { throw new Exception("Unable to load config file - " + atmSwitchConfigFileName); } try { JsonReader jsonReader = Json.createReader(is); JsonObject allConfigs = jsonReader.readObject(); JsonString logFileLocation = allConfigs.getJsonString(logFileLocationKey); if (logFileLocation == null) { throw new Exception(logFileLocationKey + " parameter missing in the configuration...."); } if ("".equals(connId)) logger = (new AsynchLogger(logFileLocation.toString() + "/ISOSysLog", Level.INFO)) .getLogger("ISOSysLog"); JsonArray serverConfigs = allConfigs.getJsonArray(serverConfigKey); if (serverConfigs == null) { throw new Exception( serverConfigKey + " parameter missing. No server Configurations specified...."); } logger.info("Initializing ATM Switch Configuration...."); if (manifestAttrs != null && "".equals(connId)) { logger.info( "Build version " + manifestAttrs.getValue("Implementation-Version") + " Build Date " + manifestAttrs.getValue("Build-Time")); } for (int i = 0; i < serverConfigs.size(); i++) { JsonObject serverConfig = serverConfigs.getJsonObject(i); JsonString host = serverConfig.getJsonString(serverHostKey); JsonNumber port = serverConfig.getJsonNumber(portKey); JsonNumber connTimeOut = serverConfig.getJsonNumber(connTimeOutKey); JsonNumber readTimeOut = serverConfig.getJsonNumber(readTimeOutKey); JsonNumber retry = serverConfig.getJsonNumber(retryKey); JsonNumber threadTimeOut = serverConfig.getJsonNumber(threadTimeOutKey); JsonString logLevelJson = serverConfig.getJsonString(loglevelKey); JsonNumber echoTimeInterval = serverConfig.getJsonNumber(echoTimeIntervalKey); JsonString uidFormat = serverConfig.getJsonString("uidFormat"); if (host == null || port == null) { logger.error( serverConfig + " Bad configuration for connection ( Host OR Port is missing ). Not Loading this connection...."); continue; } if (uidFormat == null) { logger.error( serverConfig + " Bad configuration for connection ( uidFormat is missing ). Not Loading this connection...."); continue; } Level level = null; if (logLevelJson == null) { level = Level.INFO; } else { String logLevel = logLevelJson.getString(); if (logLevel.equalsIgnoreCase("TRACE")) { level = Level.TRACE; } else if (logLevel.equalsIgnoreCase("DEBUG")) { level = Level.DEBUG; } else { level = Level.INFO; } } MessageUIDGenerator messageUIDGenerator = MessageUIDGeneratorFactory.getMessageUIDGenerator(uidFormat.toString()); if (!"".equals(connId)) { if (!connId.equalsIgnoreCase(host.getString() + "_" + port.intValue())) { continue; } } ATMSwitchTCPHandler.manualStopPool.put( host.getString() + "_" + String.valueOf(port.intValue()), Boolean.FALSE); ConnectionBean bean = new ConnectionBean( host.getString(), port.intValue(), (connTimeOut == null ? 8000 : connTimeOut.intValue()), (readTimeOut == null ? 8000 : readTimeOut.intValue()), (threadTimeOut == null ? 5000 : threadTimeOut.intValue()), (retry == null ? 3 : retry.intValue()), (echoTimeInterval == null ? 0 : echoTimeInterval.intValue())); ServerContainer container = new ServerContainer(bean, logFileLocation.getString(), level, messageUIDGenerator); try { if (container.connect(false)) { logger.info(bean.toString() + " Loaded...."); isLoadedFlag = true; } else { logger.warn(bean.toString() + " could not be loaded...."); } } catch (InterruptedException e) { logger.error( "( " + bean.getUniqueName() + " ,loadAllClientConnection(, ,) ) Interrupted Exception", e); } catch (ExecutionException e) { logger.error( "( " + bean.getUniqueName() + " ,loadAllClientConnection(, ,) ) ExecutionException", e); } catch (IOException e) { logger.error( "( " + bean.getUniqueName() + " ,loadAllClientConnection(, ,) ) IOException", e); } catch (Exception e) { logger.error( "( " + bean.getUniqueName() + " ,loadAllClientConnection(, ,) ) Exception", e); } } } finally { if (is != null) { try { is.close(); } catch (IOException e) { logger.error("IOException in closing the stream for JSON config property file....", e); } } } return isLoadedFlag; }