Example usage for com.google.gson JsonObject getAsJsonArray

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

Introduction

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

Prototype

public JsonArray getAsJsonArray(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonArray.

Usage

From source file:com.fooock.shodan.model.exploit.ExploitDeserializer.java

License:Open Source License

private Exploit parseJsonExploit(JsonElement json) {
    Exploit exploit = new Exploit();

    JsonObject jsonObject = json.getAsJsonObject();

    String id = jsonObject.get("_id").getAsString();
    String desc = jsonObject.get("description").getAsString();
    String source = jsonObject.get("source").getAsString();

    JsonElement jsonAuthor = jsonObject.get("author");
    if (jsonAuthor != null && !jsonAuthor.isJsonNull()) {
        if (jsonAuthor.isJsonPrimitive()) {
            String author = jsonAuthor.getAsString();
            exploit.setAuthor(author);//w  w  w .j a va  2  s  .  c o m
        } else {
            JsonArray array = jsonAuthor.getAsJsonArray();
            if (array != null) {
                String resAuthors = "";
                for (JsonElement element : array) {
                    resAuthors += ", " + element.getAsString();
                }
                exploit.setAuthor(resAuthors);
            }
        }
    }

    JsonElement jsonCode = jsonObject.get("code");
    if (jsonCode != null && !jsonCode.isJsonNull()) {
        String code = jsonCode.getAsString();
        exploit.setCode(code);
    }

    JsonElement jsonType = jsonObject.get("type");
    if (jsonType != null && !jsonType.isJsonNull()) {
        String type = jsonType.getAsString();
        exploit.setType(type);
    }

    JsonElement jsonVersion = jsonObject.get("version");
    if (jsonVersion != null && !jsonVersion.isJsonNull()) {
        String version = jsonVersion.getAsString();
        exploit.setVersion(version);
    }

    JsonElement jsonPrivileged = jsonObject.get("privileged");
    if (jsonPrivileged != null && !jsonPrivileged.isJsonNull()) {
        boolean privileged = jsonPrivileged.getAsBoolean();
        exploit.setPrivileged(privileged);
    }

    JsonElement jsonPort = jsonObject.get("port");
    if (jsonPort != null && !jsonPort.isJsonNull()) {
        int port = jsonPort.getAsInt();
        exploit.setPort(port);
    }

    JsonArray jsonBid = jsonObject.getAsJsonArray("bid");
    if (jsonBid != null) {
        String[] bid = new String[jsonBid.size()];
        for (int i = 0; i < jsonBid.size(); i++) {
            bid[i] = jsonBid.get(i).getAsString();
        }
        exploit.setBid(bid);
    }

    JsonArray jsonCve = jsonObject.getAsJsonArray("cve");
    if (jsonCve != null) {
        String[] cve = new String[jsonCve.size()];
        for (int i = 0; i < jsonCve.size(); i++) {
            cve[i] = jsonCve.get(i).getAsString();
        }
        exploit.setCve(cve);
    }

    JsonArray jsonMsb = jsonObject.getAsJsonArray("msb");
    if (jsonMsb != null) {
        String[] msb = new String[jsonMsb.size()];
        for (int i = 0; i < jsonMsb.size(); i++) {
            msb[i] = jsonMsb.get(i).getAsString();
        }
        exploit.setMsb(msb);
    }

    JsonArray jsonOsvdb = jsonObject.getAsJsonArray("osvdb");
    if (jsonOsvdb != null) {
        String[] osvdb = new String[jsonOsvdb.size()];
        for (int i = 0; i < jsonOsvdb.size(); i++) {
            osvdb[i] = jsonOsvdb.get(i).getAsString();
        }
        exploit.setOsvdb(osvdb);
    }

    try {
        JsonArray jsonPlatform = jsonObject.getAsJsonArray("platform");
        if (jsonPlatform != null && jsonPlatform.isJsonArray()) {
            String[] platform = new String[jsonPlatform.size()];
            for (int i = 0; i < jsonPlatform.size(); i++) {
                platform[i] = jsonPlatform.get(i).getAsString();
            }
            exploit.setPlatform(platform);
        }
    } catch (ClassCastException err) {
        JsonElement platPrimitive = jsonObject.get("platform");
        if (platPrimitive != null && !platPrimitive.isJsonNull()) {
            exploit.setPlatform(new String[] { platPrimitive.getAsString() });
        }
    }

    exploit.setId(id);
    exploit.setDescription(desc);
    exploit.setSource(source);

    return exploit;
}

From source file:com.github.benchdoos.weblocopener.updater.update.Updater.java

License:Apache License

public void formAppVersionFromJson(JsonObject root) {
    log.debug("Parsing json to app version");
    final String version = "tag_name";
    final String browser_download_url = "browser_download_url";
    final String assets = "assets";
    final String name = "name";
    final String size = "size";
    final String info = "body";

    appVersion.setVersion(root.getAsJsonObject().get(version).getAsString());
    appVersion.setUpdateInfo(root.getAsJsonObject().get(info).getAsString());
    appVersion.setUpdateTitle(root.getAsJsonObject().get(name).getAsString());

    JsonArray asserts = root.getAsJsonArray(assets);
    for (JsonElement assert_ : asserts) {
        JsonObject userObject = assert_.getAsJsonObject();
        if (userObject.get(name).getAsString().equals(WINDOWS_SETUP_DEFAULT_NAME)) {
            appVersion.setDownloadUrl(userObject.get(browser_download_url).getAsString());
            appVersion.setSize(userObject.get(size).getAsLong());
        }/*  www.  j  a v  a2  s . c  o m*/
    }
}

From source file:com.github.cc007.headsweeper.controller.HeadSweeperController.java

License:Open Source License

public HeadSweeperController(JsonObject input, HeadSweeper plugin) {
    this.sweeperGames = new ArrayList<>();
    JsonArray sweeperGamesJSON = input.getAsJsonArray("sweeperGames");
    if (sweeperGamesJSON != null) {
        for (int i = 0; i < sweeperGamesJSON.size(); i++) {
            HeadSweeperGame sweeperGame = new HeadSweeperGame(sweeperGamesJSON.get(i).getAsJsonObject(),
                    plugin);/*from   w w w  . ja  v  a2 s .  c  om*/
            sweeperGames.add(sweeperGame);
        }
    }
    this.plugin = plugin;
}

From source file:com.github.consiliens.harv.gson.IRequestLogRecordDeserializer.java

License:Open Source License

/**
 * Params name and value are stored as strings. Params are backed by a
 * HashMap so order is not guaranteed. Duplicate keys are not allowed in a
 * HashMap.// w ww .  j a  va 2  s.c o m
 **/
public static void setParamsFromJson(final HttpParams httpParams, final JsonObject obj) {
    final JsonArray requestHttpParamsJson = obj.getAsJsonArray(R.params);

    for (int a = 0; a < requestHttpParamsJson.size(); a++) {
        final JsonArray nvPair = requestHttpParamsJson.get(a).getAsJsonArray();

        httpParams.setParameter(nvPair.get(0).getAsString(), nvPair.get(1).getAsString());
    }
}

From source file:com.github.consiliens.harv.gson.IRequestLogRecordDeserializer.java

License:Open Source License

@Override
public IRequestLogRecord deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    // Follow same order as serializer for sanity.
    IRequestLogRecord record = null;//  w  w  w. j  a v  a  2  s  .co  m

    final JsonObject recordJson = json.getAsJsonObject();

    final long requestId = recordJson.get(R.requestId).getAsLong();
    final long requestTimestamp = recordJson.get(R.timestamp).getAsLong();
    final long requestMilliseconds = recordJson.get(R.requestMilliseconds).getAsLong();

    // HttpHost
    JsonObject hostJson = recordJson.getAsJsonObject(R.httpHost);

    final String hostName = hostJson.get(R.hostName).getAsString();
    final int port = hostJson.get(R.port).getAsInt();
    final String schemeName = hostJson.get(R.schemeName).getAsString();

    final HttpHost host = new HttpHost(hostName, port, schemeName);

    // Request
    final JsonObject requestJson = recordJson.getAsJsonObject(R.request);

    String requestEntityString = "";
    HttpRequest httpRequest = null;
    if (requestJson.has(R.entity)) {
        requestEntityString = requestJson.get(R.entity).getAsString();
    }

    // Must parse headers here.
    final Header[] requestHeaders = getHeaders(requestJson.getAsJsonArray(R.allHeaders));

    // Request params
    final HttpParams requestHttpParams = new BasicHttpParams();
    setParamsFromJson(requestHttpParams, requestJson);

    // Request RequestLine
    final JsonObject requestLineJson = requestJson.getAsJsonObject(R.requestLine);

    // Request RequestLine Protocol
    final ProtocolVersion requestProtocol = getProtocolVersion(
            requestLineJson.getAsJsonObject(R.protocolVersion));

    final String method = requestLineJson.get(R.method).getAsString();
    final String uri = requestLineJson.get(R.uri).getAsString();

    // Request is finished. Build the HttpRequest Object.
    if (requestEntityString.isEmpty()) {
        // non-entity request
        httpRequest = new BasicHttpRequest(method, uri, requestProtocol);
    } else {
        httpRequest = new BasicHttpEntityEnclosingRequest(method, uri, requestProtocol);

        ByteArrayEntity requestEntity = null;
        if (entitiesExternalPath.isEmpty()) {
            // From internal string.
            try {
                requestEntity = new ByteArrayEntity(requestEntityString.getBytes(UTF8));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            // From file.
            final String fileName = getEntityFileName(requestEntityString);
            try {
                requestEntity = new ByteArrayEntity(
                        Files.toByteArray(new File(entitiesExternalPath, fileName)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        ((BasicHttpEntityEnclosingRequest) httpRequest).setEntity(requestEntity);
    }

    httpRequest.setHeaders(requestHeaders);
    httpRequest.setParams(requestHttpParams);

    // HttpResponse
    final JsonObject responseJson = recordJson.getAsJsonObject(R.response);
    final Header[] responseHeaders = getHeaders(requestJson.getAsJsonArray(R.allHeaders));

    // Response Entity
    String responseEntityString = "";
    if (responseJson.has(R.entity)) {
        responseEntityString = responseJson.get(R.entity).getAsString();
    }

    // Locale
    JsonObject localeJson = responseJson.getAsJsonObject(R.locale);
    final String language = localeJson.get(R.language).getAsString();
    final String country = localeJson.get(R.country).getAsString();
    String variant = "";

    // Variant might not exist.
    if (localeJson.has(R.variant))
        variant = localeJson.get(R.variant).getAsString();

    Locale locale = new Locale(language, country, variant);

    // Response params
    final HttpParams responseHttpParams = new BasicHttpParams();
    setParamsFromJson(responseHttpParams, responseJson);

    // StatusLine
    JsonObject statusLineJson = responseJson.getAsJsonObject(R.statusLine);

    // StatusLine Protocol Version
    final ProtocolVersion responseProtocol = getProtocolVersion(
            statusLineJson.getAsJsonObject(R.protocolVersion));
    final int statusCode = statusLineJson.get(R.statusCode).getAsInt();
    final String reasonPhrase = statusLineJson.get(R.reasonPhrase).getAsString();

    StatusLine responseStatus = new BasicStatusLine(responseProtocol, statusCode, reasonPhrase);

    // Default to using EnglishReasonPhraseCatalog
    final HttpResponse httpResponse = new BasicHttpResponse(responseStatus, EnglishReasonPhraseCatalog.INSTANCE,
            locale);

    httpResponse.setHeaders(responseHeaders);
    httpResponse.setParams(responseHttpParams);

    // Ensure entity exists before processing.
    if (!requestEntityString.isEmpty()) {
        ByteArrayEntity responseEntity = null;

        try {
            if (entitiesExternalPath.isEmpty()) {
                // From internal string.
                responseEntity = new ByteArrayEntity(responseEntityString.getBytes(UTF8));
            } else {
                // From file.
                final String fileName = getEntityFileName(requestEntityString);
                responseEntity = new ByteArrayEntity(
                        Files.toByteArray(new File(entitiesExternalPath, fileName)));
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        httpResponse.setEntity(responseEntity);
    }

    // RequestLogRecord's constructors are package private so use
    // reflection.
    try {
        final Constructor<RequestLogRecord> construct = RequestLogRecord.class.getDeclaredConstructor(
                long.class, HttpRequest.class, HttpResponse.class, HttpHost.class, long.class);
        construct.setAccessible(true);
        record = (RequestLogRecord) construct.newInstance(requestId, httpRequest, httpResponse, host,
                requestMilliseconds);

        // There's no get or set timestamp so use reflection.
        final Field timestampField = RequestLogRecord.class.getDeclaredField(R.timestamp);
        timestampField.setAccessible(true);
        timestampField.set(record, requestTimestamp);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return record;
}

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.ja  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.messenger4j.profile.GreetingsProfileResponse.java

License:Apache License

private static JsonArray getArray(JsonObject jsonObject, String label) {
    return jsonObject.getAsJsonArray(label);
}

From source file:com.github.wakhub.monodict.activity.FlashcardActivity.java

License:Apache License

@Background
void importCardsFrom(String jsonPath) {
    String json;//  ww  w  .j a  va  2  s.  c om
    try {
        FileInputStream inputStream = new FileInputStream(jsonPath);
        json = TextUtils.join("", CharStreams.readLines(new InputStreamReader(inputStream)));
    } catch (IOException e) {
        activityHelper.showError(e);
        return;
    }
    JsonArray cards;
    try {
        JsonElement jsonElement = new JsonParser().parse(json);
        JsonObject object = jsonElement.getAsJsonObject();
        cards = object.getAsJsonArray(JSON_KEY_CARDS);
    } catch (JsonIOException e) {
        activityHelper.showError(e);
        return;
    }

    for (JsonElement element : cards) {
        JsonObject cardData = element.getAsJsonObject();
        Card card = new Card(cardData);
        try {
            databaseHelper.createCard(card);
        } catch (SQLException e) {
            activityHelper.showError(e);
            return;
        }
    }
    onImportCards();
}

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

License:Open Source License

/**
 * Generate all the alerts for the given account IDs under the manager account.
 *
 * @param clientCustomerIds the client customer IDs
 * @param alertsConfig the JSON config of the alerts
 *///from   w  w  w. j  av  a 2  s  . c  o m
public void generateAlerts(Set<Long> clientCustomerIds, JsonObject alertsConfig)
        throws AlertConfigLoadException, AlertProcessingException {
    Stopwatch stopwatch = Stopwatch.createStarted();

    ImmutableAdWordsSession session = null;
    try {
        session = authenticator.authenticate();
    } catch (OAuthException e) {
        throw new AlertConfigLoadException("Failed to authenticate AdWordsSession.", e);
    } catch (ValidationException e) {
        throw new AlertConfigLoadException("Failed to build AdWordsSession.", e);
    }

    if (clientCustomerIds == null) {
        clientCustomerIds = retrieveClientCustomerIds(session);

        // Write the client customer IDs into debug log.
        LOGGER.debug("Client customer IDs retrieved:{}{}", SEPARATOR,
                Joiner.on(SEPARATOR).join(clientCustomerIds));
    }

    int count = 0;
    for (JsonElement alertConfig : alertsConfig.getAsJsonArray(ConfigTags.ALERTS)) {
        count++;
        processAlert(clientCustomerIds, session, alertConfig.getAsJsonObject(), count);
    }

    stopwatch.stop();
    LOGGER.info("*** Finished all processing in {} seconds ***",
            stopwatch.elapsed(TimeUnit.MILLISECONDS) / 1000);
}

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  ww  .  j  av a  2 s. co 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);
}