private RpcHolder lookupHolder( final Vertx vertx, final String ipcName, final JsonObject config) { synchronized (this.vertx) { final String name = MessageFormat.format(DS_LOCAL_MAP_NAME, config.getString("type")); final LocalMap<String, RpcHolder> map = this.vertx.sharedData().getLocalMap(name); RpcHolder holder = map.get(ipcName); if (null == holder) { holder = new RpcHolder(vertx, config, () -> removeFromMap(map, name)); map.put(name, holder); } else { holder.incRefCount(); } return holder; } }
private double determineTargetPrice(String ticker) { LocalMap<String, Double> previousMap = engineData.getLocalMap("previousMap"); Double oldPrice = previousMap.get(ticker); if (oldPrice == null) { // oldPrice = 10.85; double random = java.util.concurrent.ThreadLocalRandom.current().nextDouble(10.85,345.24); oldPrice = new Double(random); } DecimalFormat df2 = new DecimalFormat("###.##"); double increment = java.util.concurrent.ThreadLocalRandom.current().nextDouble(10.85,24.12); Double newPrice = oldPrice + increment; Double twoDecimalPlaces = new Double(df2.format(newPrice)); System.out.println("new price " + twoDecimalPlaces); previousMap.put(ticker, twoDecimalPlaces); return twoDecimalPlaces.doubleValue(); }
@Override public Object execute() throws Exception { SharedData sharedData = getVertxService().sharedData(); LocalMap<Object, Object> map = sharedData.getLocalMap(this.map); ShellTable table = new ShellTable(); table.column("Map[" + this.map + "]\nKey"); table.column("\nValue"); if (keys != null) { keys.forEach(key -> { renderRow(map, table, key); }); } else { map.keySet().forEach(key -> { renderRow(map, table, (String) key); }); } table.print(System.out); return null; }
private void getStore(Handler<AsyncResult<AsyncMap<String, Buffer>>> handler) { if (store != null) { handler.handle(Future.succeededFuture(store)); return; } String name = getClass().getName() + ".STORE"; if (vertx.isClustered()) { vertx.sharedData().<String, Buffer>getClusterWideMap(name, ar -> { if (ar.succeeded()) { store = ar.result(); } handler.handle(ar); }); } else { LocalMap<String, Buffer> lm = vertx.sharedData().getLocalMap(name); store = new AsyncLocalMap<String, Buffer>(lm); handler.handle(Future.succeededFuture(store)); } }
@Test public void testNonShared() { LocalMap<String, Object> map = getLocalMap(); MailConfig config = new MailConfig(); MailClient client1 = MailClient.createNonShared(vertx, config); assertEquals(1, map.size()); MailClient client2 = MailClient.createNonShared(vertx, config); assertEquals(2, map.size()); MailClient client3 = MailClient.createNonShared(vertx, config); assertEquals(3, map.size()); client1.close(); assertEquals(2, map.size()); client2.close(); assertEquals(1, map.size()); client3.close(); assertWaitUntil(() -> map.size() == 0); assertWaitUntil(() -> getLocalMap().size() == 0); assertWaitUntil(() -> map != getLocalMap()); // Map has been closed }
@Test public void testSharedDefault() throws Exception { LocalMap<String, Object> map = getLocalMap(); MailConfig config = new MailConfig(); MailClient client1 = MailClient.createShared(vertx, config); assertEquals(1, map.size()); MailClient client2 = MailClient.createShared(vertx, config); assertEquals(1, map.size()); MailClient client3 = MailClient.createShared(vertx, config); assertEquals(1, map.size()); client1.close(); assertEquals(1, map.size()); client2.close(); assertEquals(1, map.size()); client3.close(); assertEquals(0, map.size()); assertNotSame(map, getLocalMap()); }
@Override public void handle(RoutingContext context) { Vertx vertx = context.vertx(); LocalMap<Object, Object> rateLimitations = vertx.sharedData().getLocalMap("mvc.rateLimitation"); String clientIp = context.request().remoteAddress().host(); JsonObject json = (JsonObject) rateLimitations.get(clientIp); ClientAccesses accesses; if (json == null) { accesses = new ClientAccesses(); } else { accesses = ClientAccesses.fromJsonObject(json); } accesses.newAccess(); rateLimitations.put(clientIp, accesses.toJsonObject()); if (accesses.isOverLimit(rateLimit)) { context.fail(420); } else { context.next(); } }
@Override public void findRouteSocketInRegistryAndRemove(ServerWebSocket serverSocket) { final SharedData sharedData = this.vertx.sharedData(); final String binaryHandlerID = serverSocket.binaryHandlerID(); final String textHandlerID = serverSocket.textHandlerID(); final LocalMap<String, byte[]> wsRegistry = sharedData.getLocalMap(WS_REGISTRY); final WSEndpointHolder holder = getWSEndpointHolderFromSharedData(wsRegistry); if (holder != null) { final List<WSEndpoint> all = holder.getAll(); final Optional<WSEndpoint> first = all.parallelStream().filter(e -> e.getBinaryHandlerId().equals(binaryHandlerID) && e.getTextHandlerId().equals(textHandlerID)).findFirst(); first.ifPresent(endpoint -> { holder.remove(endpoint); wsRegistry.replace(WS_ENDPOINT_HOLDER, serialize(holder)); log("OK REMOVE: " + serverSocket.binaryHandlerID()); }); } }
@Override public void replyToAllWS(Message<byte[]> message) { try { log("Reply to all: " + this); final WSMessageWrapper wrapper = (WSMessageWrapper) Serializer.deserialize(message.body()); final String stringResult = TypeTool.trySerializeToString(wrapper.getBody()); final byte[] payload = stringResult != null ? stringResult.getBytes() : Serializer.serialize(wrapper.getBody()); final SharedData sharedData = this.vertx.sharedData(); final LocalMap<String, byte[]> wsRegistry = sharedData.getLocalMap(WS_REGISTRY); final byte[] holderPayload = wsRegistry.get(WS_ENDPOINT_HOLDER); if (holderPayload != null) { final WSEndpointHolder holder = (WSEndpointHolder) deserialize(holderPayload); final List<WSEndpoint> all = holder.getAll(); all.parallelStream(). filter(endP -> endP.getUrl().equals(wrapper.getEndpoint().getUrl())). forEach( endpoint -> replyToEndpoint(stringResult, payload, endpoint) ); } } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } }
@Test public void testNonShared() { LocalMap<String, Object> map = getLocalMap(); JsonObject config = new JsonObject(); config.put("provider_class", TestDSProvider.class.getName()); SQLClient client1 = JDBCClient.createNonShared(vertx, config); assertEquals(1, TestDSProvider.instanceCount.get()); SQLClient client2 = JDBCClient.createNonShared(vertx, config); assertEquals(2, TestDSProvider.instanceCount.get()); SQLClient client3 = JDBCClient.createNonShared(vertx, config); assertEquals(3, TestDSProvider.instanceCount.get()); client1.close(); assertWaitUntil(() -> TestDSProvider.instanceCount.get() == 2); client2.close(); assertWaitUntil(() -> TestDSProvider.instanceCount.get() == 1); client3.close(); assertWaitUntil(() -> TestDSProvider.instanceCount.get() == 0); assertWaitUntil(() -> getLocalMap().size() == 0); assertWaitUntil(() -> map != getLocalMap()); // Map has been closed }
@Test public void testSharedDefault() throws Exception { LocalMap<String, Object> map = getLocalMap(); JsonObject config = new JsonObject(); config.put("provider_class", TestDSProvider.class.getName()); SQLClient client1 = JDBCClient.createShared(vertx, config); assertEquals(1, TestDSProvider.instanceCount.get()); assertEquals(1, map.size()); SQLClient client2 = JDBCClient.createShared(vertx, config); assertEquals(1, TestDSProvider.instanceCount.get()); assertEquals(1, map.size()); SQLClient client3 = JDBCClient.createShared(vertx, config); assertEquals(1, TestDSProvider.instanceCount.get()); assertEquals(1, map.size()); client1.close(); Thread.sleep(200); assertEquals(1, TestDSProvider.instanceCount.get()); assertEquals(1, map.size()); client2.close(); assertEquals(1, TestDSProvider.instanceCount.get()); assertEquals(1, map.size()); client3.close(); assertWaitUntil(() -> TestDSProvider.instanceCount.get() == 0); assertWaitUntil(() -> map.size() == 0); assertWaitUntil(() -> map != getLocalMap()); // Map has been closed }
public static AsyncSQLClient getOrCreate(Vertx vertx, JsonObject config, String poolName, boolean mySQL) { synchronized (vertx) { LocalMap<String, ClientHolder> map = vertx.sharedData().getLocalMap( DS_LOCAL_MAP_NAME_BASE + (mySQL ? "MySQL" : "PostgreSQL")); ClientHolder theHolder = map.get(poolName); if (theHolder == null) { theHolder = new ClientHolder(vertx, config, mySQL, () -> removeFromMap(vertx, map, poolName)); map.put(poolName, theHolder); } else { theHolder.incRefCount(); } return new ClientWrapper(theHolder); } }
@Test public void testNonShared() { LocalMap<String, Object> map = getLocalMap(); JsonObject config = new JsonObject(); SQLClient client1 = MySQLClient.createNonShared(vertx, config); assertEquals(1, map.size()); SQLClient client2 = MySQLClient.createNonShared(vertx, config); assertEquals(2, map.size()); SQLClient client3 = MySQLClient.createNonShared(vertx, config); assertEquals(3, map.size()); client1.close(); assertEquals(2, map.size()); client2.close(); assertEquals(1, map.size()); client3.close(); assertEquals(0, map.size()); assertWaitUntil(() -> getLocalMap().size() == 0); assertWaitUntil(() -> map != getLocalMap()); // Map has been closed }
@Test public void testSharedDefault() throws Exception { LocalMap<String, Object> map = getLocalMap(); JsonObject config = new JsonObject(); SQLClient client1 = MySQLClient.createShared(vertx, config); assertEquals(1, map.size()); SQLClient client2 = MySQLClient.createShared(vertx, config); assertEquals(1, map.size()); SQLClient client3 = MySQLClient.createShared(vertx, config); assertEquals(1, map.size()); client1.close(); assertEquals(1, map.size()); client2.close(); assertEquals(1, map.size()); client3.close(); assertWaitUntil(() -> map.size() == 0); assertWaitUntil(() -> map != getLocalMap()); // Map has been closed }
@Test public void testNonShared() { LocalMap<String, Object> map = getLocalMap(); JsonObject config = getConfig(); MongoClient client1 = MongoClient.createNonShared(vertx, config); assertEquals(1, map.size()); MongoClient client2 = MongoClient.createNonShared(vertx, config); assertEquals(2, map.size()); MongoClient client3 = MongoClient.createNonShared(vertx, config); assertEquals(3, map.size()); client1.close(); assertEquals(2, map.size()); client2.close(); assertEquals(1, map.size()); client3.close(); assertWaitUntil(() -> map.size() == 0); assertWaitUntil(() -> getLocalMap().size() == 0); assertWaitUntil(() -> map != getLocalMap()); // Map has been closed }
@Test public void testSharedDefault() throws Exception { LocalMap<String, Object> map = getLocalMap(); JsonObject config = getConfig(); MongoClient client1 = MongoClient.createShared(vertx, config); assertEquals(1, map.size()); MongoClient client2 = MongoClient.createShared(vertx, config); assertEquals(1, map.size()); MongoClient client3 = MongoClient.createShared(vertx, config); assertEquals(1, map.size()); client1.close(); assertEquals(1, map.size()); client2.close(); assertEquals(1, map.size()); client3.close(); assertEquals(0, map.size()); assertNotSame(map, getLocalMap()); }
HtmlFileTransport(Vertx vertx, Router router, LocalMap<String, SockJSSession> sessions, SockJSHandlerOptions options, Handler<SockJSSocket> sockHandler) { super(vertx, sessions, options); String htmlFileRE = COMMON_PATH_ELEMENT_RE + "htmlfile.*"; router.getWithRegex(htmlFileRE).handler(rc -> { if (log.isTraceEnabled()) log.trace("HtmlFile, get: " + rc.request().uri()); String callback = rc.request().getParam("callback"); if (callback == null) { callback = rc.request().getParam("c"); if (callback == null) { rc.response().setStatusCode(500).end("\"callback\" parameter required\n"); return; } } HttpServerRequest req = rc.request(); String sessionID = req.params().get("param0"); SockJSSession session = getSession(rc, options.getSessionTimeout(), options.getHeartbeatInterval(), sessionID, sockHandler); session.register(req, new HtmlFileListener(options.getMaxBytesStreaming(), rc, callback, session)); }); }
SockJSSession(Vertx vertx, LocalMap<String, SockJSSession> sessions, RoutingContext rc, String id, long timeout, long heartbeatInterval, Handler<SockJSSocket> sockHandler) { super(vertx, rc.session(), rc.user()); this.sessions = sessions; this.id = id; this.timeout = timeout; this.sockHandler = sockHandler; // Start a heartbeat heartbeatID = vertx.setPeriodic(heartbeatInterval, tid -> { if (listener != null) { listener.sendFrame("h"); } }); }
/** remove topic from session */ public void deleteSubcription(String topic, String clientID) { LocalMap<String, Object> subscriptionsMap = vertx.sharedData().getLocalMap(tenant + clientID); Set<String> subscriptions = subscriptionsMap.keySet(); Set<String> copyOfSubscriptions = new LinkedHashSet<>(subscriptions); for(String item : copyOfSubscriptions) { Subscription s = new Subscription(); s.fromString(item); if(s.getTopicFilter().equals(topic)) { subscriptions.remove(item); } } if(subscriptions.isEmpty()) { vertx.sharedData().getLocalMap(tenant + "persistence.clients").remove(clientID); } }
private void removeFromMap(final LocalMap<String, RpcHolder> map, final String name) { synchronized (this.vertx) { map.remove(name); if (map.isEmpty()) { map.close(); } } }
private EmfProvidereHolder lookupHolder() { synchronized (vertx) { LocalMap<String, EmfProvidereHolder> map = vertx.sharedData().getLocalMap(DS_LOCAL_MAP_NAME); EmfProvidereHolder theHolder = map.get(datasourceName); if (theHolder == null) { theHolder = new EmfProvidereHolder((VertxInternal) vertx, config, map, datasourceName); } else { theHolder.incRefCount(); } return theHolder; } }
public EmfProvidereHolder(VertxInternal vertx, JsonObject config, LocalMap<String, EmfProvidereHolder> map, String name) { this.name = name; this.config = config; this.vertx = vertx; this.map = map; this.emfProvider = initializeProvider().setConfig(config).setVertx(vertx); }
@Override public Object execute() throws Exception { SharedData sharedData = getVertxService().sharedData(); LocalMap<Object, Object> localMap = sharedData.getLocalMap(map); localMap.put(key, value); return "key and value added to map"; }
@Override public Object execute() throws Exception { SharedData sharedData = getVertxService().sharedData(); LocalMap<Object, Object> map = sharedData.getLocalMap(this.map); if (keys != null) { keys.forEach(map::remove); } return "removed keys from map"; }
@SuppressWarnings("unchecked") static LocalSessionStoreAdapter of(MessageProducer<String> sessionExpiredProducer, LocalSessionStoreImpl delegate) { LocalMap<String, Session> localMap = Reflection.field("localMap").ofType(LocalMap.class).in(delegate).get(); String sessionMapName = Reflection.field("name").ofType(String.class).in(localMap).get(); Vertx vertx = Reflection.field("vertx").ofType(Vertx.class).in(delegate).get(); long reaperInterval = Reflection.field("reaperInterval").ofType(long.class).in(delegate).get(); delegate.close(); return new LocalSessionStoreAdapter(vertx, sessionMapName, reaperInterval, sessionExpiredProducer); }
/** * Convenience factory method to create from shared Brave configuration in the Vertx localMap. */ public static ZipkinWebHandler create(final Vertx vertx) { final LocalMap<String, ShareableBrave> localMap = vertx.sharedData().<String, ShareableBrave>getLocalMap(ShareableBrave.LOCALMAP_KEY); Objects.requireNonNull(localMap, "localmap==null"); final ShareableBrave brave = localMap.get(ShareableBrave.LOCALMAP_ITEM_KEY); Objects.requireNonNull(brave, "brave==null"); return new ZipkinWebHandler(brave.get()); }
@Override protected void prepareData(TestContext context, Vertx vertx, String path, Handler<AsyncResult<String>> handler) { LocalMap<String, Buffer> lm = getLocalMap(vertx); String p = PathUtils.join(path, ID); lm.put(p, Buffer.buffer(CHUNK_CONTENT)); handler.handle(Future.succeededFuture(p)); }
@Override protected void validateAfterStoreAdd(TestContext context, Vertx vertx, String path, Handler<AsyncResult<Void>> handler) { LocalMap<String, Buffer> lm = getLocalMap(vertx); context.assertEquals(1, lm.size()); handler.handle(Future.succeededFuture()); }
@Override protected void validateAfterStoreDelete(TestContext context, Vertx vertx, String path, Handler<AsyncResult<Void>> handler) { LocalMap<String, Buffer> lm = getLocalMap(vertx); context.assertEquals(0, lm.size()); handler.handle(Future.succeededFuture()); }
private MailHolder lookupHolder(String poolName, MailConfig config) { synchronized (vertx) { LocalMap<String, MailHolder> map = vertx.sharedData().getLocalMap(POOL_LOCAL_MAP_NAME); MailHolder theHolder = map.get(poolName); if (theHolder == null) { theHolder = new MailHolder(vertx, config, () -> removeFromMap(map, poolName)); map.put(poolName, theHolder); } else { theHolder.incRefCount(); } return theHolder; } }
private void removeFromMap(LocalMap<String, MailHolder> map, String dataSourceName) { synchronized (vertx) { map.remove(dataSourceName); if (map.isEmpty()) { map.close(); } } }
@Test public void testSharedNamed() throws Exception { LocalMap<String, Object> map = getLocalMap(); MailConfig config = new MailConfig(); MailClient client1 = MailClient.createShared(vertx, config, "ds1"); assertEquals(1, map.size()); MailClient client2 = MailClient.createShared(vertx, config, "ds1"); assertEquals(1, map.size()); MailClient client3 = MailClient.createShared(vertx, config, "ds1"); assertEquals(1, map.size()); MailClient client4 = MailClient.createShared(vertx, config, "ds2"); assertEquals(2, map.size()); MailClient client5 = MailClient.createShared(vertx, config, "ds2"); assertEquals(2, map.size()); MailClient client6 = MailClient.createShared(vertx, config, "ds2"); assertEquals(2, map.size()); client1.close(); assertEquals(2, map.size()); client2.close(); assertEquals(2, map.size()); client3.close(); assertEquals(1, map.size()); client4.close(); assertEquals(1, map.size()); client5.close(); assertEquals(1, map.size()); client6.close(); assertEquals(0, map.size()); assertNotSame(map, getLocalMap()); }
public Optional<Auction> getById(String auctionId) { LocalMap<String, String> auctionSharedData = this.sharedData.getLocalMap(auctionId); if(auctionSharedData.isEmpty()) { return Optional.empty(); } return Optional.of(auctionSharedData).map(this::convertToAuction); }
public void insert(Auction auction) { LocalMap<String, String> auctionSharedData = this.sharedData.getLocalMap(auction.getId()); auctionSharedData.put("id", auction.getId()); auctionSharedData.put("price", auction.getPrice().toString()); auctionSharedData.put("buyer", auction.getBuyer()); auctionSharedData.put("endingTime", auction.getEndingTime().toString()); }
private Auction convertToAuction(LocalMap<String, String> auction) { return new Auction( auction.get("id"), new BigDecimal(auction.get("price")), auction.get("buyer"), ZonedDateTime.parse(auction.get("endingTime")) ); }
private static void addMemberVars(String namespace, TypeSpec.Builder builder) { builder.addField(GeneratorHelper.getLogger(namespace, "Server")); builder.addField(ParameterizedTypeName.get(LocalMap.class, String.class, Long.class), "sharedData", Modifier.PRIVATE); builder.addField(FieldSpec.builder(String.class, SHARED_DATA_FIELD, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer("$S", "shared_data").build()); builder.addField(FieldSpec.builder(String.class, INITIALIZER_THREAD_FIELD, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer("$S", "initializer_thread").build()); builder.addField(HttpServer.class, "server", Modifier.PRIVATE); builder.addField(DefaultCassandraSession.class, "session", Modifier.PRIVATE); builder.addField(int.class, "port", Modifier.PRIVATE); }
private void cleanHistoryMap(Long timerId) { LocalMap<String, ClientAccesses> rateLimitations = vertx.sharedData().getLocalMap("mvc.rateLimitation"); if (rateLimitations == null) { return; } rateLimitations.keySet().stream() .filter(clientsWithNoAccessPredicate(rateLimitations)) .forEach(rateLimitations::remove); }
private Predicate<String> clientsWithNoAccessPredicate(LocalMap<String, ClientAccesses> rateLimitations) { RateLimit rateLimit = config.getRateLimit(); return clientIp -> { ClientAccesses accesses = rateLimitations.get(clientIp); long keepAfter = rateLimit.getTimeUnit().toMillis(rateLimit.getValue()); accesses.clearHistory(keepAfter); return accesses.noAccess(); }; }
public Optional<Auction> getById(String auctionId) { LocalMap<String, String> auctionSharedData = this.sharedData.getLocalMap(auctionId); return Optional.of(auctionSharedData) .filter(m -> !m.isEmpty()) .map(this::convertToAuction); }