Java Code Examples for javax.json.Json#createArrayBuilder()

The following examples show how to use javax.json.Json#createArrayBuilder() . 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: ListHandler.java    From gluon-samples with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 2
Source File: CustomersResource.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 3
Source File: RsJsonTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * RsJSON can build a big JSON response.
 * @throws IOException If some problem inside
 */
@Test
public void buildsBigJsonResponse() throws IOException {
    final int size = 100000;
    final JsonArrayBuilder builder = Json.createArrayBuilder();
    for (int idx = 0; idx < size; ++idx) {
        builder.add(
            Json.createObjectBuilder().add("number", "212 555-1234")
        );
    }
    MatcherAssert.assertThat(
        Json.createReader(
            new RsJson(builder.build()).body()
        ).readArray().size(),
        Matchers.equalTo(size)
    );
}
 
Example 4
Source File: MethodSideEffectDetailDescriptor.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
public JsonObjectBuilder toJson()
{
    JsonObjectBuilder builder = Json.createObjectBuilder();
    builder.add( "fragment", descriptor().modifierClass().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 5
Source File: OrchestratorResourceMockTest.java    From sample-acmegifts with Eclipse Public License 1.0 6 votes vote down vote up
private String buildGroupResponseObject(String name, String[] members, String[] occasions) {
  JsonObjectBuilder group = Json.createObjectBuilder();
  group.add(JSON_KEY_GROUP_NAME, name);

  JsonArrayBuilder membersArray = Json.createArrayBuilder();
  for (int i = 0; i < members.length; i++) {
    membersArray.add(members[i]);
  }
  group.add(JSON_KEY_MEMBERS_LIST, membersArray.build());

  JsonArrayBuilder occasionsArray = Json.createArrayBuilder();
  for (int i = 0; i < occasions.length; i++) {
    occasionsArray.add(occasions[i]);
  }
  group.add(JSON_KEY_OCCASIONS_LIST, occasionsArray.build());

  return group.build().toString();
}
 
Example 6
Source File: JsonVTypeBuilder.java    From diirt with MIT License 6 votes vote down vote up
public JsonVTypeBuilder  addListColumnValues(String string, VTable vTable) {
    JsonArrayBuilder b = Json.createArrayBuilder();
    for (int column = 0; column < vTable.getColumnCount(); column++) {
        Class<?> type = vTable.getColumnType(column);
        if (type.equals(String.class)) {
            @SuppressWarnings("unchecked")
            List<String> listString = (List<String>) vTable.getColumnData(column);
            b.add(fromListString(listString));
        } else if (type.equals(double.class) || type.equals(float.class) || type.equals(long.class) ||
                type.equals(int.class) || type.equals(short.class) || type.equals(byte.class)) {
            b.add(fromListNumber((ListNumber) vTable.getColumnData(column)));
        } else if (type.equals(Instant.class)) {
            @SuppressWarnings("unchecked")
            List<Instant> listTimestamp = (List<Instant>) vTable.getColumnData(column);
            b.add(fromListTimestamp(listTimestamp));
        } else {
            throw new IllegalArgumentException("Column type " + type.getSimpleName() + " not supported");
        }
    }
    add(string, b);
    return this;
}
 
Example 7
Source File: TopCDsEndpoint.java    From microprofile-samples with Apache License 2.0 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getTopCDs() {

    JsonArrayBuilder array = Json.createArrayBuilder();
    List<Integer> randomCDs = getRandomNumbers();
    for (Integer randomCD : randomCDs) {
        array.add(Json.createObjectBuilder().add("id", randomCD));
    }
    return array.build().toString();
}
 
Example 8
Source File: SystemInputJson.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Add any properties from the given value to the given JsonObjectBuilder.
 */
private static JsonObjectBuilder addProperties( JsonObjectBuilder builder, VarValueDef value)
  {
  JsonArrayBuilder properties = Json.createArrayBuilder();
  value.getProperties().forEach( property -> properties.add( property));
  JsonArray json = properties.build();

  if( !json.isEmpty())
    {
    builder.add( PROPERTIES_KEY, json);
    }

  return builder;
  }
 
Example 9
Source File: AbstractEmbeddedDBAccess.java    From jcypher with Apache License 2.0 5 votes vote down vote up
private void addRow(JsonBuilderContext builderContext, Map<String, Object> row, List<String> cols) {

		JsonObjectBuilder rowObject = Json.createObjectBuilder();
		JsonArrayBuilder restArray = Json.createArrayBuilder();
		JsonObjectBuilder graphObject = Json.createObjectBuilder();
		JsonArrayBuilder nodesArray = Json.createArrayBuilder();
		JsonArrayBuilder relationsArray = Json.createArrayBuilder();

		Object restObject;
		List<NodeHolder> nodes = new ArrayList<NodeHolder>();
		List<RelationHolder> relations = new ArrayList<RelationHolder>();
		for (int i = 0; i < cols.size(); i++) {
			restObject = null;
			String key = cols.get(i);
			Object val = row.get(key);
			restObject = buildRestObject(val, nodes, relations);
			if (restObject == null)
				writeLiteralValue(val, restArray);
			else if (restObject instanceof JsonObjectBuilder)
				restArray.add((JsonObjectBuilder) restObject);
			else if (restObject instanceof JsonArrayBuilder)
				restArray.add((JsonArrayBuilder) restObject);
		}

		Collections.sort(nodes);
		Collections.sort(relations);
		for (NodeHolder nh : nodes) {
			nodesArray.add(nh.nodeObject);
		}
		for (RelationHolder rh : relations) {
			relationsArray.add(rh.relationObject);
		}

		rowObject.add("rest", restArray);
		graphObject.add("nodes", nodesArray);
		graphObject.add("relationships", relationsArray);
		rowObject.add("graph", graphObject);
		builderContext.dataArrays.get(builderContext.dataArrays.size() - 1).add(rowObject);
	}
 
Example 10
Source File: Group.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create a JSON string based on the content of this group
 *
 * @return - A JSON string with the content of this group
 */
public String getJson() {
  JsonObjectBuilder group = Json.createObjectBuilder();
  group.add(JSON_KEY_GROUP_ID, id);
  group.add(JSON_KEY_GROUP_NAME, name);

  JsonArrayBuilder membersArray = Json.createArrayBuilder();
  for (int i = 0; i < members.length; i++) {
    membersArray.add(members[i]);
  }
  group.add(JSON_KEY_MEMBERS_LIST, membersArray.build());

  return group.build().toString();
}
 
Example 11
Source File: MocoServerConfigWriter.java    From tcases with MIT License 5 votes vote down vote up
/**
 * Returns a JSON object that represents expectations for the given request cases.
 */
private JsonArray expectedConfigs( RequestTestDef requestCases)
  {
  JsonArrayBuilder expected = Json.createArrayBuilder();

  requestCases.getRequestCases().stream()
    .filter( rc -> !rc.isFailure())
    .forEach( rc -> expected.add( expectedConfig( rc)));
  
  return expected.build();
  }
 
Example 12
Source File: SystemInputJson.java    From tcases with MIT License 5 votes vote down vote up
public void visit( AllOf condition)
{
JsonArrayBuilder conditions = Json.createArrayBuilder();
toStream( condition.getConditions()).forEach( c -> conditions.add( toJson( c)));

json_ =
  Json.createObjectBuilder()
  .add( ALL_OF_KEY, conditions)
  .build();
}
 
Example 13
Source File: Tuple.java    From KITE with Apache License 2.0 5 votes vote down vote up
/**
 * Gets client array builder.
 *
 * @return the client array builder
 */
@Transient
public JsonArrayBuilder getClientArrayBuilder() {
  JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
  for (Client client : this.clients) {
    arrayBuilder.add(client.buildJsonObjectBuilder());
  }
  return arrayBuilder;
}
 
Example 14
Source File: CargoMonitoringService.java    From CargoTracker-J12015 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 15
Source File: GraphCreator.java    From visualee with Apache License 2.0 5 votes vote down vote up
static JsonArrayBuilder buildJSONLinks(DependencyFilter filter) {
   JsonArrayBuilder linksArray = Json.createArrayBuilder();
   int value = 1;
   Set<JavaSource> relevantClasses = DependencyContainer.getInstance().getFilteredJavaSources(filter);
   for (JavaSource javaSource : relevantClasses) {
      for (Dependency d : DependencyContainer.getInstance().getDependencies(javaSource)) {
         DependencyType type = d.getDependencyType();
         if (filter == null
                 || (relevantClasses.contains(d.getJavaSourceTo()) && filter.contains(type))) {
            int source = d.getJavaSourceFrom().getId();
            int target = d.getJavaSourceTo().getId();
            JsonObjectBuilder linksBuilder = Json.createObjectBuilder();
            if (DependencyType.isInverseDirection(type)) {
               linksBuilder.add("source", source);
               linksBuilder.add("target", target);
            } else {
               linksBuilder.add("source", target);
               linksBuilder.add("target", source);
            }
            linksBuilder.add("value", value);
            linksBuilder.add("type", type.toString());
            linksArray.add(linksBuilder);
         }
      }
   }
   return linksArray;
}
 
Example 16
Source File: CommunicationManager.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * getThingDescriptions - Return all pages of the thing descriptions of IoT object(s).
 * 
 * @param sourceObjectId 
 * 
 * @return The list of thing descriptions 
 */
public Representation getThingDescriptions(String sourceObjectId) {
	
	if (sourceObjectId == null || sourceObjectId.isEmpty()) {
		logger.warning("Method parameter sourceObjectId can't be null nor empty.");
		
		return null;
	}
	
	JsonObjectBuilder mainObjectBuilder = Json.createObjectBuilder();
	JsonArrayBuilder mainArrayBuilder = Json.createArrayBuilder();
	
	Representation r = null;
	int i = 0;
	
	do {
		
		r = getThingDescriptions(sourceObjectId, i++);
		
		if (r == null) {
			break;
		}
		
		JsonArray tds = parseThingDescriptionsFromRepresentation(r);
		tds.forEach(item -> {
			mainArrayBuilder.add(item);
		});
	}
	while (true);
	
	mainObjectBuilder.add(ATTR_TDS, mainArrayBuilder);
	JsonObject json = mainObjectBuilder.build();
	
	return new JsonRepresentation(json.toString());
}
 
Example 17
Source File: TestClass10.java    From jaxrs-analyzer with Apache License 2.0 4 votes vote down vote up
@javax.ws.rs.GET public javax.json.JsonArray method() {
    JsonArrayBuilder builder = Json.createArrayBuilder();
    final List<String> names = new LinkedList<>();
    names.stream().map(converter::convert).forEach(builder::add);
    return builder.build();
}
 
Example 18
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 19
Source File: Objects.java    From vicinity-gateway-api with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Goes through the object's roster and creates a JSON from the visible records.
 * 
 * @return JSON representation of the list. 
 */
private Representation getObjects(){
	
	CommunicationManager communicationManager = (CommunicationManager) getContext().getAttributes().get(Api.CONTEXT_COMMMANAGER);
	
	Set<String> rosterObjects = communicationManager.getRosterEntriesForObject(
						getRequest().getChallengeResponse().getIdentifier());
	
	JsonObjectBuilder mainObjectBuilder = Json.createObjectBuilder();
	JsonArrayBuilder mainArrayBuilder = Json.createArrayBuilder();
	
	
	for (String entry : rosterObjects) {
		
		mainArrayBuilder.add(
					Json.createObjectBuilder().add(ATTR_OID, entry)
				);
	}
	
	mainObjectBuilder.add(ATTR_OBJECTS, mainArrayBuilder);

	return new JsonRepresentation(mainObjectBuilder.build().toString());
}
 
Example 20
Source File: Application.java    From camel-k-runtime with Apache License 2.0 4 votes vote down vote up
private JsonArrayBuilder extractComponents() {
    JsonArrayBuilder answer = Json.createArrayBuilder();
    context.getComponentNames().forEach(answer::add);

    return answer;
}