List of usage examples for io.vertx.core.json JsonObject getBoolean
public Boolean getBoolean(String key)
From source file:com.hpe.sw.cms.verticle.MongoStoreVerticle.java
License:Apache License
@Override public void start() throws Exception { super.start(); client = MongoClient.createShared(vertx, config().getJsonObject("mongo")); vertx.eventBus().consumer(Events.GET_IMAGES.name(), msg -> { JsonObject param = (JsonObject) msg.body(); JsonObject query = new JsonObject(); if (param != null && param.getString("timestamp") != null) { Long timestamp = Long.parseLong(param.getString("timestamp")); query.put(Image.TIMESTAMP, new JsonObject().put("$gte", timestamp)); } else if (param != null && param.getString("imageid") != null) { query.put(Image.IMAGE_ID, param.getString(Image.IMAGE_ID)); }//from w ww. j a va2s. c o m if (!query.containsKey(Image.IMAGE_ID) && (param == null || param.getString("include") == null || !"all".equals(param.getString("include")))) { query.put(Image.IMAGE_ID, new JsonObject().put("$exists", true)); } JsonArray images = new JsonArray(); client.find("images", query, res -> { if (res.succeeded()) { List<JsonObject> result = res.result(); for (JsonObject dbImage : result) { images.add(Image.cloneImage(dbImage)); } msg.reply(images); } }); }); vertx.eventBus().consumer(Events.DOWNLOAD_FILE.name(), msg -> { JsonObject query = (JsonObject) msg.body(); LOG.debug("DOWNLOAD_FILE query is " + query); client.find("images", query, res -> { if (res.succeeded()) { List<JsonObject> result = res.result(); LOG.debug("DOWNLOAD_FILE result is " + result.size()); if (result.size() > 0) { msg.reply(result.get(0)); } else { msg.reply(null); } } }); }); vertx.eventBus().consumer(Events.IMAGES_UPDATED.name(), msg -> { JsonArray updates = new JsonArray(); JsonObject query = new JsonObject(); query.put(Image.IS_SCANNED, false); int fetchSize = Integer.valueOf(String.valueOf(msg.body())); FindOptions options = new FindOptions(); JsonObject sort = new JsonObject(); sort.put(Image.TIMESTAMP, -1); options.setLimit(fetchSize).setSort(sort); client.findWithOptions("images", query, options, res -> { if (res.succeeded()) { List<JsonObject> result = res.result(); for (JsonObject update : result) { updates.add(update); LOG.debug("get image from DB :" + Image.getImageKey(update)); } LOG.debug("IMAGES_UPDATED reply updates size " + updates.size()); msg.reply(updates); } }); }); vertx.eventBus().consumer(Events.SCANFILE_UPLOADED.name(), msg -> { JsonObject upFile = (JsonObject) msg.body(); JsonObject query = new JsonObject(); query.put(Image.HOST, upFile.getString(Image.HOST)).put(Image.NAME, upFile.getString(Image.NAME)) .put(Image.TAG, upFile.getString(Image.TAG)); client.find("images", query, res -> { if (res.succeeded()) { List<JsonObject> result = res.result(); if (result.size() == 0) { LOG.error("no mapped image in DB for " + Image.getImageKey(upFile)); return; } for (JsonObject dbImage : result) { if (upFile.getBoolean("isScanFailed")) { //Failed in scanning. LOG.info("store failed scan to DB " + Image.getImageKey(upFile)); dbImage.put(Image.IS_SCANNED, true); dbImage.put(Image.IS_SCANNED_FAILED, true); } else { //successfully in scanning. LOG.info("store scanfile to DB " + Image.getImageKey(upFile)); dbImage.put(Image.IS_SCANNED, true); dbImage.put(Image.IS_SCANNED_FAILED, false); dbImage.put(Image.IMAGE_ID, upFile.getString(Image.IMAGE_ID)); dbImage.put(Image.SCANNED_FILE, upFile.getBinary(Image.SCANNED_FILE)); } client.save("images", dbImage, h -> { if (h.succeeded()) { LOG.info("SCANFILE_UPLOADED:Image " + Image.getImageKey(dbImage) + " updated !"); } else { h.cause().printStackTrace(); } }); } } }); }); vertx.eventBus().consumer(Events.ENRICHFILE_UPLOADED.name(), msg -> { JsonArray upFiles = (JsonArray) msg.body(); for (Object upFileObj : upFiles) { JsonObject upFile = (JsonObject) upFileObj; if (upFile.getBinary("enrichedFile") == null) { LOG.info("enrichedFile is emptry for " + upFile.getString("imageid")); continue; } LOG.info("store enrichfile to DB " + upFile.getString("imageid")); JsonObject query = new JsonObject(); query.put(Image.IMAGE_ID, upFile.getString(Image.IMAGE_ID)); client.find("images", query, res -> { if (res.succeeded()) { List<JsonObject> result = res.result(); for (JsonObject dbImage : result) { dbImage.put(Image.IS_ENRICHED, true); dbImage.put(Image.ENRICHED_FILE, upFile.getBinary(Image.ENRICHED_FILE)); client.save("images", dbImage, h -> { if (h.succeeded()) { LOG.info("ENRICHFILE_UPLOADED:Image " + Image.getImageKey(dbImage) + " updated !"); } else { h.cause().printStackTrace(); } }); } } }); } }); vertx.eventBus().consumer(Events.IMAGE_TO_ENRICH.name(), msg -> { JsonObject query = new JsonObject(); query.put(Image.IS_SCANNED, true).put(Image.IS_SCANNED_FAILED, false).put(Image.IS_ENRICHED, false); client.find("images", query, res -> { if (res.succeeded()) { List<JsonObject> result = res.result(); msg.reply(new JsonArray(result)); } }); }); vertx.eventBus().consumer(Events.NEW_IMAGE.name(), msg -> { //to store events in JsonObject obj = (JsonObject) msg.body(); JsonObject query = new JsonObject(); query.put(Image.HOST, obj.getString(Image.HOST)).put(Image.NAME, obj.getString(Image.NAME)) .put(Image.TAG, obj.getString(Image.TAG)); client.find("images", query, res -> { if (res.succeeded()) { List<JsonObject> result = res.result(); if (result.isEmpty()) { //inserted client.insert("images", obj, h -> { if (h.succeeded()) { LOG.info("IMAGES_COMMING :Image " + Image.getImageKey(obj) + " inserted !"); } else { h.cause().printStackTrace(); } }); } else if (result.size() == 1) { JsonObject toUpdate = result.get(0); if (!obj.getString(Image.SIGN).equals(toUpdate.getString(Image.SIGN))) { toUpdate.put(Image.TIMESTAMP, obj.getLong(Image.TIMESTAMP)) .put(Image.SIGN, obj.getString(Image.SIGN)) .put(Image.IS_SCANNED, obj.getBoolean(Image.IS_SCANNED)) .put(Image.IS_ENRICHED, obj.getBoolean(Image.IS_ENRICHED)); //saved client.save("images", toUpdate, h -> { if (h.succeeded()) { LOG.info("IMAGES_COMMING :Image " + Image.getImageKey(obj) + " updated !"); } else { h.cause().printStackTrace(); } }); } else { LOG.info("IMAGES_COMMING :Image " + Image.getImageKey(obj) + " has the same sign with the coming image, so will not update to DB !"); } } else { throw new RuntimeException( "IMAGES_COMMING :Found " + result.size() + " image for " + Image.getImageKey(obj)); } } }); }); }
From source file:com.hubrick.vertx.rest.RestClientOptions.java
License:Apache License
public RestClientOptions(final JsonObject json) { super(json);//from w ww . j a va2s.co m 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:com.hubrick.vertx.s3.client.S3ClientOptions.java
License:Apache License
public S3ClientOptions(final JsonObject json) { super(json);/* w w w . j a v a 2s . com*/ setSignPayload(json.getBoolean("signPayload")); setAwsAccessKey(json.getString("awsAccessKey")); setAwsSecretKey(json.getString("awsSecretKey")); setAwsRegion(json.getString("awsRegion")); setAwsServiceName(json.getString("awsServiceName")); setGlobalTimeoutMs(json.getLong("globalTimeoutMs")); setHostnameOverride(json.getString("hostnameOverride")); }
From source file:io.engagingspaces.graphql.schema.SchemaDefinitionOptions.java
License:Open Source License
/** * Creates a {@link SchemaDefinitionOptions} from its json representation. * * @param json the serialized options instance */// ww w. jav a 2 s .co m public SchemaDefinitionOptions(JsonObject json) { Objects.requireNonNull(json, "Schema definition options json cannot be null"); this.schemaName = json.getString("schemaName"); this.deliveryOptions = new DeliveryOptions(json.getJsonObject("deliveryOptions")); this.proxyType = Enum.valueOf(SchemaProxyType.class, json.getString("proxyType")); this.isInternal = json.getBoolean("isInternal"); }
From source file:io.engagingspaces.vertx.dataloader.DataLoaderOptions.java
License:Open Source License
/** * Creates a new data loader options with values provided as JSON. * <p>/*from ww w. j av a 2 s . c om*/ * Note that only json-serializable options can be set with this constructor. Others, * like {@link DataLoaderOptions#cacheKeyFunction} must be set manually after creation. * <p> * Note also that this makes it incompatible with true Vert.x data objects, so beware if you use it that way. * * @param json the serialized data loader options to set */ public DataLoaderOptions(JsonObject json) { Objects.requireNonNull(json, "Json cannot be null"); this.batchingEnabled = json.getBoolean("batchingEnabled"); this.batchingEnabled = json.getBoolean("cachingEnabled"); }
From source file:io.flowly.auth.manager.GroupManager.java
License:Open Source License
@Override public Handler<Message<JsonObject>> getHandler() { return message -> { JsonObject args = message.body(); message.reply(get(args.getString(Group.GROUP_ID), args.getBoolean("includeDirectMemberships"), args.getBoolean("includeEffectiveMemberships"), args.getBoolean("includeDirectMembers"), args.getBoolean("includeEffectiveUsers"), args.getBoolean("includeDirectPermissions"))); };/*w w w . j av a2 s .c om*/ }
From source file:io.flowly.auth.manager.UserManager.java
License:Open Source License
@Override public Handler<Message<JsonObject>> getHandler() { return message -> { JsonObject args = message.body(); message.reply(get(args.getString(User.USER_ID), args.getBoolean("includeDirectMemberships"), args.getBoolean("includeEffectiveMemberships"), args.getBoolean("includeDirectPermissions"), args.getBoolean("includeEffectivePermissions"))); };// w w w . ja v a 2 s.c o m }
From source file:io.flowly.auth.router.UserRouter.java
License:Open Source License
private JsonObject getAuthenticatedUser(JsonObject user) { if (!user.getBoolean(User.AUTHENTICATED)) { return user; }//w w w . j ava 2s.c om JsonObject claims = new JsonObject().put("sub", user.getString(User.USER_ID)).put("permissions", user.remove(Permission.EFFECTIVE_PERMISSIONS)); JsonArray directMemberships = (JsonArray) user.remove(User.DIRECT_MEMBERSHIPS); if (directMemberships != null) { claims.put(ObjectKeys.GURU, directMemberships.stream().anyMatch(m -> { JsonObject group = (JsonObject) m; String groupId = group.getString(Group.GROUP_ID); return groupId != null && groupId.equals(ObjectKeys.ADMIN_GROUP_ID); })); } return user.put("token", authProvider.generateToken(claims, new JWTOptions())); }
From source file:io.gravitee.am.identityprovider.github.authentication.GithubAuthenticationProvider.java
License:Apache License
private User createUser(JsonObject jsonObject) { User user = new DefaultUser(jsonObject.getString(GithubUser.LOGIN)); // set additional information Map<String, Object> additionalInformation = new HashMap<>(); additionalInformation.put("sub", jsonObject.getValue(GithubUser.LOGIN)); additionalInformation.put(GithubUser.AVATAR_URL, jsonObject.getValue(GithubUser.AVATAR_URL)); additionalInformation.put(GithubUser.GRAVATAR_ID, jsonObject.getValue(GithubUser.GRAVATAR_ID)); additionalInformation.put(GithubUser.URL, jsonObject.getValue(GithubUser.URL)); additionalInformation.put(GithubUser.HTML_URL, jsonObject.getValue(GithubUser.HTML_URL)); additionalInformation.put(GithubUser.FOLLOWERS_URL, jsonObject.getValue(GithubUser.FOLLOWERS_URL)); additionalInformation.put(GithubUser.FOLLOWING_URL, jsonObject.getValue(GithubUser.FOLLOWING_URL)); additionalInformation.put(GithubUser.GISTS_URL, jsonObject.getValue(GithubUser.GISTS_URL)); additionalInformation.put(GithubUser.STARRED_URL, jsonObject.getValue(GithubUser.STARRED_URL)); additionalInformation.put(GithubUser.SUBSCRIPTIONS_URL, jsonObject.getValue(GithubUser.SUBSCRIPTIONS_URL)); additionalInformation.put(GithubUser.ORGANIZATIONS_URL, jsonObject.getValue(GithubUser.ORGANIZATIONS_URL)); additionalInformation.put(GithubUser.REPOS_URL, jsonObject.getValue(GithubUser.REPOS_URL)); additionalInformation.put(GithubUser.EVENTS_URL, jsonObject.getValue(GithubUser.EVENTS_URL)); additionalInformation.put(GithubUser.RECEIVED_EVENTS_URL, jsonObject.getValue(GithubUser.RECEIVED_EVENTS_URL)); additionalInformation.put(GithubUser.SITE_ADMIN, jsonObject.getBoolean(GithubUser.SITE_ADMIN)); additionalInformation.put(GithubUser.NAME, jsonObject.getValue(GithubUser.NAME)); additionalInformation.put(GithubUser.COMPANY, jsonObject.getValue(GithubUser.COMPANY)); additionalInformation.put(GithubUser.LOCATION, jsonObject.getValue(GithubUser.LOCATION)); additionalInformation.put(GithubUser.EMAIL, jsonObject.getValue(GithubUser.EMAIL)); additionalInformation.put(GithubUser.PUBLIC_REPOS, jsonObject.getValue(GithubUser.PUBLIC_REPOS)); additionalInformation.put(GithubUser.PUBLIC_GISTS, jsonObject.getValue(GithubUser.PUBLIC_GISTS)); additionalInformation.put(GithubUser.FOLLOWERS, jsonObject.getValue(GithubUser.FOLLOWERS)); additionalInformation.put(GithubUser.FOLLOWING, jsonObject.getValue(GithubUser.FOLLOWING)); additionalInformation.put(GithubUser.LOCATION, jsonObject.getValue(GithubUser.LOCATION)); additionalInformation.put(GithubUser.EMAIL, jsonObject.getValue(GithubUser.EMAIL)); ((DefaultUser) user).setAdditonalInformation(additionalInformation); return user;/* w ww .j ava 2 s .co m*/ }
From source file:io.nitor.api.backend.lambda.LambdaHandler.java
License:Apache License
@Override public void handle(RoutingContext ctx) { HttpServerRequest sreq = ctx.request(); final String path = normalizePath(sreq.path(), routeLength); if (path == null) { ctx.response().setStatusCode(NOT_FOUND.code()).end(); return;/* w w w . j av a 2s .c om*/ } HttpServerResponse sres = ctx.response(); PathMatchResult<Entry<String, String>> matchRes = pathTemplateMatcher.match(path); final String lambdaFunction, qualifier; if (matchRes == null) { logger.error("No matching path template"); sres.setStatusCode(BAD_GATEWAY.code()); return; } else { lambdaFunction = matchRes.getValue().getKey(); qualifier = matchRes.getValue().getValue(); } sreq.bodyHandler(new Handler<Buffer>() { @Override public void handle(Buffer event) { byte[] body = event.getBytes(); APIGatewayProxyRequestEvent reqObj = new APIGatewayProxyRequestEvent(); /* * Handle body */ String bodyObjStr = null; boolean isBase64Encoded = true; if (body != null && body.length > 0) { String ct = sreq.getHeader("content-type").toLowerCase(); if (ct.startsWith("text/") || ct.startsWith("application/json") || (ct.indexOf("charset=") > 0)) { String charset = "utf-8"; if (ct.indexOf("charset=") > 0) { charset = getCharsetFromContentType(ct); } try { bodyObjStr = Charset.forName(charset).newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(body)) .toString(); isBase64Encoded = false; } catch (CharacterCodingException e) { logger.error("Decoding body failed", e); } } if (bodyObjStr == null) { bodyObjStr = Base64.getEncoder().encodeToString(body); } reqObj = reqObj.withBody(bodyObjStr).withIsBase64Encoded(isBase64Encoded); } Map<String, List<String>> headerMultivalue = sreq.headers().entries().stream() .collect(toMap(Entry::getKey, x -> sreq.headers().getAll(x.getKey()))); Map<String, String> headerValue = sreq.headers().entries().stream() .collect(toMap(Entry::getKey, Entry::getValue)); /* * Handle request context */ RequestIdentity reqId = new RequestIdentity().withSourceIp(getRemoteAddress(ctx)) .withUserAgent(sreq.getHeader(USER_AGENT)); if (ctx.user() != null) { reqId.withUser(ctx.user().principal().toString()); } ProxyRequestContext reqCtx = new ProxyRequestContext() .withPath(sreq.path().substring(0, routeLength)).withHttpMethod(sreq.method().toString()) .withIdentity(reqId); reqObj = reqObj.withMultiValueHeaders(headerMultivalue).withHeaders(headerValue) .withHttpMethod(sreq.method().toString()).withPath(sreq.path()).withResource(path) .withQueryStringParameters(splitQuery(sreq.query())) .withMultiValueQueryStringParameters(splitMultiValueQuery(sreq.query())) .withPathParameters(matchRes.getParameters()).withRequestContext(reqCtx); String reqStr = JsonObject.mapFrom(reqObj).toString(); byte[] sendBody = reqStr.getBytes(UTF_8); InvokeRequest req = InvokeRequest.builder().invocationType(InvocationType.REQUEST_RESPONSE) .functionName(lambdaFunction).qualifier(qualifier).payload(SdkBytes.fromByteArray(sendBody)) .build(); logger.info("Calling lambda " + lambdaFunction + ":" + qualifier); logger.debug("Payload: " + reqStr); CompletableFuture<InvokeResponse> respFuture = lambdaCl.invoke(req); respFuture.whenComplete((iresp, err) -> { if (iresp != null) { try { String payload = iresp.payload().asString(UTF_8); JsonObject resp = new JsonObject(payload); int statusCode = resp.getInteger("statusCode"); sres.setStatusCode(statusCode); for (Entry<String, Object> next : resp.getJsonObject("headers").getMap().entrySet()) { sres.putHeader(next.getKey(), next.getValue().toString()); } String respBody = resp.getString("body"); byte[] bodyArr = new byte[0]; if (body != null && !respBody.isEmpty()) { if (TRUE.equals(resp.getBoolean("isBase64Encoded"))) { bodyArr = Base64.getDecoder().decode(body); } else { bodyArr = respBody.getBytes(UTF_8); } } sres.putHeader(CONTENT_LENGTH, String.valueOf(bodyArr.length)); Buffer buffer = Buffer.buffer(bodyArr); tryToCacheContent(ctx, buffer); sres.write(buffer); } catch (Throwable t) { logger.error("Error processing lambda request", t); if (!sres.headWritten()) { sres.setStatusCode(BAD_GATEWAY.code()); sres.putHeader(CONTENT_TYPE, "application/json"); Buffer response = Buffer.buffer(new LambdaErrorResponse(t).toString()); sres.putHeader(CONTENT_LENGTH, String.valueOf(response.length())); sres.write(response); } } finally { sres.end(); } } else { logger.error("Error processing lambda request", err); sres.setStatusCode(BAD_GATEWAY.code()); sres.putHeader(CONTENT_TYPE, "application/json"); Buffer response = Buffer.buffer(new LambdaErrorResponse(err).toString()); sres.putHeader(CONTENT_LENGTH, String.valueOf(response.length())); sres.end(response); } }); } }); }