Example usage for com.fasterxml.jackson.databind JsonNode size

List of usage examples for com.fasterxml.jackson.databind JsonNode size

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode size.

Prototype

public int size() 

Source Link

Usage

From source file:models.metadata.ClimateService.java

public static List<ClimateService> getMostRecentlyAdded() {

    List<ClimateService> climateServices = new ArrayList<ClimateService>();

    JsonNode climateServicesNode = APICall.callAPI(GET_MOST_RECENTLY_ADDED_CLIMATE_SERVICES_CALL);
    if (climateServicesNode == null || climateServicesNode.has("error") || !climateServicesNode.isArray()) {
        return climateServices;
    }/* ww w .jav  a 2 s. co  m*/

    for (int i = 0; i < climateServicesNode.size(); i++) {
        JsonNode json = climateServicesNode.path(i);
        ClimateService newService = new ClimateService();
        newService.setId(json.get("id").asText());
        newService.setClimateServiceName(json.get("name").asText());
        newService.setPurpose(json.findPath("purpose").asText());
        newService.setUrl(json.findPath("url").asText());
        newService.setScenario(json.findPath("scenario").asText());
        newService.setVersion(json.findPath("versionNo").asText());
        newService.setRootservice(json.findPath("rootServiceId").asText());
        climateServices.add(newService);
    }
    return climateServices;
}

From source file:models.metadata.ClimateService.java

public static List<ClimateService> getMostRecentlyUsed() {

    List<ClimateService> climateServices = new ArrayList<ClimateService>();

    JsonNode climateServicesNode = APICall.callAPI(GET_MOST_RECENTLY_USED_CLIMATE_SERVICES_CALL);

    if (climateServicesNode == null || climateServicesNode.has("error") || !climateServicesNode.isArray()) {
        return climateServices;
    }//from  w w  w.  j  a  va  2s.co m

    for (int i = 0; i < climateServicesNode.size(); i++) {
        JsonNode json = climateServicesNode.path(i);
        ClimateService newService = new ClimateService();
        newService.setId(json.get("id").asText());
        newService.setClimateServiceName(json.get("name").asText());
        newService.setPurpose(json.findPath("purpose").asText());
        newService.setUrl(json.findPath("url").asText());
        newService.setScenario(json.findPath("scenario").asText());
        newService.setVersion(json.findPath("versionNo").asText());
        newService.setRootservice(json.findPath("rootServiceId").asText());
        climateServices.add(newService);
    }
    return climateServices;
}

From source file:org.kiji.rest.representations.KijiRestEntityId.java

/**
 * Create KijiRestEntityId from json node.
 *
 * @param node of the RKF2-formatted, materialization unsuppressed row.
 * @param rowKeyFormat2 of the layout or null if the layout has RowKeyFormat1.
 *        If null, then long components may not be recognized.
 * @return a properly constructed KijiRestEntityId.
 * @throws IOException if KijiRestEntityId can not be properly constructed.
 *//* w w  w . jav  a  2 s.  c  o  m*/
public static KijiRestEntityId create(final JsonNode node, final RowKeyFormat2 rowKeyFormat2)
        throws IOException {
    Preconditions.checkNotNull(node);
    if (node.isArray()) {
        final Object[] components = new Object[node.size()];
        boolean wildCarded = false;
        for (int i = 0; i < node.size(); i++) {
            final Object component = getNodeValue(node.get(i));
            if (component.equals(WildcardSingleton.INSTANCE)) {
                wildCarded = true;
                components[i] = null;
            } else if (null != rowKeyFormat2
                    && ComponentType.LONG == rowKeyFormat2.getComponents().get(i).getType()) {
                components[i] = ((Number) component).longValue();
            } else {
                components[i] = component;
            }
        }
        return new KijiRestEntityId(components, wildCarded);
    } else {
        // Disallow non-arrays.
        throw new IllegalArgumentException(
                "Provide components wrapped as a JSON array or provide the row key.");
    }
}

From source file:controllers.nwbib.Lobid.java

/**
 * @param id The resource ID/*from   ww w.  ja  v a2 s  .  c  o  m*/
 * @return The resource JSON content
 */
public static JsonNode getResource(String id) {
    DATA_2 = Application.CONFIG.getBoolean("feature.lobid2.enabled");
    if (DATA_2) {
        String url = String.format(Application.CONFIG.getString("feature.lobid2.indexUrlFormat"), id);
        JsonNode response = cachedJsonCall(url);
        if (response.size() == 0) {
            // Fall back to data 1.x if nothing found:
            String fallbackUrl = String.format("%s/%s?format=full", Application.CONFIG.getString("nwbib.api"),
                    id);
            Logger.warn("No response from Lobid API 2.0 URL '{}', falling back to API 1.x URL '{}'", url,
                    fallbackUrl);
            DATA_2 = false; // required for processing individual fields
            return cachedJsonCall(fallbackUrl);
        }
        return response;
    }
    throw new IllegalStateException("Only implemented for Lobid.DATA_2 feature");
}

From source file:com.attribyte.essem.util.Util.java

/**
 * Gets the first node of an array or the node itself if it is not an array or null.
 * @param fieldsObj The object containing fields.
 * @param key The key.//from  ww  w .  ja va 2 s  .c  o m
 * @return The node or <code>null</code>.
 */
public static JsonNode getFieldNode(final JsonNode fieldsObj, final String key) {
    JsonNode fieldNode = fieldsObj.get(key);
    if (fieldNode != null) {
        if (fieldNode.isArray() && fieldNode.size() > 0) {
            return fieldNode.get(0);
        } else if (!fieldNode.isArray()) {
            return fieldNode;
        } else {
            return null;
        }
    } else {
        return null;
    }
}

From source file:org.kiji.rest.representations.KijiRestEntityId.java

/**
 * Converts a JSON string, integer, or wildcard (empty array)
 * node into a Java object (String, Integer, Long, WILDCARD, or null).
 *
 * @param node JSON string, integer numeric, or wildcard (empty array) node.
 * @return the JSON value, as a String, an Integer, a Long, a WILDCARD, or null.
 * @throws JsonParseException if the JSON node is not String, Integer, Long, WILDCARD, or null.
 *///w w w. ja  v  a  2  s . c om
private static Object getNodeValue(JsonNode node) throws JsonParseException {
    // TODO: Write tests to distinguish integer and long components.
    if (node.isInt()) {
        return node.asInt();
    } else if (node.isLong()) {
        return node.asLong();
    } else if (node.isTextual()) {
        return node.asText();
    } else if (node.isArray() && node.size() == 0) {
        // An empty array token indicates a wildcard.
        return WildcardSingleton.INSTANCE;
    } else if (node.isNull()) {
        return null;
    } else {
        throw new JsonParseException(String.format(
                "Invalid JSON value: '%s', expecting string, int, long, null, or wildcard [].", node), null);
    }
}

From source file:fr.gouv.vitam.utils.json.JsonHandler.java

/**
 * node should have only one property//from w  ww  .  j  a v a 2  s  . c om
 *
 * @param nodeName
 * @param node
 * @return the couple property name and property value
 * @throws InvalidParseOperationException
 */
public static final Entry<String, JsonNode> checkUnicity(final String nodeName, final JsonNode node)
        throws InvalidParseOperationException {
    if (node == null || node.isMissingNode()) {
        throw new InvalidParseOperationException(
                "The current Node is missing(empty): " + nodeName + ":" + node);
    }
    if (node.isValueNode()) {
        // not allowed
        throw new InvalidParseOperationException(
                "The current Node is a simple value and should not: " + nodeName + ":" + node);
    }
    final int size = node.size();
    if (size > 1) {
        throw new InvalidParseOperationException(
                "More than one element in current Node: " + nodeName + ":" + node);
    }
    if (size == 0) {
        throw new InvalidParseOperationException(
                "Not enough element (0) in current Node: " + nodeName + ":" + node);
    }
    final Iterator<Entry<String, JsonNode>> iterator = node.fields();
    return iterator.next();
}

From source file:com.amazonaws.services.kinesis.aggregators.configuration.ExternalConfigurationModel.java

public static List<ExternalConfigurationModel> buildFromConfig(String configFilePath) throws Exception {
    List<ExternalConfigurationModel> response = new ArrayList<>();

    // reference the config file as a full path
    File configFile = new File(configFilePath);
    if (!configFile.exists()) {

        // try to load the file from the classpath
        InputStream classpathConfig = ExternalConfigurationModel.class.getClassLoader()
                .getResourceAsStream(configFilePath);
        if (classpathConfig != null && classpathConfig.available() > 0) {
            configFile = new File(ExternalConfigurationModel.class
                    .getResource((configFilePath.startsWith("/") ? "" : "/") + configFilePath).toURI());

            LOG.info(String.format("Loaded Configuration %s from Classpath", configFilePath));
        } else {// w  w  w. j  a  va  2 s  .c  om
            if (configFilePath.startsWith("s3://")) {
                AmazonS3 s3Client = new AmazonS3Client(new DefaultAWSCredentialsProviderChain());
                TransferManager tm = new TransferManager(s3Client);

                // parse the config path to get the bucket name and prefix
                final String s3ProtoRegex = "s3:\\/\\/";
                String bucket = configFilePath.replaceAll(s3ProtoRegex, "").split("/")[0];
                String prefix = configFilePath.replaceAll(String.format("%s%s\\/", s3ProtoRegex, bucket), "");

                // download the file using TransferManager
                configFile = File.createTempFile(configFilePath, null);
                Download download = tm.download(bucket, prefix, configFile);
                download.waitForCompletion();

                // shut down the transfer manager
                tm.shutdownNow();

                LOG.info(String.format("Loaded Configuration from Amazon S3 %s/%s to %s", bucket, prefix,
                        configFile.getAbsolutePath()));
            } else {
                // load the file from external URL
                try {
                    configFile = File.createTempFile(configFilePath, null);
                    FileUtils.copyURLToFile(new URL(configFilePath), configFile, 1000, 1000);
                    LOG.info(String.format("Loaded Configuration from %s to %s", configFilePath,
                            configFile.getAbsolutePath()));
                } catch (IOException e) {
                    // handle the timeouts and so on with a generalised
                    // config
                    // file not found handler later
                }
            }
        }
    } else {
        LOG.info(String.format("Loaded Configuration from Filesystem %s", configFilePath));
    }

    // if we haven't been able to load a config file, then bail
    if (configFile == null || !configFile.exists()) {
        throw new InvalidConfigurationException(
                String.format("Unable to Load Config File from %s", configFilePath));
    }

    JsonNode document = StreamAggregatorUtils.asJsonNode(configFile);

    ExternalConfigurationModel config = null;

    Iterator<JsonNode> i = document.elements();
    while (i.hasNext()) {
        config = new ExternalConfigurationModel();

        JsonNode section = i.next();

        // set generic properties
        config.setNamespace(StreamAggregatorUtils.readValueAsString(section, "namespace"));
        config.setDateFormat(StreamAggregatorUtils.readValueAsString(section, "dateFormat"));
        addTimeHorizons(section, config);
        setAggregatorType(section, config);

        // set the label items
        JsonNode labelItems = StreamAggregatorUtils.readJsonValue(section, "labelItems");
        if (labelItems != null && labelItems.size() > 0) {
            Iterator<JsonNode> iterator = labelItems.elements();
            while (iterator.hasNext()) {
                JsonNode n = iterator.next();
                config.addLabelItems(n.asText());
            }
        }
        config.setLabelAttributeAlias(StreamAggregatorUtils.readValueAsString(section, "labelAttributeAlias"));

        config.setDateItem(StreamAggregatorUtils.readValueAsString(section, "dateItem"));
        config.setDateAttributeAlias(StreamAggregatorUtils.readValueAsString(section, "dateAttributeAlias"));
        JsonNode summaryItems = StreamAggregatorUtils.readJsonValue(section, "summaryItems");
        if (summaryItems != null && summaryItems.size() > 0) {
            Iterator<JsonNode> iterator = summaryItems.elements();
            while (iterator.hasNext()) {
                JsonNode n = iterator.next();
                config.addSummaryItem(n.asText());
            }
        }

        config.setTableName(StreamAggregatorUtils.readValueAsString(section, "tableName"));

        String readIO = StreamAggregatorUtils.readValueAsString(section, "readIOPS");
        if (readIO != null)
            config.setReadIOPs(Long.parseLong(readIO));
        String writeIO = StreamAggregatorUtils.readValueAsString(section, "writeIOPS");
        if (writeIO != null)
            config.setWriteIOPs(Long.parseLong(writeIO));

        // configure tolerance of data extraction problems
        String failOnDataExtraction = StreamAggregatorUtils.readValueAsString(section, "failOnDataExtraction");
        if (failOnDataExtraction != null)
            config.setFailOnDataExtraction(Boolean.parseBoolean(failOnDataExtraction));

        // configure whether metrics should be emitted
        String emitMetrics = StreamAggregatorUtils.readValueAsString(section, "emitMetrics");
        String metricsEmitterClassname = StreamAggregatorUtils.readValueAsString(section,
                "metricsEmitterClass");
        if (emitMetrics != null || metricsEmitterClassname != null) {
            if (metricsEmitterClassname != null) {
                config.setMetricsEmitter((Class<IMetricsEmitter>) ClassLoader.getSystemClassLoader()
                        .loadClass(metricsEmitterClassname));
            } else {
                config.setEmitMetrics(Boolean.parseBoolean(emitMetrics));
            }
        }

        // configure the data store class
        String dataStoreClass = StreamAggregatorUtils.readValueAsString(section, "IDataStore");
        if (dataStoreClass != null) {
            Class<IDataStore> dataStore = (Class<IDataStore>) ClassLoader.getSystemClassLoader()
                    .loadClass(dataStoreClass);
            config.setDataStore(dataStore);
        }

        // get the data extractor configuration, so we know what other json
        // elements to retrieve from the configuration document
        String useExtractor = null;
        try {
            useExtractor = StreamAggregatorUtils.readValueAsString(section, "dataExtractor");
            config.setDataExtractor(DataExtractor.valueOf(useExtractor));
        } catch (Exception e) {
            throw new Exception(
                    String.format("Unable to configure aggregator with Data Extractor %s", useExtractor));
        }

        switch (config.getDataExtractor()) {
        case CSV:
            configureStringCommon(section, config);
            configureCsv(section, config);
            break;
        case JSON:
            configureStringCommon(section, config);
            break;
        case OBJECT:
            configureObject(section, config);
            break;
        case REGEX:
            configureRegex(section, config);
        }

        response.add(config);
    }
    return response;
}

From source file:controllers.nwbib.Application.java

static Promise<Result> call(final String q, final String person, final String name, final String subject,
        final String id, final String publisher, final String issued, final String medium,
        final String nwbibspatial, final String nwbibsubject, final int from, final int size, String owner,
        String t, String sort, boolean showDetails, String set, String location, String word,
        String corporation, String raw) {
    final WSRequestHolder requestHolder = Lobid.request(q, person, name, subject, id, publisher, issued, medium,
            nwbibspatial, nwbibsubject, from, size, owner, t, sort, showDetails, set, location, word,
            corporation, raw);//from  w w w .  j a va  2 s. c  o  m
    return requestHolder.get().map((WSResponse response) -> {
        Long hits = 0L;
        String s = "{}";
        if (response.getStatus() == Http.Status.OK) {
            JsonNode json = response.asJson();
            hits = Lobid.getTotalResults(json);
            s = json.toString();
            if (id.isEmpty()) {
                List<JsonNode> ids = json.findValues("hbzId");
                uncache(ids.stream().map(j -> j.asText()).collect(Collectors.toList()));
                Cache.set(session("uuid") + "-lastSearch", ids.toString(), ONE_DAY);
            }
        } else {
            Logger.warn("{}: {} ({}, {})", response.getStatus(), response.getStatusText(),
                    requestHolder.getUrl(), requestHolder.getQueryParameters());
        }
        if (showDetails) {
            String json = "";
            JsonNode nodes = Json.parse(s);
            if (nodes.isArray() && nodes.size() == 2) { // first: metadata
                json = nodes.get(1).toString();
            } else {
                Logger.warn("No suitable data to show details for: {}", nodes);
            }
            return ok(details.render(CONFIG, json, id));
        }
        return ok(search.render(s, q, person, name, subject, id, publisher, issued, medium, nwbibspatial,
                nwbibsubject, from, size, hits, owner, t, sort, set, location, word, corporation, raw));
    });
}

From source file:com.heliosapm.tsdblite.json.JSON.java

public static Map<String, String> from(final JsonNode node) {
    if (node == null)
        return EMPTY_MAP;
    final int size = node.size();
    if (size == 0)
        return EMPTY_MAP;
    final Map<String, String> map = new HashMap<String, String>(node.size());
    for (Iterator<String> iter = node.fieldNames(); iter.hasNext();) {
        final String key = iter.next();
        final JsonNode v = node.get(key);
        if (v.isTextual()) {
            map.put(key, v.textValue());
        }/*from   w w w.  ja va2 s .co  m*/
    }
    return map;
}