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

The following examples show how to use javax.json.JsonBuilderFactory#createArrayBuilder() . 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 5 votes vote down vote up
private static JsonArrayBuilder createJsonArray(JsonBuilderFactory factory, final Collection<String> values) {
    final JsonArrayBuilder builder = factory.createArrayBuilder();
    for (final String value : values) {
        if (value != null) {
            builder.add(value);
        }
    }
    return builder;
}
 
Example 2
Source File: BrowserWebSocketClientShared.java    From rogue-cloud with Apache License 2.0 5 votes vote down vote up
private static JsonArrayBuilder convertSingle(Tile t, JsonBuilderFactory factory, long ticks) {
		JsonArrayBuilder outer = factory.createArrayBuilder();
		
		if(t == null) {
			throw new IllegalArgumentException();
		}
		
		// When there are multiple creatures on the same tile, alternate between them every 500 msecs.
		TileType[] ttArr = t.getTileTypeLayersForBrowserPresentation((int)(ticks/5));
		// TODO: LOW - I have hardcoded an assumption of a tick rate of 100 msecs per frame for the above line.
		
//		// [
		
		for(int c = 0; c < ttArr.length; c++) {			
//			JsonArrayBuilder tileLayer = Json.createArrayBuilder();
			// [
			
			// For each tile layer
			TileType tt = ttArr[c];
		
			if(tt.getRotation() != 0) {
				// [ number, rotation], 
				outer = outer.add(
						factory.createArrayBuilder().add(tt.getNumber()).add(tt.getRotation())
				);
			} else{
				// [ number],
				outer = outer.add(
						factory.createArrayBuilder().add(tt.getNumber())
				);
			}
			
			// ]
//			outer = outer.add(tileLayer);
		}
		
		// ]
		return outer;
		
	}
 
Example 3
Source File: HdfsSerDeImportService.java    From hadoop-etl-udfs with MIT License 5 votes vote down vote up
private static JsonArrayBuilder getJsonArrayFromFieldData(Object data, ObjectInspector objInsp, JsonBuilderFactory jsonFactory) {
    JsonArrayBuilder jab = jsonFactory.createArrayBuilder();
    ListObjectInspector oi = (ListObjectInspector) objInsp;
    List<?> list = oi.getList(data);
    ObjectInspector elemInsp = oi.getListElementObjectInspector();
    for (Object obj : list) {
        if (obj == null)
            jab.addNull();
        else if (elemInsp.getCategory() == Category.PRIMITIVE) {
            Object o = getJavaObjectFromPrimitiveData(obj, elemInsp);
            if (o instanceof Integer || o instanceof Short || o instanceof Byte)
                jab.add((Integer) o);
            else if (o instanceof Long)
                jab.add((Long) o);
            else if (o instanceof Float || o instanceof Double)
                jab.add((Double) o);
            else if (o instanceof BigDecimal)
                jab.add((BigDecimal) o);
            else if (o instanceof Boolean)
                jab.add((Boolean) o);
            else
                jab.add(o.toString());
        }
        else if (elemInsp.getCategory() == Category.LIST) {
            jab.add(getJsonArrayFromFieldData(obj, elemInsp, jsonFactory));
        }
        else {
            jab.add(getJsonObjectFromFieldData(obj, elemInsp, jsonFactory));
        }
    }
    return jab;
}
 
Example 4
Source File: JsonBuilderUtilsTest.java    From jsonix-schema-compiler with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void addsItem() {
	final JsonProvider provider = JsonProvider.provider();
	final JsonBuilderFactory builderFactory = provider
			.createBuilderFactory(null);
	final JsonArrayBuilder builder = builderFactory.createArrayBuilder();
	JsonBuilderUtils.add(builderFactory, builder, null);
	JsonBuilderUtils.add(builderFactory, builder, true);
	JsonBuilderUtils.add(builderFactory, builder, "string");
	JsonBuilderUtils.add(builderFactory, builder, 'c');
	JsonBuilderUtils.add(builderFactory, builder, BigInteger.TEN);
	JsonBuilderUtils.add(builderFactory, builder,
			BigDecimal.valueOf(1111, 2));
	JsonBuilderUtils.add(builderFactory, builder, 22f);
	JsonBuilderUtils.add(builderFactory, builder, 22d);
	JsonBuilderUtils.add(builderFactory, builder, (byte) 33);
	JsonBuilderUtils.add(builderFactory, builder, (int) 44);
	JsonBuilderUtils.add(builderFactory, builder, (int) 55);
	JsonBuilderUtils.add(builderFactory, builder,
			Arrays.<Object> asList("a", 0xbc, "d"));
	JsonBuilderUtils.add(builderFactory, builder, new Object[] { 1, "2", 3,
			false });

	JsonBuilderUtils.add(builderFactory, builder,
			Collections.singletonMap("foo", "bar"));
	// provider.createWriter(System.out).write(builder.build());
}
 
Example 5
Source File: AzureLogAnalyticsProvenanceReportingTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
private static JsonArrayBuilder createJsonArray(JsonBuilderFactory factory, final Collection<String> values) {
        final JsonArrayBuilder builder = factory.createArrayBuilder();
        for (final String value : values) {
                if (value != null) {
                        builder.add(value);
                }
        }
        return builder;
}
 
Example 6
Source File: SiteToSiteProvenanceReportingTask.java    From nifi with Apache License 2.0 5 votes vote down vote up
private static JsonArrayBuilder createJsonArray(JsonBuilderFactory factory, final Collection<String> values) {
    final JsonArrayBuilder builder = factory.createArrayBuilder();
    for (final String value : values) {
        if (value != null) {
            builder.add(value);
        }
    }
    return builder;
}
 
Example 7
Source File: OccasionResourceTest.java    From sample-acmegifts with Eclipse Public License 1.0 4 votes vote down vote up
/** Test the ability to retrieve a list of occasions for a given group */
@Test
public void testOccasionsForGroup() {
  logger.entering(
      clazz, name.getMethodName(), "\n\n+ + + + + Entering " + name.getMethodName() + "\n\n");

  String groupId = "3333";

  /*
   * build the json payload for the occasions
   */
  JsonBuilderFactory factory = Json.createBuilderFactory(null);

  // collect the expected output in this
  JsonArrayBuilder resultsBuilder = factory.createArrayBuilder();

  // build the json payload for occasion 1
  List<Occasion.Contribution> contributions = new ArrayList<>();
  contributions.add(new Occasion.Contribution("0001", 20));
  Occasion occasion =
      new Occasion(
          /* ID            */ null,
          /* date          */ "2117-07-31",
          /* group ID      */ "1111", // different ID than the others in this test so it's omitted
          // from the results
          /* interval      */ "annual",
          /* occasion name */ "John Doe's Birthday",
          /* organizer ID  */ "0001",
          /* recipient ID  */ "9998",
          contributions);

  // insert the occasion into the db
  collection.insert(occasion.toDbo());
  // occasion1 belongs to a different group. omitted from expected results

  // build the json payload for occasion 2
  contributions = new ArrayList<>();
  contributions.add(new Occasion.Contribution("0002", 50));
  contributions.add(new Occasion.Contribution("0003", 50));
  occasion =
      new Occasion(
          /* ID            */ null,
          /* date          */ "2117-09-30",
          /* group ID      */ groupId,
          /* interval      */ "annual",
          /* occasion name */ "Jill Doe's Birthday",
          /* organizer ID  */ "0002",
          /* recipient ID  */ "9997",
          contributions);

  // insert the occasion into the db and add the result to the expected result array
  collection.insert(occasion.toDbo());
  occasion = new Occasion(collection.findOne(occasion.toDbo()));
  resultsBuilder.add(occasion.toJson());

  // build the json payload for occasion 3
  contributions = new ArrayList<>();
  contributions.add(new Occasion.Contribution("9999", 20));
  contributions.add(new Occasion.Contribution("8888", 50));
  occasion =
      new Occasion(
          /* ID            */ null,
          /* date          */ "2018-01-31",
          /* group ID      */ groupId,
          /* interval      */ "annual",
          /* occasion name */ "Jason Doe's Birthday",
          /* organizer ID  */ "9999",
          /* recipient ID  */ "9996",
          contributions);

  // insert the occasion into the db and add the result to the expected result array
  collection.insert(occasion.toDbo());
  occasion = new Occasion(collection.findOne(occasion.toDbo()));
  resultsBuilder.add(occasion.toJson());

  testEndpoint("/?groupId=" + groupId, "GET", resultsBuilder.build().toString(), 200);

  logger.exiting(
      clazz, name.getMethodName(), "\n\n- - - - - Exiting " + name.getMethodName() + "\n\n");
}
 
Example 8
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;
}