Example usage for com.google.gson JsonArray size

List of usage examples for com.google.gson JsonArray size

Introduction

In this page you can find the example usage for com.google.gson JsonArray size.

Prototype

public int size() 

Source Link

Document

Returns the number of elements in the array.

Usage

From source file:com.github.jramos.snowplow.operators.MobileContextExtractionOp.java

License:Apache License

@Override
public SnowplowEventModel apply(SnowplowEventModel event) {
    String context = event.getContexts();
    try {/*  w  w w.  j  av  a 2s . c o  m*/
        String platform = event.getPlatform();
        if (platform.equals(SnowplowPlatform.Mobile.toString())) {

            // minimal tablet vs mobile detection
            if (isTablet(event.getUseragent())) {
                event.setDvce_type(SnowplowDeviceType.Tablet.toString());
                event.setDvce_ismobile(Boolean.FALSE);
            } else {
                event.setDvce_type(SnowplowDeviceType.Mobile.toString());
                event.setDvce_ismobile(Boolean.TRUE);
            }

            JsonObject rootObj = parser.parse(context).getAsJsonObject();
            if (rootObj.has(JSON_DATA)) {
                JsonArray dataArray = rootObj.getAsJsonArray(JSON_DATA);

                // find the correct object by matching on the schema
                JsonObject mobileContextObject = null;
                for (int i = 0; i < dataArray.size(); i++) {
                    JsonElement element = dataArray.get(i);
                    if (element.isJsonObject()) {
                        JsonObject jsonObject = element.getAsJsonObject();
                        if (jsonObject.has(JSON_SCHEMA)) {
                            String schema = jsonObject.getAsJsonPrimitive(JSON_SCHEMA).getAsString();
                            if (schema.contains(SCHEMA_TAG)) {
                                mobileContextObject = jsonObject;
                                break;
                            }
                        }
                    }
                }

                // parse out the mobile fields we want
                if (mobileContextObject != null && mobileContextObject.has(JSON_DATA)) {
                    JsonObject dataObject = mobileContextObject.getAsJsonObject(JSON_DATA);

                    if (dataObject.has(JSON_OPEN_IDFA)) {
                        // use as cross device user id - i.e network user id
                        String openIDFA = dataObject.getAsJsonPrimitive(JSON_OPEN_IDFA).getAsString();
                        event.setNetwork_userid(openIDFA);
                    }

                    String deviceManufacturer = dataObject.getAsJsonPrimitive(JSON_DEVICE_MANUFACTURER)
                            .getAsString();
                    event.setOs_manufacturer(deviceManufacturer);

                    String osType = dataObject.getAsJsonPrimitive(JSON_OS_TYPE).getAsString();
                    event.setOs_family(osType);

                    String osVersion = dataObject.getAsJsonPrimitive(JSON_OS_VERSION).getAsString();
                    String deviceModel = dataObject.getAsJsonPrimitive(JSON_DEVICE_MODEL).getAsString();

                    osNameBuffer.setLength(0);
                    osNameBuffer.append(osType).append(" ").append(osVersion);
                    if (deviceModel != null && deviceModel.trim().length() > 0) {
                        osNameBuffer.append(" (").append(deviceModel.trim()).append(")");
                    }
                    event.setOs_name(osNameBuffer.toString());
                }
            }
        }
    } catch (Exception e) {
        LOG.error("Exception applying operator to mobile context " + context, e);
    }
    return event;
}

From source file:com.github.messenger4j.profile.GreetingsProfileResponse.java

License:Apache License

private static boolean isJsonArrayEmpty(JsonArray jsonArray) {
    return jsonArray == null || jsonArray.size() == 0;
}

From source file:com.github.rustdt.tooling.RustJsonMessageParser.java

License:Open Source License

protected ArrayList2<String> parseNotes(JsonElement children) throws CommonException {
    ArrayList2<String> notes = new ArrayList2<>();
    if (children == null || !children.isJsonArray()) {
        return notes;
    }/*from  w  ww.j a  v a  2  s.c  o m*/
    JsonArray childrenArray = children.getAsJsonArray();
    if (childrenArray.size() == 0) {
        return notes;
    }
    for (JsonElement child : childrenArray) {
        if (child.isJsonObject()) {
            String childMessageString = helper.getOptionalString(child.getAsJsonObject(), "message");
            if (childMessageString != null && !childMessageString.isEmpty()) {
                notes.add(childMessageString);
            }
        }
    }
    return notes;
}

From source file:com.github.sommeri.sourcemap.SourceMapConsumerV3.java

License:Apache License

/**
 * @param sourceMapRoot/* ww w .jav a 2s.  c o  m*/
 * @throws SourceMapParseException
 */
private void parseMetaMap(JsonObject sourceMapRoot, SourceMapSupplier sectionSupplier)
        throws SourceMapParseException {
    if (sectionSupplier == null) {
        sectionSupplier = new DefaultSourceMapSupplier();
    }

    try {
        // Check basic assertions about the format.
        int version = sourceMapRoot.get("version").getAsInt();
        if (version != 3) {
            throw new SourceMapParseException("Unknown version: " + version);
        }

        String file = sourceMapRoot.get("file").getAsString();
        if (file.isEmpty()) {
            throw new SourceMapParseException("File entry is missing or empty");
        }

        if (sourceMapRoot.has("lineCount") || sourceMapRoot.has("mappings") || sourceMapRoot.has("sources")
                || sourceMapRoot.has("names")) {
            throw new SourceMapParseException("Invalid map format");
        }

        SourceMapGeneratorV3 generator = new SourceMapGeneratorV3();
        JsonArray sections = sourceMapRoot.get("sections").getAsJsonArray();
        for (int i = 0, count = sections.size(); i < count; i++) {
            JsonObject section = sections.get(i).getAsJsonObject();
            if (section.has("map") && section.has("url")) {
                throw new SourceMapParseException(
                        "Invalid map format: section may not have both 'map' and 'url'");
            }
            JsonObject offset = section.get("offset").getAsJsonObject();
            int line = offset.get("line").getAsInt();
            int column = offset.get("column").getAsInt();
            String mapSectionContents;
            if (section.has("url")) {
                String url = section.get("url").getAsString();
                mapSectionContents = sectionSupplier.getSourceMap(url);
                if (mapSectionContents == null) {
                    throw new SourceMapParseException("Unable to retrieve: " + url);
                }
            } else if (section.has("map")) {
                mapSectionContents = section.get("map").getAsString();
            } else {
                throw new SourceMapParseException(
                        "Invalid map format: section must have either 'map' or 'url'");
            }
            generator.mergeMapSection(line, column, mapSectionContents);
        }

        StringBuilder sb = new StringBuilder();
        try {
            generator.appendTo(sb, file);
        } catch (IOException e) {
            // Can't happen.
            throw new RuntimeException(e);
        }

        parse(sb.toString());
    } catch (IOException ex) {
        throw new SourceMapParseException("IO exception: " + ex);
    }
}

From source file:com.github.sommeri.sourcemap.SourceMapConsumerV3.java

License:Apache License

private String[] getJavaStringArray(JsonArray array) {
    int len = array.size();
    String[] result = new String[len];
    for (int i = 0; i < len; i++) {
        result[i] = array.get(i).isJsonNull() ? null : array.get(i).getAsString();
    }//from w w  w  . j  ava2 s . c  o m
    return result;
}

From source file:com.github.tarsys.android.orm.dataobjects.JSONDataSource.java

public JSONDataSource(JsonArray jArray) {
    if (jArray != null && jArray.size() > 0) {
        // cogemos el primer objeto del array, para sacarle sus claves...
        try {//from w w w. j a v  a  2s. c o m
            JsonObject obj = jArray.get(0).getAsJsonObject();
            if (obj != null) {
                for (Map.Entry<String, JsonElement> e : obj.entrySet())
                    this.columns.add(e.getKey());
            }
            this.jsonData = jArray.toString();
        } catch (Exception ex) {
        }
    }
}

From source file:com.github.thesmartenergy.sparql.generate.jena.function.library.FN_CBOR.java

License:Apache License

/**
 *
 * @param cbor a RDF Literal with datatype URI
 * {@code <urn:iana:mime:application/cbor>} or {@code xsd:string}
 * @param jsonpath a RDF Literal with datatype {@code xsd:string}
 * @return a RDF Literal with datatype URI
 * {@code <urn:iana:mime:application/json>}
 *///from w ww.  j av  a2s  . c o m
@Override
public NodeValue exec(NodeValue cbor, NodeValue jsonpath) {

    if (cbor.getDatatypeURI() == null && datatypeUri == null
            || cbor.getDatatypeURI() != null && !cbor.getDatatypeURI().equals(datatypeUri)
                    && !cbor.getDatatypeURI().equals("http://www.w3.org/2001/XMLSchema#string")) {
        LOG.warn("The URI of NodeValue1 MUST be <" + datatypeUri + ">"
                + "or <http://www.w3.org/2001/XMLSchema#string>." + " Returning null.");
    }

    String json = new String(Base64.getDecoder().decode(cbor.asNode().getLiteralLexicalForm().getBytes()));
    try {
        Object value = JsonPath.parse(json).limit(1).read(jsonpath.getString());

        if (value instanceof String) {
            return new NodeValueString((String) value);
        } else if (value instanceof Float) {
            return new NodeValueFloat((Float) value);
        } else if (value instanceof Boolean) {
            return new NodeValueBoolean((Boolean) value);
        } else if (value instanceof Integer) {
            return new NodeValueInteger((Integer) value);
        } else if (value instanceof Double) {
            return new NodeValueDouble((Double) value);
        } else if (value instanceof BigDecimal) {
            return new NodeValueDecimal((BigDecimal) value);
        } else {
            String strValue = String.valueOf(value);

            JsonParser parser = new JsonParser();
            JsonElement valElement = parser.parse(strValue);
            JsonArray list = valElement.getAsJsonArray();

            if (list.size() == 1) {
                String jsonstring = list.get(0).getAsString();
                Node node = NodeFactory.createLiteral(jsonstring);
                NodeValue nodeValue = new NodeValueNode(node);
                return nodeValue;

            } else {
                return new NodeValueString(String.valueOf(value));
            }
        }
    } catch (Exception e) {
        throw new ExprEvalException("FunctionBase: no evaluation", e);
    }
}

From source file:com.github.thesmartenergy.sparql.generate.jena.function.library.FN_JSONPath.java

License:Apache License

/**
 *
 * @param json a RDF Literal with datatype URI
 * {@code <urn:iana:mime:application/json>} or {@code xsd:string}
 * @param jsonpath a RDF Literal with datatype {@code xsd:string}
 * @return a RDF Literal with datatype being the type of the object
 * extracted from the JSON document//from   www .  j  ava  2s. com
 */
@Override
public NodeValue exec(NodeValue json, NodeValue jsonpath) {
    if (json.getDatatypeURI() == null && datatypeUri == null
            || json.getDatatypeURI() != null && !json.getDatatypeURI().equals(datatypeUri)
                    && !json.getDatatypeURI().equals("http://www.w3.org/2001/XMLSchema#string")) {
        LOG.warn("The URI of NodeValue1 MUST be <" + datatypeUri + ">"
                + "or <http://www.w3.org/2001/XMLSchema#string>." + " Returning null.");
    }

    try {
        Object value = JsonPath.parse(json.asNode().getLiteralLexicalForm()).limit(1)
                .read(jsonpath.getString());

        if (value instanceof String) {
            return new NodeValueString((String) value);
        } else if (value instanceof Float) {
            return new NodeValueFloat((Float) value);
        } else if (value instanceof Boolean) {
            return new NodeValueBoolean((Boolean) value);
        } else if (value instanceof Integer) {
            return new NodeValueInteger((Integer) value);
        } else if (value instanceof Long) {
            return new NodeValueInteger((Long) value);
        } else if (value instanceof Double) {
            return new NodeValueDouble((Double) value);
        } else if (value instanceof BigDecimal) {
            return new NodeValueDecimal((BigDecimal) value);
        } else {
            String strValue = String.valueOf(value);

            JsonParser parser = new JsonParser();
            JsonElement valElement = parser.parse(strValue);
            JsonArray list = valElement.getAsJsonArray();

            if (list.size() == 1) {
                String jsonstring = list.get(0).getAsString();
                Node node = NodeFactory.createLiteral(jsonstring);
                NodeValue nodeValue = new NodeValueNode(node);
                return nodeValue;

            } else {
                return new NodeValueString(String.valueOf(value));
            }
        }
    } catch (Exception e) {
        throw new ExprEvalException("FunctionBase: no evaluation", e);
    }
}

From source file:com.github.zhanhb.ishadowsocks.Application.java

License:Open Source License

public static void main(String[] args) throws IOException {
    try (WebClient webClient = new WebClient(BrowserVersion.CHROME)) {
        WebClientOptions options = webClient.getOptions();
        options.setCssEnabled(false);//from  w  w w .  ja  va  2  s.  c  om
        options.setDoNotTrackEnabled(true);
        options.setDownloadImages(false);
        options.setGeolocationEnabled(false);
        options.setJavaScriptEnabled(false);
        options.setThrowExceptionOnFailingStatusCode(false);
        options.setThrowExceptionOnScriptError(false);

        HtmlPage page = webClient.getPage("https://xxx.ishadowx.org");

        Stream<JsonObject> parsed = page.querySelectorAll("#portfolio .portfolio-item").stream()
                .map(node -> node.getTextContent().trim()).map(Server::newServer).filter(Objects::nonNull)
                .map(Server::toJsonObject);

        if (args.length > 0) {
            Path path = Paths.get(args[0]);
            GuiConfigs guiConfigs = GuiConfigs.parse(path);
            JsonArray configs = guiConfigs.getConfigs();
            Collection<JsonObject> servers = Stream.concat(StreamSupport
                    .stream(Spliterators.spliterator(configs.iterator(), configs.size(), Spliterator.ORDERED),
                            false)
                    .map(JsonElement::getAsJsonObject), parsed).collect(Collectors.toMap(jo -> {
                        return jo.get("server").getAsString() + ":" + jo.get("server_port").getAsString();
                    }, identity(), (a, b) -> b, LinkedHashMap::new)).values();

            guiConfigs.setConfigs(servers);
            guiConfigs.writeTo(path);
        } else {
            parsed.forEach(System.out::println);
        }
    }
}

From source file:com.goforer.beatery.ui.fragment.EateryInfoFragment.java

License:Apache License

@Subscribe(threadMode = ThreadMode.ASYNC)
public void onEvent(EateryInfoEvent event) {
    if (event.getEateryId() == mItems.get(mItemPosition).getId()) {
        if (event.getResponseClient() != null && event.getResponseClient().isSuccessful()) {
            JsonArray jsonArray = event.getResponseClient().getResponseEntity().getAsJsonArray();
            if (jsonArray.size() > 0) {
                JsonElement element = jsonArray.get(0);
                mEateryInfo = EateryInfo.gson().fromJson(element, EateryInfo.class);
                setEateryInfoChanged(true);
                requestComment(false);// www.j a v  a 2  s. c o  m
                EventBus.getDefault().post(new EateryInfoUpdatedAction(mEateryInfo));
            } else {
                infoFetchFail();
            }
        } else {
            infoFetchFail();
        }

        notifyRefreshFinished();
    }
}