Java Code Examples for javax.json.JsonBuilderFactory#createObjectBuilder()

The following examples show how to use javax.json.JsonBuilderFactory#createObjectBuilder() . 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: SiteToSiteProvenanceReportingTask.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private static void addField(final JsonObjectBuilder builder, final JsonBuilderFactory factory, final String key, final Map<String, String> values) {
    if (values == null) {
        return;
    }

    final JsonObjectBuilder mapBuilder = factory.createObjectBuilder();
    for (final Map.Entry<String, String> entry : values.entrySet()) {
        if (entry.getKey() == null || entry.getValue() == null) {
            continue;
        }

        mapBuilder.add(entry.getKey(), entry.getValue());
    }

    builder.add(key, mapBuilder);
}
 
Example 2
Source File: SiteToSiteProvenanceReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
private static void addField(final JsonObjectBuilder builder, final JsonBuilderFactory factory, final String key, final Map<String, String> values, Boolean allowNullValues) {
    if (values != null) {

        final JsonObjectBuilder mapBuilder = factory.createObjectBuilder();
        for (final Map.Entry<String, String> entry : values.entrySet()) {

            if (entry.getKey() == null ) {
                continue;
            }else if(entry.getValue() == null ){
                if(allowNullValues) {
                    mapBuilder.add(entry.getKey(), JsonValue.NULL);
                }
            }else {
                mapBuilder.add(entry.getKey(), entry.getValue());
            }
        }

        builder.add(key, mapBuilder);

    }else if(allowNullValues){
        builder.add(key,JsonValue.NULL);
    }
}
 
Example 3
Source File: SiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
private static void addField(final JsonObjectBuilder builder, final JsonBuilderFactory factory, final String key, final Map<String, Long> values, final Boolean allowNullValues) {

        if (values != null) {

            final JsonObjectBuilder mapBuilder = factory.createObjectBuilder();
            for (final Map.Entry<String, Long> entry : values.entrySet()) {

                if (entry.getKey() == null ) {
                    continue;
                }else if(entry.getValue() == null ){
                    if(allowNullValues)
                        mapBuilder.add(entry.getKey(),JsonValue.NULL);
                }else{
                    mapBuilder.add(entry.getKey(), entry.getValue());
                }
            }

            builder.add(key, mapBuilder);

        }else if(allowNullValues){
            builder.add(key,JsonValue.NULL);
        }
    }
 
Example 4
Source File: SiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void serializePortStatus(final String componentType, final JsonArrayBuilder arrayBuilder, final JsonBuilderFactory factory, final PortStatus status,
        final DateFormat df, final String hostname, final String applicationName, final String platform, final ProcessGroupStatus parent, final Date currentDate, final Boolean allowNullValues) {
    final JsonObjectBuilder builder = factory.createObjectBuilder();
    final String componentName = status.getName();

    if (componentMatchesFilters(componentType, componentName)) {
        addCommonFields(builder, df, hostname, applicationName, platform, parent, currentDate,
                componentType, componentName, allowNullValues);

        addField(builder, "componentId", status.getId(), allowNullValues);
        addField(builder, "activeThreadCount", status.getActiveThreadCount(), allowNullValues);
        addField(builder, "bytesReceived", status.getBytesReceived(), allowNullValues);
        addField(builder, "bytesSent", status.getBytesSent(), allowNullValues);
        addField(builder, "flowFilesReceived", status.getFlowFilesReceived(), allowNullValues);
        addField(builder, "flowFilesSent", status.getFlowFilesSent(), allowNullValues);
        addField(builder, "inputBytes", status.getInputBytes(), allowNullValues);
        addField(builder, "inputCount", status.getInputCount(), allowNullValues);
        addField(builder, "outputBytes", status.getOutputBytes(), allowNullValues);
        addField(builder, "outputCount", status.getOutputCount(), allowNullValues);
        addField(builder, "runStatus", status.getRunStatus() == null ? null : status.getRunStatus().name(), allowNullValues);
        addField(builder, "transmitting", status.isTransmitting(), allowNullValues);

        arrayBuilder.add(builder.build());
    }
}
 
Example 5
Source File: SiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void serializeRemoteProcessGroupStatus(final JsonArrayBuilder arrayBuilder, final JsonBuilderFactory factory,
        final RemoteProcessGroupStatus status, final DateFormat df, final String hostname, final String applicationName,
        final String platform, final ProcessGroupStatus parent, final Date currentDate, final Boolean allowNullValues) {
    final JsonObjectBuilder builder = factory.createObjectBuilder();
    final String componentType = "RemoteProcessGroup";
    final String componentName = status.getName();

    if (componentMatchesFilters(componentType, componentName)) {
        addCommonFields(builder, df, hostname, applicationName, platform, parent, currentDate,
                componentType, componentName, allowNullValues);

        addField(builder, "componentId", status.getId(), allowNullValues);
        addField(builder, "activeRemotePortCount", status.getActiveRemotePortCount(), allowNullValues);
        addField(builder, "activeThreadCount", status.getActiveThreadCount(), allowNullValues);
        addField(builder, "inactiveRemotePortCount", status.getInactiveRemotePortCount(), allowNullValues);
        addField(builder, "receivedContentSize", status.getReceivedContentSize(), allowNullValues);
        addField(builder, "receivedCount", status.getReceivedCount(), allowNullValues);
        addField(builder, "sentContentSize", status.getSentContentSize(), allowNullValues);
        addField(builder, "sentCount", status.getSentCount(), allowNullValues);
        addField(builder, "averageLineageDuration", status.getAverageLineageDuration(), allowNullValues);
        addField(builder, "transmissionStatus", status.getTransmissionStatus() == null ? null : status.getTransmissionStatus().name(), allowNullValues);
        addField(builder, "targetURI", status.getTargetUri(), allowNullValues);

        arrayBuilder.add(builder.build());
    }
}
 
Example 6
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 7
Source File: OccasionResource.java    From sample-acmegifts with Eclipse Public License 1.0 6 votes vote down vote up
Response buildPostRunResponse(OccasionResponse occasionResponse) {

    Throwable notificationThrowable = occasionResponse.getNotificationThrowable();
    String requestResponse = occasionResponse.getNotificationType();
    if (notificationThrowable != null) {
      logger.fine("Throwable message: " + notificationThrowable.getMessage());
    }
    JsonBuilderFactory factory = Json.createBuilderFactory(null);
    JsonObjectBuilder builder = factory.createObjectBuilder();
    JsonObject responseBody = null;
    if (requestResponse.equals(OccasionResponse.NOTIFICATION_TYPE_LOG)
        || requestResponse.equals(OccasionResponse.NOTIFICATION_TYPE_TWEET)) {
      responseBody = builder.add(JSON_KEY_OCCASION_POST_RUN_SUCCESS, requestResponse).build();
    } else {
      responseBody = builder.add(JSON_KEY_OCCASION_POST_RUN_ERROR, requestResponse).build();
    }
    return Response.ok(responseBody, MediaType.APPLICATION_JSON).build();
  }
 
Example 8
Source File: AzureLogAnalyticsProvenanceReportingTask.java    From nifi with Apache License 2.0 6 votes vote down vote up
public static void addField(final JsonObjectBuilder builder, final JsonBuilderFactory factory, final String key,
                final Map<String, String> values, Boolean allowNullValues) {
        if (values != null) {
                final JsonObjectBuilder mapBuilder = factory.createObjectBuilder();
                for (final Map.Entry<String, String> entry : values.entrySet()) {

                        if (entry.getKey() == null) {
                                continue;
                        } else if (entry.getValue() == null) {
                                if (allowNullValues) {
                                        mapBuilder.add(entry.getKey(), JsonValue.NULL);
                                }
                        } else {
                                mapBuilder.add(entry.getKey(), entry.getValue());
                        }
                }

                builder.add(key, mapBuilder);

        } else if (allowNullValues) {
                builder.add(key, JsonValue.NULL);
        }
}
 
Example 9
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 10
Source File: SiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void serializeProcessorStatus(final JsonArrayBuilder arrayBuilder, final JsonBuilderFactory factory, final ProcessorStatus status, final DateFormat df,
        final String hostname, final String applicationName, final String platform, final ProcessGroupStatus parent, final Date currentDate, final Boolean allowNullValues) {
    final JsonObjectBuilder builder = factory.createObjectBuilder();
    final String componentType = "Processor";
    final String componentName = status.getName();

    if (componentMatchesFilters(componentType, componentName)) {
        addCommonFields(builder, df, hostname, applicationName, platform, parent, currentDate, componentType, componentName, allowNullValues);

        addField(builder, "componentId", status.getId(), allowNullValues);
        addField(builder, "processorType", status.getType(), allowNullValues);
        addField(builder, "averageLineageDurationMS", status.getAverageLineageDuration(), allowNullValues);
        addField(builder, "bytesRead", status.getBytesRead(), allowNullValues);
        addField(builder, "bytesWritten", status.getBytesWritten(), allowNullValues);
        addField(builder, "bytesReceived", status.getBytesReceived(), allowNullValues);
        addField(builder, "bytesSent", status.getBytesSent(), allowNullValues);
        addField(builder, "flowFilesRemoved", status.getFlowFilesRemoved(), allowNullValues);
        addField(builder, "flowFilesReceived", status.getFlowFilesReceived(), allowNullValues);
        addField(builder, "flowFilesSent", status.getFlowFilesSent(), allowNullValues);
        addField(builder, "inputCount", status.getInputCount(), allowNullValues);
        addField(builder, "inputBytes", status.getInputBytes(), allowNullValues);
        addField(builder, "outputCount", status.getOutputCount(), allowNullValues);
        addField(builder, "outputBytes", status.getOutputBytes(), allowNullValues);
        addField(builder, "activeThreadCount", status.getActiveThreadCount(), allowNullValues);
        addField(builder, "terminatedThreadCount", status.getTerminatedThreadCount(), allowNullValues);
        addField(builder, "invocations", status.getInvocations(), allowNullValues);
        addField(builder, "processingNanos", status.getProcessingNanos(), allowNullValues);
        addField(builder, "runStatus", status.getRunStatus() == null ? null : status.getRunStatus().name(), allowNullValues);
        addField(builder, "executionNode", status.getExecutionNode() == null ? null : status.getExecutionNode().name(), allowNullValues);
        addField(builder, factory, "counters", status.getCounters(), allowNullValues);

        arrayBuilder.add(builder.build());
    }
}
 
Example 11
Source File: SiteToSiteStatusReportingTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void serializeConnectionStatus(final JsonArrayBuilder arrayBuilder, final JsonBuilderFactory factory, final ConnectionStatus status, final DateFormat df,
        final String hostname, final String applicationName, final String platform, final ProcessGroupStatus parent, final Date currentDate, final Boolean allowNullValues) {
    final JsonObjectBuilder builder = factory.createObjectBuilder();
    final String componentType = "Connection";
    final String componentName = status.getName();

    if (componentMatchesFilters(componentType, componentName)) {
        addCommonFields(builder, df, hostname, applicationName, platform, parent, currentDate,
                componentType, componentName, allowNullValues);

        addField(builder, "componentId", status.getId(), allowNullValues);
        addField(builder, "sourceId", status.getSourceId(), allowNullValues);
        addField(builder, "sourceName", status.getSourceName(), allowNullValues);
        addField(builder, "destinationId", status.getDestinationId(), allowNullValues);
        addField(builder, "destinationName", status.getDestinationName(), allowNullValues);
        addField(builder, "maxQueuedBytes", status.getMaxQueuedBytes(), allowNullValues);
        addField(builder, "maxQueuedCount", status.getMaxQueuedCount(), allowNullValues);
        addField(builder, "queuedBytes", status.getQueuedBytes(), allowNullValues);
        addField(builder, "queuedCount", status.getQueuedCount(), allowNullValues);
        addField(builder, "inputBytes", status.getInputBytes(), allowNullValues);
        addField(builder, "inputCount", status.getInputCount(), allowNullValues);
        addField(builder, "outputBytes", status.getOutputBytes(), allowNullValues);
        addField(builder, "outputCount", status.getOutputCount(), allowNullValues);
        addField(builder, "backPressureBytesThreshold", status.getBackPressureBytesThreshold(), allowNullValues);
        addField(builder, "backPressureObjectThreshold", status.getBackPressureObjectThreshold(), allowNullValues);
        addField(builder, "backPressureDataSizeThreshold", status.getBackPressureDataSizeThreshold(), allowNullValues);
        addField(builder, "isBackPressureEnabled", Boolean.toString((status.getBackPressureObjectThreshold() > 0 && status.getBackPressureObjectThreshold() <= status.getQueuedCount())
                || (status.getBackPressureBytesThreshold() > 0 && status.getBackPressureBytesThreshold() <= status.getMaxQueuedBytes())), allowNullValues);

        arrayBuilder.add(builder.build());
    }
}
 
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: 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 14
Source File: JsonBuilderUtilsTest.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void addsProperty() {
	final JsonProvider provider = JsonProvider.provider();
	final JsonBuilderFactory builderFactory = provider
			.createBuilderFactory(null);
	final JsonObjectBuilder builder = builderFactory.createObjectBuilder();
	JsonBuilderUtils.add(builderFactory, builder, "null", null);
	JsonBuilderUtils.add(builderFactory, builder, "true", true);
	JsonBuilderUtils.add(builderFactory, builder, "string", "string");
	JsonBuilderUtils.add(builderFactory, builder, "char", 'c');
	JsonBuilderUtils.add(builderFactory, builder, "bigInteger",
			BigInteger.TEN);
	JsonBuilderUtils.add(builderFactory, builder, "bigDecimal",
			BigDecimal.valueOf(1111, 2));
	JsonBuilderUtils.add(builderFactory, builder, "float", 22f);
	JsonBuilderUtils.add(builderFactory, builder, "double", 22d);
	JsonBuilderUtils.add(builderFactory, builder, "byte", (byte) 33);
	JsonBuilderUtils.add(builderFactory, builder, "int", (int) 44);
	JsonBuilderUtils.add(builderFactory, builder, "short", (int) 55);
	JsonBuilderUtils.add(builderFactory, builder, "list",
			Arrays.<Object> asList("a", 0xbc, "d"));
	JsonBuilderUtils.add(builderFactory, builder, "array", new Object[] {
			1, "2", 3, false });

	JsonBuilderUtils.add(builderFactory, builder, "map",
			Collections.singletonMap("foo", "bar"));
	// provider.createWriter(System.out).write(builder.build());
}
 
Example 15
Source File: RecordJsonMapper.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
private JsonVisitor(final Singer singer, final RecordService service,
        final JsonBuilderFactory jsonBuilderFactory) {
    this.singer = singer;
    this.service = service;
    this.factory = jsonBuilderFactory;
    this.builder = jsonBuilderFactory.createObjectBuilder();
}
 
Example 16
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 17
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 18
Source File: SiteToSiteBulletinReportingTask.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ReportingContext context) {

    final boolean isClustered = context.isClustered();
    final String nodeId = context.getClusterNodeIdentifier();
    if (nodeId == null && isClustered) {
        getLogger().debug("This instance of NiFi is configured for clustering, but the Cluster Node Identifier is not yet available. "
            + "Will wait for Node Identifier to be established.");
        return;
    }

    final BulletinQuery bulletinQuery = new BulletinQuery.Builder().after(lastSentBulletinId).build();
    final List<Bulletin> bulletins = context.getBulletinRepository().findBulletins(bulletinQuery);

    if(bulletins == null || bulletins.isEmpty()) {
        getLogger().debug("No events to send because no events are stored in the repository.");
        return;
    }

    final OptionalLong opMaxId = bulletins.stream().mapToLong(t -> t.getId()).max();
    final Long currMaxId = opMaxId.isPresent() ? opMaxId.getAsLong() : -1;

    if(currMaxId < lastSentBulletinId){
        getLogger().warn("Current bulletin max id is {} which is less than what was stored in state as the last queried event, which was {}. "
                + "This means the bulletins repository restarted its ids. Restarting querying from the beginning.", new Object[]{currMaxId, lastSentBulletinId});
        lastSentBulletinId = -1;
    }

    if (currMaxId == lastSentBulletinId) {
        getLogger().debug("No events to send due to the current max id being equal to the last id that was sent.");
        return;
    }

    final String platform = context.getProperty(SiteToSiteUtils.PLATFORM).evaluateAttributeExpressions().getValue();
    final Boolean allowNullValues = context.getProperty(ALLOW_NULL_VALUES).asBoolean();

    final Map<String, ?> config = Collections.emptyMap();
    final JsonBuilderFactory factory = Json.createBuilderFactory(config);
    final JsonObjectBuilder builder = factory.createObjectBuilder();

    final DateFormat df = new SimpleDateFormat(TIMESTAMP_FORMAT);
    df.setTimeZone(TimeZone.getTimeZone("Z"));

    final long start = System.nanoTime();

    // Create a JSON array of all the events in the current batch
    final JsonArrayBuilder arrayBuilder = factory.createArrayBuilder();
    for (final Bulletin bulletin : bulletins) {
        if(bulletin.getId() > lastSentBulletinId) {
            arrayBuilder.add(serialize(factory, builder, bulletin, df, platform, nodeId, allowNullValues));
        }
    }
    final JsonArray jsonArray = arrayBuilder.build();

    // Send the JSON document for the current batch
    Transaction transaction = null;
    try {
        // Lazily create SiteToSiteClient to provide a StateManager
        setup(context);

        transaction = getClient().createTransaction(TransferDirection.SEND);
        if (transaction == null) {
            getLogger().info("All destination nodes are penalized; will attempt to send data later");
            return;
        }

        final Map<String, String> attributes = new HashMap<>();
        final String transactionId = UUID.randomUUID().toString();
        attributes.put("reporting.task.transaction.id", transactionId);
        attributes.put("reporting.task.name", getName());
        attributes.put("reporting.task.uuid", getIdentifier());
        attributes.put("reporting.task.type", this.getClass().getSimpleName());
        attributes.put("mime.type", "application/json");

        sendData(context, transaction, attributes, jsonArray);
        transaction.confirm();
        transaction.complete();

        final long transferMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
        getLogger().info("Successfully sent {} Bulletins to destination in {} ms; Transaction ID = {}; First Event ID = {}",
                new Object[]{bulletins.size(), transferMillis, transactionId, bulletins.get(0).getId()});
    } catch (final Exception e) {
        if (transaction != null) {
            transaction.error();
        }
        if (e instanceof ProcessException) {
            throw (ProcessException) e;
        } else {
            throw new ProcessException("Failed to send Bulletins to destination due to IOException:" + e.getMessage(), e);
        }
    }

    lastSentBulletinId = currMaxId;
}
 
Example 19
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 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();
	
}