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

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

Introduction

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

Prototype

JSONParser

Source Link

Usage

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

public void index(String indexFilePath) throws SLIB_Ex_Critic {

    items = new ArrayList();
    metadata = new HashMap();

    logger.info("Loading items");

    JSONParser parser = new JSONParser();
    BufferedReader br = null;//from w w  w. ja  va 2s.  com
    String line = null;
    try {
        br = new BufferedReader(new FileReader(indexFilePath));

        while ((line = br.readLine()) != null) {
            JSONObject jsonObject = (JSONObject) parser.parse(line);
            indexItem(jsonObject.toJSONString());
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new SLIB_Ex_Critic("error processing line: " + line + "\n" + e.getMessage());
    }
    logger.info("indexation done (" + items.size() + " items)");
}

From source file:at.ac.tuwien.dsg.rSybl.cloudInteractionUnit.enforcementPlugins.dryRun.DryRunEnforcementAPI.java

public void readParameters() {
    JSONParser parser = new JSONParser();

    try {//from w  ww .  j a v a  2s  .c om
        InputStream inputStream = Configuration.class.getClassLoader()
                .getResourceAsStream("config/resources.json");
        Object obj = parser.parse(new InputStreamReader(inputStream));

        JSONObject jsonObject = (JSONObject) obj;

        for (Object p : jsonObject.keySet()) {
            String pluginName = (String) p;
            JSONObject plugin = (JSONObject) jsonObject.get(pluginName);
            if (pluginName.toLowerCase().contains("dry")) {
                for (Object a : plugin.keySet()) {
                    String actionName = (String) a;
                    JSONObject action = (JSONObject) plugin.get(actionName);
                    JSONArray jSONArray = (JSONArray) action.get("parameters");
                    for (int i = 0; i < jSONArray.size(); i++) {
                        parameters.add((String) jSONArray.get(i));
                    }

                }
            }
        }
    } catch (Exception e) {
        RuntimeLogger.logger.info(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);
    }/*  w w  w .  j  av a 2  s  .c om*/

    // 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:com.serena.rlc.provider.jira.domain.Issue.java

public static List<Issue> parse(String options) {
    List<Issue> list = new ArrayList<Issue>();
    JSONParser parser = new JSONParser();
    try {//from   w ww  .  j a va 2 s .  co m
        Object parsedObject = parser.parse(options);
        JSONArray array = (JSONArray) ((JSONObject) parsedObject).get("issues");
        for (Object object : array) {
            Issue obj = new Issue();
            JSONObject jsonObject = (JSONObject) object;
            JSONObject fieldsObject = (JSONObject) jsonObject.get("fields");
            JSONObject typeObject = (JSONObject) fieldsObject.get("issuetype");
            JSONObject statusObject = (JSONObject) fieldsObject.get("status");
            JSONObject projectObject = (JSONObject) fieldsObject.get("project");
            JSONObject creatorObject = (JSONObject) fieldsObject.get("creator");
            JSONObject priorityObject = (JSONObject) fieldsObject.get("priority");
            obj.setId((String) jsonObject.get("key"));
            obj.setUrl((String) jsonObject.get("key"));
            obj.setName((String) fieldsObject.get("summary"));
            obj.setDescription((String) fieldsObject.get("description"));
            obj.setDateCreated((String) fieldsObject.get("created"));
            obj.setLastUpdated((String) fieldsObject.get("updated"));
            obj.setType((String) typeObject.get("name"));
            obj.setStatus((String) statusObject.get("name"));
            obj.setProject((String) projectObject.get("name"));
            obj.setCreator((String) creatorObject.get("name"));
            obj.setPriority((String) priorityObject.get("name"));
            list.add(obj);
        }
    } catch (ParseException e) {
        logger.error("Error while parsing input JSON - " + options, e);
    }

    return list;
}

From source file:files.populate.java

private void populate_checkin(Connection connection, String string) {
    String fileName = "/Users/yash/Documents/workspace/HW 3/data/yelp_checkin.json";
    Path path = Paths.get(fileName);
    Scanner scanner = null;//from  www  .j  a va  2  s. c  om
    try {
        scanner = new Scanner(path);

    } catch (IOException e) {
        e.printStackTrace();
    }

    //read file line by line
    scanner.useDelimiter("\n");
    int i = 0;
    while (scanner.hasNext()) {

        if (i < 20) {
            JSONParser parser = new JSONParser();
            String s = (String) scanner.next();
            s = s.replace("'", "''");

            JSONObject obj;

            try {
                obj = (JSONObject) parser.parse(s);
                Map checkin_info = (Map) obj.get("checkin_info");
                Set keys = checkin_info.keySet();
                Object[] days = keys.toArray();
                Statement statement = connection.createStatement();
                for (int j = 0; j < days.length; ++j) {
                    //                           
                    String thiskey = days[j].toString();
                    String q3 = "insert into yelp_checkin values ('" + obj.get("business_id") + "','"
                            + obj.get("type") + "','" + thiskey + "','" + checkin_info.get(thiskey) + "')";
                    //
                    statement.executeUpdate(q3);

                }
                statement.close();

            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            ++i;
        } else {
            break;
        }
    }
}

From source file:agileinterop.AgileInterop.java

/**
 * Example://from ww  w.ja v a2  s  .  c  o  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:MemoryController.java

@RequestMapping("/memory")
public @ResponseBody Memory memory(
        @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication,
        @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid,
        @RequestParam(value = "metricType", required = false, defaultValue = "") String name)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {

    Properties props = new Properties();
    FileInputStream fis = new FileInputStream("properties.xml");
    //loading properites from properties file
    props.loadFromXML(fis);//from w  w  w  .  j  a  v a  2s.c  o m

    String server_ip = props.getProperty("server_ip");
    String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip

    JSONParser parser = new JSONParser();
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(ZABBIX_API_URL);
    putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this

    // create json object for apiinfo.version 
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("jsonrpc", "2.0");
    jsonObj.put("method", "item.get");
    JSONObject params = new JSONObject();
    params.put("output", "extend");
    params.put("hostid", hostid);
    JSONObject search = new JSONObject();
    search.put("key_", "memory");
    params.put("search", search);
    params.put("sortfield", "name");
    jsonObj.put("params", params);
    jsonObj.put("auth", authentication);// todo
    jsonObj.put("id", new Integer(1));

    putMethod.setRequestBody(jsonObj.toString()); // put the json object as input stream into request body 

    PutMethod putMethod2 = new PutMethod(ZABBIX_API_URL);
    putMethod2.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this

    // create json object for apiinfo.version 
    JSONObject jsonObj2 = new JSONObject();
    jsonObj2.put("jsonrpc", "2.0");
    jsonObj2.put("method", "item.get");
    JSONObject params2 = new JSONObject();
    params2.put("output", "extend");
    params2.put("hostid", hostid);
    JSONObject search2 = new JSONObject();
    search2.put("key_", "swap");
    params2.put("search", search2);
    params2.put("sortfield", "name");
    jsonObj2.put("params", params2);
    jsonObj2.put("auth", authentication);// todo
    jsonObj2.put("id", new Integer(1));

    putMethod2.setRequestBody(jsonObj2.toString());

    String loginResponse = "";
    String loginResponse2 = "";
    String memory = "";
    String clock = "";
    String metricType = "";

    try {
        client.executeMethod(putMethod); // send to request to the zabbix api

        loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response

        Object obj = parser.parse(loginResponse);
        JSONObject obj2 = (JSONObject) obj;
        String jsonrpc = (String) obj2.get("jsonrpc");
        JSONArray array = (JSONArray) obj2.get("result");

        client.executeMethod(putMethod2); // send to request to the zabbix api

        loginResponse2 = putMethod2.getResponseBodyAsString(); // read the result of the response

        Object obj3 = parser.parse(loginResponse2);
        JSONObject obj4 = (JSONObject) obj3;
        String jsonrpc2 = (String) obj4.get("jsonrpc");
        JSONArray array2 = (JSONArray) obj4.get("result");

        for (int i = 0; i < array.size(); i++) {
            JSONObject tobj = (JSONObject) array.get(i);

            //         lastValue = getLastValue(tobj);
            //         lastClock = getLastClock(tobj);
            if (!tobj.get("hostid").equals(hostid))
                continue;
            if (name.equals("totalMemory") && tobj.get("name").equals("Total memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Total Memeory";
                return new Memory(hostid, metricType, memory, clock);
            } else if (name.equals("cachedMemory") && tobj.get("name").equals("Cached memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Cached Memory";
                return new Memory(hostid, metricType, memory, clock);
            } else if (name.equals("freeMemory") && tobj.get("name").equals("Free memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Free Memory";
                return new Memory(hostid, metricType, memory, clock);
            } else if (name.equals("bufferedMemory") && tobj.get("name").equals("Buffers memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Buffered Memory";
                return new Memory(hostid, metricType, memory, clock);
            } else if (name.equals("sharedMemory") && tobj.get("name").equals("Shared memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Shared Memory";
                return new Memory(hostid, metricType, memory, clock);
            } else {
                continue;
            }
        }

        for (int i = 0; i < array2.size(); i++) {
            JSONObject tobj2 = (JSONObject) array2.get(i);

            if (!tobj2.get("hostid").equals(hostid))
                continue;
            if (name.equals("freeSwap") && tobj2.get("name").equals("Free swap space")) {
                memory = (String) tobj2.get("lastvalue");
                clock = (String) tobj2.get("lastclock");
                metricType = "Free Swap Space";
                return new Memory(hostid, metricType, memory, clock);
            } else {
                continue;
            }

        }

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException pe) {
        System.out.println("Error");
    }

    return new Memory(
            "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:");
}

From source file:blog.cobablog.java

/**
 * Web service operation//from w  ww . j  a  va 2  s  . c  o  m
 * @return 
 */
@WebMethod(operationName = "listPost")
public List<Post> listPost() {
    List<Post> out = new ArrayList<Post>();
    try {
        //TODO write your implementation code here:
        String linkString = LINK_FIREBASE + "posts.json";
        URL link = new URL(linkString);
        BufferedReader reader = new BufferedReader(new InputStreamReader(link.openStream()));

        String s = "";
        String tmp;
        while ((tmp = reader.readLine()) != null) {
            s += tmp;
        }

        JSONParser parser = new JSONParser();
        JSONObject o = (JSONObject) parser.parse(s);

        int i;
        for (i = 0; i < o.size(); i++) {
            Post p = new Post();
            p.setId(o.keySet().toArray()[i].toString());
            JSONObject postEntry = (JSONObject) parser.parse(o.get(p.getId()).toString());
            p.setAuthor((String) postEntry.get("author"));
            p.setJudul((String) postEntry.get("judul"));
            p.setKonten((String) postEntry.get("konten"));
            p.setTanggal((String) postEntry.get("tanggal"));
            p.setDeleted((String) postEntry.get("deleted"));
            p.setPublished((String) postEntry.get("published"));

            if ((!p.isDeleted()) && p.isPublished()) {
                out.add(p);
            }
        }

        return out;
        //System.out.println(array.get(0));
    } catch (MalformedURLException ex) {
        Logger.getLogger(cobablog.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(cobablog.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(cobablog.class.getName()).log(Level.SEVERE, null, ex);
    }
    return out;
}

From source file:net.amigocraft.mpt.util.MiscUtil.java

public static JSONObject getRemoteIndex(String path) throws MPTException {
    try {//from  w  w  w . j  a  v  a  2  s. co  m
        URL url = new URL(path + (!path.endsWith("/") ? "/" : "") + "mpt.json"); // get URL object for data file
        URLConnection conn = url.openConnection();
        if (conn instanceof HttpURLConnection) {
            HttpURLConnection http = (HttpURLConnection) conn; // cast the connection
            int response = http.getResponseCode(); // get the response
            if (response >= 200 && response <= 299) { // verify the remote isn't upset at us
                InputStream is = http.getInputStream(); // open a stream to the URL
                BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // get a reader
                JSONParser parser = new JSONParser(); // get a new parser
                String line;
                StringBuilder content = new StringBuilder();
                while ((line = reader.readLine()) != null)
                    content.append(line);
                JSONObject json = (JSONObject) parser.parse(content.toString()); // parse JSON object
                // vefify remote config is valid
                if (json.containsKey("packages") && json.get("packages") instanceof JSONObject) {
                    return json;
                } else
                    throw new MPTException(
                            ERROR_COLOR + "Index for repository at " + path + "is missing required elements!");
            } else {
                String error = ERROR_COLOR + "Remote returned bad response code! (" + response + ")";
                if (!http.getResponseMessage().isEmpty())
                    error += " The remote says: " + ChatColor.GRAY + ChatColor.ITALIC
                            + http.getResponseMessage();
                throw new MPTException(error);
            }
        } else
            throw new MPTException(ERROR_COLOR + "Bad protocol for URL!");
    } catch (MalformedURLException ex) {
        throw new MPTException(ERROR_COLOR + "Cannot parse URL!");
    } catch (IOException ex) {
        throw new MPTException(ERROR_COLOR + "Cannot open connection to URL!");
    } catch (ParseException ex) {
        throw new MPTException(ERROR_COLOR + "Repository index is not valid JSON!");
    }
}

From source file:com.treasure_data.td_import.reader.JSONRecordReader.java

@Override
public void sample(Task task) throws PreparePartsException {
    BufferedReader sampleReader = null;
    try {/*  w ww  .j  av  a2  s  . c  o  m*/
        sampleReader = new BufferedReader(new InputStreamReader(
                task.createInputStream(conf.getCompressionType()), conf.getCharsetDecoder()));

        // read first line only
        line = sampleReader.readLine();
        if (line == null) {
            String msg = String.format("Anything is not read or EOF [line: 1] %s", task.getSource());
            LOG.severe(msg);
            throw new PreparePartsException(msg);
        }

        try {
            JSONParser sampleParser = new JSONParser();
            row = (Map<String, Object>) sampleParser.parse(line);
            if (row == null) {
                String msg = String.format("Anything is not parsed [line: 1] %s", task.getSource());
                LOG.severe(msg);
                throw new PreparePartsException(msg);
            }
        } catch (ParseException e) {
            LOG.log(Level.SEVERE, String.format("Anything is not parsed [line: 1] %s", task.getSource()), e);
            throw new PreparePartsException(e);
        }

        // print first sample record
        printSample();
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "during sample method execution", e);
        throw new PreparePartsException(e);
    } finally {
        if (sampleReader != null) {
            try {
                sampleReader.close();
            } catch (IOException e) {
                LOG.log(Level.SEVERE, "sampling reader cannot be closed", e);
                throw new PreparePartsException(e);
            }
        }
    }
}