List of usage examples for com.google.gson JsonArray add
public void add(JsonElement element)
From source file:com.ericsson.eiffel.remrem.semantics.schemas.SchemaFile.java
License:Apache License
/** * // w w w .j a va2s . c o m * This method is used to adding the attributes JavaType ,ExtendsJavaType * and other required properties to input jsons * * @param jsonContent * -Eiffel repo json file content sent as an input parameter * @param jsonElementName * -Name of the json elements as an input parameter * @param jsonObject * -Json object is sent as an input to this to add required json * properties to generate event pojo's */ private void addAttributesToJsonSchema(JsonObject jsonContent, String jsonElementName, JsonObject jsonObject) { Set<Entry<String, JsonElement>> values = jsonContent.entrySet(); Iterator<Entry<String, JsonElement>> keyValue = values.iterator(); while (keyValue.hasNext()) { Entry<String, JsonElement> valueSet = keyValue.next(); if (valueSet.getValue().isJsonObject()) { String name = valueSet.getKey(); String previousObjectName = jsonElementName; if (name.equals(EiffelConstants.META)) { isMeta = true; } if (name.equals(EiffelConstants.TYPE) && isMeta) { isMeta = false; } addingItemsProperties(name, valueSet.getValue(), jsonObject, previousObjectName); } else { if (EiffelConstants.TYPE.equals(valueSet.getKey())) { if (EiffelConstants.OBJECTTYPE.equals(valueSet.getValue().getAsString())) { jsonObject.add(EiffelConstants.TYPE, valueSet.getValue()); if (isEvent) { jsonObject.add(EiffelConstants.JAVA_TYPE, parser.parse(EiffelConstants.COM_ERICSSON_EIFFEL_SEMANTICS_EVENTS .concat(StringUtils.capitalize(jsonElementName)))); jsonObject.add(EiffelConstants.EXTENDS_JAVA_CLASS, parser.parse(EiffelConstants.COM_ERICSSON_EIFFEL_SEMANTICS_EVENTS_EVENT)); isEvent = false; } else { jsonElementName = modifyClassName(jsonElementName); String newClassName = StringUtils.capitalize(jsonElementName); if (jsonElementName.equals(EiffelConstants.META)) { // To generate event specific Meta class jsonObject.add(EiffelConstants.JAVA_TYPE, parser.parse(EiffelConstants.COM_ERICSSON_EIFFEL_SEMANTICS_EVENTS .concat(this.eventName + "" + newClassName))); JsonArray list = new JsonArray(); list.add("com.ericsson.eiffel.semantics.events.Meta"); jsonObject.add(EiffelConstants.JAVA_INTERFACES, list); } else if (jsonElementName.equals(EiffelConstants.DATA) || jsonElementName.equals(EiffelConstants.OUTCOME)) { // Data and Outcome is different at event level jsonObject.add(EiffelConstants.JAVA_TYPE, parser.parse(EiffelConstants.COM_ERICSSON_EIFFEL_SEMANTICS_EVENTS .concat(this.eventName + "" + newClassName))); } else if (jsonElementName.equals(EiffelConstants.ISSUE)) { jsonObject.add(EiffelConstants.JAVA_TYPE, parser.parse(EiffelConstants.COM_ERICSSON_EIFFEL_SEMANTICS_EVENTS .concat(this.eventName + "" + newClassName))); } else { jsonObject.add(EiffelConstants.JAVA_TYPE, parser.parse( EiffelConstants.COM_ERICSSON_EIFFEL_SEMANTICS_EVENTS.concat(newClassName))); } } } else { jsonObject.add(EiffelConstants.TYPE, valueSet.getValue()); if (jsonElementName.equals(EiffelConstants.TIME)) { jsonObject.add(EiffelConstants.FORMAT, parser.parse(EiffelConstants.UTC_MILLISEC)); } } } else { jsonObject.add(valueSet.getKey(), valueSet.getValue()); } } } if (values.isEmpty()) { // If value field doesn't have any data type we make it to // accept either object or string value JsonArray array = new JsonArray(); JsonObject obj1 = new JsonObject(); JsonObject obj2 = new JsonObject(); JsonObject obj3 = new JsonObject(); JsonObject obj4 = new JsonObject(); obj1.add(EiffelConstants.TYPE, parser.parse(EiffelConstants.OBJECTTYPE)); obj2.add(EiffelConstants.TYPE, parser.parse(EiffelConstants.STRING)); obj3.add(EiffelConstants.TYPE, parser.parse(EiffelConstants.ARRAY)); obj4.add(EiffelConstants.TYPE, parser.parse(EiffelConstants.NUMBER)); array.add(obj1); array.add(obj2); array.add(obj3); array.add(obj4); jsonObject.add(EiffelConstants.ANYOF, array); } }
From source file:com.eventual.singleton.Administracion.java
@Override public JsonObject devuelveConectados() { JsonObject respuesta = new JsonObject(); respuesta.addProperty("tipo", "LISTA_CONECTADOS"); JsonArray conectados = new JsonArray(); this.chat.getConectados().values().stream().map((u) -> { JsonObject elemento = new JsonObject(); elemento.addProperty("id", u.getIdUsuario()); elemento.addProperty("nombre", u.getNombre()); return elemento; }).forEachOrdered((elemento) -> { conectados.add(elemento); });/*from w ww .j av a2 s . c o m*/ respuesta.add("lista", conectados); return respuesta; }
From source file:com.eventual.singleton.Chat.java
@Override public JsonArray devuelveAmigosConectados(UsuarioConectado usuario) { JsonArray amigosConectados = new JsonArray(); for (int idAmigo : usuario.getAmigos()) { UsuarioConectado amigo = conectados.get(idAmigo); if (amigo != null) { JsonObject elemento = new JsonObject(); elemento.addProperty("id", amigo.getIdUsuario()); elemento.addProperty("nombre", amigo.getNombre()); amigosConectados.add(elemento); }//from w w w .j a v a2 s .com } return amigosConectados; }
From source file:com.exalttech.trex.ui.views.streams.binders.BuilderDataBinding.java
License:Apache License
public String serializeAsPacketModel() { JsonObject model = new JsonObject(); model.add("protocols", new JsonArray()); JsonObject fieldEngine = new JsonObject(); fieldEngine.add("instructions", new JsonArray()); fieldEngine.add("global_parameters", new JsonObject()); model.add("field_engine", fieldEngine); Map<String, AddressDataBinding> l3Binds = new HashMap<>(); l3Binds.put("Ether", macDB); boolean isIPv4 = protocolSelection.getIpv4Property().get(); if (isIPv4) { l3Binds.put("IP", ipv4DB); }//w ww.j av a 2 s .co m l3Binds.entrySet().stream().forEach(entry -> { JsonObject proto = new JsonObject(); String protoID = entry.getKey(); proto.add("id", new JsonPrimitive(protoID)); JsonArray fields = new JsonArray(); AddressDataBinding binding = entry.getValue(); String srcMode = entry.getValue().getDestination().getModeProperty().get(); String dstMode = entry.getValue().getSource().getModeProperty().get(); if (!MODE_TREX_CONFIG.equals(srcMode)) { fields.add(buildProtoField("src", binding.getSource().getAddressProperty().getValue())); } if (!MODE_TREX_CONFIG.equals(dstMode)) { fields.add(buildProtoField("dst", binding.getDestination().getAddressProperty().getValue())); } if (protoID.equals("Ether") && ethernetDB.getOverrideProperty().get()) { fields.add(buildProtoField("type", ethernetDB.getTypeProperty().getValue())); } proto.add("fields", fields); model.getAsJsonArray("protocols").add(proto); if (!MODE_FIXED.equals(binding.getSource().getModeProperty().get()) && !MODE_TREX_CONFIG.equals(binding.getSource().getModeProperty().get())) { fieldEngine.getAsJsonArray("instructions") .addAll(buildVMInstructions(protoID, "src", binding.getSource())); } if (!MODE_FIXED.equals(binding.getDestination().getModeProperty().get()) && !MODE_TREX_CONFIG.equals(binding.getDestination().getModeProperty().get())) { fieldEngine.getAsJsonArray("instructions") .addAll(buildVMInstructions(protoID, "dst", binding.getDestination())); } }); boolean isVLAN = protocolSelection.getTaggedVlanProperty().get(); String pktLenName = "pkt_len"; String frameLenghtType = protocolSelection.getFrameLengthType(); boolean pktSizeChanged = !frameLenghtType.equals("Fixed"); if (pktSizeChanged) { LinkedHashMap<String, String> instructionParam = new LinkedHashMap<>(); String operation = PacketBuilderHelper.getOperationFromType(frameLenghtType); Integer minLength = Integer.valueOf(protocolSelection.getMinLength()) - 4; Integer maxLength = Integer.valueOf(protocolSelection.getMaxLength()) - 4; instructionParam.put("init_value", minLength.toString()); instructionParam.put("max_value", maxLength.toString()); instructionParam.put("min_value", minLength.toString()); instructionParam.put("name", pktLenName); instructionParam.put("op", operation); instructionParam.put("size", "2"); instructionParam.put("step", "1"); fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmFlowVar", instructionParam)); instructionParam.clear(); instructionParam.put("fv_name", pktLenName); fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmTrimPktSize", instructionParam)); instructionParam.clear(); instructionParam.put("add_val", isVLAN ? "-18" : "-14"); instructionParam.put("is_big", "true"); instructionParam.put("fv_name", pktLenName); instructionParam.put("pkt_offset", isVLAN ? "20" : "16"); fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmWrFlowVar", instructionParam)); } if (isVLAN) { JsonObject dot1QProto = new JsonObject(); dot1QProto.add("id", new JsonPrimitive("Dot1Q")); Map<String, String> fieldsMap = new HashMap<>(); fieldsMap.put("prio", vlanDB.getPriorityProperty().getValue()); fieldsMap.put("id", vlanDB.getCfiProperty().getValue()); fieldsMap.put("vlan", vlanDB.getVIdProperty().getValue()); dot1QProto.add("fields", buildProtoFieldsFromMap(fieldsMap)); JsonArray protocols = model.getAsJsonArray("protocols"); if (protocols.size() == 2) { JsonElement ipv4 = protocols.get(1); protocols.set(1, dot1QProto); protocols.add(ipv4); } else { model.getAsJsonArray("protocols").add(dot1QProto); } if (vlanDB.getOverrideTPIdProperty().getValue()) { JsonArray etherFields = ((JsonObject) model.getAsJsonArray("protocols").get(0)).get("fields") .getAsJsonArray(); if (etherFields.size() == 3) { etherFields.remove(2); } etherFields.add(buildProtoField("type", vlanDB.getTpIdProperty().getValue())); } } boolean isTCP = protocolSelection.getTcpProperty().get(); if (isTCP) { JsonObject tcpProto = new JsonObject(); tcpProto.add("id", new JsonPrimitive("TCP")); Map<String, String> fieldsMap = new HashMap<>(); fieldsMap.put("sport", tcpProtocolDB.getSrcPortProperty().getValue()); fieldsMap.put("dport", tcpProtocolDB.getDstPortProperty().getValue()); fieldsMap.put("chksum", "0x" + tcpProtocolDB.getChecksumProperty().getValue()); fieldsMap.put("seq", tcpProtocolDB.getSequenceNumberProperty().getValue()); fieldsMap.put("urgptr", tcpProtocolDB.getUrgentPointerProperty().getValue()); fieldsMap.put("ack", tcpProtocolDB.getAckNumberProperty().getValue()); int tcp_flags = 0; if (tcpProtocolDB.getUrgProperty().get()) { tcp_flags = tcp_flags | (1 << 5); } if (tcpProtocolDB.getAckProperty().get()) { tcp_flags = tcp_flags | (1 << 4); } if (tcpProtocolDB.getPshProperty().get()) { tcp_flags = tcp_flags | (1 << 3); } if (tcpProtocolDB.getRstProperty().get()) { tcp_flags = tcp_flags | (1 << 2); } if (tcpProtocolDB.getSynProperty().get()) { tcp_flags = tcp_flags | (1 << 1); } if (tcpProtocolDB.getFinProperty().get()) { tcp_flags = tcp_flags | 1; } fieldsMap.put("flags", String.valueOf(tcp_flags)); tcpProto.add("fields", buildProtoFieldsFromMap(fieldsMap)); model.getAsJsonArray("protocols").add(tcpProto); } // Field Engine instructions String cache_size = "5000"; if ("Enable".equals(advancedPropertiesDB.getCacheSizeTypeProperty().getValue())) { cache_size = advancedPropertiesDB.getCacheValueProperty().getValue(); } fieldEngine.getAsJsonObject("global_parameters").add("cache_size", new JsonPrimitive(cache_size)); boolean isUDP = protocolSelection.getUdpProperty().get(); if (isUDP) { JsonObject udpProto = new JsonObject(); udpProto.add("id", new JsonPrimitive("UDP")); Map<String, String> fieldsMap = new HashMap<>(); fieldsMap.put("sport", udpProtocolDB.getSrcPortProperty().getValue()); fieldsMap.put("dport", udpProtocolDB.getDstPortProperty().getValue()); fieldsMap.put("len", udpProtocolDB.getLengthProperty().getValue()); udpProto.add("fields", buildProtoFieldsFromMap(fieldsMap)); model.getAsJsonArray("protocols").add(udpProto); if (pktSizeChanged) { LinkedHashMap<String, String> instructionParam = new LinkedHashMap<>(); instructionParam.put("add_val", isVLAN ? "-38" : "-34"); instructionParam.put("is_big", "true"); instructionParam.put("fv_name", pktLenName); instructionParam.put("pkt_offset", isVLAN ? "42" : "38"); fieldEngine.getAsJsonArray("instructions") .add(buildInstruction("STLVmWrFlowVar", instructionParam)); } } if (ipv4DB.hasInstructions() || pktSizeChanged) { Map<String, String> flowWrVarParameters = new HashMap<>(); flowWrVarParameters.put("offset", "IP"); fieldEngine.getAsJsonArray("instructions").add(buildInstruction("STLVmFixIpv4", flowWrVarParameters)); } return model.toString(); }
From source file:com.exalttech.trex.ui.views.streams.binders.BuilderDataBinding.java
License:Apache License
private JsonArray buildVMInstructions(String protoId, String fieldId, AddressDataBinding.AddressInfo binding) { JsonArray instructions = new JsonArray(); Map<String, String> flowVarParameters = new HashMap<>(); String varName = protoId + "_" + fieldId; flowVarParameters.put("name", varName); String initAndMinValue = "1"; flowVarParameters.put("init_value", initAndMinValue); flowVarParameters.put("max_value", binding.getCountProperty().get()); flowVarParameters.put("min_value", initAndMinValue); flowVarParameters.put("step", binding.getStepProperty().get()); String operation;//from www. j av a2s.c o m switch (binding.getModeProperty().get()) { case "Random Host": operation = "random"; break; case "Decrement": case "Decrement Host": operation = "dec"; break; case "Increment": case "Increment Host": default: operation = "inc"; break; } flowVarParameters.put("op", operation); instructions.add(buildInstruction("STLVmFlowVar", flowVarParameters)); Map<String, String> flowWrVarParameters = new HashMap<>(); flowWrVarParameters.put("fv_name", varName); flowWrVarParameters.put("pkt_offset", protoId + "." + fieldId); instructions.add(buildInstruction("STLVmWrFlowVar", flowWrVarParameters)); return instructions; }
From source file:com.exalttech.trex.ui.views.streams.binders.BuilderDataBinding.java
License:Apache License
private JsonArray buildProtoFieldsFromMap(Map<String, String> fieldsMap) { JsonArray fields = new JsonArray(); fieldsMap.entrySet().forEach(entry -> { fields.add(buildProtoField(entry.getKey(), entry.getValue())); });//from www. jav a 2 s . com return fields; }
From source file:com.example.app.support.FormProcessJsonUtil.java
License:Open Source License
/** * Convert the FormProcess to JSON.//from ww w .ja v a 2s . co m * * @param formProcess the form process * @param context Optional context section for the JSON document. * @param lc the locale context * * @return json */ public static JsonObject toJSON(FormProcess formProcess, JsonObject context, LocaleContext lc) { final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); JsonObject form = new JsonObject(); form.addProperty("programmaticIdentifier", formProcess.getFormRevision().getFormDefinition().getProgrammaticIdentifier()); form.addProperty("status", formProcess.getState().name()); form.addProperty("submitTime", formProcess.getSubmitTime() == null ? null : sdf.format(formProcess.getSubmitTime())); form.addProperty("createTime", sdf.format(formProcess.getCreateTime())); JsonObject answers = new JsonObject(); form.add("answers", answers); final EntityRetriever et = EntityRetriever.getInstance(); final FormData formData = FormProcessUtil.getInstance().getFormData(formProcess, true); for (ExtraValue evl : formData.getExtraValueList().getExtraValues()) { evl = et.narrowProxyIfPossible(evl); JsonObject answer = new JsonObject(); Extra e = et.narrowProxyIfPossible(evl.getExtra()); answers.add(e.getProgrammaticName(), answer); if (e.getName() != null) answer.addProperty("name", e.getName().getText(lc).toString()); if (e.getShortName() != null) answer.addProperty("shortName", e.getShortName().getText(lc).toString()); answer.addProperty("type", e.getClass().getSimpleName().replace("Extra", "")); answer.addProperty("answer", evl.getAsText(lc).toString()); if (evl instanceof ChoiceExtraValue) { ChoiceExtraValue cev = (ChoiceExtraValue) evl; ChoiceExtra choiceExtra = (ChoiceExtra) e; if (choiceExtra.isAllowMultipleChoice()) { JsonArray programmatic = new JsonArray(); for (ChoiceExtraChoice choice : cev.getChoices()) { JsonObject c = new JsonObject(); c.addProperty("name", choice.getName().getText(lc).toString()); c.addProperty("programmaticName", choice.getProgrammaticName()); if (!StringFactory.isEmptyString(choice.getReportValue())) c.addProperty("reportValue", choice.getReportValue()); ChoiceTextValue choiceTextValue = cev.getChoiceTextValue(choice); if (choiceTextValue != null) c.addProperty("userText", choiceTextValue.getValue()); programmatic.add(c); } answer.add("programmatic", programmatic); } else { JsonObject c = new JsonObject(); ChoiceExtraChoice choice = cev.getChoices().isEmpty() ? null : cev.getChoices().get(0); if (choice != null) { c.addProperty("name", choice.getName().getText(lc).toString()); c.addProperty("programmaticName", choice.getProgrammaticName()); if (!StringFactory.isEmptyString(choice.getReportValue())) c.addProperty("reportValue", choice.getReportValue()); ChoiceTextValue choiceTextValue = cev.getChoiceTextValue(choice); if (choiceTextValue != null) c.addProperty("userText", choiceTextValue.getValue()); } answer.add("programmatic", c); } } else { Map<Enum<?>, Object> programmaticValueParts = evl.getProgrammaticValueParts(); if (!programmaticValueParts.isEmpty()) { JsonArray programmatic = new JsonArray(); for (Map.Entry<Enum<?>, Object> entry : programmaticValueParts.entrySet()) { JsonObject c = new JsonObject(); programmatic.add(c); c.addProperty("part", entry.getKey().name()); c.addProperty("value", entry.getValue() != null ? entry.getValue().toString() : null); } answer.add("programmatic", programmatic); } } } JsonObject json = new JsonObject(); json.add("form", form); if (context != null) json.add("context", context); if (_logger.isTraceEnabled()) { Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls() .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create(); _logger.trace(gson.toJson(json)); } return json; }
From source file:com.example.app.support.ui.vtcrop.VTCropPictureEditorConfig.java
License:Open Source License
/** * To json.// ww w.j a va2s . c om * * @return the string */ public String toJson() { Gson gson = new Gson(); JsonObject json = new JsonObject(); if (getImageSelector() != null) json.add("image_selector", new JsonPrimitive(getImageSelector())); if (getAcceptUndefinedImageTarget() != null) json.add("accept_undefined_image_target", new JsonPrimitive(getAcceptUndefinedImageTarget())); if (getConstrainAspectRatio() != null) json.add("constrain_aspectratio", new JsonPrimitive(getConstrainAspectRatio())); if (getMinWidth() != null) json.add("min_width", new JsonPrimitive(getMinWidth())); if (getMinHeight() != null) json.add("min_height", new JsonPrimitive(getMinHeight())); if (getMaxWidth() != null) json.add("max_width", new JsonPrimitive(getMaxWidth())); if (getMaxHeight() != null) json.add("max_height", new JsonPrimitive(getMaxHeight())); if (getCropWidth() != null) json.add("crop_width", new JsonPrimitive(getCropWidth())); if (getCropHeight() != null) json.add("crop_height", new JsonPrimitive(getCropHeight())); if (getImageBackgroundStr() != null) json.add("image_background_str", new JsonPrimitive(getImageBackgroundStr())); if (getImageType() != null) json.add("image_type", new JsonPrimitive(getImageType())); if (getEncoderOptions() != null) json.add("encoder_options", new JsonPrimitive(getEncoderOptions())); if (getImageScales() != null) { JsonArray imageScales = new JsonArray(); for (ImageScaleOption imageScale : getImageScales()) { imageScales.add(gson.toJsonTree(imageScale)); } json.add("image_scales", imageScales); } return gson.toJson(json); }
From source file:com.example.notification.executors.NotificationInterestedInExecutor.java
License:Apache License
@Override public GoPluginApiResponse execute() throws Exception { JsonObject jsonObject = new JsonObject(); JsonArray notifications = new JsonArray(); notifications.add(REQUEST_STAGE_STATUS.requestName()); notifications.add(REQUEST_AGENT_STATUS.requestName()); jsonObject.add("notifications", notifications); DefaultGoPluginApiResponse defaultGoPluginApiResponse = new DefaultGoPluginApiResponse(200); defaultGoPluginApiResponse.setResponseBody(GSON.toJson(jsonObject)); return defaultGoPluginApiResponse; }
From source file:com.exorath.commons.ItemStackSerialize.java
License:Apache License
public static JsonObject fromItemStack(ItemStack is) { JsonObject itemObject = new JsonObject(); itemObject.addProperty("material", is.getType().name()); itemObject.addProperty("amount", is.getAmount()); itemObject.addProperty("durability", is.getDurability()); if (is.getItemMeta().hasDisplayName()) itemObject.addProperty("displayName", is.getItemMeta().getDisplayName()); if (is.getItemMeta().hasLore()) { JsonArray lore = new JsonArray(); for (String l : is.getItemMeta().getLore()) lore.add(new JsonPrimitive(l)); itemObject.add("lore", lore); }//from w w w . j a va2 s.com if (is.getItemMeta().hasEnchants()) { JsonArray enchantments = new JsonArray(); for (Enchantment enchantment : is.getItemMeta().getEnchants().keySet()) { JsonObject ench = new JsonObject(); ench.addProperty("enchantment", enchantment.getName()); ench.addProperty("level", is.getItemMeta().getEnchants().get(enchantment)); enchantments.add(ench); } itemObject.add("enchantments", enchantments); } return itemObject; }