public String validateUpdatedData(String result) {
    // System.out.println("RESULT------------------>" + result);
    String status = "0";
    try {
      JSONParser parser = new JSONParser();
      Object jsonObject = parser.parse(result);

      JSONArray jsonArray = (JSONArray) jsonObject;

      System.out.println("Bookmark SIZEEEEE" + jsonArray.size());

      JSONObject jsonObjected = (JSONObject) parser.parse(jsonArray.get(0).toString());

      objTickerNewsBE.setNewsId(jsonObjected.get("id").toString());
      objTickerNewsBE.setImage(jsonObjected.get("image").toString());
      objTickerNewsBE.setContent(jsonObjected.get("content").toString());
      objTickerNewsBE.setSource(jsonObjected.get("publisher").toString());
      objTickerNewsBE.setDate(jsonObjected.get("date").toString());
      objTickerNewsBE.setTag(jsonObjected.get("tag").toString());
      objTickerNewsBE.setTitle(jsonObjected.get("title").toString());
      objTickerNewsBE.setUrl(jsonObjected.get("link").toString());

    } catch (Exception e) {
      e.printStackTrace();
    }
    return status;
  }
  protected MovieContent.MovieDetails doInBackground(MovieContent.MovieItem... movies) {
    MovieContent.MovieItem movie = movies[0];
    JSONObject movieDetails = null;
    try {
      URLConnection urlConn = new URL(movie.movieURL).openConnection();
      BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
      JSONParser parser = new JSONParser();
      movieDetails = (JSONObject) parser.parse(in);

    } catch (Exception e) {
      Log.e("Error", e.getMessage());
      e.printStackTrace();
    }
    try {
      URLConnection urlConn = new URL(movie.castURL).openConnection();
      BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
      JSONParser parser = new JSONParser();
      JSONObject obj = (JSONObject) parser.parse(in);

    } catch (Exception e) {
      Log.e("Error", e.getMessage());
      e.printStackTrace();
    }
    return new MovieContent.MovieDetails(movieDetails);
  }
  @Override
  public void run() {
    // TODO Auto-generated method stub

    try {
      this.in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
      JSONObject message;
      int i = 0;
      // receive the first several messages
      while (i < 4) {
        message = (JSONObject) parser.parse(in.readLine());
        MessageReceive(socket, message);
        i++;
      }
      while (run) {
        System.out.print("[" + room_id + "] " + identity + "> ");
        message = (JSONObject) parser.parse(in.readLine());
        MessageReceive(socket, message);
      }
      System.exit(0);
      in.close();
      socket.close();
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Exemple #4
0
 @Test
 public void detailsReturnsJson()
     throws ParseException, EmptyResponse, InvalidFormat, InvalidResponse, APIError, RequestFailed,
         EmptySession, EmptyUsername, InvalidUsername {
   Task task = setUp();
   JSONParser parser = new JSONParser();
   JSONObject json = (JSONObject) parser.parse("{\"info\":{\"info\":\"info\"}}");
   expect(task.fetch(isA(String.class), isA(String.class))).andReturn(json);
   replay(task);
   JSONObject obj = (JSONObject) parser.parse("{\"info\":\"info\"}");
   assertEquals(obj, task.details(123));
 }
  private void parseDetail(String result) {
    JSONParser jsonP = new JSONParser();
    try {
      Object obj = jsonP.parse(result);
      JSONArray jsonArrayObject = (JSONArray) obj;
      JSONObject jsonObject = (JSONObject) jsonP.parse(jsonArrayObject.get(0).toString());
      objForumQuestionDetailBE.setTitle(jsonObject.get("title").toString());
      objForumQuestionDetailBE.setName(jsonObject.get("name").toString());
      objForumQuestionDetailBE.setTimestamp(jsonObject.get("date").toString());

    } catch (Exception e) {
      e.getLocalizedMessage();
    }
  }
  public void getAccessToken(String code) {
    try {
      String accessTokenString =
          FacebookOAuth2Details.accessTokenUri
              + "?client_id="
              + FacebookOAuth2Details.clientId
              + "&client_secret="
              + FacebookOAuth2Details.clientSecret
              + "&code="
              + code
              + "&redirect_uri="
              + FacebookOAuth2Details.redirectUri;

      URL myurl = new URL(accessTokenString);
      HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
      InputStream ins = con.getInputStream();
      InputStreamReader isr = new InputStreamReader(ins, "UTF-8");

      JSONParser parser = new JSONParser();
      JSONObject jObject = (JSONObject) parser.parse(isr);
      accessToken = jObject.get("access_token").toString();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public User getUserFromSocNet() {
    try {

      String methodString = FacebookOAuth2Details.methodUri + "me?access_token=" + accessToken;
      URL newUrl = new URL(methodString);

      HttpsURLConnection con = (HttpsURLConnection) newUrl.openConnection();
      InputStream ins = con.getInputStream();

      InputStreamReader newIsr = new InputStreamReader(ins, "UTF-8");
      JSONParser parser = new JSONParser();
      JSONObject jsonUser = (JSONObject) parser.parse(newIsr);

      userId = jsonUser.get("id").toString();

      User user = new User();
      user.setSocialId("fb" + userId);

      user.setFirstName(jsonUser.get("first_name").toString());

      user.setLastName(jsonUser.get("last_name").toString());
      if (jsonUser.get("email") != null) {

        user.setEmail(jsonUser.get("email").toString());
      }
      return user;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
Exemple #8
0
  public static long getResumeTime() {

    long time = 0;

    try {
      JSONParser parser = new JSONParser();

      FileReader file = new FileReader(saveFile);

      Object obj = parser.parse(file);

      JSONObject saveFileJSON = (JSONObject) obj;
      file.close();

      time = Long.parseLong(saveFileJSON.get("resumeTime").toString());

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

    return time;
  }
  public int[] parser(String json) {
    int[] data = null;
    JSONParser parser = new JSONParser();
    try {
      JSONArray jsow = (JSONArray) parser.parse(json);
      //			JSONArray jsow = (JSONArray)job;
      Iterator<String> it = jsow.iterator();
      data = new int[jsow.size()];
      int i = 0;
      //			System.out.println("jsow: "+jsow);
      while (it.hasNext()) {
        String tg = it.next();

        if (tg.contains(":")) {
          String[] arrtg = tg.split(":");
          data[i] = Integer.parseInt(arrtg[0]) * 3600 + Integer.parseInt(arrtg[1]) * 60;
        } else {
          // System.out.println("weight");
          data[i] = Integer.parseInt(tg);
        }
        // System.out.println(data[i]);
        i++;
      }
    } catch (Exception e) {
      System.err.println("parse1: " + e.toString());
    }

    return data;
  }
Exemple #10
0
  public List<String> assemblePybossaTaskPublishForm(String inputData, ClientApp clientApp)
      throws Exception {

    List<String> outputFormatData = new ArrayList<String>();
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(inputData);

    JSONArray jsonObject = (JSONArray) obj;
    Iterator itr = jsonObject.iterator();

    while (itr.hasNext()) {
      JSONObject featureJsonObj = (JSONObject) itr.next();
      JSONObject info = assemblePybossaInfoFormat(featureJsonObj, parser, clientApp);

      JSONObject tasks = new JSONObject();

      tasks.put("info", info);
      tasks.put("n_answers", clientApp.getTaskRunsPerTask());
      tasks.put("quorum", clientApp.getQuorum());
      tasks.put("calibration", new Integer(0));
      tasks.put("app_id", clientApp.getPlatformAppID());
      tasks.put("priority_0", new Integer(0));

      outputFormatData.add(tasks.toJSONString());

      // System.out.println(featureJsonObj.toString());
    }

    return outputFormatData;
  }
Exemple #11
0
  private Trie parseGenesis() {
    JSONParser parser = new JSONParser();
    JSONObject genesisMap = null;
    try {
      genesisMap = (JSONObject) parser.parse(GENESIS_JSON);
    } catch (ParseException e) {
      e.printStackTrace();
      System.exit(-1);
    }

    Set<String> keys = genesisMap.keySet();

    Trie state = new SecureTrie(null);

    for (String key : keys) {

      JSONObject val = (JSONObject) genesisMap.get(key);
      String denom = (String) val.keySet().toArray()[0];
      String value = (String) val.values().toArray()[0];

      BigInteger wei =
          Denomination.valueOf(denom.toUpperCase()).value().multiply(new BigInteger(value));

      AccountState acctState = new AccountState(BigInteger.ZERO, wei);
      byte[] keyB = Hex.decode(key);
      state.update(keyB, acctState.getEncoded());
      premine.put(wrap(keyB), acctState);
    }

    return state;
  }
Exemple #12
0
  public User getUserFromSocNet() {
    try {

      String methodString =
          VKOAuth2Details.methodUri
              + "users.get?user_ids="
              + userId
              + "&fields=city,sex,bdate&v=5.28&access_token="
              + accessToken
              + "&lang=ua";
      URL newUrl = new URL(methodString);
      HttpsURLConnection con = (HttpsURLConnection) newUrl.openConnection();
      InputStream ins = con.getInputStream();

      InputStreamReader newIsr = new InputStreamReader(ins, "UTF-8");
      JSONParser parser = new JSONParser();
      JSONObject response = (JSONObject) parser.parse(newIsr);
      JSONArray jsonUsers = (JSONArray) response.get("response");
      JSONObject jsonUser = (JSONObject) jsonUsers.get(0);

      User user = new User();
      user.setSocialId("vk" + userId);
      user.setEmail(email);
      user.setFirstName(jsonUser.get("first_name").toString());

      user.setLastName(jsonUser.get("last_name").toString());
      return user;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  public void parseJSONFeedback(String JSON) {
    String answer, patientID;
    int questionID, questionnaire;
    JSONParser parser = new JSONParser();
    try {
      Object obj = parser.parse(JSON);
      JSONArray array = (JSONArray) obj;
      for (int i = 0; i < array.size(); i++) {
        JSONObject everyQuestion = (JSONObject) array.get(i);

        answer = everyQuestion.get("Answer").toString();
        questionID = Integer.parseInt(everyQuestion.get("QuestionID").toString());
        patientID = everyQuestion.get("PatientID").toString();
        questionnaire = Integer.parseInt(everyQuestion.get("QuestionnaireID").toString());
        FeedbackFunctionality addToTable =
            new FeedbackFunctionality(questionnaire, patientID, questionID, answer);
        try {
          addToTable.addfeedback();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    } catch (ParseException pe) {
    }
  }
 /* Returns map of Wikipedia page-ids to number of inlinks to those pages. Page ids are pages the string 'anchor' points to in Wikipedia */
 public Map<Long, Integer> getPagesMap(String anchor) {
   db.requestStart();
   Map<Long, Integer> PageCollection = new HashMap<Long, Integer>();
   BasicDBObject query = new BasicDBObject();
   query.put("anchor", anchor);
   BasicDBObject fields =
       new BasicDBObject("page_id", true)
           .append("pages", true)
           .append("page_freq", true)
           .append("anchor_freq", true)
           .append("_id", false);
   DBObject ans =
       table.findOne(query, fields); // System.out.println("num of results = "+curs.count());
   db.requestDone();
   if (ans != null) {
     JSONParser jp = new JSONParser();
     JSONArray jo = null;
     try { // System.out.println(ans.get("pages"));
       jo = (JSONArray) jp.parse(ans.get("pages").toString());
     } catch (ParseException e) {
       e.printStackTrace();
     } // System.out.println("Link Freq = "+o.get("anchPageFreq").toString());
     for (int i = 0; i < jo.size(); i++) {
       JSONObject object = (JSONObject) jo.get(i);
       Long pId = (long) (object.get("page_id"));
       Long pValue0 = (long) object.get("page_freq");
       int pValue = pValue0.intValue();
       if (PageCollection.containsKey(pId)) {
         pValue = PageCollection.get(pId) + pValue;
       }
       PageCollection.put(pId, pValue);
     }
   }
   return PageCollection;
 } // End getPagesMap()
Exemple #15
0
  private void parseFile(File file, List<Artifact> artifacts, List<HostConfig> hostConfigs) {

    try {
      JSONParser parser = new JSONParser();
      JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(file));

      if (jsonObject.containsKey(JSON_TAG_ARTIFACTS)) {
        JSONArray jsonArray = (JSONArray) jsonObject.get(JSON_TAG_ARTIFACTS);

        Iterator<JSONObject> iterator = jsonArray.iterator();
        while (iterator.hasNext()) {
          artifacts.add(new Artifact(iterator.next()));
        }
      }

      if (jsonObject.containsKey(JSON_TAG_HOST_CONFIGS)) {
        JSONArray jsonArray = (JSONArray) jsonObject.get(JSON_TAG_HOST_CONFIGS);

        Iterator<JSONObject> iterator = jsonArray.iterator();
        while (iterator.hasNext()) {
          hostConfigs.add(new HostConfig(iterator.next()));
        }
      }

    } catch (IOException e) {
      throw new RuntimeException(
          MessageFormat.format(
              Main.bundle.getString("cli.error.cannot_read_file"), file.getAbsolutePath()));
    } catch (ParseException e) {
      throw new RuntimeException(
          MessageFormat.format(Main.bundle.getString("error.json.parse"), file.getAbsolutePath()));
    }
  }
 /* Returns List of Wikipedia page-ids of pages the string 'anchor' points to in Wikipedia */
 public List<Long> getPages(String anchor) {
   db.requestStart();
   List<Long> PageCollection = new ArrayList<Long>();
   BasicDBObject query = new BasicDBObject();
   query.put("anchor", anchor);
   BasicDBObject fields = new BasicDBObject("pages", true).append("_id", false);
   DBObject obj =
       table.findOne(query, fields); // System.out.println("num of results = "+curs.count());
   if (obj != null) {
     JSONParser jp = new JSONParser();
     JSONArray jarr = null;
     try {
       jarr = (JSONArray) jp.parse(obj.get("pages").toString());
     } catch (ParseException e) {
       jarr = new JSONArray();
     }
     // System.out.println("Link Freq = "+o.get("anchPageFreq").toString());
     for (int i = 0; i < jarr.size(); i++) {
       JSONObject objects = (JSONObject) jarr.get(i);
       PageCollection.add((long) (objects.get("page_id")));
     }
   }
   db.requestDone();
   return PageCollection;
 } // End getPages()
 /**
  * Reads JSON data from the reader and returns a search result.
  *
  * @return search result derived from the JSON
  * @throws IOException if an error occurs using the reader
  */
 @Override
 @SuppressWarnings("unchecked")
 public SearchResult read() throws IOException {
   final SearchResult result = new SearchResult(sortBehavior);
   try {
     final JSONParser parser = new JSONParser();
     final JSONArray jsonArray = (JSONArray) parser.parse(jsonReader);
     for (Object o : jsonArray) {
       final LdapEntry entry = new LdapEntry(sortBehavior);
       final JSONObject jsonObject = (JSONObject) o;
       for (Object k : jsonObject.keySet()) {
         final String attrName = (String) k;
         if ("dn".equalsIgnoreCase(attrName)) {
           entry.setDn((String) jsonObject.get(k));
         } else {
           final LdapAttribute attr = new LdapAttribute(sortBehavior);
           attr.setName(attrName);
           attr.addStringValues((List<String>) jsonObject.get(k));
           entry.addAttribute(attr);
         }
       }
       result.addEntry(entry);
     }
   } catch (ParseException e) {
     throw new IOException(e);
   }
   return result;
 }
Exemple #18
0
  public static long getAccID() {
    long id = 0;

    try {
      JSONParser parser = new JSONParser();

      FileReader file = new FileReader(saveFile);

      Object obj = parser.parse(file);

      JSONObject saveFileJSON = (JSONObject) obj;
      file.close();

      id = Long.parseLong(saveFileJSON.get("accID").toString());
    } catch (NumberFormatException e) {
      Refresh.validID = false;
      System.out.println("ID had an invalid character");
      return 0;
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ParseException e) {
      e.printStackTrace();
    }

    return id;
  }
 public void loadConfig() {
   AssetManager am = mApp.getAssets();
   BufferedReader br = null;
   StringBuilder sb = new StringBuilder();
   try {
     br = new BufferedReader(new InputStreamReader(am.open("news_config.xml")));
     String line;
     while ((line = br.readLine()) != null) {
       sb.append(line);
     }
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       if (br != null) br.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   JSONParser parser = new JSONParser();
   JSONObject jobj;
   try {
     jobj = (JSONObject) parser.parse(sb.toString());
     for (Object key : jobj.keySet()) {
       mProp.put(key, jobj.get(key));
     }
   } catch (ParseException e) {
     e.printStackTrace();
   }
 }
Exemple #20
0
  /**
   * Queries the Search API based on the command line arguments and takes the first result to query
   * the Business API.
   *
   * @param yelpApi <tt>YelpAPI</tt> service instance
   * @param yelpApiCli <tt>YelpAPICLI</tt> command line arguments
   */
  private static void queryAPI(YelpAPI yelpApi, YelpAPICLI yelpApiCli) {
    String searchResponseJSON =
        yelpApi.searchForBusinessesByLocation(yelpApiCli.term, yelpApiCli.location);

    JSONParser parser = new JSONParser();
    JSONObject response = null;
    try {
      response = (JSONObject) parser.parse(searchResponseJSON);
    } catch (ParseException pe) {
      System.out.println("Error: could not parse JSON response:");
      System.out.println(searchResponseJSON);
      System.exit(1);
    }

    JSONArray businesses = (JSONArray) response.get("businesses");
    JSONObject firstBusiness = (JSONObject) businesses.get(0);
    String firstBusinessID = firstBusiness.get("id").toString();
    System.out.println(
        String.format(
            "%s businesses found, querying business info for the top result \"%s\" ...",
            businesses.size(), firstBusinessID));

    // Select the first business and display business details
    String businessResponseJSON = yelpApi.searchByBusinessId(firstBusinessID.toString());
    System.out.println(String.format("Result for business \"%s\" found:", firstBusinessID));
    System.out.println(businessResponseJSON);
  }
Exemple #21
0
  private static HashMap<String, Boolean> fetchTopDocumentsFromFile(
      String location, String fileext, String query) throws FileNotFoundException, IOException {

    HashMap<String, Boolean> validurls = new HashMap<String, Boolean>();
    int count = 0;
    File[] files = new File(location).listFiles();
    for (int i = 0; i < files.length; i++) {
      if (!files[i].isFile() || !files[i].getName().endsWith(".json")) continue;
      System.out.println(files[i]);
      JSONParser parser = new JSONParser();
      Object obj = null;
      try {
        obj = parser.parse(new FileReader(files[i]));
        // System.out.println(obj);
      } catch (ParseException e1) {
        System.out.println("Could not parse the file " + files[i] + " as json");
      }
      JSONObject json = null;
      try {
        json = (JSONObject) obj;
        JSONArray arr = (JSONArray) ((JSONObject) json.get("hits")).get("hits");
        for (int j = 0; j < arr.size(); j++) {
          if (count == 1000) break;
          JSONObject o = (JSONObject) arr.get(j);
          validurls.put((String) o.get("_id"), true);
          count++;
        }
      } catch (Exception e) {
        System.out.println("json object could not be created " + e.toString());
      }
      if (count == 1000) break;
    }
    return validurls;
  }
Exemple #22
0
  public void read(Reader reader) {
    JSONParser jparser = new JSONParser();
    try {
      JSONObject root = (JSONObject) jparser.parse(reader);
      if (root.containsKey("type")) {
        TYPE type = TYPE.valueOf((String) root.get("type"));

        switch (type) {
          case NOTIFICATION:
            readNotification(root);
            break;
          case ABM_CONTENIDO:
            readABMContenido(root);
            break;
          default:
            break;
        }
      }
      reader.close();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ParseException e) {
      e.printStackTrace();
    }
  }
  /*
   * [{"IDpatient": "12-09-1000.Bayoumy","firstname": "Mohamed","lastname": "Bayoumy","dateofbirth": "12-09-1000"},
   * {"IDpatient": "12-02-1500.Omran","firstname": "Ahmed","lastname": "Omran","dateofbirth": "12-02-1500"}]
   *
   */
  public void parseJSONPatient(String JSON) {
    String IDpatient, firstname, lastname, dateofbirth;
    JSONParser parser = new JSONParser();
    try {
      Object obj = parser.parse(JSON);
      JSONArray array = (JSONArray) obj;
      for (int i = 0; i < array.size(); i++) {
        JSONObject everyQuestion = (JSONObject) array.get(i);

        IDpatient = everyQuestion.get("IDPatient").toString();
        firstname = everyQuestion.get("firstname").toString();
        lastname = everyQuestion.get("lastname").toString();
        dateofbirth = everyQuestion.get("dateofbirth").toString();

        FeedbackFunctionality addToTable =
            new FeedbackFunctionality(IDpatient, firstname, lastname, dateofbirth);
        try {
          addToTable.addpatients();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    } catch (ParseException pe) {
    }
  }
  protected Tweet parseTweet(String json) {
    JSONParser jsonParser = new JSONParser();

    JSONObject jsonObject = null;
    try {
      jsonObject = (JSONObject) jsonParser.parse(json);
    } catch (ParseException e) {
      throw new RuntimeException(e);
    }

    String orginalUser = null;
    if (jsonObject.containsKey("user")) {
      JSONObject userData = (JSONObject) jsonObject.get("user");
      user = userData.get("name").toString();
    }

    Tweet ret = new Tweet(user);

    if (jsonObject.containsKey("entities")) {
      JSONObject entities = (JSONObject) jsonObject.get("entities");
      if (entities.containsKey("hashtags")) {
        for (Object obj : (JSONArray) entities.get("hashtags")) {
          JSONObject hashObj = (JSONObject) obj;
        }
      }
    }
    return null; // TODO implement
  }
Exemple #25
0
  public List<String> assemblePybossaTaskPublishFormWithIndex(
      String inputData, ClientApp clientApp, int indexStart, int indexEnd) throws Exception {

    List<String> outputFormatData = new ArrayList<String>();
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(inputData);

    JSONArray jsonObject = (JSONArray) obj;
    Iterator itr = jsonObject.iterator();

    for (int i = indexStart; i < indexEnd; i++) {
      JSONObject featureJsonObj = (JSONObject) jsonObject.get(i);
      JSONObject info = assemblePybossaInfoFormat(featureJsonObj, parser, clientApp);

      JSONObject tasks = new JSONObject();

      tasks.put("info", info);
      tasks.put("n_answers", clientApp.getTaskRunsPerTask());
      tasks.put("quorum", clientApp.getQuorum());
      tasks.put("calibration", new Integer(0));
      tasks.put("app_id", clientApp.getPlatformAppID());
      tasks.put("priority_0", new Integer(0));

      outputFormatData.add(tasks.toJSONString());
    }

    return outputFormatData;
  }
Exemple #26
0
 /**
  * コンストラクタ.
  *
  * @param id ID
  * @param jsonStr ソース
  * @return DavNode
  */
 @SuppressWarnings("unchecked")
 public static DavNode createFromJsonString(String id, String jsonStr) {
   if (jsonStr == null) {
     return null;
   }
   JSONParser parser = new JSONParser();
   JSONObject source;
   try {
     source = (JSONObject) parser.parse(jsonStr);
   } catch (ParseException e) {
     // ESのJSONが壊れている状態。
     throw DcCoreException.Dav.DAV_INCONSISTENCY_FOUND.reason(e);
   }
   DavNode davNode = new DavNode();
   davNode.setId(id);
   davNode.setCellId((String) source.get(KEY_CELL_ID));
   davNode.setBoxId((String) source.get(KEY_BOX_ID));
   davNode.setNodeType((String) source.get(KEY_NODE_TYPE));
   if (source.get(KEY_PARENT) instanceof String) {
     davNode.setParentId((String) source.get(KEY_PARENT));
   }
   davNode.setChildren((Map<String, String>) source.get(KEY_CHILDREN));
   davNode.setAcl((JSONObject) source.get(KEY_ACL));
   davNode.setProperties((JSONObject) source.get(KEY_PROPS));
   davNode.setCellId((String) source.get(KEY_CELL_ID));
   davNode.setPublished(((Long) source.get(KEY_PUBLISHED)).longValue());
   davNode.setUpdated(((Long) source.get(KEY_UPDATED)).longValue());
   if (source.containsKey(KEY_FILE)) {
     davNode.setFile((Map<String, Object>) source.get(KEY_FILE));
   }
   return davNode;
 }
  public void ImplyContainerFactoryInterface(String str) {
    String jsonText = str;
    // String jsonText = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}";
    JSONParser parser = new JSONParser();
    ContainerFactory containerFactory =
        new ContainerFactory() {
          // 匿名类
          @Override
          public Map createObjectContainer() {
            return new LinkedHashMap();
          }

          @Override
          public List creatArrayContainer() {
            return new LinkedList();
          }
        };
    try {
      // java.lang.Object parse(java.lang.String s, ContainerFactory containerFactory)
      Map json = (Map) parser.parse(jsonText, containerFactory);
      Iterator iter = json.entrySet().iterator();
      System.out.println("iterate results");
      while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
        System.out.println(entry.getKey() + "=>" + entry.getValue());
      }

      System.out.println("===toJSONString()===");
      System.out.println(JSONValue.toJSONString(json));

    } catch (ParseException ex) {
      Logger.getLogger(DecodeResearch.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Exemple #28
0
  public static int getMatchID(int matchNumber) {

    int id = 0;

    try {
      JSONParser parser = new JSONParser();

      FileReader file = new FileReader(saveFile);

      Object obj = parser.parse(file);

      JSONObject saveFileJSON = (JSONObject) obj;
      file.close();

      id = Integer.parseInt(saveFileJSON.get("match" + matchNumber + "ID").toString());

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

    return id;
  }
  @Test
  public void testImport() throws Exception {
    MemoryDatabase memDb = new MemoryDatabase("sample");
    memDb.start();

    final String jsonFileName = "/sample.json";
    memDb.importJSON(getClass(), jsonFileName);

    JSONParser jsonParser = new JSONParser();
    JSONArray tables =
        (JSONArray)
            jsonParser.parse(new InputStreamReader(getClass().getResourceAsStream(jsonFileName)));
    assertEquals(2, tables.size());

    Connection conn = memDb.getConnection();
    Statement stmt = conn.createStatement();

    JSONObject employee = (JSONObject) tables.get(0);
    ResultSet rs = stmt.executeQuery("SELECT * FROM \"employee\"");
    verifyTableEquals(employee, rs);
    rs.close();

    JSONObject team = (JSONObject) tables.get(1);
    rs = stmt.executeQuery("SELECT * FROM \"team\"");
    verifyTableEquals(team, rs);
    rs.close();

    stmt.close();
    conn.close();

    memDb.stop();
  }
  private void loadMappings() {
    try {
      if (!Configuration.OFFLINE_MODE) {
        try {
          fetch(Configuration.versionfile);
          fetch(Configuration.jsonfile);
        } catch (final IOException ignored) {
          System.err.println(
              "Failed to downloaded version file and hooks. Attempting to run without latest hooks.");
        }
      }

      System.out.println(Configuration.jsonfile);
      BufferedInputStream in =
          new BufferedInputStream(new FileInputStream(getLocalInsertionsFile()));
      GzipCompressorInputStream gzip = new GzipCompressorInputStream(in);

      JSONParser parser = new JSONParser();
      JSONArray classes = (JSONArray) parser.parse(new BufferedReader(new InputStreamReader(gzip)));
      for (int i = 0; i < classes.size(); i++) {
        JSONObject classEntry = (JSONObject) classes.get(i);
        String name = (String) classEntry.get("name");
        mappings.put(name, classEntry);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }