Java Code Examples for com.google.gson.JsonObject#size()

The following examples show how to use com.google.gson.JsonObject#size() . 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: IntersectingSourceStateSerializer.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
@Override
public JsonObject serialize(
		final IntersectingSourceState state,
		final Type type,
		final JsonSerializationContext context)
{
	final JsonObject map = new JsonObject();
	map.addProperty(NAME_KEY, state.nameProperty().get());
	map.add(
			SourceStateSerialization.DEPENDS_ON_KEY,
			context.serialize(Arrays.stream(state.dependsOn()).mapToInt(stateToIndex).toArray()));
	map.addProperty(COMPOSITE_TYPE_KEY, state.compositeProperty().get().getClass().getName());
	map.add(COMPOSITE_KEY, context.serialize(state.compositeProperty().get()));

	final JsonObject meshesMap = new JsonObject();
	if (state.areMeshesEnabled() != IntersectingSourceState.DEFAULT_MESHES_ENABLED)
		meshesMap.addProperty(MESHES_ENABLED_KEY, state.areMeshesEnabled());
	if (meshesMap.size() > 0)
		map.add(MESHES_KEY, meshesMap);

	return map;
}
 
Example 2
Source File: ThresholdingSourceStateSerializer.java    From paintera with GNU General Public License v2.0 6 votes vote down vote up
@Override
public JsonObject serialize(
		final ThresholdingSourceState<?, ?> state,
		final Type type,
		final JsonSerializationContext context)
{
	final JsonObject map = new JsonObject();
	map.addProperty(NAME_KEY, state.nameProperty().get());
	map.add(DEPENDS_ON_KEY, context.serialize(Arrays.stream(state.dependsOn()).mapToInt(stateToIndex).toArray()));
	final JsonObject converterMap = new JsonObject();
	converterMap.addProperty(FOREGROUND_COLOR_KEY, Colors.toHTML(state.converter().getMasked()));
	converterMap.addProperty(BACKGROUND_COLOR_KEY, Colors.toHTML(state.converter().getNotMasked()));
	map.add(CONVERTER_KEY, converterMap);
	map.add(COMPOSITE_KEY, SerializationHelpers.serializeWithClassInfo(state.compositeProperty().get(), context));
	map.addProperty(MIN_KEY, state.minProperty().get());
	map.addProperty(MAX_KEY, state.maxProperty().get());

	final JsonObject meshesMap = makeMeshesMap(state, context);
	if (meshesMap.size() > 0)
		map.add(MESHES_KEY, meshesMap);

	return map;
}
 
Example 3
Source File: S3PacbotUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
private static Map<String, Boolean> getReadOrWriteAccessDetails(
		String type, Map<String, Boolean> accessMap, String publicIp,
		String conditionStr, JsonObject conditionJsonObject,
		List<String> conditionList) {
	if ((conditionJsonObject.size() == 0) && (conditionList.isEmpty()) && null == conditionStr) {
		accessMap.put(type, true);
	}
	if (!conditionJsonObject.isJsonNull()) {
		if (conditionJsonObject.toString().equals(publicIp)) {
			accessMap.put(type, true);
		}
	} 
	if (null != conditionStr && conditionStr.contains(publicIp)) {
		accessMap.put(type, true);
	}
	if (conditionList.contains(publicIp)) {
		accessMap.put(type, true);
	}
	return accessMap;
}
 
Example 4
Source File: PacmanUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
private static Map<String, Boolean> getReadOrWriteAccessDetails(String type, Map<String, Boolean> accessMap,
        String publicIp, String conditionStr, JsonObject conditionJsonObject, List<String> conditionList) {
    if ((conditionJsonObject.size() == 0) && (conditionList.isEmpty()) && null == conditionStr) {
        accessMap.put(type, true);
    }
    if (!conditionJsonObject.isJsonNull()) {
        if (conditionJsonObject.toString().equals(publicIp)) {
            accessMap.put(type, true);
        }
    } else if (null != conditionStr && conditionStr.contains(publicIp)) {
        accessMap.put(type, true);
    } else if (conditionList.contains(publicIp)) {
        accessMap.put(type, true);
    }
    return accessMap;
}
 
Example 5
Source File: PrimitiveArray.java    From Prism with MIT License 6 votes vote down vote up
public static PrimitiveArray of(JsonObject jsonObject) {
    if (jsonObject.size() != 2 || !(jsonObject.has("key") && jsonObject.has("value"))) {
        return null;
    }

    if (!jsonObject.get("key").isJsonPrimitive() || !jsonObject.getAsJsonPrimitive("key").isString()) {
        return null;
    }

    String key = jsonObject.get("key").getAsString();
    if (!StringUtils.equalsAny(key, BYTE_ARRAY_ID, INT_ARRAY_ID, LONG_ARRAY_ID)) {
        return null;
    }

    List<Number> value = Lists.newArrayList();
    JsonArray jsonArray = jsonObject.get("value").getAsJsonArray();
    jsonArray.forEach(entry -> value.add(NumberUtils.createNumber(entry.getAsString())));
    return new PrimitiveArray(key, value);
}
 
Example 6
Source File: ITElasticSearchClient.java    From skywalking with Apache License 2.0 6 votes vote down vote up
private JsonObject undoFormatIndexName(JsonObject index) {
    if (StringUtil.isNotEmpty(namespace) && index != null && index.size() > 0) {
        logger.info("UndoFormatIndexName before " + index.toString());
        String namespacePrefix = namespace + "_";
        index.entrySet().forEach(entry -> {
            String oldIndexName = entry.getKey();
            if (oldIndexName.startsWith(namespacePrefix)) {
                index.add(oldIndexName.substring(namespacePrefix.length()), entry.getValue());
                index.remove(oldIndexName);
            } else {
                throw new RuntimeException(
                    "The indexName must contain the " + namespace + " prefix, but it is " + entry
                        .getKey());
            }
        });
        logger.info("UndoFormatIndexName after " + index.toString());
    }
    return index;
}
 
Example 7
Source File: VectorColumnFiller.java    From secor with Apache License 2.0 6 votes vote down vote up
public void convert(JsonElement value, ColumnVector vect, int row) {
    if (value == null || value.isJsonNull()) {
        vect.noNulls = false;
        vect.isNull[row] = true;
    } else {
        MapColumnVector vector = (MapColumnVector) vect;
        JsonObject obj = value.getAsJsonObject();
        vector.lengths[row] = obj.size();
        vector.offsets[row] = row > 0 ? vector.offsets[row - 1] + vector.lengths[row - 1] : 0;

        // Ensure enough space is available to store the keys and the values
        vector.keys.ensureSize((int) vector.offsets[row] + obj.size(), true);
        vector.values.ensureSize((int) vector.offsets[row] + obj.size(), true);

        int i = 0;
        for (String key : obj.keySet()) {
            childConverters[0].convert(new JsonPrimitive(key), vector.keys, (int) vector.offsets[row] + i);
            childConverters[1].convert(obj.get(key), vector.values, (int) vector.offsets[row] + i);
            i++;
        }
    }
}
 
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 List<JsonElement> toList(JsonElement value) {
  if (value.isJsonArray()) {
    return new JsonArrayListWrapper(value.getAsJsonArray());
  } else if (value.isJsonObject()) {
    JsonObject object = value.getAsJsonObject();
    List<JsonElement> list = new ArrayList<>(object.size());
    for(Map.Entry<String, JsonElement> entry : object.entrySet()) {
      list.add(entry.getValue());
    }
    return list;
  } else {
    return Collections.emptyList();
  }
}
 
Example 9
Source File: ContainersListElement.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
private Map<String, String> mapLabels(JsonObject labels) {
    int length = labels.size();
    Map<String, String> mapped = new HashMap<>(length);

    Iterator<String> iterator = labels.keySet().iterator();
    while (iterator.hasNext()) {
        String key = iterator.next();
        mapped.put(key, labels.get(key).getAsString());
    }

    return mapped;
}
 
Example 10
Source File: ContainerDetails.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
private Map<String, String> mapLabels(JsonObject labels) {
    int length = labels.size();
    Map<String, String> mapped = new HashMap<>(length);

    Iterator<String> iterator = labels.keySet().iterator();
    while (iterator.hasNext()) {
        String key = iterator.next();
        mapped.put(key, labels.get(key).getAsString());
    }

    return mapped;
}
 
Example 11
Source File: ImageDetails.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
private Map<String, String> mapLabels(JsonObject labels) {
    int length = labels.size();
    Map<String, String> mapped = new LinkedHashMap<>(length);

    Iterator<String> iterator = labels.keySet().iterator();
    while (iterator.hasNext()) {
        String key = iterator.next();
        mapped.put(key, labels.get(key).getAsString());
    }

    return mapped;
}
 
Example 12
Source File: CustomHttpClient.java    From openvidu with Apache License 2.0 5 votes vote down vote up
public JsonObject rest(HttpMethod method, String path, String body, int status, boolean exactReturnedFields,
		String jsonReturnedValue) throws Exception {
	JsonObject json = this.commonRest(method, path, body, status);
	JsonObject jsonObjExpected = null;
	jsonReturnedValue.replaceAll("'", "\"");
	try {
		jsonObjExpected = JsonParser.parseString(jsonReturnedValue).getAsJsonObject();
	} catch (JsonSyntaxException e1) {
		throw new Exception("Expected json element is a string without a JSON format: " + jsonReturnedValue);
	}

	if (exactReturnedFields) {
		if (jsonObjExpected.size() != json.size()) {
			throw new Exception(
					"Error in number of keys in JSON response to POST (" + json.toString() + ")" + path);
		}
	}
	for (String key : jsonObjExpected.keySet()) {
		Class<?> c1 = jsonObjExpected.get(key).getClass();
		Class<?> c2 = json.get(key).getClass();

		c1 = unifyNumberType(c1);
		c2 = unifyNumberType(c2);

		if (!c1.equals(c2)) {
			throw new Exception("Wrong class of property " + key);
		}
	}
	return json;
}
 
Example 13
Source File: ScorerListSerializer.java    From quaerite with Apache License 2.0 5 votes vote down vote up
public JsonElement serialize(Object o, Type type, JsonSerializationContext jsonSerializationContext) {
    JsonObject jsonObject = new JsonObject();
    String clazzName = o.getClass().getName();
    if (clazzName.startsWith(DEFAULT_CLASS_NAME_SPACE)) {
        clazzName = clazzName.substring(DEFAULT_CLASS_NAME_SPACE.length());
    } else if (! clazzName.contains(".")) {
        throw new IllegalArgumentException(
                "custom scorers must not be in the default package:" + clazzName);
    }
    jsonObject.addProperty(CLASSNAME, clazzName);
    JsonObject params = new JsonObject();
    Scorer scorer = (Scorer) o;
    if (scorer.getAtN() > -1) {
        jsonObject.add("atN",
                new JsonPrimitive(Integer.toString(scorer.getAtN())));
    }
    if (scorer instanceof AbstractJudgmentScorer) {
        AbstractJudgmentScorer jScorer = (AbstractJudgmentScorer) scorer;
        Map<String, String> origParams = jScorer.getParams();
        for (Map.Entry<String, String> e : origParams.entrySet()) {
            params.add(e.getKey(), new JsonPrimitive(e.getValue()));
        }
        if (jScorer.getExportPMatrix()) {
            params.add("exportPMatrix", new JsonPrimitive(true));
        }
        if (jScorer.getUseForTest()) {
            params.add("useForTest", new JsonPrimitive(true));
        }
        if (jScorer.getUseForTrain()) {
            params.add("useForTrain", new JsonPrimitive(true));
        }
        if (params.size() > 0) {
            jsonObject.add("params", params);
        }
    }
    return jsonObject;
}
 
Example 14
Source File: Messenger.java    From messenger4j with MIT License 5 votes vote down vote up
private <R> R doRequest(
    HttpMethod httpMethod,
    String requestUrl,
    Optional<Object> payload,
    Function<JsonObject, R> responseTransformer)
    throws MessengerApiException, MessengerIOException {

  try {
    final Optional<String> jsonBody = payload.map(this.gson::toJson);
    final HttpResponse httpResponse =
        this.httpClient.execute(httpMethod, requestUrl, jsonBody.orElse(null));
    final JsonObject responseJsonObject =
        this.jsonParser.parse(httpResponse.body()).getAsJsonObject();

    if (responseJsonObject.size() == 0) {
      throw new MessengerApiException(
          "The response JSON does not contain any key/value pair", empty(), empty(), empty());
    }

    if (httpResponse.statusCode() >= 200 && httpResponse.statusCode() < 300) {
      return responseTransformer.apply(responseJsonObject);
    } else {
      throw MessengerApiExceptionFactory.create(responseJsonObject);
    }
  } catch (IOException e) {
    throw new MessengerIOException(e);
  }
}
 
Example 15
Source File: ElasticsearchHelperService.java    From xmfcn-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 获取搜索结果,处理高亮词
 *
 * @param result
 * @param esPage
 */
public EsPartion getSearchResult(JestResult result, EsPage esPage) {
    EsPartion pt = null;
    int totalCount = result.getJsonObject().get("hits").getAsJsonObject().get("total").getAsInt();
    JsonArray asJsonArray = result.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray();
    List<JSONObject> list = new ArrayList<>();
    for (int i = 0; i < asJsonArray.size(); i++) {
        JsonElement jsonElement = asJsonArray.get(i);
        JsonObject source = jsonElement.getAsJsonObject().getAsJsonObject("_source").getAsJsonObject();
        JsonObject highlight = jsonElement.getAsJsonObject().getAsJsonObject("highlight");
        Set<Map.Entry<String, JsonElement>> entries = null;
        if (highlight != null) {
            entries = highlight.entrySet();
        }
        if (source == null || source.size() <= 0) {
            continue;
        }
        JSONObject jsonObject = JSONObject.parseObject(source.toString());
        if (jsonObject == null || jsonObject.size() <= 0) {
            continue;
        }
        jsonObject = addHightWord(entries, jsonObject);
        list.add(jsonObject);
    }
    pt = new EsPartion(esPage, list, totalCount);
    return pt;
}
 
Example 16
Source File: ContainersListElement.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private Map<String, String> mapLabels(JsonObject labels) {
    int length = labels.size();
    Map<String, String> mapped = new HashMap<>(length);

    Iterator<String> iterator = labels.keySet().iterator();
    while (iterator.hasNext()) {
        String key = iterator.next();
        mapped.put(key, labels.get(key).getAsString());
    }

    return mapped;
}
 
Example 17
Source File: ContainerDetails.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private Map<String, String> mapLabels(JsonObject labels) {
    int length = labels.size();
    Map<String, String> mapped = new HashMap<>(length);

    Iterator<String> iterator = labels.keySet().iterator();
    while (iterator.hasNext()) {
        String key = iterator.next();
        mapped.put(key, labels.get(key).getAsString());
    }

    return mapped;
}
 
Example 18
Source File: CustomHttpClient.java    From openvidu with Apache License 2.0 4 votes vote down vote up
public JsonObject rest(HttpMethod method, String path, String body, int status, boolean exactReturnedFields,
		Map<String, ?> jsonResponse) throws Exception {
	JsonObject json = this.commonRest(method, path, body, status);

	if (exactReturnedFields) {
		if (jsonResponse.size() != json.size())
			throw new Exception("Error in number of keys in JSON response to POST " + path);
	}

	for (Map.Entry<String, ?> entry : jsonResponse.entrySet()) {
		Object value = entry.getValue();

		if (value instanceof String) {
			try {
				JsonObject jsonObjExpected = JsonParser.parseString((String) value).getAsJsonObject();
				JsonObject jsonObjActual = json.get(entry.getKey()).getAsJsonObject();
				// COMPARE

			} catch (JsonSyntaxException e1) {
				try {
					JsonArray jsonArrayExpected = JsonParser.parseString((String) value).getAsJsonArray();
					JsonArray jsonArrayActual = json.get(entry.getKey()).getAsJsonArray();
					// COMPARE

				} catch (JsonSyntaxException e2) {
					if (((String) value) != json.get(entry.getKey()).getAsString()) {
						throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: "
								+ value + ". Actual: " + json.get(entry.getKey()).getAsString());
					}
				}
			}
		} else if (value instanceof Integer) {
			if (((int) value) != json.get(entry.getKey()).getAsInt()) {
				throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: " + value
						+ ". Actual: " + json.get(entry.getKey()).getAsInt());
			}
		} else if (value instanceof Long) {
			if (((long) value) != json.get(entry.getKey()).getAsLong()) {
				throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: " + value
						+ ". Actual: " + json.get(entry.getKey()).getAsLong());
			}
		} else if (value instanceof Double) {
			if (((double) value) != json.get(entry.getKey()).getAsDouble()) {
				throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: " + value
						+ ". Actual: " + json.get(entry.getKey()).getAsDouble());
			}
		} else if (value instanceof Boolean) {
			if (((boolean) value) != json.get(entry.getKey()).getAsBoolean()) {
				throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: " + value
						+ ". Actual: " + json.get(entry.getKey()).getAsBoolean());
			}
		} else if (value instanceof JSONArray || value instanceof JsonArray) {
			JsonParser.parseString(entry.getValue().toString()).getAsJsonArray();
		} else if (value instanceof JSONObject || value instanceof JsonObject) {
			JsonParser.parseString(entry.getValue().toString()).getAsJsonObject();
		} else {
			throw new Exception("JSON response field cannot be parsed: " + entry.toString());
		}
	}
	return json;
}
 
Example 19
Source File: JsonSourceMapper.java    From siddhi-map-json with Apache License 2.0 4 votes vote down vote up
private Event[] convertToEventArrayForDefaultMapping(Object eventObject) {
    Gson gson = new Gson();
    JsonObject[] eventObjects = gson.fromJson(eventObject.toString(), JsonObject[].class);
    Event[] events = new Event[eventObjects.length];
    int index = 0;
    JsonObject eventObj;
    for (JsonObject jsonEvent : eventObjects) {
        if (jsonEvent.has(DEFAULT_JSON_EVENT_IDENTIFIER)) {
            eventObj = jsonEvent.get(DEFAULT_JSON_EVENT_IDENTIFIER).getAsJsonObject();
            if (failOnMissingAttribute && eventObj.size() < streamAttributes.size()) {
                log.error("Json message " + eventObj.toString() + " contains missing attributes. " +
                        "Hence dropping the message.");
                continue;
            }
        } else {
            eventObj = jsonEvent;
            if (eventObj.size() < streamAttributes.size()) {
                log.error("Json message " + eventObj.toString() + " is not in an accepted format for default " +
                        "mapping. Hence dropping the message.");
                continue;
            }
        }
        Event event = new Event(streamAttributes.size());
        Object[] data = event.getData();


        int position = 0;
        for (Attribute attribute : streamAttributes) {
            String attributeName = attribute.getName();
            Attribute.Type type = attribute.getType();
            JsonElement attributeElement = eventObj.get(attributeName);
            if (attributeElement == null) {
                data[position++] = null;
            } else {
                data[position++] = attributeConverter.getPropertyValue(
                        attributeElement.getAsString(), type);
            }
        }
        events[index++] = event;
    }
    return Arrays.copyOfRange(events, 0, index);
}
 
Example 20
Source File: Replication.java    From java-cloudant with Apache License 2.0 4 votes vote down vote up
private JsonObject createJson() {
    JsonObject json = new JsonObject();
    addProperty(json, "cancel", cancel);
    addProperty(json, "continuous", continuous);
    addProperty(json, "filter", filter);

    if (queryParams != null) {
        json.add("query_params", queryParams);
    }
    if (docIds != null) {
        json.add("doc_ids", client.getGson().toJsonTree(docIds, String[].class));
    }

    addProperty(json, "proxy", proxy);
    addProperty(json, "since_seq", sinceSeq);
    addProperty(json, "create_target", createTarget);

    // source

    if (sourceIamApiKey == null) {
        addProperty(json, "source", source);
    } else {
        JsonObject sourceAuthJson = new JsonObject();
        JsonObject sourceIamJson = new JsonObject();
        addProperty(sourceIamJson, "api_key", sourceIamApiKey);
        sourceAuthJson.add("iam", sourceIamJson);

        JsonObject sourceJson = new JsonObject();
        addProperty(sourceJson, "url", source);
        sourceJson.add("auth", sourceAuthJson);

        json.add("source", sourceJson);
    }

    // target

    JsonObject targetAuth = new JsonObject();

    if (targetIamApiKey != null) {
        JsonObject targetIamJson = new JsonObject();
        addProperty(targetIamJson, "api_key", targetIamApiKey);
        targetAuth.add("iam", targetIamJson);
    }
    if (targetOauth != null) {
        // Note: OAuth is only supported on replication target (not source)
        JsonObject oauth = new JsonObject();
        addProperty(oauth, "consumer_secret", consumerSecret);
        addProperty(oauth, "consumer_key", consumerKey);
        addProperty(oauth, "token_secret", tokenSecret);
        addProperty(oauth, "token", token);
        targetAuth.add("oauth", oauth);
    }

    if (targetAuth.size() == 0) {
        addProperty(json, "target", target);
    } else {
        JsonObject targetJson = new JsonObject();
        addProperty(targetJson, "url", target);
        targetJson.add("auth", targetAuth);

        json.add("target", targetJson);
    }

    return json;
}