Java Code Examples for javax.json.JsonArrayBuilder#build()

The following examples show how to use javax.json.JsonArrayBuilder#build() . 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: MongoDbResource.java    From camel-quarkus with Apache License 2.0 7 votes vote down vote up
@GET
@Path("/collection/{collectionName}")
@Produces(MediaType.APPLICATION_JSON)
@SuppressWarnings("unchecked")
public JsonArray getCollection(@PathParam("collectionName") String collectionName) {
    JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();

    MongoIterable<Document> iterable = producerTemplate.requestBody(
            "mongodb:camelMongoClient?database=test&collection=" + collectionName
                    + "&operation=findAll&dynamicity=true&outputType=MongoIterable",
            null, MongoIterable.class);

    MongoCursor<Document> iterator = iterable.iterator();
    while (iterator.hasNext()) {
        Document document = iterator.next();
        JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
        objectBuilder.add("message", (String) document.get("message"));
        arrayBuilder.add(objectBuilder.build());
    }

    return arrayBuilder.build();
}
 
Example 2
Source File: generateFido2PreauthenticateChallenge.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 3
Source File: generateFido2PreregisterChallenge_v1.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 4
Source File: RequestCaseJson.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the JSON object that represents the given request case.
 */
private static JsonObject toJson( RequestCase requestCase)
  {
  JsonObjectBuilder builder = Json.createObjectBuilder();

  builder.add( ID, requestCase.getId());
  Optional.ofNullable( requestCase.getName()).ifPresent( name -> builder.add( NAME, name));
  Optional.ofNullable( requestCase.getServer()).ifPresent( server -> builder.add( SERVER, server.toString()));
  Optional.ofNullable( requestCase.getVersion()).ifPresent( version -> builder.add( VERSION, version));
  Optional.ofNullable( requestCase.getApi()).ifPresent( api -> builder.add( API, api));
  Optional.ofNullable( requestCase.getPath()).ifPresent( path -> builder.add( PATH, path));
  Optional.ofNullable( requestCase.getOperation()).ifPresent( op -> builder.add( OPERATION, op));

  JsonArrayBuilder paramBuilder = Json.createArrayBuilder();
  toStream( requestCase.getParams()).forEach( paramData -> paramBuilder.add( toJson( paramData)));
  JsonArray params = paramBuilder.build();
  if( !params.isEmpty())
    {
    builder.add( PARAMETERS, params);
    }
  
  Optional.ofNullable( requestCase.getBody()).ifPresent( body -> builder.add( BODY, toJson( body)));
  Optional.ofNullable( requestCase.getInvalidInput()).ifPresent( invalidInput -> builder.add( INVALID_INPUT, invalidInput));
  
  return builder.build();
  }
 
Example 5
Source File: Catalog.java    From cxf with Apache License 2.0 6 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
public JsonArray getBooks() throws IOException {
    final IndexReader reader = DirectoryReader.open(directory);
    final IndexSearcher searcher = new IndexSearcher(reader);
    final JsonArrayBuilder builder = Json.createArrayBuilder();

    try {
        final Query query = new MatchAllDocsQuery();

        for (final ScoreDoc scoreDoc: searcher.search(query, 1000).scoreDocs) {
            final DocumentStoredFieldVisitor fieldVisitor =
                new DocumentStoredFieldVisitor(LuceneDocumentMetadata.SOURCE_FIELD);

            reader.document(scoreDoc.doc, fieldVisitor);
            builder.add(fieldVisitor
                    .getDocument()
                    .getField(LuceneDocumentMetadata.SOURCE_FIELD)
                    .stringValue());
        }

        return builder.build();
    } finally {
        reader.close();
    }
}
 
Example 6
Source File: ListProducer.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@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 7
Source File: JavaxJsonCollectionSerializationTest.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
@Test
public void deserializeJsonArrayOfEntryObjectsAsMapWithStringKeys()
{
    JsonObjectBuilder fooEntryBuilder = jsonFactories.builderFactory().createObjectBuilder();
    fooEntryBuilder.add( "key", "foo" );
    fooEntryBuilder.add( "value", "bar" );
    JsonObject fooEntry = fooEntryBuilder.build();

    JsonObjectBuilder bazEntryBuilder = jsonFactories.builderFactory().createObjectBuilder();
    bazEntryBuilder.add( "key", "baz" );
    bazEntryBuilder.add( "value", "bazar" );
    JsonObject bazEntry = bazEntryBuilder.build();

    JsonArrayBuilder arrayBuilder = jsonFactories.builderFactory().createArrayBuilder();
    arrayBuilder.add( fooEntry );
    arrayBuilder.add( bazEntry );
    JsonArray jsonArray = arrayBuilder.build();

    MapType mapType = MapType.of( ValueType.STRING, ValueType.STRING );
    Map<String, String> map = jsonSerialization.fromJson( module, mapType, jsonArray );

    assertThat( map.get( "foo" ), equalTo( "bar" ) );
    assertThat( map.get( "baz" ), equalTo( "bazar" ) );
}
 
Example 8
Source File: JsonUtils.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
private static JsonArray toJsonArray(Collection<?> collection) {
    JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();

    for (Object element : collection) {
        if (element instanceof String) {
            arrayBuilder.add(element.toString());
        } else if (element == null) {
            arrayBuilder.add(JsonValue.NULL);
        } else {
            JsonValue jvalue = wrapValue(element);
            arrayBuilder.add(jvalue);
        }
    }

    return arrayBuilder.build();
}
 
Example 9
Source File: CargoMonitoringService.java    From pragmatic-microservices-lab with MIT License 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
public JsonArray getAllCargo() {
    List<Cargo> cargos = cargoRepository.findAll();

    JsonArrayBuilder builder = Json.createArrayBuilder();

    for (Cargo cargo : cargos) {
        builder.add(Json.createObjectBuilder()
                .add("trackingId", cargo.getTrackingId().getIdString())
                .add("routingStatus", cargo.getDelivery()
                        .getRoutingStatus().toString())
                .add("misdirected", cargo.getDelivery().isMisdirected())
                .add("transportStatus", cargo.getDelivery()
                        .getTransportStatus().toString())
                .add("atDestination", cargo.getDelivery()
                        .isUnloadedAtDestination())
                .add("origin", cargo.getOrigin().getUnLocode().getIdString())
                .add("lastKnownLocation",
                        cargo.getDelivery().getLastKnownLocation().getUnLocode().getIdString().equals("XXXXX")
                                ? "Unknown"
                                : cargo.getDelivery().getLastKnownLocation().getUnLocode().getIdString())
        );
    }

    return builder.build();
}
 
Example 10
Source File: GeneratorSetJson.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns the JSON object that represents the given combiner.
 */
private static JsonStructure toJson( TupleCombiner combiner)
  {
  JsonObjectBuilder builder = Json.createObjectBuilder();

  builder.add( TUPLES_KEY, combiner.getTupleSize());

  JsonArrayBuilder includeBuilder = Json.createArrayBuilder();
  Arrays.stream( combiner.getIncluded()).forEach( var -> includeBuilder.add( var));
  JsonArray include = includeBuilder.build();
  if( !include.isEmpty())
    {
    builder.add( INCLUDE_KEY, include);
    }

  JsonArrayBuilder excludeBuilder = Json.createArrayBuilder();
  Arrays.stream( combiner.getExcluded()).forEach( var -> excludeBuilder.add( var));
  JsonArray exclude = excludeBuilder.build();
  if( !exclude.isEmpty())
    {
    builder.add( EXCLUDE_KEY, exclude);
    }

  JsonArrayBuilder onceBuilder = Json.createArrayBuilder();
  toStream( combiner.getOnceTuples()).forEach( tuple -> onceBuilder.add( toJson( tuple)));
  JsonArray once = onceBuilder.build();
  if( !once.isEmpty())
    {
    builder.add( ONCE_KEY, once);
    }

  return builder.build();
  }
 
Example 11
Source File: JsonUtil.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public static JsonArray toJsonArray(List<String> strings) {
   JsonArrayBuilder array = JsonLoader.createArrayBuilder();
   if (strings != null) {
      for (String connector : strings) {
         array.add(connector);
      }
   }
   return array.build();
}
 
Example 12
Source File: CatalogStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
public JsonArray scan() throws IOException {
    final JsonArrayBuilder builder = Json.createArrayBuilder();

    for (final Map.Entry<String, String> entry: books.entrySet()) {
        builder.add(Json.createObjectBuilder()
            .add("id", entry.getKey())
            .add("title", entry.getValue())
        );
    }

    return builder.build();
}
 
Example 13
Source File: ExecutionErrorsService.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private JsonArray toJsonArray(List<?> list) {
    JsonArrayBuilder arrayBuilder = jsonBuilderFactory.createArrayBuilder();
    for (Object o : list) {
        if (o != null)
            arrayBuilder.add(o.toString());
    }
    return arrayBuilder.build();
}
 
Example 14
Source File: Occasion.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
public static JsonArray dboListToJsonArray(List<DBObject> dboList) {
  String method = "dboListToJsonArray";
  logger.entering(clazz, method, dboList);

  JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
  for (Object dbo : ListUtils.emptyIfNull(dboList)) {
    JsonObject json = new Occasion((DBObject) dbo).toJson();
    arrayBuilder.add(json);
  }
  JsonArray returnArray = arrayBuilder.build();

  logger.exiting(clazz, method, returnArray);
  return returnArray;
}
 
Example 15
Source File: JavaxJsonCollectionSerializationTest.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Test
public void dontKnowHowToDeserializeMapWithMixedKeys()
{
    JsonObjectBuilder fooKeyBuilder = jsonFactories.builderFactory().createObjectBuilder();
    fooKeyBuilder.add( "foo", "foo" );
    fooKeyBuilder.add( "_type", SomeValue.class.getName() );
    JsonObject fooKey = fooKeyBuilder.build();

    JsonObjectBuilder fooEntryBuilder = jsonFactories.builderFactory().createObjectBuilder();
    fooEntryBuilder.add( "key", fooKey );
    fooEntryBuilder.add( "value", "bar" );
    JsonObject fooEntry = fooEntryBuilder.build();

    JsonObjectBuilder bazEntryBuilder = jsonFactories.builderFactory().createObjectBuilder();
    bazEntryBuilder.add( "key", "baz" );
    bazEntryBuilder.add( "value", "bazar" );
    JsonObject bazEntry = bazEntryBuilder.build();

    JsonArrayBuilder arrayBuilder = jsonFactories.builderFactory().createArrayBuilder();
    arrayBuilder.add( fooEntry );
    arrayBuilder.add( bazEntry );
    JsonArray jsonArray = arrayBuilder.build();

    MapType mapType = MapType.of( ValueType.OBJECT, ValueType.STRING );
    try
    {
        jsonSerialization.fromJson( module, mapType, jsonArray );
        fail( "Should have failed deserialization" );
    }
    catch( SerializationException ex )
    {
        assertThat( ex.getMessage(),
                    equalTo( "Don't know how to deserialize java.lang.Object from \"baz\"" ) );
    }
}
 
Example 16
Source File: MessageEncoder.java    From Hands-On-Cloud-Native-Applications-with-Java-and-Quarkus with MIT License 5 votes vote down vote up
@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 17
Source File: CargoMonitoringService.java    From pragmatic-microservices-lab with MIT License 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
public JsonArray getAllCargo() {
    List<Cargo> cargos = cargoRepository.findAll();

    JsonArrayBuilder builder = Json.createArrayBuilder();

    for (Cargo cargo : cargos) {
        builder.add(Json.createObjectBuilder()
                .add("trackingId", cargo.getTrackingId().getIdString())
                .add("routingStatus", cargo.getDelivery()
                        .getRoutingStatus().toString())
                .add("misdirected", cargo.getDelivery().isMisdirected())
                .add("transportStatus", cargo.getDelivery()
                        .getTransportStatus().toString())
                .add("atDestination", cargo.getDelivery()
                        .isUnloadedAtDestination())
                .add("origin", cargo.getOrigin().getUnLocode().getIdString())
                .add("lastKnownLocation",
                        cargo.getDelivery().getLastKnownLocation().getUnLocode().getIdString().equals("XXXXX")
                                ? "Unknown"
                                : cargo.getDelivery().getLastKnownLocation().getUnLocode().getIdString())
        );
    }

    return builder.build();
}
 
Example 18
Source File: RequestCaseJson.java    From tcases with MIT License 4 votes vote down vote up
public void visit( ArrayValue<?> data)
{
JsonArrayBuilder builder = Json.createArrayBuilder();
data.getValue().stream().forEach( item -> builder.add( RequestCaseJson.toJson( item)));
json_ = builder.build();
}
 
Example 19
Source File: TestClass43.java    From jaxrs-analyzer with Apache License 2.0 4 votes vote down vote up
public javax.json.JsonArray buildJsonArray() {
    final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
    tasks.stream().map(Object::toString).forEach(arrayBuilder::add);
    return arrayBuilder.build();
}
 
Example 20
Source File: NetworkConfigTest.java    From fabric-sdk-java with Apache License 2.0 3 votes vote down vote up
private static JsonArray createJsonArray(String... elements) {

        JsonArrayBuilder builder = Json.createArrayBuilder();

        for (String ele : elements) {
            builder.add(ele);
        }

        return builder.build();
    }