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.microsoft.windowsazure.mobileservices.table.sync.MobileServiceSyncContext.java

License:Open Source License

private void pushOperation(TableOperation operation)
        throws MobileServiceLocalStoreException, MobileServiceSyncHandlerException {

    operation.setOperationState(MobileServiceTableOperationState.Attempted);

    JsonObject item = this.mStore.lookup(operation.getTableName(), operation.getItemId());

    if (item == null) {
        // '/' is a reserved character that cannot be used on string ids.
        // We use it to build a unique compound string from tableName and
        // itemId
        String tableItemId = operation.getTableName() + "/" + operation.getItemId();

        JsonObject backedUpItem = this.mStore.lookup(ITEM_BACKUP_TABLE, tableItemId);

        if (backedUpItem != null) {
            item = backedUpItem.get("clientitem").isJsonObject() ? backedUpItem.getAsJsonObject("clientitem")
                    : null;/*from   ww  w.j a va2  s .  c o m*/
        }
    }

    JsonObject result = this.mHandler
            .executeTableOperation(new RemoteTableOperationProcessor(this.mClient, item), operation);

    if (result != null) {
        this.mStore.upsert(operation.getTableName(), result, true);
    }
}

From source file:com.microsoft.windowsazure.mobileservices.table.sync.MobileServiceSyncContext.java

License:Open Source License

private TableOperationError getTableOperationError(TableOperation operation, Throwable throwable)
        throws MobileServiceLocalStoreException {
    JsonObject clientItem = this.mStore.lookup(operation.getTableName(), operation.getItemId());

    if (clientItem == null) {
        // '/' is a reserved character that cannot be used on string ids.
        // We use it to build a unique compound string from tableName and
        // itemId
        String tableItemId = operation.getTableName() + "/" + operation.getItemId();

        JsonObject backedUpItem = this.mStore.lookup(ITEM_BACKUP_TABLE, tableItemId);

        if (backedUpItem != null) {
            clientItem = backedUpItem.get("clientitem").isJsonObject()
                    ? backedUpItem.getAsJsonObject("clientitem")
                    : null;//from w  ww  .j  av a  2s .co m
        }
    }

    Integer statusCode = null;
    String serverResponse = null;
    JsonObject serverItem = null;

    if (throwable instanceof MobileServiceException) {
        MobileServiceException msEx = (MobileServiceException) throwable;
        if (msEx.getResponse() != null) {
            serverResponse = msEx.getResponse().getContent();
            if (msEx.getResponse().getStatus() != null) {
                statusCode = msEx.getResponse().getStatus().getStatusCode();
            }
        }
    }

    if (throwable instanceof MobileServiceExceptionBase) {
        MobileServiceExceptionBase mspfEx = (MobileServiceExceptionBase) throwable;
        serverItem = mspfEx.getValue();
    } else if (throwable.getCause() != null & throwable.getCause() instanceof MobileServiceExceptionBase) {
        MobileServiceExceptionBase mspfEx = (MobileServiceExceptionBase) throwable.getCause();
        serverItem = mspfEx.getValue();
    }

    return new TableOperationError(operation.getId(), operation.getKind(), operation.getTableName(),
            operation.getItemId(), clientItem, throwable.getMessage(), statusCode, serverResponse, serverItem);
}

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

/**
 * //from   w  ww.  j a  va 2 s .c  o m
 * @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.mycompany.mavenproject1.WikiCrawler.java

/**
 * Given a wikipedia article name, finds the first non italicized, non
 * parenthesized article in that article. 
 * @param articleName name of wikipedia article to process
 * @return name of the first non italicized, non parenthesized article
 *      in the input article/*from ww  w  .  j  a v a2  s  .  co  m*/
 * @throws IOException 
 */
public String nextArticle(String articleName) throws IOException, InterruptedException {
    //section of the current article
    int section = 0;
    //So far, the result has always been in the first section. If section
    //gets to 5 we're most likely in an infinite loop. Has yet to happen though.
    while (section < 5) {
        //Make api call and grab the article text from it
        URL url = new URL(String.format(PARSE_FORMAT, articleName, section));
        //URL url = new URL("https://en.wikipedia.org/w/api.php?action=parse&redirects=true&format=json&prop=text&page=" + articleName +"&section=" + section);
        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 parse = rootobj.getAsJsonObject("parse");
        if (parse == null)
            return null;
        String text = parse.getAsJsonObject("text").get("*").getAsString();
        //the paragraph element is where the main text of the article normally begins
        int index = text.indexOf("<p>");
        //Sometimes there are p tags with links before the main article text. We'll search for the bold tag,
        //as the first sentence of an article usually contains the name of the article in bold.
        while ((section == 0 && index != -1 && text.indexOf("<b>", index) > text.indexOf("</p>", index)))
            index = text.indexOf("<p>", index + 1);

        //couldn't find article text
        if (index == -1)
            continue;

        int lastOpeningParen = text.indexOf('(', index);
        int lastOpeningItalics = text.indexOf("<i>", index);
        int lastOpeningDiv = text.indexOf("<div");
        int lastOpeningSpan = text.indexOf("<span");
        while (true) {
            //get index of next link
            index = text.indexOf("<a href=", index + 1);
            if (index == -1)
                break;
            //find position of the start of the link's displayed text
            int startOfLinkText = text.indexOf("\">", index) + 2;
            String sub = text.substring(startOfLinkText, startOfLinkText + 10);
            //If our link text is parenthesized, skip the current link.
            IsInsideResults result;
            result = isInside(text, startOfLinkText, startOfLinkText, "(", ")", lastOpeningParen);
            lastOpeningParen = result.lastOpeningIndex;
            if (result.isInside) {
                index = result.nextClosingIndex;
                continue;
            }
            //same for italics
            result = isInside(text, startOfLinkText, startOfLinkText, "(", ")", lastOpeningItalics);
            lastOpeningItalics = result.lastOpeningIndex;
            if (result.isInside) {
                index = result.nextClosingIndex;
                ;
                continue;
            }
            //Sometimes there will be divs/spans with links with the float:right
            //attribute. They won't be the first clickable links when
            //viewing the page normally, but they will appear earlier than the
            //main article text in the html itself. We should avoid links contained
            //in divs and spans as a result. Main article text is normally only be 
            //a child of the body tag.
            result = isInside(text, startOfLinkText, startOfLinkText, "<span", "</span>", lastOpeningSpan);
            lastOpeningSpan = result.lastOpeningIndex;
            if (result.isInside) {
                index = result.nextClosingIndex;
                ;
                continue;
            }
            result = isInside(text, startOfLinkText, startOfLinkText, "<div", "</div>", lastOpeningDiv);
            lastOpeningDiv = result.lastOpeningIndex;
            if (result.isInside) {
                index = result.nextClosingIndex;
                ;
                continue;
            }

            //grab name of the next article
            index = text.indexOf("href", index);
            index = text.indexOf('"', index) + 1;
            String nextArticle = text.substring(index, text.indexOf('"', index));
            //Links to other articles on wikipedia do not contain colons, start with /wiki/
            //and are not red links
            if (nextArticle.contains(":"))
                continue;
            if (nextArticle.contains("/wiki/") && !nextArticle.contains("redlink=1"))
                return nextArticle.substring(6);

        }
        section++;
        Thread.sleep(DELAY_IN_MS);
    }
    System.out.println("Exiting loop in MyCrawler.search. Most likely was an infinite loop");
    return null;
}

From source file:com.nearce.gamechatter.WebSocketHandler.java

License:Mozilla Public License

private void process(InetSocketAddress address, String message) {
    JsonObject object = new JsonParser().parse(message).getAsJsonObject();

    UUID identifier = UUID.fromString(object.getAsJsonPrimitive("user").getAsString());
    String method = object.getAsJsonPrimitive("method").getAsString();
    JsonObject params = object.getAsJsonObject("params");

    switch (method) {
    case "join":
        join(address, identifier, params);
        break;//from ww  w  .j  a va2 s.c om
    case "leave":
        leave(address, params);
        break;
    case "send":
        sendMessage(address, params);
        break;
    case "psend":
        sendPrivateMessage(address, params);
        break;
    }
}

From source file:com.ninetyslide.libs.botforge.adapter.SendMessageAdapter.java

License:Apache License

/**
 * Send a message from a specific bot.//from   w  w  w  .  ja  v  a 2s .  co  m
 *
 * @param context The Context of the bot to use for message sending.
 * @param message The message to send.
 * @param recipient The recipient for the message.
 * @return A SendMessageSuccess instance or a SendMessageError instance, if something went wrong. Use the 
 * hasError() method on the returned object to determine the type of object to cast.
 */
public static SendMessageResponse sendMessage(BotContext context, OutgoingMessage message,
        OutgoingMessage.OutgoingRecipient recipient) {
    // Check that all the parameters are ok
    if (context == null) {
        throw new IllegalArgumentException(Constants.MSG_CONTEXT_INVALID);
    }
    if (message == null) {
        throw new IllegalArgumentException(Constants.MSG_MESSAGE_INVALID);
    }
    if (recipient == null) {
        throw new IllegalArgumentException(Constants.MSG_RECIPIENT_INVALID);
    }

    // Set the recipient for the message
    message.setRecipient(recipient);

    // Generate the JSON String
    String jsonStrToSend = gson.toJson(message).replace("'", "\\'");

    // Log the request data if debug is enabled
    if (context.isDebugEnabled()) {
        log.info("JSON Raw Message: " + jsonStrToSend);
    }

    // Perform the request
    String response = NetworkManager.performPostRequest(SEND_MESSAGE_BASE_URL + context.getPageAccessToken(),
            jsonStrToSend);

    // Parse the response
    if (response != null) {
        // Parse the String into a JsonObject
        JsonObject jsonResponse = jsonParser.parse(response).getAsJsonObject();

        // Check for errors
        JsonObject error = jsonResponse.getAsJsonObject(Constants.JSON_SEND_RESPONSE_FIELD_NAME_ERROR);

        if (error != null) {
            // Return an error if the response contains an error
            return gson.fromJson(error, SendMessageError.class);
        } else {
            // Return a success response otherwise
            return gson.fromJson(jsonResponse, SendMessageSuccess.class);
        }

    } else {
        // Return a generated network error if something wrong happened during the network request
        return SendMessageError.generateNetworkError();
    }
}

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  a  va  2s .c om*/
 * @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.ninetyslide.libs.botforge.FbBot.java

License:Apache License

/**
 * Set the Sender ID, Recipient ID and Timestamp in the incoming message.
 *
 * @param rawMessage The raw JSON Object received via the callback.
 * @param message The extracted IncomingMessage.
 * @return The IncomingMessage passed as input, with the values set.
 *//*from  w w  w  . j  av  a  2 s.c o m*/
private IncomingMessage setMessageHeaders(JsonObject rawMessage, IncomingMessage message) {

    message.setSenderId(rawMessage.getAsJsonObject(JSON_CALLBACK_FIELD_NAME_SENDER)
            .get(JSON_CALLBACK_FIELD_NAME_ID).getAsString());

    message.setRecipientId(rawMessage.getAsJsonObject(JSON_CALLBACK_FIELD_NAME_RECIPIENT)
            .get(JSON_CALLBACK_FIELD_NAME_ID).getAsString());

    message.setTimestamp(rawMessage.get(JSON_CALLBACK_FIELD_NAME_TIMESTAMP).getAsLong());

    return message;

}

From source file:com.officialgenius.brainiac.diodes.NixDiode.java

License:Apache License

@Override
public String getDropBoxPath() throws IOException {
    Gson gson = new Gson();
    Path pathToDropBox = Paths.get(NIX_DROPBOX_INFO_PATH);
    BufferedReader br = Files.newBufferedReader(pathToDropBox, Charset.forName("UTF-8"));
    JsonReader jsonReader = new JsonReader(br);
    JsonObject infoJson = gson.fromJson(jsonReader, JsonObject.class);
    return infoJson.getAsJsonObject("personal").get("path").getAsString();

}

From source file:com.officialgenius.brainiac.diodes.WindowsDiode.java

License:Apache License

@Override
public String getDropBoxPath() throws IOException {
    Gson gson = new Gson();
    Path pathToDropBox = Paths.get(WIN_DROPBOX_INFO_PATH);
    BufferedReader br = Files.newBufferedReader(pathToDropBox, Charset.forName("UTF-8"));
    JsonReader jsonReader = new JsonReader(br);
    JsonObject infoJson = gson.fromJson(jsonReader, JsonObject.class);
    return infoJson.getAsJsonObject("personal").get("path").getAsString();

}