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:org.jandroid2cloud.connection.ChannelHandler.java

@Override
public void message(String rawMsg) {
    logger.debug("Received message from server:" + rawMsg);

    try {//from  w w w .  ja v  a 2  s. c  o  m
        JSONObject jsonMessage = new JSONObject(new JSONTokener(rawMsg));
        JSONObject links = (JSONObject) jsonMessage.opt("links");
        if (links == null) {
            JSONObject link = jsonMessage.optJSONObject("link");
            handleLink(link);
        } else {
            Iterator it = links.keys();
            while (it.hasNext()) {
                String s = (String) it.next();
                if (s != null && !s.isEmpty()) {
                    JSONObject o = links.getJSONObject(s);
                    handleLink(o);
                }
            }
        }

        Map<String, String> params = new HashMap<String, String>();
        params.put("links", rawMsg);
        String response = oauth.makeRequest("http://" + config.getHost() + "/markread", Verb.POST, params);
        logger.debug("Marked message as read");
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (NetworkException e) {
        logger.error(NotificationAppender.MARKER, "Could not mark links as read.\n"
                + "You will not receive more links until that is done.\n" + "See log for details", e);
    }
}

From source file:net.netheos.pcsapi.credentials.AppInfoFileRepository.java

public AppInfoFileRepository(File file) throws IOException {
    this.file = file;

    BufferedReader reader = null;
    try {/*from w  w  w .ja va2 s .c  om*/
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), PcsUtils.UTF8));

        String line;
        while ((line = reader.readLine()) != null) { // while loop begins here
            line = line.trim();

            if (line.startsWith("#") || line.length() == 0) {
                continue;
            }

            String[] appInfoArray = line.split("=", 2);

            // Key
            String[] appInfoKeyArray = appInfoArray[0].trim().split("\\.");
            String providerName = appInfoKeyArray[0];
            String appName = appInfoKeyArray[1];

            String appInfoValue = appInfoArray[1].trim();
            JSONObject jsonObj = (JSONObject) new JSONTokener(appInfoValue).nextValue();
            String appId = jsonObj.optString("appId", null);

            AppInfo appInfo;
            if (appId != null) {
                // OAuth
                JSONArray jsonScope = jsonObj.optJSONArray("scope");
                List<String> scopeList = new ArrayList<String>();

                for (int i = 0; i < jsonScope.length(); i++) {
                    scopeList.add(jsonScope.get(i).toString());
                }
                String appSecret = jsonObj.getString("appSecret");
                String redirectUrl = jsonObj.optString("redirectUrl", null);
                appInfo = new OAuth2AppInfo(providerName, appName, appId, appSecret, scopeList, redirectUrl);

            } else {
                // Login / Password
                appInfo = new PasswordAppInfo(providerName, appName);
            }

            appInfoMap.put(getAppKey(providerName, appName), appInfo);
        }

    } finally {
        PcsUtils.closeQuietly(reader);
    }
}

From source file:org.sleeksnap.ScreenSnapper.java

/**
 * Initialize the program//from   w  ww .  j a  v a2 s . c om
 * 
 * @param map
 *            Flag to reset configuration
 */
private void initialize(final Map<String, Object> map) {
    // Check for a configuration option
    if (map.containsKey("dir")) {
        final File file = new File(map.get("dir").toString());
        if (!file.exists()) {
            file.mkdirs();
        }
        Util.setWorkingDirectory(file);
    }
    // Verify the directory
    final File local = Util.getWorkingDirectory();
    if (!local.exists()) {
        local.mkdirs();
    }
    // Load the Release info
    final URL releaseUrl = Util.getResourceByName("/org/sleeksnap/release.json");
    JSONObject releaseInfo = new JSONObject();
    if (releaseUrl != null) {
        try {
            releaseInfo = new JSONObject(new JSONTokener(releaseUrl.openStream()));
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
    // Set the UI skin
    try {
        UIManager.setLookAndFeel(releaseInfo.getString("uiClass", UIManager.getSystemLookAndFeelClassName()));
    } catch (final Exception e) {
        e.printStackTrace();
    }
    // Then start
    try {
        LoggingManager.configure();
    } catch (final IOException e) {
        logger.log(Level.WARNING, "Unable to configure logger, file logging and logging panel will not work.",
                e);
        JOptionPane.showMessageDialog(null,
                "Unable to configure logger, file logging and logging panel will not work.", "Error",
                JOptionPane.ERROR_MESSAGE);
    }
    logger.info("Loading plugins...");
    try {
        loadUploaders();
        loadFilters();
    } catch (final Exception e) {
        logger.log(Level.SEVERE, "Failed to load plugins!", e);
    }
    // Load the settings
    logger.info("Loading settings...");
    try {
        loadSettings(map.containsKey("resetconfig"));
    } catch (final Exception e) {
        logger.log(Level.SEVERE, "Failed to load settings!", e);
    }
    // Load the selected language
    try {
        Language.load(map.containsKey("language") ? map.get("language").toString()
                : configuration.getString("language", Constants.Configuration.DEFAULT_LANGUAGE));
    } catch (final IOException e) {
        logger.log(Level.SEVERE, "Failed to load language file!", e);
    }
    // Check the update mode
    final UpdaterMode mode = configuration.getEnumValue("updateMode", UpdaterMode.class);
    if (mode != UpdaterMode.MANUAL) {
        final UpdaterReleaseType type = configuration.getEnumValue("updateReleaseType",
                UpdaterReleaseType.class);
        final Updater updater = new Updater();
        if (updater.checkUpdate(type, mode == UpdaterMode.PROMPT)) {
            return;
        }
    }
    // Load the history
    logger.info("Loading history...");
    final File historyFile = new File(local, "history.json");
    history = new History(historyFile);
    if (historyFile.exists()) {
        logger.info("Using existing history file.");
        try {
            history.load();
        } catch (final Exception e) {
            logger.log(Level.WARNING, "Failed to load history", e);
        }
    } else {
        logger.info("Using new history file.");
    }
    // Validate settings
    if (!configuration.contains("hotkeys") || !configuration.contains("uploaders")) {
        promptConfigurationReset();
    }
    // Register the hotkeys
    logger.info("Registering keys...");
    keyManager = new HotkeyManager(this);
    keyManager.initializeInput();
    logger.info("Opening tray icon...");
    initializeTray();
    logger.info("Ready.");
}

From source file:org.sleeksnap.ScreenSnapper.java

/**
 * Load the settings for an uploader//from   w w  w.  j ava  2s. c  o m
 * 
 * @param uploader
 *            The uploader
 */
private void loadUploaderSettings(final Uploader<?> uploader) {
    if (!uploader.hasSettings()) {
        return;
    }
    final File file = getSettingsFile(uploader.getClass());
    if (!file.exists()) {
        final File old = getSettingsFile(uploader.getClass(), "xml");
        if (old.exists()) {
            logger.info("Converting old xml style file for " + uploader.getName() + " to json...");
            final Properties props = new Properties();
            try {
                final FileInputStream input = new FileInputStream(old);
                try {
                    props.loadFromXML(input);
                } finally {
                    input.close();
                }
                try {
                    // Update the settings
                    setUploaderSettings(uploader, new JSONObject(new JSONTokener(input)));
                    // Save it
                    if (uploader.hasSettings()) {
                        uploader.getSettings().save(file);
                    } else if (uploader.hasParent() && uploader.getParentUploader().hasSettings()) {
                        uploader.getParentUploader().getSettings().save(file);
                    }
                    // If everything went well, delete the old file
                    old.delete();
                } catch (final Exception e) {
                    e.printStackTrace();
                }
            } catch (final IOException e) {
                // It's invalid, don't try to use it
                old.delete();
            }
        }
    } else if (file.exists()) {
        try {
            final FileInputStream input = new FileInputStream(file);
            try {
                setUploaderSettings(uploader, new JSONObject(new JSONTokener(input)));
            } finally {
                input.close();
            }
        } catch (final Exception e) {
            file.delete();
        }
    }
}

From source file:tracerouteip.FXMLDocumentController.java

@FXML
private void handleButtonTrace(ActionEvent event) {

    String str = tf_dest.getText();
    if (!str.isEmpty())//Saisie destiantion non vide
    {//from w  w w .  j  a v  a  2s . c  om
        if (str.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"))//Destination est une ipV4
        {
            System.out.println("Destination IPV4 OK");
        } else //On suppose que destination est une URL
        {
            System.out.println("Destination URL");
            try {
                adrDest = InetAddress.getByName(str);
                str = adrDest.getHostAddress();
                System.out.println("IP destination : " + str);
            } catch (UnknownHostException ex) {
                System.out.println("Erreur getByName");
            }
        }

        //try {
        //https://code.google.com/p/org-json-java/downloads/list

        try {
            URI uri;
            //uri = new URI("http://freegeoip.net/json/"+str);
            uri = new URI("http://ip-api.com/json/" + str);
            System.out.println("URI : " + uri.toString());
            URL url = uri.toURL();

            InputStream inputStream = url.openStream();

            JSONTokener tokener = new JSONTokener(inputStream);
            JSONObject root = new JSONObject(tokener);
            //String rootJson = root.toString();
            //System.out.println("rootJson : "+rootJson);
            /*double lat = root.getDouble("latitude");
            double lng = root.getDouble("longitude");*/
            double lat = root.getDouble("lat");
            double lng = root.getDouble("lon");
            System.out.println("Latitude : " + lat + "\nLongitude : " + lng);

        } catch (URISyntaxException ex) {
            Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MalformedURLException ex) {
            Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JSONException ex) {
            Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
        }

    } else {
        System.out.println("Destination VIDE");
    }
}

From source file:com.android.launcher4.compat.PackageInstallerCompatV16.java

private static PackageInstallInfo infoFromJson(String packageName, String json) {
    PackageInstallInfo info = new PackageInstallInfo(packageName);
    try {/*from ww  w .j  a  v  a  2s.  co m*/
        JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
        info.state = object.getInt(KEY_STATE);
        info.progress = object.getInt(KEY_PROGRESS);
    } catch (JSONException e) {
        Log.e(TAG, "failed to deserialize app state update", e);
    }
    return info;
}

From source file:org.cfg4j.source.context.propertiesprovider.JsonBasedPropertiesProvider.java

/**
 * Get {@link Properties} for a given {@code inputStream} treating it as a JSON file.
 *
 * @param inputStream input stream representing JSON file
 * @return properties representing values from {@code inputStream}
 * @throws IllegalStateException when unable to read properties
 *///from  w  w w .ja  va 2  s.  c  o m
@Override
public Properties getProperties(InputStream inputStream) {
    requireNonNull(inputStream);

    Properties properties = new Properties();

    try {

        JSONTokener tokener = new JSONTokener(inputStream);
        if (tokener.end()) {
            return properties;
        }
        if (tokener.nextClean() == '"') {
            tokener.back();
            properties.put("content", tokener.nextValue().toString());
        } else {
            tokener.back();
            JSONObject obj = new JSONObject(tokener);

            Map<String, Object> yamlAsMap = convertToMap(obj);
            properties.putAll(flatten(yamlAsMap));
        }

        return properties;

    } catch (Exception e) {
        throw new IllegalStateException("Unable to load json configuration from provided stream", e);
    }
}

From source file:net.majorkernelpanic.spydroid.api.RequestHandler.java

/**
 * Executes a batch of requests and returns all the results
 * @param request Contains a json containing one or more requests
 * @return A JSON to send back/* w  w w  .j  av  a  2 s.c o m*/
 */
static public String handle(String request) {
    StringBuilder response = new StringBuilder();
    JSONTokener tokener = new JSONTokener(request);

    try {
        Object token = tokener.nextValue();

        response.append("{");

        // More than one request to execute
        if (token instanceof JSONArray) {
            JSONArray array = (JSONArray) token;
            for (int i = 0; i < array.length(); i++) {
                JSONObject object = (JSONObject) array.get(i);
                response.append("\"" + object.getString("action") + "\":");
                exec(object, response);
                if (i != array.length() - 1)
                    response.append(",");
            }
            // Only One request
        } else if (token instanceof JSONObject) {
            JSONObject object = (JSONObject) token;
            response.append("\"" + object.getString("action") + "\":");
            exec(object, response);
        }

        response.append("}");

    } catch (Exception e) {
        // Pokemon, gotta catch'em all !
        Log.e(TAG, "Invalid request: " + request);
        e.printStackTrace();
        return "INVALID REQUEST";
    }

    Log.d(TAG, "Request: " + request);
    Log.d(TAG, "Answer: " + response.toString());

    return response.toString();
}

From source file:org.everit.json.schema.RelativeURITest.java

private void run() {
    SchemaLoader.builder().resolutionScope("http://localhost:1234/schema/")
            .schemaJson(new JSONObject(new JSONTokener(
                    getClass().getResourceAsStream("/org/everit/json/schema/relative-uri/schema/main.json"))))
            .build().load().build();//  ww  w.  j  a  v  a  2 s.  c  om
}

From source file:com.whizzosoftware.hobson.dto.data.DataStreamDTOTest.java

@Test
public void testJSONConstructor() {
    JSONObject json = new JSONObject(new JSONTokener(
            "{\"name\":\"My Data Stream\",\"fields\":[{\"@id\":\"id1\", \"name\":\"field1\",\"variable\":{\"@id\":\"/api/v1/users/local/hubs/local/plugins/com.whizzosoftware.hobson.hub.hobson-hub-sample/devices/wstation/variables/inRh\"}},{\"@id\":\"id1\", \"name\":\"field2\",\"variable\":{\"@id\":\"/api/v1/users/local/hubs/local/plugins/com.whizzosoftware.hobson.hub.hobson-hub-sample/devices/bulb/variables/color\"}}]}"));
    DataStreamDTO dto = new DataStreamDTO.Builder(json).build();
    assertEquals("My Data Stream", dto.getName());
    assertEquals(2, dto.getFields().size());

    for (DataStreamFieldDTO dsf : dto.getFields()) {
        assertTrue(//w  ww. ja  v  a 2 s  .  c o  m
                "/api/v1/users/local/hubs/local/plugins/com.whizzosoftware.hobson.hub.hobson-hub-sample/devices/wstation/variables/inRh"
                        .equals(dsf.getVariable().getId())
                        || "/api/v1/users/local/hubs/local/plugins/com.whizzosoftware.hobson.hub.hobson-hub-sample/devices/bulb/variables/color"
                                .equals(dsf.getVariable().getId()));
        assertTrue("id1".equals(dsf.getId()) || "id2".equals(dsf.getId()));
        assertTrue("field1".equals(dsf.getName()) || "field2".equals(dsf.getName()));
    }
}