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.mstiles92.plugins.stileslib.updates.UpdateChecker.java

/**
 * The task to be run by the Bukkit scheduler that finds the latest published version on BukkitDev.
 *///from   ww w.j  a v a2s  .  c o m
@Override
public void run() {
    try {
        URL url = new URL("https://api.curseforge.com/servermods/files?projectIds=" + curseProjectId);
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(10000);
        connection.addRequestProperty("User-Agent", plugin.getName() + " (by mstiles92)");
        InputStream stream = connection.getInputStream();
        JSONParser parser = new JSONParser();
        Object o = parser.parse(new InputStreamReader(stream));
        stream.close();

        JSONArray array = (JSONArray) o;
        if (array.size() > 0) {
            JSONObject latest = (JSONObject) array.get(array.size() - 1);
            latestVersion = (String) latest.get("name");
            latestVersion = latestVersion.substring(1, latestVersion.length());
            updateAvailable = isNewerVersion(latestVersion);

            if (updateAvailable) {
                plugin.getLogger().info("Update available! New version: " + latestVersion);
                plugin.getLogger()
                        .info("More information available at http://dev.bukkit.org/bukkit-plugins/" + slug);
            }
        }
    } catch (IOException | ParseException | ClassCastException e) {
        plugin.getLogger()
                .info("Unable to check for updates. Will try again later. Error message: " + e.getMessage());
    }
}

From source file:edu.anu.spice.SpiceScorer.java

public void scoreBatch(SpiceArguments args) throws IOException, ScriptException {
    Stopwatch timer = Stopwatch.createStarted();
    SpiceParser parser = new SpiceParser(args.cache, args.numThreads, args.synsets);

    // Build filters for tuple categories
    Map<String, TupleFilter> filters = new HashMap<String, TupleFilter>();
    if (args.tupleSubsets) {
        filters.put("Object", TupleFilter.objectFilter);
        filters.put("Attribute", TupleFilter.attributeFilter);
        filters.put("Relation", TupleFilter.relationFilter);
        filters.put("Cardinality", TupleFilter.cardinalityFilter);
        filters.put("Color", TupleFilter.colorFilter);
        filters.put("Size", TupleFilter.sizeFilter);
    }//ww  w . j  ava2  s  . c o m

    // Parse test and refs from input file
    ArrayList<Object> image_ids = new ArrayList<Object>();
    ArrayList<String> testCaptions = new ArrayList<String>();
    ArrayList<String> refCaptions = new ArrayList<String>();
    ArrayList<Integer> refChunks = new ArrayList<Integer>();
    JSONParser json = new JSONParser();
    JSONArray input;
    try {
        input = (JSONArray) json.parse(new FileReader(args.inputPath));
        for (Object o : input) {
            JSONObject item = (JSONObject) o;
            image_ids.add(item.get("image_id"));
            testCaptions.add((String) item.get("test"));
            JSONArray refs = (JSONArray) item.get("refs");
            refChunks.add(refs.size());
            for (Object ref : refs) {
                refCaptions.add((String) ref);
            }
        }
    } catch (ParseException e) {
        System.err.println("Could not read input: " + args.inputPath);
        System.err.println(e.toString());
        e.printStackTrace();
    }

    System.err.println("Parsing reference captions");
    List<SceneGraph> refSgs = parser.parseCaptions(refCaptions, refChunks);
    System.err.println("Parsing test captions");
    List<SceneGraph> testSgs = parser.parseCaptions(testCaptions);

    this.stats = new SpiceStats(filters, args.detailed);
    for (int i = 0; i < testSgs.size(); ++i) {
        this.stats.score(image_ids.get(i), testSgs.get(i), refSgs.get(i), args.synsets);
    }
    if (!args.silent) {
        System.out.println(this.stats.toString());
    }

    if (args.outputPath != null) {
        BufferedWriter outputWriter = new BufferedWriter(new FileWriter(args.outputPath));

        // Pretty print output using javascript
        String jsonStringNoWhitespace = this.stats.toJSONString();
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine scriptEngine = manager.getEngineByName("JavaScript");
        scriptEngine.put("jsonString", jsonStringNoWhitespace);
        scriptEngine.eval("result = JSON.stringify(JSON.parse(jsonString), null, 2)");
        String prettyPrintedJson = (String) scriptEngine.get("result");

        outputWriter.write(prettyPrintedJson);
        outputWriter.close();
    }
    System.out.println("SPICE evaluation took: " + timer.stop());
}

From source file:at.uni_salzburg.cs.ckgroup.cscpp.mapper.algorithm.VehicleStatusTestCase.java

@Test
public void testCase02() throws ParseException {
    String status = "{\"vehicle.id\":\"732d463b-6836-487c-989d-47c59285c17d\",\"state\":\"corrupt\",\"latitude\":47.8226984,\"longitude\":13.04211393,\"altitude\":25.0,"
            + "\"tolerance\":12.0,\"actions\":\"photo,temperature\"}";
    JSONParser parser = new JSONParser();
    VehicleStatus s = new VehicleStatus((JSONObject) parser.parse(status));
    Assert.assertEquals("732d463b-6836-487c-989d-47c59285c17d", s.getId());
    Assert.assertEquals("corrupt", s.getState().toString().toLowerCase());
    Assert.assertNull(s.getPosition());//  www .  j a  v a  2  s .c  om
    Assert.assertEquals(Double.NaN, s.getTolerance(), 1E-9);
    Assert.assertNull(s.getActions());

    s = new VehicleStatus((JSONObject) parser.parse(s.toJSONString()));
    Assert.assertEquals("732d463b-6836-487c-989d-47c59285c17d", s.getId());
    Assert.assertEquals("corrupt", s.getState().toString().toLowerCase());
    Assert.assertNull(s.getPosition());
    Assert.assertEquals(Double.NaN, s.getTolerance(), 1E-9);
    Assert.assertNull(s.getActions());
}

From source file:com.piusvelte.webcaster.MediaLoader.java

@Override
public List<Medium> loadInBackground() {
    List<Medium> media = new ArrayList<Medium>();
    if (mediaUrl != null) {
        HttpURLConnection httpURLConnection;
        try {/*from   w w  w .j  a v a 2  s.c om*/
            String response;
            httpURLConnection = (HttpURLConnection) mediaUrl.openConnection();
            InputStream in = new BufferedInputStream(httpURLConnection.getInputStream());
            byte[] buffer = new byte[512];
            ByteArrayOutputStream content = new ByteArrayOutputStream();
            int readBytes = 0;
            while ((readBytes = in.read(buffer)) != -1) {
                content.write(buffer, 0, readBytes);
            }
            response = new String(content.toByteArray());
            JSONParser jsonParser = new JSONParser();
            JSONArray mediaJArr = (JSONArray) jsonParser.parse(response);
            Gson gson = new Gson();
            for (int i = 0, s = mediaJArr.size(); i < s; i++) {
                media.add(gson.fromJson(mediaJArr.get(i).toString(), Medium.class));
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return media;
}

From source file:kr.co.bitnine.octopus.testutils.MemoryDatabase.java

public void importJSON(Class<?> clazz, String resourceName) throws Exception {
    Connection conn = getConnection();
    conn.setAutoCommit(false);//w w w.j  av  a2  s .c  o  m
    Statement stmt = conn.createStatement();

    JSONParser jsonParser = new JSONParser();
    JSONArray tables = (JSONArray) jsonParser
            .parse(new InputStreamReader(clazz.getResourceAsStream(resourceName)));
    for (Object tableObj : tables) {
        StringBuilder queryBuilder = new StringBuilder();

        JSONObject table = (JSONObject) tableObj;

        String tableName = jsonValueToSqlIdent(table.get("table-name"));
        queryBuilder.append("CREATE TABLE ").append(tableName).append('(');
        JSONArray schema = (JSONArray) table.get("table-schema");
        for (Object columnNameObj : schema) {
            String columnName = jsonValueToSqlValue(columnNameObj);
            queryBuilder.append(columnName).append(',');
        }
        queryBuilder.setCharAt(queryBuilder.length() - 1, ')');
        stmt.execute(queryBuilder.toString());

        JSONArray rows = (JSONArray) table.get("table-rows");
        for (Object rowObj : rows) {
            JSONArray row = (JSONArray) rowObj;

            queryBuilder.setLength(0);
            queryBuilder.append("INSERT INTO ").append(tableName).append(" VALUES(");
            for (Object columnObj : row)
                queryBuilder.append(jsonValueToSqlValue(columnObj)).append(',');
            queryBuilder.setCharAt(queryBuilder.length() - 1, ')');
            stmt.executeUpdate(queryBuilder.toString());
        }
    }

    stmt.close();
    conn.commit();
    conn.close();
}

From source file:m.dekmak.License.java

public String validate() {
    String msg = "";
    URL location = License.class.getProtectionDomain().getCodeSource().getLocation();
    String url = location.getFile();
    String path = url.substring(0, url.length() - 38);
    String licensePath = path + "license";
    File f = new File(licensePath);
    if (f.exists() && !f.isDirectory()) {
        JSONParser parser = new JSONParser();
        try {/*from www . ja  va2 s. c  om*/
            Object obj = parser.parse(new FileReader(licensePath));
            JSONObject jsonObject = (JSONObject) obj;
            String client = (String) jsonObject.get("client");
            if (client == null || client.equals("")) {
                msg = "Invalid license (client not defined)";
            } else {
                String product = (String) jsonObject.get("product");
                if (product == null || product.equals("")) {
                    msg = "Invalid license (product not defined)";
                } else {
                    String nbOfUsers = (String) jsonObject.get("nbOfUsers");
                    if (nbOfUsers == null || nbOfUsers.equals("")) {
                        msg = "Invalid license (Nb Of Users not defined)";
                    } else {
                        String expiresOn = (String) jsonObject.get("expiresOn");
                        if (expiresOn == null || expiresOn.equals("")) {
                            msg = "Invalid license (Expires on date not defined)";
                        } else {
                            Encryptor encr = new Encryptor(client);
                            String license = (String) jsonObject.get("license");
                            if (license == null || license.equals("")) {
                                msg = "Invalid license (license not defined)";
                            } else {
                                product = encr.decrypt(product);
                                nbOfUsers = encr.decrypt(nbOfUsers);
                                expiresOn = encr.decrypt(expiresOn);
                                license = encr.decrypt(license);
                                if (license.equals(client)) {
                                    setExpiresOn(expiresOn);
                                    setNbOfUsers(nbOfUsers);
                                    setClient(client);
                                    setProduct(product);
                                    msg = "success";
                                } else {
                                    msg = "Invalid license";
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            msg = "Invalid license for given client";
        }
    } else {
        msg = "License file not exists";
    }

    return msg;
}

From source file:com.thesmartweb.swebrank.YahooResults.java

/**
 * Method to get the results number of a specific query from Yahoo! search api
 * @param quer the query to search for//www . jav a  2  s  .c o  m
 * @param config_path the directory to get the api keys
 * @return the amount of results
 */
public Long Get_Results_Number(String quer, String config_path) {
    try {
        long results_number = 0;
        //we connect through 
        String check_quer = quer.substring(quer.length() - 1, quer.length());
        char plus = "+".charAt(0);
        char check_plus = check_quer.charAt(0);
        if (check_plus == plus) {
            quer = quer.substring(0, quer.length() - 1);
        }
        quer = quer.replace("+", "%20");
        //URL link_ur = new URL("http://boss.yahooapis.com/ysearch/web/v1/" + quer + "?appid=zrmigQ3V34FAyR9Nc4_EK91CP3Iw0Qa48QSgKqAvl2jLAo.rx97cmpgqW_ovGHvwjH.KgNQ-&format=json");
        //APIconn apicon = new APIconn();
        YahooConn yc = new YahooConn();
        String line = yc.connect(quer, config_path);
        //String line = apicon.connect(link_ur);
        if (!line.equalsIgnoreCase("fail")) {
            JSONParser parser = new JSONParser();
            //Create the map
            Map json = (Map) parser.parse(line);
            // Get a set of the entries
            Set set = json.entrySet();
            Object[] arr = set.toArray();
            Map.Entry entry = (Map.Entry) arr[0];
            //****get to second level of yahoo json
            String you = entry.getValue().toString();
            json = (Map) parser.parse(you);
            set = json.entrySet();
            arr = set.toArray();
            entry = (Map.Entry) arr[1];
            you = entry.getValue().toString();
            json = (Map) parser.parse(you);
            set = json.entrySet();
            arr = set.toArray();
            entry = (Map.Entry) arr[3];
            you = entry.getValue().toString();
            results_number = Long.parseLong(you);
        }
        return results_number;
    } catch (ParseException | java.lang.ArrayIndexOutOfBoundsException | java.lang.NullPointerException ex) {
        Logger.getLogger(YahooResults.class.getName()).log(Level.SEVERE, null, ex);
        long results_number = 0;
        return results_number;
    }
}

From source file:org.uom.fit.level2.datavis.repository.ChatServicesImpl.java

@Override
public JSONArray getAllChatData(String message) {
    try {/*from  w  w w .j  a va2 s .  c  o  m*/
        Mongo mongo = new Mongo("localhost", 27017);
        DB db = mongo.getDB("chat");
        DBCollection collection = db.getCollection("message");
        BasicDBObject whereQuery = new BasicDBObject();
        BasicDBObject field = new BasicDBObject();
        BasicDBObject sortQuery = new BasicDBObject();

        whereQuery.put("message", message);
        field.put("senderName", 1);
        field.put("message", 1);
        field.put("receiverName", 1);
        field.put("imageData", 1);
        field.put("discription", 1);

        sortQuery.put("DateTime", 1);

        DBCursor cursor = collection.find(whereQuery, field).sort(sortQuery);
        JSON json = new JSON();
        String dataUser = json.serialize(cursor);
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(dataUser);
        JSONArray jsonarray = (JSONArray) obj;
        return jsonarray;
    } catch (Exception e) {
        System.out.println("Exception Error getAll");
        return null;
    }
}

From source file:com.telefonica.iot.cosmos.hive.authprovider.OAuth2AuthenticationProviderImpl.java

@Override
public void Authenticate(String user, String token) throws AuthenticationException {
    // create the Http client
    HttpClient httpClient = httpClientFactory.getHttpClient(true);

    // create the request
    String url = idmEndpoint + "/user?access_token=" + token;
    HttpRequestBase request = new HttpGet(url);

    // do the request
    HttpResponse httpRes = null;//from w w w . j  a v a2 s .c o m

    try {
        httpRes = httpClient.execute(request);
        LOGGER.debug("Doing request: " + request.toString());
    } catch (IOException e) {
        throw new AuthenticationException(e.getMessage());
    } // try catch

    // get the input streamResponse
    String streamResponse = "";

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpRes.getEntity().getContent()));
        streamResponse = reader.readLine();
        LOGGER.debug("Response received: " + streamResponse);
    } catch (IOException e) {
        throw new AuthenticationException(e.getMessage());
    } // try catch

    // parse the input streamResponse as a Json
    JSONObject jsonResponse = null;

    try {
        JSONParser jsonParser = new JSONParser();
        jsonResponse = (JSONObject) jsonParser.parse(streamResponse);
    } catch (ParseException e) {
        throw new AuthenticationException(e.getMessage());
    } // try catch

    // check if the given token does not exist
    if (jsonResponse.containsKey("error")) {
        throw new AuthenticationException("The given token does not exist");
    } // if

    // check if the obtained user id matches the given user
    if (jsonResponse.containsKey("id") && !jsonResponse.get("id").equals(user)) {
        throw new AuthenticationException("The given token does not match the given user");
    } // if

    // release the connection
    request.releaseConnection();

    LOGGER.debug("User " + user + " authenticated");
}

From source file:processingtest.CitySense.java

public ArrayList<CityData> getDayDataByLocation() throws IOException {
    String query = queryBuilder.getDayDataByLocation(2); //Over 2 days
    CloseableHttpResponse response = this.executeRequest(query);
    HttpEntity entity = response.getEntity();
    ArrayList<CityData> dataPoints = null;

    if (entity != null) {
        try ( // A Simple JSON Response Read
                InputStream instream = entity.getContent()) {
            String result = convertStreamToString(instream);
            // now you have the string representation of the HTML request
            //System.out.println("RESPONSE: " + result);

            JSONParser parser = new JSONParser();
            try {
                Object obj = parser.parse(result);
                JSONObject jobj = (JSONObject) obj;
                //System.out.println(jobj.entrySet());
                Object dataObject = jobj.get("data");
                JSONArray array = (JSONArray) dataObject;
                //System.out.println(array.get(0));
                dataPoints = decodeJsonData(array);
                System.out.println((dataPoints.size()));
            } catch (ParseException pe) {
                System.out.println("position: " + pe.getPosition());
                System.out.println(pe);
            }/*  ww w .  ja  v a2  s .c o  m*/
        }
    }
    return dataPoints;
}