Java Code Examples for com.fasterxml.jackson.databind.JsonNode#hasNonNull()

The following examples show how to use com.fasterxml.jackson.databind.JsonNode#hasNonNull() . 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: JsonUtilities.java    From constellation with Apache License 2.0 6 votes vote down vote up
public static Iterator<JsonNode> getFieldIterator(JsonNode node, String... keys) {
    JsonNode current = node;
    for (final String key : keys) {
        if (!current.hasNonNull(key)) {
            return new Iterator<JsonNode>() {
                @Override
                public boolean hasNext() {
                    return false;
                }

                @Override
                public JsonNode next() {
                    throw new NoSuchElementException();
                }
            };
        }
        current = current.get(key);
    }
    return current.iterator();
}
 
Example 2
Source File: Inbox.java    From ddd-wro-warehouse with MIT License 6 votes vote down vote up
private QualityReport parseQualityReport(Request request, Response response, JsonNode json) {
    return new QualityReport(
            !json.hasNonNull("locked") ? Collections.emptyList() :
                    StreamSupport.stream(json.path("locked").spliterator(), false)
                            .map(JsonNode::asText).map(labels::scanPalette)
                            .collect(Collectors.toList()),
            !json.hasNonNull("recovered") ? Collections.emptyList() :
                    StreamSupport.stream(json.path("recovered").spliterator(), false)
                            .map(unlocked -> new Recovered(
                                    labels.scanPalette(unlocked.path("label").asText()),
                                    unlocked.path("recovered").asInt(),
                                    unlocked.path("scraped").asInt())
                            )
                            .collect(Collectors.toList()),
            !json.hasNonNull("destroyed") ? Collections.emptyList() :
                    StreamSupport.stream(json.path("destroyed").spliterator(), false)
                            .map(JsonNode::asText).map(labels::scanPalette)
                            .collect(Collectors.toList())
    );
}
 
Example 3
Source File: JsonNodeMappingSupport.java    From shimmer with Apache License 2.0 6 votes vote down vote up
/**
 * @param parentNode a parent node
 * @param path a path to a child node
 * @return the child node reached by traversing the path, where dots denote nested nodes
 * @throws MissingJsonNodeMappingException if the child node doesn't exist
 */
public static JsonNode asRequiredNode(JsonNode parentNode, String path) {

    Iterable<String> pathSegments = Splitter.on(".").split(path);
    JsonNode node = parentNode;

    for (String pathSegment : pathSegments) {

        if (!node.hasNonNull(pathSegment)) {
            throw new MissingJsonNodeMappingException(node, pathSegment);
        }

        node = node.path(pathSegment);
    }

    return node;
}
 
Example 4
Source File: About.java    From TinCanJava with Apache License 2.0 6 votes vote down vote up
private void init(JsonNode jsonNode) throws URISyntaxException{

        if(jsonNode.hasNonNull("version")) {

            Iterator it = jsonNode.get("version").elements();

            while(it.hasNext()){
                if(version == null) { version = new ArrayList<TCAPIVersion>(); }
                version.add(TCAPIVersion.fromString(((JsonNode)it.next()).textValue()));
            }
        }

        if(jsonNode.hasNonNull("extensions")) {
            extensions = new Extensions(jsonNode.get("extensions"));
        }
    }
 
Example 5
Source File: VoiceStateUpdateHandler.java    From Javacord with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(JsonNode packet) {
    if (!packet.hasNonNull("user_id")) {
        return;
    }

    long userId = packet.get("user_id").asLong();
    if (packet.hasNonNull("guild_id")) {
        handleServerVoiceChannel(packet, userId);
    } else if (packet.hasNonNull("channel_id")) {
        long channelId = packet.get("channel_id").asLong();
        api.getVoiceChannelById(channelId).ifPresent(voiceChannel -> {
            if (voiceChannel instanceof PrivateChannel) {
                handlePrivateChannel(userId, ((PrivateChannelImpl) voiceChannel));
            } else if (voiceChannel instanceof GroupChannel) {
                handleGroupChannel(userId, ((GroupChannelImpl) voiceChannel));
            }
        });
    }
}
 
Example 6
Source File: RegistrationDeserializer.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Override
public Registration deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
	JsonNode node = p.readValueAsTree();
	Registration.Builder builder = Registration.builder();

	if (node.hasNonNull("name")) {
		builder.name(node.get("name").asText());
	}
	if (node.hasNonNull("url")) {
		String url = node.get("url").asText();
		builder.healthUrl(url.replaceFirst("/+$", "") + "/health").managementUrl(url);
	}
	else {
		if (node.hasNonNull("healthUrl")) {
			builder.healthUrl(node.get("healthUrl").asText());
		}
		if (node.hasNonNull("managementUrl")) {
			builder.managementUrl(node.get("managementUrl").asText());
		}
		if (node.hasNonNull("serviceUrl")) {
			builder.serviceUrl(node.get("serviceUrl").asText());
		}
	}

	if (node.has("metadata")) {
		Iterator<Map.Entry<String, JsonNode>> it = node.get("metadata").fields();
		while (it.hasNext()) {
			Map.Entry<String, JsonNode> entry = it.next();
			builder.metadata(entry.getKey(), entry.getValue().asText());
		}
	}

	if (node.hasNonNull("source")) {
		builder.source(node.get("source").asText());
	}

	return builder.build();
}
 
Example 7
Source File: MetricStoreImpl.java    From griffin with Apache License 2.0 5 votes vote down vote up
private List<MetricValue> getMetricValuesFromResponse(Response response)
    throws IOException {
    List<MetricValue> metricValues = new ArrayList<>();
    JsonNode jsonNode = mapper.readTree(EntityUtils.toString(response
        .getEntity()));
    if (jsonNode.hasNonNull("hits") && jsonNode.get("hits")
        .hasNonNull("hits")) {
        for (JsonNode node : jsonNode.get("hits").get("hits")) {
            JsonNode sourceNode = node.get("_source");
            Map<String, Object> value = JsonUtil.toEntity(
                sourceNode.get("value").toString(),
                new TypeReference<Map<String, Object>>() {
                });
            Map<String, Object> meta = JsonUtil.toEntity(
                Objects.toString(sourceNode.get("metadata"), null),
                new TypeReference<Map<String, Object>>() {
                });
            MetricValue metricValue = new MetricValue(
                sourceNode.get("name").asText(),
                Long.parseLong(sourceNode.get("tmst").asText()),
                meta,
                value);
            metricValues.add(metricValue);
        }
    }
    return metricValues;
}
 
Example 8
Source File: LinkedInIdentityProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private JsonNode doHttpGet(String url, String bearerToken) throws IOException {
	JsonNode response = SimpleHttp.doGet(url, session).header("Authorization", "Bearer " + bearerToken).asJson();

	if (response.hasNonNull("serviceErrorCode")) {
		throw new IdentityBrokerException("Could not obtain response from [" + url + "]. Response from server: " + response);
	}

	return response;
}
 
Example 9
Source File: JsonUtilities.java    From constellation with Apache License 2.0 5 votes vote down vote up
public static String getTextField(String defaultVal, JsonNode node, String... keys) {
    JsonNode current = node;
    for (final String key : keys) {
        if (!current.hasNonNull(key)) {
            return defaultVal;
        }
        current = current.get(key);
    }
    return current.textValue();
}
 
Example 10
Source File: GeoJSONDecoder.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
protected GeometryFactory getGeometryFactory(JsonNode node, GeometryFactory factory)
        throws GeoJSONDecodingException {
    if (!node.hasNonNull(JSONConstants.CRS)) {
        return factory;
    } else {
        return decodeCRS(node, factory);
    }
}
 
Example 11
Source File: JsonUtilities.java    From constellation with Apache License 2.0 5 votes vote down vote up
public static double getDoubleField(double defaultVal, JsonNode node, String... keys) {
    JsonNode current = node;
    for (final String key : keys) {
        if (!current.hasNonNull(key)) {
            return defaultVal;
        }
        current = current.get(key);
    }
    return current.doubleValue();
}
 
Example 12
Source File: JsonUtilities.java    From constellation with Apache License 2.0 5 votes vote down vote up
public static int getIntegerField(int defaultVal, JsonNode node, String... keys) {
    JsonNode current = node;
    for (final String key : keys) {
        if (!current.hasNonNull(key)) {
            return defaultVal;
        }
        current = current.get(key);
    }
    return current.intValue();
}
 
Example 13
Source File: JsonUtil.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public static Boolean optBoolean(JsonNode object, String field, Boolean defaultValue) {
return object.hasNonNull(field) ? (Boolean) object.get(field).asBoolean() : defaultValue;
   }
 
Example 14
Source File: DatafileJacksonDeserializer.java    From java-sdk with Apache License 2.0 4 votes vote down vote up
@Override
public DatafileProjectConfig deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    ObjectCodec codec = parser.getCodec();
    JsonNode node = codec.readTree(parser);

    String accountId = node.get("accountId").textValue();
    String projectId = node.get("projectId").textValue();
    String revision = node.get("revision").textValue();
    String version = node.get("version").textValue();
    int datafileVersion = Integer.parseInt(version);

    List<Group> groups = JacksonHelpers.arrayNodeToList(node.get("groups"), Group.class, codec);
    List<Experiment> experiments = JacksonHelpers.arrayNodeToList(node.get("experiments"), Experiment.class, codec);
    List<Attribute> attributes = JacksonHelpers.arrayNodeToList(node.get("attributes"), Attribute.class, codec);
    List<EventType> events = JacksonHelpers.arrayNodeToList(node.get("events"), EventType.class, codec);

    List<Audience> audiences = Collections.emptyList();
    if (node.has("audiences")) {
        audiences = JacksonHelpers.arrayNodeToList(node.get("audiences"), Audience.class, codec);
    }

    List<TypedAudience> typedAudiences = null;
    if (node.has("typedAudiences")) {
        typedAudiences = JacksonHelpers.arrayNodeToList(node.get("typedAudiences"), TypedAudience.class, codec);
    }

    boolean anonymizeIP = false;
    if (datafileVersion >= Integer.parseInt(DatafileProjectConfig.Version.V3.toString())) {
        anonymizeIP = node.get("anonymizeIP").asBoolean();
    }

    List<FeatureFlag> featureFlags = null;
    List<Rollout> rollouts = null;
    Boolean botFiltering = null;
    if (datafileVersion >= Integer.parseInt(DatafileProjectConfig.Version.V4.toString())) {
        featureFlags = JacksonHelpers.arrayNodeToList(node.get("featureFlags"), FeatureFlag.class, codec);
        rollouts = JacksonHelpers.arrayNodeToList(node.get("rollouts"), Rollout.class, codec);
        if (node.hasNonNull("botFiltering")) {
            botFiltering = node.get("botFiltering").asBoolean();
        }
    }

    return new DatafileProjectConfig(
        accountId,
        anonymizeIP,
        botFiltering,
        projectId,
        revision,
        version,
        attributes,
        audiences,
        (List<Audience>) (List<? extends Audience>) typedAudiences,
        events,
        experiments,
        featureFlags,
        groups,
        rollouts
    );
}
 
Example 15
Source File: RouterWebResource.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a collection of floatingIps from floatingIpNodes.
 *
 * @param routerNode the router json node
 * @return routers a collection of router
 */
public Collection<Router> changeJsonToSub(JsonNode routerNode) {
    checkNotNull(routerNode, JSON_NOT_NULL);
    Map<RouterId, Router> subMap = new HashMap<RouterId, Router>();
    if (!routerNode.hasNonNull("id")) {
        throw new IllegalArgumentException("id should not be null");
    } else if (routerNode.get("id").asText().isEmpty()) {
        throw new IllegalArgumentException("id should not be empty");
    }
    RouterId id = RouterId.valueOf(routerNode.get("id").asText());

    if (!routerNode.hasNonNull("tenant_id")) {
        throw new IllegalArgumentException("tenant_id should not be null");
    } else if (routerNode.get("tenant_id").asText().isEmpty()) {
        throw new IllegalArgumentException("tenant_id should not be empty");
    }
    TenantId tenantId = TenantId
            .tenantId(routerNode.get("tenant_id").asText());

    VirtualPortId gwPortId = null;
    if (routerNode.hasNonNull("gw_port_id")) {
        gwPortId = VirtualPortId
                .portId(routerNode.get("gw_port_id").asText());
    }

    if (!routerNode.hasNonNull("status")) {
        throw new IllegalArgumentException("status should not be null");
    } else if (routerNode.get("status").asText().isEmpty()) {
        throw new IllegalArgumentException("status should not be empty");
    }
    Status status = Status.valueOf(routerNode.get("status").asText());

    String routerName = null;
    if (routerNode.hasNonNull("name")) {
        routerName = routerNode.get("name").asText();
    }

    boolean adminStateUp = true;
    checkArgument(routerNode.get("admin_state_up").isBoolean(),
                  "admin_state_up should be boolean");
    if (routerNode.hasNonNull("admin_state_up")) {
        adminStateUp = routerNode.get("admin_state_up").asBoolean();
    }
    boolean distributed = false;
    if (routerNode.hasNonNull("distributed")) {
        distributed = routerNode.get("distributed").asBoolean();
    }
    RouterGateway gateway = null;
    if (routerNode.hasNonNull("external_gateway_info")) {
        gateway = jsonNodeToGateway(routerNode
                .get("external_gateway_info"));
    }
    List<String> routes = new ArrayList<String>();
    DefaultRouter routerObj = new DefaultRouter(id, routerName,
                                                adminStateUp, status,
                                                distributed, gateway,
                                                gwPortId, tenantId, routes);
    subMap.put(id, routerObj);
    return Collections.unmodifiableCollection(subMap.values());
}
 
Example 16
Source File: RouterWebResource.java    From onos with Apache License 2.0 4 votes vote down vote up
@PUT
@Path("{routerUUID}/add_router_interface")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response addRouterInterface(@PathParam("routerUUID") String id,
                                   final InputStream input) {
    if (!get(RouterService.class).exists(RouterId.valueOf(id))) {
        return Response.status(NOT_FOUND).entity(NOT_EXIST).build();
    }
    try {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode subnode = readTreeFromStream(mapper, input);
        if (!subnode.hasNonNull("id")) {
            throw new IllegalArgumentException("id should not be null");
        } else if (subnode.get("id").asText().isEmpty()) {
            throw new IllegalArgumentException("id should not be empty");
        }
        RouterId routerId = RouterId.valueOf(id);
        if (!subnode.hasNonNull("subnet_id")) {
            throw new IllegalArgumentException("subnet_id should not be null");
        } else if (subnode.get("subnet_id").asText().isEmpty()) {
            throw new IllegalArgumentException("subnet_id should not be empty");
        }
        SubnetId subnetId = SubnetId
                .subnetId(subnode.get("subnet_id").asText());
        if (!subnode.hasNonNull("tenant_id")) {
            throw new IllegalArgumentException("tenant_id should not be null");
        } else if (subnode.get("tenant_id").asText().isEmpty()) {
            throw new IllegalArgumentException("tenant_id should not be empty");
        }
        TenantId tenantId = TenantId
                .tenantId(subnode.get("tenant_id").asText());
        if (!subnode.hasNonNull("port_id")) {
            throw new IllegalArgumentException("port_id should not be null");
        } else if (subnode.get("port_id").asText().isEmpty()) {
            throw new IllegalArgumentException("port_id should not be empty");
        }
        VirtualPortId portId = VirtualPortId
                .portId(subnode.get("port_id").asText());
        RouterInterface routerInterface = RouterInterface
                .routerInterface(subnetId, portId, routerId, tenantId);
        get(RouterInterfaceService.class)
                .addRouterInterface(routerInterface);
        return ok(INTFACR_ADD_SUCCESS).build();
    } catch (Exception e) {
        return Response.status(BAD_REQUEST).entity(e.getMessage()).build();
    }
}
 
Example 17
Source File: JsonUtil.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public static String optString(JsonNode object, String field, String defaultValue) {
return object.hasNonNull(field) ? object.get(field).asText() : defaultValue;
   }
 
Example 18
Source File: JDBCHelper.java    From herd-mdl with Apache License 2.0 4 votes vote down vote up
public static List<JDBCTestCase> parseJDBCTestCases(String testCasesFile) throws IOException {
    List<JDBCTestCase> jdbcTestCases = new ArrayList<>();
    // Parse the JSON and populate the test cases
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonTestCases = mapper.readTree(JDBCHelper.class.getResourceAsStream(testCasesFile));
    for (JsonNode jsonTestCase : jsonTestCases) {
        // Print the json test case we are parsing
        printJsonTestCase(jsonTestCase.toString());

        // Extract info
        String name = jsonTestCase.get("name").asText();
        String description = jsonTestCase.get("description").asText();
        if (jsonTestCase.hasNonNull("ignore") && jsonTestCase.get("ignore").asBoolean()) {
            System.out.println("Ignoring test case --> " + name);
            continue;
        }

        JsonNode jsonTestDetails = jsonTestCase.get("testCase");
        JsonNode jsonQuery = jsonTestDetails.get("query");
        List<String> query = new ArrayList<>();
        for (JsonNode jsonQueryStr : jsonQuery) {
            query.add(jsonQueryStr.asText());
        }

        JsonNode jsonConnProps = jsonTestDetails.get("connectionProperties");
        String jdbcDriver = jsonConnProps.get("jdbcDriver").asText();
        String jdbcURL = jsonConnProps.get("jdbcURL").asText();
        String user = jsonConnProps.get("user").asText();
        String password = jsonConnProps.get("password").asText();
        JDBCConnProps connProps = new JDBCConnProps(jdbcDriver, jdbcURL, user, password);

        JDBCTestCase jdbcTestCase = new JDBCTestCase(name, description,
                query.toArray(new String[query.size()]), connProps);

        if (jsonTestDetails.hasNonNull("delimiter")) {
            jdbcTestCase.setDelimiter(jsonTestDetails.get("delimiter").asText());
        }

        if (jsonTestCase.hasNonNull("waitAfterCompletion")) {
            jdbcTestCase.setWaitAfterCompletion(jsonTestCase.get("waitAfterCompletion").asInt());
        }

        if (jsonTestCase.hasNonNull("assert")) {
            JsonNode jsonResults = jsonTestCase.get("assert");
            List<String> results = new ArrayList<>();
            for (JsonNode jsonResult : jsonResults) {
                results.add(jsonResult.asText());
            }
            jdbcTestCase.setAssertVal(results.toArray(new String[results.size()]));
        }
        jdbcTestCases.add(jdbcTestCase);
    }
    return jdbcTestCases;
}
 
Example 19
Source File: JsonODataErrorDeserializer.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
protected ODataError doDeserialize(final JsonParser parser) throws IOException {

    final ODataError error = new ODataError();

    final ObjectNode tree = parser.getCodec().readTree(parser);
    if (tree.has(Constants.JSON_ERROR)) {
      final JsonNode errorNode = tree.get(Constants.JSON_ERROR);

      if (errorNode.has(Constants.ERROR_CODE)) {
        error.setCode(errorNode.get(Constants.ERROR_CODE).textValue());
      }
      if (errorNode.has(Constants.ERROR_MESSAGE)) {
        final JsonNode message = errorNode.get(Constants.ERROR_MESSAGE);
        if (message.isValueNode()) {
          error.setMessage(message.textValue());
        } else if (message.isObject()) {
          error.setMessage(message.get(Constants.VALUE).asText());
        }
      }
      if (errorNode.has(Constants.ERROR_TARGET)) {
        error.setTarget(errorNode.get(Constants.ERROR_TARGET).textValue());
      }
      if (errorNode.hasNonNull(Constants.ERROR_DETAILS)) {
        List<ODataErrorDetail> details = new ArrayList<>();
        JsonODataErrorDetailDeserializer detailDeserializer = new JsonODataErrorDetailDeserializer(serverMode);
        for (JsonNode jsonNode : errorNode.get(Constants.ERROR_DETAILS)) {
          details.add(detailDeserializer.doDeserialize(jsonNode.traverse(parser.getCodec()))
              .getPayload());
        }

        error.setDetails(details);
      }
      if (errorNode.hasNonNull(Constants.ERROR_INNERERROR)) {
        HashMap<String, String> innerErrorMap = new HashMap<>();
        final JsonNode innerError = errorNode.get(Constants.ERROR_INNERERROR);
        for (final Iterator<String> itor = innerError.fieldNames(); itor.hasNext();) {
          final String keyTmp = itor.next();
          final String val = innerError.get(keyTmp).toString();
          innerErrorMap.put(keyTmp, val);
        }
        error.setInnerError(innerErrorMap);
      }
    }

    return error;
  }
 
Example 20
Source File: CommerceUtils.java    From template-compiler with Apache License 2.0 3 votes vote down vote up
public static boolean isMultipleQuantityAllowedForServices(JsonNode websiteSettings) {

    boolean defaultValue = true;
    String fieldName = "multipleQuantityAllowedForServices";

    JsonNode storeSettings = websiteSettings.get("storeSettings");

    if (storeSettings == null || !storeSettings.hasNonNull(fieldName)) {
      return defaultValue;
    }

    return storeSettings.get(fieldName).asBoolean(defaultValue);
  }