Java Code Examples for org.json.simple.JSONObject

The following are top voted examples for showing how to use org.json.simple.JSONObject. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: alvisnlp   File: GeniaJSONReader.java   View source code 10 votes vote down vote up
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);
	}
}
 
Example 2
Project: Necessities   File: JanetSlack.java   View source code 9 votes vote down vote up
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) {
    }
}
 
Example 3
Project: hono-weather-demo   File: WeatherDataConsumer.java   View source code 7 votes vote down vote up
/**
 * 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();
    }
}
 
Example 4
Project: BiglyBT   File: BEncoder.java   View source code 6 votes vote down vote up
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 );
}
 
Example 5
Project: talchain   File: CallCreate.java   View source code 6 votes vote down vote up
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));
    }
 
Example 6
Project: personium-core   File: UpdateTest.java   View source code 6 votes vote down vote up
/**
 * 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());
}
 
Example 7
Project: JavaShell   File: Metrics.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 8
Project: Minecordbot   File: Metrics.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 9
Project: Uranium   File: YUMCStatistics.java   View source code 6 votes vote down vote up
/**
 * 发送服务器数据到统计网页
 */
private void postPlugin() throws IOException {
    // 服务器数据获取
    final String pluginname = Uranium.name;
    final String tmposarch = System.getProperty("os.arch");

    final Map<String, Object> data = new HashMap();
    data.put("guid", guid);
    data.put("server_version", Bukkit.getVersion());
    data.put("server_port", Bukkit.getServer().getPort());
    data.put("server_tps", FMLCommonHandler.instance().getMinecraftServerInstance().recentTps[1]);
    data.put("plugin_version", Uranium.getCurrentVersion());
    data.put("players_online", Bukkit.getServer().getOnlinePlayers().size());
    data.put("os_name", System.getProperty("os.name"));
    data.put("os_arch", tmposarch.equalsIgnoreCase("amd64") ? "x86_64" : tmposarch);
    data.put("os_version", System.getProperty("os.version"));
    data.put("os_usemem", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024);
    data.put("os_cores", Runtime.getRuntime().availableProcessors());
    data.put("auth_mode", Bukkit.getServer().getOnlineMode() ? 1 : 0);
    data.put("java_version", System.getProperty("java.version"));

    final String jsondata = "Info=" + JSONValue.toJSONString(data);

    final String url = String.format("http://api.yumc.pw/I/P/S/V/%s/P/%s", REVISION, URLEncoder.encode(pluginname, "UTF-8"));
    print("Plugin: " + pluginname + " Send Data To CityCraft Data Center");
    print("Address: " + url);
    print("Data: " + jsondata);
    // 发送数据
    final JSONObject result = (JSONObject) JSONValue.parse(postData(url, jsondata));
    print("Plugin: " + pluginname + " Recover Data From CityCraft Data Center: " + result.get("info"));
}
 
Example 10
Project: ArchersBattle   File: Metrics.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 11
Project: talchain   File: Transaction.java   View source code 6 votes vote down vote up
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);
    }
 
Example 12
Project: personium-core   File: LogTest.java   View source code 6 votes vote down vote up
/**
 * ログファイルに対する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);
}
 
Example 13
Project: NeuralNetworkAPI   File: Metrics.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 14
Project: alfresco-remote-api   File: PublicApiClient.java   View source code 6 votes vote down vote up
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;
}
 
Example 15
Project: ServerConnect   File: Metrics.java   View source code 6 votes vote down vote up
@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;
      }
 
Example 16
Project: Locked   File: MerchantManager.java   View source code 6 votes vote down vote up
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;
}
 
Example 17
Project: personium-core   File: UpdateTest.java   View source code 6 votes vote down vote up
/**
 * 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");
}
 
Example 18
Project: ServerConnect   File: Metrics.java   View source code 6 votes vote down vote up
@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;
      }
 
Example 19
Project: libtrails   File: SkinDownloader.java   View source code 6 votes vote down vote up
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");
    }
}
 
Example 20
Project: JodelAPI   File: JodelAccount.java   View source code 6 votes vote down vote up
/**
 * 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();
        }
    }
}
 
Example 21
Project: eXperDB-DB2PG   File: MySqlConvertMapper.java   View source code 6 votes vote down vote up
@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);
				}
			}
		}
	}
}
 
Example 22
Project: burstcoin   File: GetPollIds.java   View source code 6 votes vote down vote up
@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;

}
 
Example 23
Project: personium-core   File: UserDataUtils.java   View source code 6 votes vote down vote up
/**
 * ユーザー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;
}
 
Example 24
Project: BiglyBT   File: EngineImpl.java   View source code 6 votes vote down vote up
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 ));
}
 
Example 25
Project: alfresco-remote-api   File: ProcessDefinitionParser.java   View source code 6 votes vote down vote up
@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;
}
 
Example 26
Project: sonar-coverage-evolution   File: DefaultSonarClient.java   View source code 6 votes vote down vote up
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();

}
 
Example 27
Project: shipkit   File: CreatePullRequest.java   View source code 6 votes vote down vote up
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);
}
 
Example 28
Project: shipkit   File: FindOpenPullRequest.java   View source code 6 votes vote down vote up
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;
}
 
Example 29
Project: shipkit   File: GitHubStatusCheck.java   View source code 6 votes vote down vote up
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;
}
 
Example 30
Project: shipkit   File: GitHubStatusCheck.java   View source code 6 votes vote down vote up
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;
}
 
Example 31
Project: shipkit   File: ProjectContributorsSerializer.java   View source code 6 votes vote down vote up
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;
}
 
Example 32
Project: shipkit   File: GitHubContributorsFetcher.java   View source code 6 votes vote down vote up
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;
}
 
Example 33
Project: shipkit   File: RecentContributorsFetcher.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 34
Project: shipkit   File: ContributorsSerializer.java   View source code 6 votes vote down vote up
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;
}
 
Example 35
Project: shipkit   File: GitHubListFetcher.java   View source code 6 votes vote down vote up
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);
}
 
Example 36
Project: shipkit   File: GitHubTicketFetcher.java   View source code 6 votes vote down vote up
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;
}
 
Example 37
Project: sonar-stash   File: StashClient.java   View source code 6 votes vote down vote up
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()));
}
 
Example 38
Project: sonar-stash   File: StashClient.java   View source code 6 votes vote down vote up
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);
  }
}
 
Example 39
Project: sonar-stash   File: StashCollector.java   View source code 6 votes vote down vote up
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;
}
 
Example 40
Project: sonar-stash   File: StashCollector.java   View source code 6 votes vote down vote up
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;
}