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:forumbox.ViewPost.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from ww w .  j a va 2  s. c om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String url = request.getRequestURI();
    String[] urlpost = url.split("/");
    String idPost = urlpost[3];

    JSONParser passPost = new JSONParser();
    JSONObject post;

    try {

        if (idPost != null) {
            Object objPost = passPost.parse(new FileReader(
                    "/home/dinalidabarera/NetBeansProjects/NewFolder/forum4/admin01/post/" + idPost + ".json"));

            post = (JSONObject) objPost;
            String postuser = post.get("username").toString();
            String posttitle = post.get("title").toString();
            String postdescription = post.get("description").toString();

            /*   JSONArray array = (JSONArray) post.get("comments");
               ArrayList<String> list;
               list = new ArrayList<>();
               Iterator<String> iterator = array.iterator();
                    
               while (iterator.hasNext()) {
            list.add(iterator.next());
               }
                    
               int listsz = list.size(); */
            /*  String[] comments = new String[listsz];
              for(int i=0;i<listsz;i++){
            comments[i]=list.get(i);
              }*/

            request.setAttribute("title", posttitle);
            request.setAttribute("description", postdescription);
            request.setAttribute("username", postuser);
            // request.setAttribute("comments",comments);
            request.setAttribute("id", idPost);

            request.getRequestDispatcher("/post.jsp").forward(request, response);

        }

    } catch (Exception e) {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println(e);

    }

}

From source file:net.phyloviz.goeburst.tree.GOeBurstMSTItemFactory.java

@Override
public ProjectItem loadData(DataSet dataset, TypingData<? extends AbstractProfile> td, String directory,
        String filename, AbstractDistance ad, int level) {
    GOeBurstMSTSchemaValidator validator = new GOeBurstMSTSchemaValidator();
    try {//w ww . j av a  2s. com
        if (!validator.validate(directory, filename)) {
            return null;
        }
    } catch (IOException e) {
        Exceptions.printStackTrace(e);
    }

    GOeBurstMSTResult goeburstItem = null;

    try {
        FileReader reader = new FileReader(new File(directory, filename));

        JSONParser parser = new JSONParser();
        JSONObject json;
        json = (JSONObject) parser.parse(reader);

        JSONArray nodesArray = (JSONArray) json.get("nodes");
        JSONArray edgesArray = (JSONArray) json.get("edges");

        Map<String, GOeBurstNode> profiles = new HashMap<>();
        for (Iterator<? extends AbstractProfile> tdIt = td.iterator(); tdIt.hasNext();) {
            GOeBurstNode node = new GOeBurstNode(tdIt.next());
            profiles.put(node.getID(), node);
        }

        Map<Integer, GOeBurstNode> nodes = getNodes(profiles, nodesArray);

        Collection<Edge<GOeBurstNode>> tree = createEdges(edgesArray, nodes);

        OutputPanel op = new OutputPanel(dataset.toString() + ": goeBURST Full MST");
        goeburstItem = new GOeBurstMSTResult(dataset, tree, ad, op);

    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
    return goeburstItem;
}

From source file:com.cabserver.handler.Driver.java

@POST
@Path("login")
@Produces(MediaType.TEXT_HTML)//from   w  w w  .  ja  v  a 2s .  c  o m
public Response login(String jsonData) {
    // String data = "";
    HashMap<String, String> responseMap = new HashMap<String, String>();
    try {

        // log.info("Inside Driver >> login before decoding = " + jsonData);

        jsonData = (URLDecoder.decode(jsonData, "UTF-8"));

        // log.info("Inside Driver >> login >>" + jsonData);

        // jsonData = jsonData.split("=")[1];
        if (jsonData.contains("=")) {
            jsonData = jsonData.split("=")[1];
            // log.info("Inside Driver >> signup >> data=" + jsonData);
        }

        log.info("login >> data=" + jsonData);

        if (jsonData != null && jsonData.length() > 1) {

            // Gson gson = new Gson();
            JSONParser parser = new JSONParser();
            JSONObject obj = (JSONObject) parser.parse(jsonData);

            // LoginInfo result = new LoginInfo();
            String phone = (String) obj.get("phone");
            // String password = (String) obj.get("password");

            // log.info("Driver Phone =" + phone);
            // log.info("password =" + password);

            if (phone != null) {

                DriverMaster driverMaster = DatabaseManager.validateDriver(phone);

                if (driverMaster != null) {

                    // log.info("Inside Driver >> Login Successfull. HTTP bookingStatus code is 200.");

                    responseMap.put("code", "200");
                    responseMap.put("msg", "Login Succesful.");
                    responseMap.put("driverId", driverMaster.getDriverId());
                    responseMap.put("firstName", driverMaster.getFirstName());
                    responseMap.put("phoneNumber", driverMaster.getPhoneNumber());
                    responseMap.put("driverStatus", driverMaster.getDriverStatus());
                    responseMap.put("currAddr", driverMaster.getCurrAddr());
                    responseMap.put("currLongt", driverMaster.getCurrLongt());
                    responseMap.put("currLat", driverMaster.getCurrLat());
                    responseMap.put("bookingId", driverMaster.getBookingId());

                    log.info("login >>  Login response = " + responseMap.toString());

                } else {
                    log.info("login >> Login Error. HTTP bookingStatus code is "
                            + ConfigDetails.constants.get("BOOKING_FAILED_CODE") + ".");

                    responseMap.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE"));
                    responseMap.put("msg", "Driver phone doesn't exists.");
                }

            }

        }

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

    if (responseMap.size() < 1) {

        log.info("Login Error. HTTP bookingStatus code is " + ConfigDetails.constants.get("BOOKING_FAILED_CODE")
                + ".");

        responseMap.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE"));
        responseMap.put("msg", "Server Error.");
        return Response.status(200).entity(jsonCreater(responseMap)).build();
    } else {
        return Response.status(200).entity(jsonCreater(responseMap)).build();
    }

}

From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java

public final Shops getFormattedShopList() {
    try {//from  ww w.ja v  a 2s  .  co  m
        String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json")));

        JSONParser parser = new JSONParser();

        Object obj = parser.parse(configTable);

        JSONObject jsonObj = (JSONObject) obj;

        JSONArray shopList = (JSONArray) jsonObj.get("shopsArray");

        String formattedShopList = "List of mcDropShops:\n";
        // Make sure that our array isn't empty
        if (shopList == null) {
            formattedShopList = "\u00A7e<\u00A7ainternal error\u00A7e>";
        }

        String shopName;
        String world;
        String x;
        String y;
        String z;
        String tmp;
        JSONObject shopObj;
        //System.out.println("[MDS DBG MSG] shopList.size() = "+shopList.size());
        for (int index = 0; index < shopList.size(); index++) {
            //System.out.println(index);

            shopObj = (JSONObject) (shopList.get(index));

            //System.out.println(shopObj);
            shopName = (String) shopObj.get("shopName");
            //System.out.println(shopName);
            world = (String) shopObj.get("world");
            //System.out.println(world);
            x = (String) shopObj.get("x");
            //System.out.println(x);
            y = (String) shopObj.get("y");
            //System.out.println(y);
            z = (String) shopObj.get("z");
            //System.out.println(z);

            formattedShopList = formattedShopList + "\u00A7a" + shopName + ": \u00A7e" + world + "," + x + ","
                    + y + "," + z + "\n";
            //System.out.println(formattedShopList);
        }

        this.returnStack = (Object) formattedShopList;
        return this;
    } catch (ParseException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in getFormattedShopList(void)");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json");
        e.printStackTrace();
    } catch (IOException e) {
        Bukkit.getLogger().warning("[mcDropShop] Caught IOException in getFormattedShopList(void)");
        e.printStackTrace();
    }

    return this;
}

From source file:net.phyloviz.nj.json.NJItemFactory.java

@Override
public ProjectItem loadData(DataSet dataset, TypingData<? extends AbstractProfile> td, String directory,
        String filename, AbstractDistance ad, int level) {

    JsonValidator validator = new JsonValidator();
    try {/*from   w  w w  . j  a  v a2 s.  c  o  m*/
        if (!validator.validate(directory, filename)) {
            return null;
        }
    } catch (IOException e) {
        Exceptions.printStackTrace(e);
    }

    NeighborJoiningItem njItem = null;

    try (FileReader reader = new FileReader(new File(directory, filename))) {

        JSONParser parser = new JSONParser();
        JSONObject json;
        json = (JSONObject) parser.parse(reader);

        JSONArray leafsArr = (JSONArray) json.get("leaf");
        JSONArray unionsArr = (JSONArray) json.get("union");
        JSONObject rootObj = (JSONObject) json.get("root");

        Map<Integer, NJLeafNode> leafs = createLeafs(td, leafsArr);

        Map<Integer, NJUnionNode> unions = new HashMap();
        if (unionsArr != null) {
            unions = createUnions(unionsArr, leafs);
        }
        NJRoot root = createRoot(rootObj, leafs, unions);

        AgglomerativeClusteringMethod cm = getMethodProvider(filename, td);

        OutputPanel op = new OutputPanel(dataset.toString() + ": Neighbor-Joining");
        njItem = new NeighborJoiningItem(root, ad, cm, op);
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
    return njItem;
}

From source file:com.neu.cloud.Controller.UseCaseController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

    ModelAndView mv = new ModelAndView();
    HttpSession session = request.getSession();

    String code = request.getParameter("code");

    // get the access token by post to Google
    String body = post("https://accounts.google.com/o/oauth2/token",
            ImmutableMap.<String, String>builder().put("code", code).put("client_id", clientId)
                    .put("client_secret", clientSecret)
                    .put("redirect_uri", "http://localhost:8080/CloudProject/usecase.htm")
                    .put("grant_type", "authorization_code").build());

    JSONObject jsonObject = null;//from   w ww  .  ja v  a2s  .  c o  m

    // get the access token from json and request info from Google
    try {
        jsonObject = (JSONObject) new JSONParser().parse(body);
    } catch (ParseException e) {
        throw new RuntimeException("Unable to parse json " + body);
    }

    // google tokens expire after an hour, but since we requested offline access we can get a new token without user involvement via the refresh token
    String accessToken = (String) jsonObject.get("access_token");

    // you may want to store the access token in session
    request.getSession().setAttribute("access_token", accessToken);

    // get some info about the user with the access token
    String json = get(new StringBuilder("https://www.googleapis.com/oauth2/v1/userinfo?access_token=")
            .append(accessToken).toString());

    // now we could store the email address in session

    JSONObject jsonObject1 = null;
    jsonObject = (JSONObject) new JSONParser().parse(json);
    // return the json of the user's basic info
    String username = (String) jsonObject.get("username");
    session.setAttribute("username", username);
    //response.getWriter().println(json);
    mv.setViewName("useCase");
    return mv;
}

From source file:fr.bmartel.speedtest.test.SpeedTestServerTest.java

@Test
public void serverListTest() throws IOException, ParseException, TimeoutException {

    initSocket();//  ww w  . j a v a  2s  .c om

    final URL url = getClass().getResource("/" + TestCommon.SERVER_LIST_FILENAME);

    final Object obj = new JSONParser().parse(new FileReader(url.getPath()));

    final JSONArray servers = (JSONArray) obj;

    for (int i = 0; i < servers.size(); i++) {

        final JSONObject serverObj = (JSONObject) servers.get(i);

        if (serverObj.containsKey("host")) {

            final String host = serverObj.get("host").toString();

            if (serverObj.containsKey("download")) {

                final JSONArray downloadEndpoints = (JSONArray) serverObj.get("download");

                for (int j = 0; j < downloadEndpoints.size(); j++) {

                    final JSONObject downloadEndpoint = (JSONObject) downloadEndpoints.get(j);

                    if (downloadEndpoint.containsKey("protocol")) {

                        final String protocol = downloadEndpoint.get("protocol").toString();

                        if (downloadEndpoint.containsKey("uri")) {

                            final String uri = downloadEndpoint.get("uri").toString();

                            switch (protocol) {
                            case "http":
                                System.out.println("[download] HTTP - testing " + host + " with uri " + uri);
                                mWaiter = new Waiter();
                                mSocket.startDownload(host, uri);
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                mWaiter = new Waiter();
                                mSocket.forceStopTask();
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                break;
                            case "ftp":

                                String username = SpeedTestConst.FTP_DEFAULT_USER;
                                String password = SpeedTestConst.FTP_DEFAULT_PASSWORD;

                                if (downloadEndpoint.containsKey("username")) {
                                    username = downloadEndpoint.get("username").toString();
                                }
                                if (downloadEndpoint.containsKey("password")) {
                                    password = downloadEndpoint.get("password").toString();
                                }
                                System.out.println("[download] FTP - testing " + host + " with uri " + uri);
                                mWaiter = new Waiter();
                                mSocket.startFtpDownload(host, SpeedTestConst.FTP_DEFAULT_PORT, uri, username,
                                        password);
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                mWaiter = new Waiter();
                                mSocket.forceStopTask();
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                break;
                            default:
                                break;
                            }

                        } else {
                            Assert.fail("download for host " + host + " has no uri");
                        }
                    } else {
                        Assert.fail("download for host " + host + " has no protocol");
                    }
                }
            }
            if (serverObj.containsKey("upload")) {

                final JSONArray uploadEndpoints = (JSONArray) serverObj.get("upload");

                for (int j = 0; j < uploadEndpoints.size(); j++) {

                    final JSONObject uploadEndpoint = (JSONObject) uploadEndpoints.get(j);

                    if (uploadEndpoint.containsKey("protocol")) {

                        final String protocol = uploadEndpoint.get("protocol").toString();

                        if (uploadEndpoint.containsKey("uri")) {

                            final String uri = uploadEndpoint.get("uri").toString();

                            switch (protocol) {
                            case "http":
                                System.out.println("[upload] HTTP - testing " + host + " with uri " + uri);
                                mWaiter = new Waiter();
                                mSocket.startUpload(host, uri, TestCommon.FILE_SIZE_LARGE);
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                mWaiter = new Waiter();
                                mSocket.forceStopTask();
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                break;
                            case "ftp":
                                String username = SpeedTestConst.FTP_DEFAULT_USER;
                                String password = SpeedTestConst.FTP_DEFAULT_PASSWORD;

                                if (uploadEndpoint.containsKey("username")) {
                                    username = uploadEndpoint.get("username").toString();
                                }
                                if (uploadEndpoint.containsKey("password")) {
                                    password = uploadEndpoint.get("password").toString();
                                }
                                System.out.println("[upload] FTP - testing " + host + " with uri " + uri);
                                final String fileName = generateFileName() + ".txt";
                                mWaiter = new Waiter();
                                mSocket.startFtpUpload(host, SpeedTestConst.FTP_DEFAULT_PORT,
                                        uri + "/" + fileName, TestCommon.FILE_SIZE_LARGE, username, password);
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                mWaiter = new Waiter();
                                mSocket.forceStopTask();
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                break;
                            default:
                                break;
                            }

                        } else {
                            Assert.fail("upload for host " + host + " has no uri");
                        }

                    } else {
                        Assert.fail("upload for host " + host + " has no protocol");
                    }
                }
            }
        }
    }

    mSocket.clearListeners();
}

From source file:it.polimi.diceH2020.plugin.control.JSonReader.java

public void read() {
    // read the json file
    FileReader reader;/*from w ww  . j a  v a2 s  .c  o  m*/

    try {
        reader = new FileReader(filePath);

        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
        provider = (String) jsonObject.get("provider");
        JSONArray lang = (JSONArray) jsonObject.get("lstSolutions");
        Iterator<?> i = lang.iterator();

        // take each value from the json array separately
        while (i.hasNext()) {
            JSONObject innerObj = (JSONObject) i.next();
            String idClass = (String) innerObj.get("id");
            long numVm = (long) innerObj.get("numberVM");
            JSONObject jsonOb = (JSONObject) innerObj.get("typeVMselected");
            String type = (String) jsonOb.get("id");
            this.classNumVM.put(idClass, numVm);
            this.classTypeVM.put(idClass, type);
            this.classes.add(idClass);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:mongodbutils.Filehandler.java

public boolean processFile(String filePath, MongodbConnection mc, String strdbName, String strCollName)
        throws IOException {
    this.mc = mc;

    FileInputStream fileIn = null;
    try {/*from  ww w.j  a  v a  2s . com*/
        fileIn = new FileInputStream(filePath);
        POIFSFileSystem fs = new POIFSFileSystem(fileIn);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);

        Object objReturn = null;

        //Read in first row as field names
        Row rowH = sheet.getRow(sheet.getFirstRowNum());
        String fields[] = new String[sheet.getRow(0).getLastCellNum()];
        for (Cell cell : rowH) {
            objReturn = null;
            objReturn = getCellValue(cell);
            fields[cell.getColumnIndex()] = objReturn.toString();
        }

        //loop thru all cells with values
        int rowcount = 0;
        for (Row row : sheet) {
            if (row.getRowNum() == 0) {
                continue; //skip first row
            }
            JSONObject obj = new JSONObject();

            for (Cell cell : row) {
                if (fields.length < cell.getColumnIndex()) {
                    continue; //only export column if we have header set
                }
                objReturn = null;
                objReturn = getCellValue(cell);
                if (!objReturn.toString().equals("")) {
                    if (objReturn instanceof Double) {
                        obj.put(fields[cell.getColumnIndex()], objReturn);

                    } else if (objReturn instanceof String) {
                        if (objReturn.toString().contains("$date")) {
                            JSONParser parser = new JSONParser();
                            try {
                                obj.put(fields[cell.getColumnIndex()], parser.parse(objReturn.toString()));
                            } catch (ParseException ex) {
                                Logger.getLogger(Filehandler.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        } else {
                            obj.put(fields[cell.getColumnIndex()], objReturn);
                        }
                    }
                }
            }
            rowcount += 1;
            mc.insertJSON(strdbName, strCollName, obj.toJSONString());
        }

        return true;
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Filehandler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Filehandler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception e) {
        Logger.getLogger(Filehandler.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        if (fileIn != null) {
            fileIn.close();
        }
    }
    return false;
}

From source file:com.Jax.GenericResource.java

@POST
@Consumes(MediaType.APPLICATION_JSON)//from  w  ww  . j  ava2  s.c  om
@Produces(MediaType.APPLICATION_JSON)
@Path("/post")
public void createProduct(String content) throws ParseException, SQLException {
    JSONParser parser = new JSONParser();
    JSONObject json = (JSONObject) parser.parse(content);

    Object id = json.get("id");
    String newProductID = id.toString();
    int productID = Integer.parseInt(newProductID);

    Object newName = json.get("newName");
    String name = newName.toString();

    Object newDescription = json.get("newDescription");
    String description = newDescription.toString();

    Object qty = json.get("qty");
    String newQty = qty.toString();
    int quantity = Integer.parseInt(newQty);

    Statement stmt = con.createStatement();
    String query = "INSERT INTO products VALUES('" + productID + "','" + newName + "','" + newDescription
            + "','" + quantity + "')";
    stmt.executeUpdate(query);
}