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.actionlauncher.api.LiveWallpaperSource.java

private void loadState() {
    String stateString = mSharedPrefs.getString(PREF_STATE, null);
    if (stateString != null) {
        try {//  w  ww  .  j  a v a 2s.co  m
            mCurrentState = SourceState.fromJson((JSONObject) new JSONTokener(stateString).nextValue());
        } catch (JSONException e) {
            LOGE("Couldn't deserialize current state, id=" + mName, e);
        }
    } else {
        mCurrentState = new SourceState();
    }
}

From source file:com.marlonjones.voidlauncher.InstallShortcutReceiver.java

private static PendingInstallShortcutInfo decode(String encoded, Context context) {
    try {//from   w ww .  j  av a  2s .  c  o  m
        JSONObject object = (JSONObject) new JSONTokener(encoded).nextValue();
        Intent launcherIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);

        if (object.optBoolean(APP_SHORTCUT_TYPE_KEY)) {
            // The is an internal launcher target shortcut.
            UserHandleCompat user = UserManagerCompat.getInstance(context)
                    .getUserForSerialNumber(object.getLong(USER_HANDLE_KEY));
            if (user == null) {
                return null;
            }

            LauncherActivityInfoCompat info = LauncherAppsCompat.getInstance(context)
                    .resolveActivity(launcherIntent, user);
            return info == null ? null : new PendingInstallShortcutInfo(info, context);
        }

        Intent data = new Intent();
        data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent);
        data.putExtra(Intent.EXTRA_SHORTCUT_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);
        }

        return new PendingInstallShortcutInfo(data, context);
    } catch (JSONException | URISyntaxException e) {
        Log.d(TAG, "Exception reading shortcut to add: " + e);
    }
    return null;
}

From source file:com.gistlabs.mechanize.document.json.JsonDocument.java

@Override
protected void loadPage() throws Exception {
    try {//from   w ww  .j  a v a2  s  .c o  m
        JSONTokener jsonTokener = new JSONTokener(new InputStreamReader(getInputStream()));
        char nextClean = jsonTokener.nextClean();
        jsonTokener.back();

        switch (nextClean) {
        case '{':
            this.json = new ObjectNodeImpl(new JSONObject(jsonTokener));
            break;
        case '[':
            this.json = new ArrayNodeImpl(new JSONArray(jsonTokener));
            break;
        default:
            throw new IllegalStateException(
                    String.format("Error processing token=%s from request=%s", nextClean, this.getRequest()));
        }
    } catch (Exception e) {
        throw MechanizeExceptionFactory.newException(e);
    }
}

From source file:com.whizzosoftware.hobson.mqtt.MQTTPlugin.java

protected void restoreDevices() {
    ConcurrentNavigableMap<String, String> devices = db.getTreeMap("devices");
    for (String id : devices.keySet()) {
        JSONObject json = new JSONObject(new JSONTokener(devices.get(id)));
        MQTTDevice d = new MQTTDevice(this, json);
        // since the device has never technically checked-in, delete the default check-in time
        d.setDeviceAvailability(false, null);
        publishDevice(d);//from w  w  w  . j  av a2  s . c  om
    }
}

From source file:com.whizzosoftware.hobson.mqtt.MQTTPlugin.java

@Override
public void messageArrived(final String topic, final MqttMessage mqttMessage) throws Exception {
    try {/*  w w w.  j a  v  a2 s. c o  m*/
        logger.trace("Message arrived on topic " + topic + ": " + new String(mqttMessage.getPayload()));

        final JSONObject json = new JSONObject(new JSONTokener(new String(mqttMessage.getPayload())));

        executeInEventLoop(new Runnable() {
            @Override
            public void run() {
                try {
                    handler.onMessage(topic, json);
                } catch (Throwable t) {
                    logger.error("Error processing MQTT message from topic " + topic + ": " + json, t);
                }
            }
        });
    } catch (JSONException e) {
        logger.error("Received invalid JSON on topic: " + topic);
    }
}

From source file:net.geco.model.iojson.JSONStore.java

public JSONStore(Reader reader, String maxIdKey) throws JSONException {
    jsonRoot = new JSONObject(new JSONTokener(reader));
    initRefMap(jsonRoot.getInt(maxIdKey) + 1);
}

From source file:io.github.medinam.jcheesum.util.VersionChecker.java

private static JSONTokener getVersionTokener() throws URISyntaxException, MalformedURLException, IOException {
    URI uri = new URI("https://medinam.github.io/jcheesum/version.json");
    return new JSONTokener(uri.toURL().openConnection().getInputStream());
}

From source file:com.check.v3.asynchttp.JsonHttpResponseHandler.java

/**
 * Returns Object of type {@link JSONObject}, {@link JSONArray}, String, Boolean, Integer, Long,
 * Double or {@link JSONObject#NULL}, see {@link org.json.JSONTokener#nextValue()}
 *
 * @param responseBody response bytes to be assembled in String and parsed as JSON
 * @return Object parsedResponse/*from   ww  w .j a v a2s . com*/
 * @throws org.json.JSONException exception if thrown while parsing JSON
 */
protected Object parseResponse(byte[] responseBody) throws JSONException {
    if (null == responseBody)
        return null;
    Object result = null;
    //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 = getResponseString(responseBody, getCharset());
    if (jsonString != null) {
        jsonString = jsonString.trim();
        if (jsonString.startsWith("{") || jsonString.startsWith("[")) {
            result = new JSONTokener(jsonString).nextValue();
        }
    }
    if (result == null) {
        result = jsonString;
    }
    return result;
}

From source file:uk.ac.imperial.presage2.core.cli.run.ExecutorModule.java

/**
 * <p>/*from   w  w  w. j av a  2s  .c o  m*/
 * Load an {@link AbstractModule} which can inject an
 * {@link ExecutorManager} with the appropriate {@link SimulationExecutor}s
 * as per provided configuration.
 * </p>
 * 
 * <p>
 * The executor config can be provided in two ways (in order of precedence):
 * </p>
 * <ul>
 * <li><code>executors.properties</code> file on the classpath. This file
 * should contain a <code>module</code> key who's value is the fully
 * qualified name of a class which extends {@link AbstractModule} and has a
 * public constructor which takes a single {@link Properties} object as an
 * argument or public no-args constructor. An instance of this class will be
 * returned.</li>
 * <li><code>executors.json</code> file on the classpath. This file contains
 * a specification of the executors to load in JSON format. If this file is
 * valid we will instantiate each executor defined in the spec and add it to
 * an {@link ExecutorModule} which will provide the bindings for them.</li>
 * </ul>
 * 
 * <h3>executors.json format</h3>
 * 
 * <p>
 * The <code>executors.json</code> file should contain a JSON object with
 * the following:
 * <ul>
 * <li><code>executors</code> key whose value is an array. Each element of
 * the array is a JSON object with the following keys:
 * <ul>
 * <li><code>class</code>: the fully qualified name of the executor class.</li>
 * <li><code>args</code>: an array of arguments to pass to a public
 * constructor of the class.</li>
 * <li><code>enableLogs</code> (optional): boolean value whether this
 * executor should save logs to file. Defaults to global value.</li>
 * <li><code>logDir</code> (optional): string path to save logs to. Defaults
 * to global value</li>
 * </ul>
 * </li>
 * <li><code>enableLogs</code> (optional): Global value for enableLogs for
 * each executor. Defaults to false.</li>
 * <li><code>logDir</code> (optional): Global value for logDir for each
 * executor. Default values depend on the executor.</li>
 * </ul>
 * </p>
 * <p>
 * e.g.:
 * </p>
 * 
 * <pre class="prettyprint">
 * {
 *    "executors": [{
 *       "class": "my.fully.qualified.Executor",
 *       "args": [1, "some string", true]
 *    },{
 *       ...
 *    }],
 * "enableLogs": true
 * }
 * </pre>
 * 
 * @return
 */
public static AbstractModule load() {
    Logger logger = Logger.getLogger(ExecutorModule.class);
    // look for executors.properties
    // This defines an AbstractModule to use instead of this one.
    // We try and load the module class given and return it.
    try {
        Properties execProps = new Properties();
        execProps.load(ExecutorModule.class.getClassLoader().getResourceAsStream("executors.properties"));
        String moduleName = execProps.getProperty("module", "");

        Class<? extends AbstractModule> module = Class.forName(moduleName).asSubclass(AbstractModule.class);
        // look for suitable ctor, either Properties parameter or default
        Constructor<? extends AbstractModule> ctor;
        try {
            ctor = module.getConstructor(Properties.class);
            return ctor.newInstance(execProps);
        } catch (NoSuchMethodException e) {
            ctor = module.getConstructor();
            return ctor.newInstance();
        }
    } catch (Exception e) {
        logger.debug("Could not create module from executors.properties");
    }
    // executors.properties fail, look for executors.json
    // This file defines a set of classes to load with parameters for the
    // constructor.
    // We try to create each defined executor and add it to this
    // ExecutorModule.
    try {
        // get executors.json file and parse to JSON.
        // throws NullPointerException if file doesn't exist, or
        // JSONException if we can't parse the JSON.
        InputStream is = ExecutorModule.class.getClassLoader().getResourceAsStream("executors.json");
        logger.debug("Processing executors from executors.json");
        JSONObject execConf = new JSONObject(new JSONTokener(new InputStreamReader(is)));
        // Create our module and look for executor specs under the executors
        // array in the JSON.
        ExecutorModule module = new ExecutorModule();
        JSONArray executors = execConf.getJSONArray("executors");

        // optional global settings
        boolean enableLogs = execConf.optBoolean("enableLogs", false);
        String logDir = execConf.optString("logDir");

        logger.info("Building Executors from executors.json");

        // Try and instantiate an instance of each executor in the spec.
        for (int i = 0; i < executors.length(); i++) {
            try {
                JSONObject executorSpec = executors.getJSONObject(i);
                String executorClass = executorSpec.getString("class");
                JSONArray args = executorSpec.getJSONArray("args");
                Class<? extends SimulationExecutor> clazz = Class.forName(executorClass)
                        .asSubclass(SimulationExecutor.class);
                // build constructor args.
                // We assume all types are in primitive form where
                // applicable.
                // The only available types are boolean, int, double and
                // String.
                Class<?>[] argTypes = new Class<?>[args.length()];
                Object[] argValues = new Object[args.length()];
                for (int j = 0; j < args.length(); j++) {
                    argValues[j] = args.get(j);
                    Class<?> type = argValues[j].getClass();
                    if (type == Boolean.class)
                        type = Boolean.TYPE;
                    else if (type == Integer.class)
                        type = Integer.TYPE;
                    else if (type == Double.class)
                        type = Double.TYPE;

                    argTypes[j] = type;
                }
                SimulationExecutor exe = clazz.getConstructor(argTypes).newInstance(argValues);
                logger.debug("Adding executor to pool: " + exe.toString());
                module.addExecutorInstance(exe);
                // logging config
                boolean exeEnableLog = executorSpec.optBoolean("enableLogs", enableLogs);
                String exeLogDir = executorSpec.optString("logDir", logDir);
                exe.enableLogs(exeEnableLog);
                if (exeLogDir.length() > 0) {
                    exe.setLogsDirectory(exeLogDir);
                }
            } catch (JSONException e) {
                logger.warn("Error parsing executor config", e);
            } catch (ClassNotFoundException e) {
                logger.warn("Unknown executor class in config", e);
            } catch (IllegalArgumentException e) {
                logger.warn("Illegal arguments for executor ctor", e);
            } catch (NoSuchMethodException e) {
                logger.warn("No matching public ctor for args in executor config", e);
            } catch (Exception e) {
                logger.warn("Could not create executor from specification", e);
            }
        }
        return module;
    } catch (JSONException e) {
        logger.debug("Could not create module from executors.json");
    } catch (NullPointerException e) {
        logger.debug("Could not open executors.json");
    }

    // no executor config, use a default config: 1 local sub process
    // executor.
    logger.info("Using default ExecutorModule.");
    return new ExecutorModule(1);
}

From source file:com.appdynamics.demo.gasp.fragment.TwitterResponderFragment.java

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

    try {//  ww w.j a  v a  2  s . c  o m
        JSONObject tweetsWrapper = (JSONObject) new JSONTokener(json).nextValue();
        JSONArray tweets = tweetsWrapper.getJSONArray("statuses");

        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;
}