Java Code Examples for io.vertx.core.shareddata.LocalMap#get()

The following examples show how to use io.vertx.core.shareddata.LocalMap#get() . 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: RateLimitationHandler.java    From nubes with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: WSLocalHandler.java    From vert.x-microservice with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: MailClientImpl.java    From vertx-mail-client with Apache License 2.0 5 votes vote down vote up
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;
  }
}
 
Example 4
Source File: VertxNubes.java    From nubes with Apache License 2.0 5 votes vote down vote up
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 5
Source File: WSLocalHandler.java    From vert.x-microservice with Apache License 2.0 5 votes vote down vote up
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 6
Source File: MongoClientImpl.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
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 7
Source File: WriteHandler.java    From nassh-relay with GNU General Public License v2.0 5 votes vote down vote up
@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 8
Source File: ReadHandler.java    From nassh-relay with GNU General Public License v2.0 5 votes vote down vote up
@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 9
Source File: MQTTStoreManagerAsync.java    From vertx-mqtt-broker with Apache License 2.0 5 votes vote down vote up
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 10
Source File: ConnectHandler.java    From nassh-relay with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handle(final ServerWebSocket ws) {
    ws.setWriteQueueMaxSize(Constants.QUEUEMAXSIZE);
    final MultiMap params = params(ws.uri());
    if (ws.path().equals("/connect") && params.contains("sid") && params.contains("ack") && params.contains("pos")) {
        final UUID sid = UUID.fromString(params.get("sid"));
        final LocalMap<String, Session> map = vertx.sharedData().getLocalMap(Constants.SESSIONS);
        final Session session = map.get(sid.toString());
        if (session == null || !session.isActive()) {
            ws.reject();
            return;
        }
        session.setRead_count(Integer.parseInt(params.get("ack")));
        session.setWrite_count(Integer.parseInt(params.get("pos")));
        final TransferObserver observer = new TransferObserver(session, ws);
        final TransferQueue queue;
        try {
            queue = QueueFactory.getQueue(sid.toString());
        } catch (final NoSuchQueueException ex) {
            logger.warn(ex, ex.fillInStackTrace());
            ws.reject();
            ws.close();
            return;
        }
        if (queue.countObservers() == 0) {
            queue.addObserver(observer);
        }
        final Buffer buffer = queue.peek();
        if (buffer != null) {
            if (!ws.writeQueueFull()) {
                final Buffer ackbuffer = Buffer.buffer();
                ackbuffer.setInt(0, session.getWrite_count());
                ackbuffer.setBuffer(4, buffer);
                ws.write(ackbuffer);
                queue.remove(buffer);
            } else {
                ws.pause();
            }
        }
        logger.debug("connected");
        ws.drainHandler(v -> ws.resume());
        ws.handler(data -> {
            if (!session.isActive()) {
                ws.close();
                return;
            }
            if (data.length() < 4) {
                logger.warn("wrong frame format");
                return;
            }
            session.setWrite_count(session.getWrite_count() + data.length() - 4);
            vertx.eventBus().publish(session.getHandler(), data.getBuffer(4, data.length()));
        });
        ws.closeHandler(v -> {
            queue.deleteObservers();
            logger.debug("disconnected");
        });
    } else {
        ws.reject();
    }
}