javax.json.JsonArrayBuilder Java Examples

The following examples show how to use javax.json.JsonArrayBuilder. 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: 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 #2
Source File: PiwikJsonArray.java    From matomo-java-tracker with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #3
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 #4
Source File: ExceptionFilter.java    From hugegraph with 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 #5
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 #6
Source File: MixinDetailDescriptor.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( "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 #7
Source File: SystemInputJson.java    From tcases with 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 #8
Source File: FilteredUriBuilder.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #9
Source File: CreateApplicationListReportRuleProvider.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
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 #10
Source File: Result.java    From KITE with 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 #11
Source File: MetricsBuilder.java    From nifi with 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 #12
Source File: ActiveMQServerControlImpl.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
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 #13
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 #14
Source File: AccessoryController.java    From HAP-Java with 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 #15
Source File: ActiveMQServerControlImpl.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@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 #16
Source File: TestClass40.java    From jaxrs-analyzer with 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 #17
Source File: LayerDetailDescriptor.java    From attic-polygene-java with 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 #18
Source File: FHIRSwaggerGenerator.java    From FHIR with 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 #19
Source File: HFCAIdentity.java    From fabric-sdk-java with 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 #20
Source File: ActiveMQServerControlImpl.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
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 #21
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 #22
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 #23
Source File: CommunicationManager.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * getThingDescriptions - Return one page of the thing descriptions of IoT object(s).
 * 
 * @param page number (0 <-> countOfObjects/5 + 1)
 * @param sourceObjectId 
 * 
 * @return JsonObject with the list of thing descriptions 
 */
public Representation getThingDescriptions(String sourceObjectId, int pageNumber){
	
	if (sourceObjectId == null || sourceObjectId.isEmpty()) {
		logger.warning("Method parameter sourceObjectId can't be null nor empty.");
		
		return null;
	}
	
	if (pageNumber < 0) {
		logger.warning("Method parameter pageNumber can't be smaller than 0;");
		logger.warning("Set pageNumber to 0;");
		
		pageNumber = 0;
	}
	
	Set<String> rosterObjects = getRosterEntriesForObject(sourceObjectId, pageNumber);
	
	if (rosterObjects == null) {
		return null;
	}
	
	JsonObjectBuilder mainObjectBuilder = Json.createObjectBuilder();
	JsonArrayBuilder mainArrayBuilder = Json.createArrayBuilder();
	
	rosterObjects.forEach(item -> {
		mainArrayBuilder.add(
				Json.createObjectBuilder().add(ATTR_OID, item)
			);
	});
	
	mainObjectBuilder.add(ATTR_OBJECTS, mainArrayBuilder);
	JsonObject json = mainObjectBuilder.build();
	
	return nmConnector.getThingDescriptions(new JsonRepresentation(json.toString()));
}
 
Example #24
Source File: TestSummary.java    From KITE with Apache License 2.0 5 votes vote down vote up
/**
 * Gets json.
 *
 * @return the json
 */
private JsonObject getJson() {
  JsonArrayBuilder resultArray = Json.createArrayBuilder();
  for (Result result : results) {
    resultArray.add(result.getJson());
  }

  return Json.createObjectBuilder()
      .add("run_info", runInfo.getJson())
      .add("startTime", startTime)
      .add("endTime", endTime)
      .add("results", resultArray)
      .build();
}
 
Example #25
Source File: JWTCallerPrincipal.java    From tomee with Apache License 2.0 5 votes vote down vote up
private JsonValue wrapValue(final Object value) {
    JsonValue jsonValue = null;
    if (value instanceof Number) {
        final Number number = (Number) value;
        if ((number instanceof Long) || (number instanceof Integer)) {
            jsonValue = Json.createObjectBuilder()
                    .add("tmp", number.longValue())
                    .build()
                    .getJsonNumber("tmp");

        } else {
            jsonValue = Json.createObjectBuilder()
                    .add("tmp", number.doubleValue())
                    .build()
                    .getJsonNumber("tmp");
        }

    } else if (value instanceof Boolean) {
        final Boolean flag = (Boolean) value;
        jsonValue = flag ? JsonValue.TRUE : JsonValue.FALSE;

    } else if (value instanceof List) {
        final JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
        final List list = (List) value;
        for (Object element : list) {
            if (element instanceof String) {
                arrayBuilder.add(element.toString());

            } else {
                JsonValue jvalue = wrapValue(element);
                arrayBuilder.add(jvalue);
            }

        }
        jsonValue = arrayBuilder.build();

    }
    return jsonValue;
}
 
Example #26
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 #27
Source File: RecordJsonMapper.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public void onBytesArray(final Schema.Entry entry, final Optional<Collection<byte[]>> array) {
    array
            .ifPresent(vs -> builder
                    .add(entry.getName(),
                            vs
                                    .stream()
                                    .map(it -> Base64.getEncoder().encodeToString(it))
                                    .collect(factory::createArrayBuilder, JsonArrayBuilder::add,
                                            JsonArrayBuilder::addAll)
                                    .build()));
}
 
Example #28
Source File: EmployeeJSONWriter.java    From journaldev with MIT License 5 votes vote down vote up
public static void main(String[] args) throws FileNotFoundException {

		Employee emp = createEmployee();

		JsonObjectBuilder empBuilder = Json.createObjectBuilder();
		JsonObjectBuilder addressBuilder = Json.createObjectBuilder();
		JsonArrayBuilder phoneNumBuilder = Json.createArrayBuilder();

		for (long phone : emp.getPhoneNumbers()) {
			phoneNumBuilder.add(phone);
		}
		
		addressBuilder.add("street", emp.getAddress().getStreet())
						.add("city", emp.getAddress().getCity())
							.add("zipcode", emp.getAddress().getZipcode());
		
		empBuilder.add("id", emp.getId())
					.add("name", emp.getName())
						.add("permanent", emp.isPermanent())
							.add("role", emp.getRole());
		
		empBuilder.add("phoneNumbers", phoneNumBuilder);
		empBuilder.add("address", addressBuilder);
		
		JsonObject empJsonObject = empBuilder.build();
		
		System.out.println("Employee JSON String\n"+empJsonObject);
		
		//write to file
		OutputStream os = new FileOutputStream("emp.txt");
		JsonWriter jsonWriter = Json.createWriter(os);
		/**
		 * We can get JsonWriter from JsonWriterFactory also
		JsonWriterFactory factory = Json.createWriterFactory(null);
		jsonWriter = factory.createWriter(os);
		*/
		jsonWriter.writeObject(empJsonObject);
		jsonWriter.close();
	}
 
Example #29
Source File: ActiveMQServerControlImpl.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public String listAllConsumersAsJSON() throws Exception {
   if (AuditLogger.isEnabled()) {
      AuditLogger.listAllConsumersAsJSON(this.server);
   }
   checkStarted();

   clearIO();

   try {
      JsonArrayBuilder array = JsonLoader.createArrayBuilder();

      Set<ServerSession> sessions = server.getSessions();
      for (ServerSession session : sessions) {
         Set<ServerConsumer> consumers = session.getServerConsumers();
         for (ServerConsumer consumer : consumers) {
            JsonObject obj = toJSONObject(consumer);
            if (obj != null) {
               array.add(obj);
            }
         }
      }
      return array.build().toString();
   } finally {
      blockOnIO();
   }
}
 
Example #30
Source File: ImportedServiceDetailDescriptor.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public JsonObjectBuilder toJson()
{
    JsonObjectBuilder builder = super.toJson();
    {
        JsonArrayBuilder activatorsBuilder = Json.createArrayBuilder();
        activators().forEach( activator -> activatorsBuilder.add( activator.toJson() ) );
        builder.add( "activators", activatorsBuilder.build() );
    }
    return builder;
}