コード例 #1
0
  // Takes in a list of locations and and list of friends and outputs a JSON object with 5 most
  // recent friends for each location
  @SuppressWarnings("unchecked")
  static JSONObject getLocsRecentFriendsJSON(ArrayList<LocWithCheckIns> locsWithCheckIns) {
    JSONObject recentFriends = new JSONObject();
    JSONArray locations = new JSONArray();

    for (int i = 0; i < locsWithCheckIns.size(); i++) {
      JSONArray jsonfriends = new JSONArray();
      JSONObject location = new JSONObject();

      ArrayList<CheckIn> temps = new ArrayList<CheckIn>(locsWithCheckIns.get(i).checkIns);

      for (int j = 0; j < temps.size(); j++) {
        // jsonfriends.add(temps.get(j));
        jsonfriends.add(temps.get(j).getUserName());
        jsonfriends.add(temps.get(j).getLocationName());
        jsonfriends.add(temps.get(j).getTimestamp());
        jsonfriends.add(temps.get(j).getMethod());
      }

      location.put("location", locsWithCheckIns.get(i).name);
      location.put("friends", jsonfriends);

      locations.add(location);
    }

    recentFriends.put("recentFriends", locations);

    return recentFriends;
  }
コード例 #2
0
ファイル: Order.java プロジェクト: harsha846/JAVA2Assignment1
  public String toJSON() {
    JSONObject root = new JSONObject();

    JSONArray purchasesArray = new JSONArray();
    for (Map.Entry<Integer, Integer> entry : this.productId_quantity.entrySet()) {
      JSONObject purchases = new JSONObject();
      purchases.put("productId", entry.getKey());
      purchases.put("quantity", entry.getValue());
      purchasesArray.add(purchases);
    }

    HashMap classObj = new LinkedHashMap();
    classObj.put("customerId", this.getCustomerId());
    classObj.put("customerName", this.getCustomerName());
    classObj.put("timeReceived", this.getTimeReceived());
    classObj.put("timeProcessed", this.getTimeProcessed());
    classObj.put("timeFulfilled", this.getTimeFullFilled());
    classObj.put("purchases", purchasesArray);
    classObj.put("notes", this.getNotes());

    JSONArray orders = new JSONArray();
    orders.add(classObj);

    root.put("", orders);
    return orders.toJSONString();
  }
コード例 #3
0
  // Takes in a list of usernames and a list of locations and outputs a JSON object with the 5 most
  // recent locations for each friend
  @SuppressWarnings("unchecked")
  static JSONObject getReturnRecentLocsJSON(ArrayList<UserWithCheckIns> usersWithCheckIns) {
    JSONObject friendsLocations = new JSONObject();
    JSONArray jsonfriends = new JSONArray();

    for (int i = 0; i < usersWithCheckIns.size(); i++) {
      JSONArray locations = new JSONArray();
      JSONObject friend = new JSONObject();

      ArrayList<CheckIn> locs = new ArrayList<CheckIn>(usersWithCheckIns.get(i).checkIns);

      for (int j = 0; j < locs.size(); j++) {
        // locations.add(locs.get(j));
        locations.add(locs.get(j).getUserName());
        locations.add(locs.get(j).getLocationName());
        locations.add(locs.get(j).getTimestamp());
        locations.add(locs.get(j).getMethod());
      }

      friend.put("username", usersWithCheckIns.get(i).username);
      friend.put("locations", locations);

      jsonfriends.add(friend);
    }

    friendsLocations.put("recentLocs", jsonfriends);

    return friendsLocations;
  }
コード例 #4
0
  @SuppressWarnings("unchecked")
  private void makeExampleBook(File booksfolder) {

    JSONObject book = new JSONObject();

    book.put("name", "Example Book");
    book.put("author", "McBadgerCraft");

    JSONArray pages = new JSONArray();
    pages.add("This is an example book");
    pages.add("Using bInfoBooks created by");
    pages.add("TheCodingBadgers");
    book.put("pages", pages);

    JSONArray taglines = new JSONArray();
    taglines.add("bInfoBooks");
    taglines.add("By TheCodingBadgers");
    book.put("taglines", taglines);

    String contents = book.toJSONString();
    try {
      BufferedWriter out =
          new BufferedWriter(
              new FileWriter(booksfolder.getAbsolutePath() + File.separator + "examplebook.json"));
      out.write(contents);
      out.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
コード例 #5
0
ファイル: JSONobject.java プロジェクト: thomasburguiere/Bloom
  public File createJSONfile() throws IOException {
    globalJsonObject = new JSONObject();
    JSONArray globalArrayJSON = new JSONArray();

    JSONObject objectPresentTags = new JSONObject();
    objectPresentTags.put("presentTags", this.getPresentTags());

    JSONObject objectDwCTags = new JSONObject();
    objectDwCTags.put("DwCTags", this.getDwcTags());

    JSONObject objectNoMappedTags = new JSONObject();
    objectNoMappedTags.put("noMappedTags", this.getNoMappedTags());

    globalArrayJSON.add(objectPresentTags);
    globalArrayJSON.add(objectDwCTags);
    globalArrayJSON.add(objectNoMappedTags);

    globalJsonObject.put(this.getUploadFilename(), globalArrayJSON);

    File jsonFile =
        new File(
            BloomConfig.getDirectoryPath() + "temp/data/" + this.getUploadFilename() + ".json");
    if (!jsonFile.exists()) {
      jsonFile.createNewFile();
    }
    FileWriter writer = new FileWriter(jsonFile);
    writer.write(globalJsonObject.toJSONString());
    writer.close();

    return jsonFile;
  }
コード例 #6
0
  public static JSONObject toJson(PsSite site, String detailLevel) {
    JSONObject json = new JSONObject();
    if (site != null) {
      json.put(PsSite.ID, int2String(site.getId()));
      json.put(PsSite.NAME, site.getName());

      if (!PsApi.DETAIL_LEVEL_LOW.equals(detailLevel)) {

        json.put(PsSite.DESCRIPTION, site.getDescription());
        json.put(PsSite.STATUS, site.getStatus());

        JSONArray listOfHosts = new JSONArray();
        Collection<PsHost> listOfHostsInSite = site.getHosts();
        Iterator<PsHost> iter = listOfHostsInSite.iterator();
        while (iter.hasNext()) {
          PsHost currentHost = (PsHost) iter.next();
          if (PsApi.DETAIL_LEVEL_MEDIUM.equals(detailLevel)) {
            JSONObject currentHostJson = toJson(currentHost, PsApi.DETAIL_LEVEL_LOW);
            listOfHosts.add(currentHostJson);
          }
          if (PsApi.DETAIL_LEVEL_HIGH.equals(detailLevel)) {
            JSONObject currentHostJson = toJson(currentHost, PsApi.DETAIL_LEVEL_HIGH);
            listOfHosts.add(currentHostJson);
          }
        }
        json.put(PsSite.HOSTS, listOfHosts);
      }
    }
    return json;
  }
コード例 #7
0
  /**
   * static method to convert host to JsonObject
   *
   * @param host
   * @return
   */
  public static JSONObject psHost2Json(PsHost host, String detailLevel) {
    JSONObject json = new JSONObject();

    json.put(PsHost.ID, int2String(host.getId()));
    json.put(PsHost.HOSTNAME, host.getHostname());

    if (!PsApi.DETAIL_LEVEL_LOW.equals(detailLevel)) {

      json.put(PsHost.IPV4, host.getIpv4());
      json.put(PsHost.IPV6, host.getIpv6());

      JSONArray services = new JSONArray();
      Iterator<PsService> iter = host.serviceIterator();
      while (iter.hasNext()) {

        PsService service = (PsService) iter.next();
        if (PsApi.DETAIL_LEVEL_MEDIUM.equals(detailLevel)) {
          JSONObject serviceObject = toJson(service, PsApi.DETAIL_LEVEL_LOW);
          services.add(serviceObject);
        }
        if (PsApi.DETAIL_LEVEL_HIGH.equals(detailLevel)) {
          JSONObject serviceObject = toJson(service, PsApi.DETAIL_LEVEL_HIGH);
          services.add(serviceObject);
        }
      }
      json.put(PsHost.SERVICES, services);
    }

    return json;
  }
コード例 #8
0
ファイル: Methods.java プロジェクト: Agronis/Countries
 public static String writer(String firstLetter, String name, String initials) throws IOException {
   JSONArray list = new JSONArray();
   list.add(firstLetter);
   list.add(name);
   list.add(new String(initials));
   StringWriter out = new StringWriter();
   list.writeJSONString(out);
   String jsonText = out.toString();
   return jsonText;
 }
コード例 #9
0
  @SuppressWarnings("unchecked")
  public String createResult(
      String name,
      int status,
      String output,
      String handlers,
      long timestamp,
      String client,
      String subscribers) {
    JSONObject check = new JSONObject();
    check.put("name", name.trim());
    check.put("type", "standard");
    check.put("command", "none");
    check.put("standalone", true);
    check.put("status", new Integer(status));
    check.put("output", output.trim());
    check.put("issued", timestamp);
    check.put("executed", timestamp);

    if (handlers.contains(",")) {
      String[] handlersArray = handlers.split(",");
      JSONArray jsonArray = new JSONArray();
      for (String handler : handlersArray) {
        jsonArray.add(handler.trim());
      }
      check.put("handlers", jsonArray);
    } else {
      check.put("handler", handlers);
    }

    JSONArray jsonArray = new JSONArray();
    if (subscribers.contains(",")) {
      String[] subscribersArray = subscribers.split(",");
      for (String subscriber : subscribersArray) {
        jsonArray.add(subscriber.trim());
      }
    } else if (!"".equals(subscribers)) {
      jsonArray.add(subscribers.trim());
    }

    if (jsonArray.size() > 0) {
      check.put("subscribers", jsonArray);
    }

    check.put("publish", false);

    JSONObject result = new JSONObject();
    result.put("client", client.trim());

    result.put("check", check);

    return result.toJSONString();
  }
コード例 #10
0
 public JSONObject toJSON() {
   JSONObject jo = new JSONObject();
   JSONArray inisArr = new JSONArray();
   for (int i = 0; i < this.inis.size(); i++) {
     inisArr.add(this.inis.get(i).toJSON());
   }
   JSONArray tagsArray = new JSONArray();
   for (int i = 0; i < this.tags.size(); i++) {
     tagsArray.add(this.tags.get(i));
   }
   jo.put("inis", inisArr);
   jo.put("tags", tagsArray);
   return jo;
 }
コード例 #11
0
  /** Method to export data like rooms, capacity and meetings array in json format into a file */
  protected static String exportData(ArrayList<Room> roomList) {

    JSONObject json = new JSONObject();

    for (Room room : roomList) {
      json.put("RoomName", room.getName());
      json.put("Capacity", room.getCapacity());
      JSONArray meetings = new JSONArray();

      for (Meeting m : room.getMeetings()) {
        meetings.add(m.toString());
      }
      json.put("Meetings", meetings);

      // write data to a file
      File fileName = new File("src/File/result.json");
      try (PrintWriter file = new PrintWriter(new BufferedWriter(new FileWriter(fileName, true)))) {
        file.write(json.toJSONString());
        file.write("\n");
        file.flush();
        file.close();
      } catch (IOException e) {
        logger.error("Exception in export method:", e);
      }
      logger.info("Data exported successfully");
    }
    return "";
  }
コード例 #12
0
ファイル: FileSystem.java プロジェクト: maligulzar/projects
  @SuppressWarnings({"unchecked"})
  void initializeFS() {
    try {
      JSONObject obj = new JSONObject();
      JSONArray jar = new JSONArray();
      jar.add("0 1#1");
      obj.put("version", jar);
      obj.put("lastblock", "1");
      version = 0;
      file.write(obj.toJSONString().getBytes());

      superBlock = new SuperBlock(obj.toJSONString().getBytes());
      // Done super block
      lastblock = 1;
      file.seek(1024);
      // root direc
      JSONObject obj1 = new JSONObject();
      JSONArray ch_dir = new JSONArray();
      obj1.put("dir", ch_dir);
      file.write(obj1.toJSONString().getBytes());
      file.close();

      getFile();
      superBlock.loadDMap(version, file);

    } catch (IOException | ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #13
0
ファイル: GuestDAO.java プロジェクト: kaiquan/CZ2002-MOBLIMA
  /**
   * *@purpose : To create a new guest *@param : Guest guestobject, Strig cineplexname *@return :
   * void
   */
  @SuppressWarnings("unchecked")
  public void createNewGuest(Guest guest, String cineplexName) {
    JSONArray jsonGuests = (JSONArray) jsonObject.get("guests");
    boolean exists = false;
    for (int i = 0; i < this.guests.size(); i++) {
      if (this.guests.get(i).getEmail().equalsIgnoreCase(guest.getEmail())
          && this.guests.get(i).getMobileNo() == guest.getMobileNo()
          && this.guests.get(i).getCineplexName().equals(cineplexName)) {
        // System.out.println("Account already exists");
        exists = true;
        break;
      }
    }
    if (!exists) {
      JSONObject jsonGuest = new JSONObject();
      jsonGuest.put("id", guest.getId().toLowerCase());
      jsonGuest.put("name", guest.getName());
      jsonGuest.put("mobileno", guest.getMobileNo());
      jsonGuest.put("email", guest.getEmail().toLowerCase());
      jsonGuest.put("cineplexname", cineplexName);

      jsonGuests.add(jsonGuest);
    }
    updateFile(JSONDAO.guestPath, this.jsonObject);
  }
コード例 #14
0
 public static JSONArray depositsToJSON() {
   JSONArray depositsJSONlist = new JSONArray();
   for (String key : deposits.keySet()) {
     depositsJSONlist.add(deposits.get(key).toJSON());
   }
   return depositsJSONlist;
 }
コード例 #15
0
ファイル: PopOff.java プロジェクト: BurstProject/burstcoin
  @Override
  JSONStreamAware processRequest(HttpServletRequest req) {

    JSONObject response = new JSONObject();
    int numBlocks = 0;
    try {
      numBlocks = Integer.parseInt(req.getParameter("numBlocks"));
    } catch (NumberFormatException e) {
    }
    int height = 0;
    try {
      height = Integer.parseInt(req.getParameter("height"));
    } catch (NumberFormatException e) {
    }

    List<? extends Block> blocks;
    JSONArray blocksJSON = new JSONArray();
    if (numBlocks > 0) {
      blocks = Nxt.getBlockchainProcessor().popOffTo(Nxt.getBlockchain().getHeight() - numBlocks);
    } else if (height > 0) {
      blocks = Nxt.getBlockchainProcessor().popOffTo(height);
    } else {
      response.put("error", "invalid numBlocks or height");
      return response;
    }
    for (Block block : blocks) {
      blocksJSON.add(JSONData.block(block, true));
    }
    response.put("blocks", blocksJSON);
    return response;
  }
コード例 #16
0
  public JSONArray ObtenerMateriales() {
    JSONArray Materiales = new JSONArray();
    JSONObject material = new JSONObject();

    try {
      this.cn = getConnection();
      this.st = this.cn.createStatement();
      String sql;
      sql = "SELECT * FROM material";
      this.rs = this.st.executeQuery(sql);

      while (this.rs.next()) {
        Material mat = new Material(rs.getString("codigo"), rs.getString("material"));
        material = mat.getJSONObject();
        System.out.printf(material.toString());
        Materiales.add(material);
      }

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

    return (Materiales);
  }
コード例 #17
0
ファイル: Hits.java プロジェクト: prachibhansali/PageRank
  private static void convertToInlinkMap(
      HashMap<String, Set<String>> outlinkmapping, HashMap<String, JSONArray> inlinkmapping)
      throws Exception, FileNotFoundException {
    Iterator<String> keys = outlinkmapping.keySet().iterator();
    System.out.println("outlink map count " + outlinkmapping.size());
    while (keys.hasNext()) {
      String key = (String) keys.next();
      Set<String> s = outlinkmapping.get(key);
      ArrayList<String> a = new ArrayList<String>(s);
      // System.out.println("Started for "+count++ + + outlinkmapping.size() +a.size());

      for (int i = 0; i < a.size(); i++) {
        String inlink = a.get(i);
        if (outlinkmapping.containsKey(inlink)) {
          Object inlinks =
              inlinkmapping.containsKey(inlink) ? inlinkmapping.get(inlink) : new JSONArray();
          ((JSONArray) inlinks).add(key);
          inlinkmapping.put(inlink, (JSONArray) inlinks);
        }
      }
      // System.out.println("Endded for "+count++  + "  " + outlinkmapping.size() +"  "+a.size());
    }
    System.out.println("inlink map count " + inlinkmapping.size());

    System.out.println("Done");
  }
コード例 #18
0
ファイル: GetAssets.java プロジェクト: fitcoin/fimk
  @Override
  JSONStreamAware processRequest(HttpServletRequest req) {

    String[] assets = req.getParameterValues("assets");
    boolean includeCounts = !"false".equalsIgnoreCase(req.getParameter("includeCounts"));

    JSONObject response = new JSONObject();
    JSONArray assetsJSONArray = new JSONArray();
    response.put("assets", assetsJSONArray);
    for (String assetIdString : assets) {
      if (assetIdString == null || assetIdString.equals("")) {
        continue;
      }
      try {
        Asset asset = Asset.getAsset(Convert.parseUnsignedLong(assetIdString));
        if (asset == null) {
          return UNKNOWN_ASSET;
        }
        assetsJSONArray.add(JSONData.asset(asset, includeCounts));
      } catch (RuntimeException e) {
        return INCORRECT_ASSET;
      }
    }
    return response;
  }
コード例 #19
0
 /** Liefert ein Update darüber, wer alles akutell im Raum ist.(an alle Chatmember) */
 public synchronized void updateMembers() {
   System.out.println("UPDATE getNAmes: " + this.names);
   ArrayList<String> names = this.names;
   Iterator it = names.iterator();
   JSONObject res = new JSONObject();
   Random r = new Random();
   int sequenceCounter = r.nextInt(2000);
   Long longseq = new Long(sequenceCounter);
   JSONArray params = new JSONArray();
   for (String n : names) {
     params.add(n);
   }
   res.put("sequence", longseq);
   res.put("statuscode", ServerGUI.STATUS_CREATED);
   res.put("response", "sendWho");
   res.put("params", params);
   for (Socket s : listWithoutName) {
     try {
       PrintWriter p = new PrintWriter(s.getOutputStream(), true);
       p.println(res);
     } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
   }
 }
コード例 #20
0
  @GET
  @Path("{id}")
  @Produces(MediaType.APPLICATION_JSON)
  public String getproduct(@PathParam("id") int id) throws SQLException {

    if (conn == null) {
      return "not connected";
    } else {
      String query = "Select * from products where product_id = ?";
      PreparedStatement pstmt = conn.prepareStatement(query);
      pstmt.setInt(1, id);
      ResultSet rs = pstmt.executeQuery();
      String result = "";
      JSONArray productArr = new JSONArray();
      while (rs.next()) {
        Map productMap = new LinkedHashMap();
        productMap.put("productID", rs.getInt("product_id"));
        productMap.put("name", rs.getString("name"));
        productMap.put("description", rs.getString("description"));
        productMap.put("quantity", rs.getInt("quantity"));
        productArr.add(productMap);
      }
      result = productArr.toString();

      return result;
    }
  }
コード例 #21
0
ファイル: GetAllExchanges.java プロジェクト: breasal/nxt
  @Override
  JSONStreamAware processRequest(HttpServletRequest req) throws NxtException {
    final int timestamp = ParameterParser.getTimestamp(req);
    int firstIndex = ParameterParser.getFirstIndex(req);
    int lastIndex = ParameterParser.getLastIndex(req);
    boolean includeCurrencyInfo =
        !"false".equalsIgnoreCase(req.getParameter("includeCurrencyInfo"));

    JSONObject response = new JSONObject();
    JSONArray exchanges = new JSONArray();
    try (FilteringIterator<Exchange> exchangeIterator =
        new FilteringIterator<>(
            Exchange.getAllExchanges(0, -1),
            new Filter<Exchange>() {
              @Override
              public boolean ok(Exchange exchange) {
                return exchange.getTimestamp() >= timestamp;
              }
            },
            firstIndex,
            lastIndex)) {
      while (exchangeIterator.hasNext()) {
        exchanges.add(JSONData.exchange(exchangeIterator.next(), includeCurrencyInfo));
      }
    }
    response.put("exchanges", exchanges);
    return response;
  }
コード例 #22
0
ファイル: ChartJSON.java プロジェクト: deuxksy/deuxksy
  /**
   * @deprecated DB직접 접근해서 JSON 으로 출력해서 그래프 그리기 위한 경우 쓸모가 아리까리해서 안씀... 나중에 쓸일있을수도 있을까 해서 남겨둠
   * @param request
   * @param response
   * @return
   * @throws ServletRequestBindingException
   */
  @SuppressWarnings({"unused", "unchecked"})
  private JSONArray doChartStd(HttpServletRequest request, HttpServletResponse response)
      throws ServletRequestBindingException {
    String miliseconds = request.getParameter("miliseconds");
    String count = request.getParameter("count");
    String flag = request.getParameter("flag");

    BtaDealCtrl dealMgr = new BtaDealCtrl();
    BtaPriceCtrl priceMgr = new BtaPriceCtrl();

    JSONArray json = new JSONArray();
    BtaDeals btaDeals = dealMgr.getBtaDealsBySelling(TYPE.PRICE);
    Iterator<BtaDeal> deals = btaDeals.iterator();

    while (deals.hasNext()) {
      BtaDeal deal = deals.next();
      LOG.debug(
          deal.getKey() + ":" + deal.getTitle() + ":" + miliseconds + ":" + count + ":" + flag);
      BtaPrices prices =
          priceMgr.getBtaPrices(
              deal.getKey(),
              miliseconds,
              BooleanUtils.toBoolean(flag),
              NumberUtils.toInt(count, BTA.DEFAULT_JSON_COUNT));
      json.add(JSONParser.getLineChartJSON(deal, prices));
    }
    return json;
  }
コード例 #23
0
ファイル: Game.java プロジェクト: nargatte/RododendronServer
 private JSONArray getFirstCards() {
   JSONArray arr = new JSONArray();
   for (int x = 0; x < 6; x++) {
     arr.add(firstCards.get(x).toString());
   }
   return arr;
 }
コード例 #24
0
  @RequestMapping(value = "/getComboxs")
  @ResponseBody
  @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
  public JSONArray getFuncMenuTops(@RequestParam("codetablename") String codetablename) {
    //		System.out.println("-----------" + voName);
    //		System.out.println("-----------" + code);
    //		System.out.println("-----------" + name);

    List<OptionObject> cacheList = CacheService.getCachelist(codetablename);
    // System.out.println("=================" + cache.get(voName));
    // System.out.println("=================" +
    // cache.get(voName).getObjectValue());

    JSONArray arrays = new JSONArray();
    if (cacheList != null && cacheList.size() > 0) {
      for (int i = 0; i < cacheList.size(); i++) {
        OptionObject optionObject = cacheList.get(i);
        ComboBox bo = new ComboBox();
        bo.setKey(optionObject.getKey());
        bo.setValue(optionObject.getValue());
        bo.setKeyvalue(optionObject.getKeyvalue());
        arrays.add(bo);
      }
    }
    // String jsonString = JSONValue.toJSONString(l1);
    // System.out.println("-----------" + arrays);
    return arrays;
  }
コード例 #25
0
  public JSONObject filterPlacesRandomly(
      JSONObject placesJSONObject, int finalPlacesNumberPerRequest, List<String> place_ids) {
    JSONObject initialJSON = (JSONObject) placesJSONObject.clone();
    JSONObject finalJSONObject = new JSONObject();
    int numberFields = placesJSONObject.size();
    int remainingPlaces = finalPlacesNumberPerRequest;
    int keywordsProcessed = 0;

    Set<String> keywords = initialJSON.keySet();

    for (String keyword : keywords) {
      JSONArray placesForKeyword = (JSONArray) initialJSON.get(keyword);
      JSONArray finalPlacesForKeyword = new JSONArray();
      int placesForKeywordSize = placesForKeyword.size();

      int maxPlacesToKeepInFinalJSON = remainingPlaces / (numberFields - keywordsProcessed);
      int placesToKeepInFinalJSON = Math.min(maxPlacesToKeepInFinalJSON, placesForKeywordSize);
      remainingPlaces -= placesToKeepInFinalJSON;

      for (int i = 0; i < placesToKeepInFinalJSON; i++) {
        int remainingPlacesInJSONArray = placesForKeyword.size();
        int randomElementPosInArray = (new Random()).nextInt(remainingPlacesInJSONArray);
        JSONObject temp = (JSONObject) placesForKeyword.remove(randomElementPosInArray);
        place_ids.add((String) temp.get("place_id"));
        finalPlacesForKeyword.add(temp);
      }

      finalJSONObject.put(keyword, finalPlacesForKeyword);
      keywordsProcessed++;
    }

    return finalJSONObject;
  }
コード例 #26
0
  public String getUserEmails(String label) throws IOException {

    Gmail service =
        new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName("Gmail Quickstart")
            .build();
    JSONObject ticketDetails = new JSONObject();
    ListMessagesResponse labelMessages =
        service
            .users()
            .messages()
            .list("me") // .setLabelIds(labelIds)
            .setQ("label:inbox label:" + label)
            .setMaxResults(new Long(3))
            .execute();
    List<Message> messages = labelMessages.getMessages();
    JSONArray labelTickets = new JSONArray();
    String returnVal = "";
    if (messages != null) {
      for (Message message : messages) {
        labelTickets.add(new JSONObject(getBareGmailMessageDetails(message.getId())));
      }
      ticketDetails.put("labelTicketDetails", labelTickets);
    }
    return ticketDetails.toJSONString();
  }
コード例 #27
0
ファイル: Block.java プロジェクト: foxesden/Qora
  @SuppressWarnings("unchecked")
  public JSONObject toJson() {
    JSONObject block = new JSONObject();

    block.put("version", this.version);
    block.put("reference", Base58.encode(this.reference));
    block.put("timestamp", this.timestamp);
    block.put("generatingBalance", this.generatingBalance);
    block.put("generator", this.generator.getAddress());
    block.put("fee", this.getTotalFee().toPlainString());
    block.put("transactionsSignature", Base58.encode(this.transactionsSignature));
    block.put("generatorSignature", Base58.encode(this.generatorSignature));
    block.put("signature", Base58.encode(this.getSignature()));
    block.put("height", this.getHeight());

    // CREATE TRANSACTIONS
    JSONArray transactionsArray = new JSONArray();

    for (Transaction transaction : this.getTransactions()) {
      transactionsArray.add(transaction.toJson());
    }

    // ADD TRANSACTIONS TO BLOCK
    block.put("transactions", transactionsArray);

    // ADD AT BYTES
    if (atBytes != null) {
      block.put("blockATs", Converter.toHex(atBytes));
      block.put("atFees", this.atFees);
    }

    // RETURN
    return block;
  }
コード例 #28
0
  @Override
  JSONStreamAware processRequest(HttpServletRequest req) {

    String accountIdString = Convert.emptyToNull(req.getParameter("account"));
    Long accountId = null;

    if (accountIdString != null) {
      try {
        accountId = Convert.parseUnsignedLong(accountIdString);
      } catch (RuntimeException e) {
        return INCORRECT_ACCOUNT;
      }
    }

    JSONArray transactionIds = new JSONArray();
    for (Transaction transaction : Nxt.getTransactionProcessor().getAllUnconfirmedTransactions()) {
      if (accountId != null
          && !(accountId.equals(transaction.getSenderId())
              || accountId.equals(transaction.getRecipientId()))) {
        continue;
      }
      transactionIds.add(transaction.getStringId());
    }

    JSONObject response = new JSONObject();
    response.put("unconfirmedTransactionIds", transactionIds);
    return response;
  }
コード例 #29
0
  @Override
  JSONStreamAware processRequest(HttpServletRequest req) throws NxtException {

    long accountId = ParameterParser.getAccount(req).getId();
    long assetId = 0;
    try {
      assetId = Convert.parseUnsignedLong(req.getParameter("asset"));
    } catch (RuntimeException e) {
      // ignore
    }
    int firstIndex = ParameterParser.getFirstIndex(req);
    int lastIndex = ParameterParser.getLastIndex(req);

    DbIterator<Order.Ask> askOrders;
    if (assetId == 0) {
      askOrders = Order.Ask.getAskOrdersByAccount(accountId, firstIndex, lastIndex);
    } else {
      askOrders = Order.Ask.getAskOrdersByAccountAsset(accountId, assetId, firstIndex, lastIndex);
    }
    JSONArray orderIds = new JSONArray();
    try {
      while (askOrders.hasNext()) {
        orderIds.add(Convert.toUnsignedLong(askOrders.next().getId()));
      }
    } finally {
      askOrders.close();
    }
    JSONObject response = new JSONObject();
    response.put("askOrderIds", orderIds);
    return response;
  }
 public void acceptRepresentation(final Representation entity) throws ResourceException {
   final Form form = getRequest().getEntityAsForm();
   final String serviceUrl = form.getFirstValue("serviceTicketUrl");
   try {
     final Assertion authentication =
         this.centralAuthenticationService.validateServiceTicket(
             serviceTicketId, new SimpleWebApplicationServiceImpl(serviceUrl, this.httpClient));
     if (authentication.getChainedAuthentications().size() > 0) {
       // Iterate through each of the ChainedAuthentications and put them into the JSonArray
       JSONArray jsonResult = new JSONArray();
       for (Authentication auth : authentication.getChainedAuthentications()) {
         // Create the principle
         JSONObject principle = createJSONPrinciple(auth);
         JSONObject jsonAuth = new JSONObject();
         jsonAuth.put("authenticated_date", auth.getAuthenticatedDate());
         jsonAuth.put("attributes", principle);
         jsonResult.add(jsonAuth);
       }
       getResponse().setEntity(jsonResult.toJSONString(), MediaType.TEXT_PLAIN);
     } else {
       getResponse()
           .setEntity(
               java.lang.String.format("\"{\"authenticated\":\"false\"}\""), MediaType.TEXT_PLAIN);
     }
   } catch (final TicketException e) {
     log.error(e.getMessage(), e);
     getResponse()
         .setStatus(Status.CLIENT_ERROR_NOT_FOUND, "TicketGrantingTicket could not be found.");
   } catch (final Exception e) {
     log.error(e.getMessage(), e);
     getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage());
   }
 }