Java 类org.json.simple.JsonObject 实例源码

项目:Necessities    文件:JanetSlack.java   
private void openWebSocket(String url) {
    try {
        ws = new WebSocketFactory().createSocket(url).addListener(new WebSocketAdapter() {
            @Override
            public void onTextMessage(WebSocket websocket, String message) {
                JsonObject json = Jsoner.deserialize(message, new JsonObject());
                if (json.containsKey("type")) {
                    if (json.getString(Jsoner.mintJsonKey("type", null)).equals("message")) {
                        //TODO: Figure out if there is a way to get the user id of a bot instead of just using janet's
                        SlackUser info = json.containsKey("bot_id") ? getUserInfo("U2Y19AVNJ") : getUserInfo(json.getString(Jsoner.mintJsonKey("user", null)));
                        String text = json.getString(Jsoner.mintJsonKey("text", null));
                        while (text.contains("<") && text.contains(">"))
                            text = text.split("<@")[0] + '@' + getUserInfo(text.split("<@")[1].split(">:")[0]).getName() + ':' + text.split("<@")[1].split(">:")[1];
                        String channel = json.getString(Jsoner.mintJsonKey("channel", null));
                        if (channel.startsWith("D")) //Direct Message
                            sendSlackChat(info, text, true);
                        else if (channel.startsWith("C") || channel.startsWith("G")) //Channel or Group
                            sendSlackChat(info, text, false);
                    }
                }
            }
        }).connect();
    } catch (Exception ignored) {
    }
}
项目:alvisnlp    文件:GeniaJSONReader.java   
private void fillAnnotations(@SuppressWarnings("unused") Logger logger, Section sec, JSONObject json, Map<String,Element> eltMap) {
    JSONArray catanns = (JSONArray) json.get("catanns");
    if (catanns == null) {
        return;
    }
    Layer annotations = sec.ensureLayer(annotationsLayerName);
    for (Object o : catanns) {
        JSONObject ca = (JSONObject) o;
        String id = (String) ca.get("id");
        JSONObject span = (JSONObject) ca.get("span");
        int begin = (int) (long) span.get("begin");
        int end = (int) (long) span.get("end");
        String category = (String) ca.get("category");
        Layer layer = sec.ensureLayer(category);
        Annotation a = new Annotation(this, layer, begin, end);
        annotations.add(a);
        a.addFeature("id", id);
        a.addFeature("category", category);
        eltMap.put(id, a);
    }
}
项目:hono-weather-demo    文件:WeatherDataConsumer.java   
/**
 * handleWeatherMessage takes received telemetry message and processes it to be printed to command line.
 * @param msg Telemetry message received through hono server.
 */
private void handleWeatherMessage(final Message msg) {
    final Section body = msg.getBody();
    //Ensures that message is Data (type of AMQP messaging). Otherwise exits method.
    if (!(body instanceof Data))
        return;
    //Gets deviceID.
    final String deviceID = MessageHelper.getDeviceId(msg);
    //Creates JSON parser to read input telemetry weather data. Prints data to console output.
    JSONParser parser = new JSONParser();
    try {
        Object obj = parser.parse(((Data) msg.getBody()).getValue().toString());
        JSONObject payload = (JSONObject) obj;
        System.out.println(new StringBuilder("Device: ").append(deviceID).append("; Location: ").
                append(payload.get("location")).append("; Temperature:").append(payload.get("temperature")));
    } catch (ParseException e) {
        System.out.println("Data was not sent in a readable way. Check telemetry input.");
        e.printStackTrace();
    }
}
项目:BiglyBT    文件:BEncoder.java   
public static JSONObject
encodeToJSONObject(
    Map<Object,Object>      b_map )
{
    if ( b_map == null ){

        return( null );
    }

    JSONObject  j_map = new JSONObject();

    for ( Map.Entry<Object,Object> entry: b_map.entrySet()){

        Object  key = entry.getKey();
        Object  val = entry.getValue();

        j_map.put((String)key, encodeToJSONGeneric( val ));
    }

    return( j_map );
}
项目:talchain    文件:CallCreate.java   
public CallCreate(JSONObject callCreateJSON) {

        String data = callCreateJSON.get("data").toString();
        String destination = callCreateJSON.get("destination").toString();
        String gasLimit = callCreateJSON.get("gasLimit").toString();
        String value = callCreateJSON.get("value").toString();

        if (data != null && data.length() > 2)
            this.data = Hex.decode(data.substring(2));
        else
            this.data = ByteUtil.EMPTY_BYTE_ARRAY;

        this.destination = Hex.decode(destination);
        this.gasLimit = ByteUtil.bigIntegerToBytes(TestCase.toBigInt(gasLimit));
        this.value = ByteUtil.bigIntegerToBytes(TestCase.toBigInt(value));
    }
项目:personium-core    文件:UpdateTest.java   
/**
 * Cellの更新の$formatがjsonのテスト.
 */
@SuppressWarnings("unchecked")
@Test
public final void Cellの更新の$formatがjsonのテスト() {

    // Cellを更新
    // リクエストヘッダをセット
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
    headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    headers.put(HttpHeaders.IF_MATCH, "*");

    // リクエストボディを生成
    JSONObject requestBody = new JSONObject();
    requestBody.put("Name", cellName);
    res = updateCellQuery(headers, requestBody, QUERY_FORMAT_JSON);

    // Cell更新のレスポンスチェック
    // TODO $formatのチェックが実装されたら変更する必要がある
    assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode());
}
项目:JavaShell    文件:Metrics.java   
/**
 * Gets the plugin specific data.
 * This method is called using Reflection.
 *
 * @return The plugin specific data.
 */
public JSONObject getPluginData() {
    JSONObject data = new JSONObject();

    String pluginName = plugin.getDescription().getName();
    String pluginVersion = plugin.getDescription().getVersion();

    data.put("pluginName", pluginName); // Append the name of the plugin
    data.put("pluginVersion", pluginVersion); // Append the version of the plugin
    JSONArray customCharts = new JSONArray();
    for (CustomChart customChart : charts) {
        // Add the data of the custom charts
        JSONObject chart = customChart.getRequestJsonObject();
        if (chart == null) { // If the chart is null, we skip it
            continue;
        }
        customCharts.add(chart);
    }
    data.put("customCharts", customCharts);

    return data;
}
项目:Minecordbot    文件:Metrics.java   
/**
 * Gets the plugin specific data.
 * This method is called using Reflection.
 *
 * @return The plugin specific data.
 */
public JSONObject getPluginData() {
    JSONObject data = new JSONObject();

    String pluginName = plugin.getDescription().getName();
    String pluginVersion = plugin.getDescription().getVersion();

    data.put("pluginName", pluginName); // Append the name of the plugin
    data.put("pluginVersion", pluginVersion); // Append the version of the plugin
    JSONArray customCharts = new JSONArray();
    for (CustomChart customChart : charts) {
        // Add the data of the custom charts
        JSONObject chart = customChart.getRequestJsonObject();
        if (chart == null) { // If the chart is null, we skip it
            continue;
        }
        customCharts.add(chart);
    }
    data.put("customCharts", customCharts);

    return data;
}
项目:ArchersBattle    文件:Metrics.java   
/**
 * Gets the plugin specific data.
 * This method is called using Reflection.
 *
 * @return The plugin specific data.
 */
public JSONObject getPluginData() {
    JSONObject data = new JSONObject();

    String pluginName = plugin.getDescription().getName();
    String pluginVersion = plugin.getDescription().getVersion();

    data.put("pluginName", pluginName); // Append the name of the plugin
    data.put("pluginVersion", pluginVersion); // Append the version of the plugin
    JSONArray customCharts = new JSONArray();
    for (CustomChart customChart : charts) {
        // Add the data of the custom charts
        JSONObject chart = customChart.getRequestJsonObject();
        if (chart == null) { // If the chart is null, we skip it
            continue;
        }
        customCharts.add(chart);
    }
    data.put("customCharts", customCharts);

    return data;
}
项目:talchain    文件:Transaction.java   
public Transaction(JSONObject callCreateJSON) {

        String dataStr = callCreateJSON.get("data").toString();
        String gasLimitStr = Utils.parseUnidentifiedBase(callCreateJSON.get("gasLimit").toString());
        String gasPriceStr = Utils.parseUnidentifiedBase(callCreateJSON.get("gasPrice").toString());
        String nonceStr = callCreateJSON.get("nonce").toString();
        String secretKeyStr = callCreateJSON.get("secretKey").toString();
        String toStr = callCreateJSON.get("to").toString();
        String valueStr = callCreateJSON.get("value").toString();

        this.data = Utils.parseData(dataStr);
        this.gasLimit = !gasLimitStr.isEmpty() ? new BigInteger(gasLimitStr).toByteArray() : new byte[]{0};
        this.gasPrice = Utils.parseLong(gasPriceStr);
        this.nonce = Utils.parseLong(nonceStr);
        this.secretKey = Utils.parseData(secretKeyStr);
        this.to = Utils.parseData(toStr);
        this.value = Utils.parseLong(valueStr);
    }
项目:personium-core    文件:LogTest.java   
/**
 * ログファイルに対するGETで200が返却されること.
 */
@SuppressWarnings("unchecked")
@Test
public final void ログファイルに対するGETで200が返却されること() {
    JSONObject body = new JSONObject();
    body.put("level", "INFO");
    body.put("action", "POST");
    body.put("object", "ObjectData");
    body.put("result", "resultData");

    CellUtils.event(MASTER_TOKEN_NAME, HttpStatus.SC_OK, Setup.TEST_CELL1, body.toJSONString());

    TResponse response = Http.request("cell/log-get.txt")
            .with("METHOD", HttpMethod.GET)
            .with("token", AbstractCase.MASTER_TOKEN_NAME)
            .with("cellPath", Setup.TEST_CELL1)
            .with("collection", CURRENT_COLLECTION)
            .with("fileName", DEFAULT_LOG)
            .with("ifNoneMatch", "*")
            .returns();
    response.debug();
    String responseBody = response.getBody();
    assertTrue(0 < responseBody.length());
    response.statusCode(HttpStatus.SC_OK);
}
项目:NeuralNetworkAPI    文件:Metrics.java   
/**
 * Gets the plugin specific data.
 * This method is called using Reflection.
 *
 * @return The plugin specific data.
 */
public JSONObject getPluginData() {
    JSONObject data = new JSONObject();

    String pluginName = plugin.getDescription().getName();
    String pluginVersion = plugin.getDescription().getVersion();

    data.put("pluginName", pluginName); // Append the name of the plugin
    data.put("pluginVersion", pluginVersion); // Append the version of the plugin
    JSONArray customCharts = new JSONArray();
    for (CustomChart customChart : charts) {
        // Add the data of the custom charts
        JSONObject chart = customChart.getRequestJsonObject();
        if (chart == null) { // If the chart is null, we skip it
            continue;
        }
        customCharts.add(chart);
    }
    data.put("customCharts", customCharts);

    return data;
}
项目:alfresco-remote-api    文件:PublicApiClient.java   
public Person getPerson(String personId, int expectedStatus) throws PublicApiException
{
    HttpResponse response = getSingle("people", personId, null, null, "Failed to get person", expectedStatus);

    if(logger.isDebugEnabled())
    {
        logger.debug(response);
    }
    System.out.println(response);

    if (response != null && response.getJsonResponse() != null)
    {
        JSONObject entry = (JSONObject) response.getJsonResponse().get("entry");
        if (entry != null)
        {
            return Person.parsePerson(entry);
        }
    }
    return null;
}
项目:ServerConnect    文件:Metrics.java   
@SuppressWarnings("unchecked")
@Override
      protected JSONObject getChartData() {
          JSONObject data = new JSONObject();
          JSONObject values = new JSONObject();
          HashMap<String, Integer> map = getValues(new HashMap<String, Integer>());
          if (map == null || map.isEmpty()) {
              // Null = skip the chart
              return null;
          }
          boolean allSkipped = true;
          for (Map.Entry<String, Integer> entry : map.entrySet()) {
              if (entry.getValue() == 0) {
                  continue; // Skip this invalid
              }
              allSkipped = false;
              values.put(entry.getKey(), entry.getValue());
          }
          if (allSkipped) {
              // Null = skip the chart
              return null;
          }
          data.put("values", values);
          return data;
      }
项目:Locked    文件:MerchantManager.java   
public static ArrayList<String> getAllNPCs() {
    ArrayList<String> a = new ArrayList<>();
    try {
        File file = plugin.getPath().getAbsoluteFile();
        JSONParser parser = new JSONParser();
        Object parsed = parser.parse(new FileReader(file.getPath()));
        JSONObject jsonObject = (JSONObject) parsed;
        JSONArray npcsArray = (JSONArray) jsonObject.get("npcs");
        for (Object npc : npcsArray) {
            a.add((String) ((JSONObject) npc).get("name"));

        }
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    }
    return a;
}
项目:personium-core    文件:UpdateTest.java   
/**
 * Cellの更新のNameが空のパターンのテスト.
 */
@SuppressWarnings("unchecked")
@Test
public final void Cellの更新のNameが空のパターンのテスト() {

    // Cellを更新
    // リクエストヘッダをセット
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
    headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    headers.put(HttpHeaders.IF_MATCH, "*");

    // リクエストボディを生成
    JSONObject requestBody = new JSONObject();
    requestBody.put("Name", "");

    res = updateCell(headers, requestBody);

    // Cell更新のレスポンスチェック
    assertEquals(HttpStatus.SC_BAD_REQUEST, res.getStatusCode());
    assertEquals(MediaType.APPLICATION_JSON, res.getResponseHeaders(HttpHeaders.CONTENT_TYPE)[0].getValue());
    this.checkErrorResponse(res.bodyAsJson(), "PR400-OD-0006");
}
项目:ServerConnect    文件:Metrics.java   
@SuppressWarnings("unchecked")
@Override
      protected JSONObject getChartData() {
          JSONObject data = new JSONObject();
          JSONObject values = new JSONObject();
          HashMap<String, Integer> map = getValues(new HashMap<String, Integer>());
          if (map == null || map.isEmpty()) {
              // Null = skip the chart
              return null;
          }
          for (Map.Entry<String, Integer> entry : map.entrySet()) {
              JSONArray categoryValues = new JSONArray();
              categoryValues.add(entry.getValue());
              values.put(entry.getKey(), categoryValues);
          }
          data.put("values", values);
          return data;
      }
项目:libtrails    文件:SkinDownloader.java   
public String getSkinUrl(GameProfile prof) throws ParseException {
    Collection<Property> ps = prof.getProperties().get("textures");

    if (ps == null || ps.isEmpty()) {
        return null;
    } else {
        Property p = Iterators.getLast(ps.iterator());

        JSONObject obj = (JSONObject) new JSONParser().parse(
                new String(Base64.getDecoder().decode(p.getValue())));

        obj = ((JSONObject) obj.get("textures"));
        obj = ((JSONObject) obj.get("SKIN"));
        return (String) obj.get("url");
    }
}
项目:JodelAPI    文件:JodelAccount.java   
/**
 * Refreshes the Access Token of the currently used account
 */
public void refreshAccessToken() {
    this.updateHTTPParameter();
    JodelHTTPResponse requestResponse = this.httpAction.getNewAccessToken();
    if (requestResponse.responseCode == 200) {
        String responseMessage = requestResponse.responseMessage;
        JSONParser parser = new JSONParser();
        try {
            JSONObject responseJson = (JSONObject) parser.parse(responseMessage);
            this.accessToken = responseJson.get("access_token").toString();
            this.expirationDate = responseJson.get("expiration_date").toString();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
项目:eXperDB-DB2PG    文件:MySqlConvertMapper.java   
@Override
protected void init() throws FileNotFoundException, IOException, ParseException {
    JSONParser jsonParser = new JSONParser();

    JSONObject convMapObj = (JSONObject)jsonParser.parse(new InputStreamReader(MySqlConvertMapper.class.getResourceAsStream("/convert_map.json")));

    convertPatternValues = new ArrayList<ConvertVO>(30);
    convertDefaultValues = new ArrayList<ConvertVO>(5);
    for(Object key : convMapObj.keySet().toArray()) {
        JSONObject jobj = (JSONObject)convMapObj.get(key);
        String toValue = (String)jobj.get("postgres");
        JSONArray asValues = (JSONArray) jobj.get("mysql");
        if(toValue != null && asValues != null) {
            for (Object asValue : asValues) {
                if(asValue instanceof String) {
                    ConvertVO convVal = new ConvertVO((String)asValue,toValue);
                    if(convVal.getPattern() != null) convertPatternValues.add(convVal);
                    else convertDefaultValues.add(convVal);
                }
            }
        }
    }
}
项目:burstcoin    文件:GetPollIds.java   
@Override
JSONStreamAware processRequest(HttpServletRequest req) {

    int firstIndex = ParameterParser.getFirstIndex(req);
    int lastIndex = ParameterParser.getLastIndex(req);

    JSONArray pollIds = new JSONArray();
    try (DbIterator<Poll> polls = Poll.getAllPolls(firstIndex, lastIndex)) {
        while (polls.hasNext()) {
            pollIds.add(Convert.toUnsignedLong(polls.next().getId()));
        }
    }
    JSONObject response = new JSONObject();
    response.put("pollIds", pollIds);
    return response;

}
项目:personium-core    文件:UserDataUtils.java   
/**
 * ユーザーODataの部分更新を実行し、レスポンスコードをチェックする.
 * @param token トークン
 * @param code 期待するレスポンスコード
 * @param body リクエストボディ
 * @param cell セル名
 * @param box ボックス名
 * @param collection コレクション名
 * @param entityType エンティティタイプ
 * @param id ユーザODataのUUID
 * @param ifMatch If-Matchヘッダー値
 * @return レスポンス
 */
public static TResponse merge(String token, int code, JSONObject body, String cell,
        String box, String collection, String entityType, String id, String ifMatch) {
    TResponse res = Http.request("box/odatacol/merge.txt")
            .with("cell", cell)
            .with("box", box)
            .with("collection", collection)
            .with("entityType", entityType)
            .with("id", id)
            .with("accept", MediaType.APPLICATION_JSON)
            .with("contentType", MediaType.APPLICATION_JSON)
            .with("token", token)
            .with("ifMatch", ifMatch)
            .with("body", body.toJSONString())
            .returns()
            .statusCode(code)
            .debug();
    return res;
}
项目:BiglyBT    文件:EngineImpl.java   
protected void
exportToJSONObject(
    JSONObject      res )

    throws IOException
{
    exportJSONMappings( res, "value_map", first_level_mapping, true );
    exportJSONMappings( res, "ctype_map", second_level_mapping, false );

    res.put( "version", new Long( version ));
    res.put( "az_version", new Long( az_version ));

    res.put( "uid", Base32.encode( uid ));

    if ( update_url != null ){

        res.put( "update_url", update_url );
    }

    res.put( "update_url_check_secs", new Long( update_check_default_secs ));
}
项目:alfresco-remote-api    文件:ProcessDefinitionParser.java   
@Override
public ProcessDefinition parseEntry(JSONObject entry)
{
    ProcessDefinition processDefinition = new ProcessDefinition();
    processDefinition.setId((String) entry.get("id"));
    processDefinition.setKey((String) entry.get("key"));
    processDefinition.setVersion(((Number) entry.get("version")).intValue());
    processDefinition.setName((String) entry.get("name"));
    processDefinition.setDeploymentId((String) entry.get("deploymentId"));
    processDefinition.setTitle((String) entry.get("title"));
    processDefinition.setDescription((String) entry.get("description"));
    processDefinition.setCategory((String) entry.get("category"));
    processDefinition.setStartFormResourceKey((String) entry.get("startFormResourceKey"));
    processDefinition.setGraphicNotationDefined((Boolean) entry.get("graphicNotationDefined"));
    return processDefinition;
}
项目:sonar-coverage-evolution    文件:DefaultSonarClient.java   
protected static <G extends Serializable> Optional<String> extractMeasure(JsonObject apiResult, Metric<G> metric) {
  JsonObject component = apiResult.getMap("component");
  if (component == null) {
    return Optional.empty();
  }
  JsonArray measures = component.getCollection("measures");
  if (measures == null) {
    return Optional.empty();
  }
  return measures.stream()
      .map(o -> (JsonObject) o)
      .filter(o ->
        metric.getKey().equals(o.getString("metric"))
      )
      .map(o ->
        o.getString("value")
      )
      .findFirst();

}
项目:shipkit    文件:CreatePullRequest.java   
public PullRequest createPullRequest(CreatePullRequestTask task, GitHubApi gitHubApi) throws IOException {
    if (task.isDryRun()) {
        LOG.lifecycle("  Skipping pull request creation due to dryRun = true");
        return null;
    }

    String headBranch = BranchUtils.getHeadBranch(task.getForkRepositoryName(), task.getVersionBranch());

    IncubatingWarning.warn("creating pull requests");
    LOG.lifecycle("  Creating a pull request of title '{}' in repository '{}' between base = '{}' and head = '{}'.",
        task.getPullRequestTitle(), task.getUpstreamRepositoryName(), task.getBaseBranch(), headBranch);

    String body = "{" +
        "  \"title\": \"" + task.getPullRequestTitle() + "\"," +
        "  \"body\": \"" + task.getPullRequestDescription() + "\"," +
        "  \"head\": \"" + headBranch + "\"," +
        "  \"base\": \"" + task.getBaseBranch() + "\"," +
        "  \"maintainer_can_modify\": true" +
        "}";

    String response = gitHubApi.post("/repos/" + task.getUpstreamRepositoryName() + "/pulls", body);
    JsonObject pullRequest = Jsoner.deserialize(response, new JsonObject());
    return toPullRequest(pullRequest);
}
项目:shipkit    文件:FindOpenPullRequest.java   
public PullRequest findOpenPullRequest(String upstreamRepositoryName, String versionBranchRegex, GitHubApi gitHubApi) throws IOException {
    String response = gitHubApi.get("/repos/" + upstreamRepositoryName + "/pulls?state=open");

    JsonArray pullRequests = Jsoner.deserialize(response, new JsonArray());

    for (Object pullRequest : pullRequests) {
        PullRequest openPullRequest = PullRequestUtils.toPullRequest((JsonObject) pullRequest);
        if (openPullRequest != null && openPullRequest.getRef().matches(versionBranchRegex)) {
            LOG.lifecycle("  Found an open pull request with version upgrade on branch {}", openPullRequest.getRef());
            return openPullRequest;
        }
    }

    LOG.lifecycle("  New pull request will be opened because we didn't find an existing PR to reuse.");

    return null;
}
项目:shipkit    文件:GitHubStatusCheck.java   
public PullRequestStatus checkStatusWithRetries() throws IOException, InterruptedException {
    int timeouts = 0;
    while (timeouts < amountOfRetries) {
        JsonObject status = getStatusCheck(task, gitHubApi);
        if (status.getCollection("statuses") == null || status.getCollection("statuses").size() == 0) {
            return PullRequestStatus.NO_CHECK_DEFINED;
        }

        if (allStatusesPassed(status)) {
            return PullRequestStatus.SUCCESS;
        } else {
            int waitTime = 10000 * timeouts;
            Thread.sleep(waitTime);
            timeouts++;
            LOG.lifecycle("Pull Request checks still in pending state. Waiting %d seconds...", waitTime / 1000);
        }
    }
    return PullRequestStatus.TIMEOUT;
}
项目:shipkit    文件:GitHubStatusCheck.java   
private boolean allStatusesPassed(JsonObject status) {
    if (status.getString("state").equals("success")) {
        return true;
    }

    if (hasErrorStates(status)) {
        Collection<JsonObject> statuses = status.getCollection("statuses");

        JsonObject firstError = findFirstError(statuses);
        if (firstError != null) {
            throw new RuntimeException(String.format(
                "Pull request %s cannot be merged. %s. You can check details here: %s",
                task.getPullRequestUrl(),
                firstError.getString("description"),
                firstError.getString("targetUrl")));
        }
    }
    return false;
}
项目:shipkit    文件:ProjectContributorsSerializer.java   
public ProjectContributorsSet deserialize(String json) {
    ProjectContributorsSet set = new DefaultProjectContributorsSet();
    try {
        LOG.debug("Deserialize project contributors from: {}", json);
        JsonArray array = (JsonArray) Jsoner.deserialize(json);
        for (Object object : array) {
            JsonObject jsonObject = (JsonObject) object;
            String name = jsonObject.getString("name");
            String login = jsonObject.getString("login");
            String profileUrl = jsonObject.getString("profileUrl");
            Integer numberOfContributions = jsonObject.getInteger("numberOfContributions");
            set.addContributor(new DefaultProjectContributor(name, login, profileUrl, numberOfContributions));
        }
    } catch (Exception e) {
        throw new RuntimeException("Can't deserialize JSON: " + json, e);
    }
    return set;
}
项目:shipkit    文件:GitHubContributorsFetcher.java   
ProjectContributorsSet fetchContributorsForProject(String apiUrl, String repository, String readOnlyAuthToken) {
    LOG.lifecycle("  Querying GitHub API for all contributors for project");
    ProjectContributorsSet result = new DefaultProjectContributorsSet(ignoredContributors);

    try {
        GitHubProjectContributors contributors =
                GitHubProjectContributors.authenticatingWith(apiUrl, repository, readOnlyAuthToken).build();

        while (contributors.hasNextPage()) {
            List<JsonObject> page = contributors.nextPage();
            result.addAllContributors(extractContributors(page, readOnlyAuthToken));
        }
    } catch (Exception e) {
        throw new RuntimeException("Problems fetching and parsing contributors from GitHub repo: '" + repository
                + "', using read only token: '" + readOnlyAuthToken + "'", e);
    }
    return result;
}
项目:shipkit    文件:RecentContributorsFetcher.java   
/**
 * Contributors that pushed commits to the repo within the time span.
 * @param dateSince - must not be null, the since date
 * @param dateUntil - can be null, it means there is no end date
 */
public Collection<Contributor> fetchContributors(String apiUrl, String repository, String readOnlyAuthToken, Date dateSince, Date dateUntil) {
    LOG.info("Querying GitHub API for commits (for contributors)");
    Set<Contributor> contributors = new LinkedHashSet<Contributor>();

    try {
        GitHubCommits commits = GitHubCommits
                .with(apiUrl, repository, readOnlyAuthToken, dateSince, dateUntil)
                .build();

        while (commits.hasNextPage()) {
            List<JsonObject> page = commits.nextPage();
            contributors.addAll(extractContributors(page));
        }
    } catch (Exception e) {
        throw new RuntimeException("Problems fetching commits from GitHub", e);
    }

    return contributors;
}
项目:shipkit    文件:ContributorsSerializer.java   
public ContributorsSet deserialize() {
    String json = "";
    ContributorsSet set = new DefaultContributorsSet();
    try {
        json = IOUtil.readFully(file);
        LOG.info("Deserialize contributors from: {}", json);
        JsonArray array = (JsonArray) Jsoner.deserialize(json);
        for (Object object : array) {
            JsonObject jsonObject = (JsonObject) object;
            String name = jsonObject.getString("name");
            String login = jsonObject.getString("login");
            String profileUrl = jsonObject.getString("profileUrl");
            set.addContributor(new DefaultContributor(name, login, profileUrl));
        }
    } catch (Exception e) {
        throw new RuntimeException("Can't deserialize JSON: " + json, e);
    }
    return set;
}
项目:shipkit    文件:GitHubListFetcher.java   
public List<JsonObject> nextPage() throws IOException, DeserializationException {
    if (RELATIVE_LINK_NOT_FOUND.equals(nextPageUrl)) {
        throw new IllegalStateException("GitHub API no more issues to fetch");
    }
    URL url = new URL(nextPageUrl);
    LOG.info("GitHub API querying page {}", queryParamValue(url, "page"));
    LOG.lifecycle("GET " + nextPageUrl);
    URLConnection urlConnection = url.openConnection();
    LOG.info("Established connection to GitHub API");

    String resetInLocalTime = resetLimitInLocalTimeOrEmpty(urlConnection);

    LOG.info("GitHub API rate info => Remaining : {}, Limit : {}, Reset at: {}",
            urlConnection.getHeaderField("X-RateLimit-Remaining"),
            urlConnection.getHeaderField("X-RateLimit-Limit"),
            resetInLocalTime);
    nextPageUrl = extractRelativeLink(urlConnection.getHeaderField("Link"), "next");

    return parseJsonFrom(urlConnection);
}
项目:shipkit    文件:GitHubTicketFetcher.java   
private static List<Improvement> extractImprovements(Collection<Long> tickets, List<JsonObject> issues,
                                                     boolean onlyPullRequests) {
    if (tickets.isEmpty()) {
        return Collections.emptyList();
    }

    ArrayList<Improvement> pagedImprovements = new ArrayList<Improvement>();
    for (JsonObject issue : issues) {
        Improvement i = GitHubImprovementsJSON.toImprovement(issue);
        if (tickets.remove(i.getId())) {
            if (!onlyPullRequests || i.isPullRequest()) {
                pagedImprovements.add(i);
            }

            if (tickets.isEmpty()) {
                return pagedImprovements;
            }
        }
    }
    return pagedImprovements;
}
项目:sonar-stash    文件:StashClient.java   
public void addPullRequestReviewer(PullRequestRef pr, long pullRequestVersion, List<StashUser> reviewers)
throws StashClientException {
  String request = MessageFormat.format(API_ONE_PR, baseUrl, pr.project(), pr.repository(), pr.pullRequestId());

  JsonObject json = new JsonObject();

  JsonArray jsonReviewers = new JsonArray();
  for (StashUser reviewer : reviewers) {
    JsonObject reviewerName = new JsonObject();
    reviewerName.put("name", reviewer.getName());

    JsonObject user = new JsonObject();
    user.put("user", reviewerName);

    jsonReviewers.add(user);
  }

  json.put("reviewers", jsonReviewers);
  json.put("id", pr.pullRequestId());
  json.put("version", pullRequestVersion);

  put(request, json, MessageFormat.format(PULL_REQUEST_PUT_ERROR_MESSAGE, pr.repository(), pr.pullRequestId()));
}
项目:sonar-stash    文件:StashClient.java   
private static JsonObject extractResponse(Response response) throws StashClientException {
  PeekableInputStream bodyStream = new PeekableInputStream(response.getResponseBodyAsStream());

  try {
    if (!bodyStream.peek().isPresent()) {
      return null;
    }
    String contentType = response.getHeader("Content-Type");
    if (!JSON.match(contentType.trim())) {
      throw new StashClientException("Received response with type " + contentType + " instead of JSON");
    }
    Reader body = new InputStreamReader(bodyStream);
    Object obj = Jsoner.deserialize(body);
    return (JsonObject)obj;
  } catch (DeserializationException | ClassCastException | IOException e) {
    throw new StashClientException("Could not parse JSON response: " + e, e);
  }
}
项目:sonar-stash    文件:StashCollector.java   
public static StashCommentReport extractComments(JsonObject jsonComments) throws StashReportExtractionException {
  StashCommentReport result = new StashCommentReport();

  JsonArray jsonValues = (JsonArray)jsonComments.get("values");
  if (jsonValues != null) {

    for (Object obj : jsonValues.toArray()) {
      JsonObject jsonComment = (JsonObject)obj;

      StashComment comment = extractComment(jsonComment);
      result.add(comment);
    }
  }

  return result;
}
项目:sonar-stash    文件:StashCollector.java   
public static StashPullRequest extractPullRequest(PullRequestRef pr,
                                                  JsonObject jsonPullRequest) {
  StashPullRequest result = new StashPullRequest(pr);

  long version = getLong(jsonPullRequest, VERSION);
  result.setVersion(version);

  JsonArray jsonReviewers = (JsonArray)jsonPullRequest.get("reviewers");
  if (jsonReviewers != null) {
    for (Object objReviewer : jsonReviewers.toArray()) {
      JsonObject jsonReviewer = (JsonObject)objReviewer;

      JsonObject jsonUser = (JsonObject)jsonReviewer.get("user");
      if (jsonUser != null) {
        StashUser reviewer = extractUser(jsonUser);
        result.addReviewer(reviewer);
      }
    }
  }

  return result;
}
项目:Necessities    文件:Necessities.java   
private Property getSkin() {
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(new URL("https://sessionserver.mojang.com/session/minecraft/profile/136f2ba62be3444ca2968ec597edb57e?unsigned=false").openConnection().getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null)
            response.append(inputLine);
        in.close();
        JsonObject json = Jsoner.deserialize(response.toString(), new JsonObject());
        JsonObject jo = (JsonObject) ((JsonArray) json.get("properties")).get(0);
        String signature = jo.getString(Jsoner.mintJsonKey("signature", null)), value = jo.getString(Jsoner.mintJsonKey("value", null));
        return new Property("textures", value, signature);
    } catch (Exception ignored) {
    }
    return null;
}