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

The following examples show how to use javax.json.JsonObjectBuilder#addNull() . 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: BaseCharacteristic.java    From HAP-Java with MIT License 6 votes vote down vote up
/**
 * Writes the value key to the serialized characteristic
 *
 * @param builder The JSON builder to add the value to
 * @param value The value to add
 */
protected void setJsonValue(JsonObjectBuilder builder, T value) {
  // I don't like this - there should really be a way to construct a disconnected JSONValue...
  if (value instanceof Boolean) {
    builder.add("value", (Boolean) value);
  } else if (value instanceof Double) {
    builder.add("value", (Double) value);
  } else if (value instanceof Integer) {
    builder.add("value", (Integer) value);
  } else if (value instanceof Long) {
    builder.add("value", (Long) value);
  } else if (value instanceof BigInteger) {
    builder.add("value", (BigInteger) value);
  } else if (value instanceof BigDecimal) {
    builder.add("value", (BigDecimal) value);
  } else if (value == null) {
    builder.addNull("value");
  } else {
    builder.add("value", value.toString());
  }
}
 
Example 2
Source File: JSONEntityState.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
private boolean stateCloneWithProperty( String stateName, JsonValue value )
{
    JsonObject valueState = state.getJsonObject( JSONKeys.VALUE );
    if( Objects.equals( valueState.get( stateName ), value ) )
    {
        return false;
    }
    JsonObjectBuilder valueBuilder = jsonFactories.cloneBuilderExclude( valueState, stateName );
    if( value == null )
    {
        valueBuilder.addNull( stateName );
    }
    else
    {
        valueBuilder.add( stateName, value );
    }
    state = jsonFactories.cloneBuilderExclude( state, JSONKeys.VALUE )
                         .add( JSONKeys.VALUE, valueBuilder.build() )
                         .build();
    return true;
}
 
Example 3
Source File: StatusMessage.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Builds the status message JSON. This method can be called repeatedly but the returned value will always reflect
 * the internal state of the StatusMessage when the method was called for the first time, which means no subsequent
 * additions of messages can be made.   
 * 
 * @return Status message JSON.
 */
public JsonObject buildMessage() {
	
	JsonObjectBuilder mainBuilder = jsonBuilderFactory.createObjectBuilder();
	
	mainBuilder.add(ATTR_ERROR, error);
	mainBuilder.add(ATTR_STATUSCODE, statusCode);
	
	if (statusCodeReason == null) {
		mainBuilder.addNull(ATTR_STATUSCODEREASON);
	} else {
		mainBuilder.add(ATTR_STATUSCODEREASON, statusCodeReason);
	}
	
	
	if (contentType == null) {
		mainBuilder.addNull(ATTR_CONTENTTYPE);
	} else {
		mainBuilder.add(ATTR_CONTENTTYPE, contentType);
	}
	
	mainBuilder.add(ATTR_MESSAGE, arrayBuilder);
		
	return mainBuilder.build();
	
}
 
Example 4
Source File: ConnectionDescriptor.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Simple method for creating JSON string with one string value. 
 *  
 * @param key Name of the attribute.
 * @param value String value.
 * @return JSON string.
 */
private String createSimpleJsonString(String key, String value) {
	// if key is null, there is no need to bother... 
	if (key == null) {
		return null;
	}
		
	JsonObjectBuilder builder = jsonBuilderFactory.createObjectBuilder();
	
	if (value == null) {
		builder.addNull(key);
	} else {
		builder.add(key, value);
	}
	
	return builder.build().toString();
}
 
Example 5
Source File: JsonFormatter.java    From structlog4j with MIT License 6 votes vote down vote up
@Override
public final IFormatter<JsonObjectBuilder> addKeyValue(Logger log, JsonObjectBuilder bld, String key, Object value) {
    // avoid overriding the "message" field
    if (key.equals(FIELD_MESSAGE)) {
        key = FIELD_MESSAGE_2;
        log.warn("Key 'message' renamed to 'message2' in order to avoid overriding default JSON message field. Please correct in your code.");
    }

    // different methods per type
    if (value == null) {
        bld.addNull(key);
    } else if (value instanceof Boolean) {
        bld.add(key,(boolean)value);
    } else if (value instanceof Integer || value instanceof Short) {
        bld.add(key,(int)value);
    } else if (value instanceof Long) {
        bld.add(key,(long)value);
    } else if (value instanceof Double || value instanceof Float) {
        bld.add(key,(double)value);
    } else {
        bld.add(key,String.valueOf(value));
    }
    return this;
}
 
Example 6
Source File: CreateOrderNaiveTest.java    From coffee-testing with Apache License 2.0 5 votes vote down vote up
JsonObject createJson(Order order) {
    JsonObjectBuilder builder = Json.createObjectBuilder();

    if (order.getType() != null)
        builder.add("type", order.getType());
    else
        builder.addNull("type");
    if (order.getOrigin() != null)
        builder.add("origin", order.getOrigin());
    else
        builder.addNull("origin");

    return builder.build();
}
 
Example 7
Source File: JsonUtil.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public static void addToObject(final String key, final Object param, final JsonObjectBuilder jsonObjectBuilder) {
   if (param instanceof Integer) {
      jsonObjectBuilder.add(key, (Integer) param);
   } else if (param instanceof Long) {
      jsonObjectBuilder.add(key, (Long) param);
   } else if (param instanceof Double) {
      jsonObjectBuilder.add(key, (Double) param);
   } else if (param instanceof String) {
      jsonObjectBuilder.add(key, (String) param);
   } else if (param instanceof Boolean) {
      jsonObjectBuilder.add(key, (Boolean) param);
   } else if (param instanceof Map) {
      JsonObject mapObject = toJsonObject((Map<String, Object>) param);
      jsonObjectBuilder.add(key, mapObject);
   } else if (param instanceof Short) {
      jsonObjectBuilder.add(key, (Short) param);
   } else if (param instanceof Byte) {
      jsonObjectBuilder.add(key, ((Byte) param).shortValue());
   } else if (param instanceof SimpleString) {
      jsonObjectBuilder.add(key, param.toString());
   } else if (param == null) {
      jsonObjectBuilder.addNull(key);
   } else if (param instanceof byte[]) {
      JsonArrayBuilder byteArrayObject = toJsonArrayBuilder((byte[]) param);
      jsonObjectBuilder.add(key, byteArrayObject);
   } else {
      throw ActiveMQClientMessageBundle.BUNDLE.invalidManagementParam(param.getClass().getName());
   }
}
 
Example 8
Source File: TestClass4.java    From jaxrs-analyzer with Apache License 2.0 5 votes vote down vote up
@javax.ws.rs.GET
public JsonObject method() {
    final JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
    objectBuilder.addNull("key");
    if ("".equals(""))
        objectBuilder.add("value", JsonValue.FALSE);
    objectBuilder.add("test", JsonValue.NULL);
    objectBuilder.add("test", JsonValue.TRUE);
    return objectBuilder.build();
}
 
Example 9
Source File: TestClass3.java    From jaxrs-analyzer with Apache License 2.0 5 votes vote down vote up
@javax.ws.rs.GET
public JsonObject method() {
    final JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
    objectBuilder.addNull("key");
    if ("".equals(""))
        objectBuilder.add("key", "test");
    objectBuilder.add("object", Json.createObjectBuilder().add("duke", 42).build());
    return objectBuilder.build();
}
 
Example 10
Source File: TestClass5.java    From jaxrs-analyzer with Apache License 2.0 5 votes vote down vote up
@javax.ws.rs.GET
public JsonObject method() {
    final JsonObject object = Json.createObjectBuilder().add("test", true).build();
    final JsonObjectBuilder objectBuilder = Json.createObjectBuilder();
    objectBuilder.addNull("key");
    if ("".equals(""))
        objectBuilder.add("value", JsonValue.FALSE);
    objectBuilder.add("test", object.getBoolean("test"));
    return objectBuilder.build();
}
 
Example 11
Source File: HdfsSerDeImportService.java    From hadoop-etl-udfs with MIT License 5 votes vote down vote up
private static void addJsonObjectPair(JsonObjectBuilder job, String key, Object obj, ObjectInspector objInsp, JsonBuilderFactory jsonFactory) {
    if (obj == null)
        job.addNull(key);
    else if (objInsp.getCategory() == Category.PRIMITIVE) {
        Object o = getJavaObjectFromFieldData(obj, objInsp);
        if (o instanceof Integer)
            job.add(key, (Integer) o);
        else if (o instanceof Byte)
            job.add(key, (Byte) o);
        else if (o instanceof Short)
            job.add(key, (Short) o);
        else if (o instanceof Long)
            job.add(key, (Long) o);
        else if (o instanceof Float)
            job.add(key, (Float) o);
        else if (o instanceof Double)
            job.add(key, (Double) o);
        else if (o instanceof BigDecimal)
            job.add(key, (BigDecimal) o);
        else if (o instanceof Boolean)
            job.add(key, (Boolean) o);
        else
            job.add(key, o.toString());
    }
    else if (objInsp.getCategory() == Category.LIST) {
        job.add(key, getJsonArrayFromFieldData(obj, objInsp, jsonFactory));
    }
    else {
        job.add(key, getJsonObjectFromFieldData(obj, objInsp, jsonFactory));
    }
}
 
Example 12
Source File: NetworkMessageEvent.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Takes all the necessary fields, attributes and parameters and assembles a valid JSON that can be sent over the
 * network. 
 * 
 */
private void buildMessageJson(){
	
	// create the factory
	JsonBuilderFactory jsonBuilderFactory = Json.createBuilderFactory(null);
	
	// build the thing
	JsonObjectBuilder mainBuilder = jsonBuilderFactory.createObjectBuilder();
	mainBuilder.add(ATTR_MESSAGETYPE, messageType)
		.add(ATTR_SOURCEOID, sourceOid)
		.add(ATTR_EVENTID, eventId);
	
	if (eventBody == null){
		mainBuilder.addNull(ATTR_EVENTBODY);
	} else {
		mainBuilder.add(ATTR_EVENTBODY, eventBody);
	}
	
	if (requestId != 0){
		mainBuilder.add(ATTR_REQUESTID, requestId);
	}
	
	// turn parameters into json
	JsonObjectBuilder parametersBuilder = jsonBuilderFactory.createObjectBuilder();
	if (!parameters.isEmpty()){
		for (Map.Entry<String, String> entry : parameters.entrySet()){
			// watch out for nulls
			if (entry.getValue() == null){
				parametersBuilder.addNull(entry.getKey());
			} else {
				parametersBuilder.add(entry.getKey(), entry.getValue());
			}
		}
	}
	
	mainBuilder.add(ATTR_PARAMETERS, parametersBuilder);
	
	jsonRepresentation = mainBuilder.build();
	
}
 
Example 13
Source File: RequestJsonBuilder.java    From coffee-testing with Apache License 2.0 5 votes vote down vote up
JsonObject forOrder(Order order) {
    JsonObjectBuilder builder = Json.createObjectBuilder();

    if (order.getType() != null)
        builder.add("type", order.getType());
    else
        builder.addNull("type");
    if (order.getOrigin() != null)
        builder.add("origin", order.getOrigin());
    else
        builder.addNull("origin");

    return builder.build();
}
 
Example 14
Source File: ExecutionService.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private JsonObjectBuilder addDataToResponse(JsonObjectBuilder returnObjectBuilder, Object pojoData) {
    if (pojoData != null) {
        JsonValue data = toJsonValue(pojoData);
        return returnObjectBuilder.add(DATA, data);
    } else {
        return returnObjectBuilder.addNull(DATA);
    }
}
 
Example 15
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(); 
}
 
Example 16
Source File: JsonEventFormatter.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void add(final JsonObjectBuilder builder, final Map<String, Object> data) {
    for (Map.Entry<String, Object> entry : data.entrySet()) {
        final String key = entry.getKey();
        final Object value = entry.getValue();
        if (value == null) {
            builder.addNull(key);
        } else if (value instanceof Boolean) {
            builder.add(key, (Boolean) value);
        } else if (value instanceof Double) {
            builder.add(key, (Double) value);
        } else if (value instanceof Integer) {
            builder.add(key, (Integer) value);
        } else if (value instanceof Long) {
            builder.add(key, (Long) value);
        } else if (value instanceof String) {
            builder.add(key, (String) value);
        } else if (value instanceof BigDecimal) {
            builder.add(key, (BigDecimal) value);
        } else if (value instanceof BigInteger) {
            builder.add(key, (BigInteger) value);
        } else if (value instanceof Collection) {
            builder.add(key, factory.createArrayBuilder((Collection<?>) value));
        } else if (value instanceof Map) {
            final Map<?, ?> mapValue = (Map<?, ?>) value;
            final JsonObjectBuilder valueBuilder = factory.createObjectBuilder();
            // Convert the map to a string/object map
            final Map<String, Object> map = new LinkedHashMap<>();
            for (Map.Entry<?, ?> valueEntry : mapValue.entrySet()) {
                final Object valueKey = valueEntry.getKey();
                final Object valueValue = valueEntry.getValue();
                if (valueKey instanceof String) {
                    map.put((String) valueKey, valueValue);
                } else {
                    map.put(String.valueOf(valueKey), valueValue);
                }
            }
            add(valueBuilder, map);
            builder.add(key, valueBuilder);
        } else if (value instanceof JsonArrayBuilder) {
            builder.add(key, (JsonArrayBuilder) value);
        } else if (value instanceof JsonObjectBuilder) {
            builder.add(key, (JsonObjectBuilder) value);
        } else if (value instanceof JsonValue) {
            builder.add(key, (JsonValue) value);
        } else if (value.getClass().isArray()) {
            // We'll rely on the array builder to convert to the correct object type
            builder.add(key, factory.createArrayBuilder(Arrays.asList((Object[]) value)));
        } else {
            builder.add(key, String.valueOf(value));
        }
    }
}
 
Example 17
Source File: ApiServiceDispatcher.java    From iaf with Apache License 2.0 4 votes vote down vote up
private JsonObjectBuilder mapResponses(IAdapter adapter, MediaTypes contentType, JsonObjectBuilder schemas) {
	JsonObjectBuilder responses = Json.createObjectBuilder();

	PipeLine pipeline = adapter.getPipeLine();
	Json2XmlValidator validator = getJsonValidator(pipeline);
	JsonObjectBuilder schema = null;
	if(validator != null) {
		JsonObject jsonSchema = validator.createJsonSchemaDefinitions("#/components/schemas/");
		if(jsonSchema != null) {
			for (Entry<String,JsonValue> entry: jsonSchema.entrySet()) {
				schemas.add(entry.getKey(), entry.getValue());
			}
			String ref = validator.getMessageRoot(true);
			schema = Json.createObjectBuilder();
			schema.add("schema", Json.createObjectBuilder().add("$ref", "#/components/schemas/"+ref));
		}
	}

	Map<String, PipeLineExit> pipeLineExits = pipeline.getPipeLineExits();
	for(String exitPath : pipeLineExits.keySet()) {
		PipeLineExit ple = pipeLineExits.get(exitPath);
		int exitCode = ple.getExitCode();
		if(exitCode == 0) {
			exitCode = 200;
		}

		JsonObjectBuilder exit = Json.createObjectBuilder();

		Status status = Status.fromStatusCode(exitCode);
		exit.add("description", status.getReasonPhrase());
		if(!ple.getEmptyResult()) {
			JsonObjectBuilder content = Json.createObjectBuilder();
			if(schema == null) {
				content.addNull(contentType.getContentType());
			} else {
				content.add(contentType.getContentType(), schema);
			}
			exit.add("content", content);
		}

		responses.add(""+exitCode, exit);
	}
	return responses;
}
 
Example 18
Source File: JsonPartialReader.java    From incubator-batchee with Apache License 2.0 4 votes vote down vote up
private void parseObject(final JsonObjectBuilder builder) {
    String key = null;
    while (parser.hasNext()) {
        final JsonParser.Event next = parser.next();
        switch (next) {
            case KEY_NAME:
                key = parser.getString();
                break;

            case VALUE_STRING:
                builder.add(key, parser.getString());
                break;

            case START_OBJECT:
                final JsonObjectBuilder subObject = provider.createObjectBuilder();
                parseObject(subObject);
                builder.add(key, subObject);
                break;

            case START_ARRAY:
                final JsonArrayBuilder subArray = provider.createArrayBuilder();
                parseArray(subArray);
                builder.add(key, subArray);
                break;

            case VALUE_NUMBER:
                if (parser.isIntegralNumber()) {
                    builder.add(key, parser.getLong());
                } else {
                    builder.add(key, parser.getBigDecimal());
                }
                break;

            case VALUE_NULL:
                builder.addNull(key);
                break;

            case VALUE_TRUE:
                builder.add(key, true);
                break;

            case VALUE_FALSE:
                builder.add(key, false);
                break;

            case END_OBJECT:
                return;

            case END_ARRAY:
                throw new JsonParsingException("']', shouldn't occur", parser.getLocation());

            default:
                throw new JsonParsingException(next.name() + ", shouldn't occur", parser.getLocation());
        }
    }
}
 
Example 19
Source File: Action.java    From vicinity-gateway-api with GNU General Public License v3.0 2 votes vote down vote up
/**
 * This method retrieves the status of a {@link eu.bavenir.ogwapi.commons.Task task} in a form of JSON.
 * 
 * @param taskId ID of a task to be polled for status.
 * @return Status, timer values, return values, ... or null if there is no such task. 
 */
public JsonObject createTaskStatusJson(String taskId) {
	
	Task task = searchForTask(taskId, true);
	
	if (task == null) {
		
		logger.finest(this.actionId + ": Task " + taskId + " not found.");
		
		return null;
	}
	
	DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	// create the factory
	JsonBuilderFactory jsonBuilderFactory = Json.createBuilderFactory(null);
	JsonObjectBuilder mainBuilder = jsonBuilderFactory.createObjectBuilder();
	
	mainBuilder.add(ATTR_TASKID, taskId);
	mainBuilder.add(ATTR_STATUS, task.getTaskStatusString());
	
	Date taskCreationTime = new Date(task.getCreationTime());
	mainBuilder.add(ATTR_CREATIONTIME, df.format(taskCreationTime).toString());
	
	if (task.getStartTime() > 0) {
		Date taskStartTime = new Date(task.getStartTime());
		mainBuilder.add(ATTR_STARTTIME, df.format(taskStartTime).toString());
	}
	
	if (task.getEndTime() > 0) {
		Date taskEndTime = new Date(task.getEndTime());
		mainBuilder.add(ATTR_ENDTIME, df.format(taskEndTime).toString());
	}
	
	mainBuilder.add(ATTR_TOTALTIME, task.getRunningTime());
	
	

	if (task.getReturnValue() == null){
		mainBuilder.addNull(ATTR_RETURNVALUE);
	} else {
		mainBuilder.add(ATTR_RETURNVALUE, task.getReturnValue());
	}
 
	return mainBuilder.build();
	
}