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.apigee.edge.config.utils.ConfigReader.java

/**
 * Example Hierarchy//ww w. j a  va 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:it.polimi.logging.LogMessageUtils.java

public static String getEventType(String message) {
    JSONParser parser = new JSONParser();
    JSONObject jsonMsg;/*from w  ww . ja v a 2 s  .  com*/
    String type = "";
    try {
        jsonMsg = (JSONObject) parser.parse(message);
        type = (String) jsonMsg.get(JsonStrings.EVENT_TYPE);
        return type;
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

From source file:de.Keyle.MyPet.util.Updater.java

protected Optional<Update> check() {
    try {/*from  www.  ja  v  a 2  s  . c  o  m*/
        String parameter = "";
        parameter += "&package=" + MyPetApi.getCompatUtil().getInternalVersion();
        parameter += "&build=" + MyPetVersion.getBuild();
        parameter += "&dev=" + MyPetVersion.isDevBuild();

        String url = "http://update.mypet-plugin.de/" + plugin + "?" + parameter;

        // no data will be saved on the server
        String content = Util.readUrlContent(url);
        JSONParser parser = new JSONParser();
        JSONObject result = (JSONObject) parser.parse(content);

        if (result.containsKey("latest")) {
            String version = result.get("latest").toString();
            int build = ((Long) result.get("build")).intValue();
            return Optional.of(new Update(version, build));
        }
    } catch (Exception ignored) {
        ignored.printStackTrace();
    }
    return Optional.empty();
}

From source file:com.pearson.eidetic.driver.threads.subthreads.SnapshotVolumeTime.java

@Override
public void run() {
    isFinished_ = false;/* w  ww  .j av a 2  s  .c  o m*/
    AmazonEC2Client ec2Client = connect(region_, awsAccessKeyId_, awsSecretKey_);

    for (Volume vol : VolumeTime_) {
        try {

            Date date = new java.util.Date();
            JSONParser parser = new JSONParser();

            String inttagvalue = getIntTagValue(vol);
            if (inttagvalue == null) {
                continue;
            }

            JSONObject eideticParameters;
            try {
                Object obj = parser.parse(inttagvalue);
                eideticParameters = (JSONObject) obj;
            } catch (Exception e) {
                logger.error("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                        + "\",Event=Error, Error=\"Malformed Eidetic Tag\", Volume_id=\"" + vol.getVolumeId()
                        + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                        + StackTrace.getStringFromStackTrace(e) + "\"");
                continue;
            }

            String period = getPeriod(eideticParameters, vol);
            if (period == null) {
                continue;
            }

            Integer keep = getKeep(eideticParameters, vol);
            if (keep == null) {
                continue;
            }

            Boolean success;
            success = snapshotCreation(ec2Client, vol, period, date);
            if (!success) {
                continue;
            }

            snapshotDeletion(ec2Client, vol, period, keep);

        } catch (Exception e) {
            logger.error("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                    + "\",Event=\"Error\", Error=\"error in SnapshotVolumeTime workflow\", stacktrace=\""
                    + e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e) + "\"");
        }

    }
    ec2Client.shutdown();
    isFinished_ = true;
}

From source file:com.intuit.tweetstest.TweetsController.java

@RequestMapping(value = "/feed", method = RequestMethod.GET)
protected String fetchFeeds(HttpServletRequest request, HttpServletResponse response)
        throws ParseException, ServletException, IOException, Exception {

    JSONObject result = new JSONObject();

    String user = request.getParameter("user");
    if (user != null && !user.isEmpty()) {
        String countStr = request.getParameter("count");
        int count;
        // If count parameter is not sent in request, set it to 100
        if (countStr != null && !countStr.isEmpty()) {
            count = Integer.parseInt(countStr);
        } else {//  w ww .j a  v a 2s .com
            count = 100;
        }

        // The access to the MongoDB should itself be a part of a separate 
        // package with all the DB APIs wrapped around and published to the users.
        // Not doing it here to save some time.
        MongoClient mongo = new MongoClient("localhost", 27017);
        DB db = mongo.getDB("tweetsdb");
        DBCollection usersCollection = db.getCollection("userscollection");

        // Not checking if the user is a valid user or not here.  That's a 
        // separate code flow on itself.
        DBObject query = new BasicDBObject("user", user);

        // Here I am retrieving the list of users the current user is following
        DBObject userDocument = usersCollection.findOne(query);
        if (userDocument == null) {
            result.put(user, "No such user");
            result.put("isSuccess", false);
            sendResponse(response, result);
            return null;
        }
        JSONObject json = (JSONObject) new JSONParser().parse(userDocument.toString());
        JSONArray following = (JSONArray) json.get("following");
        // A sample of the following array looks like ["user4", "user3"]
        List<String> followingList = getFollowingList(following);

        // Once the following list is retrieved, the tweets of those users are
        // read from the db.
        JSONArray tweetsArray = retrieveTweetsFromDB(db, followingList, count);

        result.put("tweets", tweetsArray);
        result.put("isSuccess", true);
    } else {
        System.out.println("Missing user parameter in the request.  Returning error");
        result.put("Missing parameter", "user");
        result.put("isSuccess", false);
    }
    sendResponse(response, result);
    return null;
}

From source file:me.uni.sushilkumar.geodine.util.YoutubeSearch.java

/** 
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request//from w  w  w.jav a 2 s .  com
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ParseException, SQLException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        String type = request.getParameter("type");
        String query = null;
        type += "";

        if (type.equals("random")) {
            DBConnection con = new DBConnection();
            ArrayList<String> cuisineList = con.getCuisineList();
            Random generator = new Random();
            query = cuisineList.get(generator.nextInt(cuisineList.size()));

        } else {
            query = request.getParameter("q");
        }
        query += " recipe";
        URL u = new URL("http://gdata.youtube.com/feeds/api/videos?q=" + URLEncoder.encode(query, "UTF-8")
                + "&max-results=1&v=2&alt=jsonc");
        BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream()));
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(br);
        JSONObject json = (JSONObject) obj;
        JSONObject data = (JSONObject) json.get("data");
        JSONArray items = (JSONArray) data.get("items");
        Iterator<JSONObject> it = items.iterator();
        if (it != null) {
            JSONObject item = it.next();
            String id = (String) item.get("id");
            String title = (String) item.get("title");
            out.println(id);
        } else {
            out.println("Unable to fetch any video");
        }

    } finally {
        out.close();
    }
}

From source file:com.conwet.xjsp.session.SessionState.java

@Override
public void newData(ConnectionContext context) throws ConnectionException {
    String stanza;/*from   w w  w  . j a  v a2s.  c o m*/
    JSONParser parser = new JSONParser();
    try {

        while ((stanza = JSONUtil.extractStanza(context.getBuffer())) != null) {
            if ("]}".equals(stanza)) {
                try {
                    context.getChannel().sendFragment("]}");
                } catch (IOException ex) {
                    throw new ConnectionException(ConnError.ApplicationError, ex.getMessage());
                } finally {
                    closed.set(Boolean.TRUE);
                    context.dispose();
                    removeListeners(context);
                }
            } else {
                try {
                    JSONObject json = (JSONObject) parser.parse(stanza);
                    handleMessage(json, context);

                } catch (ParseException ex) {
                    throw new ConnectionException(ConnError.ProtocolSyntaxError,
                            "Invalid stanza: " + ex.getMessage());
                }
            }
        }

    } catch (ParseException ex) {
        throw new ConnectionException(ConnError.ProtocolSyntaxError, ex.getMessage());
    }
}

From source file:GraphController.java

@RequestMapping("/graphs")
public @ResponseBody Graph graph(
        @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication,
        @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    Properties props = new Properties();
    FileInputStream fis = new FileInputStream("properties.xml");
    //loading properites from properties file
    props.loadFromXML(fis);/*w  w w  .j a va  2 s.  c  om*/

    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();
    JSONArray list = new JSONArray();
    jsonObj.put("jsonrpc", "2.0");
    jsonObj.put("method", "graph.get");
    JSONObject params = new JSONObject();
    params.put("output", "extend");
    params.put("hostids", hostid);
    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 

    String loginResponse = "";

    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");

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

            JSONObject objret = new JSONObject();

            objret.put("graphId", tobj.get("graphid"));
            objret.put("graphName", tobj.get("name"));

            String type = (String) tobj.get("graphtype");

            if (type.equals("0")) {
                objret.put("graphType", "normal");
            } else if (type.equals("1")) {
                objret.put("graphType", "stacked");
            } else if (type.equals("2")) {
                objret.put("graphType", "pie");
            } else if (type.equals("3")) {
                objret.put("graphType", "exploded");
            }

            list.add(objret);

        }

        return new Graph(list);

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException pe) {
        pe.printStackTrace();
    }
    return new Graph(
            "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:");
}

From source file:com.pearson.eidetic.driver.threads.subthreads.SnapshotVolumeNoTime.java

@Override
public void run() {
    isFinished_ = false;// w w w  .j a v a 2  s. c  o m
    //kill thread if wrong creds \/ \/ \/ \/
    AmazonEC2Client ec2Client = connect(region_, awsAccessKeyId_, awsSecretKey_);

    for (Volume vol : VolumeNoTime_) {
        try {
            Date date = new java.util.Date();
            JSONParser parser = new JSONParser();

            String inttagvalue = getIntTagValue(vol);
            if (inttagvalue == null) {
                continue;
            }

            JSONObject eideticParameters;
            try {
                Object obj = parser.parse(inttagvalue);
                eideticParameters = (JSONObject) obj;
            } catch (Exception e) {
                logger.error("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                        + "\",Event=Error, Error=\"Malformed Eidetic Tag\", Volume_id=\"" + vol.getVolumeId()
                        + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                        + StackTrace.getStringFromStackTrace(e) + "\"");
                continue;
            }

            String period = getPeriod(eideticParameters, vol);
            if (period == null) {
                continue;
            }

            Integer keep = getKeep(eideticParameters, vol);
            if (keep == null) {
                continue;
            }

            Boolean success;
            success = snapshotDecision(ec2Client, vol, period);
            if (!success) {
                continue;
            }

            success = snapshotCreation(ec2Client, vol, period, date);
            if (!success) {
                continue;
            }

            snapshotDeletion(ec2Client, vol, period, keep);

        } catch (Exception e) {
            logger.error("awsAccountNickname=\"" + uniqueAwsAccountIdentifier_
                    + "\",Event=\"Error\", Error=\"error in SnapshotVolumeNoTime workflow\", stacktrace=\""
                    + e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e) + "\"");
        }

    }
    ec2Client.shutdown();
    isFinished_ = true;

}

From source file:com.pearson.eidetic.driver.threads.subthreads.SnapshotVolumeSync.java

@Override
public void run() {
    isFinished_ = false;//from w  w w. j a  v  a 2s.co  m
    AmazonEC2Client ec2Client = connect(region_, awsAccessKeyId_, awsSecretKey_);

    for (Volume vol : VolumeSync_) {
        try {

            Date date = new java.util.Date();
            JSONParser parser = new JSONParser();

            String inttagvalue = getIntTagValue(vol);
            if (inttagvalue == null) {
                continue;
            }

            JSONObject eideticParameters;
            try {
                Object obj = parser.parse(inttagvalue);
                eideticParameters = (JSONObject) obj;
            } catch (Exception e) {
                logger.error("awsAccountId=\"" + uniqueAwsAccountIdentifier_
                        + "\",Event=Error, Error=\"Malformed Eidetic Tag\", Volume_id=\"" + vol.getVolumeId()
                        + "\", stacktrace=\"" + e.toString() + System.lineSeparator()
                        + StackTrace.getStringFromStackTrace(e) + "\"");
                continue;
            }

            //Same
            Integer keep = getKeep(eideticParameters, vol);
            if (keep == null) {
                continue;
            }

            Boolean success;
            success = snapshotCreation(ec2Client, vol, date);
            if (!success) {
                continue;
            }

            snapshotDeletion(ec2Client, vol, keep);

        } catch (Exception e) {
            logger.error("awsAccountId=\"" + uniqueAwsAccountIdentifier_
                    + "\",Event=\"Error\", Error=\"error in SnapshotVolumeSync workflow\", stacktrace=\""
                    + e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e) + "\"");
        }

    }
    ec2Client.shutdown();
    isFinished_ = true;
}