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:eu.hansolo.accs.RestClient.java

private JSONArray getSpecificArray(final URIBuilder BUILDER) {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpGet get = new HttpGet(BUILDER.build());

        CloseableHttpResponse response = httpClient.execute(get);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            //throw new RuntimeException("Failed: HTTP error code: " + statusCode);
            return new JSONArray();
        }//from   w w  w .  j a v a2s . co  m

        String output = getFromResponse(response);
        JSONArray jsonArray = (JSONArray) JSONValue.parse(output);
        return jsonArray;
    } catch (URISyntaxException | IOException e) {
        return new JSONArray();
    }
}

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

/**
 * Create and then start the given time entry.
 * //  w  ww.  j  a v a2 s.  c  o m
 * @param timeEntry
 *            the time entry to start
 * @return created {@link TimeEntry}
 */
public TimeEntry startTimeEntry(TimeEntry timeEntry) {
    Client client = prepareClient();
    WebResource webResource = client.resource(TIME_ENTRY_START);

    JSONObject object = createTimeEntryRequestParameter(timeEntry);
    String response = webResource.entity(object.toJSONString(), MediaType.APPLICATION_JSON_TYPE)
            .post(String.class);

    object = (JSONObject) JSONValue.parse(response);
    JSONObject data = (JSONObject) object.get(DATA);
    return new TimeEntry(data.toJSONString());
}

From source file:kvadrere.pig.geo.TileGeometry.java

/**
   Convenience method for parsing JSON Strings
        //from   w w w  .  j  a v a  2  s  .  co m
   * @param jsonBlob
   *
   * @return JSONObject representation of jsonBlob String
           
   */
public JSONObject parseJSONString(String jsonBlob) {
    Reader reader = new StringReader(jsonBlob);
    Object jsonObject = JSONValue.parse(reader);
    return (JSONObject) jsonObject;
}

From source file:edu.cmu.cs.quiltview.RequestPullingService.java

private void pullRequest() {
    String resultTxt = " " + DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis());
    Log.i(LOG_TAG, "Begin pull." + resultTxt);

    getLocation();// ww w . j  a  va  2s .com
    double latitude, longitude;
    if (mLocation != null) {
        Log.i(LOG_TAG, "Real Location");
        latitude = mLocation.getLatitude();
        longitude = mLocation.getLongitude();
    } else {
        //TODO test real location
        /*
         * As we usually develop and demo indoor, the GPS location is not always 
         * available. For the convenience of development, we use theses fixed fake 
         * location. This is somewhere on Carnegie Mellon University campus
         * Wenlu Hu, April 2014
         */
        Log.i(LOG_TAG, "Fake Location");
        latitude = 40.443469; //40.44416720;
        longitude = -79.943862; //-79.94336060;
    }
    Log.i(LOG_TAG, "Location: " + latitude + ", " + longitude);

    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(Const.quiltview_server_addr + "/latest/" + "?user_id=" + mSerialNumber + "&lat="
                + latitude + "&lng=" + longitude);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setRequestProperty("Content-Type", "application/json");

        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream is = urlConnection.getInputStream();
            int responseLen = urlConnection.getContentLength();
            Log.i(LOG_TAG, "Response Len = " + responseLen);

            //Read the json file 
            byte[] jsonBuffer = new byte[responseLen];
            Log.i(LOG_TAG, "Response Len = " + is.read(jsonBuffer));
            String jsonString = new String(jsonBuffer, "UTF-8");
            Log.i(LOG_TAG, "Got response: " + jsonString);

            try {
                JSONObject obj = (JSONObject) JSONValue.parse(jsonString);
                String query = obj.get("content").toString();
                int queryID = Integer.parseInt(obj.get("query_id").toString());
                int userID = Integer.parseInt(obj.get("user_id").toString());
                String imagePath = obj.get("image").toString();
                Log.i(LOG_TAG, userID + ", " + queryID + ": " + query + "&" + imagePath);
                imagePath = saveImageToLocal(imagePath);

                recordForQuery(query, queryID, userID, imagePath);
            } catch (NullPointerException ex) {
                Log.i(LOG_TAG, "No valid query");
            }

        } else {
            Log.e(LOG_TAG,
                    "Response " + urlConnection.getResponseCode() + ":" + urlConnection.getResponseMessage());
        }

    } catch (MalformedURLException ex) {
        Log.e(LOG_TAG, "", ex);
    } catch (IOException ex) {
        Log.e(LOG_TAG, "", ex);
    } finally {
        if (urlConnection != null)
            urlConnection.disconnect();
    }

}

From source file:com.jts.rest.profileservice.utils.RestServiceHelper.java

/**
 * Makes a get request to the given url and returns the json object
 * @param sessionId/*from  w  w  w  .  j a va  2  s  .  c  o m*/
 * @param url
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
public static JSONArray makeGetRequest(String sessionId, String url) throws MalformedURLException, IOException {
    URL endpoint = new URL(url);
    HttpURLConnection urlc = (HttpURLConnection) endpoint.openConnection();
    urlc.setRequestProperty("Authorization", "OAuth " + sessionId);
    urlc.setRequestMethod("GET");
    urlc.setDoOutput(true);
    String output = OauthHelperUtils.readInputStream(urlc.getInputStream());
    urlc.disconnect();
    Object json = JSONValue.parse(output);
    JSONArray jsonArr = (JSONArray) json;
    return jsonArr;
}

From source file:com.memetix.mst.MicrosoftTranslatorAPI.java

private static String jsonToString(final String inputString) throws Exception {
    String json = (String) JSONValue.parse(inputString);
    return json.toString();
}

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

public void init(final MainService mainService) {
    T.UI();// w w  w .j  a v  a 2  s .  com
    mInstallationId = UUID.randomUUID().toString();
    reInit();
    new SafeAsyncTask<Object, Object, Object>() {

        @SuppressWarnings("unchecked")
        @Override
        protected Object safeDoInBackground(Object... params) {
            try {
                HttpClient httpClient = HTTPUtil.getHttpClient(10000, 3);
                final HttpPost httpPost = new HttpPost(CloudConstants.REGISTRATION_REGISTER_INSTALL_URL);
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
                List<NameValuePair> formParams = new ArrayList<NameValuePair>();
                formParams.add(new BasicNameValuePair("version", MainService.getVersion(mainService)));
                formParams.add(new BasicNameValuePair("install_id", mInstallationId));
                formParams.add(new BasicNameValuePair("platform", "android"));
                formParams.add(new BasicNameValuePair("language", Locale.getDefault().getLanguage()));
                formParams.add(new BasicNameValuePair("country", Locale.getDefault().getCountry()));
                formParams.add(new BasicNameValuePair("app_id", CloudConstants.APP_ID));

                UrlEncodedFormEntity entity;
                try {
                    entity = new UrlEncodedFormEntity(formParams, HTTP.UTF_8);
                } catch (UnsupportedEncodingException e) {
                    L.bug(e);
                    return true;
                }
                httpPost.setEntity(entity);
                L.d("Sending installation id: " + mInstallationId);
                try {
                    HttpResponse response = httpClient.execute(httpPost);
                    L.d("Installation id sent");
                    int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode != HttpStatus.SC_OK) {
                        L.e("HTTP request resulted in status code " + statusCode);
                        return false;
                    }
                    HttpEntity httpEntity = response.getEntity();
                    if (httpEntity == null) {
                        L.e("Response of '/unauthenticated/mobi/registration/register_install' was null");
                        return false;
                    }

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

                    if ("success".equals(responseMap.get("result"))) {
                    } else {
                        L.e("HTTP request result was not 'success' but: " + responseMap.get("result"));
                        return false;
                    }
                } catch (ClientProtocolException e) {
                    L.bug(e);
                    return false;
                } catch (IOException e) {
                    L.bug(e);
                    return false;
                }

                return true;
            } catch (Exception e) {
                L.bug(e);
                return false;
            }
        }

        @Override
        protected void safeOnPostExecute(Object result) {
            T.UI();
            Boolean b = (Boolean) result;
            if (mInstallationIdSent) {
                mInstallationIdSent = b;
                save();
            }
        }

        @Override
        protected void safeOnCancelled(Object result) {
        }

        @Override
        protected void safeOnProgressUpdate(Object... values) {
        }

        @Override
        protected void safeOnPreExecute() {
        }

    }.execute();
}

From source file:backtype.storm.utils.Utils.java

public static Map readCommandLineOpts() {
    Map ret = new HashMap();
    String commandOptions = System.getProperty("storm.options");
    if (commandOptions != null) {
        String[] configs = commandOptions.split(",");
        for (String config : configs) {
            config = URLDecoder.decode(config);
            String[] options = config.split("=", 2);
            if (options.length == 2) {
                Object val = JSONValue.parse(options[1]);
                if (val == null) {
                    val = options[1];
                }/*from w w w.  j  av a2 s .  co m*/
                ret.put(options[0], val);
            }
        }
    }
    return ret;
}

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

private AuthenticateResult doAuthenticate(AuthenticateRequest request) throws ClientException {
    request.setCredentials(getConfig().getCredentials());

    String jsonData = null;/* w  w  w .  ja v  a2 s.  c  o  m*/
    String message = null;
    int code = 0;
    try {
        conn = createConnection();

        // send request
        String path = HttpURL.V3_USER_AUTHENTICATE;
        Map<String, String> header = new HashMap<String, String>();
        setUserAgentHeader(header);
        Map<String, String> params = new HashMap<String, String>();
        params.put("user", HttpConnectionImpl.e(request.getEmail()));
        params.put("password", HttpConnectionImpl.e(request.getPassword()));
        conn.doPostRequest(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("Authentication failed", message, code));
            LOG.severe(errMessage);
            throw new HttpClientException("Authentication failed", message + ", detail = " + errMessage, code);
        }

        // receive response body
        jsonData = conn.getResponseBody();
        validator.validateJSONData(jsonData);
    } catch (IOException e) {
        LOG.log(Level.WARNING, "Authentication failed", e);
        throw new HttpClientException("Authentication failed", message, code, e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    // { "user":"myemailaddress","apikey":"myapikey" }
    // parse JSON data
    @SuppressWarnings("unchecked")
    Map<String, String> map = (Map<String, String>) JSONValue.parse(jsonData);
    validator.validateJavaObject(jsonData, map);
    //String user = map.get("user");
    String apiKey = map.get("apikey");
    TreasureDataCredentials credentails = new TreasureDataCredentials(apiKey);

    return new AuthenticateResult(credentails);
}

From source file:com.treasuredata.jdbc.TDDatabaseMetaData.java

@SuppressWarnings("unchecked")
public ResultSet getColumns(String catalog, final String schemaPattern, final String tableNamePattern,
        final String columnNamePattern) throws SQLException {
    if (catalog == null) {
        catalog = "default";
    }//w  w  w. j ava2 s .c  o m

    String tableNamePattern1 = convertPattern(tableNamePattern);
    String columnNamePattern1 = convertPattern(columnNamePattern);

    List<TableSummary> ts = null;
    try {
        ts = api.showTables();
        if (ts == null) {
            ts = new ArrayList<TableSummary>();
        }
    } catch (ClientException e) {
        throw new SQLException(e);
    }

    List<TDColumn> columns = new ArrayList<TDColumn>();
    for (TableSummary t : ts) {
        if (!t.getName().matches(tableNamePattern1)) {
            continue;
        }

        List<List<String>> schemaFields = null;
        try {
            schemaFields = (List<List<String>>) JSONValue.parse(t.getSchema());
        } catch (Exception e) {
            continue;
        }

        boolean hasTimeColumn = false;
        int ordinal = 1;
        for (List<String> schemaField : schemaFields) {
            String fname = schemaField.get(0);
            String ftype = schemaField.get(1);

            if (fname.equals("time")) {
                hasTimeColumn = true;
            }

            if (!fname.matches(columnNamePattern1)) {
                continue;
            }

            TDColumn c = new TDColumn(fname, t.getName(), catalog, ftype, "comment", ordinal);
            columns.add(c);
            ordinal++;
        }

        if (t.getType() == Table.Type.LOG && !hasTimeColumn && "time".matches(columnNamePattern1)) {
            TDColumn c = new TDColumn("time", t.getName(), catalog, "int", "comment", ordinal);
            columns.add(c);
            ordinal++;
        }
    }
    Collections.sort(columns, new Comparator<TDColumn>() {
        /**
         * We sort the output of getColumns to guarantee jdbc compliance.
         * First check by table name then by ordinal position
         */
        public int compare(TDColumn o1, TDColumn o2) {
            int compareName = o1.getTableName().compareTo(o2.getTableName());
            if (compareName == 0) {
                if (o1.getOrdinal() > o2.getOrdinal()) {
                    return 1;
                } else if (o1.getOrdinal() < o2.getOrdinal()) {
                    return -1;
                }
                return 0;
            } else {
                return compareName;
            }
        }
    });

    List<String> names = Arrays.asList("TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "COLUMN_NAME", "DATA_TYPE",
            "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS", "NUM_PREC_RADIX", "NULLABLE",
            "REMARKS", "COLUMN_DEF", "SQL_DATA_TYPE", "SQL_DATETIME_SUB", "CHAR_OCTET_LENGTH",
            "ORDINAL_POSITION", "IS_NULLABLE", "SCOPE_CATLOG", "SCOPE_SCHEMA", "SCOPE_TABLE",
            "SOURCE_DATA_TYPE", "IS_AUTOINCREMENT");

    List<String> types = Arrays.asList("STRING", // TABLE_CAT
            "STRING", // TABLE_SCHEM
            "STRING", // TABLE_NAME
            "STRING", // COLUMN_NAME
            "INT", // DATA_TYPE
            "STRING", // TYPE_NAME
            "INT", // COLUMN_SIZE
            "INT", // BUFFER_LENGTH
            "INT", // DECIMAL_DIGITS
            "INT", // NUM_PREC_RADIX
            "INT", // NULLABLE
            "STRING", // REMARKS
            "STRING", // COLUMN_DEF
            "INT", // SQL_DATA_TYPE
            "INT", // SQL_DATEIME_SUB
            "INT", // CHAR_OCTET_LENGTH
            "INT", // ORDINAL_POSITION
            "STRING", // IS_NULLABLE
            "STRING", // SCOPE_CATLOG
            "STRING", // SCOPE_SCHEMA
            "STRING", // SCOPE_TABLE
            "INT", // SOURCE_DATA_TYPE
            "STRING" // IS_AUTOINCREMENT
    );

    try {
        return new TDMetaDataResultSet<TDColumn>(names, types, columns) {
            private int cnt = 0;

            public boolean next() throws SQLException {
                if (cnt >= data.size()) {
                    return false;
                }

                TDColumn column = data.get(cnt);
                List<Object> a = new ArrayList<Object>(23);
                a.add(column.getTableCatalog()); // TABLE_CAT String =>
                // table catalog (may be
                // null)
                a.add(null); // TABLE_SCHEM String => table schema (may be
                // null)
                a.add(column.getTableName()); // TABLE_NAME String => table
                // name
                a.add(column.getColumnName()); // COLUMN_NAME String =>
                // column name
                a.add(column.getSqlType()); // DATA_TYPE short => SQL type
                // from java.sql.Types
                a.add(column.getType()); // TYPE_NAME String => Data source
                // dependent type name.
                a.add(column.getColumnSize()); // COLUMN_SIZE int => column
                // size.
                a.add(null); // BUFFER_LENGTH is not used.
                a.add(column.getDecimalDigits()); // DECIMAL_DIGITS int =>
                // number of fractional
                // digits
                a.add(column.getNumPrecRadix()); // NUM_PREC_RADIX int =>
                // typically either 10 or 2
                a.add(DatabaseMetaData.columnNullable); // NULLABLE int =>
                // is NULL allowed?
                a.add(column.getComment()); // REMARKS String => comment
                // describing column (may be
                // null)
                a.add(null); // COLUMN_DEF String => default value (may be
                // null)
                a.add(null); // SQL_DATA_TYPE int => unused
                a.add(null); // SQL_DATETIME_SUB int => unused
                a.add(null); // CHAR_OCTET_LENGTH int
                a.add(column.getOrdinal()); // ORDINAL_POSITION int
                a.add("YES"); // IS_NULLABLE String
                a.add(null); // SCOPE_CATLOG String
                a.add(null); // SCOPE_SCHEMA String
                a.add(null); // SCOPE_TABLE String
                a.add(null); // SOURCE_DATA_TYPE short
                a.add("NO"); // IS_AUTOINCREMENT String

                row = a;
                cnt++;
                return true;
            }
        };
    } catch (Exception e) {
        throw new SQLException(e);
    }
}