Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

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

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:org.wso2.carbon.identity.agent.outbound.server.UserStoreServerEndpoint.java

/**
 * Process response message and send to response queue.
 * @param message Message//from  www .  jav  a  2  s. c o m
 */
private void processResponse(String message) {

    JMSConnectionFactory connectionFactory = new JMSConnectionFactory();
    Connection connection = null;
    MessageProducer producer;
    try {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Start processing response message: " + message);
        }
        MessageBrokerConfig conf = ServerConfigurationBuilder.build().getMessagebroker();
        connectionFactory.createActiveMQConnectionFactory(conf.getUrl());
        connection = connectionFactory.createConnection();
        connectionFactory.start(connection);
        javax.jms.Session session = connectionFactory.createSession(connection);
        Destination responseQueue = connectionFactory.createQueueDestination(session,
                UserStoreConstants.QUEUE_NAME_RESPONSE);
        producer = connectionFactory.createMessageProducer(session, responseQueue, DeliveryMode.NON_PERSISTENT);
        producer.setTimeToLive(UserStoreConstants.QUEUE_SERVER_MESSAGE_LIFETIME);

        JSONObject resultObj = new JSONObject(message);
        String responseData = resultObj.get(UserStoreConstants.UM_JSON_ELEMENT_RESPONSE_DATA).toString();
        String correlationId = (String) resultObj
                .get(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA_CORRELATION_ID);

        UserOperation responseOperation = new UserOperation();
        responseOperation.setCorrelationId(correlationId);
        responseOperation.setResponseData(responseData.toString());

        ObjectMessage responseMessage = session.createObjectMessage();
        responseMessage.setObject(responseOperation);
        responseMessage.setJMSCorrelationID(correlationId);
        producer.send(responseMessage);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Finished processing response message: " + message);
        }
    } catch (JMSException e) {
        LOGGER.error("Error occurred while sending message: " + message, e);
    } catch (JSONException e) {
        LOGGER.error("Error occurred while reading json payload of message: " + message, e);
    } catch (JMSConnectionException e) {
        LOGGER.error("Error occurred while creating JMS connection to send message: " + message, e);
    } finally {
        try {
            connectionFactory.closeConnection(connection);
        } catch (JMSConnectionException e) {
            LOGGER.error("Error occurred while closing JMS connection", e);
        }
    }
}

From source file:com.ecofactor.qa.automation.newapp.service.DataServiceImpl.java

/**
 * Checks if is sPO block active./*  www.  j  av a2 s  . co  m*/
 * 
 * @param thermostatId
 *            the thermostat id
 * @param algoId
 *            the algo id
 * @return true, if is sPO block active
 * @see com.ecofactor.qa.automation.algorithm.service.SPODataService#isSPOBlockActive(java.lang.Integer,
 *      int)
 */
@Override
public boolean isSPOBlockActive(Integer thermostatId, int algoId) {

    DriverConfig.setLogString("Check SPO is Active Now for Thermostat Id :" + thermostatId, true);
    boolean isSPOActive = false;
    Calendar currentTime = DateUtil.getUTCCalendar();
    JSONArray jsonArray = getJobData(thermostatId);
    boolean isDataChanged = false;
    for (int i = 0; i < jsonArray.length(); i++) {
        try {
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            Calendar startCal = DateUtil.getUTCTimeZoneCalendar((String) jsonObj.get("start"));
            Calendar endcal = DateUtil.getUTCTimeZoneCalendar((String) jsonObj.get("end"));
            int endHour = endcal.get(Calendar.HOUR_OF_DAY);
            int startHour = startCal.get(Calendar.HOUR_OF_DAY);
            if (isDataChanged) {
                startCal.set(Calendar.DATE, startCal.get(Calendar.DATE) + 1);
                endcal.set(Calendar.DATE, endcal.get(Calendar.DATE) + 1);
            }
            if (startHour > endHour) {
                endcal.set(Calendar.DATE, endcal.get(Calendar.DATE) + 1);
                isDataChanged = true;
            }
            DriverConfig.setLogString("startCal :" + DateUtil.format(startCal, DateUtil.DATE_FMT_FULL_TZ),
                    true);
            DriverConfig.setLogString("endcal :" + DateUtil.format(endcal, DateUtil.DATE_FMT_FULL_TZ), true);
            if (currentTime.after(startCal) && currentTime.before(endcal)) {
                isSPOActive = true;
                break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return isSPOActive;
}

From source file:eu.codeplumbers.cosi.services.CosiSmsService.java

private List<Sms> getRemoteMessages() {
    allSms.clear();/*w ww.jav a2  s  .  c om*/
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new SmsSyncEvent(SYNC_MESSAGE, "Your Cozy has no Text messages stored."));
                Sms.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    mBuilder.setProgress(jsonArray.length(), i, false);
                    mNotifyManager.notify(notification_id, mBuilder.build());
                    EventBus.getDefault()
                            .post(new SmsSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_cozy)));

                    JSONObject smsJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Sms sms = Sms.getBySystemIdAddressAndBody(smsJson.get("systemId").toString(),
                            smsJson.getString("address"), smsJson.getString("body"));
                    if (sms == null) {
                        sms = new Sms(smsJson);
                    } else {
                        sms.setRemoteId(smsJson.getString("_id"));
                        sms.setSystemId(smsJson.getString("systemId"));
                        sms.setAddress(smsJson.getString("address"));
                        sms.setBody(smsJson.getString("body"));

                        if (smsJson.has("readState")) {
                            sms.setReadState(smsJson.getBoolean("readState"));
                        }

                        sms.setDateAndTime(smsJson.getString("dateAndTime"));
                        sms.setType(smsJson.getInt("type"));
                    }

                    sms.save();

                    allSms.add(sms);
                }
            }
        } else {
            errorMessage = "Failed to parse API response";
            EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, "Failed to parse API response"));
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        errorMessage = e.getLocalizedMessage();
    } catch (ProtocolException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (IOException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (JSONException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    }
    return allSms;
}

From source file:com.soomla.store.domain.virtualGoods.UpgradeVG.java

/**
 * see parent/*w w w  . j  av a2s  .  c o m*/
 */
@Override
public JSONObject toJSONObject() {
    JSONObject parentJsonObject = super.toJSONObject();
    JSONObject jsonObject = new JSONObject();
    try {
        Iterator<?> keys = parentJsonObject.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            jsonObject.put(key, parentJsonObject.get(key));
        }

        jsonObject.put(JSONConsts.VGU_GOOD_ITEMID, mGoodItemId);
        jsonObject.put(JSONConsts.VGU_PREV_ITEMID, TextUtils.isEmpty(mPrevItemId) ? "" : mPrevItemId);
        jsonObject.put(JSONConsts.VGU_NEXT_ITEMID, TextUtils.isEmpty(mNextItemId) ? "" : mNextItemId);
    } catch (JSONException e) {
        StoreUtils.LogError(TAG, "An error occurred while generating JSON object.");
    }

    return jsonObject;
}

From source file:com.deltachi.videotex.grabers.IMDBGraber.java

@Override
public Video getVideo(String imdbCode) throws JSONException, IOException {
    Video video = null;/*  w  w  w.  j  a v  a  2  s  . c o  m*/
    JSONReader jsonReader = new JSONReader();
    JSONObject jSONObject = null;
    jSONObject = jsonReader.readJsonFromUrl("http://www.omdbapi.com/?i=" + imdbCode);
    video = new Video();
    video.setTitle(jSONObject.get("Title").toString());
    video.setYear(Integer.parseInt(jSONObject.get("Year").toString()));
    video.setRated(jSONObject.get("Rated").toString());
    String releasedString = jSONObject.get("Released").toString();
    SimpleDateFormat releasedFormat = new SimpleDateFormat("dd MMM yyyy", Locale.US);
    Date released = null;
    try {
        released = releasedFormat.parse(releasedString);
    } catch (ParseException ex) {
        Logger.getLogger(IMDBGraber.class.getName()).log(Level.SEVERE, null, ex);
    }
    video.setReleased(released);
    video.setRuntime(jSONObject.get("Runtime").toString());
    String[] genres = jSONObject.get("Genre").toString().split(", ");
    Collection<Genre> genreCollection = new ArrayList<>();
    for (String genres1 : genres) {
        Genre genre = new Genre();
        genre.setName(genres1);
        genreCollection.add(genre);
    }
    video.setGenreCollection(genreCollection);
    video.setDirector(jSONObject.get("Director").toString());
    video.setWriter("Writer");
    video.setActors(jSONObject.get("Actors").toString());
    video.setPlot(jSONObject.get("Plot").toString());
    video.setLanguage(jSONObject.get("Language").toString());
    video.setCountry(jSONObject.get("Country").toString());
    video.setAwards(jSONObject.get("Awards").toString());
    URL posterUrl = null;
    try {
        posterUrl = new URL(jSONObject.get("Poster").toString());
    } catch (MalformedURLException ex) {
        Logger.getLogger(IMDBGraber.class.getName()).log(Level.SEVERE, null, ex);
    }
    byte[] posterFile = null;
    try {
        posterFile = Downloader.getAsByteArray(posterUrl);
    } catch (IOException ex) {
        Logger.getLogger(IMDBGraber.class.getName()).log(Level.SEVERE, null, ex);
    }
    video.setPoster(posterFile);
    video.setRating(Float.parseFloat(jSONObject.get("imdbRating").toString()));
    video.setImdbCode(imdbCode);
    return video;
}

From source file:com.facebook.config.TestSystemPropOverridingJSONProvider.java

@Test(groups = "fast")
public void testValueAsJSON() throws Exception {
    System.setProperty(KEY5, "{nested_key : nested_value}");
    JSONObject jsonObject = jsonProvider.get();
    JSONObject nestedJSONObject = jsonObject.getJSONObject(KEY5);

    Assert.assertEquals(nestedJSONObject.get("nested_key"), "nested_value");
}

From source file:fr.liglab.adele.cilia.workbench.restmonitoring.parser.platform.BindingInstance.java

private static String getJSONField(JSONObject binding, String name) throws CiliaException {
    try {/*from www .j  ava 2  s  .  c om*/
        return (String) binding.get(name);
    } catch (JSONException e) {
        return ""; // error reported by getErrorsAndWarnings...
    }
}

From source file:com.citrus.mobile.OauthToken.java

public boolean createToken(JSONObject usertoken) {

    jsontoken = new JSONObject();

    long expiry = new Date().getTime() / 1000l;

    try {//from  ww  w.  j a v  a2 s.  c  om
        expiry += usertoken.getLong("expires_in");
        jsontoken.put("expiry", expiry);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    for (Iterator<?> keys = usertoken.keys(); keys.hasNext();) {
        String key = (String) keys.next();

        try {
            jsontoken.put(key, usertoken.get(key));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return storeToken();

}

From source file:org.torito.social.facebook.impl.FacebookServiceImpl.java

public long createAlbum(String name, String description, String location) throws FacebookException {
    long aid = 0;
    try {/* ww w.j  av  a 2 s. c  o m*/
        JSONObject nalbum = client.photos_createAlbum(name, description, location);
        String sid = String.valueOf(nalbum.get("aid"));
        aid = Long.parseLong((sid.split("_")[1]));
    } catch (Exception e) {
        e.printStackTrace();
        throw new FacebookException(e.getMessage());
    }
    return aid;
}

From source file:eu.codeplumbers.cosi.services.CosiNoteService.java

@Override
protected void onHandleIntent(Intent intent) {
    // Do the task here
    Log.i(CosiNoteService.class.getName(), "Cosi Service running");

    // Release the wake lock provided by the WakefulBroadcastReceiver.
    WakefulBroadcastReceiver.completeWakefulIntent(intent);

    Device device = Device.registeredDevice();

    // delete all local notes
    new Delete().from(Note.class).execute();

    // cozy register device url
    this.url = device.getUrl() + "/ds-api/request/note/cosiall/";

    // concatenate username and password with colon for authentication
    final String credentials = device.getLogin() + ":" + device.getPassword();
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    showNotification();/*from ww w  .j  a  va  2 s .c  o m*/

    if (isNetworkAvailable()) {
        try {
            URL urlO = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            // read the response
            int status = conn.getResponseCode();
            InputStream in = null;

            if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
                in = conn.getErrorStream();
            } else {
                in = conn.getInputStream();
            }

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONArray jsonArray = new JSONArray(result);

            if (jsonArray != null) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    String version = "0";
                    if (jsonArray.getJSONObject(i).has("version")) {
                        version = jsonArray.getJSONObject(i).getString("version");
                    }
                    JSONObject noteJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Note note = Note.getByRemoteId(noteJson.get("_id").toString());

                    if (note == null) {
                        note = new Note(noteJson);
                    } else {
                        boolean versionIncremented = note.getVersion() < Integer
                                .valueOf(noteJson.getString("version"));

                        int modifiedOnServer = DateUtils.compareDateStrings(
                                Long.valueOf(note.getLastModificationValueOf()),
                                noteJson.getLong("lastModificationValueOf"));

                        if (versionIncremented || modifiedOnServer == -1) {
                            note.setTitle(noteJson.getString("title"));
                            note.setContent(noteJson.getString("content"));
                            note.setCreationDate(noteJson.getString("creationDate"));
                            note.setLastModificationDate(noteJson.getString("lastModificationDate"));
                            note.setLastModificationValueOf(noteJson.getString("lastModificationValueOf"));
                            note.setParentId(noteJson.getString("parent_id"));
                            // TODO: 10/3/16
                            // handle note paths
                            note.setPath(noteJson.getString("path"));
                            note.setVersion(Integer.valueOf(version));
                        }

                    }

                    mBuilder.setProgress(jsonArray.length(), i, false);
                    mBuilder.setContentText("Getting note : " + note.getTitle());
                    mNotifyManager.notify(notification_id, mBuilder.build());

                    EventBus.getDefault()
                            .post(new NoteSyncEvent(SYNC_MESSAGE, "Getting note : " + note.getTitle()));
                    note.save();
                }
            } else {
                EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "Failed to parse API response"));
            }

            in.close();
            conn.disconnect();

            mNotifyManager.cancel(notification_id);
            EventBus.getDefault().post(new NoteSyncEvent(REFRESH, "Sync OK"));
        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        }
    } else {
        mSyncRunning = false;
        EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "No Internet connection"));
        mBuilder.setContentText("Sync failed because no Internet connection was available");
        mNotifyManager.notify(notification_id, mBuilder.build());
    }
}