Example usage for com.google.gson JsonObject has

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

Introduction

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

Prototype

public boolean has(String memberName) 

Source Link

Document

Convenience method to check if a member with the specified name is present in this object.

Usage

From source file:Sleep.java

License:Apache License

public static JsonObject main(JsonObject parm) throws InterruptedException {
    int sleepTimeInMs = 1;
    if (parm.has("sleepTimeInMs")) {
        sleepTimeInMs = parm.getAsJsonPrimitive("sleepTimeInMs").getAsInt();
    }/* w ww  .j av a  2  s .co m*/
    System.out.println("Specified sleep time is " + sleepTimeInMs + " ms.");

    final String responseText = "Terminated successfully after around " + sleepTimeInMs + " ms.";
    final JsonObject response = new JsonObject();
    response.addProperty("msg", responseText);

    Thread.sleep(sleepTimeInMs);

    System.out.println(responseText);
    return response;
}

From source file:ProcessRequest.java

public JSONObject parseQuery(JSONObject requestObject, OutputStream os)
        throws JSONException, SQLException, IOException {
    String query = "";
    String tableName = "";

    JSONArray selectionColumns = requestObject.getJSONArray("selection");
    query += "SELECT " + selectionColumns.getString(0);
    for (int i = 1; i < selectionColumns.length(); i++) {
        query += "," + selectionColumns.getString(i);
    }//from   ww w . j a v  a  2 s  .  co m
    query += " FROM ";
    tableName = requestObject.getString("table");
    query += tableName;
    if (requestObject.has("where")) {
        query += " WHERE ";
        query += requestObject.getString("where");
    }
    query += ";";

    JSONObject responseObject = new JSONObject();
    JSONArray resultJSONArray;

    //System.out.println(query);
    if (os != null) {
        os.write(new String("{\"result_set\":[").getBytes());
        parseQueryResults(executeQuery(query), tableName, os, false);
    }

    resultJSONArray = parseQueryResults(executeQuery(query), tableName);
    //System.out.println(resultSet.toString(5));
    if (requestObject.has("join")) {
        JSONArray joinArray = requestObject.getJSONArray("join");
        List<String> tableList = new LinkedList<String>();
        tableList.add(tableName);
        for (int h = 0; h < joinArray.length(); h++) {
            //find the next link table
            JSONObject joinObject = null;
            for (int j = 0; j < joinArray.length(); j++) {
                for (int k = 0; k < tableList.size(); k++) {
                    if (joinArray.getJSONObject(j).getString("table").equals(tableList.get(k))) {
                        //break;   //this table has already been joined
                    } else if (joinArray.getJSONObject(j).getString("link_table").equals(tableList.get(k))) {
                        joinObject = joinArray.getJSONObject(j);
                    }
                }
            }
            if (joinObject == null) {
                throw new JSONException("join syntax was incorrect, no valid joins were found");
            }
            for (int i = 0; i < resultJSONArray.length(); i++) {
                //we now know the table to join, now search through the results looking for the link_table and query on each
                if (joinObject.getString("link_table").equals(
                        resultJSONArray.getJSONObject(i).getJSONObject("metadata").getString("table"))) {
                    //this result contains the correct link_table.  query against it's link_column value
                    JsonObject linkObject = new JsonParser().parse(resultJSONArray.getJSONObject(i).toString())
                            .getAsJsonObject();
                    JsonPrimitive linkValue = null;
                    if (linkObject.has(joinObject.getString("link_column"))) {
                        linkValue = linkObject.getAsJsonPrimitive(joinObject.getString("link_column"));
                    } else {
                        //just skip this result and notify the log console.
                        //however, this is most likely an error and should be fixed.
                        System.out.println("link column did not contain the following column (please fix): "
                                + joinObject.get("link_column"));
                    }

                    String predicate = "1=1";
                    if (linkValue.isBoolean()) {
                        if (linkValue.getAsBoolean() == true) {
                            predicate = joinObject.getString("column") + "=1";
                        } else {
                            predicate = joinObject.getString("column") + "=0";
                        }
                    }
                    if (linkValue.isNumber()) {
                        predicate = joinObject.getString("column") + "=" + linkValue.getAsString();
                    }
                    if (linkValue.isString()) {
                        predicate = joinObject.getString("column") + "='" + linkValue.getAsString() + "'";
                    }
                    String joinQuery = "";
                    if (joinObject.has("selection")) {
                        JSONArray joinSelectionColumns = joinObject.getJSONArray("selection");
                        joinQuery += "SELECT " + joinSelectionColumns.getString(0);
                        for (int k = 1; k < joinSelectionColumns.length(); k++) {
                            joinQuery += "," + joinSelectionColumns.getString(k);
                        }
                    } else {
                        joinQuery += "SELECT *";
                    }
                    //build and execute query, adding it to the result set
                    joinQuery += " FROM " + joinObject.getString("table") + " WHERE " + predicate;
                    if (joinObject.has("where")) {
                        String whereClause = joinObject.getString("where");
                        joinQuery += " AND " + whereClause;
                    }
                    joinQuery += ";";
                    //System.out.println("join query: "+joinQuery);
                    //JSONArray parsedResult = parseQueryResults(executeQuery(joinQuery), joinObject.getString("table"));
                    //System.out.println("join parsed result: "+parsedResult.toString(5));
                    if (os != null)
                        parseQueryResults(executeQuery(query), joinObject.getString("table"), os, true);
                    else
                        concatArray(resultJSONArray,
                                parseQueryResults(executeQuery(query), joinObject.getString("table")));
                }
            }
            tableList.add(joinObject.getString("table"));
        }
    }
    if (os != null)
        os.write(new String("]}\n").getBytes());
    responseObject.put("result_set", resultJSONArray);
    //System.out.println(responseObject.toString(5));
    return responseObject;
}

From source file:ai.nitro.bot4j.integration.slack.receive.impl.SlackReceiveActionMessageFactoryImpl.java

License:Open Source License

@Override
public ReceiveMessage createReceiveMessage(final JsonObject json) {
    final ReceiveMessage result = new ReceiveMessage();
    result.setNativePayload(SlackPlatformEnum.SLACK, json);

    final String actionTs = json.get(ACTION_TS).getAsString();
    final JsonObject userJsonObject = json.get(USER).getAsJsonObject();
    final String userId = userJsonObject.get(ID).getAsString();
    final String messageId = actionTs + "-" + userId;
    result.setMessageId(messageId);//from ww  w . j a va2 s .  c o  m

    handleSender(json, result);
    handleRecipient(json, result);

    if (json.has(ACTIONS)) {
        handleActions(json.get(ACTIONS).getAsJsonArray(), result);
    }

    return result;
}

From source file:ai.nitro.bot4j.integration.slack.receive.impl.SlackReceiveActionMessageFactoryImpl.java

License:Open Source License

protected void handleRecipient(final JsonObject json, final ReceiveMessage result) {
    final Participant participant = new Participant();
    participant.setPlatform(SlackPlatformEnum.SLACK);

    if (json.has(CHANNEL)) {
        final JsonObject channelJsonObject = json.get(CHANNEL).getAsJsonObject();

        if (channelJsonObject.has(ID)) {
            final String channel = channelJsonObject.get(ID).getAsString();
            participant.setId(channel);/*  www .j a  va  2s. co m*/
        }
    }

    result.setRecipient(participant);
}

From source file:ai.nitro.bot4j.integration.slack.receive.impl.SlackReceiveActionMessageFactoryImpl.java

License:Open Source License

protected void handleSender(final JsonObject json, final ReceiveMessage result) {
    final Participant participant = new Participant();
    participant.setPlatform(SlackPlatformEnum.SLACK);

    if (json.has(CHANNEL)) {
        final JsonObject channelJsonObject = json.get(CHANNEL).getAsJsonObject();

        if (channelJsonObject.has(ID)) {
            final String channel = channelJsonObject.get(ID).getAsString();
            participant.setId(channel);/* www . ja v a  2 s  . co  m*/
        }
    }

    result.setSender(participant);
}

From source file:ai.nitro.bot4j.integration.slack.receive.impl.SlackReceiveEventMessageFactoryImpl.java

License:Open Source License

@Override
public ReceiveMessage createReceiveMessage(final JsonObject json) {
    final ReceiveMessage result = new ReceiveMessage();
    result.setNativePayload(SlackPlatformEnum.SLACK, json);

    final String eventTs = json.get(EVENT_TS).getAsString();
    final String username = json.get(USER).getAsString();
    final String messageId = eventTs + "-" + username;
    result.setMessageId(messageId);/*from w ww. ja va 2  s . co  m*/

    handleSender(json, result);
    handleRecipient(json, result);

    if (json.has(TEXT)) {
        handleText(json.get(TEXT).getAsString(), result);
    }

    return result;
}

From source file:ai.nitro.bot4j.integration.slack.receive.webhook.impl.SlackEventWebhookImpl.java

License:Open Source License

protected void handleEvent(final JsonObject jsonReq, final HttpServletResponse res) {
    final JsonObject eventJsonObject = jsonReq.get(EVENT).getAsJsonObject();

    if (!eventJsonObject.has(TYPE)) {
        LOG.warn("no type in event JSON");
    } else if (!MESSAGE.equals(eventJsonObject.get(TYPE).getAsString())) {
        LOG.warn("no message in event JSON");
    } else if (eventJsonObject.has(BOT_ID)) {
        LOG.info("ignoring bot message");
    } else if (eventJsonObject.has(SUBTYPE) && BOT_MESSAGE.equals(eventJsonObject.get(SUBTYPE).getAsString())) {
        LOG.info("ignoring bot message");
    } else {//from   w  w  w .j  a  va2 s .c  o  m
        slackReceiveHandler.handleEvent(eventJsonObject, (long) 0);
    }
}

From source file:ai.nitro.bot4j.integration.slack.receive.webhook.impl.SlackEventWebhookImpl.java

License:Open Source License

@Override
public String post(final HttpServletRequest req, final HttpServletResponse res) {
    String result = "";

    try {//from   w  ww  .ja  v a2  s. c o m
        final String body = CharStreams.toString(req.getReader());
        final JsonParser jsonParser = new JsonParser();
        final JsonObject jsonReq = jsonParser.parse(body).getAsJsonObject();

        if (!jsonReq.has(TYPE)) {
            LOG.warn("no type in JSON");
        } else {
            final JsonElement typeJsonElement = jsonReq.get(TYPE);
            final String type = typeJsonElement.getAsString();

            switch (type) {
            case URL_VERIFICATION:
                result = handleUrlVerification(jsonReq, res);
                break;
            case EVENT_CALLBACK:
                handleEvent(jsonReq, res);
                break;
            default:
                LOG.info("unknown type {}", type);
                break;
            }
        }
    } catch (final Exception e) {
        handleException(e);
    }

    return result;
}

From source file:app.abhijit.iter.data.source.StudentDataSource.java

License:Open Source License

public void fetch() {
    String selectedRegistrationNumber = mLocalStore.getString(SELECTED_REGISTRATION_NUMBER_KEY, null);
    if (!StringUtils.equals(selectedRegistrationNumber, mSelectedRegistrationNumber)) {
        if (mFetchStudentAsyncTask != null) {
            mFetchStudentAsyncTask.cancel(true);
            mFetchStudentAsyncTask = null;
        }/*  ww w  .  ja v  a 2s.  co  m*/
        if (mFetchStudentSubjectsAsyncTask != null) {
            mFetchStudentSubjectsAsyncTask.cancel(true);
            mFetchStudentSubjectsAsyncTask = null;
        }
        mSelectedRegistrationNumber = selectedRegistrationNumber;
    }

    if (mSelectedRegistrationNumber != null && mErrorMessage == null && mFetchStudentAsyncTask == null
            && mFetchStudentSubjectsAsyncTask == null) {
        if (!mLocalStore.contains(mSelectedRegistrationNumber)) {
            JsonObject student = new JsonObject();
            student.addProperty(STUDENT_REGISTRATION_NUMBER_KEY, mSelectedRegistrationNumber);
            mLocalStore.edit().putString(mSelectedRegistrationNumber, student.toString()).apply();
            mFetchStudentAsyncTask = new FetchStudentAsyncTask();
            mFetchStudentAsyncTask.execute();
        } else {
            JsonObject student = mJsonParser.parse(mLocalStore.getString(mSelectedRegistrationNumber, null))
                    .getAsJsonObject();
            if (!student.has(STUDENT_NAME_KEY)) {
                mFetchStudentAsyncTask = new FetchStudentAsyncTask();
                mFetchStudentAsyncTask.execute();
            } else {
                boolean isSubjectDataOld = (new Date().getTime()
                        - student.get(STUDENT_TIMESTAMP_KEY).getAsLong()) > CACHE_TIMEOUT;
                if (isSubjectDataOld || !student.has(STUDENT_SUBJECTS_KEY)) {
                    String studentId = student.get(STUDENT_ID_KEY).getAsString();
                    mFetchStudentSubjectsAsyncTask = new FetchStudentSubjectsAsyncTask();
                    mFetchStudentSubjectsAsyncTask.execute(studentId);
                }
            }
        }
    }

    if (mErrorMessage != null) {
        EventBus.getDefault().post(new Error(mErrorMessage));
        mErrorMessage = null;
    }

    ArrayList<Student> students = new ArrayList<>();

    for (Map.Entry<String, ?> entry : mLocalStore.getAll().entrySet()) {
        if (entry.getKey().equals(SELECTED_REGISTRATION_NUMBER_KEY))
            continue;
        JsonObject student = mJsonParser.parse(mLocalStore.getString(entry.getKey(), null)).getAsJsonObject();
        students.add(generateStudent(student));
    }

    EventBus.getDefault().post(ImmutableList.copyOf(students));
}

From source file:app.abhijit.iter.data.source.StudentDataSource.java

License:Open Source License

private void processStudent(String[] response) {
    mFetchStudentAsyncTask = null;/*w  w w .j a  v  a2  s.  co m*/

    if (response[0] == null || response[1] == null) {
        mErrorMessage = "Could not load registration number " + mSelectedRegistrationNumber;
        delete(mSelectedRegistrationNumber);
        fetch();
        return;
    }

    String studentId = response[0];

    if (studentId.equals("0")) {
        mErrorMessage = "Registration number " + mSelectedRegistrationNumber + " is not valid";
        delete(mSelectedRegistrationNumber);
        fetch();
        return;
    }

    JsonObject student = new JsonObject();

    try {
        JsonObject studentDetails = mJsonParser.parse(response[1]).getAsJsonArray().get(0).getAsJsonObject();
        if (!studentDetails.has("name")) {
            throw new Exception();
        }
        student.addProperty(STUDENT_ID_KEY, studentId);
        student.addProperty(STUDENT_NAME_KEY, studentDetails.get("name").getAsString());
        student.addProperty(STUDENT_REGISTRATION_NUMBER_KEY, mSelectedRegistrationNumber);
        student.addProperty(STUDENT_TIMESTAMP_KEY, new Date().getTime());
    } catch (Exception e) {
        mErrorMessage = "Could not load registration number " + mSelectedRegistrationNumber;
        delete(mSelectedRegistrationNumber);
        fetch();
        return;
    }

    mLocalStore.edit().putString(mSelectedRegistrationNumber, student.toString()).apply();

    fetch();
}