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:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java

/**
 * Send HTTP request using {@link HttpURLConnection} in JSON format.
 * /*  w w w .j a  va 2 s. c om*/
 * @param endPoint String End point URL.
 * @param httpMethod String HTTP method type (POST, PUT)
 * @param headersMap Map<String, String> Headers need to send to the end point.
 * @param fileName File name of the attachment to set as binary content.
 * @return RestResponse object.
 * @throws JSONException
 * @throws IOException
 */
protected RestResponse<JSONObject> sendBinaryContentForJsonResponse(String endPoint, String httpMethod,
        Map<String, String> headersMap, String fileName) throws IOException, JSONException {

    HttpURLConnection httpConnection = writeRequest(endPoint, httpMethod, RestResponse.JSON_TYPE, headersMap,
            fileName, true);

    String responseString = readResponse(httpConnection);

    RestResponse<JSONObject> restResponse = new RestResponse<JSONObject>();
    restResponse.setHttpStatusCode(httpConnection.getResponseCode());
    restResponse.setHeadersMap(httpConnection.getHeaderFields());

    if (responseString != null) {
        JSONObject jsonObject = null;
        if (isValidJSON(responseString)) {
            jsonObject = new JSONObject(responseString);
        } else {
            jsonObject = new JSONObject();
            jsonObject.put("output", responseString);
        }

        restResponse.setBody(jsonObject);
    }

    return restResponse;
}

From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java

/**
 * Send HTTPS request using {@link HttpsURLConnection} in JSON format.
 * //from  www  .  jav  a 2  s .  c  o m
 * @param endPoint String End point URL.
 * @param httpsMethod String HTTPS method type (POST, PUT)
 * @param headersMap Map<String, String> Headers need to send to the end point.
 * @param fileName File name of the attachment to set as binary content.
 * @return RestResponse object.
 * @throws JSONException
 * @throws IOException
 */
protected RestResponse<JSONObject> sendBinaryContentForJsonResponseHTTPS(String endPoint, String httpMethod,
        Map<String, String> headersMap, String fileName) throws IOException, JSONException {

    HttpsURLConnection httpsConnection = writeRequestHTTPS(endPoint, httpMethod, RestResponse.JSON_TYPE,
            headersMap, fileName, true);

    String responseString = readResponse(httpsConnection);

    RestResponse<JSONObject> restResponse = new RestResponse<JSONObject>();
    restResponse.setHttpStatusCode(httpsConnection.getResponseCode());
    restResponse.setHeadersMap(httpsConnection.getHeaderFields());

    if (responseString != null) {
        JSONObject jsonObject = null;
        if (isValidJSON(responseString)) {
            jsonObject = new JSONObject(responseString);
        } else {
            jsonObject = new JSONObject();
            jsonObject.put("output", responseString);
        }

        restResponse.setBody(jsonObject);
    }

    return restResponse;
}

From source file:com.mboarder.util.Translate.java

/**
 * Forms an HTTP request and parses the response for a translation.
 *
 * @param text The String to translate.//from  ww w.  j av a 2 s  .c o  m
 * @param from The language code to translate from.
 * @param to The language code to translate to.
 * @return The translated String.
 * @throws Exception
 */
private static String retrieveTranslation(String text, String from, String to) throws Exception {
    try {
        StringBuilder url = new StringBuilder();
        url.append(URL_STRING).append(from).append("%7C").append(to);
        url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING));

        Log.d(TAG, "Connecting to " + url.toString());
        HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
        uc.setDoInput(true);
        uc.setDoOutput(true);
        try {
            Log.d(TAG, "getInputStream()");
            InputStream is = uc.getInputStream();
            String result = toString(is);

            JSONObject json = new JSONObject(result);
            return ((JSONObject) json.get("responseData")).getString("translatedText");
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();
            if (uc.getErrorStream() != null)
                uc.getErrorStream().close();
        }
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:com.comcast.cns.controller.CNSSetTopicAttributesAction.java

@Override
public boolean doAction(User user, AsyncContext asyncContext) throws Exception {

    HttpServletRequest request = (HttpServletRequest) asyncContext.getRequest();
    HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();

    String userId = user.getUserId();
    String attributeName = request.getParameter("AttributeName");
    String attributeValue = request.getParameter("AttributeValue");
    String topicArn = request.getParameter("TopicArn");

    if ((userId == null) || (topicArn == null) || (attributeName == null) || (attributeValue == null)) {
        logger.error("event=cns_set_topic_attributes error_code=InvalidParameters attribute_name="
                + attributeName + " attribute_value=" + attributeValue + " topic_arn=" + topicArn + " user_id="
                + userId);/*  w ww. j a  v  a  2  s.  c  o m*/
        throw new CMBException(CNSErrorCodes.CNS_InvalidParameter, "missing parameters");
    }

    CNSTopicAttributes topicAttributes = new CNSTopicAttributes();

    if (attributeName.equals("DeliveryPolicy")) {

        JSONObject json = new JSONObject(attributeValue);
        CNSTopicDeliveryPolicy deliveryPolicy = new CNSTopicDeliveryPolicy(json);
        topicAttributes.setDeliveryPolicy(deliveryPolicy);
        logger.debug("event=cns_set_topic_delivery_policy topic_arn=" + topicArn + " value="
                + topicAttributes.getEffectiveDeliveryPolicy());

    } else if (attributeName.equals("Policy")) {

        // validate policy before updating

        try {
            new CMBPolicy(attributeValue);
        } catch (Exception ex) {
            logger.warn("event=invalid_policy topic_arn=" + topicArn + " policy=" + attributeValue, ex);
            throw ex;
        }

        topicAttributes.setPolicy(attributeValue);
        logger.debug(
                "event=cns_set_topic_policy topic_arn=" + topicArn + "  value=" + topicAttributes.getPolicy());

    } else if (attributeName.equals("DisplayName")) {

        if (validateDisplayName(attributeValue)) {
            topicAttributes.setDisplayName(attributeValue);
            logger.debug(
                    "event=cns_set_topic_display_name topic_arn=" + topicArn + "  value=" + attributeValue);
        } else {
            throw new CMBException(CNSErrorCodes.CNS_InvalidParameter, "Bad Display Name");
        }

    } else {
        logger.error("event=cns_set_topic_attributes error_code=InvalidParameters attribute_name="
                + attributeName + " attribute_value=" + attributeValue + " topic_arn=" + topicArn + " user_id="
                + userId);
        throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,
                "AttributeName: " + attributeName + " is not a valid value");
    }

    PersistenceFactory.getCNSAttributePersistence().setTopicAttributes(topicAttributes, topicArn);
    String out = CNSAttributePopulator.getSetTopicAttributesResponse();
    logger.debug("event=cns_set_topic_attributes attribute_name=" + attributeName + " attribute_value="
            + attributeValue + " topic_arn=" + topicArn + " user_id=" + userId);
    writeResponse(out, response);
    return true;
}

From source file:com.geecko.QuickLyric.tasks.IdDecoder.java

@Override
protected Lyrics doInBackground(String... strings) {
    String url = strings[0];/*  w  w w  .java 2  s.c o  m*/
    String artist;
    String track;
    if (url.contains("//www.soundhound.com/")) {
        try { // todo switch to Jsoup
            String html = getUrlAsString(url);
            int preceding = html.indexOf("root.App.trackDa") + 19;
            int following = html.substring(preceding).indexOf(";");
            String data = html.substring(preceding, preceding + following);
            JSONObject jsonData = new JSONObject(data);
            artist = jsonData.getString("artist_display_name");
            track = jsonData.getString("track_name");
        } catch (IOException | JSONException e) {
            e.printStackTrace();
            return new Lyrics(ERROR);
        }

    } else if (url.contains("//shz.am/")) {
        try {
            Document doc = Jsoup.connect(url.trim()).get();
            track = doc.getElementsByAttribute("data-track-title").text();
            artist = doc.getElementsByAttribute("data-track-artist").text();
        } catch (IOException e) {
            e.printStackTrace();
            return new Lyrics(ERROR);
        }
    } else if (url.contains("//play.google.com/store/music/")) {
        String docID = url.substring(url.indexOf("&tid=") + 5);
        try {
            Document doc = Jsoup.connect(url).get();
            Element playCell = doc.getElementsByAttributeValue("data-track-docid", docID).get(0);
            artist = doc.getElementsByClass("primary").text();
            track = playCell.parent().parent().child(1).getElementsByClass("title").text();
        } catch (IOException e) {
            e.printStackTrace();
            return new Lyrics(ERROR);
        }
    } else
        return new Lyrics(ERROR);
    Lyrics res = new Lyrics(Lyrics.SEARCH_ITEM);
    res.setArtist(artist);
    res.setTitle(track);
    return res;
}

From source file:org.wso2.app.catalog.services.DynamicClientManager.java

/**
 * This method is used to send requests to backend.
 * The reason to use this method because the function which is already
 * available for sending requests is secured with token. Therefor this can be used
 * to send requests without tokens./*from   ww w.j  a  v a 2  s .c  om*/
 */
private void sendRequest(final EndPointInfo endPointInfo, final APIResultCallBack apiResultCallback,
        final int requestCode) {
    RequestQueue queue = null;
    int requestMethod = 0;
    org.wso2.emm.agent.proxy.utils.Constants.HTTP_METHODS httpMethod = endPointInfo.getHttpMethod();
    switch (httpMethod) {
    case POST:
        requestMethod = Request.Method.POST;
        break;
    case DELETE:
        requestMethod = Request.Method.DELETE;
        break;
    }

    try {
        queue = ServerUtilities.getCertifiedHttpClient();
    } catch (IDPTokenManagerException e) {
        Log.e(TAG, "Failed to retrieve HTTP client", e);
    }

    JsonObjectRequest request = null;
    try {
        request = new JsonObjectRequest(requestMethod, endPointInfo.getEndPoint(),
                (endPointInfo.getRequestParams() != null) ? new JSONObject(endPointInfo.getRequestParams())
                        : null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d(TAG, error.toString());
                    }
                })

        {
            @Override
            protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
                String result = new String(response.data);
                if (org.wso2.emm.agent.proxy.utils.Constants.DEBUG_ENABLED) {
                    if (result != null && !result.isEmpty()) {
                        Log.d(TAG, "Result :" + result);
                    }
                }
                Map<String, String> responseParams = new HashMap<>();
                responseParams.put(org.wso2.emm.agent.proxy.utils.Constants.SERVER_RESPONSE_BODY, result);
                responseParams.put(org.wso2.emm.agent.proxy.utils.Constants.SERVER_RESPONSE_STATUS,
                        String.valueOf(response.statusCode));
                if (apiResultCallback != null) {
                    apiResultCallback.onReceiveAPIResult(responseParams, requestCode);
                }
                return super.parseNetworkResponse(response);
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                headers.put("Accept", "application/json");
                headers.put("User-Agent", Constants.USER_AGENT);
                if (endPointInfo.getHeader() != null && !endPointInfo.getHeader().trim().isEmpty()) {
                    headers.put("Authorization", endPointInfo.getHeader().trim());
                }
                return headers;
            }
        };
    } catch (JSONException e) {
        Log.e(TAG, "Failed to parse request JSON", e);
    }

    queue.add(request);
}

From source file:com.mobeelizer.mobile.android.types.FileFieldTypeHelper.java

@Override
protected void setNotNullValueFromMapToDatabase(final ContentValues values, final String value,
        final MobeelizerFieldAccessor field, final Map<String, String> options,
        final MobeelizerErrorsBuilder errors) {
    try {//  w  w  w.ja va  2  s .  co m
        JSONObject json = new JSONObject(value);
        values.put(field.getName() + _GUID, json.getString(JSON_GUID));
        values.put(field.getName() + _NAME, json.getString(JSON_NAME));
    } catch (JSONException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:org.catnut.fragment.TransientUsersFragment.java

private Response<List<TransientUser>> parseNetworkResponse(NetworkResponse response) {
    try {/*ww w.java2  s.  com*/
        String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        JSONObject result = new JSONObject(jsonString);
        // set next_cursor
        mNext_cursor = result.optInt(User.next_cursor);
        mTotal_number = result.optInt(User.total_number);
        JSONArray array = result.optJSONArray(User.MULTIPLE);
        if (array != null) {
            List<TransientUser> users = new ArrayList<TransientUser>(array.length());
            for (int i = 0; i < array.length(); i++) {
                users.add(TransientUser.convert(array.optJSONObject(i)));
            }
            return Response.success(users, HttpHeaderParser.parseCacheHeaders(response));
        } else {
            throw new RuntimeException("no users found!");
        }
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    } catch (Exception ex) {
        return Response.error(new ParseError(ex));
    }
}

From source file:uk.co.senab.photup.LoginActivity.java

private void saveFacebookSession() {
    AsyncFacebookRunner fbRunner = new AsyncFacebookRunner(mFacebook);
    fbRunner.request("me", new RequestListener() {

        public void onComplete(String response, Object state) {
            try {
                JSONObject object = new JSONObject(response);
                String id = object.getString("id");
                String name = object.getString("name");

                Session session = new Session(mFacebook, id, name);
                session.save(getApplicationContext());

                setResult(RESULT_OK);//from  w w  w. jav a  2  s.  com
                finish();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        public void onFacebookError(FacebookError e, Object state) {
            e.printStackTrace();
        }

        public void onFileNotFoundException(FileNotFoundException e, Object state) {
            e.printStackTrace();
        }

        public void onIOException(IOException e, Object state) {
            e.printStackTrace();
        }

        public void onMalformedURLException(MalformedURLException e, Object state) {
            e.printStackTrace();
        }
    });
}

From source file:com.freecast.LudoCast.MainActivity.java

private void setupCastListener() {

    mCastConsumer = new VideoCastConsumerImpl() {

        @Override/*www .  j  a  v  a2  s  . co  m*/
        public void onApplicationConnected(ApplicationMetadata appMetadata, String sessionId,
                boolean wasLaunched) {

            System.out.println("onApplicationConnected message = " + sessionId);

            Toast.makeText(MainActivity.this, "Device is Ready to Start Game!!!", Toast.LENGTH_SHORT).show();

            mAppConnected = true;
            try {
                Thread.currentThread().sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (mAppConnected) {
                Createbnt.setEnabled(true);
                Createbnt.setText("Start Game");
            } else {
                Createbnt.setEnabled(false);
                Createbnt.setText("Disconnected");
            }

        }

        @Override
        public void onConnected() {

            System.out.println("MainActivity onConnected ");
            Createbnt.setText("Connecting");

        }

        @Override
        public void onDisconnected() {

            System.out.println("onDisconnected message ");

            mAppConnected = false;

            if (mAppConnected) {
                Createbnt.setEnabled(true);
                Createbnt.setText("Start Game");
            } else {
                Createbnt.setEnabled(false);
                Createbnt.setText("Disconnected");
            }

        }

        @Override
        public void onFailed(int resourceId, int statusCode) {

            System.out.println("onFailed message = " + statusCode);

            mAppConnected = false;

            if (mAppConnected) {
                Createbnt.setEnabled(true);
                Createbnt.setText("Start Game");
            } else {
                Createbnt.setEnabled(false);
                Createbnt.setText("Disconnected");
            }

        }

        @Override
        public void onApplicationDisconnected(int errorCode) {

            System.out.println("onApplicationDisconnected message = " + errorCode);

            mAppConnected = false;

            if (mAppConnected) {
                Createbnt.setEnabled(true);
                Createbnt.setText("Start Game");
            } else {
                Createbnt.setEnabled(false);
                Createbnt.setText("Disconnected");
            }

        }

        @Override
        public boolean onApplicationConnectionFailed(int errorCode) {

            System.out.println("onApplicationConnectionFailed message = " + errorCode);

            mAppConnected = false;

            if (mAppConnected) {
                Createbnt.setEnabled(true);
                Createbnt.setText("Start Game");
            } else {
                Createbnt.setEnabled(false);
                Createbnt.setText("Disconnected");
            }

            return true;
        }

        @Override
        public void onDataMessageReceived(String message) {

            JSONObject obj = null;
            try {
                obj = new JSONObject(message);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            String command = null;
            try {
                command = obj.getString("command");
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            if (command.equals("connect_reply")) {
                boolean ret = false;
                try {
                    ret = obj.getBoolean("ret");
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                if (ret == false) {
                    String reason = null;
                    try {
                        reason = obj.getString("error");
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Log.d(TAG, "error info: " + reason);
                    Toast.makeText(MainActivity.this, "Fail to connect Ludo Server !!!!", Toast.LENGTH_SHORT)
                            .show();

                } else {
                    connectstatus = true;
                    CreateConfigGame(message);
                }

            }

            try {
                protocol.parseMessage(message);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("MainActivity receiver message = " + message);
        }

        @Override
        public void onConnectionSuspended(int cause) {
            Log.d(TAG, "onConnectionSuspended() was called with cause: " + cause);
            com.freecast.LudoCast.Utils.showToast(MainActivity.this, R.string.connection_temp_lost);
        }

        @Override
        public void onConnectivityRecovered() {
            com.freecast.LudoCast.Utils.showToast(MainActivity.this, R.string.connection_recovered);
        }

        @Override
        public void onCastDeviceDetected(final RouteInfo info) {
            if (!CastPreference.isFtuShown(MainActivity.this)) {
                CastPreference.setFtuShown(MainActivity.this);

                Log.d(TAG, "Route is visible: " + info);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        if (mediaRouteMenuItem.isVisible()) {
                            Log.d(TAG, "Cast Icon is visible: " + info.getName());
                        }
                    }
                }, 1000);
            }
        }
    };

}