Example usage for org.json JSONTokener JSONTokener

List of usage examples for org.json JSONTokener JSONTokener

Introduction

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

Prototype

public JSONTokener(String s) 

Source Link

Document

Construct a JSONTokener from a string.

Usage

From source file:net.mandaria.radioreddit.apis.RedditAPI.java

public static RedditAccount login(Context context, String username, String password) {
    RedditAccount account = new RedditAccount();

    try {//  w  ww.  j  a va  2s.  co m
        String url = context.getString(R.string.reddit_login) + "/" + username;

        // post values
        ArrayList<NameValuePair> post_values = new ArrayList<NameValuePair>();

        BasicNameValuePair user = new BasicNameValuePair("user", username);
        post_values.add(user);

        BasicNameValuePair passwd = new BasicNameValuePair("passwd", password);
        post_values.add(passwd);

        BasicNameValuePair api_type = new BasicNameValuePair("api_type", "json");
        post_values.add(api_type);

        String outputLogin = HTTPUtil.post(context, url, post_values);

        JSONTokener reddit_login_tokener = new JSONTokener(outputLogin);
        JSONObject reddit_login_json = new JSONObject(reddit_login_tokener);

        JSONObject json = reddit_login_json.getJSONObject("json");

        if (json.getJSONArray("errors").length() > 0) {
            String error = json.getJSONArray("errors").getJSONArray(0).getString(1);

            account.ErrorMessage = error;
        } else {
            JSONObject data = json.getJSONObject("data");

            // success!
            String cookie = data.getString("cookie");
            String modhash = data.getString("modhash");

            account.Username = username;
            account.Cookie = cookie;
            account.Modhash = modhash;
            account.ErrorMessage = "";
        }
    } catch (Exception ex) {
        // We fail to get the streams...
        CustomExceptionHandler ceh = new CustomExceptionHandler(context);
        ceh.sendEmail(ex);

        ex.printStackTrace();

        account.ErrorMessage = ex.toString();
    }

    return account;
}

From source file:net.mandaria.radioreddit.apis.RedditAPI.java

public static String Vote(Context context, RedditAccount account, int voteDirection, String fullname) {
    String errorMessage = "";

    try {//from w  ww .j  a  v  a 2s  .c  om
        try {
            account.Modhash = updateModHash(context);

            if (account.Modhash == null) {
                errorMessage = context.getString(R.string.error_ThereWasAProblemVotingPleaseTryAgain);
                return errorMessage;
            }
        } catch (Exception ex) {
            errorMessage = ex.getMessage();
            return errorMessage;
        }

        String url = context.getString(R.string.reddit_vote);

        // post values
        ArrayList<NameValuePair> post_values = new ArrayList<NameValuePair>();

        BasicNameValuePair id = new BasicNameValuePair("id", fullname);
        post_values.add(id);

        BasicNameValuePair dir = new BasicNameValuePair("dir", Integer.toString(voteDirection));
        post_values.add(dir);

        // not required
        //BasicNameValuePair r = new BasicNameValuePair("r", "radioreddit"); // TODO: shouldn't be hard coded, could be talkradioreddit
        //post_values.add(r);

        BasicNameValuePair uh = new BasicNameValuePair("uh", account.Modhash);
        post_values.add(uh);

        BasicNameValuePair api_type = new BasicNameValuePair("api_type", "json");
        post_values.add(api_type);

        String outputVote = HTTPUtil.post(context, url, post_values);

        JSONTokener reddit_vote_tokener = new JSONTokener(outputVote);
        JSONObject reddit_vote_json = new JSONObject(reddit_vote_tokener);

        if (reddit_vote_json.has("json")) {
            JSONObject json = reddit_vote_json.getJSONObject("json");

            if (json.has("errors") && json.getJSONArray("errors").length() > 0) {
                String error = json.getJSONArray("errors").getJSONArray(0).getString(1);

                errorMessage = error;
            }
        }
        // success!
    } catch (Exception ex) {
        // We fail to vote...
        CustomExceptionHandler ceh = new CustomExceptionHandler(context);
        ceh.sendEmail(ex);

        ex.printStackTrace();

        errorMessage = ex.toString();
    }

    return errorMessage;
}

From source file:net.mandaria.radioreddit.apis.RedditAPI.java

public static String updateModHash(Context context) {
    // Calls me.json to get the current modhash for the user
    String output = "";
    boolean errorGettingModHash = false;

    try {/*  w w w.  ja  v a2 s.c o  m*/
        try {
            output = HTTPUtil.get(context, context.getString(R.string.reddit_me));
        } catch (Exception ex) {
            ex.printStackTrace();
            errorGettingModHash = true;
            // For now, not used. It is acceptable to error out and not alert the user
            // radiosong.ErrorMessage = "Unable to connect to reddit";//context.getString(R.string.error_RadioRedditServerIsDownNotification);
        }

        if (!errorGettingModHash && output.length() > 0) {
            JSONTokener reddit_me_tokener = new JSONTokener(output);
            JSONObject reddit_me_json = new JSONObject(reddit_me_tokener);

            JSONObject data = reddit_me_json.getJSONObject("data");

            String modhash = data.getString("modhash");

            return modhash;
        } else {
            return null;
        }
    } catch (Exception ex) {
        //         CustomExceptionHandler ceh = new CustomExceptionHandler(context);
        //         ceh.sendEmail(ex);

        ex.printStackTrace();

        return null;
    }
}

From source file:io.github.runassudo.launchert.InstallShortcutReceiver.java

public static void removeFromInstallQueue(SharedPreferences sharedPrefs, ArrayList<String> packageNames) {
    if (packageNames.isEmpty()) {
        return;//from   w w  w .  j av a2 s .c om
    }
    synchronized (sLock) {
        Set<String> strings = sharedPrefs.getStringSet(APPS_PENDING_INSTALL, null);
        if (DBG) {
            Log.d(TAG, "APPS_PENDING_INSTALL: " + strings + ", removing packages: " + packageNames);
        }
        if (strings != null) {
            Set<String> newStrings = new HashSet<String>(strings);
            Iterator<String> newStringsIter = newStrings.iterator();
            while (newStringsIter.hasNext()) {
                String json = newStringsIter.next();
                try {
                    JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
                    Intent launchIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);
                    String pn = launchIntent.getPackage();
                    if (pn == null) {
                        pn = launchIntent.getComponent().getPackageName();
                    }
                    if (packageNames.contains(pn)) {
                        newStringsIter.remove();
                    }
                } catch (org.json.JSONException e) {
                    Log.d(TAG, "Exception reading shortcut to remove: " + e);
                } catch (java.net.URISyntaxException e) {
                    Log.d(TAG, "Exception reading shortcut to remove: " + e);
                }
            }
            sharedPrefs.edit().putStringSet(APPS_PENDING_INSTALL, new HashSet<String>(newStrings)).commit();
        }
    }
}

From source file:io.github.runassudo.launchert.InstallShortcutReceiver.java

private static ArrayList<PendingInstallShortcutInfo> getAndClearInstallQueue(SharedPreferences sharedPrefs) {
    synchronized (sLock) {
        Set<String> strings = sharedPrefs.getStringSet(APPS_PENDING_INSTALL, null);
        if (DBG)/*from  www  . j  a  v a 2  s  .c om*/
            Log.d(TAG, "Getting and clearing APPS_PENDING_INSTALL: " + strings);
        if (strings == null) {
            return new ArrayList<PendingInstallShortcutInfo>();
        }
        ArrayList<PendingInstallShortcutInfo> infos = new ArrayList<PendingInstallShortcutInfo>();
        for (String json : strings) {
            try {
                JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
                Intent data = Intent.parseUri(object.getString(DATA_INTENT_KEY), 0);
                Intent launchIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);
                String name = object.getString(NAME_KEY);
                String iconBase64 = object.optString(ICON_KEY);
                String iconResourceName = object.optString(ICON_RESOURCE_NAME_KEY);
                String iconResourcePackageName = object.optString(ICON_RESOURCE_PACKAGE_NAME_KEY);
                if (iconBase64 != null && !iconBase64.isEmpty()) {
                    byte[] iconArray = Base64.decode(iconBase64, Base64.DEFAULT);
                    Bitmap b = BitmapFactory.decodeByteArray(iconArray, 0, iconArray.length);
                    data.putExtra(Intent.EXTRA_SHORTCUT_ICON, b);
                } else if (iconResourceName != null && !iconResourceName.isEmpty()) {
                    Intent.ShortcutIconResource iconResource = new Intent.ShortcutIconResource();
                    iconResource.resourceName = iconResourceName;
                    iconResource.packageName = iconResourcePackageName;
                    data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
                }
                data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent);
                PendingInstallShortcutInfo info = new PendingInstallShortcutInfo(data, name, launchIntent);
                infos.add(info);
            } catch (org.json.JSONException e) {
                Log.d(TAG, "Exception reading shortcut to add: " + e);
            } catch (java.net.URISyntaxException e) {
                Log.d(TAG, "Exception reading shortcut to add: " + e);
            }
        }
        sharedPrefs.edit().putStringSet(APPS_PENDING_INSTALL, new HashSet<String>()).commit();
        return infos;
    }
}

From source file:com.chess.genesis.net.SocketClient.java

public synchronized JSONObject read() throws IOException, JSONException {
    connect();/*from  w ww  .  j  a va 2 s .co m*/

    try {
        return (JSONObject) new JSONTokener(input.readLine()).nextValue();
    } catch (final NullPointerException e) {
        return new JSONObject("{\"result\":\"error\",\"reason\":\"connection lost\"}");
    }
}

From source file:org.alfresco.jive.impl.JiveOpenClientImpl.java

/**
 * Jive returns JSON with a weird (and invalid, according to RFC-4627) prefix.
 * This method strips it off (if it exists) and parses the JSON.  
 * //  www.  jav  a  2 s . c om
 * @param responseBody The JSON string to process <i>(may be null, empty or blank)</i>.
 * @return The "cleansed" response body <i>(will be null if the input was null)</i>.
 */
private JSONObject parseJson(String jsonStr) throws JSONException {
    JSONObject result = null;

    if (jsonStr != null) {
        if (jsonStr != null && jsonStr.startsWith(JIVE_JSON_PREFIX)) {
            jsonStr = jsonStr.substring(JIVE_JSON_PREFIX.length());
        }

        result = new JSONObject(new JSONTokener(jsonStr));
    }

    return (result);
}

From source file:com.cdd.bao.importer.KeywordMapping.java

public KeywordMapping(String mapFN) {
    file = new File(mapFN);

    // try to load the file, but it's OK if it fails
    JSONObject json = null;//  w  w w  .ja v  a 2s.co m
    try {
        Reader rdr = new FileReader(file);
        json = new JSONObject(new JSONTokener(rdr));
        rdr.close();
    } catch (JSONException ex) {
        Util.writeln("NOTE: reading file " + file.getAbsolutePath() + " failed: " + ex.getMessage());
    } catch (IOException ex) {
        return;
    } // includes file not found, which is OK

    try {
        for (JSONObject obj : json.optJSONArrayEmpty("identifiers").toObjectArray()) {
            Identifier id = new Identifier();
            id.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            id.prefix = obj.optString("prefix");
            identifiers.add(id);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("textBlocks").toObjectArray()) {
            TextBlock txt = new TextBlock();
            txt.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            txt.title = obj.optString("title");
            textBlocks.add(txt);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("properties").toObjectArray()) {
            Property prop = new Property();
            prop.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            prop.propURI = obj.optString("propURI");
            prop.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            properties.add(prop);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("values").toObjectArray()) {
            Value val = new Value();
            val.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            val.valueRegex = regexOrName(obj.optString("valueRegex"), obj.optString("valueName"));
            val.valueURI = obj.optString("valueURI");
            val.propURI = obj.optString("propURI");
            val.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            values.add(val);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("literals").toObjectArray()) {
            Literal lit = new Literal();
            lit.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            lit.valueRegex = regexOrName(obj.optString("valueRegex"), obj.optString("valueName"));
            lit.propURI = obj.optString("propURI");
            lit.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            literals.add(lit);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("references").toObjectArray()) {
            Reference ref = new Reference();
            ref.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            ref.valueRegex = regexOrName(obj.optString("valueRegex"), obj.optString("valueName"));
            ref.prefix = obj.optString("prefix");
            ref.propURI = obj.optString("propURI");
            ref.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            references.add(ref);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("assertions").toObjectArray()) {
            Assertion asrt = new Assertion();
            asrt.propURI = obj.optString("propURI");
            asrt.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            asrt.valueURI = obj.optString("valueURI");
            assertions.add(asrt);
        }
    } catch (JSONException ex) {
        Util.writeln("NOTE: parsing error");
        ex.printStackTrace();
        Util.writeln(
                "*** Execution will continue, but part of the mapping has not been loaded and may be overwritten.");
    }
}

From source file:net.dahanne.gallery3.client.utils.ItemUtilsTest.java

@Test
public void parseJSONToMultipleItems() throws IOException, JSONException {
    URL resource = Resources.getResource("tree-album-1.json");
    String string = Resources.toString(resource, Charsets.UTF_8);
    JSONObject jsonResult = (JSONObject) new JSONTokener(string).nextValue();
    List<Item> items = ItemUtils.parseJSONToMultipleItems(jsonResult);
    assertEquals("http://192.168.1.60:8081/gallery3/index.php/rest/item/1264", items.get(0).getUrl());
    assertEquals(1311332015, items.get(0).getEntity().getUpdated());
    assertEquals("http://192.168.1.60:8081/gallery3/index.php/rest/item/1265", items.get(1).getUrl());
    assertEquals(1311332144, items.get(1).getEntity().getUpdated());
    assertEquals("http://192.168.1.60:8081/gallery3/index.php/rest/item/1661", items.get(2).getUrl());
    assertEquals(1319238331, items.get(2).getEntity().getUpdated());
}

From source file:net.dahanne.gallery3.client.utils.ItemUtilsTest.java

@Test
public void parseJSONTest__album() throws IOException, JSONException {
    URL resource = Resources.getResource("get-album-1.json");
    String string = Resources.toString(resource, Charsets.UTF_8);
    JSONObject jsonResult = (JSONObject) new JSONTokener(string).nextValue();
    Item item = ItemUtils.parseJSONToItem(jsonResult);
    assertEquals("http://g3.dahanne.net/index.php/rest/item/1", item.getUrl());

    Entity entity = item.getEntity();
    assertEquals(1, entity.getId());//from  ww  w  .  j av  a 2  s  .  c  om
    assertEquals(0, entity.getCaptured());
    assertEquals(1276227460, entity.getCreated());
    assertEquals("", entity.getDescription());
    assertEquals(0, entity.getHeight());
    assertEquals(1, entity.getLevel());
    assertEquals(null, entity.getMimeType());
    assertEquals(null, entity.getName());
    assertEquals(2, entity.getOwnerId());
    assertEquals(0f, entity.getRandKey(), 0);
    assertEquals(0, entity.getResizeHeight());
    assertEquals(0, entity.getResizeWidth());
    assertEquals(null, entity.getSlug());
    assertEquals("weight", entity.getSortColumn());
    assertEquals("ASC", entity.getSortOrder());
    assertEquals(200, entity.getThumbHeight());
    assertEquals(150, entity.getThumbWidth());
    assertEquals("Gallery", entity.getTitle());
    assertEquals("album", entity.getType());
    assertEquals(1276227718, entity.getUpdated());
    assertEquals(8, entity.getViewCount());
    assertEquals(0, entity.getWidth());
    assertEquals(1, entity.getView1());
    assertEquals(1, entity.getView2());
    assertEquals("http://g3.dahanne.net/index.php/rest/item/2", entity.getAlbumCover());
    assertEquals("http://g3.dahanne.net/index.php/", entity.getWebUrl());
    assertEquals("http://g3.dahanne.net/index.php/rest/data/1?size=thumb", entity.getThumbUrl());
    assertEquals(17151, entity.getThumbSize());
    assertEquals("http://g3.dahanne.net/var/thumbs//.album.jpg?m=1276227718", entity.getThumbUrlPublic());
    assertEquals(false, entity.isCanEdit());

    RelationShips relationShips = item.getRelationships();
    assertEquals("http://g3.dahanne.net/index.php/rest/item_tags/1", relationShips.getTags().getUrl());
    assertEquals(new HashSet<String>(), relationShips.getTags().getMembers());
    assertEquals("http://g3.dahanne.net/index.php/rest/item_comments/1", relationShips.getComments().getUrl());

    Collection<String> members = new HashSet<String>();
    members.add("http://g3.dahanne.net/index.php/rest/item/2");
    members.add("http://g3.dahanne.net/index.php/rest/item/3");
    assertEquals(members, item.getMembers());

}