Example usage for org.json.simple JSONValue parseWithException

List of usage examples for org.json.simple JSONValue parseWithException

Introduction

In this page you can find the example usage for org.json.simple JSONValue parseWithException.

Prototype

public static Object parseWithException(String s) throws ParseException 

Source Link

Usage

From source file:name.martingeisse.common.javascript.analyze.JsonAnalyzer.java

/**
 * Parses a JSON-encoded string and analyzes the result.
 * @param jsonReader the reader for the JSON-encoded string
 * @return the analyzer//from  w  w w .  j  av a 2 s .c  o m
 */
public static JsonAnalyzer parse(final Reader jsonReader) {
    try {
        return new JsonAnalyzer(JSONValue.parseWithException(jsonReader));
    } catch (ParseException e) {
        throw new JsonAnalysisException("Parse exception in JSON input");
    } catch (IOException e) {
        throw new RuntimeException("IOException while parsing JSON", e);
    }
}

From source file:com.healthcit.analytics.utils.ExcelExportUtils.java

public static JSONArray getAsJsonArray(String jsonString) {
    JSONArray arr = null;//from  w w w .  jav a 2s  . c  o m

    try {
        arr = (JSONArray) JSONValue.parseWithException(jsonString);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return arr;
}

From source file:moderation.Moderate.java

public List getInstapost() throws SQLException {
    List savedpost = getSavedList(album_id);
    List posts = new ArrayList();
    try {/*from   w w w  . ja  v  a  2 s. c om*/
        String access_token = new Api().getInsta_token();
        String tagname = this.hash;
        String url = "https://api.instagram.com/v1/tags/" + tagname + "/media/recent?access_token="
                + access_token + "&count=50";
        System.out.println(url);
        try {
            String genreJson = IOUtils.toString(new URL(url));
            JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
            String data = "";
            JSONArray genreArray = (JSONArray) genreJsonObject.get("data");
            JSONObject pagination = (JSONObject) genreJsonObject.get("pagination");
            this.instanext = (String) pagination.get("next_url");

            if (genreArray.size() > 0) {
                for (int i = 0; i < genreArray.size(); i++) {
                    JSONObject firstGenre = (JSONObject) genreArray.get(i);
                    PostModel post = new PostModel();
                    post.setAlbum_id(this.album_id);
                    //parameter

                    // post_id   
                    if (firstGenre.get("id") != null) {
                        post.setPost_id(firstGenre.get("id").toString());
                        if (savedpost.contains(firstGenre.get("id")))
                            post.setStatus("old");
                        else
                            post.setStatus("new");
                    }
                    //post_creation time    
                    if (firstGenre.get("created_time") != null)
                        post.setPost_time(firstGenre.get("created_time").toString());
                    // post type  
                    if (firstGenre.get("type") != null)
                        post.setType(firstGenre.get("type").toString());

                    // post link

                    if (firstGenre.get("link") != null)
                        post.setLink(firstGenre.get("link").toString());
                    // sender details name, id, pic 

                    if (firstGenre.get("user") != null) {
                        JSONObject user = (JSONObject) firstGenre.get("user");
                        post.setSender_id((String) user.get("id"));
                        post.setSender_name((String) user.get("full_name"));
                        post.setSender_pic((String) user.get("profile_picture"));

                    }

                    //post message

                    JSONObject caption = (JSONObject) firstGenre.get("caption");
                    if (caption != null)
                        post.setCaption_text(URLEncoder.encode((String) caption.get("text"), "UTF-8"));

                    boolean ispic = false;
                    String pic = "";
                    if (firstGenre.get("type").toString().equalsIgnoreCase("image")) {
                        ispic = true;
                        JSONObject images = (JSONObject) firstGenre.get("images");
                        if (images != null) {
                            JSONObject low_resolution = (JSONObject) images.get("low_resolution");
                            JSONObject standard_resolution = (JSONObject) images.get("standard_resolution");
                            post.setImage_low((String) low_resolution.get("url"));
                            post.setImage_standard((String) standard_resolution.get("url"));
                            //  out.println("<br/>original="+post_message+"<br/>encoded="+post_messageencode);
                            post.setParam("post_id=" + post.getPost_id() + "&album_id=" + post.getAlbum_id()
                                    + "&type=" + post.getType() + "&post_time=" + post.getPost_time() + "&link="
                                    + post.getLink() + "&pic_low=" + post.getImage_low() + "&pic_standard="
                                    + post.getImage_standard() + "&post_message=" + post.getCaption_text()
                                    + "&sender_name=" + post.getSender_name() + "&sender_id="
                                    + post.getSender_id() + "&sender_pic=" + post.getSender_pic());

                        }
                    }

                    if (ispic == true)
                        posts.add(post);
                }

            }

        } catch (IOException | ParseException e) {
            System.err.println("Exception occure in getInstapost inner try catch" + e);
        }

    } catch (Exception e) {
        System.err.println("Exception in getinstapost method main try-catch" + e);
    }

    return posts;
}

From source file:com.flaptor.indextank.api.resources.Docs.java

/**
 * @see java.lang.Runnable#run()/*  w w w.  j a va 2  s  . c  o  m*/
 */
public void run() {
    IndexEngineApi api = (IndexEngineApi) ctx().getAttribute("api");
    HttpServletResponse res = res();
    HttpServletRequest req = req();

    String characterEncoding = api.getCharacterEncoding();
    try {
        req.setCharacterEncoding(characterEncoding);
        res.setCharacterEncoding(characterEncoding);
        res.setContentType("application/json");
    } catch (UnsupportedEncodingException ignored) {
    }

    try {
        Object parse = JSONValue.parseWithException(req.getReader());
        if (parse instanceof JSONObject) { // 200, 400, 404, 409, 503
            JSONObject jo = (JSONObject) parse;
            try {
                putDocument(api, jo);
                res.setStatus(200);
                return;

            } catch (Exception e) {
                e.printStackTrace();
                if (LOG_ENABLED)
                    LOG.severe(e.getMessage());
                res.setStatus(400);
                print("Invalid or missing argument"); // TODO: descriptive error msg
                return;
            }
        } else if (parse instanceof JSONArray) {
            JSONArray statuses = new JSONArray();
            JSONArray ja = (JSONArray) parse;
            if (!validateDocuments(ja)) {
                res.setStatus(400);
                print("Invalid or missing argument"); // TODO: descriptive error msg
                return;
            }
            boolean hasError = false;
            for (Object o : ja) {
                JSONObject jo = (JSONObject) o;
                JSONObject status = new JSONObject();
                try {
                    putDocument(api, jo);
                    status.put("added", true);
                } catch (Exception e) {
                    status.put("added", false);
                    status.put("error", "Invalid or missing argument"); // TODO: descriptive error msg
                    hasError = true;
                }
                statuses.add(status);
            }
            print(statuses.toJSONString());
            return;
        }
    } catch (IOException e) {
        if (LOG_ENABLED)
            LOG.severe("PUT doc, parse input " + e.getMessage());
    } catch (ParseException e) {
        if (LOG_ENABLED)
            LOG.severe("PUT doc, parse input " + e.getMessage());
    } catch (Exception e) {
        if (LOG_ENABLED)
            LOG.severe("PUT doc " + e.getMessage());
    }
    res.setStatus(503);
    print("Service unavailable"); // TODO: descriptive error msg
}

From source file:com.conwet.silbops.connectors.comet.handlers.AdvertiseResponse.java

private Advertise extract(HttpServletRequest request, String param) throws ParseException {

    String advertise = retriveParameter(request, param);
    JSONArray jsonAdvertise = (JSONArray) JSONValue.parseWithException(advertise);

    return Advertise.fromJSON(jsonAdvertise);
}

From source file:com.conwet.silbops.connectors.comet.handlers.ContextResponse.java

@Override
protected void reply(HttpServletRequest req, HttpServletResponse res, PrintWriter writer,
        HttpEndPoint httpEndPoint, EndPoint connection) {
    try {//from  ww  w. j a v  a  2 s  .  c  om
        String context = retriveParameter(req, "context");
        JSONObject jsonContext = (JSONObject) JSONValue.parseWithException(context);
        ContextMsg msg = new ContextMsg(null, Context.fromJSON(jsonContext));

        logger.debug("Endpoint {}, Context: {}", httpEndPoint, msg);
        broker.receiveMessage(msg, connection);
        writeOut(writer, httpEndPoint.getEndPoint(), "context success");
    } catch (ParseException ex) {

        logger.warn("Context exception: {}", ex.getMessage());

        try {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException ex1) {
            logger.warn("Context reply exception: {}", ex1.getMessage());
        }
    }
}

From source file:com.conwet.silbops.connectors.comet.handlers.SubscribeResponse.java

@Override
protected void reply(HttpServletRequest req, HttpServletResponse res, PrintWriter writer,
        HttpEndPoint httpEndPoint, EndPoint connection) {
    try {/* w  w w.j  a v a2s  .com*/
        String subscription = retriveParameter(req, "subscription");
        JSONObject jsonSubscription = (JSONObject) JSONValue.parseWithException(subscription);

        if (jsonSubscription.isEmpty()) {

            writeOut(writer, httpEndPoint.getEndPoint(), "subscription is empty");

        } else {

            SubscribeMsg msg = new SubscribeMsg();
            msg.setSubscription(Subscription.fromJSON(jsonSubscription));

            logger.debug("Endpoint {}, Subscribe: {}", httpEndPoint, msg);
            broker.receiveMessage(msg, connection);
            writeOut(writer, httpEndPoint.getEndPoint(), "subscribe success");
        }
    } catch (Exception ex) {
        logger.warn("subscribe exception: {}", ex.getMessage());

        try {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException ex1) {
            logger.warn("subscribe reply exception: {}", ex1.getMessage());
        }
    }
}

From source file:com.conwet.silbops.connectors.comet.handlers.UnsubscribeResponse.java

@Override
protected void reply(HttpServletRequest req, HttpServletResponse res, PrintWriter writer,
        HttpEndPoint httpEndPoint, EndPoint connection) {

    try {//from  w  w w  . ja v  a 2 s .  c  o m
        String subscription = retriveParameter(req, "subscription");
        JSONObject jsonSubscription = (JSONObject) JSONValue.parseWithException(subscription);

        UnsubscribeMsg msg = new UnsubscribeMsg();
        msg.setSubscription(Subscription.fromJSON(jsonSubscription));
        broker.receiveMessage(msg, connection);
        writeOut(writer, httpEndPoint.getEndPoint(), "unsubscribe success");
    } catch (ParseException ex) {
        logger.warn("unsubscribe exception: " + ex.getMessage());
        try {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException ex1) {
            logger.warn(ex1.getMessage());
        }
    }
}

From source file:com.conwet.silbops.connectors.comet.handlers.PublishResponse.java

@Override
protected void reply(HttpServletRequest req, HttpServletResponse res, PrintWriter writer,
        HttpEndPoint httpEndPoint, EndPoint connection) {
    try {/*from  w  ww .  j a  v a 2  s.c o  m*/
        String notification = retriveParameter(req, "notification");
        String context = retriveParameter(req, "context");

        JSONObject jsonNotification = (JSONObject) JSONValue.parseWithException(notification);
        JSONObject jsonContext = (JSONObject) JSONValue.parseWithException(context);

        PublishMsg msg = new PublishMsg();
        msg.setNotification(Notification.fromJSON(jsonNotification));
        msg.setContext(Context.fromJSON(jsonContext));

        broker.receiveMessage(msg, connection);
        writeOut(writer, httpEndPoint.getEndPoint(), "publish success");

    } catch (ParseException ex) {
        logger.warn("publish exception: " + ex.getMessage());
        try {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } catch (IOException ex1) {
            logger.warn(ex1.getMessage());
        }
    }
}

From source file:eu.edisonproject.training.wsd.WikiRequestor.java

private Map<String, List<String>> getWikiCategory() throws IOException, ParseException {
    List<String> categoriesList = new ArrayList<>();
    String jsonString = IOUtils.toString(url);
    JSONObject jsonObj = (JSONObject) JSONValue.parseWithException(jsonString);
    JSONObject query = (JSONObject) jsonObj.get("query");
    JSONObject pages = (JSONObject) query.get("pages");
    Set<String> keys = pages.keySet();
    Map<String, List<String>> map = new HashMap<>();
    for (String key : keys) {
        JSONObject p = (JSONObject) pages.get(key);
        JSONArray categories = (JSONArray) p.get("categories");
        if (categories != null) {
            for (Object obj : categories) {
                JSONObject jObj = (JSONObject) obj;
                String cat = (String) jObj.get("title");
                if (shouldAddCategory(cat)) {
                    //                    System.err.println(cat.substring("Category:".length()).toLowerCase());
                    categoriesList.add(cat.substring("Category:".length()).toLowerCase().replaceAll(" ", "_"));
                }//w  w w.  ja v  a 2  s .co m
            }
            map.put(termUID, categoriesList);
        }

    }
    return map;

}