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.luorrak.ouroboros.api.JsonParser.java

License:Open Source License

public void checkExtraFiles(String label, ArrayList<String> value, JsonObject threadJson) {
    if (threadJson.has(THREAD_EXTRA_FILES)) {
        JsonArray extraFiles = threadJson.getAsJsonArray(THREAD_EXTRA_FILES);
        for (JsonElement fileElement : extraFiles) {
            JsonObject file = fileElement.getAsJsonObject();
            value.add(file.get(label).getAsString());
        }//ww  w. ja  v  a  2 s  . c  om
    }
}

From source file:com.luorrak.ouroboros.services.ReplyCheckerService.java

License:Open Source License

private void insertRCIntoDatabase(JsonObject jsonObject, String userPostBoardName,
        InfiniteDbHelper infiniteDbHelper) {
    JsonParser jsonParser = new JsonParser();
    JsonArray posts = jsonObject.getAsJsonArray("posts");
    int position = 0;
    for (JsonElement postElement : posts) {
        JsonObject post = postElement.getAsJsonObject();
        infiniteDbHelper.insertRCEntry(userPostBoardName, jsonParser.getThreadResto(post),
                jsonParser.getThreadNo(post), jsonParser.getThreadSub(post), jsonParser.getThreadCom(post),
                jsonParser.getThreadEmail(post), jsonParser.getThreadName(post), jsonParser.getThreadTrip(post),
                jsonParser.getThreadTime(post), jsonParser.getThreadLastModified(post),
                jsonParser.getThreadId(post), jsonParser.getThreadEmbed(post), jsonParser.getMediaFiles(post),
                position);/*from   ww w  .  ja va2  s .  c  o m*/
        position++;
    }
}

From source file:com.mazzella.polygon.polygonzone.PolygonZone.java

License:Apache License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_polygon_zone);

    polygonCanvas = (PolygonCanvas) findViewById(R.id.polygon_canvas);

    //        polygonCanvas.getLayoutParams().width = getResources().getDisplayMetrics().widthPixels;
    //        polygonCanvas.getLayoutParams().height = (int) (getResources().getDisplayMetrics().widthPixels * .56429330);

    JsonArray jsonArray = new JsonArray();
    polygonCanvas.init("#FFFFFF", jsonArray);

    findViewById(R.id.init).setOnClickListener(new View.OnClickListener() {
        @Override/*w  w w. j a v a2 s . c  o m*/
        public void onClick(View v) {
            //                JsonParser jsonParser = new JsonParser();
            //                JsonObject jsonObject = jsonParser.parse("{\"points\":[[2286,3053],[6000,1781],[9714,509],[9714,5000],[9714,9491],[4929,5293],[286,9491],[1286,6272]]}").getAsJsonObject();
            //                JsonArray jsonArray = jsonObject.getAsJsonArray("points");
            JsonArray jsonArray = new JsonArray();
            polygonCanvas.init("#FFFFFF", jsonArray);
        }
    });

    findViewById(R.id.predefined).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            JsonParser jsonParser = new JsonParser();
            JsonObject jsonObject = jsonParser.parse(
                    "{\"points\":[[2286,3053],[6000,1781],[9714,509],[9714,5000],[9714,9491],[4929,5293],[286,9491],[1286,6272]]}")
                    .getAsJsonObject();
            JsonArray jsonArray = jsonObject.getAsJsonArray("points");
            polygonCanvas.init("#FFFFFF", jsonArray);
        }
    });

    findViewById(R.id.clear).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            polygonCanvas.clearTouchPoints();
        }
    });
}

From source file:com.microsoft.graph.generated.BaseAttachmentCollectionResponse.java

License:MIT License

/**
 * Sets the raw json object//from w  w w .  j  a  v a 2  s .c  o  m
 *
 * @param serializer The serializer
 * @param json The json object to set this object to
 */
public void setRawObject(final ISerializer serializer, final JsonObject json) {
    mSerializer = serializer;
    mRawObject = json;

    if (json.has("value")) {
        final JsonArray array = json.getAsJsonArray("value");
        for (int i = 0; i < array.size(); i++) {
            value.get(i).setRawObject(mSerializer, (JsonObject) array.get(i));
        }
    }
}

From source file:com.mycompany.mavenproject1.WikiCrawler.java

/**
 * //from  w ww  .j  a v  a2  s  .  c  om
 * @param articleName String used to search for wikipedia article
 * @return Name of wikipedia article if one was found, or null
 *      if nothing was found.
 * @throws MalformedURLException
 * @throws IOException 
 */
public String search(String articleName) throws MalformedURLException, IOException {
    articleName = articleName.replaceAll(" ", "+");
    URL url = new URL(String.format(SEARCH_FORMAT, articleName));
    HttpURLConnection request = (HttpURLConnection) url.openConnection();
    //request.setRequestProperty("User-Agent", USER_AGENT);
    request.connect();

    JsonParser jp = new JsonParser();
    JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
    JsonObject rootobj = root.getAsJsonObject();
    JsonObject query = rootobj.getAsJsonObject("query");
    int totalHits = query.getAsJsonObject("searchinfo").get("totalhits").getAsInt();
    if (totalHits == 0)
        return null;

    String title = query.getAsJsonArray("search").get(0).getAsJsonObject().get("title").getAsString();
    return title.replaceAll(" ", "_");

}

From source file:com.ninetyslide.libs.botforge.FbBot.java

License:Apache License

/**
 * This method handles all the callbacks headed to the Webhook other than the Webhook Validation. It retrieves the
 * BotContext using the request URL, verifies the signature of the request (if enabled), parses the message received
 * via the Webhook and then delivers the parsed message to the right callback, depending on the message type.
 *
 * @param req The request object.//from   w w  w  .  j  av  a2 s . c o  m
 * @param resp The response object.
 * @throws ServletException When there is a Servlet related error.
 */
@Override
protected final void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException {

    // TODO: Add support for uploaded file in incoming and outgoing Attachment Messages
    // Get the URL of the request
    String webhookUrl = req.getRequestURL().toString();

    // Retrieve the context or fail if the context is not found
    BotContext context = retrieveContext(null, webhookUrl);
    if (context == null) {
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Get the signature header
    String signatureHeader = req.getHeader(HTTP_HEADER_SIGNATURE);

    // Get the JSON String
    String jsonStr;
    try {
        jsonStr = extractJsonString(req.getReader());
    } catch (IOException e) {
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // If debug is enabled, print the JSON and the signature header
    if (context.isDebugEnabled()) {
        log.info("Signature Header: " + signatureHeader + "\n" + "Raw JSON: " + jsonStr + "\n");
    }

    // Verify the signature using HMAC-SHA1 and send back an error if verification fails
    if (context.isCallbacksValidationActive()
            && !SignatureVerifier.verifySignature(jsonStr, signatureHeader, context.getAppSecretKey())) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // Parse the JSON String
    JsonObject rawMessage = parser.parse(jsonStr).getAsJsonObject();

    // Process every message of the batch
    JsonArray entries = rawMessage.getAsJsonArray(JSON_CALLBACK_FIELD_NAME_ENTRY);

    // If there are no entries, send back an error and just return
    if (entries == null) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // If there were no errors, answer with HTTP Code 200 to Facebook server as soon as possible
    try {
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.flushBuffer();
    } catch (IOException e) {
        return;
    }

    for (JsonElement rawEntry : entries) {

        JsonObject entry = rawEntry.getAsJsonObject();
        JsonArray messages = entry.getAsJsonArray(JSON_CALLBACK_FIELD_NAME_MESSAGING);

        // If there are no messages, go on with the next entry
        if (messages == null) {
            continue;
        }

        for (JsonElement messageRaw : messages) {
            JsonObject message = messageRaw.getAsJsonObject();
            JsonObject content;
            IncomingMessage incomingMessage;

            if ((content = message.getAsJsonObject(JSON_CALLBACK_TYPE_NAME_MESSAGE)) != null) {

                // It's a message received, parse it correctly based on the sub type
                if (content.get(JSON_CALLBACK_SUB_TYPE_NAME_TEXT) != null) {
                    incomingMessage = gson.fromJson(content, IncomingTextMessage.class);
                } else if (content.getAsJsonArray(JSON_CALLBACK_SUB_TYPE_NAME_ATTACHMENTS) != null) {
                    incomingMessage = gson.fromJson(content, IncomingAttachmentMessage.class);
                } else {
                    // Can't send an error to the server anymore, try to process as much as you can of the message
                    continue;
                }

                // Set Sender ID, Recipient ID and Timestamp
                setMessageHeaders(message, incomingMessage);

                // Deliver the message to the right callback based on the type
                ReceivedMessage receivedMessage = (ReceivedMessage) incomingMessage;
                if (receivedMessage.isEcho()) {
                    onMessageEchoReceived(context, receivedMessage);
                } else {
                    onMessageReceived(context, receivedMessage);
                }

            } else if ((content = message.getAsJsonObject(JSON_CALLBACK_TYPE_NAME_POSTBACK)) != null) {

                // Parse the message as a postback message
                incomingMessage = gson.fromJson(content, Postback.class);

                // Set Sender ID, Recipient ID and Timestamp
                setMessageHeaders(message, incomingMessage);

                // Deliver the message to the postback callback
                onPostbackReceived(context, (Postback) incomingMessage);

            } else if ((content = message.getAsJsonObject(JSON_CALLBACK_TYPE_NAME_OPTIN)) != null) {

                // Parse the message as an authentication callback
                incomingMessage = gson.fromJson(content, Optin.class);

                // Set Sender ID, Recipient ID and Timestamp
                setMessageHeaders(message, incomingMessage);

                // Deliver the message to the authentication callback
                onAuthenticationReceived(context, (Optin) incomingMessage);

            } else if ((content = message.getAsJsonObject(JSON_CALLBACK_TYPE_NAME_ACCOUNT_LINKING)) != null) {

                // Parse the message as an account linking callback
                incomingMessage = gson.fromJson(content, AccountLinking.class);

                // Set Sender ID, Recipient ID and Timestamp
                setMessageHeaders(message, incomingMessage);

                // Deliver the message to the account linking callback
                onAccountLinkingReceived(context, (AccountLinking) incomingMessage);

            } else if ((content = message.getAsJsonObject(JSON_CALLBACK_TYPE_NAME_DELIVERY)) != null) {

                // Parse the message as a delivery receipt
                incomingMessage = gson.fromJson(content, DeliveryReceipt.class);

                // Set Sender ID, Recipient ID and Timestamp
                setMessageHeaders(message, incomingMessage);

                // Deliver the message to the message delivery callback
                onMessageDelivered(context, (DeliveryReceipt) incomingMessage);

            } else if ((content = message.getAsJsonObject(JSON_CALLBACK_TYPE_NAME_READ)) != null) {

                // Parse the message as a read receipt
                incomingMessage = gson.fromJson(content, ReadReceipt.class);

                // Set Sender ID, Recipient ID and Timestamp
                setMessageHeaders(message, incomingMessage);

                // Deliver the message to the message read callback
                onMessageRead(context, (ReadReceipt) incomingMessage);

            }
        }
    }

}

From source file:com.optimizely.ab.config.parser.DatafileGsonDeserializer.java

License:Apache License

@Override
public ProjectConfig deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObject = json.getAsJsonObject();

    String accountId = jsonObject.get("accountId").getAsString();
    String projectId = jsonObject.get("projectId").getAsString();
    String revision = jsonObject.get("revision").getAsString();
    String version = jsonObject.get("version").getAsString();
    int datafileVersion = Integer.parseInt(version);

    // generic list type tokens
    Type groupsType = new TypeToken<List<Group>>() {
    }.getType();/*from   ww  w  . j ava 2  s.  co m*/
    Type experimentsType = new TypeToken<List<Experiment>>() {
    }.getType();
    Type attributesType = new TypeToken<List<Attribute>>() {
    }.getType();
    Type eventsType = new TypeToken<List<EventType>>() {
    }.getType();
    Type audienceType = new TypeToken<List<Audience>>() {
    }.getType();
    Type typedAudienceType = new TypeToken<List<TypedAudience>>() {
    }.getType();

    List<Group> groups = context.deserialize(jsonObject.get("groups").getAsJsonArray(), groupsType);
    List<Experiment> experiments = context.deserialize(jsonObject.get("experiments").getAsJsonArray(),
            experimentsType);

    List<Attribute> attributes;
    attributes = context.deserialize(jsonObject.get("attributes"), attributesType);

    List<EventType> events = context.deserialize(jsonObject.get("events").getAsJsonArray(), eventsType);
    List<Audience> audiences = Collections.emptyList();
    if (jsonObject.has("audiences")) {
        audiences = context.deserialize(jsonObject.get("audiences").getAsJsonArray(), audienceType);
    }

    List<Audience> typedAudiences = null;
    if (jsonObject.has("typedAudiences")) {
        typedAudiences = context.deserialize(jsonObject.get("typedAudiences").getAsJsonArray(),
                typedAudienceType);
    }
    boolean anonymizeIP = false;
    if (datafileVersion >= Integer.parseInt(DatafileProjectConfig.Version.V3.toString())) {
        anonymizeIP = jsonObject.get("anonymizeIP").getAsBoolean();
    }

    List<FeatureFlag> featureFlags = null;
    List<Rollout> rollouts = null;
    Boolean botFiltering = null;
    if (datafileVersion >= Integer.parseInt(DatafileProjectConfig.Version.V4.toString())) {
        Type featureFlagsType = new TypeToken<List<FeatureFlag>>() {
        }.getType();
        featureFlags = context.deserialize(jsonObject.getAsJsonArray("featureFlags"), featureFlagsType);
        Type rolloutsType = new TypeToken<List<Rollout>>() {
        }.getType();
        rollouts = context.deserialize(jsonObject.get("rollouts").getAsJsonArray(), rolloutsType);
        if (jsonObject.has("botFiltering"))
            botFiltering = jsonObject.get("botFiltering").getAsBoolean();
    }

    return new DatafileProjectConfig(accountId, anonymizeIP, botFiltering, projectId, revision, version,
            attributes, audiences, typedAudiences, events, experiments, featureFlags, groups, rollouts);
}

From source file:com.optimizely.ab.config.parser.GroupGsonDeserializer.java

License:Apache License

@Override
public Group deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    JsonObject jsonObject = json.getAsJsonObject();

    String id = jsonObject.get("id").getAsString();
    String policy = jsonObject.get("policy").getAsString();

    List<Experiment> experiments = new ArrayList<Experiment>();
    JsonArray experimentsJson = jsonObject.getAsJsonArray("experiments");
    for (Object obj : experimentsJson) {
        JsonObject experimentObj = (JsonObject) obj;
        experiments.add(GsonHelpers.parseExperiment(experimentObj, id, context));
    }/*from w w  w  .j  av a  2s  . c  o m*/

    List<TrafficAllocation> trafficAllocations = GsonHelpers
            .parseTrafficAllocation(jsonObject.getAsJsonArray("trafficAllocation"));

    return new Group(id, policy, experiments, trafficAllocations);
}

From source file:com.optimizely.ab.config.parser.GsonHelpers.java

License:Apache License

private static List<Variation> parseVariations(JsonArray variationJson, JsonDeserializationContext context) {
    List<Variation> variations = new ArrayList<Variation>(variationJson.size());
    for (Object obj : variationJson) {
        JsonObject variationObject = (JsonObject) obj;
        String id = variationObject.get("id").getAsString();
        String key = variationObject.get("key").getAsString();
        Boolean featureEnabled = false;
        if (variationObject.has("featureEnabled") && !variationObject.get("featureEnabled").isJsonNull()) {
            featureEnabled = variationObject.get("featureEnabled").getAsBoolean();
        }/*from  www . j  a v a  2  s . c o  m*/

        List<FeatureVariableUsageInstance> variableUsageInstances = null;
        // this is an existence check rather than a version check since it's difficult to pass data
        // across deserializers.
        if (variationObject.has("variables")) {
            Type featureVariableUsageInstancesType = new TypeToken<List<FeatureVariableUsageInstance>>() {
            }.getType();
            variableUsageInstances = context.deserialize(variationObject.getAsJsonArray("variables"),
                    featureVariableUsageInstancesType);
        }

        variations.add(new Variation(id, key, featureEnabled, variableUsageInstances));
    }

    return variations;
}

From source file:com.optimizely.ab.config.parser.GsonHelpers.java

License:Apache License

static Experiment parseExperiment(JsonObject experimentJson, String groupId,
        JsonDeserializationContext context) {
    String id = experimentJson.get("id").getAsString();
    String key = experimentJson.get("key").getAsString();
    JsonElement experimentStatusJson = experimentJson.get("status");
    String status = experimentStatusJson.isJsonNull() ? ExperimentStatus.NOT_STARTED.toString()
            : experimentStatusJson.getAsString();

    JsonElement layerIdJson = experimentJson.get("layerId");
    String layerId = layerIdJson == null ? null : layerIdJson.getAsString();

    JsonArray audienceIdsJson = experimentJson.getAsJsonArray("audienceIds");
    List<String> audienceIds = new ArrayList<>(audienceIdsJson.size());
    for (JsonElement audienceIdObj : audienceIdsJson) {
        audienceIds.add(audienceIdObj.getAsString());
    }/*  w  w w .j  av a 2s.  c  o m*/

    Condition conditions = parseAudienceConditions(experimentJson);

    // parse the child objects
    List<Variation> variations = parseVariations(experimentJson.getAsJsonArray("variations"), context);
    Map<String, String> userIdToVariationKeyMap = parseForcedVariations(
            experimentJson.getAsJsonObject("forcedVariations"));
    List<TrafficAllocation> trafficAllocations = parseTrafficAllocation(
            experimentJson.getAsJsonArray("trafficAllocation"));

    return new Experiment(id, key, status, layerId, audienceIds, conditions, variations,
            userIdToVariationKeyMap, trafficAllocations, groupId);
}