Example usage for org.json.simple JSONValue parse

List of usage examples for org.json.simple JSONValue parse

Introduction

In this page you can find the example usage for org.json.simple JSONValue parse.

Prototype

public static Object parse(String s) 

Source Link

Usage

From source file:ch.simas.jtoggl.JToggl.java

/**
 * All active tasks in the workspace with the given id.
 * /*  ww  w . j a  v a  2  s .  c o  m*/
 * @param workspaceId
 *            id of the workspace
 * @return all tasks
 */
public List<Task> getActiveWorkspaceTasks(long workspaceId) {
    Client client = prepareClient();
    String url = WORKSPACE_TASKS.replace(PLACEHOLDER, String.valueOf(workspaceId));
    WebResource webResource = client.resource(url);

    String response = webResource.get(String.class);
    JSONArray data = (JSONArray) JSONValue.parse(response);

    List<Task> tasks = new ArrayList<Task>();
    if (data != null) {
        for (Object obj : data) {
            JSONObject entryObject = (JSONObject) obj;
            tasks.add(new Task(entryObject.toJSONString()));
        }
    }
    return tasks;
}

From source file:mml.handler.get.MMLGetMMLHandler.java

/**
 * Get a dialect/*from  ww  w  .  j a v a  2s .  c  om*/
 * @param docid the docid of the dialect
 * @param version1 the version id that may specify a dialect variant
 * @return an Element (div) containing the content
 */
public static String getDialect(String docid, String version1) throws MMLTestException {
    try {
        Connection conn = Connector.getConnection();
        String path = docid;
        if (version1 != null && !version1.equals("/base"))
            path += version1;
        String dialect = conn.getFromDb(Database.DIALECTS, path);
        if (dialect != null) {
            JSONObject jObj = (JSONObject) JSONValue.parse(dialect);
            dialect = (String) jObj.get(JSONKeys.BODY);
        } else {
            while (path.length() > 0 && dialect == null) {
                path = Utils.chomp(path);
                String bson = conn.getFromDb(Database.DIALECTS, path);
                if (bson != null) {
                    JSONObject jObj = (JSONObject) JSONValue.parse(bson);
                    dialect = (String) jObj.get(JSONKeys.BODY);
                }
            }
        }
        if (dialect == null)
            throw new MMLException("No dialect for " + path + " found");
        else
            return dialect;
    } catch (Exception e) {
        throw new MMLTestException(e);
    }
}

From source file:com.live.aac_jenius.globalgroupmute.utilities.Updater.java

/**
 * Make a connection to the BukkitDev API and request the newest file's details.
 *
 * @return true if successful.//from  w w  w. j  a  v a  2  s  . com
 */
private boolean read() {
    try {
        final URLConnection conn = this.url.openConnection();
        conn.setConnectTimeout(5000);

        if (this.apiKey != null) {
            conn.addRequestProperty("X-API-Key", this.apiKey);
        }
        conn.addRequestProperty("User-Agent", Updater.USER_AGENT);

        conn.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.isEmpty()) {
            this.sender.sendMessage(
                    this.prefix + "The updater could not find any files for the project id " + this.id);
            this.result = UpdateResult.FAIL_BADID;
            return false;
        }

        this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE);
        this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE);
        this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE);
        this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1))
                .get(Updater.VERSION_VALUE);

        return true;
    } catch (final IOException ex) {
        if (ex.getMessage().contains("HTTP response code: 403")) {
            this.sender.sendMessage(this.prefix
                    + "dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml\nPlease double-check your configuration to ensure it is correct.");
            this.result = UpdateResult.FAIL_APIKEY;
        } else {
            this.sender.sendMessage(this.prefix
                    + "The updater could not contact dev.bukkit.org for updating.\nIf you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
            this.result = UpdateResult.FAIL_DBO;
        }
        this.plugin.getLogger().log(Level.SEVERE, null, ex);
        return false;
    }
}

From source file:com.mobicage.rogerthat.registration.ContentBrandingRegistrationActivity.java

@SuppressWarnings("unchecked")
private void postFinishRegistration(final String username, final String password, final String invitorCode,
        final String invitorSecret) throws ClientProtocolException, IOException {
    T.REGISTRATION();//  w ww  .ja v  a2  s . co  m
    final String mobileInfo = getMobileInfo();
    HttpClient httpClient = HTTPUtil.getHttpClient();
    final HttpPost httpPost = new HttpPost(CloudConstants.REGISTRATION_FINISH_URL);
    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    List<NameValuePair> formParams = new ArrayList<NameValuePair>();
    formParams.add(new BasicNameValuePair("mobileInfo", mobileInfo));
    formParams.add(new BasicNameValuePair("account", username));
    formParams.add(new BasicNameValuePair("password", password));
    formParams.add(new BasicNameValuePair("app_id", CloudConstants.APP_ID));
    formParams.add(new BasicNameValuePair("accounts", ""));
    formParams.add(new BasicNameValuePair("invitor_code", invitorCode));
    formParams.add(new BasicNameValuePair("invitor_secret", invitorSecret));
    formParams.add(new BasicNameValuePair("beacons", ""));

    httpPost.setEntity(new UrlEncodedFormEntity(formParams, HTTP.UTF_8));
    L.d("before http final post");
    HttpResponse response = httpClient.execute(httpPost);
    L.d("after http final post");
    final int responseCode = response.getStatusLine().getStatusCode();
    if (responseCode != HttpStatus.SC_OK) {
        throw new IOException("HTTP request resulted in status code " + responseCode);
    }

    L.d("finish_registration call sent");
    HttpEntity httpEntity = response.getEntity();
    if (httpEntity == null) {
        throw new IOException("Response of '/unauthenticated/mobi/registration/finish' was null");
    }

    final Map<String, Object> responseMap = (Map<String, Object>) JSONValue
            .parse(new InputStreamReader(httpEntity.getContent()));
    if (responseMap == null) {
        throw new IOException("HTTP request responseMap was null");
    }
}

From source file:com.flaptor.indextank.api.EmbeddedIndexEngine.java

public static EmbeddedIndexEngine instantiate(String[] args) throws IOException {
    String log4jConfigPath = com.flaptor.util.FileUtil.getFilePathFromClasspath("log4j.properties");
    if (null != log4jConfigPath) {
        org.apache.log4j.PropertyConfigurator.configureAndWatch(log4jConfigPath);
    } else {//from  ww w. ja  v a2s.c  om
        logger.warn("log4j.properties not found on classpath!");
    }
    // create the parser
    CommandLineParser parser = new PosixParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(getOptions(), args);
        if (line.hasOption("help")) {
            printHelp(getOptions(), null);
            System.exit(1);
        }

        File baseDir = new File(line.getOptionValue("dir"));
        int basePort = Integer.parseInt(line.getOptionValue("port", String.valueOf(DEFAULT_BASE_PORT)));
        int boostsSize = Integer.parseInt(line.getOptionValue("boosts", String.valueOf(1)));
        int rtiSize = Integer.parseInt(line.getOptionValue("rti-size", String.valueOf(DEFAULT_RTI_SIZE)));
        boolean loadState = line.hasOption("load-state");

        SuggestValues suggest;
        if (line.hasOption("suggest")) {
            String value = line.getOptionValue("suggest");
            if (value.equalsIgnoreCase("queries")) {
                suggest = SuggestValues.QUERIES;
            } else if (value.equalsIgnoreCase("documents")) {
                suggest = SuggestValues.DOCUMENTS;
            } else {
                throw new IllegalArgumentException(
                        "Invalid value for suggest: can only be \"queries\" or \"documents\".");
            }
        } else {
            suggest = SuggestValues.NO;
        }

        StorageValues storageValue = StorageValues.RAM;
        int bdbCache = 0;
        if (line.hasOption("storage")) {
            String storageType = line.getOptionValue("storage");
            if ("bdb".equals(storageType)) {
                storageValue = StorageValues.BDB;
                bdbCache = Integer
                        .parseInt(line.getOptionValue("bdb-cache", String.valueOf(DEFAULT_BDB_CACHE)));
            } else if ("cassandra".equals(storageType)) {
                storageValue = StorageValues.CASSANDRA;
            } else if ("ram".equals(storageType)) {
                storageValue = StorageValues.RAM;
            } else {
                throw new IllegalArgumentException(
                        "storage has to be 'cassandra', 'bdb' or 'ram'. '" + storageType + "' given.");
            }
        }

        String functions = null;
        if (line.hasOption("functions")) {
            functions = line.getOptionValue("functions");
        }

        String environment;
        String val = line.getOptionValue("environment-prefix", null);
        if (null != val) {
            environment = val;
        } else {
            environment = "";
        }
        logger.info("Command line option 'environment-prefix' set to " + environment);

        boolean facets = line.hasOption("facets");
        logger.info("Command line option 'facets' set to " + facets);
        String indexCode = line.getOptionValue("index-code");
        logger.info("Command line option 'index-code' set to " + indexCode);

        Map<Object, Object> configuration = Maps.newHashMap();

        String configFile = line.getOptionValue("conf-file", null);
        logger.info("Command line option 'conf-file' set to " + configFile);

        if (configFile != null) {
            configuration = (Map<Object, Object>) JSONValue.parse(FileUtil.readFile(new File(configFile)));
        }
        EmbeddedIndexEngine ie = new EmbeddedIndexEngine(baseDir, basePort, rtiSize, loadState, boostsSize,
                suggest, storageValue, bdbCache, functions, facets, indexCode, environment, configuration);

        BoostingIndexer indexer = ie.getIndexer();
        DocumentSearcher searcher = ie.getSearcher();
        Suggestor suggestor = ie.getSuggestor();
        DocumentStorage storage = ie.getStorage();

        if (line.hasOption("snippets")) {
            indexer = new DocumentStoringIndexer(indexer, storage);
            ie.setIndexer(indexer);
            searcher = new SnippetSearcher(searcher, storage, ie.getParser());
            ie.setSearcher(searcher);
        }

        if (line.hasOption("didyoumean")) {
            if (suggest != SuggestValues.DOCUMENTS) {
                throw new IllegalArgumentException("didyoumean requires --suggest documents");
            }
            DidYouMeanSuggestor dym = new DidYouMeanSuggestor((TermSuggestor) ie.getSuggestor());
            searcher = new DidYouMeanSearcher(searcher, dym);
            ie.setSearcher(searcher);
        }

        searcher = new TrafficLimitingSearcher(searcher);
        Runtime.getRuntime().addShutdownHook(new ShutdownThread(indexer));
        return ie;

    } catch (ParseException exp) {
        printHelp(getOptions(), exp.getMessage());
    }
    System.exit(1);
    return null;
}

From source file:at.ac.sbg.icts.spacebrew.client.SpacebrewClient.java

/**
 * Callback method for the <code>WebsocketClient</code> object.
 * //from   ww w  . j  a va  2  s  .co m
 * @param string The received message
 * @throws Throwable
 */
@Override
public void onMessage(String string) {
    Object temp = JSONValue.parse(string);
    JSONObject container = (JSONObject) temp;

    JSONObject message = (JSONObject) container.get("message");

    String name = (String) message.get("name");
    String type = (String) message.get("type");
    String value = (String) message.get("value");

    if (subscriberMethods.containsKey(name)) {
        Throwable cause = null;

        try {
            Method method = subscriberMethods.get(name).get(type);

            if (type.equals(SpacebrewMessage.TYPE_BOOLEAN)) {
                method.invoke(callback, Boolean.parseBoolean(value));
            } else if (type.equals(SpacebrewMessage.TYPE_RANGE)) {
                method.invoke(callback, sanitizeRangeMessage(value));
            } else if (type.equals(SpacebrewMessage.TYPE_STRING)) {
                method.invoke(callback, value);
            }
        } catch (InvocationTargetException e) {
            cause = e.getCause();
        } catch (IllegalAccessException e) {
            cause = e.getCause();
        }

        if (cause != null) {
            log.error(
                    "Could not pass incoming spacebrew message to callback, exception occurred while calling callback method for subscriber with name \"{}\" and type \"{}\"!",
                    name, type);

            StringWriter errors = new StringWriter();
            cause.printStackTrace(new PrintWriter(errors));
            log.debug("Stacktrace: \n" + errors);
        }
    }

    if (subscriberObjects.containsKey(name)) {
        Object subscriber = null;

        try {
            subscriber = subscriberObjects.get(name).get(type);
            if (type.equals(SpacebrewMessage.TYPE_BOOLEAN)) {
                ((BooleanSubscriber) subscriber).receive(Boolean.parseBoolean(value));
            } else if (type.equals(SpacebrewMessage.TYPE_RANGE)) {
                ((RangeSubscriber) subscriber).receive(sanitizeRangeMessage(value));
            } else if (type.equals(SpacebrewMessage.TYPE_STRING)) {
                ((StringSubscriber) subscriber).receive(value);
            }
        } catch (Exception e) {
            log.error(
                    "Could not pass message to callback, exception occured while passing message to subscriber with name \"{}\"",
                    name);
            log.debug("Exception: {}", e);
        }
    }
}

From source file:com.firmansyah.imam.sewa.kendaraan.FormUser.java

public void showDataUser() {
    try {//from   w w  w .  ja  v a 2 s .c o m
        getDataURL dataurl = new getDataURL();
        DefaultTableModel model = (DefaultTableModel) tblPelanggan.getModel();

        model.setRowCount(0);

        String url = Path.serverURL + "/user/show/";

        String data = dataurl.getData(url);

        Object obj = JSONValue.parse(data);
        JSONArray dataArray = (JSONArray) obj;

        System.out.println("Banyak datanya : " + dataArray.size());

        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject getData = (JSONObject) dataArray.get(i);

            String cek_status = getData.get("status").toString();

            if (cek_status.equals("0")) {
                cek_status = "Non Aktif";
            } else {
                cek_status = "Aktif";
            }

            Object[] row = { i + 1, getData.get("nama"), getData.get("username"), cek_status,
                    getData.get("id"), };

            model.addRow(row);
        }
    } catch (IOException ex) {
        Logger.getLogger(FormUser.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.treasure_data.client.bulkimport.BulkImportClientAdaptorImpl.java

private void doUploadPart(UploadPartRequest request, UploadPartResult result) throws ClientException {
    request.setCredentials(client.getTreasureDataCredentials());
    validator.validateCredentials(client, request);

    String jsonData = null;/*from   w  w w.j  a v  a 2 s .  co m*/
    int code = 0;
    String message = null;
    try {
        conn = createConnection();

        String partID = request.getPartID();
        InputStream in;
        int size;
        if (request.isMemoryData()) {
            in = new ByteArrayInputStream(request.getMemoryData());
            size = request.getMemoryData().length;
        } else {
            String partFileName = request.getPartFileName();
            File f = new File(partFileName);
            in = new BufferedInputStream(new FileInputStream(f));
            size = (int) f.length();
        }
        // send request
        String path = String.format(HttpURL.V3_UPLOAD_PART, HttpConnectionImpl.e(request.getSessionName()),
                HttpConnectionImpl.e(partID));
        Map<String, String> header = new HashMap<String, String>();
        setUserAgentHeader(header);
        conn.doPutRequest(request, path, header, in, size);

        // receive response code
        code = conn.getResponseCode();
        message = conn.getResponseMessage();
        if (code != HttpURLConnection.HTTP_OK) {
            String errMessage = conn.getErrorMessage();
            LOG.severe(HttpClientException.toMessage("Upload part failed", message, code));
            LOG.severe(errMessage);
            throw new HttpClientException("Upload part failed", message + ", detail = " + errMessage, code);
        }

        // receive response body
        jsonData = conn.getResponseBody();
        validator.validateJSONData(jsonData);
    } catch (IOException e) {
        LOG.throwing(getClass().getName(), "uploadPart", e);
        LOG.severe(HttpClientException.toMessage(e.getMessage(), message, code));
        throw new HttpClientException("Upload part failed", message, code, e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    // parse JSON data {"name":"sess01"}
    @SuppressWarnings("unchecked")
    Map<String, Object> map = (Map<String, Object>) JSONValue.parse(jsonData);
    validator.validateJavaObject(jsonData, map);

    result.set(request.getSession());
}

From source file:com.auto.solution.TestManager.TESTRAILTestManager.java

private Object sendRequest(String method, String uri, Object data)
        throws MalformedURLException, IOException, APIException {
    URL url = new URL(this.m_url + uri);

    // Create the connection object and set the required HTTP method
    // (GET/POST) and headers (content type and basic auth).
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("Content-Type", "application/json");

    String auth = getAuthorization(this.m_user, this.m_password);
    conn.addRequestProperty("Authorization", "Basic " + auth);

    if (method == "POST") {
        // Add the POST arguments, if any. We just serialize the passed
        // data object (i.e. a dictionary) and then add it to the
        // request body.
        if (data != null) {
            byte[] block = JSONValue.toJSONString(data).getBytes("UTF-8");

            conn.setDoOutput(true);/*from w w  w. ja v  a2s  .c  o m*/
            OutputStream ostream = conn.getOutputStream();
            ostream.write(block);
            ostream.flush();
        }
    }

    // Execute the actual web request (if it wasn't already initiated
    // by getOutputStream above) and record any occurred errors (we use
    // the error stream in this case).
    int status = conn.getResponseCode();

    InputStream istream;
    if (status != 200) {
        istream = conn.getErrorStream();
        if (istream == null) {
            throw new APIException(
                    "TestRail API return HTTP " + status + " (No additional error message received)");
        }
    } else {
        istream = conn.getInputStream();
    }

    // Read the response body, if any, and deserialize it from JSON.
    String text = "";
    if (istream != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(istream, "UTF-8"));

        String line;
        while ((line = reader.readLine()) != null) {
            text += line;
            text += System.getProperty("line.separator");
        }

        reader.close();
    }

    Object result;
    if (text != "") {
        result = JSONValue.parse(text);
    } else {
        result = new JSONObject();
    }

    // Check for any occurred errors and add additional details to
    // the exception message, if any (e.g. the error message returned
    // by TestRail).
    if (status != 200) {
        String error = "No additional error message received";
        if (result != null && result instanceof JSONObject) {
            JSONObject obj = (JSONObject) result;
            if (obj.containsKey("error")) {
                error = '"' + (String) obj.get("error") + '"';
            }
        }

        throw new APIException("TestRail API returned HTTP " + status + "(" + error + ")");
    }

    return result;
}

From source file:com.treasure_data.client.DefaultClientAdaptorImpl.java

private ListTablesResult doListTables(ListTablesRequest request) throws ClientException {
    // validate request
    if (request.getDatabase() == null) {
        throw new ClientException("database is not specified");
    }/*  w w  w .j  a va2  s .c o m*/

    request.setCredentials(getConfig().getCredentials());
    validator.validateCredentials(this, request);

    String jsonData = null;
    int code = 0;
    String message = null;
    try {
        conn = createConnection();

        // send request
        String path = String.format(HttpURL.V3_TABLE_LIST,
                HttpConnectionImpl.e(request.getDatabase().getName()));
        Map<String, String> header = new HashMap<String, String>();
        setUserAgentHeader(header);
        Map<String, String> params = null;
        conn.doGetRequest(request, path, header, params);

        // receive response code
        code = conn.getResponseCode();
        message = conn.getResponseMessage();
        if (code != HttpURLConnection.HTTP_OK) {
            String errMessage = conn.getErrorMessage();
            LOG.severe(HttpClientException.toMessage("List tables failed", message, code));
            LOG.severe(errMessage);
            throw new HttpClientException("List tables failed", message + ", detail = " + errMessage, code);
        }

        // receive response body
        jsonData = conn.getResponseBody();
        validator.validateJSONData(jsonData);
    } catch (IOException e) {
        LOG.throwing(getClass().getName(), "listTables", e);
        LOG.severe(HttpClientException.toMessage(e.getMessage(), message, code));
        throw new HttpClientException("List tables failed", message, code, e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    @SuppressWarnings("rawtypes")
    Map map = (Map) JSONValue.parse(jsonData);
    validator.validateJavaObject(jsonData, map);
    @SuppressWarnings("unchecked")
    Iterator<Map<String, Object>> tableMapIter = ((List<Map<String, Object>>) map.get("tables")).iterator();
    List<TableSummary> tableList = new ArrayList<TableSummary>();
    while (tableMapIter.hasNext()) {
        Map<String, Object> tableMap = tableMapIter.next();
        String name = (String) tableMap.get("name");
        String typeName = (String) tableMap.get("type");
        Long count = (Long) tableMap.get("count");
        String schema = (String) tableMap.get("schema");
        String createdAt = (String) tableMap.get("created_at");
        String updatedAt = (String) tableMap.get("updated_at");
        TableSummary tbl = new TableSummary(request.getDatabase(), name, Table.Type.fromString(typeName), count,
                schema, createdAt, updatedAt);
        tableList.add(tbl);
    }

    ListTables<TableSummary> tables = new ListTables<TableSummary>(tableList);
    return new ListTablesResult(request.getDatabase(), tables);
}