Java Code Examples for com.fasterxml.jackson.databind.JsonNode#has()
The following examples show how to use
com.fasterxml.jackson.databind.JsonNode#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: ApiConnection.java From Wikidata-Toolkit with Apache License 2.0 | 6 votes |
/** * Checks if an API response contains an error and throws a suitable * exception in this case. * * @param root * root node of the JSON result * @throws MediaWikiApiErrorException */ protected void checkErrors(JsonNode root) throws MediaWikiApiErrorException { if (root.has("error")) { JsonNode errorNode = root.path("error"); String code = errorNode.path("code").asText("UNKNOWN"); String info = errorNode.path("info").asText("No details provided"); // Special case for the maxlag error since we also want to return // the lag value in the exception thrown if (errorNode.has("lag") && MediaWikiApiErrorHandler.ERROR_MAXLAG.equals(code)) { double lag = errorNode.path("lag").asDouble(); throw new MaxlagErrorException(info, lag); } else { MediaWikiApiErrorHandler.throwMediaWikiApiErrorException(code, info); } } }
Example 2
Source File: AppVersionClientService.java From flowable-engine with Apache License 2.0 | 6 votes |
public String getEndpointType(String contextRoot, String restRoot, String serverAddress, Integer port, String userName, String password) { String result = null; HttpGet get = new HttpGet(clientUtil.getServerUrl(contextRoot, restRoot, serverAddress, port, "enterprise/app-version")); try { JsonNode jsonNode = clientUtil.executeRequest(get, userName, password); if (jsonNode != null && jsonNode.has("type")) { result = jsonNode.get("type").asText(); } } catch (Exception ex) { // could not reach configured server } return result; }
Example 3
Source File: PostmanTestStepsRunner.java From microcks with Apache License 2.0 | 5 votes |
private void extractTestScript(String operationNameRadix, JsonNode itemNode, Operation operation, List<JsonNode> collectedScripts) { String itemNodeName = itemNode.path("name").asText(); // Item may be a folder or an operation description. if (!itemNode.has("request")) { // Item is simply a folder that may contain some other folders recursively. Iterator<JsonNode> items = itemNode.path("item").elements(); while (items.hasNext()) { JsonNode item = items.next(); extractTestScript(operationNameRadix + "/" + itemNodeName, item, operation, collectedScripts); } } else { // Item is here an operation description. String operationName = PostmanCollectionImporter.buildOperationName(itemNode, operationNameRadix); log.debug("Found operation '{}', comparing with '{}'", operationName, operation.getName()); if (operationName.equals(operation.getName())) { // We've got the correct operation. JsonNode events = itemNode.path("event"); for (JsonNode event : events) { if ("test".equals(event.path("listen").asText())) { log.debug("Found a matching event where listen=test"); collectedScripts.add(event); } } } } }
Example 4
Source File: ServerTextChannelImpl.java From Javacord with Apache License 2.0 | 5 votes |
/** * Creates a new server text channel object. * * @param api The discord api instance. * @param server The server of the channel. * @param data The json data of the channel. */ public ServerTextChannelImpl(DiscordApiImpl api, ServerImpl server, JsonNode data) { super(api, server, data); nsfw = data.has("nsfw") && data.get("nsfw").asBoolean(); parentId = Long.parseLong(data.has("parent_id") ? data.get("parent_id").asText("-1") : "-1"); topic = data.has("topic") && !data.get("topic").isNull() ? data.get("topic").asText() : ""; delay = data.has("rate_limit_per_user") ? data.get("rate_limit_per_user").asInt(0) : 0; messageCache = new MessageCacheImpl( api, api.getDefaultMessageCacheCapacity(), api.getDefaultMessageCacheStorageTimeInSeconds(), api.isDefaultAutomaticMessageCacheCleanupEnabled()); }
Example 5
Source File: InviteImpl.java From Javacord with Apache License 2.0 | 5 votes |
/** * Creates a new invite. * * @param api The discord api instance. * @param data The json data of the invite. */ public InviteImpl(DiscordApi api, JsonNode data) { this.api = api; this.code = data.get("code").asText(); this.serverId = Long.parseLong(data.get("guild").get("id").asText()); this.serverName = data.get("guild").get("name").asText(); this.serverIcon = data.get("guild").has("icon") && !data.get("guild").get("icon").isNull() ? data.get("guild").get("icon").asText() : null; this.serverSplash = data.get("guild").has("splash") && !data.get("guild").get("splash").isNull() ? data.get("guild").get("splash").asText() : null; this.channelId = Long.parseLong(data.get("channel").get("id").asText()); this.channelName = data.get("channel").get("name").asText(); this.channelType = ChannelType.fromId(data.get("channel").get("type").asInt()); // May not be present / only present if requested this.approximateMemberCount = (data.has("approximate_member_count")) ? data.get("approximate_member_count").asInt() : null; this.approximatePresenceCount = (data.has("approximate_presence_count")) ? data.get("approximate_presence_count").asInt() : null; // Rich data (may not be present) this.inviter = data.has("inviter") ? ((DiscordApiImpl) api).getOrCreateUser(data.get("inviter")) : null; this.uses = data.has("uses") ? data.get("uses").asInt() : -1; this.maxUses = data.has("max_uses") ? data.get("max_uses").asInt() : -1; this.maxAge = data.has("max_age") ? data.get("max_age").asInt() : -1; this.temporary = data.has("temporary") && data.get("temporary").asBoolean(); this.creationTimestamp = data.has("created_at") ? OffsetDateTime.parse(data.get("created_at").asText()).toInstant() : null; this.revoked = data.has("revoked") && data.get("revoked").asBoolean(); }
Example 6
Source File: GPlusActivityDeserializer.java From streams with Apache License 2.0 | 5 votes |
/** * Given a raw JsonNode representation of an Activity's attachments, build out that * list of {@link com.google.api.services.plus.model.Activity.PlusObject.Attachments} objects * * @param objectNode objectNode * @return list of {@link com.google.api.services.plus.model.Activity.PlusObject.Attachments} objects */ private List<Activity.PlusObject.Attachments> buildAttachments(JsonNode objectNode) { List<Activity.PlusObject.Attachments> attachments = new ArrayList<>(); if ( objectNode.has("attachments") ) { for (JsonNode attachmentNode : objectNode.get("attachments")) { Activity.PlusObject.Attachments attachments1 = new Activity.PlusObject.Attachments(); attachments1.setObjectType(attachmentNode.get("objectType").asText()); if (attachmentNode.has("displayName")) { attachments1.setDisplayName(attachmentNode.get("displayName").asText()); } if (attachmentNode.has("content")) { attachments1.setContent(attachmentNode.get("content").asText()); } if (attachmentNode.has("url")) { attachments1.setUrl(attachmentNode.get("url").asText()); } if( attachmentNode.has("image")) { Activity.PlusObject.Attachments.Image image1 = new Activity.PlusObject.Attachments.Image(); JsonNode imageNode1 = attachmentNode.get("image"); image1.setUrl(imageNode1.get("url").asText()); attachments1.setImage(image1); } attachments.add(attachments1); } } return attachments; }
Example 7
Source File: DefinitionParserService.java From swaggerhub-maven-plugin with Apache License 2.0 | 5 votes |
public static String getOASVersion(JsonNode definition) throws DefinitionParsingException { if (definition.has("swagger")) { return definition.get("swagger").textValue(); }else if (definition.has("openapi")){ return definition.get("openapi").textValue(); }else{ throw new DefinitionParsingException("Unable to validate the OAS version of the definition."); } }
Example 8
Source File: JsonFilterSpecMapper.java From crnk-framework with Apache License 2.0 | 5 votes |
private boolean isSerializedFilterSpec(JsonNode jsonNode) { if (jsonNode.isArray() && jsonNode.size() > 0) { return isSerializedFilterSpec(jsonNode.get(0)); } if (jsonNode instanceof ObjectNode) { return jsonNode.has("path") && jsonNode.has("value") || jsonNode.has("expression") && jsonNode.has("operator"); } return false; }
Example 9
Source File: CyclingOutputContainerLayoutManagerDeserializer.java From beakerx with Apache License 2.0 | 5 votes |
@Override protected CyclingOutputContainerLayoutManager createOutputContainerLayoutManager(JsonNode n) { CyclingOutputContainerLayoutManager layout = new CyclingOutputContainerLayoutManager(); if (n.has("period")) { layout.setPeriod(n.get("period").asLong()); } return layout; }
Example 10
Source File: WebhookImpl.java From Javacord with Apache License 2.0 | 5 votes |
/** * Creates a new webhook. * * @param api The discord api instance. * @param data The json data of the webhook. */ public WebhookImpl(DiscordApi api, JsonNode data) { this.api = (DiscordApiImpl) api; this.id = Long.parseLong(data.get("id").asText()); this.serverId = data.has("guild_id") ? Long.parseLong(data.get("guild_id").asText()) : null; this.channelId = Long.parseLong(data.get("channel_id").asText()); this.user = data.has("user") ? this.api.getOrCreateUser(data.get("user")) : null; this.name = data.has("name") && !data.get("name").isNull() ? data.get("name").asText() : null; this.avatarId = data.has("avatar") && !data.get("avatar").isNull() ? data.get("avatar").asText() : null; this.token = data.has("token") ? data.get("token").asText() : null; }
Example 11
Source File: WebSocketService.java From htwplus with MIT License | 4 votes |
/** * WebSocket method when sending chat. * * @param wsMessage WebSocket message as JsonNode object * @param senderActor Sending actor * @param sender Sending account * @return WebSocket response */ private JsonNode wsSendChat(JsonNode wsMessage, ActorRef senderActor, Account sender) { // validate given parameters if (!wsMessage.has("recipient") || !wsMessage.has("text")) { return this.errorResponse("Could not send chat message, either no \"recipient\" or \"text\" information."); } Long recipientAccountId = wsMessage.get("recipient").asLong(); String text = wsMessage.get("text").asText(); Account recipient = this.getAccountById(recipientAccountId); // check, if recipient exists if (recipient == null) { return this.errorResponse("User not found"); } ActorRef recipientActor = this.getActorForAccount(recipient); // check, if the recipient is online if (recipientActor == null) { return this.errorResponse("Recipient not online"); } // sender should not be recipient if (recipientActor.equals(senderActor)) { return this.errorResponse("Cannot send chat to yourself"); } // check, if sender and recipient are friends if (sender == null || !this.isFriendshipEstablished(sender, recipient)) { return this.errorResponse("You must be a friend of the recipient"); } ObjectNode node = this.successResponseTemplate(WebSocketService.WS_METHOD_RECEIVE_CHAT); node.put("sender", Json.toJson(sender.getAsJson())); node.put("text", text); recipientActor.tell(Json.toJson(node), senderActor); return Json.toJson("OK"); }
Example 12
Source File: SPARQLServiceConverter.java From hypergraphql with Apache License 2.0 | 4 votes |
private String langFilterClause(JsonNode field) { final String PATTERN = "FILTER (lang(%s) = \"%s\") . "; String nodeVar = toVar(field.get(NODE_ID).asText()); JsonNode args = field.get(ARGS); return (args.has(LANG)) ? String.format(PATTERN, nodeVar, args.get(LANG).asText()) : ""; }
Example 13
Source File: DatasetBeanConversion.java From data-prep with Apache License 2.0 | 4 votes |
private BiFunction<Dataset, DataSetMetadata, DataSetMetadata> convertDatasetToDatasetMetadata() { return (dataset, dataSetMetadata) -> { dataSetMetadata.setName(dataset.getLabel()); dataSetMetadata.setCreationDate(dataset.getCreated()); dataSetMetadata.setLastModificationDate(dataset.getUpdated()); dataSetMetadata.setAuthor(dataset.getOwner()); Dataset.CertificationState certificationState = dataset.getCertification(); if (certificationState != null) { DataSetGovernance governance = new DataSetGovernance(); governance.setCertificationStep(DataSetGovernance.Certification.valueOf(certificationState.name())); dataSetMetadata.setGovernance(governance); } JsonNode datasetProperties = dataset.getProperties(); if (datasetProperties == null) { datasetProperties = objectMapper.createObjectNode(); } Datastore datastore = dataset.getDatastore(); //FIXME bypass for content / location information about local file or live dataset if (datastore == null) { try { if (datasetProperties.has("content")) { DataSetContent content = objectMapper.treeToValue(datasetProperties.get("content"), DataSetContent.class); dataSetMetadata.setContent(content); } else { LOGGER.warn("no dataset content for the dataset [{}]", dataSetMetadata.getId()); } if (datasetProperties.has("location")) { DataSetLocation location = objectMapper.treeToValue(datasetProperties.get("location"), DataSetLocation.class); dataSetMetadata.setLocation(location); } else { LOGGER.warn("no dataset location for the dataset [{}]", dataSetMetadata.getId()); } } catch (JsonProcessingException e) { throw new TalendRuntimeException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e); } } // Manage legacy fields that doesn't match data catalog concept Dataset.DataSetMetadataLegacy dataSetMetadataLegacy = dataset.getDataSetMetadataLegacy(); if (dataSetMetadataLegacy != null) { dataSetMetadata.setSheetName(dataSetMetadataLegacy.getSheetName()); dataSetMetadata.setSchemaParserResult(dataSetMetadataLegacy.getSchemaParserResult()); dataSetMetadata.setDraft(dataSetMetadataLegacy.isDraft()); dataSetMetadata.setEncoding(dataSetMetadataLegacy.getEncoding()); dataSetMetadata.setTag(dataSetMetadataLegacy.getTag()); dataSetMetadata.getContent().setNbRecords(dataSetMetadataLegacy.getNbRecords()); } return dataSetMetadata; }; }
Example 14
Source File: FunnelTest.java From KeenClient-Java with MIT License | 4 votes |
private List<FunnelStep> buildFunnelStepsFromRequestJson(JsonNode requestJson) { JsonNode stepsJson = requestJson.findValue("steps"); // Construct a list of funnel steps based on provided data List<FunnelStep> funnelSteps = new ArrayList<FunnelStep>(); for (JsonNode stepJson : stepsJson) { Timeframe timeframe = null; List<Filter> filters = null; Boolean inverted = null; Boolean optional = null; Boolean withActors = null; if (stepJson.has(KeenQueryConstants.TIMEFRAME) && stepJson.has(KeenQueryConstants.TIMEZONE)) { timeframe = new RelativeTimeframe( stepJson.get(KeenQueryConstants.TIMEFRAME).asText(), stepJson.get(KeenQueryConstants.TIMEZONE).asText()); } else if(stepJson.has(KeenQueryConstants.TIMEFRAME)) { JsonNode timeframeJson = stepJson.get(KeenQueryConstants.TIMEFRAME); if (!timeframeJson.isObject()) { timeframe = new RelativeTimeframe(timeframeJson.asText()); } else { throw new IllegalStateException( "Building absolute timeframes isn't supported by this method."); } } if (stepJson.has(KeenQueryConstants.FILTERS)) { JsonNode filterListJson = stepJson.get(KeenQueryConstants.FILTERS); for (JsonNode filterJson : filterListJson) { if (null == filters) { filters = new LinkedList<Filter>(); } filters.add( new Filter( filterJson.get(KeenQueryConstants.PROPERTY_NAME).asText(), stringToFilterOperator(filterJson.get(KeenQueryConstants.OPERATOR).asText()), filterJson.get(KeenQueryConstants.PROPERTY_VALUE).asText() ) ); } } if (stepJson.has(KeenQueryConstants.INVERTED)) { inverted = stepJson.get(KeenQueryConstants.INVERTED).asBoolean(); } if (stepJson.has(KeenQueryConstants.OPTIONAL)) { optional = stepJson.get(KeenQueryConstants.OPTIONAL).asBoolean(); } if (stepJson.has(KeenQueryConstants.WITH_ACTORS)) { withActors = stepJson.get(KeenQueryConstants.WITH_ACTORS).asBoolean(); } FunnelStep step = new FunnelStep( stepJson.get(KeenQueryConstants.EVENT_COLLECTION).asText(), stepJson.get(KeenQueryConstants.ACTOR_PROPERTY).asText(), timeframe, filters, inverted, optional, withActors ); funnelSteps.add(step); } return funnelSteps; }
Example 15
Source File: FFmpegParser.java From airsonic-advanced with GNU General Public License v3.0 | 4 votes |
/** * Parses meta data for the given music file. No guessing or reformatting is done. * * * @param file The music file to parse. * @return Meta data for the file. */ @Override public MetaData getRawMetaData(Path file) { MetaData metaData = new MetaData(); try { // Use `ffprobe` in the transcode directory if it exists, otherwise let the system sort it out. String ffprobe; Path inTranscodeDirectory = Util.isWindows() ? transcodingService.getTranscodeDirectory().resolve("ffprobe.exe") : transcodingService.getTranscodeDirectory().resolve("ffprobe"); if (Files.exists(inTranscodeDirectory)) { ffprobe = inTranscodeDirectory.toAbsolutePath().toString(); } else { ffprobe = "ffprobe"; } List<String> command = new ArrayList<>(); command.add(ffprobe); command.addAll(Arrays.asList(FFPROBE_OPTIONS)); command.add(file.toAbsolutePath().toString()); Process process = Runtime.getRuntime().exec(command.toArray(new String[0])); final JsonNode result = objectMapper.readTree(process.getInputStream()); metaData.setDuration(result.at("/format/duration").asDouble()); // Bitrate is in Kb/s metaData.setBitRate(result.at("/format/bit_rate").asInt() / 1000); // Find the first (if any) stream that has dimensions and use those. // 'width' and 'height' are display dimensions; compare to 'coded_width', 'coded_height'. for (JsonNode stream : result.at("/streams")) { if (stream.has("width") && stream.has("height")) { metaData.setWidth(stream.get("width").asInt()); metaData.setHeight(stream.get("height").asInt()); break; } } } catch (Throwable x) { LOG.warn("Error when parsing metadata in " + file, x); } return metaData; }
Example 16
Source File: SchemaReader.java From smallrye-open-api with Apache License 2.0 | 4 votes |
/** * Reads a {@link Schema} OpenAPI node. * * @param node json node * @return Schema model */ public static Schema readSchema(final JsonNode node) { if (node == null || !node.isObject()) { return null; } IoLogging.log.singleJsonObject("Schema"); String name = JsonUtil.stringProperty(node, SchemaConstant.PROP_NAME); Schema schema = new SchemaImpl(name); schema.setRef(JsonUtil.stringProperty(node, Referenceable.PROP_$REF)); schema.setFormat(JsonUtil.stringProperty(node, SchemaConstant.PROP_FORMAT)); schema.setTitle(JsonUtil.stringProperty(node, SchemaConstant.PROP_TITLE)); schema.setDescription(JsonUtil.stringProperty(node, SchemaConstant.PROP_DESCRIPTION)); schema.setDefaultValue(readObject(node.get(SchemaConstant.PROP_DEFAULT))); schema.setMultipleOf(JsonUtil.bigDecimalProperty(node, SchemaConstant.PROP_MULTIPLE_OF)); schema.setMaximum(JsonUtil.bigDecimalProperty(node, SchemaConstant.PROP_MAXIMUM)); schema.setExclusiveMaximum(JsonUtil.booleanProperty(node, SchemaConstant.PROP_EXCLUSIVE_MAXIMUM).orElse(null)); schema.setMinimum(JsonUtil.bigDecimalProperty(node, SchemaConstant.PROP_MINIMUM)); schema.setExclusiveMinimum(JsonUtil.booleanProperty(node, SchemaConstant.PROP_EXCLUSIVE_MINIMUM).orElse(null)); schema.setMaxLength(JsonUtil.intProperty(node, SchemaConstant.PROP_MAX_LENGTH)); schema.setMinLength(JsonUtil.intProperty(node, SchemaConstant.PROP_MIN_LENGTH)); schema.setPattern(JsonUtil.stringProperty(node, SchemaConstant.PROP_PATTERN)); schema.setMaxItems(JsonUtil.intProperty(node, SchemaConstant.PROP_MAX_ITEMS)); schema.setMinItems(JsonUtil.intProperty(node, SchemaConstant.PROP_MIN_ITEMS)); schema.setUniqueItems(JsonUtil.booleanProperty(node, SchemaConstant.PROP_UNIQUE_ITEMS).orElse(null)); schema.setMaxProperties(JsonUtil.intProperty(node, SchemaConstant.PROP_MAX_PROPERTIES)); schema.setMinProperties(JsonUtil.intProperty(node, SchemaConstant.PROP_MIN_PROPERTIES)); schema.setRequired(JsonUtil.readStringArray(node.get(SchemaConstant.PROP_REQUIRED)).orElse(null)); schema.setEnumeration(JsonUtil.readObjectArray(node.get(SchemaConstant.PROP_ENUM)).orElse(null)); schema.setType(readSchemaType(node.get(SchemaConstant.PROP_TYPE))); schema.setItems(readSchema(node.get(SchemaConstant.PROP_ITEMS))); schema.setNot(readSchema(node.get(SchemaConstant.PROP_NOT))); schema.setAllOf(readSchemaArray(node.get(SchemaConstant.PROP_ALL_OF)).orElse(null)); schema.setProperties(readSchemas(node.get(SchemaConstant.PROP_PROPERTIES)).orElse(null)); if (node.has(SchemaConstant.PROP_ADDITIONAL_PROPERTIES) && node.get(SchemaConstant.PROP_ADDITIONAL_PROPERTIES).isObject()) { schema.setAdditionalPropertiesSchema(readSchema(node.get(SchemaConstant.PROP_ADDITIONAL_PROPERTIES))); } else { schema.setAdditionalPropertiesBoolean( JsonUtil.booleanProperty(node, SchemaConstant.PROP_ADDITIONAL_PROPERTIES).orElse(null)); } schema.setReadOnly(JsonUtil.booleanProperty(node, SchemaConstant.PROP_READ_ONLY).orElse(null)); schema.setXml(XmlReader.readXML(node.get(SchemaConstant.PROP_XML))); schema.setExternalDocs(ExternalDocsReader.readExternalDocs(node.get(ExternalDocsConstant.PROP_EXTERNAL_DOCS))); schema.setExample(readObject(node.get(SchemaConstant.PROP_EXAMPLE))); schema.setOneOf(readSchemaArray(node.get(SchemaConstant.PROP_ONE_OF)).orElse(null)); schema.setAnyOf(readSchemaArray(node.get(SchemaConstant.PROP_ANY_OF)).orElse(null)); schema.setNot(readSchema(node.get(SchemaConstant.PROP_NOT))); schema.setDiscriminator(DiscriminatorReader.readDiscriminator(node.get(SchemaConstant.PROP_DISCRIMINATOR))); schema.setNullable(JsonUtil.booleanProperty(node, SchemaConstant.PROP_NULLABLE).orElse(null)); schema.setWriteOnly(JsonUtil.booleanProperty(node, SchemaConstant.PROP_WRITE_ONLY).orElse(null)); schema.setDeprecated(JsonUtil.booleanProperty(node, SchemaConstant.PROP_DEPRECATED).orElse(null)); ExtensionReader.readExtensions(node, schema); return schema; }
Example 17
Source File: ChannelCategoryImpl.java From Javacord with Apache License 2.0 | 2 votes |
/** * Creates a new server channel category object. * * @param api The discord api instance. * @param server The server of the channel. * @param data The json data of the channel. */ public ChannelCategoryImpl(DiscordApiImpl api, ServerImpl server, JsonNode data) { super(api, server, data); nsfw = data.has("nsfw") && data.get("nsfw").asBoolean(); }
Example 18
Source File: ErrorProcessor.java From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 | 2 votes |
/** * Returns true if the error matches more than one schema. * * @param error * @return true if validation concerns more than one schema. */ private boolean isMultiple(JsonNode error) { return error.has("nrSchemas") && error.get("nrSchemas").asInt() > 1; }
Example 19
Source File: EmbedProviderImpl.java From Javacord with Apache License 2.0 | 2 votes |
/** * Creates a new embed provider. * * @param data The json data of the provider. */ public EmbedProviderImpl(JsonNode data) { name = data.has("name") ? data.get("name").asText() : null; url = data.has("url") && !data.get("url").isNull() ? data.get("url").asText() : null; }
Example 20
Source File: JsonReference.java From KaiZen-OpenAPI-Editor with Eclipse Public License 1.0 | 2 votes |
/** * Returns true if the argument can be identified as a JSON reference node. * * A node is considered a reference if it is an object node and has a field named $ref having a textual value. * * @param node * @return true if a reference node */ public static boolean isReference(JsonNode value) { return value != null && value.isObject() && value.has(PROPERTY) && value.get(PROPERTY).isTextual(); }