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

The following examples show how to use com.google.gson.JsonObject#has() . 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: RetryTimeout.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Background Cloud Function that only executes within
 * a certain time period after the triggering event
 */
@Override
public void accept(PubSubMessage message, Context context) {
  ZonedDateTime utcNow = ZonedDateTime.now(ZoneOffset.UTC);
  ZonedDateTime timestamp = utcNow;

  String data = message.getData();
  JsonObject body = gson.fromJson(data, JsonObject.class);
  if (body != null && body.has("timestamp")) {
    String tz = body.get("timestamp").getAsString();
    timestamp = ZonedDateTime.parse(tz);
  }
  long eventAge = Duration.between(timestamp, utcNow).toMillis();

  // Ignore events that are too old
  if (eventAge > MAX_EVENT_AGE) {
    logger.info(String.format("Dropping event %s.", data));
    return;
  }

  // Process events that are recent enough
  // To retry this invocation, throw an exception here
  logger.info(String.format("Processing event %s.", data));
}
 
Example 2
Source File: MojangAPI.java    From SkinsRestorerX with GNU General Public License v3.0 6 votes vote down vote up
public String getUUIDBackup(String name) throws SkinRequestException {
    this.logger.log("Trying backup API to get UUID for player " + name + ".");

    String output;
    try {
        output = readURL(uuidurl_backup.replace("%name%", name), 10000);

        JsonElement element = new JsonParser().parse(output);
        JsonObject obj = element.getAsJsonObject();

        //System.out.println(output.toString()); //testing
        if (obj.has("code")) {
            if (obj.get("error").getAsString().equalsIgnoreCase("Not Found")) {
                throw new SkinRequestException(Locale.NOT_PREMIUM);
            }
            throw new SkinRequestException(Locale.ALT_API_FAILED);
        }

        return obj.get("uuid").getAsString().replace("-", "");
    } catch (IOException e) {
        throw new SkinRequestException(Locale.NOT_PREMIUM); //TODO: check flow of code
    }
}
 
Example 3
Source File: ProtocolManager.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
private void processPingMessage(ServerSessionFactory factory, Request<JsonElement> request,
    ResponseSender responseSender, String transportId) throws IOException {
  if (maxHeartbeats == 0 || maxHeartbeats > ++heartbeats) {

    long interval = -1;

    if (request.getParams() != null) {
      JsonObject element = (JsonObject) request.getParams();
      if (element.has(INTERVAL_PROPERTY)) {
        interval = element.get(INTERVAL_PROPERTY).getAsLong();
      }
    }

    pingWachdogManager.pingReceived(transportId, interval);

    String sessionId = request.getSessionId();
    JsonObject pongPayload = new JsonObject();
    pongPayload.add(PONG_PAYLOAD, new JsonPrimitive(PONG));
    responseSender.sendPingResponse(new Response<>(sessionId, request.getId(), pongPayload));
  }
}
 
Example 4
Source File: ResourceModelDeserializer.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public ResourceModel deserialize(JsonElement json, java.lang.reflect.Type typeOfT,
        JsonDeserializationContext context) throws JsonParseException {
    if (json == null)
        return null;

    if (!json.isJsonObject())
        return null;

    JsonObject jsonObject = json.getAsJsonObject();
    if (!jsonObject.has("id"))
        return null;

    int id = jsonObject.get("id").getAsInt();
    String name = jsonObject.get("name").getAsString();
    Operations operations = Operations.valueOf(jsonObject.get("operations").getAsString());
    String instancetype = jsonObject.get("instancetype").getAsString();
    boolean mandatory = jsonObject.get("mandatory").getAsBoolean();
    Type type = Type.valueOf(jsonObject.get("type").getAsString().toUpperCase());
    String range = jsonObject.get("range").getAsString();
    String units = jsonObject.get("units").getAsString();
    String description = jsonObject.get("description").getAsString();

    return new ResourceModel(id, name, operations, "multiple".equals(instancetype), mandatory, type, range, units,
            description);
}
 
Example 5
Source File: ContextsFile.java    From LuckPerms with MIT License 6 votes vote down vote up
public void load() {
    Path file = this.configuration.getPlugin().getBootstrap().getDataDirectory().resolve("contexts.json");
    if (!Files.exists(file)) {
        save();
        return;
    }

    try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
        JsonObject data = GsonProvider.normal().fromJson(reader, JsonObject.class);
        if (data == null) {
            return;
        }

        if (data.has("static-contexts")) {
            this.staticContexts = ContextSetJsonSerializer.deserializeContextSet(data.get("static-contexts").getAsJsonObject()).immutableCopy();
        }

        if (data.has("default-contexts")) {
            this.defaultContexts = ContextSetJsonSerializer.deserializeContextSet(data.get("default-contexts").getAsJsonObject()).immutableCopy();
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 6
Source File: PlacementInfo.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
static Set<String> getResourceTags(Placeable<?> element) {
    
    if (!hasPlacement(element))
        return Collections.emptySet(); 
          
    JsonObject placement = placement(element);       
    if (!placement.has(PLACEMENT_RESOURCE_TAGS))
        return Collections.emptySet();
    
    Set<String> elementResourceTags = new HashSet<>();
    addToSet(elementResourceTags, array(placement, PLACEMENT_RESOURCE_TAGS));
    return Collections.unmodifiableSet(elementResourceTags);
}
 
Example 7
Source File: RestVNFPackage.java    From NFVO with Apache License 2.0 5 votes vote down vote up
@ApiOperation(
    value = "Adding a VNFPackage from the Package Repository",
    notes =
        "The JSON object in the request body contains a field named link, which holds the URL to the package on the Open Baton Marketplace")
@RequestMapping(
    value = "/package-repository-download",
    method = RequestMethod.POST,
    consumes = MediaType.APPLICATION_JSON_VALUE)
public String packageRepositoryDownload(
    @RequestBody JsonObject link, @RequestHeader(value = "project-id") String projectId)
    throws IOException, PluginException, VimException, NotFoundException, IncompatibleVNFPackage,
        AlreadyExistingException, NetworkServiceIntegrityException, BadRequestException,
        EntityUnreachableException, InterruptedException {
  Gson gson = new Gson();
  JsonObject jsonObject = gson.fromJson(link, JsonObject.class);
  if (!jsonObject.has("link"))
    throw new BadRequestException("The sent Json has to contain a field named: link");

  String downloadlink;
  try {
    downloadlink = jsonObject.getAsJsonPrimitive("link").getAsString();
  } catch (Exception e) {
    e.printStackTrace();
    throw new BadRequestException("The provided link has to be a string.");
  }
  VirtualNetworkFunctionDescriptor virtualNetworkFunctionDescriptor =
      vnfPackageManagement.onboardFromPackageRepository(downloadlink, projectId);
  return "{ \"id\": \"" + virtualNetworkFunctionDescriptor.getVnfPackageLocation() + "\"}";
}
 
Example 8
Source File: DocumentParser.java    From Insights with Apache License 2.0 5 votes vote down vote up
/**
 * Method not used anymore
 * 
 * @param jsonElement
 * @param nodeDataList
 * @param nodeData
 * @param property
 */
private void processGraphDBJson(JsonElement jsonElement, List<NodeData> nodeDataList,  NodeData nodeData, String property){
	//{"results":[{"columns":["n"],"data":[{"row":[{"name":"Test me"}]},{"row":[{"name":"Test me"}]}]}],"errors":[]}
	if(jsonElement.isJsonNull()){
		return;
	}else if(jsonElement.isJsonArray()){
		JsonArray jsonArray = jsonElement.getAsJsonArray();
		for(JsonElement jsonArrayElement : jsonArray){
			processGraphDBJson(jsonArrayElement, nodeDataList, nodeData, property);
		}
	}else if(jsonElement.isJsonObject()){
		JsonObject jsonObject = jsonElement.getAsJsonObject();
		for(Map.Entry<String, JsonElement> entry : jsonObject.entrySet()){
			if(entry.getKey().equals("row")){
				nodeData = new NodeData();
				nodeDataList.add(nodeData);
				boolean graph = jsonObject.has("graph");
				if(graph){
					JsonArray graphNodes = jsonObject.get("graph").getAsJsonObject().get("nodes").getAsJsonArray();
					if(graphNodes.size() > 0){
						JsonArray labels = graphNodes.get(0).getAsJsonObject().get("labels").getAsJsonArray();
						for(JsonElement label : labels){
							nodeData.getLabels().add(label.getAsString());
						}
					}
				}
			}
			if(!entry.getKey().equals("graph")){
				processGraphDBJson(entry.getValue(), nodeDataList, nodeData, entry.getKey());
			}
		}
	}else if(jsonElement.isJsonPrimitive() && nodeData != null){
		nodeData.setProperty(property, jsonElement.getAsString());
	}
}
 
Example 9
Source File: JsonFunctions.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
static String optionalString(@NotNull JsonObject object, @NotNull String field) {
    if (!object.has(field)) {
        return null;
    }

    return string(object, field);
}
 
Example 10
Source File: PacmanUtils.java    From pacbot with Apache License 2.0 5 votes vote down vote up
public static JsonArray getMemberOf(String resourceId, String url) throws Exception {
    JsonArray memberOf = new JsonArray();
    Map<String, Object> mustFilter = new HashMap<>();
    Map<String, Object> mustNotFilter = new HashMap<>();
    HashMultimap<String, Object> shouldFilter = HashMultimap.create();
    Map<String, Object> mustTermsFilter = new HashMap<>();
    mustFilter.put(PacmanRuleConstants.LATEST, true);
    mustFilter.put(convertAttributetoKeyword(PacmanSdkConstants.RESOURCE_ID), resourceId);

    JsonObject nestedRolesJson = RulesElasticSearchRepositoryUtil.getQueryDetailsFromES(url, mustFilter,
            mustNotFilter, shouldFilter, null, 0, mustTermsFilter, null,null);
    if (nestedRolesJson != null && nestedRolesJson.has(PacmanRuleConstants.HITS)) {
        JsonObject hitsJson = nestedRolesJson.get(PacmanRuleConstants.HITS).getAsJsonObject();
        JsonArray jsonArray = hitsJson.getAsJsonObject().get(PacmanRuleConstants.HITS).getAsJsonArray();
        if (jsonArray.size() > 0) {

            for (int i = 0; i < jsonArray.size(); i++) {
                JsonObject firstObject = (JsonObject) jsonArray.get(i);
                JsonObject sourceJson = (JsonObject) firstObject.get(PacmanRuleConstants.SOURCE);
                if (sourceJson != null) {
                    memberOf = sourceJson.get(PacmanRuleConstants.MEMBER_OF).getAsJsonArray();

                }
            }
        }
    }
    return memberOf;
}
 
Example 11
Source File: JsonParser.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private void reapComments(JsonObject object, Element context) {
	if (object.has("fhir_comments")) {
		JsonArray arr = object.getAsJsonArray("fhir_comments");
		for (JsonElement e : arr) {
			context.getComments().add(e.getAsString());
		}
	}
}
 
Example 12
Source File: EquipmentInfoActivity.java    From kcanotify with GNU General Public License v3.0 5 votes vote down vote up
private String getItemKey(JsonObject item) {
    if (item.has("api_alv")) {
        return KcaUtils.format("%d_%d_%d", item.get("api_slotitem_id").getAsInt(),
                item.get("api_level").getAsInt(), item.get("api_alv").getAsInt());
    } else {
        return KcaUtils.format("%d_%d_n", item.get("api_slotitem_id").getAsInt(), item.get("api_level").getAsInt());
    }
}
 
Example 13
Source File: JsonUtil.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
public static int getIntKey(JsonObject obj, String key)
        throws ResponseFormatException {
    if (obj == null || ! obj.has(key)) {
        throw new ResponseFormatException(key, obj);
    }
    JsonElement val = obj.get(key);
    if (! val.isJsonPrimitive()) {
        throw new ResponseFormatException(key, val);
    }
    try {
        return val.getAsInt();
    } catch (NumberFormatException e) {
        throw new ResponseFormatException(key, val, e);
    }
}
 
Example 14
Source File: MonitorTask.java    From LagMonitor with MIT License 5 votes vote down vote up
public String paste() {
    try {
        HttpURLConnection httpConnection = (HttpURLConnection) new URL(PASTE_URL).openConnection();
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoOutput(true);
        httpConnection.setDoInput(true);

        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(httpConnection.getOutputStream(), StandardCharsets.UTF_8))
        ) {
            writer.write("content=" + UrlEscapers.urlPathSegmentEscaper().escape(toString()));
            writer.write("&from=" + logger.getName());
        }

        JsonObject object;
        try (Reader reader = new BufferedReader(
                new InputStreamReader(httpConnection.getInputStream(), StandardCharsets.UTF_8))
        ) {
            object = new Gson().fromJson(reader, JsonObject.class);
        }

        if (object.has("url")) {
            return object.get("url").getAsString();
        }

        logger.log(Level.INFO, "Failed to parse url from {0}", object);
    } catch (IOException ex) {
        logger.log(Level.SEVERE, "Failed to upload monitoring data", ex);
    }

    return null;
}
 
Example 15
Source File: JsonUtils.java    From Natty with GNU General Public License v3.0 5 votes vote down vote up
public static void handleBackoff(JsonObject root) {
    if (root.has("backoff")) {
        int backoff = root.get("backoff").getAsInt();
        System.out.println("Backing off for " + backoff+ " seconds. Quota left "+root.get("quota_remaining").getAsString());
        try {
            Thread.sleep(1000 * backoff);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 
Example 16
Source File: SOARPlugin.java    From cst with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void addBranchToJson(String newBranch, JsonObject json, JsonObject value) {
    String[] newNodes = newBranch.split("\\.");
    JsonObject temp;// = new JsonObject();

    if (newNodes.length > 1) {
        if (json.has(newNodes[0])) {
            addBranchToJson(newBranch.substring(newNodes[0].length() + 1), json.getAsJsonObject(newNodes[0]), value);
        } else {
            temp = createJsonFromString(newBranch.substring(newNodes[0].length() + 1), value);
            json.add(newNodes[0], temp);
        }
    } else {
        json.add(newNodes[0], value);
    }
}
 
Example 17
Source File: MeshNetworkDeserializer.java    From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns a list of scenes de-serializing the json array containing the scenes
 *
 * @param jsonNetwork json array containing the scenes
 * @param meshUuid    network provisionerUuid
 * @return List of nodes
 */
private List<Scene> deserializeScenes(@NonNull final JsonObject jsonNetwork,
                                      @NonNull final String meshUuid) {
    final List<Scene> scenes = new ArrayList<>();
    try {
        if (!jsonNetwork.has("scenes"))
            return scenes;

        final JsonArray jsonScenes = jsonNetwork.getAsJsonArray("scenes");
        for (int i = 0; i < jsonScenes.size(); i++) {
            final JsonObject jsonScene = jsonScenes.get(i).getAsJsonObject();
            final String name = jsonScene.get("name").getAsString();
            final List<Integer> addresses = new ArrayList<>();
            if (jsonScene.has("addresses")) {
                final JsonArray addressesArray = jsonScene.get("addresses").getAsJsonArray();
                for (int j = 0; j < addressesArray.size(); j++) {
                    addresses.add(Integer.parseInt(addressesArray.get(j).getAsString(), 16));
                }
            }
            final int number = jsonScene.get("number").getAsInt();
            final Scene scene = new Scene(number, addresses, meshUuid);
            scene.setName(name);
        }
    } catch (Exception ex) {
        Log.e(TAG, "Error while de-serializing scenes: " + ex.getMessage());
    }
    return scenes;
}
 
Example 18
Source File: SOARPlugin.java    From cst with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void addBranchToJson(String newBranch, JsonObject json, double value) {
    String[] newNodes = newBranch.split("\\.");
    JsonObject temp;// = new JsonObject();

    if (newNodes.length > 1) {
        if (json.has(newNodes[0])) {
            addBranchToJson(newBranch.substring(newNodes[0].length() + 1), json.getAsJsonObject(newNodes[0]), value);
        } else {
            temp = createJsonFromString(newBranch.substring(newNodes[0].length() + 1), value);
            json.add(newNodes[0], temp);
        }
    } else {
        json.addProperty(newNodes[0], value);
    }
}
 
Example 19
Source File: LabelSourceStateDeserializer.java    From paintera with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
protected LabelSourceState<?, ?> makeState(
		final JsonObject map,
		final DataSource<?, ?> source,
		final Composite<ARGBType, ARGBType> composite,
		final C converter,
		final String name,
		final SourceState<?, ?>[] dependsOn,
		final JsonDeserializationContext context) throws IOException, ClassNotFoundException, ReflectionException {
	final boolean isMaskedSource = source instanceof MaskedSource<?, ?>;
	LOG.debug("Is {} masked source? {}", source, isMaskedSource);
	if (isMaskedSource)
	{
		LOG.debug("Underlying source: {}", ((MaskedSource<?, ?>) source).underlyingSource());
	}

	final SelectedIds selectedIds = context.deserialize(map.get(SELECTED_IDS_KEY), SelectedIds.class);
	final long[] locallyLockedSegments = Optional
			.ofNullable(map.get(LOCKED_SEGMENTS_KEY))
			.map(el -> (long[]) context.deserialize(el, long[].class))
			.orElseGet(() -> new long[] {});

	final JsonObject assignmentMap                  = map.get(ASSIGNMENT_KEY).getAsJsonObject();
	final FragmentSegmentAssignmentState assignment = tryDeserializeOrFallBackToN5(assignmentMap, context, source);

	final SelectedSegments selectedSegments = new SelectedSegments(selectedIds, assignment);

	final JsonObject idServiceMap = map.has(LabelSourceStateSerializer.ID_SERVICE_KEY)
			? map.get(LabelSourceStateSerializer.ID_SERVICE_KEY).getAsJsonObject()
			: null;
	final IdService idService     = tryDeserializeIdServiceOrFallBacktoN5(idServiceMap, context, source);

	final LockedSegmentsOnlyLocal lockedSegments = new LockedSegmentsOnlyLocal(locked -> {}, locallyLockedSegments);

	final AbstractHighlightingARGBStream stream = converter.getStream();
	stream.setSelectedAndLockedSegments(
			selectedSegments, lockedSegments);

	LOG.debug("Deserializing lookup from map {} with key {}", map, LabelSourceStateSerializer.LABEL_BLOCK_MAPPING_KEY);
	final LabelBlockLookup lookup = map.has(LabelSourceStateSerializer.LABEL_BLOCK_MAPPING_KEY)
			? context.deserialize(map.get(LabelSourceStateSerializer.LABEL_BLOCK_MAPPING_KEY), LabelBlockLookup.class)
			: getLabelBlockLookupFromN5IfPossible(isMaskedSource ? ((MaskedSource<?, ?>)source).underlyingSource() : source);

	final MeshManagerWithAssignmentForSegments meshManager = MeshManagerWithAssignmentForSegments.fromBlockLookup(
			(DataSource) source,
			selectedSegments,
			stream,
			arguments.viewer.viewer3D().viewFrustumProperty(),
			arguments.viewer.viewer3D().eyeToWorldTransformProperty(),
			lookup,
			arguments.meshManagerExecutors,
			arguments.meshWorkersExecutors);

	LOG.debug("Creating state with converter {}", converter);
	final LabelSourceState state = new LabelSourceState(
			source,
			converter,
			composite,
			name,
			assignment,
			lockedSegments,
			idService,
			selectedIds,
			meshManager,
			lookup
	);

	if (map.has(LabelSourceStateSerializer.MANAGED_MESH_SETTINGS_KEY))
	{
		final ManagedMeshSettings meshSettings = context.deserialize(
				map.get(LabelSourceStateSerializer.MANAGED_MESH_SETTINGS_KEY),
				ManagedMeshSettings.class
		                                                            );
		state.managedMeshSettings().set(meshSettings);
	}
	return state;

}
 
Example 20
Source File: Output.java    From thunder with GNU Affero General Public License v3.0 4 votes vote down vote up
public Output (JsonObject o, boolean spent) {
    this(o.get("n").getAsInt(), o.get("value").getAsLong(), o.has("addr") ? o.get("addr").getAsString() : "", o.get("tx_index").getAsLong(), o.get
            ("script").getAsString(), spent);
}