Java Code Examples for javax.json.JsonArrayBuilder

The following examples show how to use javax.json.JsonArrayBuilder. These examples are extracted from open source projects. 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
private JsonArray generateAllowCredentialsList(AuthenticationPolicyOptions authOp, Collection<FidoKeys> fks) throws SKFEException {
        JsonArrayBuilder allowCredentialsBuilder = Json.createArrayBuilder();

        for (FidoKeys fk : fks) {
            if (authOp.getAllowCredentials() != null &&
                    authOp.getAllowCredentials().equalsIgnoreCase(skfsConstants.POLICY_CONST_ENABLED)) {
                if (fk.getFidoProtocol().equals(skfsConstants.FIDO_PROTOCOL_VERSION_2_0)) {
                    JsonObjectBuilder excludedCredential = Json.createObjectBuilder()
                            .add(skfsConstants.FIDO2_ATTR_TYPE, "public-key") //TODO fix this hardcoded assumption
                            .add(skfsConstants.FIDO2_ATTR_ID, decryptKH(fk.getKeyhandle()))
                            .add(skfsConstants.FIDO2_ATTR_ALG, RegistrationSettings
                                    .parse(fk.getRegistrationSettings(), fk.getRegistrationSettingsVersion()).getAlg());

                    //TODO transports is just an hint so we are not adding it right now. Fix this
//                    if (fk.getTransports() != null) {
//                        excludedCredential.add(skfsConstants.FIDO2_ATTR_TRANSPORTS, skfsCommon.getTransportJson(fk.getTransports().intValue()));
//                    }

                    allowCredentialsBuilder.add(excludedCredential);
                }
                else{}   //TODO use APPID extension if false
            }
        }
        return allowCredentialsBuilder.build();
    }
 
Example 2
private JsonArray generateExcludeCredentialsList(RegistrationPolicyOptions regOp,
            Long did, String username) throws SKFEException{
        JsonArrayBuilder excludeCredentialsBuilder = Json.createArrayBuilder();

        if(regOp.getExcludeCredentials().equalsIgnoreCase(skfsConstants.POLICY_CONST_ENABLED)){
            Collection<FidoKeys> fks = getkeybean.getByUsernameStatus(did, username, "Active");
            for(FidoKeys fk: fks){
                if(fk.getFidoProtocol().equals(skfsConstants.FIDO_PROTOCOL_VERSION_2_0)){
                    JsonObjectBuilder excludedCredential = Json.createObjectBuilder()
                            .add(skfsConstants.FIDO2_ATTR_TYPE, "public-key") //TODO fix this hardcoded assumption
                            .add(skfsConstants.FIDO2_ATTR_ID, decryptKH(fk.getKeyhandle()))
                            .add(skfsConstants.FIDO2_ATTR_ALG, RegistrationSettings
                                    .parse(fk.getRegistrationSettings(), fk.getRegistrationSettingsVersion()).getAlg());

                    //TODO transports are a hint that not all browsers support atm.
//                    if(fk.getTransports() != null){
//                        excludedCredential.add(skfsConstants.FIDO2_ATTR_TRANSPORTS, skfsCommon.getTransportJson(fk.getTransports().intValue()));
//                    }

                    excludeCredentialsBuilder.add(excludedCredential);
                }
            }
        }
        return excludeCredentialsBuilder.build();
    }
 
Example 3
/**
 * Returns a JSON encoded array string representing this object.
 * @return returns the current array as a JSON encode string
 */
@Override
public String toString(){
    JsonArrayBuilder ab = Json.createArrayBuilder();
    
    for (int x = 0; x < list.size(); ++x){
        JsonValue value = list.get(x);
        if (value instanceof EcommerceItem){
            ab.add(((EcommerceItem)value).toJsonArray());
        }
        else{
            ab.add(value);
        }
    }
    
    return ab.build().toString();
}
 
Example 4
@Override
public JsonValue createValue(JsonSchemaMappingCompiler<T, C> mappingCompiler, String item) {
	final JsonArrayBuilder arrayBuilder = mappingCompiler.getJsonBuilderFactory().createArrayBuilder();
	final String[] values = item.split(" ");
	for (String value : values) {
		if (!value.isEmpty()) {
			JsonValue v = itemTypeInfoProducer.createValue(mappingCompiler, value);
			if (v == null) {
				return null;
			} else {
				arrayBuilder.add(v);
			}
		}
	}
	return arrayBuilder.build();
}
 
Example 5
Source Project: attic-polygene-java   Source File: MixinDetailDescriptor.java    License: Apache License 2.0 6 votes vote down vote up
public JsonObjectBuilder toJson()
{
    JsonObjectBuilder builder = Json.createObjectBuilder();
    builder.add( "mixin", descriptor().mixinClass().getName() );
    JsonObjectBuilder injectionBuilder = Json.createObjectBuilder();
    {
        JsonArrayBuilder constructorsBuilder = Json.createArrayBuilder();
        constructors().forEach( constructor -> constructorsBuilder.add( constructor.toJson() ) );
        builder.add( "constructors", constructorsBuilder );
    }
    builder.add( "injection", injectionBuilder );
    {
        JsonArrayBuilder injectedFieldsBuilder = Json.createArrayBuilder();
        injectedFields().forEach( field -> injectedFieldsBuilder.add( field.toJson() ) );
        injectionBuilder.add( "fields", injectedFieldsBuilder );
    }
    {
        JsonArrayBuilder injectedMethodsBuilder = Json.createArrayBuilder();
        injectedMethods().forEach( method -> injectedMethodsBuilder.add( method.toJson() ) );
        injectionBuilder.add( "methods", injectedMethodsBuilder );
    }

    return builder;
}
 
Example 6
private JsonObject toJson(Label label)
{
    JsonArrayBuilder supportedJsonArrayBuilder = Json.createArrayBuilder();
    JsonArrayBuilder unsuitableJsonArrayBuilder = Json.createArrayBuilder();
    JsonArrayBuilder neutralJsonArrayBuilder = Json.createArrayBuilder();

    label.getSupported().forEach(supportedJsonArrayBuilder::add);
    label.getUnsuitable().forEach(unsuitableJsonArrayBuilder::add);
    label.getNeutral().forEach(neutralJsonArrayBuilder::add);

    return Json.createObjectBuilder()
                .add("id", label.getId())
                .add("name", label.getName())
                .add("description", label.getDescription() != null ? label.getDescription() : "")
                .add("supported", supportedJsonArrayBuilder.build())
                .add("unsuitable", unsuitableJsonArrayBuilder.build())
                .add("neutral", neutralJsonArrayBuilder.build())
                .build();
}
 
Example 7
Source Project: KITE   Source File: Result.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets json.
 *
 * @return the json
 */
public JsonObject getJson() {

  JsonArrayBuilder subTestResults = Json.createArrayBuilder();
  for (SubTest subTest : this) {
    subTestResults.add(subTest.getJson());
    if (subTest.getActualResult().equals("PASS") || subTest.getActualResult().equals("OK")) {
      sucessCount++;
    }
  }

  return Json.createObjectBuilder()
      .add("test", test)
      .add("status", status)
      .add("duration", duration)
      .add("subtests", subTestResults)
      .build();
}
 
Example 8
/**
 * Called by Gluon CloudLink when a list with the specified identifier is retrieved for the first time from the
 * client application, but does noet yet exist in Gluon CloudLink. This implementation will return all the Notes
 * from the database to Gluon CloudLink as a JSON Array in the correct format.
 *
 * The format that Gluon CloudLink expects, is a JSON Array where each element is a JSON Object with the following
 * two keys:
 * <ul>
 *     <li><code>id</code>: the identifier of the Note</li>
 *     <li><code>payload</code>: the JSON payload of the Note object, as a String</li>
 * </ul>
 *
 * @param listIdentifier the identifier of the list that is being retrieved from Gluon CloudLink
 * @return a string representation of the constructed JSON Array
 */
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON + "; " + CHARSET)
public String getList(@PathParam("listIdentifier") String listIdentifier) {
    LOG.log(Level.INFO, "Return list " + listIdentifier);
    JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
    List<Note> notes = noteService.findAll();
    notes.stream().map(note -> Json.createObjectBuilder()
            .add("id", note.getId())
            .add("payload", Json.createObjectBuilder()
                .add("title", note.getTitle())
                .add("text", note.getText())
                .add("creationDate", note.getCreationDate())
                .build().toString())
            .build())
        .forEach(jsonArrayBuilder::add);
    return jsonArrayBuilder.build().toString();
}
 
Example 9
Source Project: FHIR   Source File: FHIRSwaggerGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private static void generateSearchParameters(Class<?> modelClass, JsonArrayBuilder parameters) throws Exception {
    List<SearchParameter> searchParameters = new ArrayList<SearchParameter>(
            SearchUtil.getApplicableSearchParameters(modelClass.getSimpleName()));
    for (SearchParameter searchParameter : searchParameters) {
        JsonObjectBuilder parameter = factory.createObjectBuilder();
        String name = searchParameter.getName().getValue();
        if (name.startsWith("_")) {
            parameter.add("$ref", "#/parameters/" + name + "Param");
        } else {
            parameter.add("name", name);
            parameter.add("description", searchParameter.getDescription().getValue());
            parameter.add("in", "query");
            parameter.add("type", "string");
            parameter.add("required", false);
        }
        parameters.add(parameter);
    }
}
 
Example 10
Source Project: attic-polygene-java   Source File: LayerDetailDescriptor.java    License: Apache License 2.0 6 votes vote down vote up
public JsonObject toJson()
{
    JsonObjectBuilder builder = Json.createObjectBuilder();
    builder.add( "name", descriptor().name() );
    {
        JsonArrayBuilder modulesBuilder = Json.createArrayBuilder();
        modules().forEach( module -> modulesBuilder.add( module.toJson() ) );
        builder.add( "modules", modulesBuilder.build() );
    }

    {
        JsonArrayBuilder usedLayersBuilder = Json.createArrayBuilder();
        usedLayers().forEach( layer -> usedLayersBuilder.add( layer.descriptor().name() ) );
        builder.add( "usedLayers", usedLayersBuilder.build() );
    }

    {
        JsonArrayBuilder activatorsBuilder = Json.createArrayBuilder();
        activators().forEach( activator -> activatorsBuilder.add( activator.toJson() ) );
        builder.add( "activators", activatorsBuilder.build() );
    }

    return builder.build();
}
 
Example 11
Source Project: HAP-Java   Source File: AccessoryController.java    License: MIT License 6 votes vote down vote up
private CompletableFuture<JsonObject> toJson(Service service, int interfaceId) throws Exception {
  String shortType =
      service.getType().replaceAll("^0*([0-9a-fA-F]+)-0000-1000-8000-0026BB765291$", "$1");
  JsonObjectBuilder builder =
      Json.createObjectBuilder().add("iid", ++interfaceId).add("type", shortType);
  List<Characteristic> characteristics = service.getCharacteristics();
  Collection<CompletableFuture<JsonObject>> characteristicFutures =
      new ArrayList<>(characteristics.size());
  for (Characteristic characteristic : characteristics) {
    characteristicFutures.add(characteristic.toJson(++interfaceId));
  }

  return CompletableFuture.allOf(
          characteristicFutures.toArray(new CompletableFuture<?>[characteristicFutures.size()]))
      .thenApply(
          v -> {
            JsonArrayBuilder jsonCharacteristics = Json.createArrayBuilder();
            characteristicFutures.stream()
                .map(future -> future.join())
                .forEach(c -> jsonCharacteristics.add(c));
            builder.add("characteristics", jsonCharacteristics);
            return builder.build();
          });
}
 
Example 12
@Override
public String listAllSessionsAsJSON() throws Exception {
   if (AuditLogger.isEnabled()) {
      AuditLogger.listAllSessionsAsJSON(this.server);
   }
   checkStarted();

   clearIO();

   JsonArrayBuilder array = JsonLoader.createArrayBuilder();
   try {
      Set<ServerSession> sessions = server.getSessions();
      for (ServerSession sess : sessions) {
         buildSessionJSON(array, sess);
      }
   } finally {
      blockOnIO();
   }
   return array.build().toString();
}
 
Example 13
Source Project: jaxrs-analyzer   Source File: TestClass40.java    License: Apache License 2.0 6 votes vote down vote up
@javax.ws.rs.GET
public Response method() {
    BiFunction<JsonObjectBuilder, String, JsonObjectBuilder> function = JsonObjectBuilder::addNull;
    BinaryOperator<JsonArrayBuilder> anotherFunction = JsonArrayBuilder::add;

    JsonObjectBuilder builder = Json.createObjectBuilder();
    function.apply(builder, "test");

    JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
    JsonArrayBuilder anotherArrayBuilder = Json.createArrayBuilder();

    arrayBuilder.add("test1");
    anotherArrayBuilder.add("test2");
    anotherFunction.apply(arrayBuilder, anotherArrayBuilder);

    builder.add("array", arrayBuilder);

    return Response.ok(builder.build()).build();
}
 
Example 14
Source Project: fabric-sdk-java   Source File: HFCAIdentity.java    License: Apache License 2.0 6 votes vote down vote up
private JsonObject idToJsonObject(Set<String> filteredAttrs) {
    JsonObjectBuilder ob = Json.createObjectBuilder();
    ob.add("id", enrollmentID);
    ob.add("type", type);
    if (null != maxEnrollments) {
        ob.add("max_enrollments", maxEnrollments);
    }
    if (affiliation != null) {
        ob.add("affiliation", affiliation);
    }
    JsonArrayBuilder ab = Json.createArrayBuilder();
    for (Attribute attr : attrs) {
        if (!filteredAttrs.contains(attr.getName())) {
            ab.add(attr.toJsonObject());
        }
    }
    ob.add("attrs", ab.build());
    if (this.secret != null) {
        ob.add("secret", secret);
    }
    if (client.getCAName() != null) {
        ob.add(HFCAClient.FABRIC_CA_REQPROP, client.getCAName());
    }
    return ob.build();
}
 
Example 15
private String internaListUser(String username) throws Exception {
   PropertiesLoginModuleConfigurator config = getPropertiesLoginModuleConfigurator();
   Map<String, Set<String>> info = config.listUser(username);
   JsonArrayBuilder users = JsonLoader.createArrayBuilder();
   for (Entry<String, Set<String>> entry : info.entrySet()) {
      JsonObjectBuilder user = JsonLoader.createObjectBuilder();
      user.add("username", entry.getKey());
      JsonArrayBuilder roles = JsonLoader.createArrayBuilder();
      for (String role : entry.getValue()) {
         roles.add(role);
      }
      user.add("roles", roles);
      users.add(user);
   }
   return users.build().toString();
}
 
Example 16
public void buildSessionJSON(JsonArrayBuilder array, ServerSession sess) {
   JsonObjectBuilder obj = JsonLoader.createObjectBuilder().add("sessionID", sess.getName()).add("creationTime", sess.getCreationTime()).add("consumerCount", sess.getServerConsumers().size());

   if (sess.getValidatedUser() != null) {
      obj.add("principal", sess.getValidatedUser());
   }

   if (sess.getMetaData() != null) {
      final JsonObjectBuilder metadata = JsonLoader.createObjectBuilder();
      for (Entry<String, String> entry : sess.getMetaData().entrySet()) {
         metadata.add(entry.getKey(), entry.getValue());
      }
      obj.add("metadata", metadata);
   }

   array.add(obj);
}
 
Example 17
Source Project: jcypher   Source File: AbstractEmbeddedDBAccess.java    License: Apache License 2.0 6 votes vote down vote up
private void init(Node node) {
	JsonObjectBuilder nd = Json.createObjectBuilder();
	nd.add("id", String.valueOf(node.getId()));
	JsonArrayBuilder labels = Json.createArrayBuilder();
	Iterator<Label> lblIter = node.getLabels().iterator();
	boolean hasLabels = false;
	while (lblIter.hasNext()) {
		hasLabels = true;
		Label lab = lblIter.next();
		labels.add(lab.name());
	}
	if (hasLabels)
		nd.add("labels", labels);
	JsonObjectBuilder props = Json.createObjectBuilder();
	Iterator<String> pit = node.getPropertyKeys().iterator();
	while (pit.hasNext()) {
		String pKey = pit.next();
		Object pval = node.getProperty(pKey);
		writeLiteral(pKey, pval, props);
	}
	nd.add("properties", props);
	this.nodeObject = nd;
}
 
Example 18
Source Project: nifi   Source File: MetricsBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public JsonObject build(final boolean allowNullValues) {
    // builds JsonObject for individual metrics
    final MetricBuilder metricBuilder = new MetricBuilder(factory);
    metricBuilder.instanceId(instanceId).applicationId(applicationId).timestamp(timestamp).hostname(hostname);

    final JsonArrayBuilder metricArrayBuilder = factory.createArrayBuilder();

    for (Map.Entry<String,String> entry : metrics.entrySet()) {
        metricBuilder.metricName(entry.getKey()).metricValue(entry.getValue());
        metricArrayBuilder.add(metricBuilder.build(allowNullValues));
    }

    // add the array of metrics to a top-level json object
    final JsonObjectBuilder metricsBuilder = factory.createObjectBuilder();
    metricsBuilder.add(ROOT_JSON_ELEMENT, metricArrayBuilder);
    return metricsBuilder.build();
}
 
Example 19
/**
 * Adds a JSON encoded `filters` parameter.
 * @param filters Filters.
 */
private void addFilters(final Map<String, Iterable<String>> filters) {
    if (filters != null && !filters.isEmpty()) {
        final JsonObjectBuilder json = Json.createObjectBuilder();
        filters.forEach(
            (name, values) -> {
                final JsonArrayBuilder array = Json.createArrayBuilder();
                values.forEach(array::add);
                json.add(name, array);
            }
        );
        this.origin.addParameter("filters", json.build().toString());
    }


}
 
Example 20
Source Project: hugegraph   Source File: ExceptionFilter.java    License: Apache License 2.0 6 votes vote down vote up
public static String formatException(Throwable exception, boolean trace) {
    String clazz = exception.getClass().toString();
    String message = exception.getMessage() != null ?
                     exception.getMessage() : "";
    String cause = exception.getCause() != null ?
                   exception.getCause().toString() : "";

    JsonObjectBuilder json = Json.createObjectBuilder()
                                 .add("exception", clazz)
                                 .add("message", message)
                                 .add("cause", cause);

    if (trace) {
        JsonArrayBuilder traces = Json.createArrayBuilder();
        for (StackTraceElement i : exception.getStackTrace()) {
            traces.add(i.toString());
        }
        json.add("trace", traces);
    }

    return json.build().toString();
}
 
Example 21
Source Project: tcases   Source File: SystemInputJson.java    License: MIT License 6 votes vote down vote up
public void visit( Not condition)
{
ICondition[] conditions = IteratorUtils.toArray( condition.getConditions(), ICondition.class);

JsonObjectBuilder builder = Json.createObjectBuilder();
if( conditions.length > 1)
  {
  builder.add( NOT_KEY, toJson( new AnyOf( conditions)));
  }
else if( conditions[0].getClass().equals( ContainsAny.class))
  {
  // Special case: abbreviate "not:{hasAny:[...]}" as "hasNone:[...]".
  JsonArrayBuilder properties = Json.createArrayBuilder();
  toStream( ((ContainsAny) conditions[0]).getProperties()).forEach( property -> properties.add( property));
  builder.add( HAS_NONE_KEY, properties);
  }
else
  {
  builder.add( NOT_KEY, toJson( conditions[0]));
  }

json_ = builder.build();
}
 
Example 22
@PUT
@Path("batchadd/")
@Consumes(MediaType.APPLICATION_JSON)
public Response putUsers(JsonObject jsonEntity) {
	JsonArray jsonArray = jsonEntity.getJsonArray("customers");
	final JsonArrayBuilder result = Json.createArrayBuilder();
	jsonArray.forEach((jsonValue) -> {
		try {
			Customer c = createCustomer(jsonValue.asJsonObject());
			result.add(c.toJSon());
		} catch (ValidationException e) {
			result.add(Utils.errorAsJSon(e));
		}
	});
	return Response.accepted(result.build()).build();
}
 
Example 23
Source Project: component-runtime   Source File: RecordJsonMapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onFloatArray(final Schema.Entry entry, final Optional<Collection<Float>> array) {
    array
            .ifPresent(vs -> builder
                    .add(entry.getName(),
                            vs
                                    .stream()
                                    .collect(factory::createArrayBuilder, JsonArrayBuilder::add,
                                            JsonArrayBuilder::addAll)
                                    .build()));
}
 
Example 24
Source Project: activemq-artemis   Source File: ActiveMQAbstractView.java    License: Apache License 2.0 5 votes vote down vote up
public String getResultsAsJson(int page, int pageSize) {
   JsonObjectBuilder obj = JsonLoader.createObjectBuilder();
   JsonArrayBuilder array = JsonLoader.createArrayBuilder();
   collection = collection.stream().filter(getPredicate()).collect(Collectors.toList());
   for (T element : getPagedResult(page, pageSize)) {
      JsonObjectBuilder jsonObjectBuilder = toJson(element);
      //toJson() may return a null
      if (jsonObjectBuilder != null) {
         array.add(jsonObjectBuilder);
      }
   }
   obj.add("data", array);
   obj.add("count", collection.size());
   return obj.build().toString();
}
 
Example 25
Source Project: component-runtime   Source File: RecordConverters.java    License: Apache License 2.0 5 votes vote down vote up
private JsonArray toArray(final JsonBuilderFactory factory, final Function<Object, JsonValue> valueFactory,
        final Collection<?> collection) {
    final Collector<JsonValue, JsonArrayBuilder, JsonArray> collector = Collector
            .of(factory::createArrayBuilder, JsonArrayBuilder::add, JsonArrayBuilder::addAll,
                    JsonArrayBuilder::build);
    return collection.stream().map(valueFactory).collect(collector);
}
 
Example 26
@Override
public String encode(List<Customer> list) throws EncodeException {
    JsonArrayBuilder jsonArray = Json.createArrayBuilder();
    for(Customer c : list) {
        jsonArray.add(Json.createObjectBuilder()
                .add("Name", c.getName())
                .add("Surname", c.getSurname()));
    }
    JsonArray array = jsonArray.build();
    StringWriter buffer = new StringWriter();
    Json.createWriter(buffer).writeArray(array);
    return buffer.toString();
}
 
Example 27
Source Project: tutorials   Source File: BookResource.java    License: MIT License 5 votes vote down vote up
private JsonArray from(List<Book> books) {
    JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
    books.forEach(book -> {
        jsonArrayBuilder.add(from(book));
    });
    return jsonArrayBuilder.build();
}
 
Example 28
Source Project: camel-quarkus   Source File: CamelSupportResource.java    License: Apache License 2.0 5 votes vote down vote up
@Path("/describe")
@GET
@Produces(MediaType.APPLICATION_JSON)
public JsonObject describeMain() {
    JsonArrayBuilder routes = Json.createArrayBuilder();
    context.getRoutes().forEach(route -> routes.add(route.getId()));

    return Json.createObjectBuilder()
            .add("routes", routes)
            .build();
}
 
Example 29
@Override
public String listProducersInfoAsJSON() throws Exception {
   if (AuditLogger.isEnabled()) {
      AuditLogger.listProducersInfoAsJSON(this.server);
   }
   JsonArrayBuilder producers = JsonLoader.createArrayBuilder();

   for (ServerSession session : server.getSessions()) {
      session.describeProducersInfo(producers);
   }

   return producers.build().toString();
}
 
Example 30
Source Project: jaxrs-hypermedia   Source File: BooksResource.java    License: Apache License 2.0 5 votes vote down vote up
@GET
public JsonArray getBooks() {
    return bookStore.getBooks().stream()
            .map(b -> entityBuilder.buildBookTeaser(b, resourceUriBuilder.forBook(b, uriInfo)))
            .collect(Json::createArrayBuilder, JsonArrayBuilder::add, JsonArrayBuilder::add)
            .build();
}