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:net.modsec.ms.connector.ConnRequestHandler.java

/**
 * Parses the incomming requests and process it accordingly.
 * @param msg//from   w  ww .  j a  va  2  s  .  c om
 */
public static void onConRequest(String msg) {

    log.info("onConRequest called :" + msg);
    JSONParser parser = new JSONParser();
    try {

        Object obj = parser.parse(msg);
        JSONObject json = (JSONObject) obj;

        String action = (String) json.get("action");

        if (action.equals("start")) {

            onStartRequest(json);

        } else if (action.equals("stop")) {

            onStopRequest(json);

        } else if (action.equals("restart")) {

            onRestartRequest(json);

        } else if (action.equals("status")) {

            onStatusRequest(json);

        } else if (action.equals("readMSConfig")) {

            onReadMSConfig(json);

        } else if (action.equals("writeMSConfig")) {

            onWriteMSConfig(json);

        } else if (action.equals("deployRules")) {

            onDeployMSRules(json);

        }

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

}

From source file:com.apigee.edge.config.mavenplugin.KVMMojo.java

public static List getOrgKVM(ServerProfile profile) throws IOException {

    HttpResponse response = RestUtil.getOrgConfig(profile, "keyvaluemaps");
    if (response == null)
        return new ArrayList();
    JSONArray kvms = null;//from  ww w  .  java  2  s  .c  om
    try {
        logger.debug("output " + response.getContentType());
        // response can be read only once
        String payload = response.parseAsString();
        logger.debug(payload);

        /* Parsers fail to parse a string array.
         * converting it to an JSON object as a workaround */
        String obj = "{ \"kvms\": " + payload + "}";

        JSONParser parser = new JSONParser();
        JSONObject obj1 = (JSONObject) parser.parse(obj);
        kvms = (JSONArray) obj1.get("kvms");

    } catch (ParseException pe) {
        logger.error("Get KVM parse error " + pe.getMessage());
        throw new IOException(pe.getMessage());
    } catch (HttpResponseException e) {
        logger.error("Get KVM error " + e.getMessage());
        throw new IOException(e.getMessage());
    }

    return kvms;
}

From source file:com.apigee.edge.config.mavenplugin.KVMMojo.java

public static List getEnvKVM(ServerProfile profile) throws IOException {

    HttpResponse response = RestUtil.getEnvConfig(profile, "keyvaluemaps");
    if (response == null)
        return new ArrayList();
    JSONArray kvms = null;//w w w .  j  a v  a 2s  .c o m
    try {
        logger.debug("output " + response.getContentType());
        // response can be read only once
        String payload = response.parseAsString();
        logger.debug(payload);

        /* Parsers fail to parse a string array.
         * converting it to an JSON object as a workaround */
        String obj = "{ \"kvms\": " + payload + "}";

        JSONParser parser = new JSONParser();
        JSONObject obj1 = (JSONObject) parser.parse(obj);
        kvms = (JSONArray) obj1.get("kvms");

    } catch (ParseException pe) {
        logger.error("Get KVM parse error " + pe.getMessage());
        throw new IOException(pe.getMessage());
    } catch (HttpResponseException e) {
        logger.error("Get KVM error " + e.getMessage());
        throw new IOException(e.getMessage());
    }

    return kvms;
}

From source file:com.apigee.edge.config.mavenplugin.KVMMojo.java

public static List getAPIKVM(ServerProfile profile, String api) throws IOException {

    HttpResponse response = RestUtil.getAPIConfig(profile, api, "keyvaluemaps");
    if (response == null)
        return new ArrayList();
    JSONArray kvms = null;//  w w w  . j  a v  a  2 s .c  o m
    try {
        logger.debug("output " + response.getContentType());
        // response can be read only once
        String payload = response.parseAsString();
        logger.debug(payload);

        /* Parsers fail to parse a string array.
         * converting it to an JSON object as a workaround */
        String obj = "{ \"kvms\": " + payload + "}";

        JSONParser parser = new JSONParser();
        JSONObject obj1 = (JSONObject) parser.parse(obj);
        kvms = (JSONArray) obj1.get("kvms");

    } catch (ParseException pe) {
        logger.error("Get KVM parse error " + pe.getMessage());
        throw new IOException(pe.getMessage());
    } catch (HttpResponseException e) {
        logger.error("Get KVM error " + e.getMessage());
        throw new IOException(e.getMessage());
    }

    return kvms;
}

From source file:it.polimi.geinterface.network.MessageUtils.java

/**
 * Method that return the sender {@link Entity} identifier from a message 
 *//*from   ww  w . j a va 2s. c om*/
public static String getSenderID(String msgJson) {
    JSONParser parser = new JSONParser();
    JSONObject jsonMsg;
    String senderID = "";
    try {
        jsonMsg = (JSONObject) parser.parse(msgJson);
        JSONObject message = (JSONObject) jsonMsg.get(JsonStrings.MESSAGE);
        senderID = (String) message.get(JsonStrings.SENDER);
        return senderID;
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:it.polimi.geinterface.network.MessageUtils.java

/**
 * Method retrieving message type form a {@link String} representing the message received.
 *//* w w w . j  a  v a2s  . c  o m*/
public static MessageType getMsgType(String msgJson) {

    JSONParser parser = new JSONParser();
    JSONObject jsonMsg;
    String msgType = "";
    try {
        jsonMsg = (JSONObject) parser.parse(msgJson);
        JSONObject message = (JSONObject) jsonMsg.get(JsonStrings.MESSAGE);
        msgType = ((String) message.get(JsonStrings.MSG_TYPE)).toUpperCase().trim();
    } catch (ParseException e) {
        e.printStackTrace();
    }

    for (MessageType type : MessageType.values())
        if (type.name().equals(msgType))
            return type;

    return null;
}

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

public static JSONObject getRemoteIndex(String path) throws MPTException {
    try {/*from   w  w  w.  java  2  s  .c  o 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.conwet.silbops.model.JSONvsRMIPerfT.java

public static JSONObject desJSONizeObject(ByteArrayInputStream bais) throws Exception {

    ObjectInputStream inputStream = new ObjectInputStream(bais);
    JSONParser parser = new JSONParser();

    String jsonReceived = (String) inputStream.readObject();

    return (JSONObject) parser.parse(jsonReceived);
}

From source file:mas.MAS_TOP_PAPERS.java

public static String getConferenceName(int id) {

    String url = "https://api.datamarket.azure.com/MRC/MicrosoftAcademic/v2/Conference?$filter=ID%20eq%20" + id
            + "&$format=json";
    while (true) {
        try {/*from  w w  w .ja  v a2 s . com*/
            StringBuilder csv_str = new StringBuilder();
            final String json = getData2(url, 0);
            JSONParser parser = new JSONParser();
            JSONObject jsonObj = (JSONObject) parser.parse(json);
            final JSONObject dObj = (JSONObject) jsonObj.get("d");
            final JSONArray results = (JSONArray) dObj.get("results");
            if (results.size() == 0) {
                System.out.println("results is Empty, break.");
                break;
            } else {
                //                    System.out.println("Conf: results# = " + results.size());
                for (Object conf : results) {
                    JSONObject confObj = (JSONObject) conf;
                    String shortName = normalized((String) confObj.get("ShortName"));
                    if (!shortName.equals("")) {
                        return shortName;
                    } else {
                        String fullName = normalized((String) confObj.get("FullName"));
                        return fullName;
                    }
                }
            }
            //                System.out.println("json= " + jsonObj);
        } catch (ParseException ex) {
            System.out.println(ex.getMessage() + " Cause: " + ex.getCause());
            Logger.getLogger(MAS_TOP_PAPERS.class.getName()).log(Level.SEVERE, null, ex);
            try {
                Thread.sleep(5000L);
            } catch (InterruptedException ex1) {
                Logger.getLogger(MAS_TOP_PAPERS.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }
    }
    return null;
}

From source file:mas.MAS_TOP_PAPERS.java

public static void extractConference(int start) {
    String file_prefix = "conferences";
    String csv_file_path = "data/" + file_prefix + ".csv";
    String json_dump_file_path = "data/" + file_prefix + "_dump.json";
    String url = "https://api.datamarket.azure.com/MRC/MicrosoftAcademic/v2/Conference?";
    url += "$format=json";
    while (true) {
        try {/*  ww w. j a va2 s  . c  om*/
            StringBuilder csv_str = new StringBuilder();
            final String json = getData2(url, start);
            JSONParser parser = new JSONParser();
            JSONObject jsonObj = (JSONObject) parser.parse(json);
            final JSONObject dObj = (JSONObject) jsonObj.get("d");
            final JSONArray results = (JSONArray) dObj.get("results");
            if (results.size() == 0) {
                System.out.println("results is Empty, break.");
                break;
            } else {
                System.out.println("Conference: start = " + start + " results# = " + results.size());
                for (Object paper : results) {
                    JSONObject paperObj = (JSONObject) paper;
                    Long id = (Long) paperObj.get("ID");
                    String shortName = normalized((String) paperObj.get("ShortName"));
                    String fullName = normalized((String) paperObj.get("FullName"));
                    String homepage = normalized((String) paperObj.get("Homepage"));
                    csv_str.append(id).append(SEPERATOR).append(shortName).append(SEPERATOR).append(fullName)
                            .append(SEPERATOR).append(homepage).append(NEWLINE);
                }
                IOUtils.writeDataIntoFile(json + "\n", json_dump_file_path);
                IOUtils.writeDataIntoFile(csv_str.toString(), csv_file_path);
                start += 100;
                Thread.sleep(300L);
            }
            //                System.out.println("json= " + jsonObj);
        } catch (ParseException ex) {
            Logger.getLogger(MAS_TOP_PAPERS.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(MAS_TOP_PAPERS.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}