Example usage for com.google.gson JsonObject getAsJsonObject

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

Introduction

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

Prototype

public JsonObject getAsJsonObject(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonObject.

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 w  ww .j a  v  a 2  s .  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.nyrkovalex.deploy.me.parsing.Parser.java

License:Open Source License

@Override
public Application parse(String name, JsonElement element) {
    JsonObject jsonObject = element.getAsJsonObject();
    Set<Fileset> filesets = filesetSetParser.parse(jsonObject.getAsJsonObject("filesets"));
    Set<Server> servers = serverSetParser.parse(jsonObject.getAsJsonObject("servers"), filesets);
    return new Application(name, servers);
}

From source file:com.google.api.ads.adwords.awalerting.processor.AlertProcessor.java

License:Open Source License

/**
 * Process one alert for the given account IDs under the manager account.
 *
 * @param clientCustomerIds the client customer IDs
 * @param protoSession the prototype adwords session used for downloading reports
 * @param alertConfig the JSON config of the alert
 * @param count the sequence number of current alert
 *//* w  w  w.j a  v  a 2 s  .c  o  m*/
protected void processAlert(Set<Long> clientCustomerIds, ImmutableAdWordsSession protoSession,
        JsonObject alertConfig, int count) throws AlertConfigLoadException, AlertProcessingException {
    String alertName = alertConfig.get(ConfigTags.ALERT_NAME).getAsString();
    LOGGER.info("*** Generating alert #{} (name: \"{}\") for {} accounts ***", count, alertName,
            clientCustomerIds.size());

    JsonObject downloaderConfig = alertConfig.getAsJsonObject(ConfigTags.REPORT_DOWNLOADER);
    JsonArray rulesConfig = alertConfig.getAsJsonArray(ConfigTags.RULES); // optional
    String alertMessage = alertConfig.get(ConfigTags.ALERT_MESSAGE).getAsString();
    JsonArray actionsConfig = alertConfig.getAsJsonArray(ConfigTags.ACTIONS);

    // Generate AWQL report query and download report data for all accounts under manager account.
    List<ReportData> reports = downloadReports(protoSession, clientCustomerIds, downloaderConfig);
    printReports(reports, "*** Downloaded report data:");

    // Process the downloaded reports
    processReports(reports, rulesConfig, alertMessage, actionsConfig);
}

From source file:com.google.api.ads.adwords.awalerting.sampleimpl.downloader.AwqlReportDownloader.java

License:Open Source License

public AwqlReportDownloader(JsonObject config) {
    JsonObject reportQueryConfig = config.getAsJsonObject(REPORT_QUERY_TAG);
    this.reportQuery = new AwqlReportQuery(reportQueryConfig);
}

From source file:com.google.dart.server.internal.remote.processor.NotificationSearchResultsProcessor.java

License:Open Source License

@Override
public void process(JsonObject response) throws Exception {
    JsonObject params = response.getAsJsonObject("params");
    getListener().computedSearchResults(params.get("id").getAsString(),
            SearchResult.fromJsonArray(params.getAsJsonArray("results")), params.get("isLast").getAsBoolean());
}

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 ww  w.  ja va  2s .  c o m*/
    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.gdt.googleapi.core.ApiDirectoryListingJsonCodec.java

License:Open Source License

protected void populateApiInfoFromJson(URL baseURL, JsonObject object, MutableApiInfo info) {
    if (object.has("name")) {
        info.setName(object.get("name").getAsString());
    }/*w  ww  .  j av  a 2s .  co  m*/
    if (object.has("version")) {
        info.setVersion(object.get("version").getAsString());
    }
    if (object.has("title")) {
        info.setDisplayName(object.get("title").getAsString());
    }
    if (object.has("publisher")) {
        info.setPublisher(object.get("publisher").getAsString());
    }
    if (object.has("description")) {
        info.setDescription(object.get("description").getAsString());
    }
    if (object.has("icons")) {
        JsonObject iconLinks = object.getAsJsonObject("icons");
        Set<Entry<String, JsonElement>> iconLinksEntrySet = iconLinks.entrySet();
        for (Entry<String, JsonElement> entry : iconLinksEntrySet) {
            try {
                info.putIconLink(entry.getKey(), new URL(baseURL, entry.getValue().getAsString()));
            } catch (MalformedURLException e) {
                // TODO Add logging warn
            }
        }
    }
    if (object.has("labels")) {
        JsonArray labelsJsonArray = object.getAsJsonArray("labels");

        for (JsonElement labelElement : labelsJsonArray) {
            info.addLabel(labelElement.getAsString());
        }
    }
    if (object.has("releaseDate")) {
        try {
            LocalDate date = new LocalDate(object.get("releaseDate").getAsString());
            info.setReleaseDate(date);
        } catch (IllegalArgumentException e) {
            throw new JsonParseException(e);
        }
    }
    if (object.has("releaseNotesLink")) {
        try {
            info.setReleaseNotesLink(new URL(baseURL, object.get("releaseNotesLink").getAsString()));
        } catch (MalformedURLException e) {
            // TODO Add logging warn
        }
    }
    if (object.has("ranking")) {
        info.setRanking(object.get("ranking").getAsInt());
    }
    if (object.has("discoveryLink")) {
        try {
            info.setDiscoveryLink(new URL(baseURL, object.get("discoveryLink").getAsString()));
        } catch (MalformedURLException e) {
            // TODO Add logging warn
        }
    }
    if (object.has("documentationLink")) {
        try {
            info.setDocumentationLink(new URL(baseURL, object.get("documentationLink").getAsString()));
        } catch (MalformedURLException e) {
            // TODO Add logging warn
        }
    }
    if (object.has("downloadLink")) {
        try {
            info.setDownloadLink(new URL(baseURL, object.get("downloadLink").getAsString()));
        } catch (MalformedURLException e) {
            // TODO Add logging warn
        }
    }
    if (object.has("tosLink")) {
        try {
            info.setTosLink(new URL(baseURL, object.get("tosLink").getAsString()));
        } catch (MalformedURLException e) {
            // TODO Add logging warn
        }
    }
}

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// w  w  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 w w .ja  v a  2 s.  c  om*/
 */
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

/**
 * 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  av a  2 s .  c  o m*/
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;
}