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

The following examples show how to use javax.json.Json#createBuilderFactory() . 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: AvroRecordConvertersTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void avroRecordArrays() throws Exception {
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final RecordBuilderFactory factory = new AvroRecordBuilderFactoryProvider().apply("test");
        final RecordConverters converters = new RecordConverters();
        final JsonBuilderFactory builderFactory = Json.createBuilderFactory(emptyMap());
        final Record record =
                converters
                        .toRecord(new RecordConverters.MappingMetaRegistry(),
                                builderFactory
                                        .createObjectBuilder()
                                        .add("value", builderFactory
                                                .createObjectBuilder()
                                                .add("somekey", builderFactory.createArrayBuilder().build()))
                                        .build(),
                                () -> jsonb, () -> factory);
        final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        SchemaRegistryCoder.of().encode(record, buffer);
        assertTrue(SchemaRegistryCoder
                .of()
                .decode(new ByteArrayInputStream(buffer.toByteArray()))
                .getRecord("value")
                .getArray(Object.class, "somekey")
                .isEmpty());
    }
}
 
Example 2
Source File: TestAzureLogAnalyticsProvenanceReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddField1() throws IOException, InterruptedException, InitializationException {

    final Map<String, Object> config = Collections.emptyMap();
    final JsonBuilderFactory factory = Json.createBuilderFactory(config);
    final JsonObjectBuilder builder = factory.createObjectBuilder();
    AzureLogAnalyticsProvenanceReportingTask.addField(builder, "TestKeyString", "StringValue", true);
    AzureLogAnalyticsProvenanceReportingTask.addField(builder, "TestKeyInteger", 2674440, true);
    AzureLogAnalyticsProvenanceReportingTask.addField(builder, "TestKeyLong", 1289904147324L, true);
    AzureLogAnalyticsProvenanceReportingTask.addField(builder, "TestKeyBoolean", true, true);
    AzureLogAnalyticsProvenanceReportingTask.addField(builder, "TestKeyNotSupportedObject", 1.25, true);
    AzureLogAnalyticsProvenanceReportingTask.addField(builder, "TestKeyNull", null, true);
    javax.json.JsonObject actualJson = builder.build();
    String expectedjsonString = "{" +
                                    "\"TestKeyString\": \"StringValue\"," +
                                    "\"TestKeyInteger\": 2674440," +
                                    "\"TestKeyLong\": 1289904147324," +
                                    "\"TestKeyBoolean\": true," +
                                    "\"TestKeyNotSupportedObject\": \"1.25\"," +
                                    "\"TestKeyNull\": null" +
                                "}";
    JsonObject expectedJson = new Gson().fromJson(expectedjsonString, JsonObject.class);
    assertEquals(expectedJson.toString(), actualJson.toString());
}
 
Example 3
Source File: NotificationRetryBean.java    From sample-acmegifts with Eclipse Public License 1.0 6 votes vote down vote up
@Retry(maxRetries = 2)
@Fallback(NotificationFallbackHandler.class)
public OccasionResponse makeNotificationConnection(
    String message,
    Orchestrator orchestrator,
    String jwtTokenString,
    String notification11ServiceUrl,
    String twitterHandle,
    String notificationServiceUrl)
    throws IOException {

  JsonBuilderFactory factory = Json.createBuilderFactory(null);
  JsonObjectBuilder builder = factory.createObjectBuilder();
  JsonObject notificationRequestPayload = builder.add(JSON_KEY_NOTIFICATION, message).build();
  Response notificationResponse =
      orchestrator.makeConnection(
          "POST", notificationServiceUrl, notificationRequestPayload.toString(), jwtTokenString);
  OccasionResponse occasionResponse =
      new OccasionResponse(notificationResponse, OccasionResponse.NOTIFICATION_TYPE_LOG, null);

  return occasionResponse;
}
 
Example 4
Source File: InitializrSpringCloudInfoServiceTests.java    From spring-cloud-release-tools with Apache License 2.0 6 votes vote down vote up
private Iterable<Milestone> buildMilestonesIterable() throws IOException {
	JsonBuilderFactory builderFactory = Json.createBuilderFactory(new HashMap<>());
	List<Milestone> milestonesList = new ArrayList<>();
	for (String m : milestoneStrings.keySet()) {
		Milestone milestone = mock(Milestone.class);
		String dueDate = milestoneStrings.get(m);
		JsonObjectBuilder builder = builderFactory.createObjectBuilder().add("title",
				m);
		if (dueDate == null) {
			builder.add("due_on", JsonValue.NULL);
		}
		else {
			builder.add("due_on", dueDate);
		}
		doReturn(builder.build()).when(milestone).json();
		milestonesList.add(milestone);
	}
	return new Iterable() {
		@Override
		public Iterator iterator() {
			return milestonesList.iterator();
		}
	};
}
 
Example 5
Source File: RestAgentConnector.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Very handy testing method that, if set in the configuration file, can be used instead of performOperation. This one does
 * not rely on functional agent and always returns positive results.
 *
 * @param operationCode Code of the HTTP operation, see the constants.
 * @param sourceOid The object ID of the source.
 * @param fullUrl Full URL of the Agent's end point to be reached.
 * @param body Body of the request.
 * @param parameters Parameters passed in the request.
 * @return Response message with the results.
 */
private NetworkMessageResponse performDummyOperation (byte operationCode, String sourceOid, String fullUrl,
		String body, Map<String, String> parameters) {

	// don't forget to put source OID as one of the parameters
	parameters.put(PARAM_SOURCEOID, sourceOid);

	String dummyResponseMessage =
			new String("Dummy REST Agent Connector received following data to perform request:"
					+ "\nOperation code: " + operationCode
					+ "\nParameters: " + parameters.toString()
					+ "\nFull URL: " + fullUrl
					+ "\nBody: " + body);

	logger.fine(dummyResponseMessage);

	JsonBuilderFactory jsonBuilderFactory = Json.createBuilderFactory(null);

	JsonObjectBuilder builder = jsonBuilderFactory.createObjectBuilder();

	builder.add(ATTR_DUMMY, dummyResponseMessage);

	NetworkMessageResponse response = new NetworkMessageResponse(config, logger);

	response.setError(false);
	response.setResponseCode(CodesAndReasons.CODE_200_OK);
	response.setResponseCodeReason(CodesAndReasons.REASON_200_OK);
	response.setResponseBody(builder.build().toString());

	return response;
}
 
Example 6
Source File: ConfigurationLoader.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
protected Optional<Routes> doLoad(final String content) {
    try (final Jsonb jsonb = JsonbBuilder.newBuilder()
                 .withProvider(loadJsonpProvider())
                 .withConfig(new JsonbConfig().setProperty("org.apache.johnzon.supports-comments", true))
                 .build()) {
        routes = jsonb.fromJson(content, Routes.class);
        final boolean hasRoutes = routes.routes != null && !routes.routes.isEmpty();
        if (routes.defaultRoute == null && !hasRoutes) {
            return Optional.empty();
        }
        if (hasRoutes) {
            // before merging, ensure all routes have an id to not duplicate default id
            routes.routes.stream().filter(it -> it.id == null).forEach(it -> it.id = newId());
        }
        if (routes.defaultRoute != null) {
            if (routes.defaultRoute.id == null) {
                routes.defaultRoute.id = "default";
            }
            if (routes.routes == null) { // no route were defined, consider it is the default route, /!\ empty means no route, don't default
                routes.routes = singletonList(routes.defaultRoute);
            }
            if (hasRoutes) {
                final JsonBuilderFactory jsonFactory = Json.createBuilderFactory(emptyMap());
                final JsonObject template = jsonb.fromJson(jsonb.toJson(routes.defaultRoute), JsonObject.class);
                routes.routes = routes.routes.stream().map(r -> merge(jsonb, jsonFactory, template, r)).collect(toList());
            }
        }
    } catch (final Exception e) {
        throw new IllegalArgumentException(e);
    }
    routes.routes.forEach(this::init);
    return Optional.of(routes);
}
 
Example 7
Source File: ProcessorImpl.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private JsonBuilderFactory jsonBuilderFactory() {
    if (jsonBuilderFactory == null) {
        synchronized (this) {
            if (jsonBuilderFactory == null) {
                jsonBuilderFactory =
                        ContainerFinder.Instance.get().find(plugin()).findService(JsonBuilderFactory.class);
            }
            if (jsonBuilderFactory == null) {
                jsonBuilderFactory = Json.createBuilderFactory(emptyMap());
            }
        }
    }
    return jsonBuilderFactory;
}
 
Example 8
Source File: SchemaRegistryCoderTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void changingSchema() throws Exception {
    try (final Jsonb jsonb = JsonbBuilder.create()) {
        final RecordBuilderFactory factory = new AvroRecordBuilderFactoryProvider().apply("test");
        final RecordConverters converters = new RecordConverters();
        final JsonBuilderFactory builderFactory = Json.createBuilderFactory(emptyMap());
        final Record record1 = converters
                .toRecord(new RecordConverters.MappingMetaRegistry(),
                        builderFactory.createObjectBuilder().add("value", "firstSchemaUsesAString").build(),
                        () -> jsonb, () -> factory);
        // go through the encoder with a schema which will change
        final ByteArrayOutputStream buffer1 = new ByteArrayOutputStream();
        SchemaRegistryCoder.of().encode(record1, buffer1);

        final Record decoded1 = SchemaRegistryCoder.of().decode(new ByteArrayInputStream(buffer1.toByteArray()));
        assertEquals("firstSchemaUsesAString", decoded1.getString("value"));

        final Record record2 = converters
                .toRecord(new RecordConverters.MappingMetaRegistry(),
                        builderFactory
                                .createObjectBuilder()
                                .add("value",
                                        Json
                                                .createArrayBuilder()
                                                .add(Json.createValue("a"))
                                                .add(Json.createValue("b"))
                                                .build())
                                .build(),
                        () -> jsonb, () -> factory);
        final ByteArrayOutputStream buffer2 = new ByteArrayOutputStream();
        SchemaRegistryCoder.of().encode(record2, buffer2);

        final Record decoded2 = SchemaRegistryCoder.of().decode(new ByteArrayInputStream(buffer2.toByteArray()));
        assertEquals(asList("a", "b"), decoded2.getArray(String.class, "value"));
    }
}
 
Example 9
Source File: Generator.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private static void writeServerOpenApi(final File output, final String resource, final String version)
        throws Exception {
    try (final InputStream source = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
            final Jsonb jsonb = JsonbBuilder.create(new JsonbConfig())) {
        final String newJson = IO.slurp(source);
        String oldJson = !output.exists() ? "{}" : String.join("\n", Files.readAllLines(output.toPath()));
        final int start = oldJson.indexOf(".swaggerUi = ");
        if (start > 0) {
            oldJson = oldJson.substring(start + ".swaggerUi = ".length());
        }

        final int end = oldJson.indexOf(";</script>");
        if (end > 0) {
            oldJson = oldJson.substring(0, end);
        }
        final JsonBuilderFactory builderFactory = Json.createBuilderFactory(emptyMap());
        final JsonObject oldApi = !oldJson.startsWith("{") ? builderFactory.createObjectBuilder().build()
                : jsonb.fromJson(oldJson, JsonObject.class);
        final JsonObject newApi = builderFactory
                .createObjectBuilder(jsonb.fromJson(newJson, JsonObject.class))
                .add("servers", builderFactory
                        .createArrayBuilder()
                        .add(builderFactory
                                .createObjectBuilder()
                                .add("url", String
                                        .format("https://talend.github.io/component-runtime/main/%s/examples/apidemo",
                                                version))))
                .build();
        if (!oldJson.startsWith("{") || !areEqualsIgnoringOrder(oldApi, newApi)) {
            try (final OutputStream writer = new WriteIfDifferentStream(output)) {
                writer
                        .write(("= Component Server API\n:page-talend_swaggerui:\n\n++++\n<script>\n"
                                + "(window.talend " + "= (window.talend || {})).swaggerUi = " + newApi.toString()
                                + ";</script>\n" + "<div id=\"swagger-ui\"></div>\n++++\n")
                                        .getBytes(StandardCharsets.UTF_8));
            }
        }
    }
}
 
Example 10
Source File: JsonEventFormatter.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private JsonEventFormatter(final Map<String, Object> metaData, final String timestampKey,
                           final DateTimeFormatter formatter, final boolean includeTimestamp) {
    this.metaData = metaData;
    this.timestampKey = timestampKey;
    this.formatter = formatter;
    this.includeTimestamp = includeTimestamp;
    factory = Json.createBuilderFactory(Collections.emptyMap());
}
 
Example 11
Source File: ResourceProcessor.java    From FHIR with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JsonReaderFactory jsonReaderFactory = Json.createReaderFactory(null);
    JsonWriterFactory jsonWriterFactory = Json.createWriterFactory(null);
    JsonBuilderFactory jsonBuilderFactory = Json.createBuilderFactory(null);

    File dir = new File("src/main/resources/hl7/fhir/us/davinci-pdex-plan-net/package/");
    for (File file : dir.listFiles()) {
        String fileName = file.getName();
        if (!fileName.endsWith(".json") || file.isDirectory()) {
            continue;
        }
        JsonObject jsonObject = null;
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            JsonReader jsonReader = jsonReaderFactory.createReader(reader);
            jsonObject = jsonReader.readObject();

            JsonObjectBuilder jsonObjectBuilder = jsonBuilderFactory.createObjectBuilder(jsonObject);

            JsonObject text = jsonObject.getJsonObject("text");
            if (text != null) {
                JsonObjectBuilder textBuilder = jsonBuilderFactory.createObjectBuilder(text);
                String div = text.getString("div");
                div = div.replace("<p><pre>", "<pre>").replace("</pre></p>", "</pre>");
                textBuilder.add("div", div);
                jsonObjectBuilder.add("text", textBuilder);
            }

            if (!jsonObject.containsKey("version")) {
                System.out.println("file: " + file + " does not have a version");
                jsonObjectBuilder.add("version", "0.1.0");
            }

            jsonObject = jsonObjectBuilder.build();
        }
        try (FileWriter writer = new FileWriter(file)) {
            JsonWriter jsonWriter = jsonWriterFactory.createWriter(writer);
            jsonWriter.write(jsonObject);
        }
    }
}
 
Example 12
Source File: TestAzureLogAnalyticsProvenanceReportingTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddField3() throws IOException, InterruptedException, InitializationException {

    final Map<String, Object> config = Collections.emptyMap();
    final JsonBuilderFactory factory = Json.createBuilderFactory(config);
    final JsonObjectBuilder builder = factory.createObjectBuilder();
    Collection<String> values = new ArrayList<String>();
    values.add("TestValueString1");
    values.add("TestValueString2");
    AzureLogAnalyticsProvenanceReportingTask.addField(builder, factory, "TestKeyString", values, true);
    javax.json.JsonObject actualJson = builder.build();
    String expectedjsonString = "{\"TestKeyString\":[\"TestValueString1\",\"TestValueString2\"]}";
    JsonObject expectedJson = new Gson().fromJson(expectedjsonString, JsonObject.class);
    assertEquals(expectedJson.toString(), actualJson.toString());
}
 
Example 13
Source File: AmbariReportingTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
@OnScheduled
public void setup(final ConfigurationContext context) throws IOException {
    final Map<String, ?> config = Collections.emptyMap();
    factory = Json.createBuilderFactory(config);
    client = createClient();
    virtualMachineMetrics = JmxJvmMetrics.getInstance();
    previousMetrics = null;
}
 
Example 14
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 15
Source File: TestAzureLogAnalyticsProvenanceReportingTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddField2() throws IOException, InterruptedException, InitializationException {

    final Map<String, Object> config = Collections.emptyMap();
    final JsonBuilderFactory factory = Json.createBuilderFactory(config);
    final JsonObjectBuilder builder = factory.createObjectBuilder();
    Map<String, String> values = new HashMap<String, String>();
    values.put("TestKeyString1", "StringValue1");
    values.put("TestKeyString2", "StringValue2");
    AzureLogAnalyticsProvenanceReportingTask.addField(builder, factory, "TestKeyString", values, true);
    javax.json.JsonObject actualJson = builder.build();
    String expectedjsonString = "{\"TestKeyString\":{\"TestKeyString2\":\"StringValue2\",\"TestKeyString1\":\"StringValue1\"}}";
    JsonObject expectedJson = new Gson().fromJson(expectedjsonString, JsonObject.class);
    assertEquals(expectedJson.toString(), actualJson.toString());
}
 
Example 16
Source File: ConnectionDescriptor.java    From vicinity-gateway-api with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Retrieves the status of local or remote event channel. 
 * 
 * @param destinationOid ID of the object that is to be polled (it can be the local owner verifying the state of its channel.
 * @param eventId ID of the event.
 * @param parameters Any parameters to be sent (usually none).
 * @param body Any body to be sent (usually none).
 * @return Status message.
 */
public StatusMessage getEventChannelStatus(String destinationOid, String eventId, Map<String, String> parameters, 
		String body) {
	
	String statusCodeReason;
	StatusMessage statusMessage;
	
	// when the owner wants to check its own status, there is no need to send it across the network
	if (destinationOid.equals(this.objectId)) {

		EventChannel eventChannel = searchForEventChannel(eventId);
		
		if (eventChannel == null) {
			statusCodeReason = new String("Local request for providing status of invalid event "
					+ "channel was received.");
			
			logger.info(this.objectId + ": " + statusCodeReason);
			
			statusMessage = new StatusMessage(
					true, 
					CodesAndReasons.CODE_404_NOTFOUND, 
					CodesAndReasons.REASON_404_NOTFOUND + statusCodeReason,
					StatusMessage.CONTENTTYPE_APPLICATIONJSON);
			
			return statusMessage;

		} else {
			
			statusCodeReason = new String("Local request for providing status of event channel " 
					 + eventId + ".");
			
			logger.info(this.objectId + ": " + statusCodeReason);
			
			statusMessage = new StatusMessage(
					false, 
					CodesAndReasons.CODE_200_OK, 
					CodesAndReasons.REASON_200_OK + statusCodeReason,
					StatusMessage.CONTENTTYPE_APPLICATIONJSON);
			
			// also include that we are not subscribed to our channel
			JsonBuilderFactory jsonBuilderFactory = Json.createBuilderFactory(null);
			JsonObjectBuilder jsonBuilder = jsonBuilderFactory.createObjectBuilder();
			
			jsonBuilder.add(EventChannel.ATTR_ACTIVE, eventChannel.isActive());
			jsonBuilder.add(EventChannel.ATTR_SUBSCRIBED, false);
			
			statusMessage.addMessageJson(jsonBuilder);
			
		}
		
		return statusMessage;
	} 
	
	// otherwise if it is not local continue as normal
	
	Map<String, String> attributes = new HashMap<String,String>();
	attributes.put(NetworkMessageRequest.ATTR_EID, eventId);
	
	logger.info(this.objectId + ": Sending request to get status of remote event channel " + eventId + " on " 
				+ destinationOid + " with parameters: \n" + parameters.toString() + "\nand body: \n" + body);
	
	return sendRequestForRemoteOperation(
			NetworkMessageRequest.OPERATION_GETEVENTCHANNELSTATUS, 
			destinationOid, 
			attributes, 
			parameters,
			body,
			"GETEVENTCHANNELSTATUS");	
}
 
Example 17
Source File: TestMetricsBuilder.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testBuildMetricsObject() {
    final Map<String, ?> config = Collections.emptyMap();
    final JsonBuilderFactory factory = Json.createBuilderFactory(config);

    final String instanceId = "1234-5678-1234-5678";
    final String applicationId = "NIFI";
    final String hostname = "localhost";
    final long timestamp = System.currentTimeMillis();

    final Map<String,String> metrics = new HashMap<>();
    metrics.put("a", "1");
    metrics.put("b", "2");

    final MetricsBuilder metricsBuilder = new MetricsBuilder(factory);
    final JsonObject metricsObject = metricsBuilder
            .applicationId(applicationId)
            .instanceId(instanceId)
            .hostname(hostname)
            .timestamp(timestamp)
            .addAllMetrics(metrics)
            .build();

    final JsonArray metricsArray = metricsObject.getJsonArray("metrics");
    Assert.assertNotNull(metricsArray);
    Assert.assertEquals(2, metricsArray.size());

    JsonObject firstMetric = metricsArray.getJsonObject(0);
    if (!"a".equals(firstMetric.getString(MetricFields.METRIC_NAME))) {
        firstMetric = metricsArray.getJsonObject(1);
    }

    Assert.assertEquals("a", firstMetric.getString(MetricFields.METRIC_NAME));
    Assert.assertEquals(applicationId, firstMetric.getString(MetricFields.APP_ID));
    Assert.assertEquals(instanceId, firstMetric.getString(MetricFields.INSTANCE_ID));
    Assert.assertEquals(hostname, firstMetric.getString(MetricFields.HOSTNAME));
    Assert.assertEquals(String.valueOf(timestamp), firstMetric.getString(MetricFields.TIMESTAMP));

    final JsonObject firstMetricValues = firstMetric.getJsonObject("metrics");
    Assert.assertEquals("1", firstMetricValues.getString("" + timestamp));
}
 
Example 18
Source File: TestMetricsBuilder.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testBuildMetricsObject() {
    final Map<String, ?> config = Collections.emptyMap();
    final JsonBuilderFactory factory = Json.createBuilderFactory(config);

    final String instanceId = "1234-5678-1234-5678";
    final String applicationId = "NIFI";
    final String hostname = "localhost";
    final long timestamp = System.currentTimeMillis();

    final Map<String,String> metrics = new HashMap<>();
    metrics.put("a", "1");
    metrics.put("b", "2");

    final MetricsBuilder metricsBuilder = new MetricsBuilder(factory);
    final JsonObject metricsObject = metricsBuilder
            .applicationId(applicationId)
            .instanceId(instanceId)
            .hostname(hostname)
            .timestamp(timestamp)
            .addAllMetrics(metrics)
            .build();

    final JsonArray metricsArray = metricsObject.getJsonArray("metrics");
    Assert.assertNotNull(metricsArray);
    Assert.assertEquals(2, metricsArray.size());

    JsonObject firstMetric = metricsArray.getJsonObject(0);
    if (!"a".equals(firstMetric.getString(MetricFields.METRIC_NAME))) {
        firstMetric = metricsArray.getJsonObject(1);
    }

    Assert.assertEquals("a", firstMetric.getString(MetricFields.METRIC_NAME));
    Assert.assertEquals(applicationId, firstMetric.getString(MetricFields.APP_ID));
    Assert.assertEquals(instanceId, firstMetric.getString(MetricFields.INSTANCE_ID));
    Assert.assertEquals(hostname, firstMetric.getString(MetricFields.HOSTNAME));
    Assert.assertEquals(String.valueOf(timestamp), firstMetric.getString(MetricFields.TIMESTAMP));

    final JsonObject firstMetricValues = firstMetric.getJsonObject("metrics");
    Assert.assertEquals("1", firstMetricValues.getString("" + timestamp));
}
 
Example 19
Source File: SparqlQuery.java    From vicinity-gateway-api with GNU General Public License v3.0 3 votes vote down vote up
public SparqlQuery(XMLConfiguration config, ConnectionDescriptor descriptor, Logger logger) {
	this.descriptor = descriptor;
	this.logger = logger;
	
	gwapiServicesUrl = config.getString(CONFIG_PARAM_GWAPISERVICESURL, CONFIG_DEF_GWAPISERVICESURL);
	
	jsonBuilderFactory = Json.createBuilderFactory(null);
	
	
}
 
Example 20
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();
	
}