List of usage examples for io.vertx.core.json JsonObject getLong
public Long getLong(String key, Long def)
From source file:com.groupon.vertx.memcache.MemcacheClusterConfig.java
License:Apache License
public MemcacheClusterConfig(JsonObject jsonConfig) { if (jsonConfig == null) { log.error("initialize", "exception", "noConfigFound"); throw new MemcacheException("No Memcache cluster config found"); }//from w w w . j a v a2s. c o m this.eventBusAddressPrefix = jsonConfig.getString(EVENT_BUS_ADDRESS_PREFIX_KEY); this.retryInterval = jsonConfig.getLong(RETRY_INTERVAL, MemcacheConfig.DEFAULT_RETRY_INTERVAL); JsonObject clusters = jsonConfig.getJsonObject(CLUSTERS_KEY, new JsonObject()); if (eventBusAddressPrefix != null && !eventBusAddressPrefix.isEmpty() && clusters.size() > 0) { for (String clusterKey : clusters.fieldNames()) { JsonObject clusterConfig = clusters.getJsonObject(clusterKey, new JsonObject()).copy(); clusterConfig.put(EVENT_BUS_ADDRESS_KEY, eventBusAddressPrefix); clusterConfig.put(RETRY_INTERVAL, retryInterval); clusterMap.put(clusterKey, new MemcacheConfig(clusterConfig)); } } else { log.error("initialize", "exception", "invalidConfigFound", new String[] { "config" }, jsonConfig.encode()); throw new MemcacheException("Invalid Memcache config defined"); } log.info("initialize", "success", new String[] { "eventBusAddressPrefix", "clusters" }, eventBusAddressPrefix, clusterMap.size()); }
From source file:com.groupon.vertx.memcache.MemcacheConfig.java
License:Apache License
public MemcacheConfig(JsonObject jsonConfig) { if (jsonConfig == null) { log.error("initialize", "exception", "noConfigFound"); throw new MemcacheException("No Memcache config found"); }/*from ww w . jav a2 s . c o m*/ if (jsonConfig.getJsonArray(SERVERS_KEY) != null && jsonConfig.getString(EVENT_BUS_ADDRESS_KEY) != null && !jsonConfig.getString(EVENT_BUS_ADDRESS_KEY).isEmpty()) { this.servers.addAll(processServers(jsonConfig.getJsonArray(SERVERS_KEY))); this.eventBusAddress = jsonConfig.getString(EVENT_BUS_ADDRESS_KEY); this.namespace = jsonConfig.getString(NAMESPACE_KEY); this.pointsPerServer = jsonConfig.getInteger(POINTS_PER_SERVER, DEFAULT_POINTS_PER_SERVER); this.retryInterval = jsonConfig.getLong(RETRY_INTERVAL, DEFAULT_RETRY_INTERVAL); final HashAlgorithm defaultHashAlgorithm = HashAlgorithm.FNV1_32_HASH; String algorithmStr = jsonConfig.getString(ALGORITHM_KEY, defaultHashAlgorithm.name()); this.algorithm = algorithmStr == null ? defaultHashAlgorithm : HashAlgorithm.valueOf(algorithmStr); final ContinuumType defaultContinuumType = ContinuumType.KETAMA; String continuumStr = jsonConfig.getString(CONTINUUM_KEY, defaultContinuumType.name()); this.continuum = continuumStr == null ? defaultContinuumType : ContinuumType.valueOf(continuumStr); } else { log.error("initialize", "exception", "invalidConfigFound", new String[] { "config" }, jsonConfig.encode()); throw new MemcacheException("Invalid Memcache config defined"); } log.info("initialize", "success", new String[] { "eventBusAddress", "namespace", "servers", "algorithm" }, eventBusAddress, namespace, servers.size(), algorithm); }
From source file:com.groupon.vertx.redis.RedisConfig.java
License:Apache License
public RedisConfig(JsonObject redisConfigObj) throws Exception { this.host = redisConfigObj.getString(HOST_KEY); this.port = redisConfigObj.getInteger(PORT_KEY, port); this.eventBusAddress = redisConfigObj.getString(EVENT_BUS_ADDRESS_KEY); this.retryInterval = redisConfigObj.getLong(RETRY_INTERVAL_KEY, retryInterval); this.replyTimeout = redisConfigObj.getLong(REPLY_TIMEOUT_KEY, replyTimeout); if (host == null || host.isEmpty() || eventBusAddress == null || eventBusAddress.isEmpty()) { throw new Exception("Invalid Redis config."); }//from w w w. j av a 2 s . co m }
From source file:com.hubrick.vertx.kafka.consumer.KafkaConsumerVerticle.java
License:Apache License
@Override public void start() throws Exception { super.start(); final JsonObject config = vertx.getOrCreateContext().config(); vertxAddress = getMandatoryStringConfig(config, KafkaConsumerProperties.KEY_VERTX_ADDRESS); configuration = KafkaConsumerConfiguration.create( getMandatoryStringConfig(config, KafkaConsumerProperties.KEY_GROUP_ID), getMandatoryStringConfig(config, KafkaConsumerProperties.KEY_KAFKA_TOPIC), getMandatoryStringConfig(config, KafkaConsumerProperties.KEY_ZOOKEEPER), config.getString(KafkaConsumerProperties.KEY_OFFSET_RESET, "largest"), config.getInteger(KafkaConsumerProperties.KEY_ZOOKEPER_TIMEOUT_MS, 100000), config.getInteger(KafkaConsumerProperties.KEY_MAX_UNACKNOWLEDGED, 100), config.getLong(KafkaConsumerProperties.KEY_MAX_UNCOMMITTED_OFFSETS, 1000L), config.getLong(KafkaConsumerProperties.KEY_ACK_TIMEOUT_SECONDS, 600L), config.getLong(KafkaConsumerProperties.KEY_COMMIT_TIMEOUT_MS, 5 * 60 * 1000L), config.getInteger(KafkaConsumerProperties.KEY_MAX_RETRIES, Integer.MAX_VALUE), config.getInteger(KafkaConsumerProperties.KEY_INITIAL_RETRY_DELAY_SECONDS, 1), config.getInteger(KafkaConsumerProperties.KEY_MAX_RETRY_DELAY_SECONDS, 10), config.getLong(KafkaConsumerProperties.EVENT_BUS_SEND_TIMEOUT, DeliveryOptions.DEFAULT_TIMEOUT)); consumer = KafkaConsumer.create(vertx, configuration, this::handler); consumer.start();//from w ww . j a v a 2 s . co m }
From source file:com.hubrick.vertx.rest.RestClientOptions.java
License:Apache License
public RestClientOptions(final JsonObject json) { super(json);//from ww w. j a v a2s. c om final JsonObject jsonObjectGlobalRequestCacheOptions = json.getJsonObject("globalRequestCacheOptions"); if (jsonObjectGlobalRequestCacheOptions != null) { final RequestCacheOptions requestCacheOptions = new RequestCacheOptions(); final Integer ttlInMillis = jsonObjectGlobalRequestCacheOptions.getInteger("ttlInMillis"); final Boolean evictBefore = jsonObjectGlobalRequestCacheOptions.getBoolean("evictBefore"); if (jsonObjectGlobalRequestCacheOptions.getJsonArray("cachedStatusCodes") != null) { final Set<Integer> cachedStatusCodes = jsonObjectGlobalRequestCacheOptions .getJsonArray("cachedStatusCodes").stream().map(e -> (Integer) e) .collect(Collectors.toSet()); requestCacheOptions.withCachedStatusCodes(cachedStatusCodes); } if (ttlInMillis != null) { requestCacheOptions.withExpiresAfterWriteMillis(ttlInMillis); } if (evictBefore != null) { requestCacheOptions.withEvictBefore(evictBefore); } globalRequestCacheOptions = requestCacheOptions; } globalHeaders = new CaseInsensitiveHeaders(); globalRequestTimeoutInMillis = json.getLong("globalRequestTimeoutInMillis", DEFAULT_GLOBAL_REQUEST_TIMEOUT_IN_MILLIS); }
From source file:fr.wseduc.rack.controllers.RackController.java
License:Open Source License
/** * Post a new document to other people's rack folder. * @param request Client request containing a list of user ids belonging to the receivers and the file. *//*from w ww. j a v a 2s. co m*/ @Post("") @SecuredAction(send) public void postRack(final HttpServerRequest request) { UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() { @Override public void handle(final UserInfos userInfos) { if (userInfos == null) { badRequest(request); return; } request.setExpectMultipart(true); final Buffer fileBuffer = Buffer.buffer(); final JsonObject metadata = new JsonObject(); /* Upload file */ request.uploadHandler(getUploadHandler(fileBuffer, metadata, request)); /* After upload */ request.endHandler(new Handler<Void>() { @Override public void handle(Void v) { String users = request.formAttributes().get("users"); if (users == null) { badRequest(request); return; } String[] userIds = users.split(","); final AtomicInteger countdown = new AtomicInteger(userIds.length); final AtomicInteger success = new AtomicInteger(0); final AtomicInteger failure = new AtomicInteger(0); /* Final handler - called after each attempt */ final Handler<Boolean> finalHandler = new Handler<Boolean>() { @Override public void handle(Boolean event) { if (event == null || !event) failure.addAndGet(1); else success.addAndGet(1); if (countdown.decrementAndGet() == 0) { JsonObject result = new JsonObject(); result.put("success", success.get()); result.put("failure", failure.get()); renderJson(request, result); } } }; for (final String to : userIds) { /* Query user and check existence */ String query = "MATCH (n:User) " + "WHERE n.id = {id} " + "RETURN count(n) as nb, n.displayName as username"; Map<String, Object> params = new HashMap<>(); params.put("id", to); Handler<Message<JsonObject>> existenceHandler = new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> res) { JsonArray result = res.body().getJsonArray("result"); if (!"ok".equals(res.body().getString("status")) || 1 != result.size() || 1 != result.getJsonObject(0).getInteger("nb")) { finalHandler.handle(false); return; } /* Pre write rack document fields */ final JsonObject doc = new JsonObject(); doc.put("to", to); doc.put("toName", result.getJsonObject(0).getString("username")); doc.put("from", userInfos.getUserId()); doc.put("fromName", userInfos.getUsername()); String now = dateFormat.format(new Date()); doc.put("sent", now); /* Rack collection saving */ final Handler<JsonObject> rackSaveHandler = new Handler<JsonObject>() { @Override public void handle(JsonObject uploaded) { if (uploaded == null || !"ok".equals(uploaded.getString("status"))) { finalHandler.handle(false); } else { addAfterUpload(uploaded.put("metadata", metadata), doc, request.params().get("name"), request.params().get("application"), request.params().getAll("thumbnail"), new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> res) { if ("ok".equals(res.body().getString("status"))) { JsonObject params = new JsonObject() .put("uri", "/userbook/annuaire#" + doc.getString("from")) .put("resourceUri", pathPrefix) .put("username", doc.getString("fromName")) .put("documentName", doc.getString("name")); List<String> receivers = new ArrayList<>(); receivers.add(doc.getString("to")); JsonObject pushNotif = new JsonObject() .put("title", "rack.push.notif.rack-post") .put("body", I18n.getInstance().translate( "rack.push.notif.rack-post.body", getHost(request), I18n.acceptLanguage( request), doc.getString( "fromName"), doc.getString("name"))); params.put("pushNotif", pushNotif); timelineHelper.notifyTimeline(request, "rack.rack-post", userInfos, receivers, userInfos.getUserId() + System.currentTimeMillis() + "postrack", null, params, true); finalHandler.handle(true); } else { finalHandler.handle(false); } } }); } } }; /* Get user quota & check */ getUserQuota(to, new Handler<JsonObject>() { @Override public void handle(JsonObject j) { if (j == null || "error".equals(j.getString("status"))) { finalHandler.handle(false); return; } long emptySize = 0l; long quota = j.getLong("quota", 0l); long storage = j.getLong("storage", 0l); emptySize = quota - storage; if (emptySize < metadata.getLong("size", 0l)) { finalHandler.handle(false); return; } //Save file RackController.this.storage.writeBuffer(fileBuffer, metadata.getString("content-type"), metadata.getString("name"), rackSaveHandler); } }); } }; Neo4j.getInstance().execute(query, params, existenceHandler); } } }); } }); }
From source file:fr.wseduc.rack.controllers.RackController.java
License:Open Source License
private Handler<HttpServerFileUpload> getUploadHandler(final Buffer fileBuffer, final JsonObject metadata, final HttpServerRequest request) { return new Handler<HttpServerFileUpload>() { @Override//from w w w.j av a 2 s . c om public void handle(final HttpServerFileUpload upload) { upload.handler(new Handler<Buffer>() { @Override public void handle(Buffer data) { fileBuffer.appendBuffer(data); } }); upload.endHandler(new Handler<Void>() { @Override public void handle(Void v) { metadata.put("name", upload.name()); metadata.put("filename", upload.filename()); metadata.put("content-type", upload.contentType()); metadata.put("content-transfer-encoding", upload.contentTransferEncoding()); metadata.put("charset", upload.charset()); metadata.put("size", upload.size()); if (metadata.getLong("size", 0l).equals(0l)) { metadata.put("size", fileBuffer.length()); } if (storage.getValidator() != null) { request.pause(); storage.getValidator().process(metadata, new JsonObject(), new Handler<AsyncResult<Void>>() { @Override public void handle(AsyncResult<Void> voidAsyncResult) { if (voidAsyncResult.succeeded()) { request.resume(); } else { badRequest(request, voidAsyncResult.cause().getMessage()); return; } } }); } } }); } }; }
From source file:fr.wseduc.rack.controllers.RackController.java
License:Open Source License
private void emptySize(final UserInfos userInfos, final Handler<Long> emptySizeHandler) { try {/*from www. ja v a 2 s . co m*/ long quota = Long.valueOf(userInfos.getAttribute("quota").toString()); long storage = Long.valueOf(userInfos.getAttribute("storage").toString()); emptySizeHandler.handle(quota - storage); } catch (Exception e) { getUserQuota(userInfos.getUserId(), new Handler<JsonObject>() { @Override public void handle(JsonObject j) { long quota = j.getLong("quota", 0l); long storage = j.getLong("storage", 0l); for (String attr : j.fieldNames()) { UserUtils.addSessionAttribute(eb, userInfos.getUserId(), attr, j.getLong(attr), null); } emptySizeHandler.handle(quota - storage); } }); } }
From source file:fr.wseduc.rack.controllers.RackController.java
License:Open Source License
private void copyFiles(final HttpServerRequest request, final JsonArray idsArray, final String folder, final UserInfos user, final String destinationCollection) { String criteria = "{ \"_id\" : { \"$in\" : " + idsArray.encode() + "}"; criteria += ", \"to\" : \"" + user.getUserId() + "\" }"; mongo.find(collection, new JsonObject(criteria), new Handler<Message<JsonObject>>() { private void persist(final JsonArray insert, int remains) { if (remains == 0) { mongo.insert(destinationCollection, insert, new Handler<Message<JsonObject>>() { @Override/*ww w .j a v a 2 s . c o m*/ public void handle(Message<JsonObject> inserted) { if ("ok".equals(inserted.body().getString("status"))) { /* Increment quota */ long totalSize = 0l; for (Object insertion : insert) { JsonObject added = (JsonObject) insertion; totalSize += added.getJsonObject("metadata", new JsonObject()).getLong("size", 0l); } updateUserQuota(user.getUserId(), totalSize); renderJson(request, inserted.body()); } else { renderError(request, inserted.body()); } } }); } } @Override public void handle(Message<JsonObject> r) { JsonObject src = r.body(); if ("ok".equals(src.getString("status")) && src.getJsonArray("results") != null) { final JsonArray origs = src.getJsonArray("results"); final JsonArray insert = new JsonArray(); final AtomicInteger number = new AtomicInteger(origs.size()); emptySize(user, new Handler<Long>() { @Override public void handle(Long emptySize) { long size = 0; /* Get total file size */ for (Object o : origs) { if (!(o instanceof JsonObject)) continue; JsonObject metadata = ((JsonObject) o).getJsonObject("metadata"); if (metadata != null) { size += metadata.getLong("size", 0l); } } /* If total file size is too big (> quota left) */ if (size > emptySize) { badRequest(request, "files.too.large"); return; } /* Process */ for (Object o : origs) { JsonObject orig = (JsonObject) o; final JsonObject dest = orig.copy(); String now = MongoDb.formatDate(new Date()); dest.remove("_id"); dest.remove("protected"); dest.remove("comments"); dest.put("application", WORKSPACE_NAME); dest.put("owner", user.getUserId()); dest.put("ownerName", dest.getString("toName")); dest.remove("to"); dest.remove("from"); dest.remove("toName"); dest.remove("fromName"); dest.put("created", now); dest.put("modified", now); if (folder != null && !folder.trim().isEmpty()) { dest.put("folder", folder); } else { dest.remove("folder"); } insert.add(dest); final String filePath = orig.getString("file"); if (folder != null && !folder.trim().isEmpty()) { //If the document has a new parent folder, replicate sharing rights String parentName, parentFolder; if (folder.lastIndexOf('_') < 0) { parentName = folder; parentFolder = folder; } else if (filePath != null) { String[] splittedPath = folder.split("_"); parentName = splittedPath[splittedPath.length - 1]; parentFolder = folder; } else { String[] splittedPath = folder.split("_"); parentName = splittedPath[splittedPath.length - 2]; parentFolder = folder.substring(0, folder.lastIndexOf("_")); } QueryBuilder parentFolderQuery = QueryBuilder.start("owner") .is(user.getUserId()).and("folder").is(parentFolder).and("name") .is(parentName); mongo.findOne(collection, MongoQueryBuilder.build(parentFolderQuery), new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> event) { if ("ok".equals(event.body().getString("status"))) { JsonObject parent = event.body().getJsonObject("result"); if (parent != null && parent.getJsonArray("shared") != null && parent.getJsonArray("shared").size() > 0) dest.put("shared", parent.getJsonArray("shared")); if (filePath != null) { storage.copyFile(filePath, new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if (event != null && "ok" .equals(event.getString("status"))) { dest.put("file", event.getString("_id")); persist(insert, number.decrementAndGet()); } } }); } else { persist(insert, number.decrementAndGet()); } } else { renderJson(request, event.body(), 404); } } }); } else if (filePath != null) { storage.copyFile(filePath, new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if (event != null && "ok".equals(event.getString("status"))) { dest.put("file", event.getString("_id")); persist(insert, number.decrementAndGet()); } } }); } else { persist(insert, number.decrementAndGet()); } } } }); } else { notFound(request, src.toString()); } } }); }
From source file:org.entcore.auth.services.impl.DefaultOpendIdConnectService.java
License:Open Source License
@Override public void executeFederate(JsonObject payload, Handler<Either<String, Object>> handler) { if (iss.equals(payload.getString("iss")) && payload.getLong("exp", 0l) > (System.currentTimeMillis() / 1000)) { AbstractSSOProvider.executeFederateQuery("MATCH (u:User { externalId : {sub}}) ", payload, null, setFederated, Neo4j.getInstance(), handler); } else {/*from w w w. j a v a 2s . c o m*/ handler.handle(new Either.Left<String, Object>("invalid.openid.payload")); } }