Java Code Examples for io.vertx.core.json.JsonObject#copy()

The following examples show how to use io.vertx.core.json.JsonObject#copy() . 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: OAuth2API.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
/**
 * The logout (end-session) endpoint is specified in OpenID Connect Session Management 1.0.
 *
 * see: https://openid.net/specs/openid-connect-session-1_0.html
 */
public String endSessionURL(String idToken, JsonObject params) {
  final String path = config.getLogoutPath();

  if (path == null) {
    // we can't generate anything, there's no configured logout path
    return null;
  }

  final JsonObject query = params.copy();

  if (idToken != null) {
    query.put("id_token_hint", idToken);
  }

  final String url = path.charAt(0) == '/' ? config.getSite() + path : path;

  return url + '?' + stringify(query);
}
 
Example 2
Source File: OAuth2API.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
/**
 * The client sends the end-user's browser to this endpoint to request their authentication and consent. This endpoint is used in the code and implicit OAuth 2.0 flows which require end-user interaction.
 *
 * see: https://tools.ietf.org/html/rfc6749
 */
public String authorizeURL(JsonObject params) {
  final JsonObject query = params.copy();

  if (config.getFlow() != OAuth2FlowType.AUTH_CODE) {
    throw new IllegalStateException("authorization URL cannot be computed for non AUTH_CODE flow");
  }

  if (query.containsKey("scopes")) {
    // scopes have been passed as a list so the provider must generate the correct string for it
    query.put("scope", String.join(config.getScopeSeparator(), query.getJsonArray("scopes").getList()));
    query.remove("scopes");
  }

  query.put("response_type", "code");
  query.put("client_id", config.getClientID());

  final String path = config.getAuthorizationPath();
  final String url = path.charAt(0) == '/' ? config.getSite() + path : path;

  return url + '?' + stringify(query);
}
 
Example 3
Source File: EventbusBridgeTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendPermittedStructureMatchWithAddress() throws Exception {
  JsonObject match = new JsonObject().put("fib", "wib").put("oop", 12);
  sockJSHandler.bridge(defaultOptions.addInboundPermitted(new PermittedOptions().setMatch(match).setAddress(addr)));
  testSend(addr, match);
  JsonObject json1 = match.copy();
  json1.put("blah", "foob");
  testSend(addr, json1);
  json1.remove("fib");
  testError(new JsonObject().put("type", "send").put("address", addr).put("body", json1),
    "access_denied");
  testError(new JsonObject().put("type", "send").put("address", "otheraddress").put("body", json1),
    "access_denied");
}
 
Example 4
Source File: App.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public MongoDBBenchmark(Vertx vertx, JsonObject config) {
  final JsonObject mongoConfig = config.copy();

  // mongo is configured without credentials
  mongoConfig.remove("username");
  mongoConfig.remove("password");

  this.database = MongoClient.createShared(vertx, mongoConfig);
  this.engine = RockerTemplateEngine.create();
}
 
Example 5
Source File: JWTAuthProviderImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
@Override
public String generateToken(JsonObject claims, final JWTOptions options) {
  final JsonObject _claims = claims.copy();

  // we do some "enhancement" of the claims to support roles and permissions
  if (options.getPermissions() != null && !_claims.containsKey(permissionsClaimKey)) {
    _claims.put(permissionsClaimKey, new JsonArray(options.getPermissions()));
  }

  return jwt.sign(_claims, options);
}
 
Example 6
Source File: OpenAPIHolderImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public Map.Entry<JsonPointer, JsonObject> normalizeSchema(JsonObject schema, JsonPointer scope, Map<JsonPointer,
  JsonObject> additionalSchemasToRegister) {
  JsonObject normalized = schema.copy();
  JsonPointer newId = new SchemaURNId().toPointer();
  normalized.put("x-$id", newId.toURI().toString());

  innerNormalizeSchema(normalized, scope, additionalSchemasToRegister);
  return new AbstractMap.SimpleImmutableEntry<>(newId, normalized);
}
 
Example 7
Source File: EventbusBridgeTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegisterPermittedStructureMatchWithAddress() throws Exception {
  JsonObject match = new JsonObject().put("fib", "wib").put("oop", 12);
  sockJSHandler.bridge(defaultOptions.addOutboundPermitted(new PermittedOptions().setMatch(match).setAddress(addr)));
  testReceive(addr, match);
  JsonObject json1 = match.copy();
  json1.put("blah", "foob");
  testReceive(addr, json1);
  JsonObject json2 = json1.copy();
  json2.remove("fib");
  testReceiveFail(addr, json2);
}
 
Example 8
Source File: EventbusBridgeTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testRegisterPermittedStructureMatch() throws Exception {
  JsonObject match = new JsonObject().put("fib", "wib").put("oop", 12);
  sockJSHandler.bridge(defaultOptions.addOutboundPermitted(new PermittedOptions().setMatch(match)));
  testReceive(addr, match);
  JsonObject json1 = match.copy();
  json1.put("blah", "foob");
  testReceive(addr, json1);
  JsonObject json2 = json1.copy();
  json2.remove("fib");
  testReceiveFail(addr, json2);
}
 
Example 9
Source File: EventbusBridgeTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendPermittedStructureMatch() throws Exception {
  JsonObject match = new JsonObject().put("fib", "wib").put("oop", 12);
  sockJSHandler.bridge(defaultOptions.addInboundPermitted(new PermittedOptions().setMatch(match)));
  testSend(addr, match);
  JsonObject json1 = match.copy();
  json1.put("blah", "foob");
  testSend(addr, json1);
  json1.remove("fib");
  testError(new JsonObject().put("type", "send").put("address", addr).put("body", json1),
    "access_denied");
}
 
Example 10
Source File: SchemaMetadata.java    From vertx-graphql-service-discovery with Apache License 2.0 5 votes vote down vote up
public SchemaMetadata(JsonObject json) {
    Objects.requireNonNull(json, "Json metadata cannot be null");
    this.schemaName = json.getString("schemaName");
    this.serviceAddress = json.getString("serviceAddress");
    this.exposeToGateway = json.getBoolean("exposeToGateway", false);
    if (json.containsKey("deliveryOptions")) {
        this.deliveryOptions = new DeliveryOptions(json.getJsonObject("deliveryOptions"));
    }
    this.metadata = json.copy();
    this.metadata.remove("exposeToGateway");
    this.metadata.remove("schemaName");
    this.metadata.remove("deliveryOptions");
}
 
Example 11
Source File: X509AuthProvider.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a {@link SubjectDnCredentials} instance from information provided by a
 * device in its client (X.509) certificate.
 * <p>
 * The JSON object passed in is required to contain a <em>subject-dn</em> property.
 * If the <em>singleTenant</em> service config property is {@code false}, then the
 * object is also required to contain a <em>tenant-id</em> property, otherwise
 * the default tenant is used.
 * <p>
 * Any additional properties that might be present in the JSON object 
 * are copied into the client context of the returned credentials.
 *
 * @param authInfo The authentication information provided by the device.
 * @return The credentials or {@code null} if the authentication information
 *         does not contain a tenant ID and subject DN.
 * @throws NullPointerException if the authentication info is {@code null}.
 */
@Override
protected SubjectDnCredentials getCredentials(final JsonObject authInfo) {

    Objects.requireNonNull(authInfo);
    try {
        final String tenantId = Optional.ofNullable(authInfo.getString(CredentialsConstants.FIELD_PAYLOAD_TENANT_ID))
                .orElseGet(() -> {
                    if (config.isSingleTenant()) {
                        return Constants.DEFAULT_TENANT;
                    } else {
                        return null;
                    }
                });
        final String subjectDn = authInfo.getString(CredentialsConstants.FIELD_PAYLOAD_SUBJECT_DN);
        if (tenantId == null || subjectDn == null) {
            return null;
        } else {
            final JsonObject clientContext = authInfo.copy();
            // credentials object already contains tenant ID and subject DN, so remove them from the client context
            clientContext.remove(CredentialsConstants.FIELD_PAYLOAD_TENANT_ID);
            clientContext.remove(CredentialsConstants.FIELD_PAYLOAD_SUBJECT_DN);
            return SubjectDnCredentials.create(tenantId, subjectDn, clientContext);
        }
    } catch (ClassCastException | IllegalArgumentException e) {
        log.warn("Reading authInfo failed", e);
        return null;
    }
}
 
Example 12
Source File: KubernetesServiceImporter.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
private static void manageHttpService(Record record, JsonObject service) {
  JsonObject spec = service.getJsonObject("spec");
  JsonArray ports = spec.getJsonArray("ports");

  if (ports != null && !ports.isEmpty()) {
    if (ports.size() > 1) {
      LOGGER.warn("More than one port has been found for " + record.getName() + " - taking the first" +
        " one to extract the HTTP endpoint location");
    }

    JsonObject port = ports.getJsonObject(0);
    Integer p = port.getInteger("port");

    record.setType(HttpEndpoint.TYPE);

    HttpLocation location = new HttpLocation(port.copy());

    if (isExternalService(service)) {
      location.setHost(spec.getString("externalName"));
    } else {
      location.setHost(spec.getString("clusterIP"));
    }

    if (isTrue(record.getMetadata().getString("ssl")) || p != null && p == 443) {
      location.setSsl(true);
    }
    record.setLocation(location.toJson());
  } else {
    throw new IllegalStateException("Cannot extract the HTTP URL from the service " + record + " - no port");
  }
}
 
Example 13
Source File: KubernetesServiceImporter.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
private static void manageUnknownService(Record record, JsonObject service, String type) {
  JsonObject spec = service.getJsonObject("spec");
  JsonArray ports = spec.getJsonArray("ports");
  if (ports != null && !ports.isEmpty()) {
    if (ports.size() > 1) {
      LOGGER.warn("More than one ports has been found for " + record.getName() + " - taking the " +
        "first one to build the record location");
    }
    JsonObject port = ports.getJsonObject(0);
    JsonObject location = port.copy();

    if (isExternalService(service)) {
      location.put("host", spec.getString("externalName"));
    } else {
      //Number or name of the port to access on the pods targeted by the service.
      Object targetPort = port.getValue("targetPort");
      if (targetPort instanceof Integer) {
        location.put("internal-port", (Integer) targetPort);
      }
      location.put("host", spec.getString("clusterIP"));
    }

    record.setLocation(location).setType(type);
  } else {
    throw new IllegalStateException("Cannot extract the location from the service " + record + " - no port");
  }
}
 
Example 14
Source File: ValidationHandlerProcessorsIntegrationTest.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Test
public void testQueryJsonObjectAsyncParam(VertxTestContext testContext) {
  Checkpoint checkpoint = testContext.checkpoint(2);

  ValidationHandler validationHandler = ValidationHandlerBuilder
    .create(parser)
    .queryParameter(Parameters.jsonParam("myTree", ref(JsonPointer.fromURI(URI.create("tree_schema.json")))))
    .build();
  router
    .get("/test")
    .handler(validationHandler)
    .handler(routingContext -> {
      RequestParameters params = routingContext.get("parsedParameters");
      routingContext
        .response()
        .putHeader("content-type", "application/json")
        .end(params.queryParameter("myTree").getJsonObject().toBuffer());
    });

  JsonObject testSuccessObj = new JsonObject()
    .put("value", "aaa")
    .put("childs", new JsonArray().add(
      new JsonObject().put("value", "bbb")
    ));

  testRequest(client, HttpMethod.GET, "/test?myTree=" + urlEncode(testSuccessObj.encode()))
    .expect(statusCode(200), jsonBodyResponse(testSuccessObj))
    .send(testContext, checkpoint);

  JsonObject testFailureObj = testSuccessObj.copy();
  testFailureObj.remove("value");

  testRequest(client, HttpMethod.GET, "/test?myTree=" + urlEncode(testFailureObj.encode()))
    .expect(statusCode(400))
    .expect(badParameterResponse(
      ParameterProcessorException.ParameterProcessorErrorType.VALIDATION_ERROR,
      "myTree",
      ParameterLocation.QUERY
    ))
    .send(testContext, checkpoint);
}
 
Example 15
Source File: FileBasedCredentialsService.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Get the credentials associated with the authId and the given type. If type is null, all credentials associated
 * with the authId are returned (as JsonArray inside the return value).
 *
 * @param tenantId The id of the tenant the credentials belong to.
 * @param authId The authentication identifier to look up credentials for.
 * @param type The type of credentials to look up.
 * @param span The active OpenTracing span for this operation.
 * @return The credentials object of the given type or {@code null} if no matching credentials exist.
 */
private JsonObject getSingleCredentials(final String tenantId, final String authId, final String type,
        final JsonObject clientContext, final Span span) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(authId);
    Objects.requireNonNull(type);

    final ConcurrentMap<String, JsonArray> credentialsForTenant = credentials.get(tenantId);
    if (credentialsForTenant == null) {
        TracingHelper.logError(span, "no credentials found for tenant");
        return null;
    }

    final JsonArray authIdCredentials = credentialsForTenant.get(authId);
    if (authIdCredentials == null) {
        TracingHelper.logError(span, "no credentials found for auth-id");
        return null;
    }

    for (final Object authIdCredentialEntry : authIdCredentials) {
        final JsonObject authIdCredential = (JsonObject) authIdCredentialEntry;

        if (!type.equals(authIdCredential.getString(CredentialsConstants.FIELD_TYPE))) {
            // credentials type doesn't match ... continue search
            continue;
        }

        if (Boolean.FALSE.equals(authIdCredential.getBoolean(CredentialsConstants.FIELD_ENABLED, true))) {
            // do not report disabled
            continue;
        }

        if (clientContext != null && !clientContext.isEmpty()) {

            final JsonObject extensionProperties = authIdCredential.getJsonObject(RegistryManagementConstants.FIELD_EXT, new JsonObject());

            final boolean credentialsOnRecordMatchClientContext = clientContext.stream()
                    .filter(entry -> entry.getValue() != null)
                    .allMatch(entry -> {
                        final Object valueOnRecord = extensionProperties.getValue(entry.getKey());
                        LOG.debug("comparing client context property [name: {}, value: {}] to value on record: {}",
                                entry.getKey(), entry.getValue(), valueOnRecord);
                        if (valueOnRecord == null) {
                            return true;
                        } else {
                            return entry.getValue().equals(valueOnRecord);
                        }
                    });

            if (!credentialsOnRecordMatchClientContext) {
                continue;
            }

        }

        // copy
        final var authIdCredentialCopy = authIdCredential.copy();
        final var secrets = authIdCredentialCopy.getJsonArray(CredentialsConstants.FIELD_SECRETS);

        for (final Iterator<Object> i = secrets.iterator(); i.hasNext();) {

            final Object o = i.next();
            if (!(o instanceof JsonObject)) {
                i.remove();
                continue;
            }

            final JsonObject secret = (JsonObject) o;
            if (Boolean.FALSE.equals(secret.getBoolean(CredentialsConstants.FIELD_ENABLED, true))) {
                i.remove();
            }
        }

        if (secrets.isEmpty()) {
            // no more secrets left
            continue;
        }

        // return the first entry that matches
        return authIdCredentialCopy;
    }

    // we ended up with no match
    if (clientContext != null) {
        TracingHelper.logError(span, "no credentials found with matching type and client context");
    } else {
        TracingHelper.logError(span, "no credentials found with matching type");
    }

    return null;
}
 
Example 16
Source File: OAuth2Options.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
/**
 * Copy constructor
 *
 * @param other the options to copy
 */
public OAuth2Options(OAuth2Options other) {
  tenant = other.getTenant();
  clientID = other.getClientID();
  clientSecret = other.getClientSecret();
  validateIssuer = other.isValidateIssuer();
  flow = other.getFlow();
  authorizationPath = other.getAuthorizationPath();
  tokenPath = other.getTokenPath();
  revocationPath = other.getRevocationPath();
  userInfoPath = other.getUserInfoPath();
  introspectionPath = other.getIntrospectionPath();
  scopeSeparator = other.getScopeSeparator();
  useBasicAuthorizationHeader = other.isUseBasicAuthorizationHeader();
  clientSecretParameterName = other.getClientSecretParameterName();
  site = other.getSite();
  pubSecKeys = other.getPubSecKeys();
  jwtOptions = other.getJWTOptions();
  logoutPath = other.getLogoutPath();
  // extras
  final JsonObject obj = other.getExtraParameters();
  if (obj != null) {
    extraParams = obj.copy();
  } else {
    extraParams = null;
  }
  // user info params
  final JsonObject obj2 = other.getUserInfoParameters();
  if (obj2 != null) {
    userInfoParams = obj2.copy();
  } else {
    userInfoParams = null;
  }
  // custom headers
  final JsonObject obj3 = other.getHeaders();
  if (obj3 != null) {
    headers = obj3.copy();
  } else {
    headers = null;
  }
  jwkPath = other.getJwkPath();
  httpClientOptions = other.getHttpClientOptions();
  userAgent = other.getUserAgent();
  // compute paths with variables, at this moment it is only relevant that
  // the paths and site are properly computed
  replaceVariables(false);
}
 
Example 17
Source File: OAuth2AccessTokenTest.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
private JsonObject removeAuthDetails(JsonObject config) {
  JsonObject request = config.copy();
  request.remove("client_secret");
  request.remove("client_id");
  return request;
}
 
Example 18
Source File: ApplicationConfiguration.java    From kubernetes-lab with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a new json object containing the content of the given json object merged with
 * the given Map. The content of the Map overrides the content of the given json object.
 *
 * @param conf  the configuration
 * @param props the map
 * @return the json object
 */
private static JsonObject putAll(JsonObject conf, Map<String, String> props) {
  Objects.requireNonNull(conf);
  Objects.requireNonNull(props);
  JsonObject json = conf.copy();
  props.entrySet().stream().forEach(entry -> put(json, entry.getKey(), entry.getValue()));
  return json;
}
 
Example 19
Source File: ApplicationConfiguration.java    From kubernetes-lab with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a new json object containing the content of the given json object merged with
 * the given Properties. The content of the Properties overrides the content of the given
 * json object.
 *
 * @param conf  the configuration
 * @param props the map
 * @return the json object
 */
private static JsonObject putAll(JsonObject conf, Properties props) {
  Objects.requireNonNull(conf);
  Objects.requireNonNull(props);
  JsonObject json = conf.copy();
  props.stringPropertyNames().stream()
      .forEach(name -> put(json, name, props.getProperty(name)));
  return json;
}