Java Code Examples for io.vertx.core.json.JsonArray#size()

The following examples show how to use io.vertx.core.json.JsonArray#size() . 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: MongoAuthImpl.java    From vertx-auth with Apache License 2.0 6 votes vote down vote up
private User createUser(JsonObject json) {
  User user = new UserImpl(json);
  json.put(PROPERTY_FIELD_SALT, getSaltField());
  json.put(PROPERTY_FIELD_PASSWORD, getPasswordField());
  JsonArray roles = json.getJsonArray(mongoAuthorizationOptions.getRoleField());
  if (roles!=null) {
    for (int i=0; i<roles.size(); i++) {
      String role = roles.getString(i);
      user.authorizations().add(PROVIDER_ID, RoleBasedAuthorization.create(role));
    }
  }
  JsonArray permissions = json.getJsonArray(mongoAuthorizationOptions.getPermissionField());
  if (permissions!=null) {
    for (int i=0; i<permissions.size(); i++) {
      String permission = permissions.getString(i);
      user.authorizations().add(PROVIDER_ID, PermissionBasedAuthorization.create(permission));
    }
  }
  user.setAuthProvider(this);
  return user;
}
 
Example 2
Source File: JsonTest.java    From df_data_service with Apache License 2.0 6 votes vote down vote up
public static JsonArray livyTableResultToArray(JsonObject livyStatementResult) {
    JsonObject output = livyStatementResult
            .getJsonObject("output")
            .getJsonObject("data")
            .getJsonObject("application/vnd.livy.table.v1+json");

    JsonArray header = output.getJsonArray("headers");
    JsonArray data = output.getJsonArray("data");
    JsonArray result = new JsonArray();
    JsonObject headerRowJson = new JsonObject();
    String headerRow = "";

    if(header.size() == 0) return new JsonArray().add(new JsonObject().put("row", ""));

    for(int i = 0; i < header.size(); i++) {
        headerRow = headerRow + header.getJsonObject(i).getString("name") + ",";
    }

    result.add(headerRowJson.put("row", headerRow));

    for(int i = 0; i < data.size(); i++) {
        result.add(new JsonObject().put("row", arrayToString(data.getJsonArray(i))));
    }

    return result;
}
 
Example 3
Source File: Artemis.java    From enmasse with Apache License 2.0 6 votes vote down vote up
public Set<String> getAddressNames() throws TimeoutException {
    log.info("Retrieving address names for broker {}", syncRequestClient.getRemoteContainer());
    Message response = doOperation("broker", "getAddressNames");

    Set<String> addressNames = new LinkedHashSet<>();
    JsonArray payload = new JsonArray((String)((AmqpValue)response.getBody()).getValue());
    for (int i = 0; i < payload.size(); i++) {
        JsonArray inner = payload.getJsonArray(i);
        for (int j = 0; j < inner.size(); j++) {
            String addressName = inner.getString(j);
            if (!addressName.equals(syncRequestClient.getReplyTo())) {
                addressNames.add(addressName);
            }
        }
    }
    return addressNames;
}
 
Example 4
Source File: JDBCStatementHelper.java    From vertx-jdbc-client with Apache License 2.0 6 votes vote down vote up
public void fillStatement(PreparedStatement statement, JsonArray in) throws SQLException {
  if (in == null) {
    in = EMPTY;
  }

  for (int i = 0; i < in.size(); i++) {
    Object value = in.getValue(i);

    if (value != null) {
      if (value instanceof String) {
        statement.setObject(i + 1, optimisticCast((String) value));
      } else {
        statement.setObject(i + 1, value);
      }
    } else {
      statement.setObject(i + 1, null);
    }
  }
}
 
Example 5
Source File: Artemis.java    From enmasse with Apache License 2.0 6 votes vote down vote up
public Set<String> getQueueNames() throws TimeoutException {
    log.info("Retrieving queue names for broker {}", syncRequestClient.getRemoteContainer());
    Message response = doOperation("broker", "getQueueNames");

    Set<String> queues = new LinkedHashSet<>();
    JsonArray payload = new JsonArray((String)((AmqpValue)response.getBody()).getValue());
    for (int i = 0; i < payload.size(); i++) {
        JsonArray inner = payload.getJsonArray(i);
        for (int j = 0; j < inner.size(); j++) {
            String queueName = inner.getString(j);
            if (!queueName.equals(syncRequestClient.getReplyTo())) {
                queues.add(queueName);
            }
        }
    }
    return queues;
}
 
Example 6
Source File: MongoClientImpl.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
private AggregatePublisher<JsonObject> doAggregate(final String collection, final JsonArray pipeline, final AggregateOptions aggregateOptions) {
  requireNonNull(collection, "collection cannot be null");
  requireNonNull(pipeline, "pipeline cannot be null");
  requireNonNull(aggregateOptions, "aggregateOptions cannot be null");
  final MongoCollection<JsonObject> coll = getCollection(collection);
  final List<Bson> bpipeline = new ArrayList<>(pipeline.size());
  pipeline.getList().forEach(entry -> bpipeline.add(wrap(JsonObject.mapFrom(entry))));
  AggregatePublisher<JsonObject> aggregate = coll.aggregate(bpipeline, JsonObject.class);

  if (aggregateOptions.getBatchSize() != -1) {
    aggregate.batchSize(aggregateOptions.getBatchSize());
  }
  if (aggregateOptions.getMaxTime() > 0) {
    aggregate.maxTime(aggregateOptions.getMaxTime(), TimeUnit.MILLISECONDS);
  }
  if (aggregateOptions.getAllowDiskUse() != null) {
    aggregate.allowDiskUse(aggregateOptions.getAllowDiskUse());
  }
  return aggregate;
}
 
Example 7
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 8
Source File: SpringConfigServerStore.java    From vertx-config with Apache License 2.0 5 votes vote down vote up
private void parseFromStandard(JsonObject body, Handler<AsyncResult<Buffer>> handler) {
  JsonArray sources = body.getJsonArray("propertySources");
  if (sources == null) {
    handler.handle(Future.failedFuture("Invalid configuration server response, property sources missing"));
  } else {
    JsonObject configuration = new JsonObject();
    for (int i = sources.size() - 1; i >= 0; i--) {
      JsonObject source = sources.getJsonObject(i);
      JsonObject content = source.getJsonObject("source");
      configuration = configuration.mergeIn(content, true);
    }
    handler.handle(Future.succeededFuture(Buffer.buffer(configuration.encode())));
  }
}
 
Example 9
Source File: Auth.java    From okapi with Apache License 2.0 5 votes vote down vote up
/**
 * Fake some module permissions.
 * Generates silly tokens with the module name as the tenant, and a list
 * of permissions as the user. These are still valid tokens, although it is
 * not possible to extract the user or tenant from them.
 */
private String moduleTokens(RoutingContext ctx) {
  String modPermJson = ctx.request().getHeader(XOkapiHeaders.MODULE_PERMISSIONS);
  logger.debug("test-auth: moduleTokens: trying to decode '{}'", modPermJson);
  HashMap<String, String> tokens = new HashMap<>();
  if (modPermJson != null && !modPermJson.isEmpty()) {
    JsonObject jo = new JsonObject(modPermJson);
    StringBuilder permstr = new StringBuilder();
    for (String mod : jo.fieldNames()) {
      JsonArray ja = jo.getJsonArray(mod);
      for (int i = 0; i < ja.size(); i++) {
        String p = ja.getString(i);
        if (permstr.length() > 0) {
          permstr.append(",");
        }
        permstr.append(p);
      }
      tokens.put(mod, token(mod, permstr.toString()));
    }
  }
  if (!tokens.isEmpty()) { // return also a 'clean' token
    tokens.put("_", ctx.request().getHeader(XOkapiHeaders.TOKEN));
  }
  String alltokens = Json.encode(tokens);
  logger.debug("test-auth: module tokens for {}: {}", modPermJson, alltokens);
  return alltokens;
}
 
Example 10
Source File: RestVerticle.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
static String acceptCheck(JsonArray l, String h) {
  String []hl = h.split(",");
  String hBest = null;
  for (int i = 0; i < hl.length; i++) {
    String mediaRange = hl[i].split(";")[0].trim();
    for (int j = 0; j < l.size(); j++) {
      String c = l.getString(j);
      if (mediaRange.compareTo("*/*") == 0 || c.equalsIgnoreCase(mediaRange)) {
        hBest = c;
        break;
      }
    }
  }
  return hBest;
}
 
Example 11
Source File: AndAuthorizationConverter.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
public static AndAuthorization decode(JsonObject json) throws IllegalArgumentException {
  Objects.requireNonNull(json);

  if (TYPE_AND_AUTHORIZATION.equals(json.getString(FIELD_TYPE))) {
    AndAuthorization result = AndAuthorization.create();
    JsonArray authorizations = json.getJsonArray(FIELD_AUTHORIZATIONS);
    for (int i = 0; i < authorizations.size(); i++) {
      JsonObject authorization = authorizations.getJsonObject(i);
      result.addAuthorization(AuthorizationConverter.decode(authorization));
    }
    return result;
  }
  return null;
}
 
Example 12
Source File: MultiSearchResponse.java    From vertx-elasticsearch-service with Apache License 2.0 5 votes vote down vote up
public MultiSearchResponse(JsonObject json) {
    super(json);
    final JsonArray jsonResponses = json.getJsonArray(JSON_FIELD_RESPONSES, new JsonArray());
    for (int i = 0; i < jsonResponses.size(); i++) {
        this.responses.add(new MultiSearchResponseItem(jsonResponses.getJsonObject(i)));
    }
}
 
Example 13
Source File: JsonArrayValueResolver.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolve(Object context, String name) {
  if (context instanceof JsonArray) {
    JsonArray jsonArray = ((JsonArray) context);
    if ("length".equals(name) || "size".equals(name)) {
      return jsonArray.size();
    }
    // NumberFormatException will bubble up and cause a HandlebarsException with line, row info
    Object value = jsonArray.getValue(Integer.valueOf(name));
    if (value != null) {
      return value;
    }
  }
  return UNRESOLVED;
}
 
Example 14
Source File: KeycloakAuthorizationImpl.java    From vertx-auth with Apache License 2.0 5 votes vote down vote up
private static void extractRealmRoles(JsonObject accessToken, Set<Authorization> authorizations) {
  JsonArray appRoles = accessToken
    .getJsonObject("realm_access", EMPTY_JSON)
    // locate the role list
    .getJsonArray("roles");

  if (appRoles != null && appRoles.size() >= 0) {
    for (Object el : appRoles) {
      // convert to the authorization type
      authorizations.add(RoleBasedAuthorization.create((String) el));
    }
  }
}
 
Example 15
Source File: ResourceMethodExtensionPlugin.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
private static void handleOverrides() throws IOException {
  String overrides = null;
  if(overrideFileExists){
    overrides = IOUtils.toString(ResourceMethodExtensionPlugin.class.getClassLoader().getResourceAsStream(
      "overrides/raml_overrides.json"), "UTF-8");
    if(overrides == null){
      log.info("No overrides/raml_overrides.json file found, continuing...");
      overrideFileExists = false;
      return;
    }
  }
  else{
    return;
  }
  if(overrideMap.isEmpty()){
    try {
      JsonObject jobj = new JsonObject(overrides);
      JsonArray jar = jobj.getJsonArray("overrides");
      int size = jar.size();
      for (int i = 0; i < size; i++) {
        JsonObject overrideEntry = jar.getJsonObject(i);
        String type = overrideEntry.getString("type");
        String url = overrideEntry.getString("url");
        overrideMap.put(url, type, overrideEntry);
      }
    } catch (Exception e1) {
      log.error(e1.getMessage(), e1);
    }
  }
}
 
Example 16
Source File: CacheBasedDeviceConnectionInfoTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Asserts the the given result JSON of the <em>getCommandHandlingAdapterInstances</em> method contains
 * an "adapter-instances" entry with the given device id and adapter instance id.
 */
private void assertGetInstancesResultMapping(final JsonObject resultJson, final String deviceId, final String adapterInstanceId) {
    assertNotNull(resultJson);
    final JsonArray adapterInstancesJson = resultJson.getJsonArray(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCES);
    assertNotNull(adapterInstancesJson);
    boolean entryFound = false;
    for (int i = 0; i < adapterInstancesJson.size(); i++) {
        final JsonObject entry = adapterInstancesJson.getJsonObject(i);
        if (deviceId.equals(entry.getString(DeviceConnectionConstants.FIELD_PAYLOAD_DEVICE_ID))) {
            entryFound = true;
            assertEquals(adapterInstanceId, entry.getString(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCE_ID));
        }
    }
    assertTrue(entryFound);
}
 
Example 17
Source File: KubeAuthApi.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
public TokenReview performTokenReview(String token) {
    if (client.isAdaptable(OkHttpClient.class)) {
        JsonObject body = new JsonObject();

        body.put("kind", "TokenReview");
        body.put("apiVersion", "authentication.k8s.io/v1");

        JsonObject spec = new JsonObject();
        spec.put("token", token);
        body.put("spec", spec);

        log.debug("Token review request: {}", body);
        JsonObject responseBody= doRawHttpRequest("/apis/authentication.k8s.io/v1/tokenreviews", "POST", body, false);
        log.debug("Token review response: {}", responseBody);
        JsonObject status = responseBody.getJsonObject("status");
        boolean authenticated = false;
        String userName = null;
        String userId = null;
        Set<String> groups = null;
        Map<String, List<String>> extra = null;
        if (status != null) {
            Boolean auth = status.getBoolean("authenticated");
            authenticated = auth == null ? false : auth;
            JsonObject user = status.getJsonObject("user");
            if (user != null) {
                userName = user.getString("username");
                userId = user.getString("uid");
                JsonArray groupArray = user.getJsonArray("groups");
                if (groupArray != null) {
                    groups = new HashSet<>();
                    for (int i = 0; i < groupArray.size(); i++) {
                        groups.add(groupArray.getString(i));
                    }
                }

                JsonObject extraObject = user.getJsonObject("extra");
                if (extraObject != null) {
                    extra = new HashMap<>();
                    for (String field : extraObject.fieldNames()) {
                        JsonArray extraValues = extraObject.getJsonArray(field);
                        List<String> extraValuesList = new ArrayList<>();
                        for (int i = 0; i < extraValues.size(); i++) {
                            extraValuesList.add(extraValues.getString(i));
                        }
                        extra.put(field, extraValuesList);
                    }
                }

            }
        }
        return new TokenReview(userName, userId, groups, extra, authenticated);
    } else {
        return new TokenReview(null, null, null, null, false);
    }
}
 
Example 18
Source File: CustomTypeAnnotator.java    From raml-module-builder with Apache License 2.0 4 votes vote down vote up
@Override
public void propertyField(JFieldVar field, JDefinedClass clazz, String propertyName, JsonNode propertyNode) {
  super.propertyField(field, clazz, propertyName, propertyNode);

  // Optionally annotates arrays with ElementsNotNull and ElementsPattern
  if(isArray(propertyNode)) {
    if(isItemsNotNull(propertyNode)) {
      field.annotate(ElementsNotNull.class);
    }
    Optional<String> pattern = getPattern(propertyNode);
    if(pattern.isPresent()) {
      field.annotate(ElementsPattern.class).param(REGEXP, pattern.get());
    }
  }

  JsonObject annotation = fields2annotate.get(propertyName);
  if(annotation != null){
    String annotationType = annotation.getString("type");
    JsonArray annotationMembers = annotation.getJsonArray("values");
    log.info("Attempting to annotate " + propertyName +
      " with " + annotationType);
    JClass annClazz = null;
    try {
      annClazz = new JCodeModel().ref(Class.forName(annotationType));
    } catch (ClassNotFoundException e) {
      log.error("annotation of type " + annotationType + " which is used on field "
          + propertyName + " can not be found (class not found)......");
      throw new RuntimeException(e);
    }
    //annotate the field with the requested annotation
    JAnnotationUse ann = field.annotate(annClazz);
    if(annotationMembers != null){
      //add members to the annotation if they exist
      //for example for Size, min and max
      int memberCount = annotationMembers.size();
      for (int i = 0; i < memberCount; i++) {
        //a member is something like {"max", 5}
        JsonObject member = annotationMembers.getJsonObject(i);
        member.getMap().entrySet().forEach( entry -> {
          String memberKey = entry.getKey();
          Object memberValue = entry.getValue();
          //find the type of the member value so we can create it correctly
          String valueType = memberValue.getClass().getName();
          if(valueType.toLowerCase().endsWith("string")){
            ann.param(memberKey, (String)memberValue);
          }
          else if(valueType.toLowerCase().endsWith("integer")){
            ann.param(memberKey, (Integer)memberValue);
          }
          else if(valueType.toLowerCase().endsWith("boolean")){
            ann.param(memberKey, (Boolean)memberValue);
          }
          else if(valueType.toLowerCase().endsWith("double")){
            ann.param(memberKey, (Double)memberValue);
          }
        });
      }
    }
  }
}
 
Example 19
Source File: MQTTBroker.java    From vertx-mqtt-broker with Apache License 2.0 4 votes vote down vote up
@Override
public void start() {
    try {
        JsonObject config = config();

        // 1 store x 1 broker
        deployStoreVerticle(1);

        // 2 bridge server
        if(config.containsKey("bridge_server")) {
            JsonObject bridgeServerConf = config.getJsonObject("bridge_server", new JsonObject());
            deployBridgeServerVerticle(bridgeServerConf, 1);
        }

        // 3 bridge client
        if(config.containsKey("bridge_client")) {
            JsonObject bridgeClientConf = config.getJsonObject("bridge_client", new JsonObject());
            deployBridgeClientVerticle(bridgeClientConf, 1);
        }

        // 4 authenticators
        if(config.containsKey("authenticators")) {
            JsonArray authenticators = config.getJsonArray("authenticators", new JsonArray());
            int size = authenticators.size();
            for(int i=0; i<size; i++) {
                JsonObject authConf = authenticators.getJsonObject(i);
                deployAuthorizationVerticle(authConf, 5);
            }
        }

        JsonArray brokers = config.getJsonArray("brokers");
        for(int i=0; i<brokers.size(); i++) {
            JsonObject brokerConf = brokers.getJsonObject(i);
            ConfigParser c = new ConfigParser(brokerConf);
            boolean wsEnabled = c.isWsEnabled();
            if (wsEnabled) {
                // MQTT over WebSocket
                startWebsocketServer(c);
            }
            else {
                // MQTT over TCP
                startTcpServer(c);
            }
            logger.info(
                    "Startd Broker ==> [port: " + c.getPort() + "]" +
                            " [" + c.getFeatursInfo() + "] " +
                            " [socket_idle_timeout:" + c.getSocketIdleTimeout() + "] "
            );
        }

    } catch(Exception e ) {
        logger.error(e.getMessage(), e);
    }

}
 
Example 20
Source File: BaseJsonArrayConverter.java    From konduit-serving with Apache License 2.0 3 votes vote down vote up
protected List<Map<FieldName, Object>> doTransformProcessConvertPmml(Schema schema, JsonArray jsonArray, TransformProcess transformProcess) {
    Schema outputSchema = transformProcess.getFinalSchema();

    if (!transformProcess.getInitialSchema().equals(schema)) {
        throw new IllegalArgumentException("Transform process specified, but does not match target input inputSchema");
    }


    List<Map<FieldName, Object>> ret = new ArrayList<>(jsonArray.size());
    List<FieldName> fieldNames = getNameRepresentationFor(outputSchema);

    ArrowWritableRecordBatch conversion = convert(schema, jsonArray, transformProcess);
    for (int i = 0; i < conversion.size(); i++) {
        List<Writable> recordToMap = conversion.get(i);
        Map<FieldName, Object> record = new LinkedHashMap();
        for (int j = 0; j < outputSchema.numColumns(); j++) {
            record.put(fieldNames.get(j), WritableValueRetriever.getUnderlyingValue(recordToMap.get(j)));

        }

        ret.add(record);
    }

    return ret;


}