List of usage examples for io.vertx.core.json JsonObject getString
public String getString(String key)
From source file:org.entcore.common.http.response.SecurityHookRender.java
License:Open Source License
private void contentSecurityPolicyHeader(HttpServerRequest request, JsonObject session) { if (contentSecurityPolicy == null) return;// w w w . j a v a 2s . co m final String csp; if (session != null && session.getJsonObject("cache") != null && session.getJsonObject("cache").getString("content-security-policy") != null) { csp = session.getJsonObject("cache").getString("content-security-policy"); } else if (session != null && session.getJsonArray("apps") != null) { final StringBuilder sb = new StringBuilder(contentSecurityPolicy); if (!contentSecurityPolicy.contains("frame-src")) { if (!contentSecurityPolicy.trim().endsWith(";")) { sb.append("; "); } sb.append("frame-src 'self'"); } for (Object o : session.getJsonArray("apps")) { if (!(o instanceof JsonObject)) continue; String address = ((JsonObject) o).getString("address"); if (address != null && address.contains("adapter#")) { String[] s = address.split("adapter#"); if (s.length == 2 && isNotEmpty(s[1])) { try { URI uri = new URI(s[1]); sb.append(" ").append(uri.getHost()); } catch (URISyntaxException e) { log.warn("Invalid adapter URI : " + s[1], e); } } } } csp = sb.append(";").toString(); UserUtils.addSessionAttribute(eb, session.getString("userId"), "content-security-policy", csp, null); } else { csp = contentSecurityPolicy; } request.response().putHeader("Content-Security-Policy", csp); }
From source file:org.entcore.common.http.response.SecurityHookRender.java
License:Open Source License
private void csrfToken(final HttpServerRequest request, final Handler<Void> handler, JsonObject session) { if (!csrf || request.path().contains("preview") || "XMLHttpRequest".equals(request.headers().get("X-Requested-With"))) { handler.handle(null);//from w w w . j ava2 s .c om return; } String token = null; final String xsrfToken; final String userId = session.getString("userId"); if (session.getJsonObject("cache") != null) { token = session.getJsonObject("cache").getString("xsrf-token"); if (token == null) { // TODO remove when support session cache persistence String t = CookieHelper.get("XSRF-TOKEN", request); xsrfToken = ((t != null) ? t : UUID.randomUUID().toString()); } else { xsrfToken = token; } } else { xsrfToken = UUID.randomUUID().toString(); } if (token == null) { UserUtils.addSessionAttribute(eb, userId, "xsrf-token", xsrfToken, new Handler<Boolean>() { @Override public void handle(Boolean s) { if (Boolean.TRUE.equals(s)) { CookieHelper.set("XSRF-TOKEN", xsrfToken, request); } handler.handle(null); } }); } else { handler.handle(null); } }
From source file:org.entcore.common.neo4j.Neo4j.java
License:Open Source License
public void init(Vertx vertx, JsonObject config) { this.eb = Server.getEventBus(vertx); JsonArray serverUris = config.getJsonArray("server-uris"); String serverUri = config.getString("server-uri"); if (serverUris == null && serverUri != null) { serverUris = new fr.wseduc.webutils.collections.JsonArray().add(serverUri); }// w w w . ja va2 s. c o m if (serverUris != null) { try { URI[] uris = new URI[serverUris.size()]; for (int i = 0; i < serverUris.size(); i++) { uris[i] = new URI(serverUris.getString(i)); } database = new Neo4jRest(uris, config.getBoolean("slave-readonly", false), vertx, config.getLong("checkDelay", 3000l), config.getInteger("poolSize", 16), config.getBoolean("keepAlive", true), config); } catch (Exception e) { log.error(e.getMessage(), e); } } else { log.error("Invalid Neo4j URI"); } }
From source file:org.entcore.common.neo4j.Neo4j.java
License:Open Source License
private Handler<JsonObject> resultHandler(final Handler<Message<JsonObject>> m) { return new Handler<JsonObject>() { @Override//from w ww . j av a 2 s.c o m public void handle(JsonObject res) { if (res.getString("message") != null) { log.error(res.getString("exception") + " : " + res.getString("message")); res.put("status", "error"); } if (m != null) { m.handle(new ResultMessage(res)); } } }; }
From source file:org.entcore.common.neo4j.Neo4jRest.java
License:Open Source License
private void createIndex(final JsonObject j) { try {/*from w ww.ja v a 2s. c o m*/ final HttpClientRequest req = nodeManager.getClient().post("/db/data/index/" + j.getString("for"), new Handler<HttpClientResponse>() { @Override public void handle(HttpClientResponse event) { if (event.statusCode() != 201) { event.bodyHandler(new Handler<Buffer>() { @Override public void handle(Buffer event) { logger.error( "Error creating index : " + j.encode() + " -> " + event.toString()); } }); } } }); JsonObject body = new JsonObject().put("name", j.getString("name")); body.put("config", new JsonObject().put("type", j.getString("type", "exact")).put("provider", "lucene")); req.exceptionHandler(e -> logger.error("Error creating index : " + j.encode(), e)); req.end(body.encode()); } catch (Neo4jConnectionException e) { logger.error(e.getMessage(), e); } }
From source file:org.entcore.common.neo4j.Neo4jRest.java
License:Open Source License
public void executeTransaction(final JsonArray statements, final Integer transactionId, final boolean commit, final boolean allowRetry, final Handler<JsonObject> handler) { String uri = "/transaction"; if (transactionId != null) { uri += "/" + transactionId; }/*from ww w . j av a2s. co m*/ if (commit) { uri += "/commit"; } try { sendRequest(uri, new JsonObject().put("statements", statements), new Handler<HttpClientResponse>() { @Override public void handle(final HttpClientResponse resp) { resp.bodyHandler(new Handler<Buffer>() { @Override public void handle(Buffer b) { logger.debug(b.toString()); if (resp.statusCode() != 404 && resp.statusCode() != 500) { JsonObject json = new JsonObject(b.toString("UTF-8")); JsonArray results = json.getJsonArray("results"); if (json.getJsonArray("errors", new fr.wseduc.webutils.collections.JsonArray()) .size() == 0 && results != null) { JsonArray out = new fr.wseduc.webutils.collections.JsonArray(); for (Object o : results) { if (!(o instanceof JsonObject)) continue; out.add(transformJson((JsonObject) o)); } json.put("results", out); String commit = json.getString("commit"); if (commit != null) { String[] c = commit.split("/"); if (c.length > 2) { json.put("transactionId", Integer.parseInt(c[c.length - 2])); } } json.remove("errors"); handler.handle(json); } else { if (transactionId == null && commit && allowRetry && json.getJsonArray("errors") != null && json.getJsonArray("errors").size() > 0) { JsonArray errors = json.getJsonArray("errors"); for (Object o : errors) { if (!(o instanceof JsonObject)) continue; switch (((JsonObject) o).getString("code", "")) { case "Neo.TransientError.Transaction.ConstraintsChanged": case "Neo.TransientError.Transaction.DeadlockDetected": case "Neo.TransientError.Transaction.InstanceStateChanged": case "Neo.TransientError.Schema.SchemaModifiedConcurrently": executeTransaction(statements, transactionId, commit, false, handler); if (logger.isDebugEnabled()) { logger.debug("Retry transaction : " + statements.encode()); } return; } } } handler.handle( new JsonObject().put("message", json.getJsonArray("errors", new fr.wseduc.webutils.collections.JsonArray()) .encode())); } } else { handler.handle(new JsonObject().put("message", resp.statusMessage() + " : " + b.toString())); } } }); } }); } catch (Neo4jConnectionException e) { ExceptionUtils.exceptionToJson(e); } }
From source file:org.entcore.common.notification.ws.OssFcm.java
License:Open Source License
private void getAccessToken(final Handler<String> handler) throws Exception { if (accessToken != null && tokenExpiresDate > (System.currentTimeMillis() + 1000) / 1000) { handler.handle(accessToken);/* www .j a v a 2s.c om*/ } else { try { final Long date = System.currentTimeMillis() / 1000; payload.put("iat", Long.toString(date)); payload.put("exp", Long.toString(date + 3600)); client.client2LO(payload, this.key, new Handler<JsonObject>() { @Override public void handle(JsonObject json) { JsonObject token = json.getJsonObject("token"); if ("ok".equals(json.getString("status")) && token != null) { accessToken = token.getString("access_token"); tokenExpiresDate = date + token.getInteger("expires_in"); handler.handle(accessToken); } else { handler.handle(null); } } }); } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); handler.handle(null); } } }
From source file:org.entcore.common.service.impl.MongoDbCrudService.java
License:Open Source License
public void isOwner(String id, UserInfos user, final Handler<Boolean> handler) { QueryBuilder query = QueryBuilder.start("_id").is(id).put("owner.userId").is(user.getUserId()); mongo.count(collection, MongoQueryBuilder.build(query), new Handler<Message<JsonObject>>() { @Override//from w w w . j a v a2 s . c om public void handle(Message<JsonObject> event) { JsonObject res = event.body(); handler.handle(res != null && "ok".equals(res.getString("status")) && 1 == res.getInteger("count")); } }); }
From source file:org.entcore.common.service.impl.MongoDbCrudService.java
License:Open Source License
private void addPlainField(JsonObject data) { if (!this.mongoDbConf.getSearchTextFields().isEmpty()) { for (final String field : this.mongoDbConf.getSearchTextFields()) { final List<String> decomposition = StringUtils.split(field, "\\."); final String collection = decomposition.get(0); if (this.collection.equals(collection)) { if (decomposition.size() == 2) { //not an object or array final String label = decomposition.get(1); if (data.containsKey(label)) { data.put(label + plainSuffixField, StringUtils.stripHtmlTag(data.getString(label))); }//w ww . ja v a 2s .c o m } else if (decomposition.size() == 3) { final String label = decomposition.get(1); final String deepLabel = decomposition.get(2); final Object element = data.getValue(label); if (element instanceof JsonArray) { //not processed yet log.error("the plain duplication d'ont support Json Array"); } else if (element instanceof JsonObject) { final JsonObject jo = (JsonObject) element; if (jo.containsKey(deepLabel)) { jo.put(deepLabel + plainSuffixField, StringUtils.stripHtmlTag(jo.getString(deepLabel))); } } } else { //object too complex : not treaty log.error( "the plain duplication only works for a string field or top-level field of an object : collection.field | collection.object.field"); } } else { break; } } } }
From source file:org.entcore.common.service.impl.MongoDbRepositoryEvents.java
License:Open Source License
@Override public void deleteGroups(JsonArray groups) { if (groups == null || groups.size() == 0) { return;//from w w w . j av a 2s .c o m } final String[] groupIds = new String[groups.size()]; for (int i = 0; i < groups.size(); i++) { JsonObject j = groups.getJsonObject(i); groupIds[i] = j.getString("group"); } final JsonObject matcher = MongoQueryBuilder.build(QueryBuilder.start("shared.groupId").in(groupIds)); MongoUpdateBuilder modifier = new MongoUpdateBuilder(); modifier.pull("shared", MongoQueryBuilder.build(QueryBuilder.start("groupId").in(groupIds))); final String collection = MongoDbConf.getInstance().getCollection(); if (collection == null || collection.trim().isEmpty()) { log.error("Error deleting groups : invalid collection " + collection + " in class " + this.getClass().getName()); return; } mongo.update(collection, matcher, modifier.build(), false, true, new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> event) { if (!"ok".equals(event.body().getString("status"))) { log.error("Error deleting groups in collection " + collection + " : " + event.body().getString("message")); } } }); }