Example usage for org.json JSONObject getJSONObject

List of usage examples for org.json JSONObject getJSONObject

Introduction

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

Prototype

public JSONObject getJSONObject(String key) throws JSONException 

Source Link

Document

Get the JSONObject value associated with a key.

Usage

From source file:org.b3log.solo.event.symphony.CommentSender.java

@Override
public void action(final Event<JSONObject> event) throws EventException {
    final JSONObject data = event.getData();
    LOGGER.log(Level.FINER, "Processing an event[type={0}, data={1}] in listener[className={2}]",
            new Object[] { event.getType(), data, ArticleSender.class.getName() });
    try {// ww w  .  ja va2 s  . com
        final JSONObject originalComment = data.getJSONObject(Comment.COMMENT);

        final JSONObject preference = preferenceQueryService.getPreference();
        if (null == preference) {
            throw new EventException("Not found preference");
        }

        final String blogHost = preference.getString(Preference.BLOG_HOST).toLowerCase();
        if (blogHost.contains("localhost")) {
            LOGGER.log(Level.INFO,
                    "Blog Solo runs on local server, so should not send this comment[id={0}] to Symphony",
                    new Object[] { originalComment.getString(Keys.OBJECT_ID) });
            return;
        }

        final HTTPRequest httpRequest = new HTTPRequest();
        httpRequest.setURL(ADD_COMMENT_URL);
        httpRequest.setRequestMethod(HTTPRequestMethod.PUT);
        final JSONObject requestJSONObject = new JSONObject();
        final JSONObject comment = new JSONObject();
        comment.put("commentId", originalComment.optString(Keys.OBJECT_ID));
        comment.put("commentAuthorName", originalComment.getString(Comment.COMMENT_NAME));
        comment.put("commentAuthorEmail", originalComment.getString(Comment.COMMENT_EMAIL));
        comment.put(Comment.COMMENT_CONTENT, originalComment.getString(Comment.COMMENT_CONTENT));
        comment.put("articleId", originalComment.getString(Comment.COMMENT_ON_ID));

        requestJSONObject.put(Comment.COMMENT, comment);
        requestJSONObject.put("clientVersion", SoloServletListener.VERSION);
        requestJSONObject.put("clientRuntimeEnv", Latkes.getRuntimeEnv().name());
        requestJSONObject.put("clientName", "B3log Solo");
        requestJSONObject.put("clientHost", blogHost);
        requestJSONObject.put("clientAdminEmail", preference.optString(Preference.ADMIN_EMAIL));
        requestJSONObject.put("userB3Key", preference.optString(Preference.KEY_OF_SOLO));

        httpRequest.setPayload(requestJSONObject.toString().getBytes("UTF-8"));

        urlFetchService.fetchAsync(httpRequest);
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, "Sends a comment to Symphony error: {0}", e.getMessage());
    }

    LOGGER.log(Level.FINER, "Sent a comment to Symphony");
}

From source file:com.github.koraktor.steamcondenser.community.AppNews.java

/**
 * Loads the news for the given game with the given restrictions
 *
 * @param appId The unique Steam Application ID of the game (e.g.
 *        <code>440</code> for Team Fortress 2). See
 *        http://developer.valvesoftware.com/wiki/Steam_Application_IDs for
 *        all application IDs/* www. ja  v a 2 s .co m*/
 * @param count The maximum number of news to load (default: 5). There's no
 *        reliable way to load all news. Use really a really great number
 *        instead
 * @param maxLength The maximum content length of the news (default: nil).
 *        If a maximum length is defined, the content of the news will only
 *        be at most <code>maxLength</code> characters long plus an
 *        ellipsis
 * @return A list of news for the specified game with the given options
 * @throws WebApiException if a request to Steam's Web API fails
 */
public static List<AppNews> getNewsForApp(int appId, int count, Integer maxLength) throws WebApiException {
    try {
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("appid", appId);
        params.put("count", count);
        params.put("maxlength", maxLength);
        JSONObject data = new JSONObject(WebApi.getJSON("ISteamNews", "GetNewsForApp", 2, params));

        List<AppNews> newsItems = new ArrayList<AppNews>();
        JSONArray newsData = data.getJSONObject("appnews").getJSONArray("newsitems");
        for (int i = 0; i < newsData.length(); i++) {
            newsItems.add(new AppNews(appId, newsData.getJSONObject(i)));
        }

        return newsItems;
    } catch (JSONException e) {
        throw new WebApiException("Could not parse JSON data.", e);
    }
}

From source file:com.goliathonline.android.kegbot.io.RemoteDrinksHandler.java

/** {@inheritDoc} */
@Override//from  w w w. j ava  2 s. c om
public ArrayList<ContentProviderOperation> parse(JSONObject parser, ContentResolver resolver)
        throws JSONException, IOException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();

    // Walk document, parsing any incoming entries
    int drink_id = 0;
    JSONObject result = parser.getJSONObject("result");
    JSONArray drinks = result.getJSONArray("drinks");
    JSONObject drink;
    for (int i = 0; i < drinks.length(); i++) {
        if (drink_id == 0) { // && ENTRY.equals(parser.getName()
            // Process single spreadsheet row at a time
            drink = drinks.getJSONObject(i);
            final String drinkId = sanitizeId(drink.getString("id"));
            final Uri drinkUri = Drinks.buildDrinkUri(drinkId);

            // Check for existing details, only update when changed
            final ContentValues values = queryDrinkDetails(drinkUri, resolver);
            final long localUpdated = values.getAsLong(SyncColumns.UPDATED);
            final long serverUpdated = 500; //entry.getUpdated();
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "found drink " + drinkId);
                Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated);
            }
            if (localUpdated != KegbotContract.UPDATED_NEVER)
                continue;

            final Uri drinkKegUri = Drinks.buildKegUri(drinkId);
            final Uri drinkUserUri = Drinks.buildUserUri(drinkId);

            // Clear any existing values for this session, treating the
            // incoming details as authoritative.
            batch.add(ContentProviderOperation.newDelete(drinkUri).build());
            batch.add(ContentProviderOperation.newDelete(drinkKegUri).build());

            final ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newInsert(Drinks.CONTENT_URI);

            builder.withValue(SyncColumns.UPDATED, serverUpdated);
            builder.withValue(Drinks.DRINK_ID, drinkId);

            // Inherit starred value from previous row
            if (values.containsKey(Drinks.DRINK_STARRED)) {
                builder.withValue(Drinks.DRINK_STARRED, values.getAsInteger(Drinks.DRINK_STARRED));
            }

            if (drink.has("session_id"))
                builder.withValue(Drinks.SESSION_ID, drink.getInt("session_id"));
            if (drink.has("status"))
                builder.withValue(Drinks.STATUS, drink.getString("status"));
            if (drink.has("user_id"))
                builder.withValue(Drinks.USER_ID, drink.getString("user_id"));
            if (drink.has("keg_id"))
                builder.withValue(Drinks.KEG_ID, drink.getInt("keg_id"));
            if (drink.has("volume_ml"))
                builder.withValue(Drinks.VOLUME, drink.getDouble("volume_ml"));
            if (drink.has("pour_time"))
                builder.withValue(Drinks.POUR_TIME, drink.getString("pour_time"));

            // Normal session details ready, write to provider
            batch.add(builder.build());

            // Assign kegs
            final int kegId = drink.getInt("keg_id");
            batch.add(ContentProviderOperation.newInsert(drinkKegUri).withValue(DrinksKeg.DRINK_ID, drinkId)
                    .withValue(DrinksKeg.KEG_ID, kegId).build());

            // Assign users
            if (drink.has("user_id")) {
                final String userId = drink.getString("user_id");
                batch.add(ContentProviderOperation.newInsert(drinkUserUri)
                        .withValue(DrinksUser.DRINK_ID, drinkId).withValue(DrinksUser.USER_ID, userId).build());
            }
        }
    }

    return batch;
}

From source file:io.teak.sdk.Teak.java

static void purchaseSucceeded(final JSONObject purchaseData) {
    Teak.asyncExecutor.submit(new Runnable() {
        public void run() {
            try {
                if (Teak.isDebug) {
                    Log.d(LOG_TAG, "Purchase succeeded: " + purchaseData.toString(2));
                }/*from   w  w w  . j a va2  s.  co  m*/

                final HashMap<String, Object> payload = new HashMap<>();

                if (Teak.appConfiguration.installerPackage == null) {
                    Log.e(LOG_TAG, "Purchase succeded from unknown app store.");
                } else if (Teak.appConfiguration.installerPackage.equals("com.amazon.venezia")) {
                    JSONObject receipt = purchaseData.getJSONObject("receipt");
                    JSONObject userData = purchaseData.getJSONObject("userData");

                    payload.put("purchase_token", receipt.get("receiptId"));
                    payload.put("purchase_time_string", receipt.get("purchaseDate"));
                    payload.put("product_id", receipt.get("sku"));
                    payload.put("store_user_id", userData.get("userId"));
                    payload.put("store_marketplace", userData.get("marketplace"));

                    Log.d(LOG_TAG, "Purchase of " + receipt.get("sku") + " detected.");
                } else {
                    payload.put("purchase_token", purchaseData.get("purchaseToken"));
                    payload.put("purchase_time", purchaseData.get("purchaseTime"));
                    payload.put("product_id", purchaseData.get("productId"));
                    if (purchaseData.has("orderId")) {
                        payload.put("order_id", purchaseData.get("orderId"));
                    }

                    Log.d(LOG_TAG, "Purchase of " + purchaseData.get("productId") + " detected.");
                }

                if (Teak.appStore != null) {
                    JSONObject skuDetails = Teak.appStore.querySkuDetails((String) payload.get("product_id"));
                    if (skuDetails != null) {
                        if (skuDetails.has("price_amount_micros")) {
                            payload.put("price_currency_code", skuDetails.getString("price_currency_code"));
                            payload.put("price_amount_micros", skuDetails.getString("price_amount_micros"));
                        } else if (skuDetails.has("price_string")) {
                            payload.put("price_string", skuDetails.getString("price_string"));
                        }
                    }
                }

                Session.whenUserIdIsReadyRun(new Session.SessionRunnable() {
                    @Override
                    public void run(Session session) {
                        new Request("/me/purchase", payload, session).run();
                    }
                });
            } catch (Exception e) {
                Log.e(LOG_TAG, "Error reporting purchase: " + Log.getStackTraceString(e));
                Teak.sdkRaven.reportException(e);
            }
        }
    });
}

From source file:org.brickred.socialauth.provider.HotmailImpl.java

private Profile getProfile() throws Exception {
    Profile p = new Profile();
    Response serviceResponse;/*from www.  ja  v  a 2s. c o  m*/
    try {
        serviceResponse = authenticationStrategy.executeFeed(PROFILE_URL);
    } catch (Exception e) {
        throw new SocialAuthException("Failed to retrieve the user profile from  " + PROFILE_URL, e);
    }

    String result;
    try {
        result = serviceResponse.getResponseBodyAsString(Constants.ENCODING);
        LOG.debug("User Profile :" + result);
    } catch (Exception e) {
        throw new SocialAuthException("Failed to read response from  " + PROFILE_URL, e);
    }
    try {
        JSONObject resp = new JSONObject(result);
        if (resp.has("id")) {
            p.setValidatedId(resp.getString("id"));
        }
        if (resp.has("name")) {
            p.setFullName(resp.getString("name"));
        }
        if (resp.has("first_name")) {
            p.setFirstName(resp.getString("first_name"));
        }
        if (resp.has("last_name")) {
            p.setLastName(resp.getString("last_name"));
        }
        if (resp.has("Location")) {
            p.setLocation(resp.getString("Location"));
        }
        if (resp.has("gender")) {
            p.setGender(resp.getString("gender"));
        }
        if (resp.has("ThumbnailImageLink")) {
            p.setProfileImageURL(resp.getString("ThumbnailImageLink"));
        }

        if (resp.has("birth_day") && !resp.isNull("birth_day")) {
            BirthDate bd = new BirthDate();
            bd.setDay(resp.getInt("birth_day"));
            if (resp.has("birth_month") && !resp.isNull("birth_month")) {
                bd.setMonth(resp.getInt("birth_month"));
            }
            if (resp.has("birth_year") && !resp.isNull("birth_year")) {
                bd.setYear(resp.getInt("birth_year"));
            }
            p.setDob(bd);
        }

        if (resp.has("emails")) {
            JSONObject eobj = resp.getJSONObject("emails");
            String email = null;
            if (eobj.has("preferred")) {
                email = eobj.getString("preferred");
            }
            if ((email == null || email.isEmpty()) && eobj.has("account")) {
                email = eobj.getString("account");
            }
            if ((email == null || email.isEmpty()) && eobj.has("personal")) {
                email = eobj.getString("personal");
            }
            p.setEmail(email);

        }
        if (resp.has("locale")) {
            p.setLanguage(resp.getString("locale"));
        }
        serviceResponse.close();
        p.setProviderId(getProviderId());
        String picUrl = String.format(PROFILE_PICTURE_URL, accessGrant.getKey());
        p.setProfileImageURL(picUrl);
        userProfile = p;
        return p;
    } catch (Exception e) {
        throw new SocialAuthException("Failed to parse the user profile json : " + result, e);
    }
}

From source file:org.dasein.cloud.benchmark.Suite.java

static public void main(String... args) throws Exception {
    ArrayList<Map<String, Object>> suites = new ArrayList<Map<String, Object>>();
    ArrayList<Map<String, Object>> tests = new ArrayList<Map<String, Object>>();

    for (String suiteFile : args) {
        HashMap<String, Object> suite = new HashMap<String, Object>();

        ArrayList<Benchmark> benchmarks = new ArrayList<Benchmark>();

        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(suiteFile)));
        StringBuilder json = new StringBuilder();
        String line;/*from  w  w  w.  jav a 2s.  c o m*/

        while ((line = reader.readLine()) != null) {
            json.append(line);
            json.append("\n");
        }
        JSONObject ob = new JSONObject(json.toString());

        suite.put("name", ob.getString("name"));
        suite.put("description", ob.getString("description"));

        JSONArray benchmarkClasses = ob.getJSONArray("benchmarks");

        for (int i = 0; i < benchmarkClasses.length(); i++) {
            String cname = benchmarkClasses.getString(i);

            benchmarks.add((Benchmark) Class.forName(cname).newInstance());
        }

        JSONArray clouds = ob.getJSONArray("clouds");

        for (int i = 0; i < clouds.length(); i++) {
            JSONObject cloud = clouds.getJSONObject(i);

            if (cloud.has("regions")) {
                JSONObject regions = cloud.getJSONObject("regions");
                String[] regionIds = JSONObject.getNames(regions);

                if (regionIds != null) {
                    for (String regionId : regionIds) {
                        final JSONObject regionCfg = regions.getJSONObject(regionId);
                        String cname = cloud.getString("providerClass");
                        CloudProvider provider = (CloudProvider) Class.forName(cname).newInstance();
                        JSONObject ctxCfg = cloud.getJSONObject("context");
                        ProviderContext ctx = new ProviderContext();

                        ctx.setEndpoint(regionCfg.getString("endpoint"));
                        ctx.setAccountNumber(ctxCfg.getString("accountNumber"));
                        ctx.setRegionId(regionId);
                        if (ctxCfg.has("accessPublic")) {
                            ctx.setAccessPublic(ctxCfg.getString("accessPublic").getBytes("utf-8"));
                        }
                        if (ctxCfg.has("accessPrivate")) {
                            ctx.setAccessPrivate(ctxCfg.getString("accessPrivate").getBytes("utf-8"));
                        }
                        ctx.setCloudName(ctxCfg.getString("cloudName"));
                        ctx.setProviderName(ctxCfg.getString("providerName"));
                        if (ctxCfg.has("x509Cert")) {
                            ctx.setX509Cert(ctxCfg.getString("x509Cert").getBytes("utf-8"));
                        }
                        if (ctxCfg.has("x509Key")) {
                            ctx.setX509Key(ctxCfg.getString("x509Key").getBytes("utf-8"));
                        }
                        if (ctxCfg.has("customProperties")) {
                            JSONObject p = ctxCfg.getJSONObject("customProperties");
                            String[] names = JSONObject.getNames(p);

                            if (names != null) {
                                Properties props = new Properties();

                                for (String name : names) {
                                    String value = p.getString(name);

                                    if (value != null) {
                                        props.put(name, value);
                                    }
                                }
                                ctx.setCustomProperties(props);
                            }
                        }
                        provider.connect(ctx);

                        Suite s = new Suite(benchmarks, provider);

                        tests.add(s.runBenchmarks(regionCfg));
                    }
                }
            }
        }
        suite.put("benchmarks", tests);
        suites.add(suite);
    }
    System.out.println((new JSONArray(suites)).toString());
}

From source file:ru.otdelit.astrid.opencrx.sync.OpencrxSyncProvider.java

/** Create a task container for the given RtmTaskSeries
 * @throws JSONException/*from ww  w  .j  av a 2  s  . c  o m*/
 * @throws IOException
 * @throws ApiServiceException */
private OpencrxTaskContainer parseRemoteTask(JSONObject remoteTask)
        throws JSONException, ApiServiceException, IOException {

    String resourceId = Preferences.getStringValue(OpencrxUtilities.PREF_RESOURCE_ID);

    String crxId = remoteTask.getString("repeating_value");

    JSONArray labels = invoker.resourcesShowForTask(crxId);

    int secondsSpentOnTask = invoker.getSecondsSpentOnTask(crxId, resourceId);

    Task task = new Task();
    ArrayList<Metadata> metadata = new ArrayList<Metadata>();

    if (remoteTask.has("task"))
        remoteTask = remoteTask.getJSONObject("task");

    task.setValue(Task.TITLE, ApiUtilities.decode(remoteTask.getString("title")));
    task.setValue(Task.NOTES, remoteTask.getString("detailedDescription"));
    task.setValue(Task.CREATION_DATE,
            ApiUtilities.producteevToUnixTime(remoteTask.getString("time_created"), 0));
    task.setValue(Task.COMPLETION_DATE, remoteTask.getInt("status") == 1 ? DateUtilities.now() : 0);
    task.setValue(Task.DELETION_DATE, remoteTask.getInt("deleted") == 1 ? DateUtilities.now() : 0);
    task.setValue(Task.ELAPSED_SECONDS, secondsSpentOnTask);
    task.setValue(Task.MODIFICATION_DATE, remoteTask.getLong("modifiedAt"));

    long dueDate = ApiUtilities.producteevToUnixTime(remoteTask.getString("deadline"), 0);
    if (remoteTask.optInt("all_day", 0) == 1)
        task.setValue(Task.DUE_DATE, Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, dueDate));
    else
        task.setValue(Task.DUE_DATE, Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, dueDate));
    task.setValue(Task.IMPORTANCE, 5 - remoteTask.getInt("star"));

    for (int i = 0; i < labels.length(); i++) {
        JSONObject label = labels.getJSONObject(i);

        Metadata tagData = new Metadata();
        tagData.setValue(Metadata.KEY, OpencrxDataService.TAG_KEY);
        tagData.setValue(OpencrxDataService.TAG, label.getString("name"));
        metadata.add(tagData);
    }

    OpencrxTaskContainer container = new OpencrxTaskContainer(task, metadata, remoteTask);

    return container;
}

From source file:com.asd.littleprincesbeauty.data.Task.java

@Override
public void setContentByLocalJSON(JSONObject js) {
    if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) || !js.has(GTaskStringUtils.META_HEAD_DATA)) {
        Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
    }//from   w  w  w . j  a v a  2  s.co  m

    try {
        JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
        JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);

        if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
            Log.e(TAG, "invalid type");
            return;
        }

        for (int i = 0; i < dataArray.length(); i++) {
            JSONObject data = dataArray.getJSONObject(i);
            if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
                setName(data.getString(DataColumns.CONTENT));
                break;
            }
        }

    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }
}

From source file:cz.karry.vpnc.LunaService.java

@LunaServiceThread.PublicMethod
public void connectVpn(final ServiceMessage msg) throws JSONException, LSException {
    JSONObject jsonObj = msg.getJSONPayload();

    tcpLogger.log("invoke connectVpn " + jsonObj.toString());

    if ((!jsonObj.has("type")) || (!jsonObj.has("name")) || (!jsonObj.has("display_name"))
            || (!jsonObj.has("configuration"))) {
        msg.respondError("1", "Improperly formatted request. (" + jsonObj.toString() + ")");
        return;//  ww  w.java2  s.  c  om
    }

    String type = jsonObj.getString("type");
    String name = jsonObj.getString("name");
    String displayName = jsonObj.getString("display_name");
    JSONObject configuration = jsonObj.getJSONObject("configuration");

    if (!name.matches("^[a-zA-Z]{1}[a-zA-Z0-9]*$")) {
        msg.respondError("2", "Bad session name format.");
        return;
    }

    if (type.toLowerCase().equals("pptp")) {
        String host = configuration.getString("host").replaceAll("\n", "\\\\n");

        String user = configuration.getString("pptp_user").replaceAll("\n", "\\\\n");
        String pass = configuration.getString("pptp_password").replaceAll("\n", "\\\\n");
        String mppe = configuration.getString("pptp_mppe").replaceAll("\n", "\\\\n");
        String mppe_stateful = configuration.getString("pptp_mppe_stateful").replaceAll("\n", "\\\\n");
        connectPptpVpn(msg, name, displayName, host, user, pass, mppe, mppe_stateful);
        return;
    } else if (type.toLowerCase().equals("openvpn")) {
        String host = configuration.getString("host").replaceAll("\n", "\\\\n");

        String topology = configuration.getString("openvpn_topology");
        String protocol = configuration.getString("openvpn_protocol");
        String cipher = configuration.getString("openvpn_cipher");
        this.connectOpenVPN(msg, name, displayName, host, topology, protocol, cipher);
        return;
    } else if (type.toLowerCase().equals("cisco")) {
        String host = configuration.getString("host").replaceAll("\n", "\\\\n");

        String userid = configuration.getString("cisco_userid").replaceAll("\n", "\\\\n");
        String userpass = configuration.getString("cisco_userpass").replaceAll("\n", "\\\\n");
        String groupid = configuration.getString("cisco_groupid").replaceAll("\n", "\\\\n");
        String grouppass = configuration.getString("cisco_grouppass").replaceAll("\n", "\\\\n");
        String userpasstype = configuration.getString("cisco_userpasstype");
        String grouppasstype = configuration.getString("cisco_grouppasstype");
        String domain = configuration.has("cisco_domain") && configuration.getString("cisco_domain") != null
                && configuration.getString("cisco_domain").trim().length() > 0
                        ? "Domain " + configuration.getString("cisco_domain")
                        : "";
        tcpLogger.log("use domain \"" + domain + "\"");
        this.connectCiscoVpn(msg, name, displayName, host, userid, userpass, userpasstype, groupid, grouppass,
                grouppasstype, domain);
        return;
    }

    msg.respondError("3", "Undefined vpn type (" + type + ").");
}

From source file:uk.co.senab.photup.model.Place.java

public Place(JSONObject object, Account account) throws JSONException {
    super(object, account);
    mCategory = object.getString("category");

    JSONObject location = object.getJSONObject("location");
    mLatitude = location.getDouble("latitude");
    mLongitude = location.getDouble("longitude");
}