List of usage examples for io.vertx.core.json JsonObject containsKey
public boolean containsKey(String key)
From source file:net.kuujo.vertigo.network.impl.EndpointConfigImpl.java
License:Apache License
@Override public void update(JsonObject endpoint) { if (endpoint.containsKey(ENDPOINT_COMPONENT)) { this.component = endpoint.getString(ENDPOINT_COMPONENT); }/*from ww w .ja v a 2 s. c om*/ if (endpoint.containsKey(ENDPOINT_PORT)) { this.port = endpoint.getString(ENDPOINT_PORT); } if (endpoint.containsKey(ENDPOINT_IS_NETWORK)) { this.isNetwork = endpoint.getBoolean(ENDPOINT_IS_NETWORK); } }
From source file:org.eclipse.hono.service.credentials.BaseCredentialsService.java
License:Open Source License
/** * Gets the payload from the request and ensures that the enabled flag is contained. * * @param request The request from which the payload is tried to be extracted. Must not be null. * @return The payload as JsonObject (if found). Null otherwise. *///from w w w . ja va 2s. co m private JsonObject getRequestPayload(final JsonObject request) { if (request == null) { return null; } else { JsonObject payload = null; Object payloadObject = request.getValue(CredentialsConstants.FIELD_PAYLOAD); if (JsonObject.class.isInstance(payloadObject)) { payload = (JsonObject) payloadObject; if (!payload.containsKey(FIELD_ENABLED)) { log.debug("adding 'enabled' key to payload"); payload.put(FIELD_ENABLED, Boolean.TRUE); } } return payload; } }
From source file:org.eclipse.hono.service.tenant.BaseTenantService.java
License:Open Source License
/** * Add default values for optional fields that are not filled in the payload. * <p>/*from w w w .j a va 2 s . c om*/ * Payload should be checked for validity first, there is no error handling inside this method anymore. * </p> * * @param checkedPayload The checked payload to add optional fields to. * @throws ClassCastException If the {@link TenantConstants#FIELD_ADAPTERS_TYPE} element is not a {@link JsonArray} * or the JsonArray contains elements that are not of type {@link JsonObject}. */ protected final void addNotPresentFieldsWithDefaultValuesForTenant(final JsonObject checkedPayload) { if (!checkedPayload.containsKey(TenantConstants.FIELD_ENABLED)) { log.trace("adding 'enabled' key to payload"); checkedPayload.put(TenantConstants.FIELD_ENABLED, Boolean.TRUE); } final JsonArray adapters = checkedPayload.getJsonArray(TenantConstants.FIELD_ADAPTERS); if (adapters != null) { adapters.forEach(elem -> addNotPresentFieldsWithDefaultValuesForAdapter((JsonObject) elem)); } }
From source file:org.eclipse.hono.service.tenant.BaseTenantService.java
License:Open Source License
private void addNotPresentFieldsWithDefaultValuesForAdapter(final JsonObject adapter) { if (!adapter.containsKey(TenantConstants.FIELD_ENABLED)) { log.trace("adding 'enabled' key to payload"); adapter.put(TenantConstants.FIELD_ENABLED, Boolean.TRUE); }// ww w . j a v a2 s. co m if (!adapter.containsKey(TenantConstants.FIELD_ADAPTERS_DEVICE_AUTHENTICATION_REQUIRED)) { log.trace("adding 'device-authentication-required' key to adapter payload"); adapter.put(TenantConstants.FIELD_ADAPTERS_DEVICE_AUTHENTICATION_REQUIRED, Boolean.TRUE); } }
From source file:org.eclipse.hono.tests.IntegrationTestSupport.java
License:Open Source License
/** * A simple implementation of subtree containment: all entries of the JsonObject that is tested to be contained * must be contained in the other JsonObject as well. Nested JsonObjects are treated the same by recursively calling * this method to test the containment./*from w w w .jav a 2s . co m*/ * JsonArrays are tested for containment as well: all elements in a JsonArray belonging to the contained JsonObject * must be present in the corresponding JsonArray of the other JsonObject as well. The sequence of the array elements * is not important (suitable for the current tests). * @param jsonObject The JsonObject that must fully contain the other JsonObject (but may contain more entries as well). * @param jsonObjectToBeContained The JsonObject that needs to be fully contained inside the other JsonObject. * @return The result of the containment test. */ public static boolean testJsonObjectToBeContained(final JsonObject jsonObject, final JsonObject jsonObjectToBeContained) { if (jsonObjectToBeContained == null) { return true; } if (jsonObject == null) { return false; } final AtomicBoolean containResult = new AtomicBoolean(true); jsonObjectToBeContained.forEach(entry -> { if (!jsonObject.containsKey(entry.getKey())) { containResult.set(false); } else { if (entry.getValue() == null) { if (jsonObject.getValue(entry.getKey()) != null) { containResult.set(false); } } else if (entry.getValue() instanceof JsonObject) { if (!(jsonObject.getValue(entry.getKey()) instanceof JsonObject)) { containResult.set(false); } else { if (!testJsonObjectToBeContained((JsonObject) entry.getValue(), (JsonObject) jsonObject.getValue(entry.getKey()))) { containResult.set(false); } } } else if (entry.getValue() instanceof JsonArray) { if (!(jsonObject.getValue(entry.getKey()) instanceof JsonArray)) { containResult.set(false); } else { // compare two JsonArrays final JsonArray biggerArray = (JsonArray) jsonObject.getValue(entry.getKey()); final JsonArray smallerArray = (JsonArray) entry.getValue(); if (!testJsonArrayToBeContained(biggerArray, smallerArray)) { containResult.set(false); } } } else { if (!entry.getValue().equals(jsonObject.getValue(entry.getKey()))) { containResult.set(false); } } } }); return containResult.get(); }
From source file:org.entcore.auth.controllers.SamlController.java
License:Open Source License
@Get("/saml/metadata/:idp") public void idpGar(HttpServerRequest request) { JsonObject idpConfig = config.getJsonObject("idp-metadata-mapping", new JsonObject()); String idpParam = request.getParam("idp"); if (!idpConfig.isEmpty() && idpConfig.containsKey(idpParam)) { request.response().sendFile(idpConfig.getString(idpParam)); } else {//from w w w . j a va2 s . co m request.response().setStatusCode(404).setStatusMessage("idp not found").end(); } }
From source file:org.entcore.auth.oauth.OAuthDataHandler.java
License:Open Source License
@Override public void createOrUpdateAccessToken(final AuthInfo authInfo, final Handler<AccessToken> handler) { if (authInfo != null) { final JsonObject query = new JsonObject().put("authId", authInfo.getId()); mongo.count(ACCESS_TOKEN_COLLECTION, query, new io.vertx.core.Handler<Message<JsonObject>>() { @Override/*from www . ja v a2s.c o m*/ public void handle(Message<JsonObject> event) { if ("ok".equals(event.body().getString("status")) && (event.body().getInteger("count", 1) == 0 || isNotEmpty(authInfo.getRefreshToken()))) { final JsonObject token = new JsonObject().put("authId", authInfo.getId()) .put("token", UUID.randomUUID().toString()).put("createdOn", MongoDb.now()) .put("expiresIn", 3600); if (openIdConnectService != null && authInfo.getScope() != null && authInfo.getScope().contains("openid")) { //"2.0".equals(RequestUtils.getAcceptVersion(getRequest().getHeader("Accept")))) { openIdConnectService.generateIdToken(authInfo.getUserId(), authInfo.getClientId(), new io.vertx.core.Handler<AsyncResult<String>>() { @Override public void handle(AsyncResult<String> ar) { if (ar.succeeded()) { token.put("id_token", ar.result()); persistToken(token); } else { log.error("Error generating id_token.", ar.cause()); handler.handle(null); } } }); } else { persistToken(token); } } else { // revoke existing token and code with same authId mongo.delete(ACCESS_TOKEN_COLLECTION, query); mongo.delete(AUTH_INFO_COLLECTION, new JsonObject().put("_id", authInfo.getId())); handler.handle(null); } } private void persistToken(final JsonObject token) { mongo.save(ACCESS_TOKEN_COLLECTION, token, new io.vertx.core.Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> res) { if ("ok".equals(res.body().getString("status"))) { AccessToken t = new AccessToken(); t.setAuthId(authInfo.getId()); t.setToken(token.getString("token")); t.setCreatedOn(new Date(token.getJsonObject("createdOn").getLong("$date"))); t.setExpiresIn(3600); if (token.containsKey("id_token")) { t.setIdToken(token.getString("id_token")); } handler.handle(t); } else { handler.handle(null); } } }); } }); } else { handler.handle(null); } }
From source file:org.entcore.auth.security.SamlValidator.java
License:Open Source License
/** * Build SAMLResponse and convert it in base64 * * @param serviceProvider serviceProvider name qualifier * @param userId neo4j userID/*from www . j a v a 2s . c om*/ * @param nameId ameId value * @param message message * * * @throws SignatureException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws UnsupportedEncodingException * @throws MarshallingException */ public void generateSAMLResponse(final String serviceProvider, final String userId, final String nameId, final String host, final Message<JsonObject> message) throws SignatureException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, MarshallingException { logger.info("start generating SAMLResponse"); logger.info("SP : " + serviceProvider); final JsonObject idp = config.getJsonObject("saml-entng-idp-nq"); String entngIdpNameQualifierTMP = null; if (idp.containsKey(serviceProvider)) { entngIdpNameQualifierTMP = idp.getString(serviceProvider); } else if (idp.containsKey("default")) { entngIdpNameQualifierTMP = idp.getString(serviceProvider); } final String entngIdpNameQualifier = entngIdpNameQualifierTMP; if (entngIdpNameQualifier == null) { String error = "entngIdpNameQualifier can not be null. You must specify it in auth configuration (saml-entng-idp-nq properties)"; logger.error(error); JsonObject jsonObject = new JsonObject().put("error", error); sendOK(message, jsonObject); } logger.info("entngIdpNameQualifier : " + entngIdpNameQualifier); // -- get spSSODescriptor from serviceProvider id -- if (spSSODescriptor == null) { String error = "error SSODescriptor not found for serviceProvider : " + serviceProvider; logger.error(error); JsonObject jsonObject = new JsonObject().put("error", error); sendOK(message, jsonObject); } // --- TAG Issuer --- final Issuer idpIssuer = createIssuer(entngIdpNameQualifier); // --- TAG Status --- final Status status = createStatus(); final AssertionConsumerService assertionConsumerService = spSSODescriptor .getDefaultAssertionConsumerService(); if (assertionConsumerService == null) { String error = "error : AssertionConsumerService not found"; logger.error(error); sendError(message, error); } // --- TAG AttributeStatement --- createVectors(userId, host, new Handler<Either<String, JsonArray>>() { @Override public void handle(Either<String, JsonArray> event) { if (event.isRight()) { LinkedHashMap<String, List<String>> attributes = new LinkedHashMap<String, List<String>>(); JsonArray vectors = event.right().getValue(); if (vectors == null || vectors.size() == 0) { String error = "error building vectors for user " + userId; logger.error(error); sendError(message, error); } else { for (int i = 0; i < vectors.size(); i++) { List<String> vectorsValue = new ArrayList<>(); String vectorType = ""; JsonObject vectorsJsonObject = (vectors.getJsonObject(i)); for (Iterator<String> iter = (vectors.getJsonObject(i)).fieldNames().iterator(); iter .hasNext();) { vectorType = iter.next(); if (attributes.containsKey(vectorType)) { vectorsValue = attributes.get(vectorType); } vectorsValue.add(((JsonObject) vectorsJsonObject).getString(vectorType)); } attributes.put(vectorType, vectorsValue); } } AttributeStatement attributeStatement = createAttributeStatement(attributes); // --- TAG Assertion --- Assertion assertion = null; try { assertion = generateAssertion(entngIdpNameQualifier, serviceProvider, nameId, assertionConsumerService.getLocation(), userId); } catch (Exception e) { logger.error(e.getMessage(), e); sendError(message, e.getMessage(), e); } if (assertion == null) { String error = "error building assertion"; logger.error(error); sendError(message, error); } assertion.getAttributeStatements().add(attributeStatement); // -- attribute Destination (acs) -- String destination = assertionConsumerService.getLocation(); // --- Build response -- Response response = createResponse(new DateTime(), idpIssuer, status, assertion, destination); Signature signature = null; try { signature = createSignature(); } catch (Throwable e) { logger.error(e.getMessage(), e); sendError(message, e.getMessage()); } //response.setSignature(signature); assertion.setSignature(signature); ResponseMarshaller marshaller = new ResponseMarshaller(); Element element = null; try { element = marshaller.marshall(response); } catch (MarshallingException e) { logger.error(e.getMessage(), e); sendError(message, e.getMessage(), e); } if (signature != null) { try { Signer.signObject(signature); } catch (org.opensaml.xml.signature.SignatureException e) { logger.error(e.getMessage(), e); sendError(message, e.getMessage(), e); } } StringWriter rspWrt = new StringWriter(); XMLHelper.writeNode(element, rspWrt); debug("response : " + rspWrt.toString()); JsonObject jsonObject = new JsonObject(); String base64Response = Base64.getEncoder().encodeToString(rspWrt.toString().getBytes()); //, Base64.DONT_BREAK_LINES); debug("base64Response : " + base64Response); jsonObject.put("SAMLResponse64", base64Response); jsonObject.put("destination", destination); sendOK(message, jsonObject); } else { String error = "error bulding vectors for user " + userId + " :"; logger.error(error); logger.error(event.left().getValue()); sendError(message, error); } } }); }
From source file:org.entcore.auth.services.impl.FranceConnectServiceProvider.java
License:Open Source License
private void federateWithPivot(JsonObject payload, final Handler<Either<String, Object>> handler) { if (!payload.containsKey("preferred_username")) { payload.put("preferred_username", ""); }//from ww w . jav a 2 s.c o m payload.put("setFederated", setFederated); neo4j.execute(QUERY_PIVOT_FC, payload, validUniqueResultHandler(new Handler<Either<String, JsonObject>>() { @Override public void handle(final Either<String, JsonObject> event) { if (event.isRight() && event.right().getValue().getBoolean("blockedProfile", false)) { handler.handle(new Either.Left<String, Object>("blocked.profile")); } else if (event.isRight() && event.right().getValue().size() > 0) { handler.handle(new Either.Right<String, Object>(event.right().getValue())); } else { handler.handle(new Either.Left<String, Object>(UNRECOGNIZED_USER_IDENTITY)); } } })); }
From source file:org.entcore.blog.services.impl.DefaultPostService.java
License:Open Source License
@Override public void create(String blogId, JsonObject post, UserInfos author, final Handler<Either<String, JsonObject>> result) { JsonObject now = MongoDb.now();// w w w.j a v a 2 s . c o m JsonObject blogRef = new JsonObject().put("$ref", "blogs").put("$id", blogId); JsonObject owner = new JsonObject().put("userId", author.getUserId()).put("username", author.getUsername()) .put("login", author.getLogin()); post.put("created", now).put("modified", now).put("author", owner).put("state", StateType.DRAFT.name()) .put("comments", new JsonArray()).put("views", 0).put("blog", blogRef); JsonObject b = Utils.validAndGet(post, FIELDS, FIELDS); if (validationError(result, b)) return; b.put("sorted", now); if (b.containsKey("content")) { b.put("contentPlain", StringUtils.stripHtmlTag(b.getString("content", ""))); } mongo.save(POST_COLLECTION, b, MongoDbResult.validActionResultHandler(new Handler<Either<String, JsonObject>>() { public void handle(Either<String, JsonObject> event) { if (event.isLeft()) { result.handle(event); return; } mongo.findOne(POST_COLLECTION, new JsonObject().put("_id", event.right().getValue().getString("_id")), MongoDbResult.validResultHandler(result)); } })); }