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

The following examples show how to use javax.json.JsonArrayBuilder#add() . 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: RegistrationRequest.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
JsonObject toJsonObject() {
    JsonObjectBuilder ob = Json.createObjectBuilder();
    ob.add("id", enrollmentID);
    ob.add("type", type);
    if (this.secret != null) {
        ob.add("secret", secret);
    }
    if (null != maxEnrollments) {

        ob.add("max_enrollments", maxEnrollments);
    }
    if (affiliation != null) {
        ob.add("affiliation", affiliation);
    }

    JsonArrayBuilder ab = Json.createArrayBuilder();
    for (Attribute attr : attrs) {
        ab.add(attr.toJsonObject());
    }
    if (caName != null) {
        ob.add(HFCAClient.FABRIC_CA_REQPROP, caName);
    }
    ob.add("attrs", ab.build());
    return ob.build();
}
 
Example 2
Source File: ActiveMQServerControlImpl.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Override
public String getRolesAsJSON(final String addressMatch) throws Exception {
   if (AuditLogger.isEnabled()) {
      AuditLogger.getRolesAsJSON(this.server, addressMatch);
   }
   checkStarted();

   clearIO();
   try {
      JsonArrayBuilder json = JsonLoader.createArrayBuilder();
      Set<Role> roles = server.getSecurityRepository().getMatch(addressMatch);

      for (Role role : roles) {
         json.add(role.toJson());
      }
      return json.build().toString();
   } finally {
      blockOnIO();
   }
}
 
Example 3
Source File: CustomersResource.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
public JsonArray list() {
	JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
	for (Customer customer : DataAccess.getAllCustomers()) {
		// UriBuilder ub = uriInfo.getAbsolutePathBuilder();
		// URI userUri = ub.path(String.valueOf(customer.getCustomerId())).build();
		JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
		// Can't trust the transfer of longs, unfortunately.
		objectBuilder.add(Customer.KEY_CUSTOMER_ID, String.valueOf(customer.getId()));
		objectBuilder.add(Customer.KEY_FULL_NAME, customer.getFullName());
		objectBuilder.add(Customer.KEY_PHONE_NUMBER, customer.getPhoneNumber());
		arrayBuilder.add(objectBuilder);
	}
	return arrayBuilder.build();
}
 
Example 4
Source File: Group.java    From sample-acmegifts with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Create a JSON string based on the content of this group
 *
 * @return The JSON string with the content of this group
 */
public String getJson() {
  JsonObjectBuilder group = Json.createObjectBuilder();
  if (id != null) {
    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 5
Source File: AbstractEmbeddedDBAccess.java    From jcypher with 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 6
Source File: JsonMarshaller.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void addValue(JsonArrayBuilder json, Object value) {
    if (value instanceof Map) {
        json.add(build((Map<String, Object>)value));
    } else if (value instanceof BigDecimal) {
        json.add((BigDecimal)value);
    } else if (value instanceof BigInteger) {
        json.add((BigInteger)value);
    } else if (value instanceof String) {
        json.add((String)value);
    } else if (value instanceof Long) {
        json.add((Long)value);
    } else if (value instanceof Integer) {
        json.add((Integer)value);
    } else if (value instanceof Float) {
        json.add((Float)value);
    } else if (value instanceof Double) {
        json.add((Double)value);
    } else if (value instanceof Boolean) {
        json.add((Boolean)value);
    }
}
 
Example 7
Source File: MissionControlStatusEndpoint.java    From launchpad-missioncontrol with Apache License 2.0 6 votes vote down vote up
@OnOpen
public void onOpen(Session session, @PathParam("uuid") String uuid) {
    UUID key = UUID.fromString(uuid);
    peers.put(key, session);
    JsonArrayBuilder builder = Json.createArrayBuilder();
    for (StatusMessage statusMessage : StatusMessage.values()) {
        JsonObjectBuilder object = Json.createObjectBuilder();
        builder.add(object.add(statusMessage.name(), statusMessage.getMessage()).build());
    }

    RemoteEndpoint.Async asyncRemote = session.getAsyncRemote();
    asyncRemote.sendText(builder.build().toString());
    // Send pending messages
    List<String> messages = messageBuffer.remove(key);
    if (messages != null) {
        messages.forEach(asyncRemote::sendText);
    }
}
 
Example 8
Source File: QueueControlImpl.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private static String toJSON(final Map<String, Map<String, Object>[]> messages) {
   JsonArrayBuilder arrayReturn = JsonLoader.createArrayBuilder();
   for (Map.Entry<String, Map<String, Object>[]> entry : messages.entrySet()) {
      JsonObjectBuilder objectItem = JsonLoader.createObjectBuilder();
      objectItem.add("consumerName", entry.getKey());
      objectItem.add("elements", toJSONMsgArray(entry.getValue()));
      arrayReturn.add(objectItem);
   }

   return arrayReturn.build().toString();
}
 
Example 9
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 10
Source File: HdfsSerDeImportService.java    From hadoop-etl-udfs with MIT License 5 votes vote down vote up
private static JsonArrayBuilder getJsonArrayFromFieldData(Object data, ObjectInspector objInsp, JsonBuilderFactory jsonFactory) {
    JsonArrayBuilder jab = jsonFactory.createArrayBuilder();
    ListObjectInspector oi = (ListObjectInspector) objInsp;
    List<?> list = oi.getList(data);
    ObjectInspector elemInsp = oi.getListElementObjectInspector();
    for (Object obj : list) {
        if (obj == null)
            jab.addNull();
        else if (elemInsp.getCategory() == Category.PRIMITIVE) {
            Object o = getJavaObjectFromPrimitiveData(obj, elemInsp);
            if (o instanceof Integer || o instanceof Short || o instanceof Byte)
                jab.add((Integer) o);
            else if (o instanceof Long)
                jab.add((Long) o);
            else if (o instanceof Float || o instanceof Double)
                jab.add((Double) o);
            else if (o instanceof BigDecimal)
                jab.add((BigDecimal) o);
            else if (o instanceof Boolean)
                jab.add((Boolean) o);
            else
                jab.add(o.toString());
        }
        else if (elemInsp.getCategory() == Category.LIST) {
            jab.add(getJsonArrayFromFieldData(obj, elemInsp, jsonFactory));
        }
        else {
            jab.add(getJsonObjectFromFieldData(obj, elemInsp, jsonFactory));
        }
    }
    return jab;
}
 
Example 11
Source File: RealizedOrdersResource.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
public JsonArray list() {
	JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
	for (RealizedOrder order : OrderManager.getInstance().getCompletedOrders()) {
		arrayBuilder.add(order.toJSon());
	}
	return arrayBuilder.build();
}
 
Example 12
Source File: FactoryResource.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@GET
@Path("/inproduction/")
@Produces(MediaType.APPLICATION_JSON)
public JsonArray listInProduction() {
	JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
	for (Long serialId : Factory.getInstance().getInProduction()) {
		arrayBuilder.add(String.valueOf(serialId));
	}
	return arrayBuilder.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: 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 (Map.Entry<String, String> entry: books.entrySet()) {
        builder.add(Json.createObjectBuilder()
            .add("id", entry.getKey())
            .add("title", entry.getValue())
        );
    }

    return builder.build();
}
 
Example 15
Source File: GnpsJsonGenerator.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * JSON of data points array
 * 
 * @param dps
 * @return
 */
private static JsonArray genJSONData(DataPoint[] dps) {
  JsonArrayBuilder data = Json.createArrayBuilder();
  JsonArrayBuilder signal = Json.createArrayBuilder();
  for (DataPoint dp : dps) {
    // round to five digits. thats more than enough
    signal.add(((int) (dp.getMZ() * 1000000)) / 1000000.0);
    signal.add(dp.getIntensity());
    data.add(signal.build());
  }
  return data.build();
}
 
Example 16
Source File: FHIRSwaggerGenerator.java    From FHIR with Apache License 2.0 5 votes vote down vote up
private static void generateCreatePathItem(Class<?> modelClass, JsonObjectBuilder path) {
    JsonObjectBuilder post = factory.createObjectBuilder();

    JsonArrayBuilder tags = factory.createArrayBuilder();
    tags.add(modelClass.getSimpleName());

    post.add("tags", tags);
    post.add("summary", "Create" + getArticle(modelClass) + modelClass.getSimpleName() + " resource");
    post.add("operationId", "create" + modelClass.getSimpleName());

    JsonArrayBuilder consumes = factory.createArrayBuilder();
    consumes.add(FHIRMediaType.APPLICATION_FHIR_JSON);
    post.add("consumes", consumes);

    JsonArrayBuilder parameters = factory.createArrayBuilder();
    JsonObjectBuilder bodyParameter = factory.createObjectBuilder();

    bodyParameter.add("name", "body");
    bodyParameter.add("in", "body");
    bodyParameter.add("required", true);

    JsonObjectBuilder schema = factory.createObjectBuilder();
    schema.add("$ref", "#/definitions/" + modelClass.getSimpleName());
    bodyParameter.add("schema", schema);

    parameters.add(bodyParameter);
    post.add("parameters", parameters);

    JsonObjectBuilder responses = factory.createObjectBuilder();

    JsonObjectBuilder response = factory.createObjectBuilder();
    response.add("description", "Create " + modelClass.getSimpleName() + " operation successful");
    responses.add("201", response);
    post.add("responses", responses);

    path.add("post", post);
}
 
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: XmlTypeToJsonSchemaConverter.java    From iaf with Apache License 2.0 4 votes vote down vote up
private void applyFacet(XSSimpleTypeDefinition simpleTypeDefinition, JsonObjectBuilder builder, String key, short facet){
	if(simpleTypeDefinition.getFacet(facet) != null){
		String lexicalFacetValue = simpleTypeDefinition.getLexicalFacetValue(facet);
		if(lexicalFacetValue != null){
			switch(facet){
				case XSSimpleTypeDefinition.FACET_MAXINCLUSIVE:
				case XSSimpleTypeDefinition.FACET_MININCLUSIVE:
				case XSSimpleTypeDefinition.FACET_MAXEXCLUSIVE:
				case XSSimpleTypeDefinition.FACET_MINEXCLUSIVE:
				case XSSimpleTypeDefinition.FACET_MAXLENGTH:
				case XSSimpleTypeDefinition.FACET_MINLENGTH:
					/*
						Not sure about this.. 

						simpleTypeDefinition.getLexicalFacetValue(facet) returns a numeric value as string
						if value > MAX_INT, Integer.parseInt(value) will throw NumberFormatException

						currently this exception is catched and retried as Long.ParseLong(value)
						but what if this throws NumberFormatException?

						how to deal with this properly?
						-----
						UPDATE:
						Tried parsing as long and logging the value when couldn't parse, appears to be a 20 digit numeric value
						which would require to use BigInteger

						What is the best method to do this? Try and catch int, long & then bigint or directly to big int?
					*/
					try {
						builder.add(key, Integer.parseInt(lexicalFacetValue));
					} catch (NumberFormatException nfe) {
						log.warn("Couldn't parse value ["+lexicalFacetValue+"] as Integer... retrying as Long");

						try {
							builder.add(key, Long.parseLong(lexicalFacetValue));
						} catch (NumberFormatException nfex) {
							log.warn("Couldn't parse value ["+lexicalFacetValue+"] as Long... retrying as BigInteger");
							
							try {
								builder.add(key, new BigInteger(lexicalFacetValue));
							} catch (NumberFormatException nfexx) {
								log.warn("Couldn't parse value ["+lexicalFacetValue+"] as BigInteger");
							}
						}
					}	
					break;
				default:
					// hmm never reaches this block?
					log.debug("Setting value ["+lexicalFacetValue+"] as String for facet ["+simpleTypeDefinition.getFacet(facet)+"]");
					builder.add(key, lexicalFacetValue);
					break;
			}
		} else if (facet == XSSimpleTypeDefinition.FACET_PATTERN || facet == XSSimpleTypeDefinition.FACET_ENUMERATION) {
			XSObjectList multiValuedFacets = simpleTypeDefinition.getMultiValueFacets();

			for (int i=0; i<multiValuedFacets.getLength(); i++) {
				XSMultiValueFacet multiValuedFacet = (XSMultiValueFacet) multiValuedFacets.item(i);

				if (log.isTraceEnabled()) log.trace("Inspecting single multi valued facet ["+multiValuedFacet+"] which is named ["+multiValuedFacet.getName()+"] which is of type ["+multiValuedFacet.getType()+"]");
				if (log.isTraceEnabled()) log.trace("Inspecting multiValuedFacet.getLexicalFacetValues() for ["+multiValuedFacet.getName()+"] which has value of ["+multiValuedFacet.getLexicalFacetValues()+"]");
				if (log.isTraceEnabled()) log.trace("Inspecting multiValuedFacet.getEnumerationValues() for ["+multiValuedFacet.getName()+"] which has value of ["+multiValuedFacet.getEnumerationValues()+"]");
				if (log.isTraceEnabled()) log.trace("Inspecting multiValuedFacet.getFacetKind() == enum for ["+multiValuedFacet.getName()+"] which has value of ["+(multiValuedFacet.getFacetKind() == XSSimpleTypeDefinition.FACET_ENUMERATION)+"]");
				if (log.isTraceEnabled()) log.trace("Inspecting multiValuedFacet.getFacetKind() == pattern for ["+multiValuedFacet.getName()+"] which has value of ["+(multiValuedFacet.getFacetKind() == XSSimpleTypeDefinition.FACET_PATTERN)+"]");

				if(facet == multiValuedFacet.getFacetKind()){
					StringList lexicalFacetValues = multiValuedFacet.getLexicalFacetValues();

					/* 
						Isn't this strange?
						This assumes that an enumeration/pattern value is always a string, 
						
						don't we need to try and parse?
					*/

					if(facet == XSSimpleTypeDefinition.FACET_ENUMERATION){
						JsonArrayBuilder enumBuilder = Json.createArrayBuilder();
						for (int x=0; x<lexicalFacetValues.getLength(); x++) {
							lexicalFacetValue = lexicalFacetValues.item(x); 
							enumBuilder.add(lexicalFacetValue);
						}

						builder.add(key, enumBuilder.build());
					}
					else if(facet == XSSimpleTypeDefinition.FACET_PATTERN){
						builder.add(key, lexicalFacetValues.item(0));
					}
				}
			}
		}
	}
	
}
 
Example 19
Source File: RequestCaseJson.java    From tcases with MIT License 4 votes vote down vote up
public void visit( DecimalValue data)
{
JsonArrayBuilder builder = Json.createArrayBuilder();
builder.add( data.getValue());
json_ = builder.build().get(0);
}
 
Example 20
Source File: FHIROpenApiGenerator.java    From FHIR with Apache License 2.0 4 votes vote down vote up
private static void generateDefinition(Class<?> modelClass, JsonObjectBuilder definitions) throws Exception {
        if (!ModelSupport.isPrimitiveType(modelClass)) {
            JsonObjectBuilder definition = factory.createObjectBuilder();
            JsonObjectBuilder properties = factory.createObjectBuilder();
            JsonArrayBuilder required = factory.createArrayBuilder();

            StructureDefinition structureDefinition = getStructureDefinition(modelClass);

            if (structureDefinition == null) {
                System.err.println("Failed generateDefinition for: " + modelClass.getName());
                return;
            }

            if (Resource.class.isAssignableFrom(modelClass)) {
                // if the modelClass is a resource, then add the 'resourceType' property
                JsonObjectBuilder property = factory.createObjectBuilder();

                // Convert all the primitive types to json types.
                property.add("type", "string");
                if (Resource.class == modelClass) {
                    // TODO: when a filter was passed, limit this to just the resource types included in the filter
                    List<String> typeNames = Arrays.stream(ResourceType.ValueSet.values()).map(ResourceType.ValueSet::value).collect(Collectors.toList());
                    JsonArrayBuilder enumValues = factory.createArrayBuilder(typeNames);
                    property.add("enum", enumValues);
                    properties.add("resourceType", property.build());
                    required.add("resourceType");
                } else {
                    // TODO how to "overwrite" the Resource definition and say that the value is fixed?
                    // https://github.com/OAI/OpenAPI-Specification/issues/1313
//                    property.add("enum", modelClass.getSimpleName());
                }
            }

            for (Field field : modelClass.getDeclaredFields()) {
                if (!Modifier.isStatic(field.getModifiers()) && !Modifier.isVolatile(field.getModifiers())) {
                    if (!ModelSupport.isChoiceElement(modelClass, ModelSupport.getElementName(field)) &&
                            field.isAnnotationPresent(Required.class)) {
                        required.add(ModelSupport.getElementName(field));
                    }
                    generateProperties(structureDefinition, modelClass, field, properties);
                }
            }

            JsonArray requiredArray = required.build();

            Class<?> superClass = modelClass.getSuperclass();
            if (superClass != null && superClass.getPackage().getName().startsWith("com.ibm.fhir.model")
                    && !superClass.equals(AbstractVisitable.class)) {
                JsonArrayBuilder allOf = factory.createArrayBuilder();

                JsonObjectBuilder ref = factory.createObjectBuilder();
                ref.add("$ref", "#/components/schemas/" + superClass.getSimpleName());
                allOf.add(ref);

                JsonObjectBuilder wrapper = factory.createObjectBuilder();
                wrapper.add("type", "object");
                wrapper.add("properties", properties);
                if (!requiredArray.isEmpty()) {
                    wrapper.add("required", requiredArray);
                }
                allOf.add(wrapper);

                definition.add("allOf", allOf);
            } else {
                definition.add("type", "object");
                if (Resource.class.equals(modelClass)) {
                    definition.add("discriminator", "resourceType");
                }
                definition.add("properties", properties);
                if (!requiredArray.isEmpty()) {
                    definition.add("required", requiredArray);
                }
            }

            if (Resource.class.isAssignableFrom(modelClass)) {
                addExamples(modelClass, definition);
            }

            definitions.add(getSimpleNameWithEnclosingNames(modelClass), definition);
        }
    }