Java Code Examples for com.google.gson.JsonArray#add()

The following examples show how to use com.google.gson.JsonArray#add() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ObservationFromFullInventoryImplementation.java    From malmo with MIT License 7 votes vote down vote up
public static void getInventoryJSON(JsonArray arr, IInventory inventory)
{
    String invName = getInventoryName(inventory);
    for (int i = 0; i < inventory.getSizeInventory(); i++)
    {
        ItemStack is = inventory.getStackInSlot(i);
        if (is != null && !is.isEmpty())
        {
            JsonObject jobj = new JsonObject();
            DrawItem di = MinecraftTypeHelper.getDrawItemFromItemStack(is);
            String name = di.getType();
            if (di.getColour() != null)
                jobj.addProperty("colour", di.getColour().value());
            if (di.getVariant() != null)
                jobj.addProperty("variant", di.getVariant().getValue());
            jobj.addProperty("type", name);
            jobj.addProperty("index", i);
            jobj.addProperty("quantity", is.getCount());
            jobj.addProperty("inventory",  invName);
            arr.add(jobj);
        }
    }
}
 
Example 2
Source File: Prediction.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
public JsonElement toJson() {

	JsonObject root = new JsonObject();

	for (PredictionElement predictedElement : this.getElementsWithPrediction()) {
		CtElement element = predictedElement.getElement();
		root.addProperty("code", element.toString());
		root.addProperty("type", element.getClass().getSimpleName());
		root.addProperty("path", element.getPath().toString());
		root.addProperty("index", predictedElement.getIndex());
		JsonArray ops = new JsonArray();
		root.add("ops", ops);
		for (AstorOperator op : this.get(predictedElement)) {
			if (op != null)
				ops.add(op.name());
		}

	}

	return root;
}
 
Example 3
Source File: JsonEncoder.java    From js-dossier with Apache License 2.0 6 votes vote down vote up
/** Encode the given message as a JSON array. */
public JsonArray encode(Message message) {
  JsonArray array = new JsonArray();
  for (FieldDescriptor field : message.getDescriptorForType().getFields()) {
    if (field.isRepeated() || message.hasField(field)) {
      JsonElement element = encodeField(field, message.getField(field));
      if (!element.isJsonNull()) {
        while (array.size() < field.getNumber()) {
          array.add(JsonNull.INSTANCE);
        }
        array.set(field.getNumber() - 1, element);
      }
    }
  }
  return array;
}
 
Example 4
Source File: EventStreamSerializer.java    From dolphin-platform with Apache License 2.0 6 votes vote down vote up
private JsonObject convertToJson(final MessageEventContext<?> eventContext) throws IOException {
    final JsonObject root = new JsonObject();
    root.addProperty(TOPIC_PARAM, eventContext.getTopic().getName());
    root.addProperty(TIMESTAMP_PARAM, eventContext.getTimestamp());

    final JsonArray metadataArray = new JsonArray();
    for (final Map.Entry<String, Serializable> entry : eventContext.getMetadata().entrySet()) {
        final String key = entry.getKey();
        final Serializable data = entry.getValue();
        final JsonObject metadataEntry = new JsonObject();
        metadataEntry.addProperty(METADATA_KEY_PARAM, key);
        if (data != null) {
            metadataEntry.addProperty(METADATA_VALUE_PARAM, Base64Utils.toBase64(data));
        } else {
            metadataEntry.add(METADATA_VALUE_PARAM, JsonNull.INSTANCE);
        }
        metadataArray.add(metadataEntry);
    }
    root.add(METADATA_PARAM, metadataArray);
    return root;
}
 
Example 5
Source File: AndroidOperation.java    From product-emm with Apache License 2.0 5 votes vote down vote up
@Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP,
        description = "Test Android blacklist apps operation.")
public void testBlacklistApps() throws Exception {
    JsonObject operationData = PayloadGenerator
            .getJsonPayload(Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME,
                    Constants.AndroidOperations.INSTALL_APPS_OPERATION);
    JsonArray deviceIds = new JsonArray();
    JsonPrimitive deviceID = new JsonPrimitive(Constants.DEVICE_ID);
    deviceIds.add(deviceID);
    operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds);
    HttpResponse response = client.post(Constants.AndroidOperations.ANDROID_DEVICE_MGT_API
            + Constants.AndroidOperations.BLACKLIST_APPS_ENDPOINT, operationData.toString());
    Assert.assertEquals(HttpStatus.SC_CREATED, response.getResponseCode());
}
 
Example 6
Source File: GraphBuilder.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
public JsonObject _complete() {
    JsonObject json = super._complete();
    
    JsonArray oa = new JsonArray();
    json.add("operators", oa);
    for (BOperator op : ops) {
        oa.add(op._complete());
    }
            
    return json;
}
 
Example 7
Source File: CommonTestUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
public static JsonArray getJsonArray() {
    Gson gson = new Gson();
    JsonArray array = new JsonArray();
    array.add(gson.fromJson("r_win_abc_admin", JsonElement.class));
    array.add(gson.fromJson("r_rhel_abc_admin", JsonElement.class));
    return array;
}
 
Example 8
Source File: GsonRuntime.java    From jmespath-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public JsonElement createArray(Collection<JsonElement> elements) {
  JsonArray array = new JsonArray();
  for (JsonElement e : elements) {
    array.add(e);
  }
  return array;
}
 
Example 9
Source File: Metrics.java    From Crazy-Crates with MIT License 5 votes vote down vote up
@Override
protected JsonObject getChartData() throws Exception {
    JsonObject data = new JsonObject();
    JsonObject values = new JsonObject();
    Map<String, int[]> map = callable.call();
    if (map == null || map.isEmpty()) {
        // Null = skip the chart
        return null;
    }
    boolean allSkipped = true;
    for (Map.Entry<String, int[]> entry : map.entrySet()) {
        if (entry.getValue().length == 0) {
            continue; // Skip this invalid
        }
        allSkipped = false;
        JsonArray categoryValues = new JsonArray();
        for (int categoryValue : entry.getValue()) {
            categoryValues.add(categoryValue);
        }
        values.add(entry.getKey(), categoryValues);
    }
    if (allSkipped) {
        // Null = skip the chart
        return null;
    }
    data.add("values", values);
    return data;
}
 
Example 10
Source File: Metrics.java    From Quests with MIT License 5 votes vote down vote up
@Override
protected JsonObject getChartData() throws Exception {
    JsonObject data = new JsonObject();
    JsonObject values = new JsonObject();
    Map<String, int[]> map = callable.call();
    if (map == null || map.isEmpty()) {
        // Null = skip the chart
        return null;
    }
    boolean allSkipped = true;
    for (Map.Entry<String, int[]> entry : map.entrySet()) {
        if (entry.getValue().length == 0) {
            continue; // Skip this invalid
        }
        allSkipped = false;
        JsonArray categoryValues = new JsonArray();
        for (int categoryValue : entry.getValue()) {
            categoryValues.add(categoryValue);
        }
        values.add(entry.getKey(), categoryValues);
    }
    if (allSkipped) {
        // Null = skip the chart
        return null;
    }
    data.add("values", values);
    return data;
}
 
Example 11
Source File: ClusterNodeMain.java    From modernmt with Apache License 2.0 5 votes vote down vote up
/**
 * Update the embedded services in local properties
 *
 * @param services the list of embedded services of the ClusterNode
 * @return this very FileStatusListener
 */
public FileStatusListener updateServices(List<EmbeddedService> services) {
    JsonArray array = new JsonArray();

    for (EmbeddedService service : services) {
        for (Process process : service.getSubprocesses()) {
            int pid = getPid(process);
            if (pid > 0)
                array.add(pid);
        }
    }

    this.properties.add("embedded_services", array);
    return this;
}
 
Example 12
Source File: Metrics.java    From ClaimChunk with MIT License 5 votes vote down vote up
@Override
protected JsonObject getChartData() throws Exception {
    JsonObject data = new JsonObject();
    JsonObject values = new JsonObject();
    Map<String, int[]> map = callable.call();
    if (map == null || map.isEmpty()) {
        // Null = skip the chart
        return null;
    }
    boolean allSkipped = true;
    for (Map.Entry<String, int[]> entry : map.entrySet()) {
        if (entry.getValue().length == 0) {
            continue; // Skip this invalid
        }
        allSkipped = false;
        JsonArray categoryValues = new JsonArray();
        for (int categoryValue : entry.getValue()) {
            categoryValues.add(categoryValue);
        }
        values.add(entry.getKey(), categoryValues);
    }
    if (allSkipped) {
        // Null = skip the chart
        return null;
    }
    data.add("values", values);
    return data;
}
 
Example 13
Source File: Metrics.java    From Crazy-Auctions with MIT License 5 votes vote down vote up
@Override
protected JsonObject getChartData() throws Exception {
    JsonObject data = new JsonObject();
    JsonObject values = new JsonObject();
    Map<String, int[]> map = callable.call();
    if (map == null || map.isEmpty()) {
        // Null = skip the chart
        return null;
    }
    boolean allSkipped = true;
    for (Map.Entry<String, int[]> entry : map.entrySet()) {
        if (entry.getValue().length == 0) {
            continue; // Skip this invalid
        }
        allSkipped = false;
        JsonArray categoryValues = new JsonArray();
        for (int categoryValue : entry.getValue()) {
            categoryValues.add(new JsonPrimitive(categoryValue));
        }
        values.add(entry.getKey(), categoryValues);
    }
    if (allSkipped) {
        // Null = skip the chart
        return null;
    }
    data.add("values", values);
    return data;
}
 
Example 14
Source File: RestApiExtractor.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
@Override
public void extractMetadata(String schema, String entity, WorkUnit workUnit) throws SchemaException {
  log.info("Extract Metadata using Rest Api");
  JsonArray columnArray = new JsonArray();
  String inputQuery = workUnitState.getProp(ConfigurationKeys.SOURCE_QUERYBASED_QUERY);
  List<String> columnListInQuery = null;
  JsonArray array = null;
  if (!Strings.isNullOrEmpty(inputQuery)) {
    columnListInQuery = Utils.getColumnListFromQuery(inputQuery);
  }

  String excludedColumns = workUnitState.getProp(ConfigurationKeys.SOURCE_QUERYBASED_EXCLUDED_COLUMNS);
  List<String> columnListExcluded = ImmutableList.<String> of();

  if (Strings.isNullOrEmpty(inputQuery) && !Strings.isNullOrEmpty(excludedColumns)) {
    Splitter splitter = Splitter.on(",").omitEmptyStrings().trimResults();
    columnListExcluded = splitter.splitToList(excludedColumns.toLowerCase());
  }

  try {
    boolean success = this.connector.connect();
    if (!success) {
      throw new SchemaException("Failed to connect.");
    }
    log.debug("Connected successfully.");
    List<Command> cmds = this.getSchemaMetadata(schema, entity);
    CommandOutput<?, ?> response = this.connector.getResponse(cmds);
    array = this.getSchema(response);

    for (JsonElement columnElement : array) {
      Schema obj = GSON.fromJson(columnElement, Schema.class);
      String columnName = obj.getColumnName();

      obj.setWaterMark(this.isWatermarkColumn(workUnitState.getProp("extract.delta.fields"), columnName));

      if (this.isWatermarkColumn(workUnitState.getProp("extract.delta.fields"), columnName)) {
        obj.setNullable(false);
      } else if (this.getPrimarykeyIndex(workUnitState.getProp("extract.primary.key.fields"), columnName) == 0) {
        // set all columns as nullable except primary key and watermark columns
        obj.setNullable(true);
      }

      obj.setPrimaryKey(this.getPrimarykeyIndex(workUnitState.getProp("extract.primary.key.fields"), columnName));

      String jsonStr = GSON.toJson(obj);
      JsonObject jsonObject = GSON.fromJson(jsonStr, JsonObject.class).getAsJsonObject();

      // If input query is null or provided '*' in the query select all columns.
      // Else, consider only the columns mentioned in the column list
      if (inputQuery == null || columnListInQuery == null
          || (columnListInQuery.size() == 1 && columnListInQuery.get(0).equals("*"))
          || (columnListInQuery.size() >= 1 && this.isMetadataColumn(columnName, columnListInQuery))) {
        if (!columnListExcluded.contains(columnName.trim().toLowerCase())) {
          this.columnList.add(columnName);
          columnArray.add(jsonObject);
        }
      }
    }

    this.updatedQuery = buildDataQuery(inputQuery, entity);
    log.info("Schema:" + columnArray);
    this.setOutputSchema(columnArray);
  } catch (RuntimeException | RestApiProcessingException | RestApiConnectionException | IOException
      | SchemaException e) {
    throw new SchemaException("Failed to get schema using rest api; error - " + e.getMessage(), e);
  }
}
 
Example 15
Source File: SessionEventsHandler.java    From openvidu with Apache License 2.0 4 votes vote down vote up
public void onPublishMedia(Participant participant, String streamId, Long createdAt, String sessionId,
		MediaOptions mediaOptions, String sdpAnswer, Set<Participant> participants, Integer transactionId,
		OpenViduException error) {
	if (error != null) {
		rpcNotificationService.sendErrorResponse(participant.getParticipantPrivateId(), transactionId, null, error);
		return;
	}
	JsonObject result = new JsonObject();
	result.addProperty(ProtocolElements.PUBLISHVIDEO_SDPANSWER_PARAM, sdpAnswer);
	result.addProperty(ProtocolElements.PUBLISHVIDEO_STREAMID_PARAM, streamId);
	result.addProperty(ProtocolElements.PUBLISHVIDEO_CREATEDAT_PARAM, createdAt);
	rpcNotificationService.sendResponse(participant.getParticipantPrivateId(), transactionId, result);

	JsonObject params = new JsonObject();
	params.addProperty(ProtocolElements.PARTICIPANTPUBLISHED_USER_PARAM, participant.getParticipantPublicId());
	JsonObject stream = new JsonObject();

	stream.addProperty(ProtocolElements.PARTICIPANTPUBLISHED_STREAMID_PARAM, streamId);
	stream.addProperty(ProtocolElements.PARTICIPANTPUBLISHED_CREATEDAT_PARAM, createdAt);
	stream.addProperty(ProtocolElements.PARTICIPANTPUBLISHED_HASAUDIO_PARAM, mediaOptions.hasAudio);
	stream.addProperty(ProtocolElements.PARTICIPANTPUBLISHED_HASVIDEO_PARAM, mediaOptions.hasVideo);
	stream.addProperty(ProtocolElements.PARTICIPANTPUBLISHED_AUDIOACTIVE_PARAM, mediaOptions.audioActive);
	stream.addProperty(ProtocolElements.PARTICIPANTPUBLISHED_VIDEOACTIVE_PARAM, mediaOptions.videoActive);
	stream.addProperty(ProtocolElements.PARTICIPANTPUBLISHED_TYPEOFVIDEO_PARAM, mediaOptions.typeOfVideo);
	stream.addProperty(ProtocolElements.PARTICIPANTPUBLISHED_FRAMERATE_PARAM, mediaOptions.frameRate);
	stream.addProperty(ProtocolElements.PARTICIPANTPUBLISHED_VIDEODIMENSIONS_PARAM, mediaOptions.videoDimensions);
	JsonElement filter = mediaOptions.getFilter() != null ? mediaOptions.getFilter().toJson() : new JsonObject();
	stream.add(ProtocolElements.JOINROOM_PEERSTREAMFILTER_PARAM, filter);

	JsonArray streamsArray = new JsonArray();
	streamsArray.add(stream);
	params.add(ProtocolElements.PARTICIPANTPUBLISHED_STREAMS_PARAM, streamsArray);

	for (Participant p : participants) {
		if (p.getParticipantPrivateId().equals(participant.getParticipantPrivateId())) {
			continue;
		} else {
			rpcNotificationService.sendNotification(p.getParticipantPrivateId(),
					ProtocolElements.PARTICIPANTPUBLISHED_METHOD, params);
		}
	}
}
 
Example 16
Source File: Kms.java    From openvidu with Apache License 2.0 4 votes vote down vote up
public JsonObject toJsonExtended(boolean withSessions, boolean withExtraInfo) {

		JsonObject json = this.toJson();

		if (withSessions) {
			JsonArray sessions = new JsonArray();
			for (KurentoSession session : this.kurentoSessions.values()) {
				sessions.add(session.toJson());
			}
			json.add("sessions", sessions);
		}

		if (withExtraInfo) {

			if (json.get("connected").getAsBoolean()) {

				JsonObject kurentoExtraInfo = new JsonObject();

				try {

					kurentoExtraInfo.addProperty("memory", this.client.getServerManager().getUsedMemory() / 1024);

					ServerInfo info = this.client.getServerManager().getInfo();
					kurentoExtraInfo.addProperty("version", info.getVersion());
					kurentoExtraInfo.addProperty("capabilities", info.getCapabilities().toString());

					JsonArray modules = new JsonArray();
					for (ModuleInfo moduleInfo : info.getModules()) {
						JsonObject moduleJson = new JsonObject();
						moduleJson.addProperty("name", moduleInfo.getName());
						moduleJson.addProperty("version", moduleInfo.getVersion());
						moduleJson.addProperty("generationTime", moduleInfo.getGenerationTime());
						JsonArray factories = new JsonArray();
						moduleInfo.getFactories().forEach(fact -> factories.add(fact));
						moduleJson.add("factories", factories);
						modules.add(moduleJson);
					}
					kurentoExtraInfo.add("modules", modules);

					json.add("kurentoInfo", kurentoExtraInfo);

				} catch (Exception e) {
					log.warn("KMS {} extra info was requested but there's no connection to it", this.id);
				}
			}
		}

		return json;
	}
 
Example 17
Source File: MultiOutAttachmentResponse.java    From burstkit4j with Apache License 2.0 4 votes vote down vote up
private static JsonArray serialize(MultiOutRecipient source) {
    JsonArray array = new JsonArray(2);
    array.add(source.getRecipient().getID());
    array.add(source.getAmount().toPlanck());
    return array;
}
 
Example 18
Source File: JSONWriter.java    From tabula-java with MIT License 4 votes vote down vote up
@Override public void write(Appendable out, List<Table> tables) throws IOException {
	Gson gson = gson();
	JsonArray array = new JsonArray();
	for (Table table : tables) array.add(gson.toJsonTree(table, Table.class));
	out.append(gson.toJson(array));
}
 
Example 19
Source File: ShowStudentStatisticsDispatchAction.java    From fenixedu-academic with GNU Lesser General Public License v3.0 4 votes vote down vote up
private JsonObject computeCurricularCoursesOvertimeStatistics(Collection<Enrolment> approvedEnrolments) {
    JsonObject curricularCoursesOvertime = new JsonObject();
    int lowestStartYear = Integer.MAX_VALUE;
    int highestStartYear = Integer.MIN_VALUE;
    JsonArray curricularCoursesJsonArray = new JsonArray();
    for (Enrolment enrolment : approvedEnrolments) {
        CurricularCourse curricularCourse = enrolment.getCurricularCourse();
        JsonObject curricularCourseJsonObject = new JsonObject();
        curricularCourseJsonObject.addProperty("name", curricularCourse.getNameI18N().getContent());
        JsonArray entriesArray = new JsonArray();
        Map<Integer, CurricularCourseYearStatistics> entries = new HashMap<Integer, CurricularCourseYearStatistics>();
        for (ExecutionCourse executionCourse : curricularCourse.getAssociatedExecutionCoursesSet()) {
            AcademicInterval academicInterval = executionCourse.getAcademicInterval();
            int startYear = academicInterval.getStart().getYear();
            CurricularCourseYearStatistics curricularCourseYearStatistics =
                    computeExecutionCourseJsonArray(executionCourse, entries.get(startYear));
            if (curricularCourseYearStatistics == null) {
                continue;
            }
            entries.put(startYear, curricularCourseYearStatistics);
            if (lowestStartYear > startYear) {
                lowestStartYear = startYear;
            }
            if (highestStartYear < startYear) {
                highestStartYear = startYear;
            }
        }
        for (int year : entries.keySet()) {
            JsonArray jsonArray = new JsonArray();
            jsonArray.add(new JsonPrimitive(year));
            jsonArray.add(new JsonPrimitive(entries.get(year).getApproved()));
            jsonArray.add(new JsonPrimitive(entries.get(year).getFlunked()));
            jsonArray.add(new JsonPrimitive(entries.get(year).getNotEvaluated()));
            entriesArray.add(jsonArray);
        }
        curricularCourseJsonObject.add("years", entriesArray);
        curricularCoursesJsonArray.add(curricularCourseJsonObject);
    }
    curricularCoursesOvertime.addProperty("start-year", lowestStartYear);
    curricularCoursesOvertime.addProperty("end-year", highestStartYear);
    curricularCoursesOvertime.add("entries", curricularCoursesJsonArray);
    return curricularCoursesOvertime;
}
 
Example 20
Source File: FixedChatSerializer.java    From Carbon-2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public JsonElement serialize(IChatBaseComponent base, Type type, JsonSerializationContext ctx) {
    JsonObject result = new JsonObject();
    if (!base.getChatModifier().g()) {
        this.a(base.getChatModifier(), result, ctx);
    }

    if (!base.a().isEmpty()) {
        JsonArray extrajson = new JsonArray();
        for (IChatBaseComponent comp : base.a()) {
            extrajson.add(serialize(comp, comp.getClass(), ctx));
        }
        result.add("extra", extrajson);
    }

    if (base instanceof ChatComponentText) {
        result.addProperty("text", ((ChatComponentText) base).g());
    } else if (base instanceof ChatMessage) {
        ChatMessage chatmessage = (ChatMessage) base;
        result.addProperty("translate", chatmessage.i());
        if ((chatmessage.j() != null) && (chatmessage.j().length > 0)) {
            JsonArray withjson = new JsonArray();
            for (Object arg : chatmessage.j()) {
                if (arg instanceof IChatBaseComponent) {
                    withjson.add(serialize(((IChatBaseComponent) arg), arg.getClass(), ctx));
                } else {
                    withjson.add(new JsonPrimitive(String.valueOf(arg)));
                }
            }

            result.add("with", withjson);
        }
    } else if (base instanceof ChatComponentScore) {
        ChatComponentScore scorecomp = (ChatComponentScore) base;
        JsonObject scorejson = new JsonObject();
        scorejson.addProperty("name", scorecomp.g());
        scorejson.addProperty("objective", scorecomp.h());
        scorejson.addProperty("value", scorecomp.getText());
        result.add("score", scorejson);
    } else {
        if (!(base instanceof ChatComponentSelector)) {
            throw new IllegalArgumentException("Don\'t know how to serialize " + base + " as a Component");
        }

        ChatComponentSelector selectorcomp = (ChatComponentSelector) base;
        result.addProperty("selector", selectorcomp.g());
    }

    return result;
}