Example usage for org.json.simple.parser JSONParser parse

List of usage examples for org.json.simple.parser JSONParser parse

Introduction

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

Prototype

public Object parse(Reader in) throws IOException, ParseException 

Source Link

Usage

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

private static JSONObject readAccessToken() {
    Reader reader = null;//w ww  .java2 s  .  c om
    try {
        reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(tokenFilename), StandardCharsets.UTF_8));
        JSONParser parser = new JSONParser();
        return (JSONObject) parser.parse(reader);
    } catch (IOException | ParseException e) {
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
    }
    return null;
}

From source file:com.nubits.nubot.trading.wrappers.TradeUtilsCCEDK.java

public static String getCCDKEvalidNonce(String htmlString) {
    //used by ccedkqueryservice

    JSONParser parser = new JSONParser();
    try {//from  w w w  .  j a va 2 s. c o m
        //{"errors":{"nonce":"incorrect range `nonce`=`1234567891`, must be from `1411036100` till `1411036141`"}
        JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString));
        JSONObject errors = (JSONObject) httpAnswerJson.get("errors");
        String nonceError = (String) errors.get("nonce");

        //String startStr = " must be from";
        //int indexStart = nonceError.lastIndexOf(startStr) + startStr.length() + 2;
        //String from = nonceError.substring(indexStart, indexStart + 10);

        String startStr2 = " till";
        int indexStart2 = nonceError.lastIndexOf(startStr2) + startStr2.length() + 2;
        String to = nonceError.substring(indexStart2, indexStart2 + 10);

        //if (to.equals(from)) {
        //    LOG.info("Detected ! " + to + " = " + from);
        //    return "retry";
        //}

        return to;
    } catch (ParseException ex) {
        LOG.error(htmlString + " " + ex.toString());
        return "1234567891";
    }
}

From source file:com.github.lgi2p.obirs.utils.JSONConverter.java

public static ObirsQuery parseObirsJSONQuery(SM_Engine engine, String jsonQuery)
        throws ParseException, Exception {

    logger.info("parsing query: " + jsonQuery);
    URIFactory factory = URIFactoryMemory.getSingleton();

    jsonQuery = jsonQuery.replace("\n", "");
    jsonQuery = jsonQuery.replace("\r", "");
    JSONParser parser = new JSONParser();

    Object obj = parser.parse(jsonQuery);
    JSONObject jsonObject = (JSONObject) obj;
    String aggregator = (String) jsonObject.get("aggregator");
    String similarityMeasure = (String) jsonObject.get("similarityMeasure");
    Double aggregatorParameter;/*w w w . j a v a  2s.  com*/
    if (jsonObject.get("aggregatorParameter") != null) {
        aggregatorParameter = Double.parseDouble(jsonObject.get("aggregatorParameter").toString());
    } else {
        aggregatorParameter = 2.0;
    }
    Double scoreThreshold = (Double) jsonObject.get("scoreThreshold");
    Integer numberOfResults = (Integer) jsonObject.get("numberOfResults");

    JSONArray concepts = (JSONArray) jsonObject.get("concepts");

    Map<URI, Double> conceptsMap = new HashMap<URI, Double>();

    ObirsQuery query = new ObirsQuery(conceptsMap, aggregator, similarityMeasure, aggregatorParameter,
            scoreThreshold, numberOfResults);

    if (concepts != null) {
        Iterator<JSONObject> iterator = concepts.iterator();
        while (iterator.hasNext()) {
            JSONObject concept = iterator.next();
            Double weight = Double.parseDouble(concept.get("weight").toString());
            Object uriString = concept.get("uri");

            if (uriString == null) {
                throw new SLIB_Ex_Critic("Error a URI must be specified for each query concept");
            }
            URI uri = factory.getURI(uriString.toString());

            if (engine.getGraph().containsVertex(uri)) {
                query.addConcept(uri, weight);
            } else {
                throw new Exception("concept associated to URI '" + uri + "' does not exists...");
            }
        }
    }
    return query;
}

From source file:com.tr8n.core.Utils.java

/**
 * Parsing JSON from string//from www. j a  v a2s .  com
 * @param jsonText
 * @return
 */
public static Object parseJSON(String jsonText) {
    if (jsonText == null)
        return null;

    JSONParser p = new JSONParser();
    Object obj = null;
    try {
        obj = p.parse(jsonText);
    } catch (ParseException pe) {
        Tr8n.getLogger().logException(pe);
        return null;
    }

    return obj;
}

From source file:com.creapple.tms.mobiledriverconsole.utils.MDCUtils.java

/**
 * Get distance information between two GPS
 * @param originLat/* ww w  .j a va  2  s . c  o  m*/
 * @param originLon
 * @param destLat
 * @param destLon
 * @return
 */
public static String[] getDistanceInfo(double originLat, double originLon, double destLat, double destLon) {

    String[] infos = new String[] { "0", "0" };

    String address = Constants.GOOGLE_DISTANCE_MATRIX_ADDRESS;
    address += originLat + "," + originLon;
    address += "&destinations=";
    address += destLat + "," + destLon;
    address += "&mode=driving&units=metric&language=en&key=";
    address += Constants.GOOGLE_DISTANCE_MATRIX_API_KEY;
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(address).build();
    Response response = null;
    String dist = null;
    try {
        response = client.newCall(request).execute();
        dist = response.body().string();
    } catch (IOException e) {
        return infos;
    }

    Log.d("@@@@@@", dist);
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = null;
    try {
        jsonObject = (JSONObject) jsonParser.parse(dist);
    } catch (ParseException e) {
        return infos;
    }

    // status check as well

    JSONArray rows = (JSONArray) jsonObject.get(Constants.GOOGLE_DISTANCE_MATRIX_ROWS);
    for (int i = 0; i < rows.size(); i++) {
        JSONObject obj = (JSONObject) rows.get(i);
        JSONArray elements = (JSONArray) obj.get(Constants.GOOGLE_DISTANCE_MATRIX_ELEMENTS);
        for (int j = 0; j < elements.size(); j++) {
            JSONObject datas = (JSONObject) elements.get(j);
            JSONObject distance = (JSONObject) datas.get(Constants.GOOGLE_DISTANCE_MATRIX_DISTANCE);
            JSONObject duration = (JSONObject) datas.get(Constants.GOOGLE_DISTANCE_MATRIX_DURATION);
            infos[0] = distance.get(Constants.GOOGLE_DISTANCE_MATRIX_VALUE) + "";
            infos[1] = duration.get(Constants.GOOGLE_DISTANCE_MATRIX_TEXT) + "";

        }

    }
    String status = jsonObject.get(Constants.GOOGLE_DISTANCE_MATRIX_STATUS).toString();
    //        Log.d("@@@@@@", status);
    if (!StringUtils.equalsIgnoreCase(Constants.GOOGLE_DISTANCE_MATRIX_OK, status)) {
        return infos;
    }
    return infos;
}

From source file:com.apigee.edge.config.utils.ConfigReader.java

/**
 * Example Hierarchy/*from   w  ww. jav  a  2  s  . c  o  m*/
 * orgConfig.developerApps.<developerId>.apps
 * 
 * Returns Map of
 * <developerId> => [ {app1}, {app2}, {app3} ]
 */
public static Map<String, List<String>> getOrgConfigWithId(File configFile) throws ParseException, IOException {

    Logger logger = LoggerFactory.getLogger(ConfigReader.class);

    JSONParser parser = new JSONParser();
    Map<String, List<String>> out = null;
    List<String> outStrs = null;
    try {
        BufferedReader bufferedReader = new BufferedReader(new java.io.FileReader(configFile));

        Map sConfig = (Map) parser.parse(bufferedReader);
        if (sConfig == null)
            return null;

        // orgConfig.developerApps.<developerId>
        Iterator it = sConfig.entrySet().iterator();
        out = new HashMap<String, List<String>>();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry) it.next();
            JSONArray confs = (JSONArray) pair.getValue();
            outStrs = new ArrayList<String>();
            for (Object conf : confs) {
                outStrs.add(((JSONObject) conf).toJSONString());
            }
            out.put((String) pair.getKey(), outStrs);
        }

    } catch (IOException ie) {
        logger.info(ie.getMessage());
        throw ie;
    } catch (ParseException pe) {
        logger.info(pe.getMessage());
        throw pe;
    }

    return out;
}

From source file:agileinterop.AgileInterop.java

/**
 * Example://from   ww  w.j a v a2  s .  co m
 * {
 *     "psrNumbers": ["SR-123456", "SR-234567", "SR-345678", "SR-456789"],
 *     "database": "C:\\Users\\mburny\\Desktop\\AgileBot\\mt\\agile.db",
 *     "map": "C:\\Users\\mburny\\Desktop\\AgileBot\\mt\\map.json"
 * }
 * 
 * @param body
 * @return 
 * @throws ParseException
 */
private static JSONObject crawlAgileByPSRList(String body) throws ParseException {
    // Parse body as JSON
    JSONParser parser = new JSONParser();
    JSONArray jsonBody = (JSONArray) parser.parse(body);

    return null;
}

From source file:agileinterop.AgileInterop.java

/**
 * Example:/*from www .j  a va 2 s. c  o  m*/
 * {
 *     "startDate": "02/12/2014",
 *     "endDate": "03/01/2014",
 *     "database": "C:\\Users\\mburny\\Desktop\\AgileBot\\mt\\agile.db",
 *     "map": "C:\\Users\\mburny\\Desktop\\AgileBot\\mt\\map.json"
 * }
 * 
 * @param body
 * @return
 * @throws ParseException 
 */
private static JSONObject crawlAgileByDateOriginated(String body) throws ParseException {
    // Parse body as JSON
    JSONParser parser = new JSONParser();
    JSONObject jsonBody = (JSONObject) parser.parse(body);

    return null;
}

From source file:com.ibm.bluemix.samples.PostgreSQLReportedErrors.java

/**
 * Establishes a connection to the database
 * /*ww w.j  a v a  2s  .co  m*/
 * @return the established connection
 * 
 * @throws Exception
 *          a custom exception thrown if no postgresql service URL was found
 */
public static Connection getConnection() throws Exception {
    Map<String, String> env = System.getenv();

    if (env.containsKey("VCAP_SERVICES")) {
        // we are running on cloud foundry, let's grab the service details from vcap_services
        JSONParser parser = new JSONParser();
        JSONObject vcap = (JSONObject) parser.parse(env.get("VCAP_SERVICES"));
        JSONObject service = null;

        // We don't know exactly what the service is called, but it will contain "postgresql"
        for (Object key : vcap.keySet()) {
            String keyStr = (String) key;
            if (keyStr.toLowerCase().contains("postgresql")) {
                service = (JSONObject) ((JSONArray) vcap.get(keyStr)).get(0);
                break;
            }
        }

        if (service != null) {
            JSONObject creds = (JSONObject) service.get("credentials");
            String name = (String) creds.get("name");
            String host = (String) creds.get("host");
            Long port = (Long) creds.get("port");
            String user = (String) creds.get("user");
            String password = (String) creds.get("password");

            String url = "jdbc:postgresql://" + host + ":" + port + "/" + name;

            return DriverManager.getConnection(url, user, password);
        }
    }
    throw new Exception(
            "No PostgreSQL service URL found. Make sure you have bound the correct services to your app.");
}

From source file:it.polimi.logging.LogMessageUtils.java

public static boolean getValidBitFromMessage(String message) {

    JSONObject jsonMsg;//from   w  w w. j  a  v a 2 s .c om
    JSONParser parser = new JSONParser();
    String type = getEventType(message);

    if (type.equals(MessageType.CHECK_OUT.ordinal())) {
        try {
            jsonMsg = (JSONObject) parser.parse(message);
            return (Boolean) jsonMsg.get(JsonStrings.VALID);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    return false;
}