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

The following examples show how to use com.google.gson.JsonArray#forEach() . 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: GroovyServices.java    From groovy-language-server with Apache License 2.0 6 votes vote down vote up
private void updateClasspath(JsonObject settings) {
	List<String> classpathList = new ArrayList<>();

	if (settings.has("groovy") && settings.get("groovy").isJsonObject()) {
		JsonObject groovy = settings.get("groovy").getAsJsonObject();
		if (groovy.has("classpath") && groovy.get("classpath").isJsonArray()) {
			JsonArray classpath = groovy.get("classpath").getAsJsonArray();
			classpath.forEach(element -> {
				classpathList.add(element.getAsString());
			});
		}
	}

	if (!classpathList.equals(compilationUnitFactory.getAdditionalClasspathList())) {
		compilationUnitFactory.setAdditionalClasspathList(classpathList);

		createOrUpdateCompilationUnit();
		compile();
		visitAST();
		previousContext = null;
	}
}
 
Example 2
Source File: MetadataPostmanTest.java    From Quicksql with MIT License 6 votes vote down vote up
private void validateSimpleName(String meta, String dbName, String tableName) {
    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(meta);
    JsonElement schemas = element.getAsJsonObject().get("schemas");
    Assert.assertTrue(schemas != null && schemas.getAsJsonArray().size() >= 1);
    JsonArray schemaArr = schemas.getAsJsonArray();
    List<JsonElement> elements = new ArrayList<>();
    schemaArr.forEach(elements::add);
    Assert.assertTrue(elements.stream()
        .anyMatch(el -> el.getAsJsonObject()
            .get("name").getAsString().equals(dbName)));
    Assert.assertTrue(elements.stream()
        .anyMatch(el -> {
            JsonArray arr = el.getAsJsonObject().get("tables").getAsJsonArray();
            List<JsonElement> tables = new ArrayList<>();
            arr.forEach(tables::add);
            return tables.stream()
                .anyMatch(table -> table.getAsJsonObject().get("name")
                    .getAsString().equals(tableName));
        }));
}
 
Example 3
Source File: MTGStockDashBoard.java    From MtgDesktopCompanion with GNU General Public License v3.0 6 votes vote down vote up
private void initEds() throws IOException {
	
	if(correspondance.isEmpty()) 
	{
		JsonArray arr = RequestBuilder.build().setClient(URLTools.newClient()).method(METHOD.GET).url(MTGSTOCK_API_URI + "/card_sets").toJson().getAsJsonArray();
		arr.forEach(el->{
			if (!el.getAsJsonObject().get("abbreviation").isJsonNull())
				correspondance.put(el.getAsJsonObject().get("abbreviation").getAsString(),el.getAsJsonObject().get("id").getAsInt());
			else
				logger.error("no id for" + el.getAsJsonObject().get("name"));
		});
		logger.debug("init editions id done: " + correspondance.size() + " items");
		
	}
	correspondance.put("FBB", 305);
	correspondance.put("FWB", 306);
	
}
 
Example 4
Source File: MongoUtil.java    From game-server with MIT License 6 votes vote down vote up
/**
 * json 数组转文档
 *
 * @param jsonStr
 * @return
 */
public static List<Object> getDocuments(String jsonStr) {
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(jsonStr);
    if (jsonElement.isJsonArray()) {
        JsonArray jsonArray = jsonElement.getAsJsonArray();
        List<Object> list = new ArrayList<>();
        jsonArray.forEach(element -> {
            if (element.isJsonObject()) {
                Document d = new Document();
                for (Entry<String, JsonElement> entry : element.getAsJsonObject().entrySet()) {
                    d.append(entry.getKey(), getRealValue(entry.getValue().toString()));   //TODO 数据类型检查
                }
                list.add(d);
            } else if (element.isJsonPrimitive()) {
               list.add(getBsonValue(getRealValue(element.getAsString())));
            } else {
                LOGGER.warn("{}数据复杂,不支持多重嵌套", jsonStr);
            }
        });
        return list;
    }
    LOGGER.warn("{}不是json数组", jsonStr);
    return null;
}
 
Example 5
Source File: CommonUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the map from array.
 *
 * @param jsonArray the json array
 * @param ruleUUID the rule UUID
 * @return the map from array
 */
private static Map<String, String> getMapFromArray(JsonArray jsonArray, String ruleUUID) {
    Map<String, String> toReturn = new HashMap<>();
    jsonArray.forEach(e -> {
        if (e.getAsJsonObject().get("encrypt").getAsBoolean())
            try {
                toReturn.put(e.getAsJsonObject().get("key").getAsString(),
                        decrypt(e.getAsJsonObject().get("value").getAsString(), ruleUUID));
            } catch (Exception e1) {
                LOGGER.error("unable to decrypt", e);
            }
        else
            toReturn.put(e.getAsJsonObject().get("key").getAsString(),
                    e.getAsJsonObject().get("value").getAsString());
    });
    return toReturn;
}
 
Example 6
Source File: DataImporterController.java    From curly with Apache License 2.0 6 votes vote down vote up
private List<List<String>> readNodes(JsonArray data) {
    TreeSet<String> attributes = new TreeSet<>();
    List<Map<String, String>> rows = new ArrayList<>();
    data.forEach((elem) -> {
        if (elem.isJsonObject()) {
            JsonObject row = elem.getAsJsonObject();
            Map<String, String> rowMap = row.entrySet().stream().
                    filter((entry) -> entry.getValue().isJsonPrimitive()).
                    collect(Collectors.toMap((entry) -> entry.getKey(),
                            (entry) -> entry.getValue().getAsString()));
            rows.add(rowMap);
            attributes.addAll(rowMap.keySet());
        }
    });
    List<List<String>> results = rows.stream().map((row)
            -> attributes.stream().map((attr)
                    -> row.get(attr)).collect(Collectors.toList())
    ).collect(Collectors.toList());
    results.add(0, new ArrayList<String>(attributes));
    return results;
}
 
Example 7
Source File: SerializableUtils.java    From NetDiscovery with Apache License 2.0 5 votes vote down vote up
public static <T> List<T> fromJsonToList(String json, Type type) {
    JsonParser jsonParser = new JsonParser();
    JsonArray jsonArray = jsonParser.parse(json).getAsJsonArray();
    List<T> list = new ArrayList<>();
    jsonArray.forEach(jsonElement -> list.add(SerializableUtils.fromJson(jsonElement, type)));
    return list;
}
 
Example 8
Source File: RulesRepresenter.java    From gocd with Apache License 2.0 5 votes vote down vote up
public static Rules fromJSON(JsonArray jsonArray) {
    Rules rules = new Rules();

    jsonArray.forEach(directiveJSON -> {
        rules.add(getDirective(directiveJSON));
    });

    return rules;
}
 
Example 9
Source File: HealthRecord.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Parse a JSON array of codes.
 * @param jsonCodes the codes.
 * @return a list of Code objects.
 */
public static List<Code> fromJson(JsonArray jsonCodes) {
  List<Code> codes = new ArrayList<>();
  jsonCodes.forEach(item -> {
    codes.add(new Code((JsonObject) item));
  });
  return codes;
}
 
Example 10
Source File: LoadData.java    From elastic-rabbitmq with MIT License 5 votes vote down vote up
public JsonArray getSKUChannelIds(Long tenantId, JsonArray skuIds) {
    // get sku list info
    JsonObject queryIds = new JsonObject();
    queryIds.add("ids", skuIds);
    HashMap<String, String> param = new HashMap<String, String>();
    param.put("routing", tenantId.toString());

    ESMultiGetResponse response = multiGet(param, queryIds.toString());
    if (response == null) {
        logger.warn("Query sku info failed, no need do any update");
        return new JsonArray();
    }

    ArrayList<ESGetByIdResponse> responses = response.getDocs();
    JsonArray channelIds = new JsonArray();
    for (int i = 0; i < responses.size(); ++i) {
        ESGetByIdResponse res = responses.get(i);
        if (res.getFound()) {
            JsonObject sku = res.getObject();
            JsonArray channels = null;//sku.get(CHANNELIDS) == null ? null : sku.get(CHANNELIDS).getAsJsonArray();
            if (channels != null && channels.size() > 0) {
                channels.forEach( channelId -> {
                    if (!channelIds.contains(channelId)) {
                        channelIds.add(channelId);
                    }
                });
            }
        } else {
            logger.warn("Product with skuIds, but sku body missing");
        }
    }
    return channelIds;
}
 
Example 11
Source File: ESProductListSyncHandler.java    From elastic-rabbitmq with MIT License 5 votes vote down vote up
private void addToArray(JsonArray skuChannels, JsonArray newAdded) {
    newAdded.forEach(id -> {
        if (!skuChannels.contains(id)) {
            skuChannels.add(id);
        }
    });
}
 
Example 12
Source File: FunctionAppTest.java    From faas-tutorial with Apache License 2.0 5 votes vote down vote up
@Test
public void testFunction() {
  JsonObject args = new JsonObject();
  args.addProperty("text", "apple,orange,banana");
  JsonObject response = FunctionApp.main(args);
  assertNotNull(response);
  JsonArray results = response.getAsJsonArray("result");
  assertNotNull(results);
  assertEquals(3, results.size());
  List<String> actuals = new ArrayList<>();
  results.forEach(j -> actuals.add(j.getAsString()));
  assertTrue(actuals.contains("apple"));
  assertTrue(actuals.contains("orange"));
  assertTrue(actuals.contains("banana"));
}
 
Example 13
Source File: ElasticSearchLabelValuesStmt.java    From sofa-lookout with Apache License 2.0 4 votes vote down vote up
@Override
public List<String> executeQuery() {
    //合理大小
    size = size <= 0 || size > MAX_LABEL_SIZE ? MAX_LABEL_SIZE : size;

    QueryBuilder queryBuilder = new QueryBuilder();
    if (label != null) {
        //辅助筛选的label是?
        if (MetricName.equals(label.getName())) {
            queryBuilder.addMustQueries(new QueryBuilder.StringQuery().addMetricName(label.getValue()).toString());
        } else {
            queryBuilder.addMustQueries(
                    new QueryBuilder.StringQuery().addTagCond(label.getName(), label.getValue()).toString());
        }
    }

    Search search = null;
    String query = null;
    //query for metric names;
    if (MetricName.equals(labelName)) {
        if (!StringUtils.isEmpty(q)) {
            //metricName的模糊条件过滤
            queryBuilder.addMustQueries(new QueryBuilder.StringQuery(true).addMetricName(q + "*").toString());
        }
        query = queryBuilder.buildMetricNameQuery(startTime, endTime, size);
    } else {
        //普通tag的模糊条件过滤:q
        query = queryBuilder.buildLabelQuery(labelName, q, startTime, endTime, size);
    }
    search = new Search.Builder(query).addIndex(index).build();

    try {
        JestResult jestResult = jestClient.execute(search);

        if (!jestResult.isSucceeded()) {
            logger.error("execute query err:{}, query body:{}!", jestResult.getErrorMessage(), query);
            throw new RuntimeException(jestResult.getErrorMessage());
        }
        List<String> tags = new ArrayList<>();
        //pop to series set;
        JsonArray elements = jestResult.getJsonObject().getAsJsonObject("aggregations").getAsJsonObject("tags").getAsJsonArray(
                "buckets");
        if (elements != null) {
            elements.forEach(jsonElement -> {
                String key = jsonElement.getAsJsonObject().getAsJsonPrimitive("key").getAsString();
                tags.add(key.substring(key.indexOf('=') + 1));
            });
        }
        return tags;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 14
Source File: ESProductListSyncHandler.java    From elastic-rabbitmq with MIT License 4 votes vote down vote up
private void doProductList(JsonObject jsonObject) {
    Long productId = jsonObject.get("sourceId").getAsLong();
    JsonArray skuIds = jsonObject.get("listIds").getAsJsonArray();

    ESGetByIdResponse response = loadProductChannelListInfo(productId);
    if (response.getFound() != true) {
        logger.error("Product not exist! need redo again later");
        throw new IllegalStateException("need reentrant");
    }

    ESQueryResponse skuChannelResponse = querySKUChannelIds(skuIds, productId);
    Hit hitResult = skuChannelResponse.getHit();
    if (hitResult.getTotal() == 0) {
        logger.warn("No need merge channelsInfo, since no sku list info found");
        return;
    }

    JsonArray skuChannels = new JsonArray();
    hitResult.getHits().forEach (
            hits -> {
                if (hits.getSource() != null && hits.getSource().get(CHANNELIDS_KEY) != null) {
                    addToArray(skuChannels, hits.getSource().get(CHANNELIDS_KEY).getAsJsonArray());
                }
            }
    );

    if (skuChannels.size() == 0) {
        // nothing need change
        return;
    }

    JsonObject productChannels = response.getObject();
    // merge the channels info
    HashMap<String, String> params = new HashMap<>();
    params.put("version", response.getVersion().toString());

    if (productChannels != null && productChannels.get(CHANNELIDS_KEY) != null) {
        JsonArray channles = productChannels.get(CHANNELIDS_KEY).getAsJsonArray();
        channles.forEach(id -> {
            if (!skuChannels.contains(id)) {
                skuChannels.add(id);
            }
        });
    }

    JsonObject updateDoc = new JsonObject();
    updateDoc.add(CHANNELIDS_KEY, skuChannels);
    hotDocumentService.update(ESConstants.STORE_INDEX, ESConstants.PRODUCT_TYPE, productId,
            params, updateDoc, this.conflictFunction());
}
 
Example 15
Source File: GsonArrayAdapter.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public List<?> convertOutput(JsonArray original, AnnotatedType type, ResolutionEnvironment resolutionEnvironment) {
    List<Object> elements = new ArrayList<>(original.size());
    original.forEach(element -> elements.add(resolutionEnvironment.convertOutput(element, resolutionEnvironment.resolver.getTypedElement(), JSON)));
    return elements;
}
 
Example 16
Source File: JsonElementConversionFactory.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
public EnumConverter(JsonSchema enumSchema) {
  super(enumSchema, STRING, false);
  JsonArray symbolsArray = enumSchema.getSymbols();
  symbolsArray.forEach(e -> symbols.add(e.getAsString()));
}
 
Example 17
Source File: Session.java    From openvidu with Apache License 2.0 4 votes vote down vote up
protected Session resetSessionWithJson(JsonObject json) {
	this.sessionId = json.get("sessionId").getAsString();
	this.createdAt = json.get("createdAt").getAsLong();
	this.recording = json.get("recording").getAsBoolean();
	SessionProperties.Builder builder = new SessionProperties.Builder()
			.mediaMode(MediaMode.valueOf(json.get("mediaMode").getAsString()))
			.recordingMode(RecordingMode.valueOf(json.get("recordingMode").getAsString()))
			.defaultOutputMode(Recording.OutputMode.valueOf(json.get("defaultOutputMode").getAsString()));
	if (json.has("defaultRecordingLayout")) {
		builder.defaultRecordingLayout(RecordingLayout.valueOf(json.get("defaultRecordingLayout").getAsString()));
	}
	if (json.has("defaultCustomLayout")) {
		builder.defaultCustomLayout(json.get("defaultCustomLayout").getAsString());
	}
	if (this.properties != null && this.properties.customSessionId() != null) {
		builder.customSessionId(this.properties.customSessionId());
	} else if (json.has("customSessionId")) {
		builder.customSessionId(json.get("customSessionId").getAsString());
	}
	this.properties = builder.build();
	JsonArray jsonArrayConnections = (json.get("connections").getAsJsonObject()).get("content").getAsJsonArray();
	this.activeConnections.clear();
	jsonArrayConnections.forEach(connection -> {
		JsonObject con = connection.getAsJsonObject();

		Map<String, Publisher> publishers = new ConcurrentHashMap<>();
		JsonArray jsonArrayPublishers = con.get("publishers").getAsJsonArray();
		jsonArrayPublishers.forEach(publisher -> {
			JsonObject pubJson = publisher.getAsJsonObject();
			JsonObject mediaOptions = pubJson.get("mediaOptions").getAsJsonObject();
			Publisher pub = new Publisher(pubJson.get("streamId").getAsString(),
					pubJson.get("createdAt").getAsLong(), mediaOptions.get("hasAudio").getAsBoolean(),
					mediaOptions.get("hasVideo").getAsBoolean(), mediaOptions.get("audioActive"),
					mediaOptions.get("videoActive"), mediaOptions.get("frameRate"), mediaOptions.get("typeOfVideo"),
					mediaOptions.get("videoDimensions"));
			publishers.put(pub.getStreamId(), pub);
		});

		List<String> subscribers = new ArrayList<>();
		JsonArray jsonArraySubscribers = con.get("subscribers").getAsJsonArray();
		jsonArraySubscribers.forEach(subscriber -> {
			subscribers.add((subscriber.getAsJsonObject()).get("streamId").getAsString());
		});

		this.activeConnections.put(con.get("connectionId").getAsString(),
				new Connection(con.get("connectionId").getAsString(), con.get("createdAt").getAsLong(),
						OpenViduRole.valueOf(con.get("role").getAsString()), con.get("token").getAsString(),
						con.get("location").getAsString(), con.get("platform").getAsString(),
						con.get("serverData").getAsString(), con.get("clientData").getAsString(), publishers,
						subscribers));
	});
	return this;
}
 
Example 18
Source File: MTGADecksSniffer.java    From MtgDesktopCompanion with GNU General Public License v3.0 4 votes vote down vote up
@Override
public List<RetrievableDeck> getDeckList() throws IOException {
	
	List<RetrievableDeck> ret = new ArrayList<>();
	
	RequestBuilder e = RequestBuilder.build()
			 .setClient(URLTools.newClient())
			 .method(METHOD.GET)
			 .url(URL+"/serverSide")
			 .addHeader("x-requested-with", "XMLHttpRequest")
			 .addContent("draw", "2")
			 .addContent("start", "0")
			 .addContent("length", "100")
			 .addContent("search[value]", "")
			 .addContent("search[regex]", FALSE)
			 .addContent("draw", "2")
			 .addContent("columns[0][data]","0")
			 .addContent("columns[0][name]","deckname")
			 .addContent("columns[0][searchable]",FALSE)
			 .addContent("columns[0][orderable]",TRUE)
			 .addContent("columns[0][orderable]","")
			 .addContent("columns[0][search][regex]",FALSE)
			 .addContent("columns[1][data]","1")
			 .addContent("columns[1][name]","colors")
			 .addContent("columns[1][searchable]",FALSE)
			 .addContent("columns[1][orderable]",FALSE)
			 .addContent("columns[1][search][value]","")
			 .addContent("columns[1][search][regex]",FALSE)
			 .addContent("columns[2][data]","2")
			 .addContent("columns[2][name]","archetype")
			 .addContent("columns[2][searchable]",FALSE)
			 .addContent("columns[2][orderable]",FALSE)
			 .addContent("columns[2][search][value]","")
			 .addContent("columns[2][search][regex]",FALSE)
			 .addContent("columns[3][name]","real_update")
			 .addContent("columns[3][searchable]",FALSE)
			 .addContent("columns[3][orderable]",TRUE)
			 .addContent("columns[3][search][value]","")
			 .addContent("columns[3][search][regex]",FALSE)
			 .addContent("&order[0][column]","3")
			 .addContent("&order[0][dir]","desc");
			 
			 if(!getString(FORMAT).isEmpty())
				 e.addContent("data", "archetype="+ArrayUtils.indexOf(listFilter(), getString(FORMAT)));
				 
				 
			 JsonArray arr = e.toJson().getAsJsonObject().get("data").getAsJsonArray();

			 arr.forEach(a->{
				
				 RetrievableDeck deck = new RetrievableDeck();
				
				 String name = URLTools.toHtml(a.getAsJsonArray().get(0).getAsString()).select("a").text();
		 			name = name.substring(0,name.indexOf(" by "));
		 			name = RegExUtils.replaceAll(name, "BO1","").trim();
		 			deck.setName(name);
			
				 try {
					deck.setUrl(new URI(URL+URLTools.toHtml(a.getAsJsonArray().get(0).getAsString()).select("a").attr("href")));
				 } catch (URISyntaxException e1) {
					logger.error(e1);
				 }
				 
				 deck.setAuthor(URLTools.toHtml(a.getAsJsonArray().get(0).getAsString()).select("p").text());

				 
				 String colors = URLTools.toHtml(a.getAsJsonArray().get(1).getAsString()).select("img").attr("alt");
				 StringBuilder deckColor = new StringBuilder();
				
				 for(int i=0;i<colors.length();i++)
					 	deckColor.append("{").append(String.valueOf(colors.charAt(i)).toUpperCase()).append("}");
				 
				 deck.setColor(deckColor.toString());
				 
				 
				 deck.setDescription(URLTools.toHtml(a.getAsJsonArray().get(2).getAsString()).text());

				
				 ret.add(deck);
				 
			 });

			return ret;
}
 
Example 19
Source File: JsonUtil.java    From olca-app with Mozilla Public License 2.0 4 votes vote down vote up
private static JsonArray deepCopy(JsonArray element) {
	JsonArray copy = new JsonArray();
	element.forEach((child) -> copy.add(deepCopy(child)));
	return copy;
}
 
Example 20
Source File: FqdnExecutor.java    From oneops with Apache License 2.0 4 votes vote down vote up
private List<HealthCheck> healthChecks(Context context, String logKey) {
  Instance lb = context.lb;
  if (lb == null) {
    throw new RuntimeException("DependsOn Lb is empty");
  }
  List<HealthCheck> hcList = new ArrayList<>();
  String listenerJson = lb.getCiAttributes().get(ATTRIBUTE_LISTENERS);
  String ecvMapJson = lb.getCiAttributes().get(ATTRIBUTE_ECV_MAP);
  if (isNotBlank(listenerJson) && isNotBlank(ecvMapJson)) {
    JsonElement element = jsonParser.parse(ecvMapJson);
    if (element instanceof JsonObject) {
      JsonObject root = (JsonObject) element;
      Set<Entry<String, JsonElement>> set = root.entrySet();
      Map<Integer, String> ecvMap = set.stream().
          collect(Collectors.toMap(s -> Integer.parseInt(s.getKey()), s -> s.getValue().getAsString()));
      logger.info(logKey + "listeners "  + listenerJson);
      JsonArray listeners = (JsonArray) jsonParser.parse(listenerJson);
      listeners.forEach(s -> {
        String listener = s.getAsString();
        //listeners are generally in this format 'http <lb-port> http <app-port>', gslb needs to use the lb-port for health checks
        //ecv map is configured as '<app-port> : <ecv-url>', so we need to use the app-port from listener configuration to lookup the ecv config from ecv map
        String[] config = listener.split(" ");
        if (config.length >= 2) {
          String protocol = config[0];
          int lbPort = Integer.parseInt(config[1]);
          int ecvPort = Integer.parseInt(config[config.length-1]);
          String healthConfig = ecvMap.get(ecvPort);
          if (healthConfig != null) {
            if ((protocol.equals("http"))) {
              String path = healthConfig.substring(healthConfig.indexOf(" ")+1);
              logger.info(logKey +  "healthConfig : " + healthConfig + ", health check configuration, protocol: " + protocol + ", port: " + lbPort
                  + ", path " + path);
              hcList.add(newHealthCheck(protocol, lbPort, path));
            } else {
              logger.info(logKey + "health check configuration, protocol: " + protocol + ", port: " + lbPort);
              hcList.add(newHealthCheck(protocol, lbPort, null ));
            }
          }
        }
      });
    }
  }
  return hcList;
}