/** * @return The json object get by performing request. */ public JSONObject getAsJSONObject() { JSONObject json; try { HttpResponse<JsonNode> response = request.asJson(); checkRateLimit(response); handleErrorCode(response); JsonNode node = response.getBody(); if (node.isArray()) { throw new UnirestException("The request returns a JSON Array. Json: "+node.getArray().toString(4)); } else { json = node.getObject(); } } catch (UnirestException e) { throw new JSONException("Error Occurred while getting JSON Object: "+e.getLocalizedMessage()); } handleErrorResponse(json); return json; }
/** * @return The json array get by performing request. */ public JSONArray getAsJSONArray() { JSONArray json; try { HttpResponse<JsonNode> response = request.asJson(); checkRateLimit(response); handleErrorCode(response); JsonNode node = response.getBody(); if (!node.isArray()) { handleErrorResponse(node.getObject()); throw new UnirestException("The request returns a JSON Object. Json: "+node.getObject().toString(4)); } else { json = node.getArray(); } } catch (UnirestException e) { throw new JSONException("Error Occurred while getting JSON Array: "+e.getLocalizedMessage()); } return json; }
@Test public void test() throws UnirestException { gitHubSourceTask.config = new GitHubSourceConnectorConfig(initialConfig()); gitHubSourceTask.nextPageToVisit = 1; gitHubSourceTask.nextQuerySince = Instant.parse("2017-01-01T00:00:00Z"); gitHubSourceTask.gitHubHttpAPIClient = new GitHubAPIHttpClient(gitHubSourceTask.config); String url = gitHubSourceTask.gitHubHttpAPIClient.constructUrl(gitHubSourceTask.nextPageToVisit, gitHubSourceTask.nextQuerySince); System.out.println(url); HttpResponse<JsonNode> httpResponse = gitHubSourceTask.gitHubHttpAPIClient.getNextIssuesAPI(gitHubSourceTask.nextPageToVisit, gitHubSourceTask.nextQuerySince); if (httpResponse.getStatus() != 403) { assertEquals(200, httpResponse.getStatus()); Set<String> headers = httpResponse.getHeaders().keySet(); assertTrue(headers.contains("ETag")); assertTrue(headers.contains("X-RateLimit-Limit")); assertTrue(headers.contains("X-RateLimit-Remaining")); assertTrue(headers.contains("X-RateLimit-Reset")); assertEquals(batchSize.intValue(), httpResponse.getBody().getArray().length()); JSONObject jsonObject = (JSONObject) httpResponse.getBody().getArray().get(0); Issue issue = Issue.fromJson(jsonObject); assertNotNull(issue); assertNotNull(issue.getNumber()); assertEquals(2072, issue.getNumber().intValue()); } }
@Override public List<User> readUsers(String locatie) { try { HttpResponse<JsonNode> getResponse = Unirest .get("http://localhost:8080/openidm/managed/user?_prettyPrint=true&_queryId=query-all") .header("Accept", "application/json") .header("Content-Type", "application/json") .header("X-Requested-With", "Swagger-UI") .header("X-OpenIDM-Username", "openidm-admin") .header("X-OpenIDM-Password", "openidm-admin") .asJson(); JSONObject body = getResponse.getBody().getObject(); System.out.println(body.toString(4)); JSONArray users = body.getJSONArray("result"); List<User> result = new ArrayList<>(); for (int i = 0, maxi = users.length(); i < maxi; i++) { result.add(toUser((JSONObject) users.get(i))); } return result; } catch (UnirestException e) { throw new RuntimeException("Wrapped checked exception.", e); } }
private void reloadCMCPrice() { try { HttpResponse<JsonNode> jsonResponse = Unirest.get("https://api.coinmarketcap.com/v1/ticker").asJson(); JSONArray body = jsonResponse.getBody().getArray(); synchronized (cmcCurrencies) { cmcCurrencies.clear(); for (int i = 0; i < body.length(); i++) { JSONObject currency = body.getJSONObject(i); cmcCurrencies.add(new CurrencyData(currency.getString("name"), currency.getString("symbol"), !currency.isNull("price_btc") ? currency.getString("price_btc") : "0", !currency.isNull("price_usd") ? currency.getString("price_usd") : "0", !currency.isNull("market_cap_usd") ? currency.getString("market_cap_usd") : "0", !currency.isNull("percent_change_24h") ? currency.getString("percent_change_24h") : "0")); } CurrencyData btc = getCurrencyByCode("BTC"); cmcCurrencies.add(new CurrencyData("American Dollar", "USD", 1 / btc.getUsdPrice(), 1, 0, 0, false)); cmcCurrencies.add(new CurrencyData("Milli-Bitcoin", "mBTC", 0.001, btc.getUsdPrice() / 1000, btc.getMarketCap(), btc.getPctChange24h(), false)); cmcCurrencies.add(new CurrencyData("Satoshi", "Sat", 0.00000001, btc.getUsdPrice() / 100000000, btc.getMarketCap(), btc.getPctChange24h(), false)); } lastCoinMarketCapUpdate = System.currentTimeMillis(); } catch (Exception e) { e.printStackTrace(); } }
public <T> Results<T> parse(JsonNode jsonNode, Class<? extends ApiObject> apiObject) { LOGGER.debug("Parsing JSON node"); final Results<T> results = new Results<>(); final JSONObject root = jsonNode.getObject(); results.setPage(root.getInt("current_page")); results.setTotal(root.getInt("total_entries")); results.setRawResults(jsonNode.toString()); final JSONArray rso = root.getJSONArray("results"); if (Product.class == apiObject) { results.setResults(parseProducts(rso)); } else if (Vendor.class == apiObject) { results.setResults(parseVendors(rso)); } else if (Version.class == apiObject) { results.setResults(parseVersions(rso)); } else if (Vulnerability.class == apiObject) { results.setResults(parseVulnerabilities(rso)); } return results; }
@Override public String getToken(String code) throws UnirestException { HttpResponse<JsonNode> response = Unirest.post("https://www.googleapis.com/oauth2/v4/token") .header("User-Agent", "pxls.space") .field("grant_type", "authorization_code") .field("code", code) .field("redirect_uri", getCallbackUrl()) .field("client_id", App.getConfig().getString("oauth.google.key")) .field("client_secret", App.getConfig().getString("oauth.google.secret")) .asJson(); JSONObject json = response.getBody().getObject(); if (json.has("error")) { return null; } else { return json.getString("access_token"); } }
public String getToken(String code) throws UnirestException { HttpResponse<JsonNode> response = Unirest.post("https://oauth.vk.com/access_token") .header("User-Agent", "pxls.space") .field("grant_type", "authorization_code") .field("code", code) .field("redirect_uri", getCallbackUrl()) .field("client_id", App.getConfig().getString("oauth.vk.key")) .field("client_secret", App.getConfig().getString("oauth.vk.secret")) .asJson(); JSONObject json = response.getBody().getObject(); if (json.has("error")) { return null; } else { return json.getString("access_token"); } }
public String getIdentifier(String token) throws UnirestException, InvalidAccountException { HttpResponse<JsonNode> me = Unirest.get("https://api.vk.com/method/users.get?access_token=" + token) .header("User-Agent", "pxls.space") .asJson(); JSONObject json = me.getBody().getObject(); if (json.has("error")) { return null; } else { try { return Integer.toString(json.getJSONArray("response").getJSONObject(0).getInt("uid")); } catch (JSONException e) { return null; } } }
public String getIdentifier(String token) throws UnirestException, InvalidAccountException { String[] codes = token.split("\\|"); HttpResponse<JsonNode> me = Unirest.get("https://api.tumblr.com/v2/user/info?" + getOauthRequest("https://api.tumblr.com/v2/user/info", "oauth_token="+codes[0], "oob", "GET", codes[1])) .header("User-Agent", "pxls.space") .asJson(); JSONObject json = me.getBody().getObject(); if (json.has("error")) { return null; } else { try { return json.getJSONObject("response").getJSONObject("user").getString("name"); } catch (JSONException e) { return null; } } }
public String getToken(String code) throws UnirestException { HttpResponse<JsonNode> response = Unirest.post("https://discordapp.com/api/oauth2/token") .header("User-Agent", "pxls.space") .field("grant_type", "authorization_code") .field("code", code) .field("redirect_uri", getCallbackUrl()) .basicAuth(App.getConfig().getString("oauth.discord.key"), App.getConfig().getString("oauth.discord.secret")) .asJson(); JSONObject json = response.getBody().getObject(); if (json.has("error")) { return null; } else { return json.getString("access_token"); } }
public String getIdentifier(String token) throws UnirestException, InvalidAccountException { HttpResponse<JsonNode> me = Unirest.get("https://discordapp.com/api/users/@me") .header("Authorization", "Bearer " + token) .header("User-Agent", "pxls.space") .asJson(); JSONObject json = me.getBody().getObject(); if (json.has("error")) { return null; } else { long id = json.getLong("id"); long signupTimeMillis = (id >> 22) + 1420070400000L; long ageMillis = System.currentTimeMillis() - signupTimeMillis; long minAgeMillis = App.getConfig().getDuration("oauth.discord.minAge", TimeUnit.MILLISECONDS); if (ageMillis < minAgeMillis){ long days = minAgeMillis / 86400 / 1000; throw new InvalidAccountException("Account too young"); } return json.getString("id"); } }
public String getToken(String code) throws UnirestException { HttpResponse<JsonNode> response = Unirest.post("https://www.reddit.com/api/v1/access_token") .header("User-Agent", "pxls.space") .field("grant_type", "authorization_code") .field("code", code) .field("redirect_uri", getCallbackUrl()) .basicAuth(App.getConfig().getString("oauth.reddit.key"), App.getConfig().getString("oauth.reddit.secret")) .asJson(); JSONObject json = response.getBody().getObject(); if (json.has("error")) { return null; } else { return json.getString("access_token"); } }
public String getIdentifier(String token) throws UnirestException, InvalidAccountException { HttpResponse<JsonNode> me = Unirest.get("https://oauth.reddit.com/api/v1/me") .header("Authorization", "bearer " + token) .header("User-Agent", "pxls.space") .asJson(); JSONObject json = me.getBody().getObject(); if (json.has("error")) { return null; } else { long accountAgeSeconds = (System.currentTimeMillis() / 1000 - json.getLong("created")); long minAgeSeconds = App.getConfig().getDuration("oauth.reddit.minAge", TimeUnit.SECONDS); if (accountAgeSeconds < minAgeSeconds){ long days = minAgeSeconds / 86400; throw new InvalidAccountException("Account too young"); } else if (!json.getBoolean("has_verified_email")) { throw new InvalidAccountException("Account must have a verified e-mail"); } return json.getString("name"); } }
public static List<String> retrieveAllFiles(String auth, String folder) throws IOException, UnirestException { List<String> lis= new LinkedList<String>(); HttpResponse<JsonNode> jsonResponse = Unirest.get("https://www.googleapis.com/drive/v2/files/root/children?q=title='"+folder+"'").header("Authorization","Bearer "+auth).asJson(); JSONObject jsonObject= new JSONObject(jsonResponse.getBody()); JSONArray array = jsonObject.getJSONArray("array"); for(int i=0;i<array.length();i++){ JSONArray jarray=array.getJSONObject(i).getJSONArray("items"); int j=jarray.length(); while(j>0){ String id=jarray.getJSONObject(0).getString("id"); auxRetrieveAllFiles(lis,auth,"https://www.googleapis.com/drive/v2/files?includeTeamDriveItems=false&pageSize=500&q='"+id+"'%20in%20parents"+"&key="+ MISConfig.getGoogle_api(),id); j--; } } return lis; }
private static void auxRetrieveAllFiles(List<String> lis,String auth, String link, String parents) throws IOException, UnirestException { HttpResponse<JsonNode> jsonResponse = Unirest.get(link).header("Authorization","Bearer "+auth).asJson(); JSONObject jsonObject = new JSONObject(jsonResponse.getBody()); JSONArray array = jsonObject.getJSONArray("array"); for (int j=0;j<array.length();j++){ JSONArray jarray=array.getJSONObject(j).getJSONArray("items"); for(int i = 0; i < jarray.length(); i++) { if(jarray.getJSONObject(i).has("mimeType") && !jarray.getJSONObject(i).get("mimeType").equals("application/vnd.google-apps.folder")){ String name= jarray.getJSONObject(i).getString("title"); lis.add(jarray.getJSONObject(i).getString("title")); } else { if(jarray.getJSONObject(i).has("id")){ auxRetrieveAllFiles(lis,auth,"https://www.googleapis.com/drive/v2/files?includeTeamDriveItems=false&pageSize=500&q='"+jarray.getJSONObject(i).get("id")+"'%20in%20parents"+"&key="+ MISConfig.getGoogle_api(),parents); } } } if(array.getJSONObject(j).has("nextLink")){ String next=array.getJSONObject(j).getString("nextLink"); auxRetrieveAllFiles(lis,auth,next,parents); } } }
public static String processHttpRequest(String completeURL, Map<String, Object> params, Map<String, String> customHeaders, HttpMethod method) throws IOException { Map<String, String> headers = getDefaultHeader(); if (customHeaders != null) { headers.putAll(customHeaders); } HttpResponse<JsonNode> result = executeHttpMethod(completeURL, params, headers, method); if (result == null) { return null; } if (result.getStatus() != 200) { String exceptionResponse = result.getBody().toString(); throw new ServiceException((result.getStatus() + result.getStatusText()), exceptionResponse); } return result.getBody().toString(); }
public static String fetchSchemaFromRemote(String url, String basicAuthUsername, String basicAuthPassword) { Map<String, String> bodyMap = new HashMap<>(); bodyMap.put("query", introspectionQuery()); bodyMap.put("variables", null); HttpRequestWithBody requestWithBody = Unirest.post(url) .header("Content-Type", "application/json") .header("accept", "application/json"); // basic auth if (basicAuthUsername != null && basicAuthPassword != null) { requestWithBody.basicAuth(basicAuthUsername, basicAuthPassword); } // body RequestBodyEntity requestBodyEntity = requestWithBody.body(bodyMap); HttpResponse<JsonNode> jsonNodeHttpResponse; try { jsonNodeHttpResponse = requestBodyEntity.asJson(); } catch (UnirestException e) { throw new RuntimeException(e); } return Util.convertStreamToString(jsonNodeHttpResponse.getRawBody(), "UTF-8"); }
private void login() throws IOException { HttpResponse<JsonNode> loginResult; try { loginResult = Unirest.post(serverUrl + "v1/login").field("username", user).field("password", password).asJson(); } catch (UnirestException e) { throw new IOException(e); } if (loginResult.getStatus() == 401) throw new IOException("The username and password provided are incorrect."); if (loginResult.getStatus() != 200) throw new IOException("The login failed with a result of: " + loginResult.getStatus()); JSONObject data = loginResult.getBody().getObject().getJSONObject("data"); this.authToken = data.getString("authToken"); this.userId = data.getString("userId"); }
private static int registerMetadata() throws UnirestException { JSONObject rootJson = new JSONObject(); JSONObject objectJson = new JSONObject(); objectJson.put("type", "website"); objectJson.put("display", "Web"); rootJson.put("object", objectJson); JSONArray counterArray = new JSONArray(); rootJson.put("counters", counterArray); JSONObject counterMap = new JSONObject(); counterArray.put(counterMap); counterMap.put("name", "Time"); counterMap.put("unit", "ms"); HttpResponse<JsonNode> response = Unirest.post("http://" + ip + ":" + port + "/register") .header("accept", "application/json") .header("content-type", "application/json") .body(rootJson).asJson(); return response.getStatus(); }
@Override public void sendCallBack(Sms sms, Object result) throws UnirestException { // TODO Auto-generated method stub for(int count = 0; count < 10; count++){ try { HttpResponse<JsonNode> jsonResponse = Unirest.post(sms.getCallbackUrl()) .header("accept", "application/json") .field("result", result) .asJson(); break; } catch (UnirestException e) { // TODO Auto-generated catch block e.printStackTrace(); if(count == 10){ throw new UnirestException(e); } continue; } } }
private static JSONObject createPlaylist(String spotifyId, String title, String authHeader) { HttpRequestWithBody http = Unirest.post("https://api.spotify.com/v1/users/" + spotifyId + "/playlists"); try { HttpResponse<JsonNode> httpResponse = http .header("Content-Type", "application/json") .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36") .header("Authorization", authHeader) .body("{\"name\":\"" + title + "\", \"public\":true}") .asJson(); JsonNode response = httpResponse.getBody(); return response.getObject(); } catch (Exception e) { e.printStackTrace(); throw new WrapperException(); } }
public static void main(String[] args) throws Exception { try { JsonNode jsonData = new JsonNode("{}"); // json data without encrypt String keyFile = "/home/xuan/Downloads/449033.key"; byte[] keyByte = EncryptUtils.getBytesFromFile(keyFile); Key key = EncryptUtils.restorePrivateKey(keyByte); HttpResponse<JsonNode> jsonResponse = Unirest .post(org_getall_url) .header("Content-Type", "application/x-www-form-urlencoded") .field("eid", "449033") .field("nonce", UUID.randomUUID().toString()) .field("data", EncryptUtils.encryptWithEncodeBase64UTF8( jsonData.toString(), key)).asJson(); System.out.println(jsonResponse.getBody()); } catch (UnirestException e) { e.printStackTrace(); } }
public static CommandResult otp(CommandSource commandSource, int code) { String ticket = MFA_TICKETS.remove(commandSource); if (ticket == null) { commandSource.sendMessage(Text.of(TextColors.RED, "No OTP auth queued!")); return CommandResult.empty(); } try { HttpResponse<JsonNode> response = Unirest.post("https://discordapp.com/api/v6/auth/mfa/totp") .header("content-type", "application/json") .body(new JSONObject().put("code", String.format("%06d", code)).put("ticket", ticket)) .asJson(); if (response.getStatus() != 200) { commandSource.sendMessage(Text.of(TextColors.RED, "Wrong auth code! Retry with '/discord loginconfirm <email> <password>'")); return CommandResult.empty(); } String token = response.getBody().getObject().getString("token"); prepareHumanClient(Javacord.getApi(token, false), commandSource); } catch (UnirestException e) { e.printStackTrace(); commandSource.sendMessage(Text.of(TextColors.RED, "Unexpected error!")); return CommandResult.empty(); } return CommandResult.success(); }
@Test(expected = KintoException.class) public void testExecuteKintoError() throws UnirestException, KintoException, ClientException { // GIVEN a fake url String remote = "https://fake.kinto.url"; // AND a kintoClient KintoClient kintoClient = new KintoClient(remote); // AND a httpResponse mock HttpResponse<JsonNode> response = mock(HttpResponse.class); doReturn(400).when(response).getStatus(); doReturn("an error").when(response).getStatusText(); // AND GetRequest mock GetRequest request = mock(GetRequest.class); doReturn(response).when(request).asJson(); // WHEN calling execute kintoClient.execute(request); // THEN a KintoException is thrown }
public NgrokTunnel(String url, int port) throws UnirestException { this.name = UUID.randomUUID().toString(); this.ngrokAddr = url; String payload = String.format( "{" + "\"addr\":\"%d\", " + "\"name\":\"%s\", " + "\"proto\":\"http\", " + "\"bind_tls\":\"false\"" + "}" , port, name); HttpResponse<JsonNode> jsonResponse = Unirest.post(ngrokAddr.concat("/api/tunnels")) .header("accept", "application/json") .header("Content-Type", "application/json; charset=utf8") .body(payload) .asJson(); this.url = jsonResponse.getBody().getObject().getString("public_url"); }
@Override public void completed(final HttpResponse<JsonNode> response) { final String strResponse = response.getBody().toString(); final int status = response.getStatus(); final BreinResult result; if (status == 200) { final Map<String, Object> mapResponse = this.engine.parseJson(strResponse); result = new BreinResult(mapResponse); } else { result = new BreinResult(strResponse, status); } if (this.callback != null) { this.callback.accept(result); } }
/** * GET request using UniRest library. * * @param url is endpoint to which request has to be done. * @param params is data that has to be sent. * @return JSONObject returns json response. * @throws KiteException contains error message and error code inside. * @throws JSONException occurs when there is error while parsing data. */ public JSONObject getRequest(String url, Map<String, Object> params) throws KiteException, JSONException { try { if(KiteConnect.httpHost != null){ Unirest.setProxy(KiteConnect.httpHost); } HttpResponse<JsonNode> response = Unirest.get(url).queryString(params) .header("accept", "application/json") .asJson(); JsonNode body = response.getBody(); JSONObject jsonObject = body.getObject(); int code = response.getStatus(); if (code == 200) return jsonObject; else throw dealWithKiteException(body, code); } catch (UnirestException e) { throw new KiteNoNetworkException("Connection error"); } }
/** * GET request using UniRest library without params. * @param url is endpoint to which request has to be done. * @return JSONObject returns json response. * @throws KiteException contains error message and error code inside. * @throws JSONException occurs when there is error while parsing data. */ public JSONObject getRequest(String url) throws KiteException, JSONException { try { if(KiteConnect.httpHost != null){ Unirest.setProxy(KiteConnect.httpHost); } HttpResponse<JsonNode> response = Unirest.get(url) .header("accept", "application/json") .asJson(); JsonNode body = response.getBody(); JSONObject jsonObject = body.getObject(); int code = response.getStatus(); if (code == 200) return jsonObject; else throw dealWithKiteException(body, code); } catch (UnirestException e) { throw new KiteNoNetworkException("Connection error"); } }
private Observable<OSMCity> getCities(final String _search) { return Observable.create(new Observable.OnSubscribe<OSMCity>() { @Override public void call(Subscriber<? super OSMCity> arg0) { try { arg0.onStart(); JsonNode json = Unirest .get("https://nominatim.openstreetmap.org/search.php?format=json&q=" + _search) .asJson() .getBody(); JSONArray array = json.getArray(); for (int i = 0; i < array.length(); i++) { arg0.onNext(new OSMCity(array.getJSONObject(i))); } arg0.onCompleted(); } catch (UnirestException ex) { arg0.onError(ex); } } }); }
/** * POST request using UniRest library. * * @param url is endpoint to which request has to be done. * @param params is data that has to be sent in body. * @return JSONObject returns json response. * @throws KiteException contains error message and error code inside. * @throws JSONException occurs when there is error while parsing data. */ public JSONObject postRequest(String url, Map<String, Object> params) throws KiteException, JSONException { try { if(KiteConnect.httpHost != null){ Unirest.setProxy(KiteConnect.httpHost); } HttpResponse<JsonNode> response = Unirest.post(url) .header("accept", "application/json") .fields(params) .asJson(); JsonNode body = response.getBody(); JSONObject jsonObject = body.getObject(); int code = response.getStatus(); if (code == 200) return jsonObject; else throw dealWithKiteException(body, code); } catch (UnirestException e) { throw new KiteNoNetworkException("Connection error"); } }
public void updateKv(String key, JSONObject js) { Unirest.post(urlRoot() + "/api/kv/set").field("key", key).field("value", js.toString()) .asJsonAsync(new Callback<JsonNode>() { @Override public void completed(HttpResponse<JsonNode> response) { } @Override public void failed(UnirestException e) { e.printStackTrace(); } @Override public void cancelled() { } }); }
@Override public boolean checkTokenBlocking(String token) { try { // only the last 0-9 digits of the token should be visible. // We don't want someone being able to login to an account by reading the logs. logger.debug("Checking token {}", token.replaceAll(".{10}", "**********")); HttpResponse<JsonNode> response = Unirest.get("https://discordapp.com/api/v6/users/@me/guilds") .header("authorization", token) .asJson(); if (response.getStatus() < 200 || response.getStatus() > 299) { logger.debug("Checked token {} (valid: {})", token.replaceAll(".{10}", "**********"), false); return false; } logger.debug("Checked token {} (valid: {})", token.replaceAll(".{10}", "**********"), true); return true; } catch (UnirestException e) { return false; } }
@Override public Future<Invite> parseInvite(final String invite, FutureCallback<Invite> callback) { final String inviteCode = invite.replace("https://discord.gg/", "").replace("http://discord.gg/", ""); ListenableFuture<Invite> future = getThreadPool().getListeningExecutorService().submit(new Callable<Invite>() { @Override public Invite call() throws Exception { logger.debug("Trying to parse invite {} (parsed code: {})", invite, inviteCode); HttpResponse<JsonNode> response = Unirest .get("https://discordapp.com/api/v6/invite/" + inviteCode) .header("authorization", token) .asJson(); checkResponse(response); logger.debug("Parsed invite {} (parsed code: {})", invite, inviteCode); return new ImplInvite(ImplDiscordAPI.this, response.getBody().getObject()); } }); if (callback != null) { Futures.addCallback(future, callback); } return future; }
@Override public Future<Void> deleteInvite(final String inviteCode) { return getThreadPool().getExecutorService().submit(new Callable<Void>() { @Override public Void call() throws Exception { logger.debug("Trying to delete invite {}", inviteCode); HttpResponse<JsonNode> response = Unirest .delete("https://discordapp.com/api/v6/invite/" + inviteCode) .header("authorization", token) .asJson(); checkResponse(response); logger.info("Deleted invite {}", inviteCode); return null; } }); }
/** * Requests the gateway. * * @return The requested gateway. */ public String requestGatewayBlocking() { try { logger.debug("Requesting gateway (token: {})", token.replaceAll(".{10}", "**********")); HttpResponse<JsonNode> response = Unirest.get("https://discordapp.com/api/v6/gateway") .header("authorization", token) .asJson(); if (response.getStatus() == 401) { throw new IllegalStateException("Cannot request gateway! Invalid token?"); } if (response.getStatus() < 200 || response.getStatus() > 299) { throw new IllegalStateException("Received http status code " + response.getStatus() + " with message " + response.getStatusText() + " and body " + response.getBody()); } String gateway = response.getBody().getObject().getString("url"); logger.debug("Requested gateway {} (token: {})", gateway, token.replaceAll(".{10}", "**********")); return gateway; } catch (UnirestException e) { e.printStackTrace(); return null; } }
/** * Checks the response. * * @param response The response to check. * @throws Exception If the response has problems (status code not between 200 and 300). */ public void checkResponse(HttpResponse<JsonNode> response) throws Exception { String message = ""; if (response.getBody() != null && !response.getBody().isArray() && response.getBody().getObject().has("message")) { message = " " + response.getBody().getObject().getString("message"); } if (response.getStatus() == 403) { throw new PermissionsException("Missing permissions!" + message); } if (response.getStatus() == 429) { // Handled in #checkRateLimit return; } if (response.getStatus() < 200 || response.getStatus() > 299) { throw new BadResponseException("Received http status code " + response.getStatus() + " with message " + response.getStatusText() + " and body " + response.getBody(), response.getStatus(), response.getStatusText(), response); } }
@Override public Future<Void> removeAllReactions() { return api.getThreadPool().getExecutorService().submit(new Callable<Void>() { @Override public Void call() throws Exception { logger.debug("Trying to remove all reactions from message {}", ImplMessage.this); HttpResponse<JsonNode> response = Unirest .delete("https://discordapp.com/api/v6/channels/" + channelId + "/messages/" + getId() + "/reactions") .header("authorization", api.getToken()) .asJson(); api.checkResponse(response); if (isPrivateMessage()) { api.checkRateLimit(response, RateLimitType.UNKNOWN, null, null); } else { api.checkRateLimit(response, RateLimitType.UNKNOWN, null, getChannelReceiver()); } logger.debug("Removed all reactions from message {}", ImplMessage.this); return null; } }); }
/** * Adds an reaction to the message. * * @param reaction The reaction to add. Whether a unicode emoji or a custom emoji in the format <code>name:id</code>. * @return A future which tells us if the creation was a success. */ private Future<Void> addReaction(final String reaction) { return api.getThreadPool().getExecutorService().submit(new Callable<Void>() { @Override public Void call() throws Exception { logger.debug("Trying to add reaction to message with id {} (reaction: {})", getId(), reaction); HttpResponse<JsonNode> response = Unirest .put("https://discordapp.com/api/v6/channels/" + channelId + "/messages/" + getId() + "/reactions/" + reaction + "/@me") .header("authorization", api.getToken()) .header("content-type", "application/json") .body("{}") .asJson(); api.checkResponse(response); if (isPrivateMessage()) { api.checkRateLimit(response, RateLimitType.UNKNOWN, null, null); } else { api.checkRateLimit(response, RateLimitType.UNKNOWN, null, getChannelReceiver()); } logger.debug("Added reaction to message with id {} (reaction: {})", getId(), reaction); return null; } }); }
@Override public Future<Void> removeUser(final User user) { return api.getThreadPool().getExecutorService().submit(new Callable<Void>() { @Override public Void call() throws Exception { logger.debug("Trying to remove reactor {} from reaction {} of message {}", user, ImplReaction.this, message); String reactionString = isCustomEmoji() ? getCustomEmoji().getName() + ":" + getCustomEmoji().getId() : getUnicodeEmoji(); HttpResponse<JsonNode> response = Unirest .delete("https://discordapp.com/api/v6/channels/" + ((ImplMessage) message).getChannelId() + "/messages/" + message.getId() + "/reactions/" + reactionString + "/" + user.getId()) .header("authorization", api.getToken()) .asJson(); api.checkResponse(response); api.checkRateLimit(response, RateLimitType.UNKNOWN, null, message.getChannelReceiver()); logger.debug("Removed reactor {} from reaction {} of message {}", user, ImplReaction.this, message); return null; } }); }