List of usage examples for io.vertx.core.json JsonObject getJsonArray
public JsonArray getJsonArray(String key)
From source file:org.sfs.integration.java.BaseTestVerticle.java
License:Apache License
@Before public void before(TestContext context) { vertx = rule.vertx();/*w w w .j av a 2s.c om*/ Async async = context.async(); aVoid().flatMap(aVoid -> { String clusteruuid = UUID.randomUUID().toString(); try { rootTmpDir = createTempDirectory(""); esTempDir = createTempDirectory(rootTmpDir, format("test-cluster-%s", clusteruuid)); tmpDir = createTempDirectory(rootTmpDir, valueOf(currentTimeMillis())); } catch (IOException e) { throw new RuntimeException(e); } int esPort = findFreePort(9300, 9400); esHost = "127.0.0.1:" + esPort; esClusterName = format("test-cluster-%s", clusteruuid); esNodeName = format("test-server-node-%s", clusteruuid); Builder settings = settingsBuilder(); settings.put("script.groovy.sandbox.enabled", false); settings.put("cluster.name", esClusterName); settings.put("node.name", esNodeName); settings.put("http.enabled", false); settings.put("discovery.zen.ping.multicast.enabled", false); settings.put("discovery.zen.ping.unicast.hosts", esHost); settings.put("transport.tcp.port", esPort); settings.put("network.host", "127.0.0.1"); settings.put("node.data", true); settings.put("node.master", true); settings.put("path.home", esTempDir); esNode = nodeBuilder().settings(settings).node(); esClient = esNode.client(); JsonObject verticleConfig; Buffer buffer = vertx.fileSystem().readFileBlocking( currentThread().getContextClassLoader().getResource("intgtestconfig.json").getFile()); verticleConfig = new JsonObject(buffer.toString(UTF_8)); verticleConfig.put("fs.home", tmpDir.toString()); if (!verticleConfig.containsKey("elasticsearch.cluster.name")) { verticleConfig.put("elasticsearch.cluster.name", esClusterName); } if (!verticleConfig.containsKey("elasticsearch.node.name")) { verticleConfig.put("elasticsearch.node.name", esNodeName); } if (!verticleConfig.containsKey("elasticsearch.discovery.zen.ping.unicast.hosts")) { verticleConfig.put("elasticsearch.discovery.zen.ping.unicast.hosts", new JsonArray().add(esHost)); } if (!verticleConfig.containsKey("http.listen.addresses")) { int freePort = findFreePort(6677, 7777); verticleConfig.put("http.listen.addresses", new JsonArray().add(HostAndPort.fromParts("127.0.0.1", freePort).toString())); } HostAndPort hostAndPort = HostAndPort .fromString(verticleConfig.getJsonArray("http.listen.addresses").getString(0)); HttpClientOptions httpClientOptions = new HttpClientOptions(); httpClientOptions.setDefaultPort(hostAndPort.getPort()).setDefaultHost(hostAndPort.getHostText()) .setMaxPoolSize(25).setConnectTimeout(1000).setKeepAlive(false).setLogActivity(true); HttpClientOptions httpsClientOptions = new HttpClientOptions(); httpsClientOptions.setDefaultPort(hostAndPort.getPort()).setDefaultHost(hostAndPort.getHostText()) .setMaxPoolSize(25).setConnectTimeout(1000).setKeepAlive(false).setLogActivity(true) .setSsl(true); httpClient = vertx.createHttpClient(httpClientOptions); httpsClient = vertx.createHttpClient(httpsClientOptions); SfsServer sfsServer = new SfsServer(); ObservableFuture<String> handler = RxHelper.observableFuture(); vertx.deployVerticle(sfsServer, new DeploymentOptions().setConfig(verticleConfig), handler.toHandler()); return handler.map(new ToVoid<>()).doOnNext(aVoid1 -> { vertxContext = sfsServer.vertxContext(); checkState(vertxContext != null, "VertxContext was null on Verticle %s", sfsServer); }).onErrorResumeNext(throwable -> { throwable.printStackTrace(); return cleanup().flatMap(aVoid1 -> Observable.<Void>error(throwable)); }); }).subscribe(new TestSubscriber(context, async)); }
From source file:org.sfs.util.ConfigHelper.java
License:Apache License
public static Iterable<String> getArrayFieldOrEnv(JsonObject config, String name, Iterable<String> defaultValue) { String envVar = formatEnvVariable(name); //USED_ENV_VARS.add(envVar); if (config.containsKey(name)) { JsonArray values = config.getJsonArray(name); if (values != null) { Iterable<String> iterable = FluentIterable.from(values).filter(Predicates.notNull()) .filter(input -> input instanceof String).transform(input -> input.toString()); log(name, envVar, name, iterable); return iterable; }// ww w . j ava2s .co m } else { String value = System.getenv(envVar); if (value != null) { log(name, envVar, envVar, value); return Splitter.on(',').split(value); } } log(name, envVar, null, defaultValue); return defaultValue; }
From source file:org.sfs.vo.Segment.java
License:Apache License
public T merge(JsonObject document) { Long id = document.getLong("id"); checkNotNull(id, "id cannot be null"); checkState(id == this.id, "id was %s, expected %s", id, this.id); setReadMd5(document.getBinary("read_md5")); setReadSha512(document.getBinary("read_sha512")); setReadLength(document.getLong("read_length")); setWriteSha512(document.getBinary("write_sha512")); setWriteLength(document.getLong("write_length")); isTinyData = document.getBoolean("is_tiny_data"); tinyData = document.getBinary("tiny_data"); isTinyDataDeleted = document.getBoolean("is_tiny_data_deleted"); String cipherKey = document.getString("container_key_id"); byte[] cipherSalt = document.getBinary("cipher_salt"); segmentCipher = new SegmentCipher(cipherKey, cipherSalt); JsonArray blobJsonArray = document.getJsonArray("blobs"); this.blobs.clear(); if (blobJsonArray != null) { for (Object o : blobJsonArray) { JsonObject jsonObject = (JsonObject) o; TransientBlobReference transientBlobReference = new TransientBlobReference(this).merge(jsonObject); this.blobs.add(transientBlobReference); }/*from ww w. jav a 2 s. c o m*/ } return (T) this; }
From source file:org.sfs.vo.ServiceDef.java
License:Apache License
public T merge(JsonObject jsonObject) { this.id = jsonObject.getString("id"); this.lastUpdate = fromDateTimeString(jsonObject.getString("update_ts")); this.master = jsonObject.getBoolean("master_node"); this.dataNode = jsonObject.getBoolean("data_node"); this.documentCount = jsonObject.getLong("document_count"); this.availableProcessors = jsonObject.getInteger("available_processors"); this.freeMemory = jsonObject.getLong("free_memory"); this.maxMemory = jsonObject.getLong("max_memory"); this.totalMemory = jsonObject.getLong("total_memory"); JsonObject jsonFileSystem = jsonObject.getJsonObject("file_system"); if (jsonFileSystem != null) { this.fileSystem = new TransientXFileSystem().merge(jsonFileSystem); } else {/*from w w w . j a v a 2 s. com*/ this.fileSystem = null; } JsonArray jsonListeners = jsonObject.getJsonArray("publish_addresses"); this.publishAddresses.clear(); if (jsonListeners != null) { for (Object o : jsonListeners) { String jsonListener = (String) o; this.publishAddresses.add(HostAndPort.fromString(jsonListener)); } } JsonArray jsonVolumes = jsonObject.getJsonArray("volumes"); this.volumes.clear(); if (jsonVolumes != null) { for (Object o : jsonVolumes) { JsonObject jsonVolume = (JsonObject) o; TransientXVolume transientXVolume = new TransientXVolume().merge(jsonVolume); this.volumes.add(transientXVolume); } } return (T) this; }
From source file:org.sfs.vo.XObject.java
License:Apache License
public T merge(JsonObject document) { this.versions.clear(); this.ownerGuid = document.getString("owner_guid"); this.nodeId = document.getString("node_id"); JsonArray jsonVerionArray = document.getJsonArray("versions"); if (jsonVerionArray != null) { for (Object o : jsonVerionArray) { JsonObject versionDocument = (JsonObject) o; Long id = versionDocument.getLong("id"); if (id == null) { checkNotNull(id, "id is null for %s", document.encodePrettily()); }//from ww w . ja va2s.c o m TransientVersion transientVersion = new TransientVersion(this, id).merge(versionDocument); versions.add(transientVersion); } } String createTimestamp = document.getString("create_ts"); String updateTimestamp = document.getString("update_ts"); if (createTimestamp != null) { setCreateTs(fromDateTimeString(createTimestamp)); } if (updateTimestamp != null) { setUpdateTs(fromDateTimeString(updateTimestamp)); } return (T) this; }
From source file:org.sub.bug.entity.BugConverter.java
License:Apache License
public static void fromJson(JsonObject json, Bug obj) { if (json.getValue("bugDateClosed") instanceof String) { obj.setBugDateClosed((String) json.getValue("bugDateClosed")); }//from w w w . j a va 2 s .co m if (json.getValue("bugDateReported") instanceof String) { obj.setBugDateReported((String) json.getValue("bugDateReported")); } if (json.getValue("bugDescription") instanceof String) { obj.setBugDescription((String) json.getValue("bugDescription")); } if (json.getValue("bugDeveloper") instanceof JsonObject) { obj.setBugDeveloper(new org.sub.bug.entity.BugDeveloper((JsonObject) json.getValue("bugDeveloper"))); } if (json.getValue("bugId") instanceof String) { obj.setBugId((String) json.getValue("bugId")); } if (json.getValue("bugReporter") instanceof String) { obj.setBugReporter((String) json.getValue("bugReporter")); } if (json.getValue("module") instanceof String) { obj.setModule((String) json.getValue("module")); } if (json.getValue("moduleName") instanceof String) { obj.setModuleName((String) json.getValue("moduleName")); } if (json.getValue("problemLogs") instanceof JsonArray) { java.util.ArrayList<org.sub.bug.entity.BugProblemLog> list = new java.util.ArrayList<>(); json.getJsonArray("problemLogs").forEach(item -> { if (item instanceof JsonObject) list.add(new org.sub.bug.entity.BugProblemLog((JsonObject) item)); }); obj.setProblemLogs(list); } }
From source file:se.liquidbytes.jel.owfs.OwfsAdapter.java
License:Apache License
/** * Scan for available devices on 1-wire bus. And updates our internal list of available devices. Note this is a blocking call! * *//* www . ja v a 2s . c o m*/ private void scanAvailableDevices() { try { String hwId, deviceType, deviceFamily, isPowered; Set<String> foundDeviceIds = new HashSet<>(); EventBus eb = vertx.eventBus(); JsonObject device, childDevice, broadcastDevice; Instant startExecutionTime = Instant.now(); logger.debug("Scanning for available devices on Owserver at {}:{} with adapter id \"{}\".", this.host, this.port, this.getId()); List<String> owDevices = owserverConnection.listDirectory(true); logger.debug("Found {} devices on Owserver at {}:{} with adapter id \"{}\".", owDevices.size(), this.host, this.port, this.getId()); for (String owDevice : owDevices) { hwId = owserverConnection.read(owDevice + "/id"); deviceType = owserverConnection.read(owDevice + "/type"); deviceFamily = owserverConnection.read(owDevice + "/family"); foundDeviceIds.add(hwId); device = deviceLookup.get(hwId); // Device not found in existing list, this must be a newly added device. Add it to the collection and broadcast its existence. if (device == null) { if (DeviceDatabase.getDeviceTypeInfo(deviceType) != null) { JsonObject typeInfo = DeviceDatabase.getDeviceTypeInfo(deviceType); // For devices that need to be setup in a special state to be usable, run their init commands when added to list of available devices. if (typeInfo.containsKey("initCommands")) { for (Iterator it = typeInfo.getJsonArray("initCommands").iterator(); it.hasNext();) { JsonObject command = (JsonObject) it.next(); String path = owDevice + command.getString("path"); logger.debug( "Running initcommand (path '{}', value '{}') for device '{}' on Owserver at {}:{} with adapter id \"{}\".", path, command.getString("value"), hwId, this.host, this.port, this.getId()); owserverConnection.write(path, command.getString("value")); } } try { isPowered = owserverConnection.read(owDevice + "/power"); if (isPowered != null && isPowered.equals("0")) { logger.warn( "Device '{}' of type '{}' on Owserver at {}:{} with adapter id \"{}\" is running on parasitic power, this will slow down the 1-wire network and is less reliable than a powered device.", hwId, deviceType, this.host, this.port, this.getId()); } } catch (OwServerConnectionException ex) { // Ignore. Devices that don't support the power-property will throw an error, so we just ignore this. } device = new JsonObject(); device.put("hwId", hwId); device.put("type", deviceType); device.put("name", typeInfo.getString("name")); device.put("family", deviceFamily); device.put("path", owDevice); device.put("typeInfo", typeInfo); deviceLookup.put(hwId, device); logger.info( "New device found during scan of Owserver at {}:{} with adapter id \"{}\". Device hwId: {}, type: {}, family: {}.", this.host, this.port, this.getId(), hwId, deviceType, deviceFamily); // For devices that supports it. //setupAlarmHandler(device); broadcastDevice = new JsonObject().put("adapterId", this.getId()).put("port", this.port) .put("host", this.host).put("hwId", hwId).put("type", deviceType) .put("name", typeInfo.getString("name")); eb.publish(AdapterEvents.EVENTBUS_ADAPTERS, broadcastDevice, new DeliveryOptions().addHeader("action", AdapterEvents.EVENT_DEVICES_ADDED)); // Check if this device is an container for other "child-devices". In that case, add all the children too, their Id will be <parent_childnumber>. if (typeInfo.containsKey("childDevices")) { for (Iterator it = typeInfo.getJsonArray("childDevices").iterator(); it.hasNext();) { JsonObject childType = (JsonObject) it.next(); String childId = String.format("%s%s%s", hwId, CHILDSEPARATOR, childType.getString("idSuffix")); childDevice = new JsonObject(); childDevice.put("hwId", childId); childDevice.put("type", deviceType); childDevice.put("name", String.format("%s-%s", typeInfo.getString("name"), childType.getString("name"))); deviceLookup.put(childId, childDevice); logger.info( "New childdevice for device {} found during scan of Owserver at {}:{} with adapter id \"{}\". Device hwId: {}, type: {}, family: {}.", hwId, this.host, this.port, this.getId(), childId, deviceType, deviceFamily); broadcastDevice = new JsonObject().put("adapterId", this.getId()) .put("port", this.port).put("host", this.host).put("hwId", childId) .put("type", deviceType).put("name", childDevice.getString("name")); eb.publish(AdapterEvents.EVENTBUS_ADAPTERS, broadcastDevice, new DeliveryOptions() .addHeader("action", AdapterEvents.EVENT_DEVICES_ADDED)); } } } else { logger.info( "Found unsupported devicetype for device with hwId '{}' on Owserver at {}:{} with adapter id \"{}\". Device will be ignored! Please notify developers and provide: type={}, family={}.", hwId, this.host, this.port, this.getId(), deviceType, deviceFamily); } } } // Remove all devices in device list that was no longer found during this scan. They has been disconnected from the 1-wire bus. Set<String> tempSet = new HashSet(deviceLookup.keySet()); tempSet.removeAll(foundDeviceIds); for (String removeId : tempSet) { // Check that it's not a childdevice, we are not interested in them right now. if (!removeId.contains(CHILDSEPARATOR)) { // If device has children, remove these first. List<String> childDevicesId = tempSet.stream() .filter(d -> d.startsWith(removeId + CHILDSEPARATOR)).collect(Collectors.toList()); for (String childDeviceId : childDevicesId) { removeDeviceFromLookup(childDeviceId, eb); } // Then remove device. removeDeviceFromLookup(removeId, eb); } } logger.debug("Scanning bus for devices took {}ms on Owserver at {}:{} with adapter id \"{}\".", Duration.between(startExecutionTime, Instant.now()).toMillis(), this.host, this.port, this.getId()); } catch (OwServerConnectionException ex) { logger.error( "Error while trying to scan Owserver at {}:{} with adapter id \"{}\" for available devices.", this.host, this.port, this.getId(), ex); } }
From source file:se.liquidbytes.jel.owfs.OwfsAdapter.java
License:Apache License
/** * Set value on device with specified hwId. * * @param hwId Id on device/*w w w . j av a2 s. c o m*/ * @param value value to set on device. * @throws DeviceMissingException throws exception if specified device does not exist. * @throws OwServerConnectionException throws exception if command fails for any reason. */ private void setDeviceValue(String hwId, String value) throws DeviceMissingException, OwServerConnectionException { if (hwId == null || !deviceLookup.containsKey(hwId)) { throw new DeviceMissingException("Trying to perform a action on a non existing device.", hwId); } if (hwId.contains(CHILDSEPARATOR)) { String parentId = hwId.split(CHILDSEPARATOR)[0]; String childSuffix = hwId.split(CHILDSEPARATOR)[1]; JsonObject parentDevice = deviceLookup.get(parentId); JsonObject typeInfo = parentDevice.getJsonObject("typeInfo"); if (typeInfo == null) { throw new OwServerConnectionException(String.format("typeInfo missing for device with type '%s'", parentDevice.getString("type"))); } JsonArray childDevices = typeInfo.getJsonArray("childDevices"); if (childDevices != null && childDevices.size() > 0) { String writePath = childDevices.stream().filter(t -> t instanceof JsonObject) .map(t -> (JsonObject) t).filter((d) -> d.getString("idSuffix").equals(childSuffix)) .map((cd) -> cd.getString("valueWritePath")).findFirst().get(); writePath = parentDevice.getString("path") + writePath; // Queue command. Record time so we could measure how long command has been queued before executed, if we want to. this.commandQueue.offer(new JsonObject().put("path", writePath).put("value", value).put("nanoTime", System.nanoTime())); } } else { JsonObject device = deviceLookup.get(hwId); JsonObject typeInfo = device.getJsonObject("typeInfo"); if (typeInfo == null) { throw new OwServerConnectionException( String.format("typeInfo missing for device with type '%s'", device.getString("type"))); } // Check if this type of device is writable. if (typeInfo.containsKey("valueWritePath")) { String writePath = device.getString("path") + typeInfo.getString("valueWritePath"); // Queue command. Record time so we could measure how long command has been queued before executed, if we want to. this.commandQueue.offer(new JsonObject().put("path", writePath).put("value", value).put("nanoTime", System.nanoTime())); } } }
From source file:se.liquidbytes.jel.system.device.DeviceManager.java
License:Apache License
public void listAdapterDevices(String adapterId, Handler<AsyncResult<JsonArray>> resultHandler) { DeliveryOptions options = new DeliveryOptions(); options.addHeader("action", "listDevices"); DeployedAdapter adapter = JelService.adapterManager().getAdapter(adapterId); if (adapter == null) { resultHandler/*from w w w . j a v a 2 s. com*/ .handle(Future.failedFuture(String.format("Adapter with id %s does not exist.", adapterId))); } else { // Send message to adapter to report back its devices. JelService.vertx().eventBus().send(String.format("%s.%s@%s:%d", AdapterEvents.EVENTBUS_ADAPTERS, adapter.config().getType(), adapter.config().getAddress(), adapter.config().getPort()), null, options, res -> { if (res.succeeded()) { JsonArray devices = new JsonArray(); JsonObject result = (JsonObject) res.result().body(); result.getJsonArray("result").forEach((d) -> { JsonObject tmpDevice = (JsonObject) d; // Sync found devices with allDevices-collection in case we are out of sync and have missed an event! addToDeviceCollections(new JsonObject().put("adapterId", adapterId) .put("name", tmpDevice.getString("name")) .put("type", tmpDevice.getString("type")) .put("hwId", tmpDevice.getString("hwId"))); devices.add(new JsonObject() .put("deviceId", generateDeviceId(adapterId, tmpDevice.getString("hwId"))) .put("type", tmpDevice.getString("type")) .put("name", tmpDevice.getString("name"))); }); resultHandler.handle(Future.succeededFuture(devices)); } else { resultHandler.handle(Future.failedFuture(res.cause())); } }); } }
From source file:se.liquidbytes.jel.system.device.DeviceManager.java
License:Apache License
/** * Returns a list of all supported devices for a specific adapter. * * @param adapterId id for adapter to query. * @param resultHandler Promise will give the list of supported devices. */// ww w . j a va 2 s. com public void listSupportedAdapterDevices(String adapterId, Handler<AsyncResult<JsonArray>> resultHandler) { DeliveryOptions options = new DeliveryOptions(); options.addHeader("action", "listSupportedDevices"); DeployedAdapter adapter = JelService.adapterManager().getAdapter(adapterId); if (adapter == null) { resultHandler .handle(Future.failedFuture(String.format("Adapter with id %s does not exist.", adapterId))); } else { JelService.vertx().eventBus().send(String.format("%s.%s@%s:%d", AdapterEvents.EVENTBUS_ADAPTERS, adapter.config().getType(), adapter.config().getAddress(), adapter.config().getPort()), null, options, res -> { if (res.succeeded()) { JsonObject result = (JsonObject) res.result().body(); resultHandler.handle(Future.succeededFuture(result.getJsonArray("result"))); } else { resultHandler.handle(Future.failedFuture(res.cause())); } }); } }