List of usage examples for io.vertx.core.json JsonArray JsonArray
public JsonArray()
From source file:net.kuujo.vertigo.network.impl.ComponentConfigImpl.java
License:Apache License
@Override @SuppressWarnings("unchecked") public void update(JsonObject component) { if (this.name == null) { this.name = component.getString(COMPONENT_NAME, UUID.randomUUID().toString()); }/*from w ww.ja v a 2 s . c o m*/ if (this.identifier == null) { this.identifier = component.getString(COMPONENT_IDENTIFIER); if (this.identifier == null) { throw new NetworkFormatException("Component " + this.name + " did not specify an identifier."); } } if (component.containsKey(COMPONENT_CONFIG)) { this.config = component.getJsonObject(COMPONENT_CONFIG); } if (component.containsKey(COMPONENT_WORKER)) { this.worker = component.getBoolean(COMPONENT_WORKER); } if (component.containsKey(COMPONENT_MULTI_THREADED)) { this.multiThreaded = component.getBoolean(COMPONENT_MULTI_THREADED); } if (component.containsKey(COMPONENT_STATEFUL)) { this.stateful = component.getBoolean(COMPONENT_STATEFUL); } if (component.containsKey(COMPONENT_REPLICAS)) { this.replicas = component.getInteger(COMPONENT_REPLICAS, 1); } if (component.containsKey(COMPONENT_RESOURCES)) { this.resources.addAll(component.getJsonArray(COMPONENT_RESOURCES, new JsonArray()).getList()); } JsonObject inputs = component.getJsonObject(COMPONENT_INPUT); if (inputs == null) { inputs = new JsonObject(); } if (this.input == null) { this.input = new InputConfigImpl(inputs).setComponent(this); } else { this.input.update(inputs); } JsonObject outputs = component.getJsonObject(COMPONENT_OUTPUT); if (outputs == null) { outputs = new JsonObject(); } if (this.output == null) { this.output = new OutputConfigImpl(outputs).setComponent(this); } else { this.output.update(outputs); } }
From source file:net.kuujo.vertigo.network.impl.NetworkImpl.java
License:Apache License
@Override public JsonObject toJson() { JsonObject json = new JsonObject(); json.put(NETWORK_NAME, name);/*from w w w . j a v a2 s .co m*/ JsonObject components = new JsonObject(); for (ComponentConfig component : this.components) { components.put(component.getName(), component.toJson()); } json.put(NETWORK_COMPONENTS, components); JsonArray connections = new JsonArray(); for (ConnectionConfig connection : this.connections) { connections.add(connection.toJson()); } json.put(NETWORK_CONNECTIONS, connections); return json; }
From source file:net.sf.sgsimulator.sgsrest.vertx.controllers.QueryController.java
License:Open Source License
@GET("/transformer-names") public String getTransformerNames() { return jsonResponse(() -> { JsonArray res = new JsonArray(); gL.getTransformerNames().forEach(res::add); return res; });//from ww w.java 2 s . c o m }
From source file:org.azrul.langmera.DecisionService.java
private void getHistory(RoutingContext routingContext) { final HistoryRequest req = Json.decodeValue(routingContext.getBodyAsString(), HistoryRequest.class); List<HistoryResponseElement> histResponses = new ArrayList<>(); String driver = config.getProperty("jdbc.driver", String.class); String url = config.getProperty("jdbc.url", String.class); String username = config.getProperty("jdbc.username", String.class); String password = config.getProperty("jdbc.password", String.class); JDBCClient client = JDBCClient.createShared(vertx, new JsonObject().put("url", url) .put("driver_class", driver).put("user", username).put("password", password)); JsonArray param = new JsonArray(); param.add(req.getContext()).add(req.getFrom()).add(req.getTo()); // for (int i = 0; i < InMemoryDB.store.get(0).size(); i++) { // HistoryResponseElement resp = new HistoryResponseElement(); // String context = (String) InMemoryDB.store.get(0).get(i); // if (context.equals(req.getContext())) { // Date time = (Date) InMemoryDB.store.get(3).get(i); // if (time.after(req.getFrom()) && time.before(req.getTo())) { // resp.setContext(context); // resp.setDecision((String) InMemoryDB.store.get(1).get(i)); // resp.setInterest((Double) InMemoryDB.store.get(2).get(i)); // resp.setTime(time); // histResponses.add(resp); // } // } // }/* ww w. j av a 2s .co m*/ client.getConnection(ar -> { SQLConnection connection = ar.result(); connection.queryWithParams( "SELECT * FROM Trace ORDER BY decisiontime desc where context=? and decisiontime between ? and ?", param, r -> { if (r.succeeded()) { for (JsonArray row : r.result().getResults()) { HistoryResponseElement respElement = new HistoryResponseElement(); respElement.setContext(row.getString(1)); respElement.setDecision(row.getString(6)); respElement.setInterest(row.getDouble(8)); respElement.setTime(new Date(row.getLong(5))); histResponses.add(respElement); } HistoryResponse resp = new HistoryResponse(); resp.setElements(histResponses); routingContext.response().setStatusCode(201) .putHeader("content-type", "application/json; charset=utf-8") .exceptionHandler(ex -> { logger.log(Level.SEVERE, "Problem encountered when making decision", ex); }).end(Json.encodePrettily(resp)); } connection.close(); }); }); }
From source file:org.dfr.dfr.worker.MemberWorker.java
@Override public void start(Future<Void> fut) { JsonObject config = new JsonObject(); config.put("url", "jdbc:mysql://localhost:3306/latihan"); config.put("driver_class", "com.mysql.jdbc.Driver"); config.put("user", "root"); config.put("password", "admin"); JDBCClient client = JDBCClient.createShared(vertx, config, "memberds"); final Validator v = Validation.buildDefaultValidatorFactory().getValidator(); SimpleDateFormat mysqlFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); vertx.eventBus().consumer("MemberWorker#Register").handler(h -> { MemberRegisterRequest req = null; try {//w ww.jav a 2 s. c om req = Json.decodeValue(h.body().toString(), MemberRegisterRequest.class); } catch (Exception e) { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON))); return; } Set<ConstraintViolation<MemberRegisterRequest>> vr = v.validate(req); if (!vr.isEmpty()) { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON) .setMessage(vr.iterator().next().getMessage()))); return; } final MemberRegisterRequest r = req; final HashMap<String, Object> smap = new HashMap(); client.getConnection(ch -> { if (ch.succeeded()) { SQLConnection c = ch.result(); Future<Void> f1 = Future.future(); c.setAutoCommit(false, f1.completer()); f1.compose(o -> { Future<ResultSet> f2 = Future.future(); c.queryWithParams("select username from member where username=?", new JsonArray().add(r.getUsername()), f2.completer()); return f2; }).compose(res -> { Future<ResultSet> f2 = Future.future(); if (res.getNumRows() != 0) { f2.fail(ErrorCode.USER_EXIST); } else { c.queryWithParams("select email from member where email=?", new JsonArray().add(r.getEmail()), f2.completer()); } return f2; }).compose(res -> { if (res.getNumRows() > 0) { return Future.failedFuture(ErrorCode.EMAIL_EXIST); } else { try { r.setPassword(hash(r.getPassword())); } catch (Exception e) { return Future.failedFuture(ErrorCode.SERVER_ERROR); } Future<UpdateResult> f2 = Future.future(); c.updateWithParams("insert into member(username,password,email) values (?,?,?)", new JsonArray().add(r.getUsername()).add(r.getPassword()).add(r.getEmail()), f2.completer()); return f2; } }).compose(res -> { Future<UpdateResult> f2 = Future.future(); c.updateWithParams("insert into profile(member_id) values(?)", new JsonArray().add(res.getKeys().getLong(0)), f2.completer()); return f2; }).compose(res -> { Future<Void> cfut = Future.future(); c.commit(cfut.completer()); return cfut; }).setHandler(ch1 -> { if (ch1.succeeded()) { c.close(close -> { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE))); }); } else { c.rollback(rr -> { c.close(close -> { h.reply(Json.encode(new GeneralResponse().setCode(ch1.cause().getMessage()) .setMessage(ErrorCode.getMessage(ch1.cause().getMessage())))); }); }); } }); } else { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR) .setMessage(ErrorCode.getMessage(ErrorCode.SERVER_ERROR)))); } }); }); vertx.eventBus().consumer("MemberWorker#ProfileUpdate").handler(h -> { ProfileUpdateRequest req = null; try { req = Json.decodeValue(h.body().toString(), ProfileUpdateRequest.class); } catch (Exception e) { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON))); return; } Set<ConstraintViolation<ProfileUpdateRequest>> vr = v.validate(req); if (!vr.isEmpty()) { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON) .setMessage(vr.iterator().next().getMessage()))); return; } ProfileUpdateRequest rq = req; client.getConnection(connection -> { if (connection.succeeded()) { HashMap<String, Object> sm = new HashMap<String, Object>(); SQLConnection con = connection.result(); Future<Void> ac = Future.future(); con.setAutoCommit(false, ac.completer()); ac.compose(rv -> { Future<ResultSet> lock = Future.future(); con.queryWithParams( "select p.* from profile p inner join member m on p.member_id=m.member_id where m.username=? and m.password=? for update", new JsonArray().add(rq.getUsername()).add(rq.getPassword()), lock.completer()); return lock; }).compose(r -> { if (r.getNumRows() == 0) { return Future.failedFuture(ErrorCode.USERNAME_PASSWORD_NOT_MATCH); } long member_id = r.getRows().iterator().next().getLong("member_id"); Future<UpdateResult> up = Future.future(); con.updateWithParams( "update profile set name=?, phone=?, address=?, company_name=?, company_address=? where member_id=?", new JsonArray().add(rq.getName()).add(rq.getPhone()).add(rq.getAddress()) .add(rq.getCompanyName()).add(rq.getCompanyAddress()).add(member_id), up.completer()); return up; }).compose(ok -> { Future<Void> commitFu = Future.future(); con.commit(commitFu.completer()); return commitFu; }).setHandler(th -> { if (th.succeeded()) { con.close(cr -> { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE))); }); } else { con.rollback(rh -> { con.close(cl -> { h.reply(Json.encode(new GeneralResponse().setCode(th.cause().getMessage()) .setMessage(ErrorCode.getMessage(th.cause().getMessage())))); }); }); } }); } else { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR) .setMessage(ErrorCode.getMessage(ErrorCode.SERVER_ERROR)))); } }); }); vertx.eventBus().consumer("MemberWorker#GetProfile").handler(h -> { ProfileRequest req = null; try { req = Json.decodeValue(h.body().toString(), ProfileRequest.class); } catch (Exception e) { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON))); return; } Set<ConstraintViolation<ProfileRequest>> rV = v.validate(req); if (!rV.isEmpty()) { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON))); return; } final ProfileRequest r = req; client.getConnection(cH -> { if (cH.succeeded()) { SQLConnection c = cH.result(); Future<Void> f = Future.future(); c.setAutoCommit(true, f.completer()); f.compose(res -> { Future<ResultSet> f0 = Future.future(); c.queryWithParams("select member_id from member m where m.username=? and m.password=?", new JsonArray().add(r.getUsername()).add(r.getPassword()), f0.completer()); return f0; }).compose(res -> { Future<ResultSet> f0 = Future.future(); if (res.getNumRows() <= 0) { f0.fail(ErrorCode.USERNAME_PASSWORD_NOT_MATCH); } else { c.queryWithParams("select * from profile where member_id=?", new JsonArray().add(res.getRows().iterator().next().getLong("member_id")), f0.completer()); } return f0; }).setHandler(rh -> { c.close(); if (rh.succeeded()) { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE) .setData(rh.result().getRows().get(0)))); } else { h.reply(Json.encode(new GeneralResponse().setCode(rh.cause().getMessage()) .setMessage(ErrorCode.getMessage(rh.cause().getMessage())))); } }); } else { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR) .setMessage(ErrorCode.getMessage(ErrorCode.SERVER_ERROR)))); } }); }); vertx.eventBus().consumer("MemberWorker#ChangePassword").handler(h -> { ChangePasswordRequest req = null; try { req = Json.decodeValue(h.body().toString(), ChangePasswordRequest.class); } catch (Exception e) { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON))); return; } Set<ConstraintViolation<ChangePasswordRequest>> rV = v.validate(req); if (!rV.isEmpty()) { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON))); return; } final ChangePasswordRequest r = req; client.getConnection(connection -> { if (connection.succeeded()) { SQLConnection c = connection.result(); Future<Void> f1 = Future.future(); c.setAutoCommit(false, f1.completer()); f1.compose(vo -> { Future<ResultSet> f = Future.future(); c.queryWithParams("select member_id from member where username=? and password=? for update", new JsonArray().add(r.getUsername()).add(r.getPassword()), f.completer()); return f; }).compose(res -> { Future<UpdateResult> f0 = Future.future(); if (res.getNumRows() <= 0) { f0.fail(ErrorCode.USERNAME_PASSWORD_NOT_MATCH); } else { long member_id = res.getRows().iterator().next().getLong("member_id"); String hash = null; try { hash = hash(r.getNewPassword()); } catch (Exception e) { return Future.failedFuture(ErrorCode.SERVER_ERROR); } c.updateWithParams("update member set password=? where member_id=?", new JsonArray().add(hash).add(member_id), f0.completer()); } return f0; }).compose(res -> { Future<Void> cf = Future.future(); c.commit(cf.completer()); return cf; }).setHandler(ch -> { if (ch.succeeded()) { c.close(); h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE))); } else { ch.cause().printStackTrace(); c.rollback(rh -> { c.close(); h.reply(Json.encode(new GeneralResponse().setCode(ch.cause().getMessage()) .setMessage(ErrorCode.getMessage(ch.cause().getMessage())))); }); } }); } else { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR) .setMessage(ErrorCode.getMessage(ErrorCode.SERVER_ERROR)))); } }); }); vertx.eventBus().consumer("MembrWorker#AddAsset").handler(h -> { AddAssetRequest req = null; try { req = Json.decodeValue(h.body().toString(), AddAssetRequest.class); } catch (Exception e) { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON))); return; } Set<ConstraintViolation<AddAssetRequest>> res = v.validate(req); if (!res.isEmpty()) { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON) .setMessage(res.iterator().next().getMessage()))); return; } AddAssetRequest r = req; client.getConnection(connection -> { if (connection.succeeded()) { SQLConnection con = connection.result(); Future<Void> f = Future.future(); con.setAutoCommit(false, f.completer()); f.compose(vo -> { Future<ResultSet> f1 = Future.future(); con.queryWithParams("select * from member where username=? and password=?", new JsonArray().add(r.getUsername()).add(r.getPassword()), f1.completer()); return f1; }).compose(re -> { Future<UpdateResult> f1 = Future.future(); if (re.getNumRows() <= 0) { System.out.println(Json.encode(re)); System.out.println(Json.encode(r)); f1.fail(ErrorCode.USERNAME_PASSWORD_NOT_MATCH); } else { long member_id = re.getRows().iterator().next().getLong("member_id"); con.updateWithParams( "insert into assets (member_id,debit_credit,asset_name,asset_value,date_time,description) values(?,?,?,?,?,?)", new JsonArray().add(member_id).add(r.getDebitCredit()).add(r.getAssetName()) .add(r.getAssetValue()).add(mysqlFormat.format(new Date())) .add(r.getDescription()), f1.completer()); } return f1; }).compose(re -> { Future<Void> end = Future.future(); con.commit(end.completer()); return end; }).setHandler(ch -> { if (ch.succeeded()) { con.close(); h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE))); } else { con.rollback(rh -> { con.close(); h.reply(Json.encode(new GeneralResponse().setCode(ch.cause().getMessage()) .setMessage(ErrorCode.getMessage(ch.cause().getMessage())))); }); } }); } else { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR) .setMessage(ErrorCode.getMessage(ErrorCode.SERVER_ERROR)))); } }); }); vertx.eventBus().consumer("AssetWorker#GetAsset").handler(h -> { GetAssetRequest req = null; try { req = Json.decodeValue(h.body().toString(), GetAssetRequest.class); } catch (Exception e) { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON))); return; } Set<ConstraintViolation<GetAssetRequest>> res = v.validate(req); if (!res.isEmpty()) { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON) .setMessage(res.iterator().next().getMessage()))); return; } GetAssetRequest r = req; client.getConnection(connection -> { if (connection.succeeded()) { SQLConnection c = connection.result(); Future<Void> vo = Future.future(); c.setAutoCommit(true, vo.completer()); vo.compose(re -> { Future<ResultSet> f0 = Future.future(); c.queryWithParams("select member_id from member where username=? and password=?", new JsonArray().add(r.getUsername()).add(r.getPassword()), f0.completer()); return f0; }).compose(re -> { Future<ResultSet> f0 = Future.future(); if (re.getNumRows() <= 0) { f0.fail(ErrorCode.USERNAME_PASSWORD_NOT_MATCH); } else { long member_id = re.getRows().iterator().next().getLong("member_id"); c.queryWithParams("select * from assets where member_id=?", new JsonArray().add(member_id), f0.completer()); } return f0; }).setHandler(resp -> { if (resp.succeeded()) { h.reply(Json.encodePrettily(new GeneralResponse().setCode(ErrorCode.COMPLETE) .setData(resp.result().getRows()))); } else { h.reply(Json.encode(new GeneralResponse().setCode(resp.cause().getMessage()) .setMessage(ErrorCode.getMessage(resp.cause().getMessage())))); } c.close(); }); } else { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR) .setMessage(connection.cause().getMessage()))); } }); }); vertx.eventBus().consumer("AssetWorker#UpdateAsset").handler(h -> { UpdateAssetRequest req = null; try { req = Json.decodeValue(h.body().toString(), UpdateAssetRequest.class); } catch (Exception e) { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON))); return; } Set<ConstraintViolation<UpdateAssetRequest>> res = v.validate(req); if (!res.isEmpty()) { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.INVALID_JSON) .setMessage(res.iterator().next().getMessage()))); return; } final UpdateAssetRequest r = req; client.getConnection(connection -> { if (connection.succeeded()) { SQLConnection con = connection.result(); Future<Void> f = Future.future(); con.setAutoCommit(false, f.completer()); f.compose(vo -> { Future<ResultSet> f0 = Future.future(); con.queryWithParams("select member_id from member where username=? and password=?", new JsonArray().add(r.getUsername()).add(r.getPassword()), f0.completer()); return f0; }).compose(rs -> { Future<ResultSet> f0 = Future.future(); if (rs.getNumRows() <= 0) { f0.fail(ErrorCode.USERNAME_PASSWORD_NOT_MATCH); } else { long member_id = rs.getRows().iterator().next().getLong("member_id"); con.queryWithParams("select * from assets where asset_id=? and member_id=? for update", new JsonArray().add(r.getAssetId()).add(member_id), f0.completer()); } return f0; }).compose(rs -> { Future<UpdateResult> f0 = Future.future(); con.updateWithParams( "update assets set debit_credit=?,asset_name=?,asset_value=?,date_time=?,description=? where asset_id=?", new JsonArray().add(r.getDebitCredit()).add(r.getAssetName()).add(r.getAssetValue()) .add(mysqlFormat.format(new Date())).add(r.getDescription()) .add(r.getAssetId()), f0.completer()); return f0; }).compose(rs -> { Future<Void> cf = Future.future(); con.commit(cf.completer()); return cf; }).setHandler(sh -> { if (sh.succeeded()) { con.close(); h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.COMPLETE))); } else { con.rollback(rh -> { con.close(); h.reply(Json.encode(new GeneralResponse().setCode(sh.cause().getMessage()) .setMessage(ErrorCode.getMessage(sh.cause().getMessage())))); }); } }); } else { h.reply(Json.encode(new GeneralResponse().setCode(ErrorCode.SERVER_ERROR))); } }); }); fut.complete(); }
From source file:org.eclipse.hono.client.impl.HonoClientImpl.java
License:Open Source License
@Override public JsonArray getSenderStatus() { JsonArray result = new JsonArray(); for (Entry<String, MessageSender> senderEntry : activeSenders.entrySet()) { final MessageSender sender = senderEntry.getValue(); JsonObject senderStatus = new JsonObject().put("address", senderEntry.getKey()) .put("open", sender.isOpen()).put("credit", sender.getCredit()); result.add(senderStatus);/*from w ww .ja va2 s. c om*/ } return result; }
From source file:org.eclipse.hono.deviceregistry.FileBasedCredentialsService.java
License:Open Source License
private void parseCredentials(final JsonArray credentialsObject) { final AtomicInteger credentialsCount = new AtomicInteger(); log.debug("trying to load credentials for {} tenants", credentialsObject.size()); for (Object obj : credentialsObject) { JsonObject tenant = (JsonObject) obj; String tenantId = tenant.getString(FIELD_TENANT); Map<String, JsonArray> credentialsMap = new HashMap<>(); for (Object credentialsObj : tenant.getJsonArray(ARRAY_CREDENTIALS)) { JsonObject credentials = (JsonObject) credentialsObj; JsonArray authIdCredentials; if (credentialsMap.containsKey(credentials.getString(FIELD_AUTH_ID))) { authIdCredentials = credentialsMap.get(credentials.getString(FIELD_AUTH_ID)); } else { authIdCredentials = new JsonArray(); }//ww w .j av a 2s .c om authIdCredentials.add(credentials); credentialsMap.put(credentials.getString(FIELD_AUTH_ID), authIdCredentials); credentialsCount.incrementAndGet(); } credentials.put(tenantId, credentialsMap); } log.info("successfully loaded {} credentials from file [{}]", credentialsCount.get(), getConfig().getCredentialsFilename()); }
From source file:org.eclipse.hono.deviceregistry.FileBasedCredentialsService.java
License:Open Source License
private void saveToFile(final Future<Void> writeResult) { if (!dirty) { log.trace("credentials registry does not need to be persisted"); return;//from w w w .ja v a 2 s . c o m } final FileSystem fs = vertx.fileSystem(); String filename = getConfig().getCredentialsFilename(); if (!fs.existsBlocking(filename)) { fs.createFileBlocking(filename); } final AtomicInteger idCount = new AtomicInteger(); JsonArray tenants = new JsonArray(); for (Entry<String, Map<String, JsonArray>> entry : credentials.entrySet()) { JsonArray credentialsArray = new JsonArray(); for (Entry<String, JsonArray> credentialEntry : entry.getValue().entrySet()) { // authId -> full json attributes object JsonArray singleAuthIdCredentials = credentialEntry.getValue(); // from one authId credentialsArray.addAll(singleAuthIdCredentials); idCount.incrementAndGet(); } tenants.add( new JsonObject().put(FIELD_TENANT, entry.getKey()).put(ARRAY_CREDENTIALS, credentialsArray)); } fs.writeFile(getConfig().getCredentialsFilename(), Buffer.factory.buffer(tenants.encodePrettily()), writeAttempt -> { if (writeAttempt.succeeded()) { dirty = false; log.trace("successfully wrote {} credentials to file {}", idCount.get(), filename); writeResult.complete(); } else { log.warn("could not write credentials to file {}", filename, writeAttempt.cause()); writeResult.fail(writeAttempt.cause()); } }); }
From source file:org.eclipse.hono.deviceregistry.FileBasedRegistrationService.java
License:Open Source License
private void saveToFile(final Future<Void> writeResult) { if (!dirty) { log.trace("registry does not need to be persisted"); return;/* w ww . j a v a 2 s. c o m*/ } final FileSystem fs = vertx.fileSystem(); if (!fs.existsBlocking(getConfig().getFilename())) { fs.createFileBlocking(getConfig().getFilename()); } final AtomicInteger idCount = new AtomicInteger(); JsonArray tenants = new JsonArray(); for (Entry<String, Map<String, JsonObject>> entry : identities.entrySet()) { JsonArray devices = new JsonArray(); for (Entry<String, JsonObject> deviceEntry : entry.getValue().entrySet()) { devices.add(new JsonObject().put(FIELD_DEVICE_ID, deviceEntry.getKey()).put(FIELD_DATA, deviceEntry.getValue())); idCount.incrementAndGet(); } tenants.add(new JsonObject().put(FIELD_TENANT, entry.getKey()).put(ARRAY_DEVICES, devices)); } fs.writeFile(getConfig().getFilename(), Buffer.factory.buffer(tenants.encodePrettily()), writeAttempt -> { if (writeAttempt.succeeded()) { dirty = false; log.trace("successfully wrote {} device identities to file {}", idCount.get(), getConfig().getFilename()); writeResult.complete(); } else { log.warn("could not write device identities to file {}", getConfig().getFilename(), writeAttempt.cause()); writeResult.fail(writeAttempt.cause()); } }); }
From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java
License:Open Source License
Future<Void> saveToFile() { if (!getConfig().isSaveToFile()) { return Future.succeededFuture(); } else if (dirty) { return checkFileExists(true).compose(s -> { final JsonArray tenantsJson = new JsonArray(); tenants.values().stream().forEach(tenant -> { tenantsJson.add(JsonObject.mapFrom(tenant)); });//from www . j a v a 2 s. c o m final Future<Void> writeHandler = Future.future(); vertx.fileSystem().writeFile(getConfig().getFilename(), Buffer.factory.buffer(tenantsJson.encodePrettily()), writeHandler.completer()); return writeHandler.map(ok -> { dirty = false; log.trace("successfully wrote {} tenants to file {}", tenantsJson.size(), getConfig().getFilename()); return (Void) null; }).otherwise(t -> { log.warn("could not write tenants to file {}", getConfig().getFilename(), t); return (Void) null; }); }); } else { log.trace("tenants registry does not need to be persisted"); return Future.succeededFuture(); } }