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:com.cloudbees.gasp.fragment.TwitterSearchResponderFragment.java

private static List<String> getTweetsFromJson(String json) {
    ArrayList<String> tweetList = new ArrayList<String>();

    try {/*from   w  w  w.j  a  va 2s . c o  m*/
        JSONObject tweetsWrapper = (JSONObject) new JSONTokener(json).nextValue();
        JSONArray tweets = tweetsWrapper.getJSONArray("results");

        for (int i = 0; i < tweets.length(); i++) {
            JSONObject tweet = tweets.getJSONObject(i);
            Log.d(TAG, "Tweet: " + tweet.getString("text"));
            tweetList.add(tweet.getString("text"));
        }
    } catch (JSONException e) {
        Log.e(TAG, "Failed to parse JSON.", e);
    }

    return tweetList;
}

From source file:com.trk.aboutme.facebook.Response.java

static List<Response> createResponsesFromString(String responseString, HttpURLConnection connection,
        RequestBatch requests, boolean isFromCache) throws FacebookException, JSONException, IOException {
    JSONTokener tokener = new JSONTokener(responseString);
    Object resultObject = tokener.nextValue();

    List<Response> responses = createResponsesFromObject(connection, requests, resultObject, isFromCache);
    Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response\n  Id: %s\n  Size: %d\n  Responses:\n%s\n",
            requests.getId(), responseString.length(), responses);

    return responses;
}

From source file:org.fabrican.extension.variable.provider.servlet.ManagementServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//from w w  w  . j a  v a2  s .  c o m
        Pair<String, String> params = gePathParams(req);
        String cmd = params.left();
        String name = params.right();
        RuleSetDAO dao = RuleSetDAO.getInstance();
        resp.setHeader("Cache-Control", "no-cache");
        switch (cmd) {
        case "config":
            InputStreamReader reader = new InputStreamReader(req.getInputStream());
            JSONObject jo = new JSONObject(new JSONTokener(reader));
            String driver = null, url = null, user = null, pass = null;
            if (jo.has("driver")) {
                driver = jo.getString("driver");
            }
            if (jo.has("url")) {
                url = jo.getString("url");
            }
            if (jo.has("user")) {
                user = jo.getString("user");
            }
            if (jo.has("pass")) {
                pass = jo.getString("pass");
            }
            if (driver == null || url == null) {
                resp.setStatus(400);
                output(resp, "missing paramter \"driver\" or \"url\"");
            } else {
                try {
                    if (dao.resetConnection(driver, url, user, pass)) {
                        resp.setStatus(200);
                    } else {
                        resp.setStatus(400);
                        output(resp, "config failed");
                    }
                } catch (Exception ex) {
                    resp.setStatus(500);
                    output(resp, ex.toString());
                }
            }
            return;
        case "providers":
            name = name.trim();
            if (name.equals("")) { // add
                RuleSet r = RuleSetJSONHelper.parse(req.getInputStream());
                if (dao.addRuleSet(r)) {
                    resp.setStatus(201);
                } else {
                    resp.setStatus(400);
                    output(resp, "add failed.");
                }
            } else {
                RuleSet r = RuleSetJSONHelper.parse(req.getInputStream());
                if (dao.updateRuleSet(r)) {
                    resp.setStatus(200);
                } else {
                    resp.setStatus(409);
                    output(resp, "update failed.");
                }
            }
            return;
        case "command":
            name = name.trim();
            if (name.equals("copy")) {
                reader = new InputStreamReader(req.getInputStream());
                jo = new JSONObject(new JSONTokener(reader));
                String from = null;
                String to = null;
                if (jo.has("copyFrom")) {
                    from = jo.getString("copyFrom");
                }
                if (jo.has("copyTo")) {
                    to = jo.getString("copyTo");
                }
                if (from == null || to == null || from.equals(to)) {
                    resp.setStatus(400);
                    output(resp, "parameter error");
                    return;
                }
                RuleSet rFrom = dao.getRuleSetByName(from);
                if (rFrom == null) {
                    resp.setStatus(400);
                    output(resp, "rule not found");
                    return;
                } else {
                    rFrom.setName(to);
                    if (dao.addRuleSet(rFrom)) {
                        resp.setStatus(201);
                    } else {
                        resp.setStatus(400);
                        output(resp, "rule not added, " + to);
                    }
                }
                return;
            } else if (name.equals("destroyCache")) {
                dao.destroyCache();
                resp.setStatus(201);
                return;
            }
        }
    } catch (JSONException ex) {
        resp.setStatus(400);
        output(resp, ex.toString());
    } catch (SQLException e) {
        resp.setStatus(500);
        output(resp, e.toString());
    } catch (InterruptedException e) {
        resp.setStatus(500);
        output(resp, e.toString());
    }
    resp.setStatus(400);
    output(resp, "unrecognized request");
}

From source file:org.artags.android.app.stackwidget.service.TagService.java

public static List<Tag> getTagList(String url) {
    long start = new Date().getTime();
    Log.i(Constants.LOG_TAG, "Tag Service : begin tag fetching");
    List<Tag> list = new ArrayList<Tag>();
    String jsonflow = HttpUtils.getUrl(url);

    try {/*from   w  w  w  .  j  a  v  a2  s .  c  o  m*/

        JSONTokener tokener = new JSONTokener(jsonflow);
        JSONObject json = (JSONObject) tokener.nextValue();
        JSONArray jsonTags = json.getJSONArray("tags");

        int max = (jsonTags.length() < Constants.MAX_TAGS) ? jsonTags.length() : Constants.MAX_TAGS;
        for (int i = 0; i < max; i++) {
            JSONObject jsonTag = jsonTags.getJSONObject(i);
            Tag tag = new Tag();
            tag.setId(jsonTag.getString("id"));
            tag.setText(jsonTag.getString("title"));
            tag.setThumbnailUrl(jsonTag.getString("imageUrl"));
            tag.setRating(jsonTag.getString("rating"));
            list.add(tag);
        }
    } catch (JSONException e) {
        Log.e(Constants.LOG_TAG, "JSON Parsing Error : " + e.getMessage(), e);
    }
    long end = new Date().getTime();
    Log.i(Constants.LOG_TAG, "Tag Service : " + list.size() + " tags fetched in " + (start - end) + "ms");
    return list;
}

From source file:cn.rongcloud.im.server.network.http.JsonHttpResponseHandler.java

protected Object parseResponse(String responseBody) throws JSONException {
    if (null == responseBody)
        return null;
    Object result = null;/* ww  w. ja  v  a2 s.c o  m*/
    //trim the string to prevent start with blank, and test if the string is valid JSON, because the parser don't do this :(. If Json is not valid this will return null
    String jsonString = responseBody.trim();
    if (jsonString.startsWith("{") || jsonString.startsWith("[")) {
        result = new JSONTokener(jsonString).nextValue();
    }
    if (result == null) {
        result = jsonString;
    }
    return result;
}

From source file:org.loklak.api.learning.ConsoleLearning.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization user,
        final JSONObjectWithDefault permissions) throws APIException {
    JSONObject json = new JSONObject(true).put("accepted", true);

    // unauthenticated users are rejected
    if (user.getIdentity().isAnonymous()) {
        json.put("accepted", false);
        json.put("reject-reason", "you must be logged in");
        return json;
    }/*from  w  ww .j  a  v a  2s .  co m*/
    String client = user.getIdentity().getClient();

    // to categorize the rule, we use project names and tags. Both can be omitted, in that case the project
    // is named "default" and the tag list is empty. Both methods can later be used to retrieve subsets of the
    // rule set
    String project = post.get("project", "default");
    String[] tagsl = post.get("tags", "").split(",");
    JSONArray tags = new JSONArray();
    for (String t : tagsl)
        tags.put(t);
    json.put("project", project);
    json.put("tags", tags);

    // parameters
    String action = post.get("action", "");
    if (action.length() == 0) {
        json.put("accepted", false);
        json.put("reject-reason",
                "you must submit a parameter 'action' containing either the word 'list', 'test', 'learn' or 'delete'");
        return json;
    }
    json.put("action", action);

    if (action.equals("list")) {
        Set<String> projectnames = DAO.susi.getRulesetNames(client);
        JSONObject projects = new JSONObject(true);
        for (String p : projectnames) {
            try {
                JsonTray t = DAO.susi.getRuleset(client, p);
                projects.put(p, t.toJSON().getJSONObject("console"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        json.put("projects", projects);
    } else {
        String name = post.get("name", "");
        if (name.length() == 0) {
            json.put("accepted", false);
            json.put("reject-reason", "you must submit a parameter 'name' containing the rule name");
            return json;
        }
        json.put("name", name);

        if (action.equals("delete")) {
            try {
                JsonTray tray = DAO.susi.getRuleset(client, project);
                if (!tray.has("console"))
                    tray.put("console", new JSONObject(), true);
                JSONObject console = tray.getJSONObject("console");
                console.remove(name);
                tray.commit();
            } catch (IOException e) {
                e.printStackTrace();
                json.put("accepted", false);
                json.put("reject-reason", "deletion the console rule causes an error: " + e.getMessage());
            }
            return json;
        }

        String serviceURL = post.get("url", ""); // i.e. url=http://api.loklak.org/api/console.json?q=SELECT%20*%20FROM%20wikigeodata%20WHERE%20place='$query$';
        if (serviceURL.length() == 0) {
            json.put("accepted", false);
            json.put("reject-reason", "url parameter required");
            return json;
        }
        if (!serviceURL.contains("$query$")) {
            json.put("accepted", false);
            json.put("reject-reason", "the url must contain a string $query$");
            return json;
        }

        String test = post.get("test", "");
        if (test.length() == 0) {
            json.put("accepted", false);
            json.put("reject-reason", "a testquery parameter is required");
            return json;
        }

        // now test the api call
        byte[] serviceResponse = null;
        try {
            serviceResponse = ConsoleService.loadData(serviceURL, test);
        } catch (Exception e) {
            json.put("accepted", false);
            json.put("reject-reason", "the console test load resulted in an error: " + e.getMessage());
            return json;
        }

        // try to find the correct jsonPath automatically
        JSONArray path_computed = new JSONArray();
        Object serviceObject = null;
        try {
            serviceObject = new JSONObject(new JSONTokener(new ByteArrayInputStream(serviceResponse)));
        } catch (JSONException e) {
        }
        if (serviceObject != null && ((JSONObject) serviceObject).length() > 0) {
            for (String s : ((JSONObject) serviceObject).keySet()) {
                if (((JSONObject) serviceObject).get(s) instanceof JSONArray)
                    path_computed.put("$." + s);
            }
        } else {
            try {
                serviceObject = new JSONArray(new JSONTokener(new ByteArrayInputStream(serviceResponse)));
            } catch (JSONException e) {
            }
            if (serviceObject != null && ((JSONArray) serviceObject).length() > 0) {
                path_computed.put("$");
            }
        }

        String path = post.get("path", "");
        if (path.length() == 0) {
            if (path_computed.length() == 1) {
                path = path_computed.getString(0);
            } else {
                json.put("accepted", false);
                json.put("reject-reason",
                        "a data parameter containing the jsonpath to the data object is required. "
                                + (path_computed.length() < 1 ? ""
                                        : "Suggested paths: " + path_computed.toString(0)));
                return json;
            }
        }

        JSONArray data = ConsoleService
                .parseJSONPath(new JSONTokener(new ByteArrayInputStream(serviceResponse)), path);
        if (data == null || data.length() == 0) {
            json.put("accepted", false);
            json.put("reject-reason", "the jsonPath from data object did not recognize an array object");
            return json;
        }

        // find out the attributes in the data object
        Set<String> a = new LinkedHashSet<>();
        for (int i = 0; i < data.length(); i++)
            a.addAll(data.getJSONObject(i).keySet());
        for (int i = 0; i < data.length(); i++) {
            Set<String> doa = data.getJSONObject(i).keySet();
            Iterator<String> j = a.iterator();
            while (j.hasNext())
                if (!doa.contains(j.next()))
                    j.remove();
        }
        JSONArray attributes = new JSONArray();
        for (String s : a)
            attributes.put(s);
        json.put("path_computed", path_computed);

        // construct a new rule
        JSONObject consolerule = new JSONObject(true);
        consolerule.put("example", "http://127.0.0.1:4000/susi/console.json?q=%22SELECT%20*%20FROM%20" + name
                + "%20WHERE%20query=%27" + test + "%27;%22");
        consolerule.put("url", serviceURL);
        consolerule.put("test", test);
        consolerule.put("parser", "json");
        consolerule.put("path", path);
        consolerule.put("attributes", attributes);
        //consolerule.put("author", user.getIdentity().getName());
        //consolerule.put("license", "provided by " + user.getIdentity().getName() + ", licensed as public domain");
        json.put("console", new JSONObject().put(name, consolerule));

        // testing was successful, now decide which action to take: report or store
        if (action.equals("test")) {
            json.put("data", data);
            return json;
        }

        if (action.equals("learn")) {
            try {
                JsonTray tray = DAO.susi.getRuleset(client, project);
                if (!tray.has("console"))
                    tray.put("console", new JSONObject(), true);
                JSONObject console = tray.getJSONObject("console");
                console.put(name, consolerule);
                tray.commit();
            } catch (IOException e) {
                e.printStackTrace();
                json.put("accepted", false);
                json.put("reject-reason", "storing the console rule causes an error: " + e.getMessage());
            }
            return json;
        }
    }

    // fail case
    json.put("accepted", false);
    json.put("reject-reason", "no valid action given");
    return json;
}

From source file:com.moarub.kipptapi.ListsGetter.java

@Override
protected void onPostExecute(StringBuilder result) {
    try {/*from www  . j  av a 2  s.c  o m*/
        JSONObject jobj = (JSONObject) new JSONTokener(result.toString()).nextValue();

        setLists(jobj.getJSONArray("objects"));

        for (int i = 0; i < fLists.length(); i++) {
            JSONObject job = fLists.getJSONObject(i);
            Log.d("ListsGetter", job.getString("app_url"));
        }

    } catch (JSONException e) {
        Log.d("ApiTokenFailure", "Can't fetch API Token");
        return;
    }
    Log.d("Result", result.toString());
    fListener.setListsReady();
}

From source file:org.marinemc.settings.JSONConfig.java

public JSONConfig(final File path, final String name) throws JSONException {
    this.path = path;
    this.name = name;
    if (!path.exists())
        if (!path.mkdirs())
            throw new JSONConfigException(name, "Could not create parent folders");
    file = new File(path + File.separator + name + ".json");

    if (file.length() == 0) {
        map = new JSONObject();
        return;/*from  w ww. j a  v a 2 s.  com*/
    }
    if (!file.exists())
        try {
            if (!file.createNewFile())
                throw new JSONConfigException(name, "Could not create the config");
        } catch (final Exception e) {
            throw new JSONConfigException(name, "Could not be created", e);
        } finally {
            map = new JSONObject();
        }
    else
        try {
            final BufferedReader reader = new BufferedReader(new FileReader(file));
            final JSONTokener tokener = new JSONTokener(reader);
            map = new JSONObject(tokener);
            reader.close();
        } catch (final IOException e) {
            throw new JSONConfigException(name, "Could not load in the config", e);
        }
    for (final Map.Entry<String, Object> entry : defaultValues().entrySet())
        setIfNull(entry.getKey(), entry.getValue());
}

From source file:com.arthurpitman.common.HttpUtils.java

/**
 * Calls a URL as JSON./* w w w  .j  a  v  a  2  s  .  c om*/
 * @param url
 * @param requestProperties optional request properties, <code>null</code> if not required.
 * @param post optional post data, <code>null</code> if not required.
 * @return a {@link JSONObject} representing the response.
 * @throws IOException
 * @throws JSONException
 */
public static JSONObject retrieveUrlAsJson(final String url, final RequestProperty[] requestProperties,
        final String post) throws IOException, JSONException {
    return (JSONObject) new JSONTokener(retrieveUrlAsString(url, requestProperties, post.getBytes()))
            .nextValue();
}

From source file:org.nabucco.alfresco.enhScriptEnv.share.surf.ShareRegisteredScriptLocator.java

protected void retrieveReposioryEditionInfo() {
    try {/*from w w w .j  a v a 2 s  . c o  m*/
        final Connector connector = this.connectorService.getConnector("alfresco");

        // workaround NPE-bugs in RequestCachingConnector when calling "call" outside of active request
        final boolean fakedRequestContext;
        RequestContext requestContext = ThreadLocalRequestContext.getRequestContext();
        if (requestContext == null) {
            fakedRequestContext = true;
            requestContext = new AbstractRequestContext(this.serviceRegistry, this.frameworkUtil) {

                private static final long serialVersionUID = 1L;

                @Override
                public LinkBuilder getLinkBuilder() {
                    return null;
                }

                // Only relevant in Alfresco 5 - thus no @Override
                public boolean isExtensibilitySuppressed() {
                    return false;
                }
            };
        } else {
            fakedRequestContext = false;
        }

        try {

            final Response response = connector.call("/api/server", new ConnectorContext());
            if (response.getStatus().getCode() == Status.STATUS_OK) {
                try {
                    final JSONObject json = new JSONObject(new JSONTokener(response.getResponse()));

                    final JSONObject data = json.getJSONObject("data");
                    if (data != null) {
                        final String edition = data.getString("edition");

                        final boolean isCommunity;
                        if (EDITION_ENTERPRISE.equalsIgnoreCase(edition)
                                || EDITION_TEAM.equalsIgnoreCase(edition)) {
                            isCommunity = false;
                        } else if (EDITION_UNKNOWN.equalsIgnoreCase(edition)
                                || EDITION_COMMUNITY.equalsIgnoreCase(edition) || edition == null
                                || edition.trim().length() == 0) {
                            isCommunity = true;
                        } else {
                            LOGGER.warn("Unknown / unexpected edition {} - assuming 'community mode'", edition);
                            isCommunity = true;
                        }
                        this.isCommunity = isCommunity;

                        this.lastUpdateCheckTimestamp = System.currentTimeMillis();
                        this.nextUpdateInterval = DEFAULT_UPDATE_CHECK_INTERVAL;
                    } else {
                        this.lastUpdateCheckTimestamp = System.currentTimeMillis();
                        // check again in a minute
                        this.nextUpdateInterval = 1000 * 60;
                        LOGGER.warn("Unexpected response content from /api/server");
                    }
                } catch (final JSONException jsonEx) {
                    this.lastUpdateCheckTimestamp = System.currentTimeMillis();
                    // check again in a minute
                    this.nextUpdateInterval = 1000 * 60;
                    LOGGER.error("Error parsing version information from Repository", jsonEx);
                }
            } else {
                this.lastUpdateCheckTimestamp = System.currentTimeMillis();
                // check again in a minute
                this.nextUpdateInterval = 1000 * 60;
                LOGGER.warn("Failed to load version information from Repository: " + response.getStatus());
            }
        } finally {
            if (fakedRequestContext) {
                requestContext.release();
            }
        }
    } catch (final ConnectorServiceException conEx) {
        this.lastUpdateCheckTimestamp = System.currentTimeMillis();
        // check again in a minute
        this.nextUpdateInterval = 1000 * 60;

        LOGGER.error("Error retrieving connector for version information query to Repository", conEx);
    }
}