Example usage for com.google.gson JsonObject getAsJsonPrimitive

List of usage examples for com.google.gson JsonObject getAsJsonPrimitive

Introduction

In this page you can find the example usage for com.google.gson JsonObject getAsJsonPrimitive.

Prototype

public JsonPrimitive getAsJsonPrimitive(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonPrimitive element.

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 {//from  ww w. j a  va 2  s . co 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.google.dart.server.internal.remote.utilities.RequestUtilities.java

License:Open Source License

/**
 * Return the ID of the given request./*w  ww  .  j av  a  2  s  . c  om*/
 */
public static String getId(JsonObject request) {
    return request.getAsJsonPrimitive(ID).getAsString();
}

From source file:com.google.devtools.kythe.platform.shared.KytheMetadataLoader.java

License:Open Source License

@Nullable
private static RuleXorError parseRule(JsonObject json) {
    JsonPrimitive ruleType = json.getAsJsonPrimitive(TYPE);
    if (ruleType == null) {
        return RuleXorError.create("Rule missing type.");
    }//from w w w .  j a  va 2s .com
    switch (ruleType.getAsString()) {
    case NOP:
        return null;
    case ANCHOR_DEFINES:
        Metadata.Rule rule = new Metadata.Rule();
        rule.vname = GSON.fromJson(json.getAsJsonObject(VNAME), VName.class);
        rule.begin = json.getAsJsonPrimitive(BEGIN).getAsInt();
        rule.end = json.getAsJsonPrimitive(END).getAsInt();
        String edge = json.getAsJsonPrimitive(EDGE).getAsString();
        if (edge.length() == 0) {
            return RuleXorError.create("Rule edge has zero length");
        }
        rule.reverseEdge = (edge.charAt(0) == '%');
        if (rule.reverseEdge) {
            edge = edge.substring(1);
        }
        if (edge.equals(GENERATES)) {
            rule.edgeOut = EdgeKind.GENERATES;
        } else {
            return RuleXorError.create("Unknown edge type: " + edge);
        }
        return RuleXorError.create(rule);
    default:
        return RuleXorError.create("Unknown rule type: " + ruleType.getAsString());
    }
}

From source file:com.google.devtools.kythe.platform.shared.KytheMetadataLoader.java

License:Open Source License

@Override
public Metadata parseFile(String fileName, byte[] data) {
    if (!fileName.endsWith(META_SUFFIX)) {
        return null;
    }//from w  w  w.j a v  a 2s .co  m
    JsonElement root = null;
    try (ByteArrayInputStream stream = new ByteArrayInputStream(data);
            InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
        root = PARSER.parse(reader);
    } catch (IOException ex) {
        emitWarning(ex.getMessage(), fileName);
        return null;
    }
    if (root == null || !root.isJsonObject()) {
        emitWarning("Missing root.", fileName);
        return null;
    }
    JsonObject rootObject = root.getAsJsonObject();
    JsonPrimitive rootType = rootObject.getAsJsonPrimitive(TYPE);
    if (rootType == null || !rootType.getAsString().equals(KYTHE_FORMAT_0)) {
        emitWarning("Root missing type.", fileName);
        return null;
    }
    JsonArray rules = rootObject.getAsJsonArray(META);
    if (rules == null) {
        emitWarning("Root missing meta array.", fileName);
        return null;
    }
    Metadata metadata = new Metadata();
    for (JsonElement rule : rules) {
        RuleXorError ruleXorError = parseRule(rule.getAsJsonObject());
        if (ruleXorError != null) { // skip nulls
            Metadata.Rule metadataRule = ruleXorError.rule();
            if (metadataRule != null) {
                metadata.addRule(metadataRule);
            } else {
                emitWarning(ruleXorError.error(), fileName);
            }
        }
    }
    return metadata;
}

From source file:com.google.gms.googleservices.GoogleServicesTask.java

License:Apache License

/**
 * Handle project_info/project_number for @string/gcm_defaultSenderId, and fill the res map with the read value.
 * @param rootObject the root Json object.
 * @throws IOException/*ww  w. j  a  v  a 2 s . c o  m*/
 */
private void handleProjectNumber(JsonObject rootObject, Map<String, String> resValues) throws IOException {
    JsonObject projectInfo = rootObject.getAsJsonObject("project_info");
    if (projectInfo == null) {
        throw new GradleException("Missing project_info object");
    }

    JsonPrimitive projectNumber = projectInfo.getAsJsonPrimitive("project_number");
    if (projectNumber == null) {
        throw new GradleException("Missing project_info/project_number object");
    }

    resValues.put("gcm_defaultSenderId", projectNumber.getAsString());
}

From source file:com.google.gms.googleservices.GoogleServicesTask.java

License:Apache License

/**
 * Handle a client object for analytics (@xml/global_tracker)
 * @param clientObject the client Json object.
 * @throws IOException/*from w ww  . j a v a2  s .com*/
 */
private void handleAnalytics(JsonObject clientObject, Map<String, String> resValues) throws IOException {
    JsonObject analyticsService = getServiceByName(clientObject, "analytics_service");
    if (analyticsService == null)
        return;

    JsonObject analyticsProp = analyticsService.getAsJsonObject("analytics_property");
    if (analyticsProp == null)
        return;

    JsonPrimitive trackingId = analyticsProp.getAsJsonPrimitive("tracking_id");
    if (trackingId == null)
        return;

    resValues.put("ga_trackingId", trackingId.getAsString());

    File xml = new File(intermediateDir, "xml");
    if (!xml.exists() && !xml.mkdirs()) {
        throw new GradleException("Failed to create folder: " + xml);
    }

    Files.write(getGlobalTrackerContent(trackingId.getAsString()), new File(xml, "global_tracker.xml"),
            Charsets.UTF_8);
}

From source file:com.google.gms.googleservices.GoogleServicesTask.java

License:Apache License

private static void findStringByName(JsonObject jsonObject, String stringName, Map<String, String> resValues) {
    JsonPrimitive id = jsonObject.getAsJsonPrimitive(stringName);
    if (id != null) {
        resValues.put(stringName, id.getAsString());
    }/*from  w w  w . j a va 2s . co m*/
}

From source file:com.google.gms.googleservices.GoogleServicesTask.java

License:Apache License

/**
 * find an item in the "client" array that match the package name of the app
 * @param jsonObject the root json object.
 * @return a JsonObject representing the client entry or null if no match is found.
 *//*from w w w. j  a  va 2s  .  com*/
private JsonObject getClientForPackageName(JsonObject jsonObject) {
    JsonArray array = jsonObject.getAsJsonArray("client");
    if (array != null) {
        final int count = array.size();
        for (int i = 0; i < count; i++) {
            JsonElement clientElement = array.get(i);
            if (clientElement == null || !clientElement.isJsonObject()) {
                continue;
            }

            JsonObject clientObject = clientElement.getAsJsonObject();

            JsonObject clientInfo = clientObject.getAsJsonObject("client_info");
            if (clientInfo == null)
                continue;

            JsonObject androidClientInfo = clientInfo.getAsJsonObject("android_client_info");
            if (androidClientInfo == null)
                continue;

            JsonPrimitive clientPackageName = androidClientInfo.getAsJsonPrimitive("package_name");
            if (clientPackageName == null)
                continue;

            if (packageName.equals(clientPackageName.getAsString())) {
                return clientObject;
            }
        }
    }

    return null;
}

From source file:com.google.gms.googleservices.GoogleServicesTask.java

License:Apache License

/**
 * Finds a service by name in the client object. Returns null if the service is not found
 * or if the service is disabled.//from  w  ww.  ja  va 2s. co  m
 *
 * @param clientObject the json object that represents the client.
 * @param serviceName the service name
 * @return the service if found.
 */
private JsonObject getServiceByName(JsonObject clientObject, String serviceName) {
    JsonObject services = clientObject.getAsJsonObject("services");
    if (services == null)
        return null;

    JsonObject service = services.getAsJsonObject(serviceName);
    if (service == null)
        return null;

    JsonPrimitive status = service.getAsJsonPrimitive("status");
    if (status == null)
        return null;

    String statusStr = status.getAsString();

    if (STATUS_DISABLED.equals(statusStr))
        return null;
    if (!STATUS_ENABLED.equals(statusStr)) {
        getLogger().warn(String.format("Status with value '%1$s' for service '%2$s' is unknown", statusStr,
                serviceName));
        return null;
    }

    return service;
}

From source file:com.google.iosched.model.DataExtractor.java

License:Open Source License

private void setRelatedVideos(JsonObject origin, JsonObject dest) {
    JsonArray related = getAsArray(origin, VendorAPISource.Topics.related);
    if (related == null) {
        return;/*ww  w  .ja v  a  2  s .  c o m*/
    }
    for (JsonElement el : related) {
        if (!el.isJsonObject()) {
            continue;
        }
        JsonObject obj = el.getAsJsonObject();
        if (!obj.has("name") || !obj.has("values")) {
            continue;
        }

        if (InputJsonKeys.VendorAPISource.Topics.RELATED_NAME_VIDEO
                .equals(obj.getAsJsonPrimitive("name").getAsString())) {

            JsonElement values = obj.get("values");
            if (!values.isJsonArray()) {
                continue;
            }

            // As per the data specification, related content is formatted as
            // "video1 title1\nvideo2 title2\n..."
            StringBuilder relatedContentStr = new StringBuilder();
            for (JsonElement value : values.getAsJsonArray()) {
                String relatedSessionId = value.getAsString();
                JsonObject relatedVideo = videoSessionsById.get(relatedSessionId);
                if (relatedVideo != null) {
                    JsonElement vid = get(relatedVideo, OutputJsonKeys.VideoLibrary.vid);
                    JsonElement title = get(relatedVideo, OutputJsonKeys.VideoLibrary.title);
                    if (vid != null && title != null) {
                        relatedContentStr.append(vid.getAsString()).append(" ").append(title.getAsString())
                                .append("\n");
                    }
                }
            }
            set(new JsonPrimitive(relatedContentStr.toString()), dest, OutputJsonKeys.Sessions.relatedContent);
        }
    }
}