@Test
  public void testGetLocation() throws Exception {
    LocationRepository repository = container.getInjector().getInstance(LocationRepository.class);

    String id = repository.create(new Location("foo", 0, 0)).getId();
    HttpResponse httpResponse = container.execute(new HttpGet("/location/" + id));
    assertEquals(HttpURLConnection.HTTP_OK, httpResponse.getStatusLine().getStatusCode());
    HttpEntity entity = httpResponse.getEntity();
    assertEquals(ContentType.APPLICATION_JSON.getMimeType(), ContentType.get(entity).getMimeType());
    String content = EntityUtils.toString(entity);
    ObjectMapper om = new ObjectMapper();
    Map<String, ?> response = om.readValue(content, new TypeReference<Map<String, ?>>() {});
    assertEquals(id, response.get("id"));
  }
  private JSONObject prepareRequestAndExtractResponse(HttpUriRequest request) throws HTTPError {
    if (key != null) {
      String encoding = "";
      try {
        encoding = Base64.encodeBase64String((key + ":").getBytes("UTF-8"));
      } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
      }
      request.setHeader("Authorization", "Basic " + encoding + "=");
    }

    HttpResponse response;
    try {
      response = httpClient.execute(request);
    } catch (ClientProtocolException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    String body = null;
    HttpEntity entity = response.getEntity();
    if (entity != null) {
      try {
        body = EntityUtils.toString(entity);

      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }

    StatusLine status = response.getStatusLine();
    if (status.getStatusCode() >= 299
        && !ContentType.APPLICATION_JSON
            .getMimeType()
            .equals(
                (entity.getContentType() != null ? entity.getContentType().getValue() : null))) {
      throw new HTTPError(response, body);
    }

    JSONObject result;
    try {
      result = new JSONObject(body);
    } catch (JSONException e) {
      throw new RuntimeException(e);
    }

    return result;
  }
  private CloseableHttpClient createClientInstance() {
    final RequestConfig requestConfig =
        RequestConfig.copy(RequestConfig.DEFAULT)
            .setConnectionRequestTimeout((int) config.getConnectTimeout().toMillis())
            .setSocketTimeout((int) config.getConnectTimeout().toMillis())
            .build();

    final List<Header> headers = new ArrayList<>(1);
    headers.add(
        new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()));

    return HttpClients.custom()
        .setDefaultRequestConfig(requestConfig)
        .setDefaultHeaders(headers)
        .build();
  }
  @Test
  public void testGetContentType() throws Exception {
    String input = "0123456789";
    BasicHttpEntity basic;
    PartiallyRepeatableHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.getContentType(), nullValue());

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    basic.setContentType(ContentType.APPLICATION_JSON.getMimeType());
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.getContentType().getValue(), is("application/json"));
  }
 public boolean banImpl(String userId, String serverId) {
   Map<String, String> headers = new HashMap<>();
   headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
   headers.put(HttpHeaders.AUTHORIZATION, apiClient.getToken());
   try {
     HttpResponse<JsonNode> response =
         Unirest.put(
                 "https://discordapp.com/api/guilds/"
                     + serverId
                     + "/bans/"
                     + userId
                     + "?delete-message-days=1")
             .headers(headers)
             .asJson();
     //  Ignore
     return true;
   } catch (Exception e) {
     LOGGER.warn("Exception when trying to ban " + userId, e);
     return false;
   }
 }
  private void vanish(MessageContext context, String args) {
    Message message = context.getMessage();
    if (args.isEmpty()) {
      return;
    }

    try {
      final int cap = 100;
      final int capPages = 10;
      String[] vals = args.split(" ");
      String userId;
      int numMsgs;
      if (vals.length == 2) {
        User user = findUser(context, vals[0]);
        userId = user.getId();
        if (user == NO_USER) {
          userId = vals[0];
        }
        numMsgs = Math.max(1, Math.min(cap, Integer.parseInt(vals[1])));
      } else if (vals.length == 1) {
        userId = "";
        numMsgs = Math.max(1, Math.min(cap, Integer.parseInt(vals[0])));
      } else {
        userId = "";
        numMsgs = 10;
      }

      int limit = numMsgs;
      String before = message.getId();
      //  Limit search to 10 pages (500 msgs)
      //  Instead of deleting them when we find them, we build a list instead
      List<String> messagesToDelete = new ArrayList<>(limit);
      for (int k = 0; k < capPages && limit > 0; k++) {
        Map<String, String> headers = new HashMap<>();
        headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
        headers.put(HttpHeaders.AUTHORIZATION, apiClient.getToken());
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("limit", 50);
        queryParams.put("before", before);
        HttpResponse<JsonNode> response =
            Unirest.get(ApiConst.CHANNELS_ENDPOINT + message.getChannelId() + "/messages")
                .headers(headers)
                .queryString(queryParams)
                .asJson();
        JSONArray ret = response.getBody().getArray();
        if (userId.isEmpty()) {
          for (int i = 0; i < ret.length() && limit > 0; i++) {
            JSONObject msg = ret.getJSONObject(i);
            String mid = msg.getString("id");
            before = mid;
            messagesToDelete.add(mid);
            limit--;
          }
        } else {
          for (int i = 0; i < ret.length() && limit > 0; i++) {
            JSONObject msg = ret.getJSONObject(i);
            String mid = msg.getString("id");
            JSONObject msgUsr = msg.getJSONObject("author");
            String uid = msgUsr.getString("id");
            before = mid;
            if (userId.equals(uid)) {
              messagesToDelete.add(mid);
              limit--;
            }
          }
        }
      }
      LOGGER.info("Deleting {} messages", messagesToDelete.size());
      //  Using bulk delete endpoint
      apiClient.bulkDeleteMessages(
          context.getChannel().getId(),
          messagesToDelete.toArray(new String[messagesToDelete.size()]));
    } catch (Exception e) {
      LOGGER.warn("Unable to get messages", e);
    }
  }
 private void setNick(MessageContext context, String args) {
   if (context.getServer() == null || context.getServer() == NO_SERVER) {
     return;
   }
   String serverId = context.getServer().getId();
   Channel channel = context.getChannel();
   String[] split = args.split(" ", 2);
   String newNickname;
   if (split.length == 1) {
     //  Clearing nickname, set to empty string
     newNickname = "";
   } else {
     newNickname = split[1];
   }
   User[] mentions = context.getMessage().getMentions();
   if (mentions.length == 0) {
     apiClient.sendMessage(loc.localize("commands.mod.setnick.response.blank"), channel);
   }
   User target = mentions[0];
   Map<String, String> headers = new HashMap<>();
   headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
   headers.put(HttpHeaders.AUTHORIZATION, apiClient.getToken());
   try {
     HttpResponse<JsonNode> response =
         Unirest.patch(
                 "https://discordapp.com/api/guilds/" + serverId + "/members/" + target.getId())
             .headers(headers)
             .body("{\"nick\":\"" + newNickname + "\"}")
             .asJson();
     int status = response.getStatus();
     if (status != 204) {
       if (status == 403) {
         apiClient.sendMessage(
             loc.localize("commands.mod.setnick.response.failed.no_perms"), channel);
       } else if (status == 404) {
         apiClient.sendMessage(
             loc.localize("commands.mod.setnick.response.failed.not_found"), channel);
       } else {
         apiClient.sendMessage(
             loc.localize(
                 "commands.mod.setnick.response.unknown_error",
                 status,
                 response.getStatusText(),
                 response.getBody().toString()),
             channel);
       }
     } else {
       if (newNickname.isEmpty()) {
         apiClient.sendMessage(
             loc.localize("commands.mod.setnick.response.removed", target.getUsername()), channel);
       } else {
         apiClient.sendMessage(
             loc.localize(
                 "commands.mod.setnick.response.changed", target.getUsername(), newNickname),
             channel);
       }
     }
   } catch (UnirestException e) {
     LOGGER.warn(
         "Exception while setting nickname for {} {} in {} {}",
         target.getUsername(),
         target.getId(),
         context.getServer().getName(),
         serverId);
     LOGGER.warn("Nickname set exception", e);
   }
 }
Example #8
0
 public static String doPostJson(String url, String json) {
   return doPostString(url, json, ContentType.APPLICATION_JSON.getMimeType());
 }