io.vertx.core.shareddata.LocalMap Java Examples
The following examples show how to use
io.vertx.core.shareddata.LocalMap.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RefCountTest.java From vertx-mongo-client with Apache License 2.0 | 6 votes |
@Test public void testNonShared() { LocalMap<String, Object> map = getLocalMap(); JsonObject config = getConfig(); MongoClient client1 = MongoClient.create(vertx, config); assertEquals(1, map.size()); MongoClient client2 = MongoClient.create(vertx, config); assertEquals(2, map.size()); MongoClient client3 = MongoClient.create(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 }
Example #2
Source File: RefCountTest.java From vertx-mongo-client with Apache License 2.0 | 6 votes |
@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()); }
Example #3
Source File: WSLocalHandler.java From vert.x-microservice with Apache License 2.0 | 6 votes |
@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(); } }
Example #4
Source File: MQTTStoreManagerAsync.java From vertx-mqtt-broker with Apache License 2.0 | 6 votes |
/** 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); } }
Example #5
Source File: WSLocalHandler.java From vert.x-microservice with Apache License 2.0 | 6 votes |
@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()); }); } }
Example #6
Source File: RefCountTest.java From vertx-mail-client with Apache License 2.0 | 6 votes |
@Test public void testNonShared() { LocalMap<String, Object> map = getLocalMap(); MailConfig config = new MailConfig(); MailClient client1 = MailClient.create(vertx, config); assertEquals(1, map.size()); MailClient client2 = MailClient.create(vertx, config); assertEquals(2, map.size()); MailClient client3 = MailClient.create(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 }
Example #7
Source File: RefCountTest.java From vertx-mail-client with Apache License 2.0 | 6 votes |
@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()); }
Example #8
Source File: SockJSSession.java From vertx-web with Apache License 2.0 | 6 votes |
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; context = vertx.getOrCreateContext(); pendingReads = new InboundBuffer<>(context); // Start a heartbeat heartbeatID = vertx.setPeriodic(heartbeatInterval, tid -> { if (listener != null) { listener.sendFrame("h", null); } }); }
Example #9
Source File: RateLimitationHandler.java From nubes with Apache License 2.0 | 6 votes |
@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(); } }
Example #10
Source File: WriteHandler.java From nassh-relay with GNU General Public License v2.0 | 5 votes |
@Override public void handle(final RoutingContext context) { final HttpServerRequest request = context.request(); final HttpServerResponse response = context.response(); response.putHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0"); response.putHeader("Pragma", "no-cache"); if (request.params().contains("sid") && request.params().contains("wcnt") && request.params().contains("data")) { final UUID sid = UUID.fromString(request.params().get("sid")); final byte[] data = Base64.getUrlDecoder().decode(request.params().get("data")); response.setStatusCode(200); final LocalMap<String, Session> map = vertx.sharedData().getLocalMap(Constants.SESSIONS); final Session session = map.get(sid.toString()); if (session == null) { response.setStatusCode(410); response.end(); return; } session.setWrite_count(Integer.parseInt(request.params().get("wcnt"))); final Buffer message = Buffer.buffer(); message.appendBytes(data); vertx.eventBus().publish(session.getHandler(), message); response.end(); } else { response.setStatusCode(410); response.end(); } }
Example #11
Source File: RefCountTest.java From vertx-mongo-client with Apache License 2.0 | 5 votes |
@Test public void testSharedNamed() throws Exception { LocalMap<String, Object> map = getLocalMap(); JsonObject config = getConfig(); MongoClient client1 = MongoClient.createShared(vertx, config, "ds1"); assertEquals(1, map.size()); MongoClient client2 = MongoClient.createShared(vertx, config, "ds1"); assertEquals(1, map.size()); MongoClient client3 = MongoClient.createShared(vertx, config, "ds1"); assertEquals(1, map.size()); MongoClient client4 = MongoClient.createShared(vertx, config, "ds2"); assertEquals(2, map.size()); MongoClient client5 = MongoClient.createShared(vertx, config, "ds2"); assertEquals(2, map.size()); MongoClient client6 = MongoClient.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()); }
Example #12
Source File: WebSocketTransport.java From vertx-web with Apache License 2.0 | 5 votes |
WebSocketTransport(Vertx vertx, Router router, LocalMap<String, SockJSSession> sessions, SockJSHandlerOptions options, Handler<SockJSSocket> sockHandler) { super(vertx, sessions, options); String wsRE = COMMON_PATH_ELEMENT_RE + "websocket"; router.getWithRegex(wsRE).handler(rc -> { HttpServerRequest req = rc.request(); String connectionHeader = req.headers().get(io.vertx.core.http.HttpHeaders.CONNECTION); if (connectionHeader == null || !connectionHeader.toLowerCase().contains("upgrade")) { rc.response().setStatusCode(400); rc.response().end("Can \"Upgrade\" only to \"WebSocket\"."); } else { ServerWebSocket ws = rc.request().upgrade(); if (log.isTraceEnabled()) log.trace("WS, handler"); SockJSSession session = new SockJSSession(vertx, sessions, rc, options.getHeartbeatInterval(), sockHandler); session.register(req, new WebSocketListener(ws, session)); } }); router.getWithRegex(wsRE).handler(rc -> { if (log.isTraceEnabled()) log.trace("WS, get: " + rc.request().uri()); rc.response().setStatusCode(400); rc.response().end("Can \"Upgrade\" only to \"WebSocket\"."); }); router.routeWithRegex(wsRE).handler(rc -> { if (log.isTraceEnabled()) log.trace("WS, all: " + rc.request().uri()); rc.response().putHeader(HttpHeaders.ALLOW, "GET").setStatusCode(405).end(); }); }
Example #13
Source File: EventSourceTransport.java From vertx-web with Apache License 2.0 | 5 votes |
EventSourceTransport(Vertx vertx, Router router, LocalMap<String, SockJSSession> sessions, SockJSHandlerOptions options, Handler<SockJSSocket> sockHandler) { super(vertx, sessions, options); String eventSourceRE = COMMON_PATH_ELEMENT_RE + "eventsource"; router.getWithRegex(eventSourceRE).handler(rc -> { if (log.isTraceEnabled()) log.trace("EventSource transport, get: " + rc.request().uri()); String sessionID = rc.request().getParam("param0"); SockJSSession session = getSession(rc, options.getSessionTimeout(), options.getHeartbeatInterval(), sessionID, sockHandler); HttpServerRequest req = rc.request(); session.register(req, new EventSourceListener(options.getMaxBytesStreaming(), rc, session)); }); }
Example #14
Source File: XhrTransport.java From vertx-web with Apache License 2.0 | 5 votes |
XhrTransport(Vertx vertx, Router router, LocalMap<String, SockJSSession> sessions, SockJSHandlerOptions options, Handler<SockJSSocket> sockHandler) { super(vertx, sessions, options); String xhrBase = COMMON_PATH_ELEMENT_RE; String xhrRE = xhrBase + "xhr"; String xhrStreamRE = xhrBase + "xhr_streaming"; Handler<RoutingContext> xhrOptionsHandler = createCORSOptionsHandler(options, "OPTIONS, POST"); router.optionsWithRegex(xhrRE).handler(xhrOptionsHandler); router.optionsWithRegex(xhrStreamRE).handler(xhrOptionsHandler); registerHandler(router, sockHandler, xhrRE, false, options); registerHandler(router, sockHandler, xhrStreamRE, true, options); String xhrSendRE = COMMON_PATH_ELEMENT_RE + "xhr_send"; router.optionsWithRegex(xhrSendRE).handler(xhrOptionsHandler); router.postWithRegex(xhrSendRE).handler(rc -> { if (log.isTraceEnabled()) log.trace("XHR send, post, " + rc.request().uri()); String sessionID = rc.request().getParam("param0"); final SockJSSession session = sessions.get(sessionID); if (session != null && !session.isClosed()) { handleSend(rc, session); } else { rc.response().setStatusCode(404); setJSESSIONID(options, rc); rc.response().end(); } }); }
Example #15
Source File: HtmlFileTransport.java From vertx-web with Apache License 2.0 | 5 votes |
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; } } if (CALLBACK_VALIDATION.matcher(callback).find()) { rc.response().setStatusCode(500); rc.response().end("invalid \"callback\" parameter\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)); }); }
Example #16
Source File: MongoClientImpl.java From vertx-mongo-client with Apache License 2.0 | 5 votes |
private MongoHolder lookupHolder(String datasourceName, JsonObject config) { synchronized (vertx) { LocalMap<String, MongoHolder> map = vertx.sharedData().getLocalMap(DS_LOCAL_MAP_NAME); MongoHolder theHolder = map.get(datasourceName); if (theHolder == null) { theHolder = new MongoHolder(config, () -> removeFromMap(map, datasourceName)); map.put(datasourceName, theHolder); } else { theHolder.incRefCount(); } return theHolder; } }
Example #17
Source File: ReadHandler.java From nassh-relay with GNU General Public License v2.0 | 5 votes |
@Override public void handle(final RoutingContext context) { final HttpServerRequest request = context.request(); final HttpServerResponse response = context.response(); response.putHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0"); response.putHeader("Pragma", "no-cache"); if (request.params().contains("sid") && request.params().contains("rcnt")) { final UUID sid = UUID.fromString(request.params().get("sid")); final LocalMap<String, Session> map = vertx.sharedData().getLocalMap(Constants.SESSIONS); final Session session = map.get(sid.toString()); if (session == null) { logger.warn("could not find valid session for " + sid); response.setStatusCode(410); response.end(); return; } session.setRead_count(Integer.parseInt(request.params().get("rcnt"))); final TransferQueue queue; try { queue = QueueFactory.getQueue(sid.toString()); } catch (NoSuchQueueException ex) { logger.warn(ex, ex.fillInStackTrace()); response.setStatusCode(410); response.end(); return; } final Buffer buffer = queue.poll(); if (buffer == null) { queue.addObserver(new TransferObserver(session, request)); } else { final String encodedBytes = Base64.getUrlEncoder().encodeToString(buffer.getBytes()); response.setStatusCode(200); response.end(encodedBytes); } } else { response.setStatusCode(410); response.end(); } }
Example #18
Source File: MQTTStoreManagerAsync.java From vertx-mqtt-broker with Apache License 2.0 | 5 votes |
/** get subscribed topics by clientID from session*/ public void getSubscriptionsByClientID(String clientID, Handler<List<Subscription>> handler) { ArrayList<Subscription> ret = new ArrayList<>(); LocalMap<String, Object> subscriptions = vertx.sharedData().getLocalMap(tenant + clientID); for(String item : subscriptions.keySet()) { Subscription s = new Subscription(); s.fromString(item); ret.add(s); } handler.handle(ret); }
Example #19
Source File: MQTTStoreManagerAsync.java From vertx-mqtt-broker with Apache License 2.0 | 5 votes |
private void decrementID(String k) { Integer currentID=0; LocalMap<String, Integer> seq = seq(); if(seq.keySet().contains(k)) { currentID = seq.get(k); if (currentID > 0) { seq.put(k, currentID - 1); } } }
Example #20
Source File: MQTTStoreManagerAsync.java From vertx-mqtt-broker with Apache License 2.0 | 5 votes |
public void deleteMessage(String topic) { String key = topic; LocalMap<String, byte[]> map = vertx.sharedData().getLocalMap(tenant); if(map.keySet().contains(key)) { map.remove(key); } }
Example #21
Source File: MQTTStoreManagerAsync.java From vertx-mqtt-broker with Apache License 2.0 | 5 votes |
/** retrieve all stored messages by topicFilter */ public void getMessagesByTopic(String topicFilter, String clientID, Handler<List<byte[]>> handler) { String key = tenant + clientID + topicFilter; // qos 1 and 2 messages LocalMap<String, byte[]> set = vertx.sharedData().getLocalMap(key); // retained messages LocalMap<String, byte[]> set2 = vertx.sharedData().getLocalMap(tenant); // union ArrayList<byte[]> ret = new ArrayList<>(); ret.addAll(set.values()); ret.addAll(set2.values()); handler.handle( ret ); }
Example #22
Source File: MQTTStoreManagerAsync.java From vertx-mqtt-broker with Apache License 2.0 | 5 votes |
/** get and delete topic/message */ public void popMessage(String topic, String clientID, Handler<byte[]> handler) { String key = clientID+topic; String k = ""+currentID(key); LocalMap<String, byte[]> set = vertx.sharedData().getLocalMap(tenant + key); if(set.keySet().contains(k)) { byte[] removed = set.remove(k); decrementID(key); handler.handle( removed ); } else { handler.handle(null); } }
Example #23
Source File: MQTTStoreManagerAsync.java From vertx-mqtt-broker with Apache License 2.0 | 5 votes |
public void clientIDExists(String clientID, Handler<Boolean> handler) { LocalMap<String, Object> m = vertx.sharedData().getLocalMap("clientIDs"); if(m!=null) { handler.handle(m.keySet().contains(clientID)); } else { handler.handle(false); } }
Example #24
Source File: MongoClientImpl.java From vertx-mongo-client with Apache License 2.0 | 5 votes |
private void removeFromMap(LocalMap<String, MongoHolder> map, String dataSourceName) { synchronized (vertx) { map.remove(dataSourceName); if (map.isEmpty()) { map.close(); } } }
Example #25
Source File: WSLocalHandler.java From vert.x-microservice with Apache License 2.0 | 5 votes |
private WSEndpointHolder getWSEndpointHolderFromSharedData(final LocalMap<String, byte[]> wsRegistry) { final byte[] holderPayload = wsRegistry.get(WS_ENDPOINT_HOLDER); if (holderPayload != null) { return (WSEndpointHolder) deserialize(holderPayload); } return null; }
Example #26
Source File: WSLocalHandler.java From vert.x-microservice with Apache License 2.0 | 5 votes |
private void replaceOrAddEndpoint(LocalMap<String, byte[]> wsRegistry, WSEndpointHolder holder, WSEndpoint endpoint) { if (holder != null) { holder.add(endpoint); wsRegistry.replace(WS_ENDPOINT_HOLDER, serialize(holder)); } else { final WSEndpointHolder holderTemp = new WSEndpointHolder(); holderTemp.add(endpoint); wsRegistry.put(WS_ENDPOINT_HOLDER, serialize(holderTemp)); } }
Example #27
Source File: VertxNubes.java From nubes with Apache License 2.0 | 5 votes |
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(); }; }
Example #28
Source File: SessionHolderMapCleaningTest.java From vertx-cassandra-client with Apache License 2.0 | 5 votes |
@Test public void testMapCleaned() { LocalMap<String, SessionHolder> holders = vertx.sharedData().getLocalMap(CassandraClientImpl.HOLDERS_LOCAL_MAP_NAME); int instances = 5; vertx.deployVerticle(() -> new SampleVerticle(), new DeploymentOptions().setInstances(instances), onSuccess(id -> { assertEquals(instances, holders.get(CLIENT_NAME).refCount); vertx.undeploy(id, onSuccess(v -> { assertEquals(0, holders.size()); testComplete(); })); })); await(); }
Example #29
Source File: VertxNubes.java From nubes with Apache License 2.0 | 5 votes |
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); }
Example #30
Source File: MailClientImpl.java From vertx-mail-client with Apache License 2.0 | 5 votes |
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; } }