Exemplo n.º 1
0
 @Then("^the user should receive a specified JSON content$")
 public void jsonResponse() throws Exception {
   assertThat(response.getHeaders("Content-Type"))
       .extracting(Header::getValue)
       .containsExactly(org.apache.http.entity.ContentType.APPLICATION_JSON.toString());
   DocumentContext jsonPath = JsonPath.parse(response.getEntity().getContent());
   assertThat(jsonPath.<String>read("blobId")).isEqualTo(_1M_ZEROED_FILE_BLOB_ID);
   assertThat(jsonPath.<String>read("type")).isEqualTo("application/octet-stream");
   assertThat(jsonPath.<Integer>read("size")).isEqualTo(_1M);
 }
  @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 void testInitialSearchEntity() throws IOException {
    String query = "{\"match_all\":{}}";
    HttpEntity entity = initialSearchEntity(new BytesArray(query));
    assertEquals(ContentType.APPLICATION_JSON.toString(), entity.getContentType().getValue());
    assertEquals(
        "{\"query\":" + query + "}",
        Streams.copyToString(new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8)));

    // Invalid XContent fails
    RuntimeException e =
        expectThrows(
            RuntimeException.class,
            () -> initialSearchEntity(new BytesArray("{}, \"trailing\": {}")));
    assertThat(e.getCause().getMessage(), containsString("Unexpected character (',' (code 44))"));
    e = expectThrows(RuntimeException.class, () -> initialSearchEntity(new BytesArray("{")));
    assertThat(e.getCause().getMessage(), containsString("Unexpected end-of-input"));
  }
Exemplo n.º 7
0
 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;
   }
 }
Exemplo n.º 8
0
  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);
    }
  }
Exemplo n.º 9
0
 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);
   }
 }
Exemplo n.º 10
0
  private Res handlePOSTRequest(Req request, Class<Res> resClass) {
    L.d(TAG, "Request URL: " + request.getURL());
    HttpPost httpPost = new HttpPost(request.getURL());
    // 添加请求头
    Map<String, String> headersMap = request.getHeaders();
    if (headersMap != null) {
      Iterator<Map.Entry<String, String>> iterator = headersMap.entrySet().iterator();
      while (iterator.hasNext()) {
        Map.Entry<String, String> entry = iterator.next();
        httpPost.addHeader(entry.getKey(), entry.getValue());
      }
    }
    L.d(TAG, "Request Header: " + new Gson().toJson(headersMap));
    // 判断是否存在上传文件,以不同方式添加请求参数
    if (request.existUploadFiles()) {
      Map<String, String> uploadFilesMap = request.getUploadFiles();
      Map<String, Object> paramsMap = request.getParams();
      /*MultipartEntityBuilder builder = MultipartEntityBuilder.create();
      builder.setMode( HttpMultipartMode.BROWSER_COMPATIBLE );
      //			builder.setCharset( Charset.forName( "UTF-8" ) );
      String data = new Gson().toJson( paramsMap );
      // 设置中文编码
      ContentType contentType = ContentType.create( "application/json" , HTTP.UTF_8 );
      StringBody strBody = new StringBody( data , contentType );
      builder.addPart( "data" , strBody );

      //			builder.addTextBody( "data" , data );
      //			builder.addTextBody( "data" , data , ContentType.APPLICATION_JSON.withCharset( "UTF-8" ) );
      Log.d( "[File Data]" , data );
      Iterator<Entry<String , String>> iterator = uploadFilesMap.entrySet().iterator();
      while( iterator.hasNext() )
      {
      	Map.Entry<String , String> entry = iterator.next();
      	String key = entry.getKey();
      	String filePath = entry.getValue();
      	if( !TextUtils.isEmpty( filePath ) )
      	{
      		byte[] fileByte = FileUtils.getBytesFromFile( new File( filePath ) );
      		builder.addBinaryBody( key , fileByte );
      	}
      }
      HttpEntity httpEntity = builder.build();*/
      MultipartEntity httpEntity = new MultipartEntity();
      StringBody sb =
          new StringBody(
              new Gson().toJson(paramsMap), ContentType.APPLICATION_JSON.withCharset("UTF-8"));
      httpEntity.addPart("data", sb);
      Iterator<Entry<String, String>> iterator = uploadFilesMap.entrySet().iterator();
      while (iterator.hasNext()) {
        Map.Entry<String, String> entry = iterator.next();
        String key = entry.getKey();
        String filePath = entry.getValue();
        if (!TextUtils.isEmpty(filePath)) {
          /*byte[] fileByte = FileUtils.getBytesFromFile( new File( filePath ) );
          builder.addBinaryBody( key , fileByte );*/
          ContentBody cbFile = new FileBody(new File(filePath));
          httpEntity.addPart(key, cbFile);
        }
      }
      httpPost.setEntity(httpEntity);
      /*if( paramsMap != null )
      {
      	MultipartEntity httpEntity = new MultipartEntity();
      	Iterator<Map.Entry<String , Object>> iterator = paramsMap.entrySet().iterator();
      	while( iterator.hasNext() )
      	{
      		Map.Entry<String , Object> entry = iterator.next();
      		L.d( TAG , "---- Params Key: " + entry.getKey() + " ----\n---- Params Value: " + entry.getValue() );
      		StringBody sb = new StringBody( new Gson().toJson( entry.getValue() ) , ContentType.APPLICATION_JSON.withCharset( "UTF-8" ) );
      		httpEntity.addPart( entry.getKey() , sb );
      	}
      	httpPost.setEntity( httpEntity );
      }*/
    } else {
      Map<String, Object> paramsMap = request.getParams();
      L.e(TAG, "[Request Params]: " + new Gson().toJson(paramsMap));
      if (paramsMap != null) {
        String bodyJsonString = new Gson().toJson(paramsMap);
        StringEntity entity = null;
        try {
          entity = new StringEntity(bodyJsonString, HTTP.UTF_8);
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }
        httpPost.setEntity(entity);
      }
    }
    Res response = null;
    try {
      HttpResponse httpResponse = httpClient.execute(httpPost);
      try {
        response = (Res) resClass.newInstance().parseResult(httpResponse);
        if (response != null && response.isTokenError()) {
          EventBus.getDefault().post(new ErrorTokenEvent());
        }
      } catch (InstantiationException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return response;
  }
Exemplo n.º 11
0
 public static String doPostJson(String url, String json) {
   return doPostString(url, json, ContentType.APPLICATION_JSON.getMimeType());
 }