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

The following examples show how to use javax.json.JsonObjectBuilder#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: CustomVariableList.java    From matomo-java-tracker with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
@Override
public String toString(){
    JsonObjectBuilder ob = Json.createObjectBuilder();

    for (Entry<Integer, CustomVariable> entry : map.entrySet()){
        JsonArrayBuilder ab = Json.createArrayBuilder();
        ab.add(entry.getValue().getKey());
        ab.add(entry.getValue().getValue());
        ob.add(entry.getKey().toString(), ab);
    }

    return ob.build().toString();
}
 
Example 2
Source File: BookClient.java    From jaxrs-hypermedia with Apache License 2.0 7 votes vote down vote up
public void addToCart(final Book book, final int quantity) {
    final Entity bookEntity = client.retrieveEntity(book.getUri());

    final JsonObjectBuilder properties = Json.createObjectBuilder();
    entityMapper.encodeBook(book).forEach(properties::add);
    properties.add("quantity", quantity);

    client.performAction(bookEntity, "add-to-cart", properties.build());
}
 
Example 3
Source File: MocoServerConfigWriter.java    From tcases with MIT License 6 votes vote down vote up
/**
 * Returns the JSON object that represents expectations for the given request case.
 */
private JsonObject expectedConfig( RequestCase requestCase)
  {
  try
    {
    JsonObjectBuilder expected = Json.createObjectBuilder();

    expected.add( "request", expectedRequest( requestCase));
    expected.add( "response", expectedResponse( requestCase));

    return expected.build();
    }
  catch( Exception e)
    {
    throw new RequestCaseException( String.format( "Can't write Moco server configuration for %s", requestCase), e);
    }
  }
 
Example 4
Source File: NotificationUtil.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
public static JsonObject toJson(final Vulnerability vulnerability) {
    final JsonObjectBuilder vulnerabilityBuilder = Json.createObjectBuilder();
    vulnerabilityBuilder.add("uuid", vulnerability.getUuid().toString());
    JsonUtil.add(vulnerabilityBuilder, "vulnId", vulnerability.getVulnId());
    JsonUtil.add(vulnerabilityBuilder, "source", vulnerability.getSource());
    JsonUtil.add(vulnerabilityBuilder, "title", vulnerability.getTitle());
    JsonUtil.add(vulnerabilityBuilder, "subtitle", vulnerability.getSubTitle());
    JsonUtil.add(vulnerabilityBuilder, "description", vulnerability.getDescription());
    JsonUtil.add(vulnerabilityBuilder, "recommendation", vulnerability.getRecommendation());
    JsonUtil.add(vulnerabilityBuilder, "cvssv2", vulnerability.getCvssV2BaseScore());
    JsonUtil.add(vulnerabilityBuilder, "cvssv3", vulnerability.getCvssV3BaseScore());
    JsonUtil.add(vulnerabilityBuilder, "severity",  vulnerability.getSeverity());
    if (vulnerability.getCwe() != null) {
        final JsonObject cweNode = Json.createObjectBuilder()
                .add("cweId", vulnerability.getCwe().getCweId())
                .add("name", vulnerability.getCwe().getName())
                .build();
        vulnerabilityBuilder.add("cwe", cweNode);
    }
    return vulnerabilityBuilder.build();
}
 
Example 5
Source File: XmlTypeToJsonSchemaConverter.java    From iaf with Apache License 2.0 6 votes vote down vote up
private void buildSkippableArrayContainer(XSParticle childParticle, JsonObjectBuilder builder){
	JsonObjectBuilder refBuilder = Json.createObjectBuilder();
	handleParticle(refBuilder,childParticle,null, false);

	XSTerm childTerm = childParticle.getTerm();
	if( childTerm instanceof XSElementDeclaration ){
		XSElementDeclaration elementDeclaration=(XSElementDeclaration) childTerm;
		XSTypeDefinition elementTypeDefinition = elementDeclaration.getTypeDefinition();
		JsonStructure definition =getDefinition(elementTypeDefinition, true);
	
		builder.add("type", "array");
		if (elementDeclaration.getNillable()) {
			definition=nillable(definition);
		}
		builder.add("items", definition);
	}
}
 
Example 6
Source File: Message.java    From sample-room-java with Apache License 2.0 6 votes vote down vote up
/**
 * Indicates that a player can leave by the requested exit (`exitId`).
 * @param userId Targeted user
 * @param exitId Direction the user will be exiting (used as a lookup key)
 * @param message Message to be displayed when the player leaves the room
 * @return constructed message
 */
public static Message createExitMessage(String userId, String exitId, String message) {
    if ( exitId == null ) {
        throw new IllegalArgumentException("exitId is required");
    }

    //  playerLocation,<userId>,{
    //      "type": "exit",
    //      "content": "You exit through door xyz... ",
    //      "exitId": "N"
    //      "exit": { ... }
    //  }
    // The exit attribute describes an exit the map service wouldn't know about..
    // This would have to be customized..

    JsonObjectBuilder payload = Json.createObjectBuilder();
    payload.add(TYPE, "exit");
    payload.add("exitId", exitId);
    payload.add(CONTENT, message == null ? "Fare thee well" : message);

    return new Message(Target.playerLocation, userId, payload.build().toString());
}
 
Example 7
Source File: XmlTypeToJsonSchemaConverter.java    From iaf with Apache License 2.0 6 votes vote down vote up
public JsonObject getDefinitions() {
	JsonObjectBuilder definitionsBuilder = Json.createObjectBuilder();
	for (XSModel model:models) {
		XSNamedMap elements = model.getComponents(XSConstants.ELEMENT_DECLARATION);
		for (int i=0; i<elements.getLength(); i++) {
			XSElementDeclaration elementDecl = (XSElementDeclaration)elements.item(i);
			handleElementDeclaration(definitionsBuilder, elementDecl, false, false);
		}
		XSNamedMap types = model.getComponents(XSConstants.TYPE_DEFINITION);
		for (int i=0; i<types.getLength(); i++) {
			XSTypeDefinition typeDefinition = (XSTypeDefinition)types.item(i);
			String typeNamespace = typeDefinition.getNamespace();
			if (typeNamespace==null || !typeDefinition.getNamespace().equals(XML_SCHEMA_NS)) {
				definitionsBuilder.add(typeDefinition.getName(), getDefinition(typeDefinition, false));
			}
		}
	}
	return definitionsBuilder.build();
}
 
Example 8
Source File: ModuleDetailDescriptor.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 servicesBuilder = Json.createArrayBuilder();
        services().forEach( service -> servicesBuilder.add( service.toJson() ) );
        builder.add( "services", servicesBuilder.build() );
    }
    {
        JsonArrayBuilder activatorsBuilder = Json.createArrayBuilder();
        activators().forEach( activator -> activatorsBuilder.add( activator.toJson() ) );
        builder.add( "activators", activatorsBuilder.build() );
    }
    return builder.build();
}
 
Example 9
Source File: NotificationTest.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Tests sending a twitter post and a direct notification. IMPORTANT: Before enabling this test,
 * update the application's twitter related properties (default: CHANGE_ME) with valid values.
 * These properties are located in the application's root pom.xml.
 */
// @Test
public void testTwitterPostMention() throws Exception {
  // Post a message.
  String userMention = "@" + twitterRecepientHandle;
  JsonObjectBuilder content = Json.createObjectBuilder();
  content.add(JSON_KEY_TWITTER_HANDLE, twitterRecepientHandle);
  content.add(
      JSON_KEY_MESSAGE,
      "Merry Christmas "
          + userMention
          + "."
          + System.getProperty("line.separator")
          + "Jack D., Jane D. and James D. contributed $10,000 for your gift. A wishlist gift was ordered and mailed.");
  JsonObjectBuilder notification = Json.createObjectBuilder();
  notification.add(JSON_KEY_NOTIFICATION, content.build());

  Response response =
      processRequest(notificationServiceURL, "POST", notification.build().toString());
  assertEquals(
      "HTTP response code should have been " + Status.OK.getStatusCode() + ".",
      Status.OK.getStatusCode(),
      response.getStatus());

  // Verify that the notification was logged.
  BufferedReader br = new BufferedReader(new FileReader(logFile));
  try {
    String line = null;
    while ((line = br.readLine()) != null) {
      if (line.contains("Merry Christmas " + userMention)) {
        return;
      }
    }

    fail("Not all notifications were found.");
  } finally {
    br.close();
  }
}
 
Example 10
Source File: XMLGregorianCalendarTypeInfoProducer.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public JsonValue createValue(JsonSchemaMappingCompiler<T, C> mappingCompiler, String item) {
	final JsonObjectBuilder objectBuilder = mappingCompiler.getJsonBuilderFactory().createObjectBuilder();
	final XMLGregorianCalendar calendar = datatypeFactory.newXMLGregorianCalendar(item);
	if (calendar.getYear() != DatatypeConstants.FIELD_UNDEFINED) {
		objectBuilder.add("year", calendar.getYear());
	}
	if (calendar.getMonth() != DatatypeConstants.FIELD_UNDEFINED) {
		objectBuilder.add("month", calendar.getMonth());
	}
	if (calendar.getDay() != DatatypeConstants.FIELD_UNDEFINED) {
		objectBuilder.add("day", calendar.getDay());
	}
	if (calendar.getHour() != DatatypeConstants.FIELD_UNDEFINED) {
		objectBuilder.add("hour", calendar.getHour());
	}
	if (calendar.getMinute() != DatatypeConstants.FIELD_UNDEFINED) {
		objectBuilder.add("minute", calendar.getMinute());
	}
	if (calendar.getSecond() != DatatypeConstants.FIELD_UNDEFINED) {
		objectBuilder.add("second", calendar.getSecond());
	}
	if (calendar.getFractionalSecond() != null) {
		objectBuilder.add("second", calendar.getFractionalSecond());
	}
	if (calendar.getTimezone() != DatatypeConstants.FIELD_UNDEFINED) {
		objectBuilder.add("timeZone", calendar.getTimezone());
	}
	return objectBuilder.build();
}
 
Example 11
Source File: JWTokenFactory.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
public static String createAuthToken(Key key, UserGroupMapping userGroupMapping) {
    JsonObjectBuilder subjectBuilder = Json.createObjectBuilder();
    subjectBuilder.add(SUBJECT_LOGIN, userGroupMapping.getLogin());
    subjectBuilder.add(SUBJECT_GROUP_NAME, userGroupMapping.getGroupName());
    JsonObject build = subjectBuilder.build();
    return createToken(key, build);
}
 
Example 12
Source File: PaintsResource.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 builder = Json.createArrayBuilder();
	for (Color c : Color.values()) {
		JsonObjectBuilder colorBuilder = Json.createObjectBuilder();
		colorBuilder.add(Robot.KEY_COLOR, c.toString());
		builder.add(colorBuilder);
	}
	return builder.build();
}
 
Example 13
Source File: FHIROpenApiGenerator.java    From FHIR with Apache License 2.0 5 votes vote down vote up
private static void addIdPathParam(JsonObjectBuilder idParamRef) {
    idParamRef.add("name", "id");
    idParamRef.add("in", "path");
    idParamRef.add("required", true);
    idParamRef.add("description", "logical identifier");
    JsonObjectBuilder schema = factory.createObjectBuilder();
    schema.add("type", "string");
    idParamRef.add("schema", schema);
}
 
Example 14
Source File: User.java    From sample-acmegifts with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Return a JSON object suitable to be returned to the caller with no confidential information
 * (like password or salt).
 */
public JsonObject getPublicJsonObject() {
  JsonObjectBuilder user = Json.createObjectBuilder();
  user.add(JSON_KEY_USER_ID, id);
  user.add(JSON_KEY_USER_FIRST_NAME, firstName);
  user.add(JSON_KEY_USER_LAST_NAME, lastName);
  user.add(JSON_KEY_USER_NAME, userName);
  user.add(JSON_KEY_USER_TWITTER_HANDLE, twitterHandle);
  user.add(JSON_KEY_USER_WISH_LIST_LINK, wishListLink);
  user.add(JSON_KEY_USER_TWITTER_LOGIN, isTwitterLogin);

  return user.build();
}
 
Example 15
Source File: AbstractSiteToSiteReportingTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected void addField(final JsonObjectBuilder builder, final String key, final String value, boolean allowNullValues) {
    if (value != null) {
        builder.add(key, value);
    }else if(allowNullValues){
        builder.add(key,JsonValue.NULL);
    }
}
 
Example 16
Source File: JsonMetadataExporter.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
private JsonObject rootJSON() {
    JsonObjectBuilder root = JsonProviderHolder.get().createObjectBuilder();

    root.add("base", registryJSON(MetricRegistries.get(MetricRegistry.Type.BASE)));
    root.add("vendor", registryJSON(MetricRegistries.get(MetricRegistry.Type.VENDOR)));
    root.add("application", registryJSON(MetricRegistries.get(MetricRegistry.Type.APPLICATION)));

    return root.build();
}
 
Example 17
Source File: Message.java    From sample-room-java with Apache License 2.0 5 votes vote down vote up
/**
 * Send information about the room to the client. This message is sent after
 * receiving a `roomHello`.
 * @param userId
 * @param roomDescription Room attributes
 * @return constructed message
 */
public static Message createLocationMessage(String userId, RoomDescription roomDescription) {
    //  player,<userId>,{
    //      "type": "location",
    //      "name": "Room name",
    //      "fullName": "Room's descriptive full name",
    //      "description", "Lots of text about what the room looks like",
    //      "exits": {
    //          "shortDirection" : "currentDescription for Player",
    //          "N" :  "a dark entranceway"
    //      },
    //      "commands": {
    //          "/custom" : "Description of what command does"
    //      },
    //      "roomInventory": ["itemA","itemB"]
    //  }
    JsonObjectBuilder payload = Json.createObjectBuilder();
    payload.add(TYPE, "location");
    payload.add("name", roomDescription.getName());
    payload.add("fullName", roomDescription.getFullName());
    payload.add("description", roomDescription.getDescription());

    // convert map of commands into JsonObject
    JsonObject commands = roomDescription.getCommands();
    if ( !commands.isEmpty()) {
        payload.add("commands", commands);
    }

    // Convert list of items into json array
    JsonArray inventory = roomDescription.getInventory();
    if ( !inventory.isEmpty()) {
        payload.add("roomInventory", inventory);
    }

    return new Message(Target.player, userId, payload.build().toString());
}
 
Example 18
Source File: SiteToSiteBulletinReportingTask.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
private static void addField(final JsonObjectBuilder builder, final String key, final String value) {
    if (value == null) {
        return;
    }
    builder.add(key, value);
}
 
Example 19
Source File: GnpsJsonGenerator.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Whole JSON entry
 * 
 * @param param
 * @param dps
 * @return
 */
public static String generateJSON(LibrarySubmitIonParameters param, DataPoint[] dps) {
  LibraryMetaDataParameters meta = (LibraryMetaDataParameters) param
      .getParameter(LibrarySubmitIonParameters.META_PARAM).getValue();

  boolean exportRT = meta.getParameter(LibraryMetaDataParameters.EXPORT_RT).getValue();

  JsonObjectBuilder json = Json.createObjectBuilder();
  // tag spectrum from mzmine2
  json.add(DBEntryField.SOFTWARE.getGnpsJsonID(), "mzmine2");
  // ion specific
  Double precursorMZ = param.getParameter(LibrarySubmitIonParameters.MZ).getValue();
  if (precursorMZ != null)
    json.add(DBEntryField.MZ.getGnpsJsonID(), precursorMZ);

  Integer charge = param.getParameter(LibrarySubmitIonParameters.CHARGE).getValue();
  if (charge != null)
    json.add(DBEntryField.CHARGE.getGnpsJsonID(), charge);

  String adduct = param.getParameter(LibrarySubmitIonParameters.ADDUCT).getValue();
  if (adduct != null && !adduct.trim().isEmpty())
    json.add(DBEntryField.ION_TYPE.getGnpsJsonID(), adduct);

  if (exportRT) {
    Double rt =
        meta.getParameter(LibraryMetaDataParameters.EXPORT_RT).getEmbeddedParameter().getValue();
    if (rt != null)
      json.add(DBEntryField.RT.getGnpsJsonID(), rt);
  }

  // add data points array
  json.add("peaks", genJSONData(dps));

  // add meta data
  for (Parameter<?> p : meta.getParameters()) {
    if (!p.getName().equals(LibraryMetaDataParameters.EXPORT_RT.getName())) {
      String key = p.getName();
      Object value = p.getValue();
      if (value instanceof Double) {
        if (Double.compare(0d, (Double) value) == 0)
          json.add(key, 0);
        else
          json.add(key, (Double) value);
      } else if (value instanceof Float) {
        if (Float.compare(0f, (Float) value) == 0)
          json.add(key, 0);
        else
          json.add(key, (Float) value);
      } else if (value instanceof Integer)
        json.add(key, (Integer) value);
      else {
        if (value == null || (value instanceof String && ((String) value).isEmpty()))
          value = "N/A";
        json.add(key, value.toString());
      }
    }
  }

  // return Json.createObjectBuilder().add("spectrum", json.build()).build().toString();
  return json.build().toString();
}
 
Example 20
Source File: NetworkMessageResponse.java    From vicinity-gateway-api with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Takes all the necessary fields, attributes and parameters and assembles a valid JSON that can be sent over 
 * network. 
 */
private void buildMessageJson(){
	// create the factory
	JsonBuilderFactory jsonBuilderFactory = Json.createBuilderFactory(null);
	
	// build the thing
	JsonObjectBuilder mainBuilder = jsonBuilderFactory.createObjectBuilder();
	
	mainBuilder.add(ATTR_MESSAGETYPE, messageType);
	mainBuilder.add(ATTR_REQUESTID, requestId);
	mainBuilder.add(ATTR_SOURCEOID, sourceOid);
	mainBuilder.add(ATTR_DESTINATIONOID, destinationOid);
	mainBuilder.add(ATTR_ERROR, error);
	mainBuilder.add(ATTR_RESPONSECODE, responseCode);
	
	
	if (sourceOid == null){
		mainBuilder.addNull(ATTR_SOURCEOID);
	} else {
		mainBuilder.add(ATTR_SOURCEOID, sourceOid);
	}
	
	if (destinationOid == null){
		mainBuilder.addNull(ATTR_DESTINATIONOID);
	} else {
		mainBuilder.add(ATTR_DESTINATIONOID, destinationOid);
	}
	
	if (responseCodeReason == null){
		mainBuilder.addNull(ATTR_RESPONSECODEREASON);
	} else {
		mainBuilder.add(ATTR_RESPONSECODEREASON, responseCodeReason);
	}
	
	if (contentType == null){
		mainBuilder.addNull(ATTR_CONTENTTYPE);
	} else {
		mainBuilder.add(ATTR_CONTENTTYPE, contentType);
	}
	
	if (responseBody == null){
		mainBuilder.addNull(ATTR_RESPONSEBODY);
	} else {
		mainBuilder.add(ATTR_RESPONSEBODY, responseBody);
	}
	
	if (responseBodySupplement == null) {
		mainBuilder.addNull(ATTR_RESPONSEBODYSUPPLEMENT);
	} else {
		mainBuilder.add(ATTR_RESPONSEBODYSUPPLEMENT, responseBodySupplement);
	}
			
	// build the thing
	jsonRepresentation = mainBuilder.build(); 
}