List of usage examples for io.vertx.core.shareddata LocalMap get
V get(Object key);
From source file:SampleVerticle2.java
License:Apache License
public void start() { LocalMap<String, String> map = vertx.sharedData().getLocalMap("demo.mymap"); Container<Sample> theContainer = new Container<>("Demo", Container.TYPE.PERSISTENT, Container.MODEL.SHARED); String uidName = map.get(ClientVerticle.LEADER); Sample obj1 = theContainer.clone(new SampleLockable(10), new Uid(uidName)); AtomicAction A = new AtomicAction(); int value = -1; int initialValue = -1; boolean shouldCommit = true; A.begin();/* w w w. j av a 2 s. co m*/ try { initialValue = obj1.value(); obj1.increment(); } catch (final Throwable ex) { ex.printStackTrace(); shouldCommit = false; } try { if (shouldCommit) { obj1.increment(); value = obj1.value(); } } catch (final Throwable ex) { ex.printStackTrace(); shouldCommit = false; } if (shouldCommit) A.commit(); else { A.abort(); value = -1; } System.err.println("SampleVerticle2 initialised state with: " + value); if (value == initialValue + 2) System.err.println("SampleVerticle2 SUCCEEDED!"); else System.err.println("SampleVerticle2 FAILED!"); }
From source file:examples.SharedDataExamples.java
License:Open Source License
public void example1(Vertx vertx) { SharedData sd = vertx.sharedData();//from ww w.j a v a2s. co m LocalMap<String, String> map1 = sd.getLocalMap("mymap1"); map1.put("foo", "bar"); // Strings are immutable so no need to copy LocalMap<String, Buffer> map2 = sd.getLocalMap("mymap2"); map2.put("eek", Buffer.buffer().appendInt(123)); // This buffer will be copied before adding to map // Then... in another part of your application: map1 = sd.getLocalMap("mymap1"); String val = map1.get("foo"); map2 = sd.getLocalMap("mymap2"); Buffer buff = map2.get("eek"); }
From source file:io.flowly.engine.verticles.Build.java
License:Open Source License
private Handler<Message<Object>> deployAppHandler() { return message -> { App app = App.toApp((JsonObject) message.body()); LocalMap<String, Boolean> deployedAppsMap = vertx.sharedData().getLocalMap(DEPLOYED_APPS_KEY); Boolean appExists = deployedAppsMap.get(app.getId()); if (appExists != null && appExists) { Failure failure = new Failure(4001, "App is already deployed: " + app.getId()); logger.error(failure.getError()); message.fail(failure.getCode(), failure.getMessage()); } else {//ww w. ja v a2 s .c om // Add the app to the local map. deployedAppsMap.put(app.getId(), true); String appFolder = app.getAppFolder(); String verticlesPath = PathUtils.createPath(appFolder, PathUtils.VERTICLES_FOLDER); vertx.executeBlocking(future -> { try { prepareVerticlesFolderBlocking(app, verticlesPath); // Parse flows. List<Flow> flows = parseFlowsBlocking(appFolder); // Build flows. buildFlowsBlocking(app, flows, future, deployedAppsMap); } catch (Exception ex) { Failure failure = new Failure(4002, "Unable to compile flow verticles for app: " + app.getId(), ex); logger.error(failure.getError(), failure.getCause()); future.fail(failure); } }, r -> { if (r.succeeded()) { message.reply(true); } else { message.fail(4002, r.cause().getMessage()); } }); } }; }
From source file:io.flowly.engine.verticles.Build.java
License:Open Source License
private Handler<Message<Object>> undeployHandler() { return message -> { App app = App.toApp((JsonObject) message.body()); LocalMap<String, Set<String>> deployedAppsMap = vertx.sharedData().getLocalMap(DEPLOYED_APPS_KEY); Set<String> deploymentIds = deployedAppsMap.get(app.getId()); if (deploymentIds == null) { Failure failure = new Failure(4004, "App is not deployed: " + app.getId()); logger.error(failure.getError()); message.fail(failure.getCode(), failure.getMessage()); } else {/* w w w . j av a 2s . c o m*/ VerticleUtils.undeployVerticles(deploymentIds.iterator(), vertx, h -> { if (h.failed()) { Failure failure = new Failure(4005, "Unable to undeploy app: " + app.getId(), h.cause()); logger.error(failure.getError(), failure.getCause()); message.fail(failure.getCode(), failure.getMessage()); } else { message.reply(true); } }); } }; }
From source file:io.github.jdocker.serviceregistry.ServiceRegistry.java
License:Apache License
private void findEndpointEndReply(String endpointName, Message<String> message, SharedData sd) { LocalMap<String, String> map1 = sd.getLocalMap(REG_NAME); final String endpointValue = map1.get(endpointName); // TODO should we define any timeouts or anything else? message.reply(endpointValue);/*from w ww . j a va2s. c om*/ }
From source file:net.kuujo.vertigo.deployment.impl.LocalDeploymentManager.java
License:Apache License
@Override public DeploymentManager undeployNetwork(NetworkContext network, Handler<AsyncResult<Void>> doneHandler) { LocalMap<String, String> deploymentIds = vertx.sharedData().getLocalMap(network.name()); CountingCompletionHandler<Void> counter = new CountingCompletionHandler<Void>(deploymentIds.size()) .setHandler(result -> {// w w w.j a va2 s.co m if (result.succeeded()) { vertx.sharedData().<String, NetworkContext>getLocalMap(NETWORKS_KEY).remove(network.name()); vertx.sharedData().<String, String>getLocalMap(network.name()).clear(); } doneHandler.handle(result); }); for (ComponentContext component : network.components()) { String deploymentId = deploymentIds.get(component.address()); if (deploymentId != null) { vertx.undeploy(deploymentId, counter); } } return this; }
From source file:org.azrul.langmera.QLearningAnalytics.java
public void getCalculatedDecision(DecisionRequest req, Vertx vertx, Consumer<DecisionResponse> responseAction) { getDecisionPreCondition(req);/*from w w w .j ava 2 s .c o m*/ LocalMap<String, Double> q = vertx.sharedData().getLocalMap("Q"); String keyWithMaxVal = null; Double maxVal = Double.NEGATIVE_INFINITY; for (String k : q.keySet()) { if (q.get(k) > maxVal) { maxVal = q.get(k); keyWithMaxVal = k; } } DecisionResponse resp = null; if (keyWithMaxVal != null) { String decision = keyWithMaxVal.split(":")[1]; resp = new DecisionResponse(); resp.setDecisionId(req.getDecisionId()); resp.setDecision(decision); resp.setQValue(maxVal); //save cache to be matched to feedback if (req != null) { vertx.sharedData().getLocalMap("DECISION_REQUEST").put(req.getDecisionId(), req); } if (resp != null) { vertx.sharedData().getLocalMap("DECISION_RESPONSE").put(req.getDecisionId(), resp); } responseAction.accept(resp); } else { getRandomDecision(req, vertx, responseAction); } }
From source file:org.azrul.langmera.QLearningAnalytics.java
@Override public void learn(DecisionFeedback currentFeedback, Vertx vertx, Runnable responseAction) { LocalMap<String, DetailDecisionFeedback> decisionFeedbackMap = vertx.sharedData() .getLocalMap("DECISION_FEEDBACK"); LocalMap<String, DecisionRequest> decisionRequestMap = vertx.sharedData().getLocalMap("DECISION_REQUEST"); LocalMap<String, DecisionResponse> decisionResponseMap = vertx.sharedData() .getLocalMap("DECISION_RESPONSE"); LocalMap<String, Double> q = vertx.sharedData().getLocalMap("Q"); LocalMap<Long, String> trackers = vertx.sharedData().getLocalMap("FEEDBACK_TRACKER"); int feedbackCount = decisionFeedbackMap.size(); boolean skipLearning = false; if (decisionRequestMap.get(currentFeedback.getDecisionId()) == null) { skipLearning = true;// w ww .j a v a2 s. c om } if (decisionResponseMap.get(currentFeedback.getDecisionId()) == null) { skipLearning = true; } if (skipLearning == false) { String context = decisionRequestMap.get(currentFeedback.getDecisionId()).getContext(); String decision = decisionResponseMap.get(currentFeedback.getDecisionId()).getDecision(); DetailDecisionFeedback detailFB = new DetailDecisionFeedback(); detailFB.setFeedback(currentFeedback); detailFB.setContext(context); detailFB.setDecision(decision); decisionFeedbackMap.put(currentFeedback.getDecisionId(), detailFB); Long trackerKey = (new Date()).getTime(); trackers.put(trackerKey, currentFeedback.getDecisionId()); int feedbackCountByDecision = 0; List<Double> rewards = new ArrayList<>(); for (DetailDecisionFeedback fb : decisionFeedbackMap.values()) { if (context.equals(decisionFeedbackMap.get(fb.getFeedback().getDecisionId()).getContext()) && decision .equals(decisionFeedbackMap.get(fb.getFeedback().getDecisionId()).getDecision())) { feedbackCountByDecision++; rewards.add(fb.getFeedback().getScore()); } } Double w = 0.0; Double alpha = config.getProperty("alpha", Double.class); //if no step parameter is configured, calculate it if (alpha == null) { alpha = 1.0 / (feedbackCountByDecision); } //non-stationary q-learning int i = 0; for (Double ri : rewards) { i++; w = w + alpha * (Math.pow(1 - alpha, feedbackCountByDecision - i)) * ri; } Double newQ = w; //System.out.println(feedbackCount+" Q:["+context + ":" + decision+"]"+newQ); //save what we learn if (newQ.isInfinite() || newQ.isNaN()) { //skip } else { String key = context + ":" + decision; q.put(key, newQ); } //Limit the number of history taken into account - prevents memory leak if (feedbackCount > config.getProperty("maxHistoryRetained", Integer.class)) { Long tk = Collections.min(trackers.keySet()); String decisionIDWithMinTracker = trackers.get(tk); decisionFeedbackMap.remove(decisionIDWithMinTracker); trackers.remove(tk); } //clear cached req/resp once the feedback has come back decisionRequestMap.remove(currentFeedback.getDecisionId()); decisionResponseMap.remove(currentFeedback.getDecisionId()); //Get maxQ Double maxQ = Double.NEGATIVE_INFINITY; String decisionWithMaxQ = null; for (String contextDecision : q.keySet()) { if (q.get(contextDecision) > maxQ) { decisionWithMaxQ = contextDecision; maxQ = q.get(contextDecision); } } //keep traces if (Boolean.TRUE.equals(config.getProperty("collect.traces", Boolean.class))) { Date now = new Date(); for (String contextDecision : q.keySet()) { List<Double> qtrace = traces.get(contextDecision); if (qtrace == null) { qtrace = new ArrayList<Double>(); qtrace.add(q.get(contextDecision)); traces.put(contextDecision, qtrace); } else { qtrace.add(q.get(contextDecision)); } String[] c = contextDecision.split(":"); Trace trace = new Trace(currentFeedback.getDecisionId(), c[0], q.get(contextDecision), maxQ, now, c[1], currentFeedback.getScore()); vertx.eventBus().publish("SAVE_TRACE_TO_TRACE", SerializationUtils.serialize((Serializable) trace)); } } // //put in in-memory DB // // // String[] c = decisionWithMaxQ.split(":"); // if (InMemoryDB.store.get(0)==null){ // List<Object> imContext = new ArrayList<Object>(); // imContext.add(c[0]); // InMemoryDB.store.add(0,imContext); // }else{ // InMemoryDB.store.get(0).add(c[0]); // } // // if (InMemoryDB.store.get(1)==null){ // List<Object> imDecision = new ArrayList<Object>(); // imDecision.add(c[1]); // InMemoryDB.store.add(1,imDecision); // }else{ // InMemoryDB.store.get(1).add(c[1]); // } // // if (InMemoryDB.store.get(2)==null){ // List<Object> imMaxQ = new ArrayList<Object>(); // imMaxQ.add(maxQ); // InMemoryDB.store.add(2,imMaxQ); // }else{ // InMemoryDB.store.get(2).add(maxQ); // } // // if (InMemoryDB.store.get(3)==null){ // List<Object> imTime= new ArrayList<Object>(); // imTime.add(new Date()); // InMemoryDB.store.add(3,imTime); // }else{ // InMemoryDB.store.get(3).add(new Date()); // } responseAction.run(); if (Boolean.TRUE.equals(currentFeedback.getTerminal())) { long delta = (new Date()).getTime() - startTime; System.out.println("Time taken to process " + feedbackCount + " msgs:" + delta + " ms"); System.out.println("Time taken per msg: " + (delta / feedbackCount) + " ms"); System.out .println("Msgs per s: " + ((1000.0 * (double) feedbackCount) / ((double) delta)) + " msgs"); if (Boolean.TRUE.equals(config.getProperty("collect.traces", Boolean.class)) && Boolean.TRUE.equals(config.getProperty("display.desktop.chart", Boolean.class))) { final LineChart demo = new LineChart(chartDesc, traces); demo.pack(); demo.setVisible(true); } } } else { logger.log(Level.WARNING, "Attempt to learn from a feedback with no corresponding request/response"); responseAction.run(); } // //select qmovies,qsports,qconcerts from // (select t1.qvalue as qsports,t1.decisionid from trace t1 where t1.decision='SPORTS' order by t1.decisiontime) as A1 // join (select t2.qvalue as qmovies,t2.decisionid from trace t2 where t2.decision='MOVIES' order by t2.decisiontime) as A2 on A1.decisionid = A2.decisionid // join (select t3.qvalue as qconcerts,t3.decisionid from trace t3 where t3.decision='CONCERTS' order by t3.decisiontime) as A3 on A1.decisionid = A3.decisionid }
From source file:org.entcore.admin.Admin.java
License:Open Source License
@Override public void start() throws Exception { super.start(); addController(new AdminController()); final PlateformeInfoController plateformeInfoController = new PlateformeInfoController(); // check if sms module activated String smsAddress = ""; String smsProvider = ""; LocalMap<Object, Object> server = vertx.sharedData().getLocalMap("server"); if (server != null && server.get("smsProvider") != null) { smsProvider = (String) server.get("smsProvider"); final String node = (String) server.get("node"); smsAddress = (node != null ? node : "") + "entcore.sms"; } else {//from ww w . jav a 2 s. co m smsAddress = "entcore.sms"; } JsonObject pingAction = new JsonObject().put("provider", smsProvider).put("action", "ping"); vertx.eventBus().send(smsAddress, pingAction, new DeliveryOptions().setSendTimeout(5000l), new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> res) { if (res != null && res.succeeded()) { if ("ok".equals(res.result().body().getString("status"))) { plateformeInfoController.setSmsModule(true); } } addController(plateformeInfoController); } }); }
From source file:org.entcore.archive.controllers.ArchiveController.java
License:Open Source License
@Override public void init(Vertx vertx, final JsonObject config, RouteMatcher rm, Map<String, fr.wseduc.webutils.security.SecuredAction> securedActions) { super.init(vertx, config, rm, securedActions); String exportPath = config.getString("export-path", System.getProperty("java.io.tmpdir")); Set<String> expectedExports = new HashSet<>(); final JsonArray e = config.getJsonArray("expected-exports"); for (Object o : e) { if (o instanceof String) { expectedExports.add((String) o); }//w ww .j a v a 2 s. c o m } LocalMap<Object, Object> server = vertx.sharedData().getLocalMap("server"); Boolean cluster = (Boolean) server.get("cluster"); final Map<String, Long> userExport = MapFactory.getSyncClusterMap(Archive.ARCHIVES, vertx); EmailFactory emailFactory = new EmailFactory(vertx, config); EmailSender notification = config.getBoolean("send.export.email", false) ? emailFactory.getSender() : null; storage = new StorageFactory(vertx, config).getStorage(); exportService = new FileSystemExportService(vertx.fileSystem(), eb, exportPath, expectedExports, notification, storage, userExport, new TimelineHelper(vertx, eb, config)); eventStore = EventStoreFactory.getFactory().getEventStore(Archive.class.getSimpleName()); Long periodicUserClear = config.getLong("periodicUserClear"); if (periodicUserClear != null) { vertx.setPeriodic(periodicUserClear, new Handler<Long>() { @Override public void handle(Long event) { final long limit = System.currentTimeMillis() - config.getLong("userClearDelay", 3600000l); Set<Map.Entry<String, Long>> entries = new HashSet<>(userExport.entrySet()); for (Map.Entry<String, Long> e : entries) { if (e.getValue() == null || e.getValue() < limit) { userExport.remove(e.getKey()); } } } }); } }