Package org.json.simple.parser

Examples of org.json.simple.parser.JSONParser


   *             string.
   */
  public static CassandraConfiguration create(String configuration)
      throws IOException, ParseException {
    final CassandraConfiguration result = new CassandraConfiguration();
    final JSONParser parser = new JSONParser();

    try {
      _log.info("Started checking whether configuration is a URI...");
      final File file = new File(configuration);
      if (file.exists()) {
        _log.info("Configuration is a file.");
        result.configure((JSONObject) parser
            .parse(new FileReader(file)));
        return result;
      } else {
        _log.info("Configuration is not a file.");
      }

      _log.info("Started checking whether configuration is a resource...");
      InputStream stream = null;
      try {
        stream = CassandraConfiguration.class
            .getResourceAsStream(configuration);
        _log.info("Configuration is a resource.");
      } catch (Exception e) {
        _log.info("Configuration is not a resource.");
      } finally {
        if (stream != null) {
          result.configure((JSONObject) parser
              .parse(new BufferedReader(new InputStreamReader(
                  stream))));
          return result;
        }
      }

      _log.info("Started checking whether configuration is a JSON string...");
      JSONObject configObject = null;
      try {
        configObject = (JSONObject) parser.parse(configuration);
      } catch (Exception e) {
        _log.info("Configuration is not a JSON string.");
      } finally {
        if (configObject != null) {
          _log.info("Configuration is a JSON string.");
View Full Code Here


     * @param json string to be parsed
     * @return a {@code JSONArray}
     * @throws {@code AssertionError} if the string cannot be parsed into a {@code JSONArray}
     */
    private JSONArray parseJSONArray(String json) throws AssertionError {
        JSONParser parser = new JSONParser();
        try {
            Object obj = parser.parse(json);
            assertTrue(obj instanceof JSONArray);
            return (JSONArray) obj;
        } catch (Exception e) {
            throw new AssertionError("not a valid JSON array: " + e.getMessage());
        }
View Full Code Here

                        rev = mk.getHeadRevision();
                    }
                    int sum = 0;
                    for (Map.Entry<Integer, JSONObject> entry : nodes.entrySet()) {
                        String json = mk.getNodes("/node-" + entry.getKey(), rev, 0, 0, 1000, null);
                        JSONParser parser = new JSONParser();
                        JSONObject obj = (JSONObject) parser.parse(json);
                        entry.setValue(obj);
                        sum += (Long) obj.get("value");
                    }
                    if (sum < 60) {
                        // retry with other nodes
                        return false;
                    }
                    StringBuilder jsop = new StringBuilder();
                    boolean withdrawn = false;
                    for (Map.Entry<Integer, JSONObject> entry : nodes.entrySet()) {
                        long value = (Long) entry.getValue().get("value");
                        jsop.append("^\"/node-").append(entry.getKey());
                        jsop.append("/value\":");
                        if (value >= 20 && !withdrawn) {
                            jsop.append(value - 20);
                            withdrawn = true;
                        } else {
                            jsop.append(value + 10);
                        }
                    }
                    String oldRev = rev;
                    rev = mk.commit("", jsop.toString(), rev, null);
                    if (useBranch) {
                        rev = mk.merge(rev, null);
                    }
                    log("Successful transfer @" + oldRev + ": " + jsop.toString() + " (new rev: " + rev + ")");
                    return true;
                }
            }));
        }
        for (Thread t : writers) {
            t.start();
        }
        for (Thread t : writers) {
            t.join();
        }
        // dispose will flush all pending revisions
        for (DocumentMK mk : kernels) {
            mk.dispose();
        }
        DocumentMK mk = openDocumentMK();
        String rev = mk.getHeadRevision();
        long sum = 0;
        for (int i = 0; i < NUM_NODES; i++) {
            String json = mk.getNodes("/node-" + i, rev, 0, 0, 1000, null);
            JSONParser parser = new JSONParser();
            JSONObject obj = (JSONObject) parser.parse(json);
            sum += (Long) obj.get("value");
        }
        log("Conflict rate: " + conflicts.get() +
                "/" + (NUM_WRITERS * NUM_TRANSFERS_PER_THREAD));
        System.out.print(logBuffer);
View Full Code Here

        return obj.toJSONString();
    }

    private <T extends Document> T fromString(Collection<T> collection, String data) throws ParseException {
        T doc = collection.newDocument(this);
        Map<String, Object> obj = (Map<String, Object>) new JSONParser().parse(data);
        for (Map.Entry<String, Object> entry : obj.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (value == null) {
                // ???
View Full Code Here

   * @throws IOException thrown if the <code>InputStream</code> could not be
   * JSON parsed.
   */
  static Object jsonParse(HttpURLConnection conn) throws IOException {
    try {
      JSONParser parser = new JSONParser();
      return parser.parse(new InputStreamReader(conn.getInputStream()));
    } catch (ParseException ex) {
      throw new IOException("JSON parser error, " + ex.getMessage(), ex);
    }
  }
View Full Code Here

  public HashMap<String, String> getFinalData(ArrayList<String> OutputData, String URI, String MovieName) {
   
    HashMap<String, String> FinalData = new HashMap<String, String>();
   
    String StrMovieData = new String(); // JSON String returned from server
    JSONParser parser = new JSONParser();
    KeyFinder finder = new KeyFinder();
   
    // avoid EOF exception
    MovieName = MovieName.replaceAll("([\\.\\s_])", "+"); // avoid EOF exception
    MovieName = MovieName.replaceAll("(?i)" +
              "(dvdrip" +
              "|hdtv" +
              "|xvid" +
              "|subforced" +
              "|vfstfr" +
              "|fastsub" +
              "|brrip" +
              "|ac3" +
              "|dvd)", "");
    MovieName = MovieName.replaceAll("(?i)vost[a-zA-Z]{2}", "");
    //MovieName = MovieName.replaceAll("(?i)(fr|en)", ""); // "freak" = "eak"
    MovieName = MovieName.replaceAll("\\[(.*)\\]", "");
    MovieName = MovieName.replaceAll("\\((.*)\\)", "");
    MovieName = MovieName.replaceAll("[\\+]+", "+");

    try {
      // Create URL for the API
      URL url = new URL(URI+MovieName);
     
      // Get JSON from server
      BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
      String JSONString;
      while ((JSONString = in.readLine()) != null) {
        StrMovieData += JSONString;
      }
      in.close();
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    }

    for (String Data : OutputData) {
   
      finder.setMatchKey(Data);

      try{
        parser.parse(StrMovieData, finder, true);
        if(finder.isFound()){
          finder.setFound(false);
          FinalData.put(Data, finder.getValue().toString().trim());
        }
        parser.reset();
      }
      catch(ParseException pe){// TODO add an error for Unavailable service
        return null;
      }
   
View Full Code Here

    private JSONArray Zauber;
    private JSONObject Spruch;
   
public Object get_zauber(String name){
    try{
    parser = new JSONParser();
    Zauber = (JSONArray) parser.parse(json);
        } catch (ParseException ex) {
                ex.printStackTrace();
        } catch (NullPointerException ex) {
                ex.printStackTrace();
View Full Code Here

public String[] getAllZauber(){
    String[] Zauberliste;
   
try{
    parser = new JSONParser();
    Zauber = (JSONArray) parser.parse(json);
        } catch (ParseException ex) {
                ex.printStackTrace();
        } catch (NullPointerException ex) {
                ex.printStackTrace();
View Full Code Here

      sord = req.getParameter("sord");
     
      SSPageInfo sspInfo = new SSPageInfo(page, limit, sidx, sord);
      sspInfo.set_search( req.getParameter("_search") );
      if(sspInfo.is_search() && req.getParameter("filters")!=null ) {
        JSONParser jnParser = new JSONParser();
        JSONObject jo = (JSONObject)jnParser.parse( req.getParameter("filters") );
        sspInfo.setCondition(jo);
      }   
   
      // $2 -----------------------     
 
      List<UserAccount> accounts = UserAccountServices.getInstance().sspUserAccount(sspInfo);
     
      // $3 -----------------------
      // constructing a JSON
      JSONObject jnObj = new JSONObject();
      jnObj.put("page", sspInfo.getPage());
      jnObj.put("total", sspInfo.getTotal());
      jnObj.put("records", sspInfo.getRecords());
     
      JSONArray jnAry = new JSONArray();
      JSONObject perJN;
      UserAccount acc = null;
      for(int i=0, size=accounts.size(); i<size; i++) {
        acc = accounts.get(i);
        perJN = new JSONObject();
        perJN.put("id", acc.getId());
        perJN.put("account", acc.getAccount());
        perJN.put("profile.name", acc.getProfile().getName());
        perJN.put("profile.employeeId", acc.getProfile().getEmployeeId());
        perJN.put("profile.email", acc.getProfile().getEmail());
        perJN.put("profile.mobile", acc.getProfile().getMobile());
       
        perJN.put("myGroups", acc.getMyGroups())
        perJN.put("delMark", acc.isDeleteMark());
        jnAry.add(perJN);
      }
     
      jnObj.put("rows", jnAry);
     
//      System.out.println( "JSON.toString = \n"+ jnObj.toString() );
      res.setContentType("text/json;charset=utf-8");
      res.getWriter().write( jnObj.toString() );
// EDIT     
    } else if (req.getRequestURI().endsWith("edit.do")) {
//      System.out.println("req.URI="+req.getRequestURI());
      UserAccount user = this.compose(req);
      JSONObject jnObj = new JSONObject();
      try {
        if( !UserAccountServices.getInstance().saveOrUpdateUserAccount(user, true) ) {       
          jnObj.put("msg", "Edit User Info Failure~!");
          res.getWriter().write(jnObj.toString());
        } else {
          jnObj.put("msg","Edit User Info Success !");         
          res.getWriter().write(jnObj.toString());         
        }
      } catch (Exception ex) {
        res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        jnObj.put("msg",ex.getMessage());         
        res.getWriter().write(jnObj.toString());         
      }
     
// ADD     
    } else if (req.getRequestURI().endsWith("add.do")) {
//      System.out.println("req.URI="+req.getRequestURI());
      UserAccount user = compose(req);
      try {
        if(!UserAccountServices.getInstance().saveOrUpdateUserAccount(user, false)) {
          res.getWriter().write("Add User Account/Profile/Group Failure~!");
        } else {
          res.getWriter().write("Add User Account/Profile/Group Success !");
        }
      } catch (Exception ex) {
        //ex.printStackTrace();
        //res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        res.getWriter().write(ex.getMessage());
      }     
// DEL     
    } else if (req.getRequestURI().endsWith("del.do")) {
//      System.out.println("req.URI="+req.getRequestURI());
      String account = req.getParameter("account");
      try {
        if(! UserAccountServices.getInstance().deleteMark(account, true) ) {
          res.getWriter().write("Mark Delete failure!");
        } else {
          res.getWriter().write("Mark Delete Success!");
        }
      } catch(Exception ex) {
        res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        res.getWriter().write(ex.getMessage());
      }
// RESET     
    } else if (req.getRequestURI().endsWith("reset.do")) {
//      System.out.println("req.URI="+req.getRequestURI());
      String account = req.getParameter("account");
      String type = req.getParameter("type");
      JSONObject jnObj = new JSONObject();
      try {
        if("R".equals(type)) {
          if(! UserAccountServices.getInstance().resetPassword(account, account) ) {
            res.getWriter().write("Reset Password Failure!");
          } else {
            res.getWriter().write("Reset Password Success!<br> Your New Password is Your Account! ");
          }
        } else if("C".equals(type)) {
          if(! UserAccountServices.getInstance().deleteMark(account, false) ) {
            res.getWriter().write("Cancel Delete Mark Failure!");
          } else {
            res.getWriter().write("Cancel Delete Mark Success!");
          }
        } else if("N".equals(type)) {
          String oldPwd = req.getParameter("oldPwd");
          String newPwd = req.getParameter("newPwd");
         
          if(! UserAccountServices.getInstance().setNewPassword(account, oldPwd, newPwd) ) {
            jnObj.put("msg", "Set New Password Failure!");
            res.getWriter().write(jnObj.toString());
          } else {
            jnObj.put("msg", "Set New Password Success!");
            res.getWriter().write(jnObj.toString());
          }
        }
      } catch(Exception ex) {
        res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        jnObj.put("msg", ex.getMessage());
        res.getWriter().write( jnObj.toString() );
      }
// List GROUPS     
    } else if(req.getRequestURI().endsWith("groups.do")) {
        Integer page, limit;
        String sidx, sord;
        // $1 ----------------------
        // get the requested page
        page = Integer.valueOf(req.getParameter("page"));
        // get how many rows we want to have into the grid
        // rowNum parameter in the grid
        limit = Integer.valueOf(req.getParameter("rows"));
        // get index row - i.e. user click to sort
        // at first time sortname parameter - after that the index from colModel
        sidx = req.getParameter("sidx");
        // sorting order - at first time sortorder
        sord = req.getParameter("sord");
       
        SSPageInfo sspInfo = new SSPageInfo(page, limit, sidx, sord);
        sspInfo.set_search( req.getParameter("_search") );
        if(sspInfo.is_search() && req.getParameter("filters")!=null ) {
          JSONParser jnParser = new JSONParser();
          JSONObject jo = (JSONObject)jnParser.parse( req.getParameter("filters") );
          sspInfo.setCondition(jo);
        }   
     
        // $2 -----------------------         
        List<Group> allGroups = UserAccountServices.getInstance().sspGroups(sspInfo);
View Full Code Here

        Map<String, String> map = new HashMap<String, String>();
        map.put("a", "A");
        map.put("b", "&");
        String str = ELConstantsFunctions.toJsonStr(map);
        Element e = XmlUtils.parseXml("<x>" + str + "</x>");
        JSONObject json = (JSONObject) new JSONParser().parse(e.getText());
        Map<String, String> map2 = new HashMap<String, String>(json);
        assertEquals(map, map2);
    }
View Full Code Here

TOP

Related Classes of org.json.simple.parser.JSONParser

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.