Example usage for org.json JSONObject JSONObject

List of usage examples for org.json JSONObject JSONObject

Introduction

In this page you can find the example usage for org.json JSONObject JSONObject.

Prototype

public JSONObject(String source) throws JSONException 

Source Link

Document

Construct a JSONObject from a source JSON text string.

Usage

From source file:abelymiguel.miralaprima.GetPrima.java

/**
 * Processes requests for both HTTP//from   w  w w .j a  v  a 2s  . c  om
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        _con = Utils.getConnection();
        _stmt = _con.createStatement();

    } catch (URISyntaxException ex) {
        Logger.getLogger(GetPrima.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(GetPrima.class.getName()).log(Level.SEVERE, null, ex);
    }
    PrintWriter out = response.getWriter();
    response.setContentType("text/javascript;charset=UTF-8");

    String country_code;
    country_code = request.getParameter("country_code");

    JSONObject jsonObject;
    JSONArray jsonArray;
    String json_str;
    if (country_code != null) {
        jsonObject = new JSONObject(this.getCountry(country_code));
        json_str = jsonObject.toString();
    } else {
        jsonArray = new JSONArray(this.getAllCountries());
        json_str = jsonArray.toString();
    }

    String jsonpCallback = request.getParameter("callback");
    if (jsonpCallback != null) {
        out.write(jsonpCallback + "(" + json_str + ")");
    } else {
        out.println(json_str);
    }
    try {
        _con.close();
        _stmt.close();
        _rs.close();
    } catch (SQLException ex) {
        Logger.getLogger(GetPrima.class.getName()).log(Level.SEVERE, null, ex);
    }
    out.close();
}

From source file:at.alladin.rmbt.db.QoSTestObjective.java

@SuppressWarnings("unchecked")
public String toHtml() {
    StringBuilder sb = new StringBuilder();
    sb.append("<h3>QoS-Test (uid: " + getUid() + ", test_class: " + getTestClass() + ")</h3>");
    if (getObjective() != null) {
        try {//www.j a v  a 2  s.  c o m
            JSONObject objectives = new JSONObject(getObjective());
            Iterator<String> keys = objectives.keys();
            sb.append("<b>Test objectives (as plain text):</b> <ul>");
            while (keys.hasNext()) {
                String key = keys.next();
                sb.append("<li><i>" + key + "</i>: " + objectives.optString(key) + "</li>");
            }
            sb.append("</ul>");
            sb.append("<b>Test objectives (as hstore representation):</b> "
                    + Helperfunctions.json2hstore(objectives, null) + "<br><br>");
            if (testSummary != null) {
                sb.append("<b>Test summary (test_summary):</b> <a href=\"#"
                        + testSummary.replaceAll("[\\-\\+\\.\\^:,]", "_") + "\">" + testSummary
                        + "</a><br><br>");
            } else {
                sb.append("<b>Test summary (test_summary):</b> <i>NULL</i><br><br>");
            }
            if (testDescription != null) {
                sb.append("<b>Test description (test_desc):</b> <a href=\"#"
                        + testDescription.replaceAll("[\\-\\+\\.\\^:,]", "_") + "\">" + testDescription
                        + "</a><br><br>");
            } else {
                sb.append("<b>Test description (test_desc):</b> <i>NULL</i><br><br>");
            }
        } catch (JSONException e) {
            sb.append(
                    "<b><i>incorrect test objectives format:</i></b><ul><li>" + getObjective() + "</li></ul>");
            e.printStackTrace();
        }
    } else {
        sb.append("<b><i>no objectives set for this test</i></b>");
    }

    sb.append("<b>Expected test results (as hstore representation):</b><ul>");
    if (getResults() != null) {
        JSONArray resultsJson;
        try {
            resultsJson = new JSONArray(getResults());
            for (int i = 0; i < resultsJson.length(); i++) {
                try {
                    final JSONObject expected = resultsJson.getJSONObject(i);
                    sb.append("<li>" + Helperfunctions.json2htmlWithLinks(expected) + "</li>");
                } catch (Exception e) {
                    e.printStackTrace();
                    sb.append("<li>incorrect expected test result format</li>");
                }
            }
        } catch (JSONException e1) {
            sb.append("<li>incorrect expected test result format</li>");
        }
    } else {
        sb.append("<li><i>No expected results set for this test</i></li>");
    }
    sb.append("</ul>");
    return sb.toString();
}

From source file:abelymiguel.miralaprima.SetMoza.java

/**
 * Processes requests for both HTTP/*w  w  w .j av a  2  s.  c om*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    try {
        _con = Utils.getConnection();
        _stmt = _con.createStatement();
    } catch (URISyntaxException ex) {
        Logger.getLogger(GetMoza.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(GetMoza.class.getName()).log(Level.SEVERE, null, ex);
    }

    PrintWriter out = null;
    try {
        out = response.getWriter();
    } catch (IOException ex) {
        Logger.getLogger(GetMoza.class.getName()).log(Level.SEVERE, null, ex);
    }
    response.setContentType("text/javascript;charset=UTF-8");

    String url_moza;
    url_moza = request.getParameter("url_moza");

    String country_code;
    country_code = request.getParameter("country_code");

    if (country_code == null) {
        country_code = "ALL";
    }

    JSONObject jsonObject;
    String json_str;

    jsonObject = new JSONObject(this.setMozaInDB(url_moza, country_code));
    json_str = jsonObject.toString();

    String jsonpCallback = request.getParameter("callback");
    if (jsonpCallback != null) {
        out.write(jsonpCallback + "(" + json_str + ")");
    } else {
        out.println(json_str);
    }
    try {
        _con.close();
        _stmt.close();
    } catch (SQLException ex) {
        Logger.getLogger(SetMoza.class.getName()).log(Level.SEVERE, null, ex);
    }
    out.close();
}

From source file:at.tugraz.ist.catroid.web.ServerCalls.java

public String uploadProject(String projectName, String projectDescription, String zipFileString,
        String userEmail, String language, String token) throws WebconnectionException {
    if (emailForUiTests != null) {
        userEmail = emailForUiTests;/* w ww .java 2  s  .  c o m*/
    }
    try {
        String md5Checksum = Utils.md5Checksum(new File(zipFileString));

        HashMap<String, String> postValues = new HashMap<String, String>();
        postValues.put(PROJECT_NAME_TAG, projectName);
        postValues.put(PROJECT_DESCRIPTION_TAG, projectDescription);
        postValues.put(USER_EMAIL, userEmail);
        postValues.put(PROJECT_CHECKSUM_TAG, md5Checksum.toLowerCase());
        postValues.put(Constants.TOKEN, token);

        if (language != null) {
            postValues.put(USER_LANGUAGE, language);
        }
        String serverUrl = useTestUrl ? TEST_FILE_UPLOAD_URL : FILE_UPLOAD_URL;

        Log.v(TAG, "url to upload: " + serverUrl);
        resultString = connection.doHttpPostFileUpload(serverUrl, postValues, FILE_UPLOAD_TAG, zipFileString);

        JSONObject jsonObject = null;
        int statusCode = 0;

        Log.v(TAG, "result string: " + resultString);

        jsonObject = new JSONObject(resultString);
        statusCode = jsonObject.getInt("statusCode");
        String serverAnswer = jsonObject.getString("answer");

        if (statusCode == 200) {
            return serverAnswer;
        } else {
            throw new WebconnectionException(statusCode, serverAnswer);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new WebconnectionException(WebconnectionException.ERROR_JSON);
    } catch (IOException e) {
        e.printStackTrace();
        throw new WebconnectionException(WebconnectionException.ERROR_NETWORK);
    }
}

From source file:at.tugraz.ist.catroid.web.ServerCalls.java

public boolean checkToken(String token) throws WebconnectionException {
    try {/* www. j av  a  2s  .  com*/
        HashMap<String, String> postValues = new HashMap<String, String>();
        postValues.put(Constants.TOKEN, token);

        String serverUrl = useTestUrl ? TEST_CHECK_TOKEN_URL : CHECK_TOKEN_URL;

        Log.v(TAG, "url to upload: " + serverUrl);
        resultString = connection.doHttpPost(serverUrl, postValues);

        JSONObject jsonObject = null;
        int statusCode = 0;

        Log.v(TAG, "result string: " + resultString);

        jsonObject = new JSONObject(resultString);
        statusCode = jsonObject.getInt("statusCode");
        String serverAnswer = jsonObject.optString("answer");

        if (statusCode == SERVER_RESPONSE_TOKEN_OK) {
            return true;
        } else {
            throw new WebconnectionException(statusCode, serverAnswer);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new WebconnectionException(WebconnectionException.ERROR_JSON);
    } catch (IOException e) {
        e.printStackTrace();
        throw new WebconnectionException(WebconnectionException.ERROR_NETWORK);
    }
}

From source file:at.tugraz.ist.catroid.web.ServerCalls.java

public boolean registerOrCheckToken(String username, String password, String userEmail, String language,
        String country, String token) throws WebconnectionException {
    if (emailForUiTests != null) {
        userEmail = emailForUiTests;//from  w ww .  j  ava  2 s  .  co m
    }
    try {

        HashMap<String, String> postValues = new HashMap<String, String>();
        postValues.put(REG_USER_NAME, username);
        postValues.put(REG_USER_PASSWORD, password);
        postValues.put(REG_USER_EMAIL, userEmail);
        postValues.put(Constants.TOKEN, token);

        if (country != null) {
            postValues.put(REG_USER_COUNTRY, country);
        }
        if (language != null) {
            postValues.put(REG_USER_LANGUAGE, language);
        }
        String serverUrl = useTestUrl ? TEST_REGISTRATION_URL : REGISTRATION_URL;

        Log.v(TAG, "url to use: " + serverUrl);
        resultString = connection.doHttpPost(serverUrl, postValues);

        JSONObject jsonObject = null;
        int statusCode = 0;

        Log.v(TAG, "result string: " + resultString);

        jsonObject = new JSONObject(resultString);
        statusCode = jsonObject.getInt("statusCode");
        String serverAnswer = jsonObject.optString("answer");

        boolean registered;
        if (statusCode == SERVER_RESPONSE_TOKEN_OK) {
            registered = false;
        } else if (statusCode == SERVER_RESPONSE_REGISTER_OK) {
            registered = true;
        } else {
            throw new WebconnectionException(statusCode, serverAnswer);
        }
        return registered;
    } catch (JSONException e) {
        e.printStackTrace();
        throw new WebconnectionException(WebconnectionException.ERROR_JSON);
    } catch (IOException e) {
        e.printStackTrace();
        throw new WebconnectionException(WebconnectionException.ERROR_NETWORK);
    }
}

From source file:com.google.cast.samples.tictactoe.GameChannel.java

/**
 * Processes all Text messages received from the receiver device and performs the appropriate
 * action for the message. Recognizable messages are of the form:
 *
 * <ul>// ww w.  j a  v  a 2 s.  c o m
 * <li> KEY_JOINED: a player joined the current game
 * <li> KEY_MOVED: a player made a move
 * <li> KEY_ENDGAME: the game has ended in one of the END_STATE_* states
 * <li> KEY_ERROR: a game error has occurred
 * <li> KEY_BOARD_LAYOUT_RESPONSE: the board has been laid out in some new configuration
 * </ul>
 *
 * <p>No other messages are recognized.
 */
@Override
public void onMessageReceived(CastDevice castDevice, String namespace, String message) {
    try {
        Log.d(TAG, "onTextMessageReceived: " + message);
        JSONObject payload = new JSONObject(message);
        Log.d(TAG, "payload: " + payload);
        if (payload.has(KEY_EVENT)) {
            String event = payload.getString(KEY_EVENT);
            if (KEY_JOINED.equals(event)) {
                Log.d(TAG, "JOINED");
                try {
                    String player = payload.getString(KEY_PLAYER);
                    String opponentName = payload.getString(KEY_OPPONENT);
                    onGameJoined(player, opponentName);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (KEY_MOVED.equals(event)) {
                Log.d(TAG, "MOVED");
                try {
                    String player = payload.getString(KEY_PLAYER);
                    int row = payload.getInt(KEY_ROW);
                    int column = payload.getInt(KEY_COLUMN);
                    boolean isGameOver = payload.getBoolean(KEY_GAME_OVER);
                    onGameMove(player, row, column, isGameOver);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (KEY_ENDGAME.equals(event)) {
                Log.d(TAG, "ENDGAME");
                try {
                    String endState = payload.getString(KEY_END_STATE);
                    int winningLocation = -1;
                    if (END_STATE_ABANDONED.equals(endState) == false) {
                        winningLocation = payload.getInt(KEY_WINNING_LOCATION);
                    }
                    onGameEnd(endState, winningLocation);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (KEY_ERROR.equals(event)) {
                Log.d(TAG, "ERROR");
                try {
                    String errorMessage = payload.getString(KEY_MESSAGE);
                    onGameError(errorMessage);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (KEY_BOARD_LAYOUT_RESPONSE.equals(event)) {
                Log.d(TAG, "Board Layout");
                int[][] boardLayout = new int[3][3];
                try {
                    JSONArray boardJSONArray = payload.getJSONArray(KEY_BOARD);
                    for (int i = 0; i < 3; ++i) {
                        for (int j = 0; j < 3; ++j) {
                            boardLayout[i][j] = boardJSONArray.getInt(i * 3 + j);
                        }
                    }
                    onGameBoardLayout(boardLayout);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } else {
            Log.w(TAG, "Unknown payload: " + payload);
        }
    } catch (JSONException e) {
        Log.w(TAG, "Message doesn't contain an expected key.", e);
    }
}

From source file:com.tatsuowatanabe.funukulelequiz.util.Purchase.java

public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException {
    mItemType = itemType;/*from w  w w .j av  a2 s  .co m*/
    mOriginalJson = jsonPurchaseInfo;
    JSONObject o = new JSONObject(mOriginalJson);
    mOrderId = o.optString("orderId");
    mPackageName = o.optString("packageName");
    mSku = o.optString("productId");
    mPurchaseTime = o.optLong("purchaseTime");
    mPurchaseState = o.optInt("purchaseState");
    mDeveloperPayload = o.optString("developerPayload");
    mToken = o.optString("token", o.optString("purchaseToken"));
    mIsAutoRenewing = o.optBoolean("autoRenewing");
    mSignature = signature;
}

From source file:com.weibo.net.Oauth2AccessToken.java

public Oauth2AccessToken(String rltString) {
    // { "access_token":"SlAV32hkKG", "expires_in":3600, "refresh_token":"8xLOxBtZp8" } 
    if (rltString != null) {
        if (rltString.indexOf("{") >= 0) {
            try {
                JSONObject json = new JSONObject(rltString);
                setToken(json.optString("access_token"));
                setExpiresIn(json.optInt("expires_in"));
                setRefreshToken(json.optString("refresh_token"));
            } catch (JSONException e) {
                //??
            }/* ww w.ja  v  a2  s.  c  o m*/
        }
    }
}

From source file:de.lespace.apprtc.firebase.MyFirebaseMessagingService.java

/**
 * Called when message is received./*from ww w.ja va  2s . c  o  m*/
 *
 * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
 */
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    JSONObject jsonData = new JSONObject(remoteMessage.getData());
    Log.d(TAG, "calldata: " + jsonData.toString());

    Intent intent = new Intent(this, SignalingService.class);
    intent.putExtra(RTCConnection.EXTRA_SIGNALING_REGISTRATION, "true");
    intent.putExtra(RTCConnection.EXTRA_FROM, remoteMessage.getData().get("toUUID"));
    startService(intent);

    //Start Registration
    Log.d(TAG, "we should call to:" + remoteMessage.getData().get("fromUUID") + " but callto 'chrome' now!");
    Intent connectIntent = new Intent(getApplicationContext(), IncomingCall.class);
    String to = "chrome";
    RTCConnection.from = remoteMessage.getData().get("toUUID");
    RTCConnection.to = to;
    RTCConnection.initiator = true;
    /*
    connectIntent.putExtra(RTCConnection.EXTRA_TO, to);
    connectIntent.putExtra(RTCConnection.EXTRA_FROM, remoteMessage.getData().get("toUUID"));
    connectIntent.putExtra(RTCConnection.EXTRA_INITIATOR, true);*/
    connectIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(connectIntent);

}