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());
   }
 }
Ejemplo n.º 2
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;
  }
  /** UserDataに完全一致検索クエリのキーを真偽値falseで指定して対象のデータのみ取得できること. */
  @Test
  public final void UserDataに完全一致検索クエリのキーを真偽値falseで指定して対象のデータのみ取得できること() {
    String entityTypeName = "boolFilterTest";
    try {
      // Boolean検索のテスト用データを作成する
      createTestData(entityTypeName);

      // 取得対象のデータに対する検索を実施する
      // ユーザデータの一覧取得
      String searchRequestUrl =
          UrlUtils.userData(cellName, boxName, colName, entityTypeName)
              + "?$filter=bool+eq+false&$inlinecount=allpages";
      DcRequest req = DcRequest.get(searchRequestUrl);
      req.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
      req.header(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
      DcResponse searchResponse = request(req);
      assertEquals(HttpStatus.SC_OK, searchResponse.getStatusCode());
      JSONObject responseBody = searchResponse.bodyAsJson();

      // ヒットしたデータが1件であることを確認する
      String count = (String) ((JSONObject) responseBody.get("d")).get("__count");
      assertEquals("1", count);

      // 期待したデータが取得できたことを確認する
      JSONArray results = (JSONArray) ((JSONObject) responseBody.get("d")).get("results");
      assertEquals("boolFalse", (String) ((JSONObject) results.get(0)).get("__id"));
      assertEquals(false, (Boolean) ((JSONObject) results.get(0)).get("bool"));
    } finally {
      deleteTestData(entityTypeName);
    }
  }
Ejemplo n.º 4
0
  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;
  }
Ejemplo n.º 5
0
  @RequestMapping(value = "/home")
  public String home(ModelMap modelMap) {
    HttpServletRequest request =
        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    System.out.println("HomeController: passing through...");
    System.out.println("获取相关renren参数");
    String sessionKey = request.getParameter("xn_sig_session_key");
    String renrenUserId = request.getParameter("xn_sig_user");
    System.out.println("Session Key: " + sessionKey);
    System.out.println("renrenUserId: " + renrenUserId);
    if (sessionKey != null && renrenUserId != null) {
      RenrenApiClient apiClient = new RenrenApiClient(sessionKey);
      SessionKey sessionKeyReal = new SessionKey(sessionKey);
      // 获取用户信息
      JSONArray userInfo = apiClient.getUserService().getInfo(renrenUserId, sessionKeyReal);
      if (userInfo != null && userInfo.size() > 0) {
        JSONObject currentUser = (JSONObject) userInfo.get(0);
        if (currentUser != null) {
          String userName = (String) currentUser.get("name");
          String userHead = (String) currentUser.get("headurl");
          request.setAttribute("userName", userName);
          request.setAttribute("userHead", userHead);
        }
      }
      JSONArray friends = apiClient.getFriendsService().getFriends(2, 80, sessionKeyReal);
      String friendsStr = friends.toJSONString().replace("\"", "\'");
      request.setAttribute("friends", friendsStr);
    }

    // 测试commit

    modelMap.addAttribute("welcome", "Walter's APP");
    return "home";
  }
Ejemplo n.º 6
0
  @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;
  }
Ejemplo n.º 7
0
  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;
  }
Ejemplo n.º 8
0
  @Override
  public void loadPage(Map<String, List<String>> parameterHolder) throws KettlePageException {
    try {
      JSONArray fields = XMLHandler.getPageRows(parameterHolder, fid("fields"));
      int nrfields = fields.size();

      allocate(nrfields);

      for (int i = 0; i < nrfields; i++) {
        JSONObject field = (JSONObject) fields.get(i);

        fieldName[i] = (String) field.get("fieldName");
        fieldType[i] = (String) field.get("fieldType");
        fieldFormat[i] = (String) field.get("fieldFormat");
        currency[i] = (String) field.get("currency");
        decimal[i] = (String) field.get("decimal");
        group[i] = (String) field.get("group");
        value[i] = (String) field.get("value");

        fieldLength[i] = Const.toInt(String.valueOf(field.get("fieldLength")), -1);
        fieldPrecision[i] = Const.toInt(String.valueOf(field.get("fieldPrecision")), -1);
        setEmptyString[i] = Const.toBoolean(String.valueOf(field.get("setEmptyString")), false);
      }

      rowLimit = XMLHandler.getPageValue(parameterHolder, fid("limit"));
    } catch (Exception e) {
      throw new KettlePageException(
          "Unexpected error reading step information from the repository", e);
    }
  }
Ejemplo n.º 9
0
  @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;
  }
Ejemplo n.º 10
0
  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();
    }
  }
Ejemplo n.º 11
0
  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;
  }
Ejemplo n.º 12
0
 @Override
 public void run() {
   try {
     try {
       Peer peer = Peers.getAnyPeer(Peer.State.CONNECTED, true);
       if (peer == null) {
         return;
       }
       JSONObject response = peer.send(getUnconfirmedTransactionsRequest);
       if (response == null) {
         return;
       }
       JSONArray transactionsData = (JSONArray) response.get("unconfirmedTransactions");
       if (transactionsData == null || transactionsData.size() == 0) {
         return;
       }
       processPeerTransactions(transactionsData, false);
     } catch (Exception e) {
       Logger.logDebugMessage("Error processing unconfirmed transactions from peer", e);
     }
   } catch (Throwable t) {
     Logger.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString());
     t.printStackTrace();
     System.exit(1);
   }
 }
  public VineNotificationsResponse(JSONObject data, String baseURL) throws Exception {
    this.baseURL = baseURL;
    if (data != null) {
      nextPage = JSONUtil.getLong(data, "nextPage");
      previousPage = JSONUtil.getLong(data, "previousPage");
      size = JSONUtil.getLong(data, "size");
      anchor = JSONUtil.getLong(data, "anchor");
      count = JSONUtil.getLong(data, "count");

      JSONArray jsonNotifications = JSONUtil.getJSONArray(data, "records");
      notfications = new ArrayList<VineNotification>();
      if (jsonNotifications != null && jsonNotifications.size() > 0) {
        for (int i = 0; i < jsonNotifications.size(); i++) {
          try {
            JSONObject n = (JSONObject) jsonNotifications.get(i);
            if (n != null) {
              VineNotification notf = new VineNotification(n);
              notfications.add(notf);
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    }
  }
Ejemplo n.º 14
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;
  }
Ejemplo n.º 15
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;
  }
Ejemplo n.º 16
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;
  }
Ejemplo n.º 17
0
 @Test
 public void testGetMovie() {
   JSONArray json = client.getMovie(SIN_CITY_MOVIE_ID);
   assertNotNull(json);
   assertEquals(1, json.size());
   assertEquals("Sin City", ((JSONObject) json.get(0)).get("name"));
 }
  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) {
    }
  }
 public void addsuara(
     Integer urut,
     Integer suaraTPS,
     Integer suaraVerifikasiC1,
     Integer suaraKPU,
     JSONObject jsonObject) {
   for (int i = 0; i < this.kandidat.size(); i++) {
     if (this.kandidat.get(i).urut == urut) {
       if (i == 0) {
         this.kandidatPemenang = this.kandidat.get(i);
       }
       this.kandidat.get(i).suaraTPS += suaraTPS;
       this.kandidat.get(i).suaraVerifikasiC1 += suaraVerifikasiC1;
       this.kandidat.get(i).suaraKPU += suaraKPU;
       try {
         JSONArray data = (JSONArray) jsonObject.get(this.kandidat.get(i).kpu_id_peserta + "");
         this.kandidat.get(i).partaiPendukung = data.get(8).toString();
         this.kandidat.get(i).jenisDukungan = data.get(7).toString();
         this.kandidat.get(i).jeniskelamin1 = data.get(2).toString();
         this.kandidat.get(i).jeniskelamin2 = data.get(5).toString();
       } catch (Exception e) {
       }
       if (this.kandidat.get(i).suaraVerifikasiC1 > this.kandidatPemenang.suaraVerifikasiC1) {
         this.kandidatPemenang = this.kandidat.get(i);
       }
     }
   }
 }
  /*
   * [{"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) {
    }
  }
Ejemplo n.º 21
0
  @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();
    }
  }
Ejemplo n.º 22
0
  public Object sendSingleRequest(String category, String action, JSONObject parameters) {
    // If the connection is busy, sleep 1ms at a time until it isn't
    synchronized (this) {

      //		}(busy)
      //			try {
      //				Thread.sleep(1);
      //			} catch (InterruptedException e) {
      //				// TODO Auto-generated catch block
      //				e.printStackTrace();
      //			}
      //
      //		busy = true;
      this.addRequest(category, action, parameters);
      //		if (!(new String(category).equals("Chat") ||
      //				new String(action).equals("getLineChanges") ||
      //				new String(action).equals("getLineLocks"))){
      //			System.out.println(category.toString() + action.toString() + parameters.toString());
      //		}

      JSONArray fullResponse = (JSONArray) this.sendRequestBuffer();
      busy = false;

      Object out = null;
      if (fullResponse != null && fullResponse.size() > 0) {
        JSONObject singleResponse = (JSONObject) fullResponse.get(0);
        return (Object) singleResponse.get("result");
      }
    }
    return null;
  }
Ejemplo n.º 23
0
  @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();
  }
  /**
   * If the provided record doesn't have correct parent information, update appropriate bookkeeping
   * to improve the situation.
   *
   * @param bmk
   */
  private void handleParenting(BookmarkRecord bmk) {
    if (parentGuidToIDMap.containsKey(bmk.parentID)) {
      bmk.androidParentID = parentGuidToIDMap.get(bmk.parentID);

      // Might as well set a basic position from the downloaded children array.
      JSONArray children = parentToChildArray.get(bmk.parentID);
      if (children != null) {
        int index = children.indexOf(bmk.guid);
        if (index >= 0) {
          bmk.androidPosition = index;
        }
      }
    } else {
      bmk.androidParentID = parentGuidToIDMap.get("unfiled");
      ArrayList<String> children;
      if (missingParentToChildren.containsKey(bmk.parentID)) {
        children = missingParentToChildren.get(bmk.parentID);
      } else {
        children = new ArrayList<String>();
      }
      children.add(bmk.guid);
      needsReparenting++;
      missingParentToChildren.put(bmk.parentID, children);
    }
  }
Ejemplo n.º 25
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;
  }
Ejemplo n.º 26
0
 public static JSONArray depositsToJSON() {
   JSONArray depositsJSONlist = new JSONArray();
   for (String key : deposits.keySet()) {
     depositsJSONlist.add(deposits.get(key).toJSON());
   }
   return depositsJSONlist;
 }
Ejemplo n.º 27
0
  /**
   * @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;
  }
Ejemplo n.º 28
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;
  }
  @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;
  }
Ejemplo n.º 30
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()));
    }
  }