org.apache.http.entity.BasicHttpEntity Java Examples

The following examples show how to use org.apache.http.entity.BasicHttpEntity. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConanClient.java    From nexus-repository-conan with Eclipse Public License 1.0 7 votes vote down vote up
public HttpResponse getHttpResponse(final String path) throws IOException {
  try (CloseableHttpResponse closeableHttpResponse = super.get(path)) {
    HttpEntity entity = closeableHttpResponse.getEntity();

    BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
    String content = EntityUtils.toString(entity);
    basicHttpEntity.setContent(IOUtils.toInputStream(content));

    basicHttpEntity.setContentEncoding(entity.getContentEncoding());
    basicHttpEntity.setContentLength(entity.getContentLength());
    basicHttpEntity.setContentType(entity.getContentType());
    basicHttpEntity.setChunked(entity.isChunked());

    StatusLine statusLine = closeableHttpResponse.getStatusLine();
    HttpResponse response = new BasicHttpResponse(statusLine);
    response.setEntity(basicHttpEntity);
    response.setHeaders(closeableHttpResponse.getAllHeaders());
    response.setLocale(closeableHttpResponse.getLocale());
    return response;
  }
}
 
Example #2
Source File: HttpUrlConnStack.java    From simple_net_framework with MIT License 6 votes vote down vote up
/**
 * 执行HTTP请求之后获取到其数据流,即返回请求结果的流
 * 
 * @param connection
 * @return
 */
private HttpEntity entityFromURLConnwction(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream = null;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
        inputStream = connection.getErrorStream();
    }

    // TODO : GZIP 
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());

    return entity;
}
 
Example #3
Source File: GenericApiGatewayClientTest.java    From apigateway-generic-java-sdk with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
    AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider(new BasicAWSCredentials("foo", "bar"));

    mockClient = Mockito.mock(SdkHttpClient.class);
    HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream("test payload".getBytes()));
    resp.setEntity(entity);
    Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class));

    ClientConfiguration clientConfig = new ClientConfiguration();

    client = new GenericApiGatewayClientBuilder()
            .withClientConfiguration(clientConfig)
            .withCredentials(credentials)
            .withEndpoint("https://foobar.execute-api.us-east-1.amazonaws.com")
            .withRegion(Region.getRegion(Regions.fromName("us-east-1")))
            .withApiKey("12345")
            .withHttpClient(new AmazonHttpClient(clientConfig, mockClient, null))
            .build();
}
 
Example #4
Source File: RequestExecutor.java    From vertx-deploy-tools with Apache License 2.0 6 votes vote down vote up
HttpPost createPost(DeployRequest deployRequest, String host) {
    URI deployUri = createDeployUri(host, deployRequest.getEndpoint());
    log.info("Deploying to host : " + deployUri.toString());
    HttpPost post = new HttpPost(deployUri);
    if (!StringUtils.isNullOrEmpty(authToken)) {
        log.info("Adding authToken to request header.");
        post.addHeader("authToken", authToken);
    }

    ByteArrayInputStream bos = new ByteArrayInputStream(deployRequest.toJson(false).getBytes());
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(bos);
    entity.setContentLength(deployRequest.toJson(false).getBytes().length);
    post.setEntity(entity);
    return post;
}
 
Example #5
Source File: RequestParamEndpointTest.java    From RoboZombie with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Test for a {@link Request} with a <b>buffered</b> entity.</p>
 * 
 * @since 1.3.0
 */
@Test
public final void testBufferedHttpEntity() throws ParseException, IOException {
	
	Robolectric.getFakeHttpLayer().interceptHttpRequests(false);
	
	String subpath = "/bufferedhttpentity";
	
	ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
	InputStream inputStream = classLoader.getResourceAsStream("LICENSE.txt");
	InputStream parallelInputStream = classLoader.getResourceAsStream("LICENSE.txt");
	BasicHttpEntity bhe = new BasicHttpEntity();
	bhe.setContent(parallelInputStream);
	
	stubFor(put(urlEqualTo(subpath))
			.willReturn(aResponse()
			.withStatus(200)));
	
	requestEndpoint.bufferedHttpEntity(inputStream);
	
	verify(putRequestedFor(urlEqualTo(subpath))
		   .withRequestBody(equalTo(EntityUtils.toString(new BufferedHttpEntity(bhe)))));
}
 
Example #6
Source File: HttpServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDownloadArtifact() throws IOException, URISyntaxException {
    String url = "http://blah";
    FetchHandler fetchHandler = mock(FetchHandler.class);

    HttpGet mockGetMethod = mock(HttpGet.class);
    CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
    ByteArrayInputStream instream = new ByteArrayInputStream(new byte[]{});
    basicHttpEntity.setContent(instream);
    when(response.getEntity()).thenReturn(basicHttpEntity);
    when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
    when(httpClient.execute(mockGetMethod)).thenReturn(response);
    when(httpClientFactory.createGet(url)).thenReturn(mockGetMethod);

    when(mockGetMethod.getURI()).thenReturn(new URI(url));

    service.download(url, fetchHandler);
    verify(httpClient).execute(mockGetMethod);
    verify(fetchHandler).handle(instream);
}
 
Example #7
Source File: GenericApiGatewayClientTest.java    From apigateway-generic-java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute_non2xx_exception() throws IOException {
    HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 404, "Not found"));
    BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream("{\"message\" : \"error payload\"}".getBytes()));
    resp.setEntity(entity);
    Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class));

    Map<String, String> headers = new HashMap<>();
    headers.put("Account-Id", "fubar");
    headers.put("Content-Type", "application/json");

    try {
        client.execute(
                new GenericApiGatewayRequestBuilder()
                        .withBody(new ByteArrayInputStream("test request".getBytes()))
                        .withHttpMethod(HttpMethodName.POST)
                        .withHeaders(headers)
                        .withResourcePath("/test/orders").build());

        Assert.fail("Expected exception");
    } catch (GenericApiGatewayException e) {
        assertEquals("Wrong status code", 404, e.getStatusCode());
        assertEquals("Wrong exception message", "{\"message\":\"error payload\"}", e.getErrorMessage());
    }
}
 
Example #8
Source File: ApacheHttpResponseBuilder.java    From junit-servers with MIT License 6 votes vote down vote up
@Override
public HttpResponse build() {
	ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
	StatusLine statusLine = new BasicStatusLine(protocolVersion, status, "");
	HttpResponse response = new BasicHttpResponse(statusLine);

	InputStream is = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
	BasicHttpEntity entity = new BasicHttpEntity();
	entity.setContent(is);
	response.setEntity(entity);

	for (Map.Entry<String, List<String>> header : headers.entrySet()) {
		for (String value : header.getValue()) {
			response.addHeader(header.getKey(), value);
		}
	}

	return response;
}
 
Example #9
Source File: HttpPostGet.java    From ApiManager with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String postBody(String url, String body, Map<String, String> headers, int timeout) throws Exception {
    HttpClient client = buildHttpClient(url);
    HttpPost httppost = new HttpPost(url);
    httppost.setHeader("charset", "utf-8");

    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout).setStaleConnectionCheckEnabled(true).build();
    httppost.setConfig(requestConfig);
    buildHeader(headers, httppost);

    BasicHttpEntity requestBody = new BasicHttpEntity();
    requestBody.setContent(new ByteArrayInputStream(body.getBytes("UTF-8")));
    requestBody.setContentLength(body.getBytes("UTF-8").length);
    httppost.setEntity(requestBody);
    // 执行客户端请求
    HttpResponse response = client.execute(httppost);
    HttpEntity entity = response.getEntity();
    return EntityUtils.toString(entity, "UTF-8");
}
 
Example #10
Source File: AsyncHTTPConduit.java    From cxf with Apache License 2.0 6 votes vote down vote up
public AsyncWrappedOutputStream(Message message,
                                boolean needToCacheRequest,
                                boolean isChunking,
                                int chunkThreshold,
                                String conduitName,
                                URI uri) {
    super(message,
          needToCacheRequest,
          isChunking,
          chunkThreshold,
          conduitName,
          uri);
    csPolicy = getClient(message);
    entity = message.get(CXFHttpRequest.class);
    basicEntity = (BasicHttpEntity)entity.getEntity();
    basicEntity.setChunked(isChunking);
    HeapByteBufferAllocator allocator = new HeapByteBufferAllocator();
    int bufSize = csPolicy.getChunkLength() > 0 ? csPolicy.getChunkLength() : 16320;
    inbuf = new SharedInputBuffer(bufSize, allocator);
    outbuf = new SharedOutputBuffer(bufSize, allocator);
    isAsync = outMessage != null && outMessage.getExchange() != null
        && !outMessage.getExchange().isSynchronous();
}
 
Example #11
Source File: HttpServerUtilities.java    From Repeat with Apache License 2.0 6 votes vote down vote up
public static byte[] getPostContent(HttpRequest request) {
	if (!(request instanceof HttpEntityEnclosingRequest)) {
		LOGGER.warning("Unknown request type for POST request " + request.getClass());
		return null;
	}
	HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
	HttpEntity entity = entityRequest.getEntity();
	if (!(entity instanceof BasicHttpEntity)) {
		LOGGER.warning("Unknown entity type for POST request " + entity.getClass());
		return null;
	}
	BasicHttpEntity basicEntity = (BasicHttpEntity) entity;
	ByteArrayOutputStream buffer = new ByteArrayOutputStream();
	try {
		basicEntity.writeTo(buffer);
	} catch (IOException e) {
		LOGGER.log(Level.WARNING, "Failed to read all request content.", e);
		return null;
	}
	return buffer.toByteArray();
}
 
Example #12
Source File: ConfigServerApiImplTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Before
public void initExecutor() throws IOException {
    CloseableHttpClient httpMock = mock(CloseableHttpClient.class);
    when(httpMock.execute(any())).thenAnswer(invocationOnMock -> {
        HttpGet get = (HttpGet) invocationOnMock.getArguments()[0];
        mockLog.append(get.getMethod()).append(" ").append(get.getURI()).append("  ");

        switch (mockReturnCode) {
            case FAIL_RETURN_CODE: throw new RuntimeException("FAIL");
            case TIMEOUT_RETURN_CODE: throw new SocketTimeoutException("read timed out");
        }

        BasicStatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, mockReturnCode, null);
        BasicHttpEntity entity = new BasicHttpEntity();
        String returnMessage = "{\"foo\":\"bar\", \"no\":3, \"error-code\": " + mockReturnCode + "}";
        InputStream stream = new ByteArrayInputStream(returnMessage.getBytes(StandardCharsets.UTF_8));
        entity.setContent(stream);

        CloseableHttpResponse response = mock(CloseableHttpResponse.class);
        when(response.getEntity()).thenReturn(entity);
        when(response.getStatusLine()).thenReturn(statusLine);

        return response;
    });
    configServerApi = ConfigServerApiImpl.createForTestingWithClient(configServers, httpMock);
}
 
Example #13
Source File: HurlStack.java    From SaveVolley with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
 *
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
/*
 *  通过一个 HttpURLConnection 获取其对应的 HttpEntity ( 这里就 HttpEntity 而言,耦合了 Apache )
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    // 设置 HttpEntity 的内容
    entity.setContent(inputStream);
    // 设置 HttpEntity 的长度
    entity.setContentLength(connection.getContentLength());
    // 设置 HttpEntity 的编码
    entity.setContentEncoding(connection.getContentEncoding());
    // 设置 HttpEntity Content-Type
    entity.setContentType(connection.getContentType());
    return entity;
}
 
Example #14
Source File: HurlStack.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes an {@link HttpEntity} from the given
 * {@link HttpURLConnection}.
 * 
 * @param connection
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) {

    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}
 
Example #15
Source File: AuthenticationHandlerTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
private CloseableHttpResponse getValidationResponse() throws UnsupportedEncodingException {
    ValidationResponce response = new ValidationResponce();
    response.setDeviceId("1234");
    response.setDeviceType("testdevice");
    response.setJWTToken("1234567788888888");
    response.setTenantId(-1234);
    Gson gson = new Gson();
    String jsonReponse = gson.toJson(response);
    CloseableHttpResponse mockDCRResponse = new MockHttpResponse();
    BasicHttpEntity responseEntity = new BasicHttpEntity();
    responseEntity.setContent(new ByteArrayInputStream(jsonReponse.getBytes(StandardCharsets.UTF_8.name())));
    responseEntity.setContentType(TestUtils.CONTENT_TYPE);
    mockDCRResponse.setEntity(responseEntity);
    mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK"));
    return mockDCRResponse;
}
 
Example #16
Source File: ClientImpl.java    From datamill with ISC License 6 votes vote down vote up
private CloseableHttpResponse doWithEntity(Body body, CloseableHttpClient httpClient, HttpUriRequest request) throws IOException {
    if (!(request instanceof HttpEntityEnclosingRequestBase)) {
        throw new IllegalArgumentException("Expecting to write an body for a request type that does not support it!");
    }

    PipedOutputStream pipedOutputStream = buildPipedOutputStream();
    PipedInputStream pipedInputStream = buildPipedInputStream();

    pipedInputStream.connect(pipedOutputStream);

    BasicHttpEntity httpEntity = new BasicHttpEntity();
    httpEntity.setContent(pipedInputStream);
    ((HttpEntityEnclosingRequestBase) request).setEntity(httpEntity);

    writeEntityOutOverConnection(body, pipedOutputStream);

    return doExecute(httpClient, request);
}
 
Example #17
Source File: HttpKnife.java    From WeGit with Apache License 2.0 6 votes vote down vote up
/**
 * 获取响应报文实体
 * 
 * @return
 * @throws IOException
 */
private HttpEntity entityFromConnection() throws IOException {
	BasicHttpEntity entity = new BasicHttpEntity();
	InputStream inputStream;
	try {
		inputStream = connection.getInputStream();
	} catch (IOException ioe) {
		inputStream = connection.getErrorStream();
	}
	if (GZIP.equals(getResponseheader(ResponseHeader.HEADER_CONTENT_ENCODING))) {
		entity.setContent(new GZIPInputStream(inputStream));
	} else {
		entity.setContent(inputStream);
	}
	entity.setContentLength(connection.getContentLength());
	entity.setContentEncoding(connection.getContentEncoding());
	entity.setContentType(connection.getContentType());
	return entity;
}
 
Example #18
Source File: HurlStack.java    From volley with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
 * @param connection
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    
    return entity;
}
 
Example #19
Source File: StoryWebServiceControllerTest.java    From ezScrum with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testAddExistedTask() throws Exception {
	// create 3 tasks in project
	TaskObject task1 = new TaskObject(mProject.getId());
	task1.setName("TASK_NAME1").save();
	
	TaskObject task2 = new TaskObject(mProject.getId());
	task2.setName("TASK_NAME2").save();
	
	TaskObject task3 = new TaskObject(mProject.getId());
	task3.setName("TASK_NAME3").save();
	
	// initial request data,add task#1 & #3 to story#1
	StoryObject story = mASTS.getStories().get(0);
	String taskIdJsonString = String.format("[%s, %s]", task1.getId(), task2.getId());
	String URL = String.format(API_URL, mProjectName, story.getId() + "/add-existed-task", mUsername, mPassword);
	BasicHttpEntity entity = new BasicHttpEntity();
	entity.setContent(new ByteArrayInputStream(taskIdJsonString.getBytes()));
	entity.setContentEncoding("utf-8");
	HttpPost httpPost = new HttpPost(URL);
	httpPost.setEntity(entity);
	mHttpClient.execute(httpPost);
	
	story.reload();
	assertEquals(2, story.getTasks().size());
}
 
Example #20
Source File: OkHttpStack.java    From wasp with Apache License 2.0 5 votes vote down vote up
private static HttpEntity entityFromOkHttpResponse(Response response) throws IOException {
  BasicHttpEntity entity = new BasicHttpEntity();
  ResponseBody body = response.body();

  entity.setContent(body.byteStream());
  entity.setContentLength(body.contentLength());
  entity.setContentEncoding(response.header("Content-Encoding"));

  if (body.contentType() != null) {
    entity.setContentType(body.contentType().type());
  }
  return entity;
}
 
Example #21
Source File: ProductBacklogWebServiceControllerTest.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testCreateStory() throws Exception {
	JSONObject storyJson = new JSONObject();
	storyJson
		.put("name", "TEST_STORY")
		.put("importance", 100)
		.put("estimate", 2)
		.put("value", 50)
		.put("how_to_demo", "TEST_STORY_DEMO")
		.put("notes", "TEST_STORY_NOTE")
		.put("status", 1)
		.put("sprint_id", -1)
		.put("tags", "");
	
	// send request to create a story
	String URL = String.format(API_URL, mProjectName, "create", mUsername, mPassword);
	HttpPost httpPost = new HttpPost(URL);
	BasicHttpEntity entity = new BasicHttpEntity();
	entity.setContent(new ByteArrayInputStream(storyJson.toString().getBytes(StandardCharsets.UTF_8)));
	entity.setContentEncoding("utf-8");
	httpPost.setEntity(entity);
	HttpResponse httpResponse = mHttpClient.execute(httpPost);
	String response = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
	
	// assert result
	ProductBacklogHelper productBacklogHelper = new ProductBacklogHelper(mProject);
	ArrayList<StoryObject> stories = productBacklogHelper.getStories();
	assertEquals(4, stories.size());
	
	JSONObject responseJson = new JSONObject(response);
	assertEquals("SUCCESS", responseJson.getString("status"));
	assertEquals(stories.get(stories.size() - 1).getId(), responseJson.getLong("storyId"));
}
 
Example #22
Source File: StoryApiTest.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testPost() throws Exception {
	// 預設已經新增五個 stories
	ArrayList<StoryObject> stories = mProject.getStories();
	assertEquals(5, stories.size());

	// initial request data
	JSONObject storyJson = new JSONObject();
	storyJson.put("name", "TEST_NAME").put("notes", "TEST_NOTES")
			.put("how_to_demo", "TEST_HOW_TO_DEMO").put("importance", 99)
			.put("value", 15).put("estimate", 21).put("status", 0)
			.put("sprint_id", -1).put("tags", "")
			.put("project_name", mProject.getName());

	BasicHttpEntity entity = new BasicHttpEntity();
	entity.setContent(new ByteArrayInputStream(storyJson.toString()
			.getBytes()));
	entity.setContentEncoding("utf-8");
	HttpPost httpPost = new HttpPost(API_URL);
	httpPost.setEntity(entity);
	setHeaders(httpPost, mAccountId, mPlatformType);
	HttpResponse httpResponse = mClient.execute(httpPost);
	String result = EntityUtils.toString(httpResponse.getEntity());
	JSONObject response = new JSONObject(result);

	// 新增一個 story,project 內的 story 要有六個
	stories = mProject.getStories();
	assertEquals(6, stories.size());
	// 對回傳的 JSON 做 assert
	assertEquals("SUCCESS", response.getString("status"));
	assertEquals(stories.get(stories.size() - 1).getId(),
			response.getLong("storyId"));
}
 
Example #23
Source File: TaskApiTest.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testPut() throws JSONException, ParseException, ClientProtocolException, IOException {
	TaskObject task = mATTS.getTasks().get(0);
	
	// test data
	String TEST_TASK_NAME = "TEST_TASK_NAME_NEW";
	String TEST_TASK_NOTES = "TEST_TASK_NOTES_NEW";
	long TEST_TASK_STORY_ID = -1;
	int TEST_TASK_ESTIMATE = 8;
	int TEST_TASK_REMAIN = 8;

	// initial request data
	JSONObject taskJson = new JSONObject();
	taskJson.put(TaskEnum.ID, task.getId())
	        .put(TaskEnum.NAME, TEST_TASK_NAME)
	        .put(TaskEnum.NOTES, TEST_TASK_NOTES)
	        .put(TaskEnum.ESTIMATE, TEST_TASK_ESTIMATE)
	        .put(TaskEnum.STORY_ID, TEST_TASK_STORY_ID)
	        .put(TaskEnum.REMAIN, TEST_TASK_REMAIN)
	        .put(TaskEnum.HANDLER_ID, mAccountId)
	        .put("project_name", mProject.getName());
	
	BasicHttpEntity entity = new BasicHttpEntity();
	entity.setContent(new ByteArrayInputStream(taskJson.toString().getBytes()));
	entity.setContentEncoding(StandardCharsets.UTF_8.name());
	HttpPut httpPut = new HttpPut(API_URL + "/" + task.getId());
	httpPut.setEntity(entity);
	setHeaders(httpPut, mAccountId, mPlatformType);
	String result = EntityUtils.toString(mClient.execute(httpPut).getEntity(), StandardCharsets.UTF_8);
	JSONObject response = new JSONObject(result);
	
	// assert
	assertEquals(TEST_TASK_NAME, response.getString(TaskEnum.NAME));
	assertEquals(TEST_TASK_NOTES, response.getString(TaskEnum.NOTES));
	assertEquals(TEST_TASK_ESTIMATE, response.getInt(TaskEnum.ESTIMATE));
	assertEquals(TEST_TASK_REMAIN, response.getInt(TaskEnum.REMAIN));
}
 
Example #24
Source File: HurlStack.java    From DaVinci with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
 * @param connection
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}
 
Example #25
Source File: StoryApiTest.java    From ezScrum with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testPut() throws JSONException, ParseException,
		ClientProtocolException, IOException {
	StoryObject story = mCPB.getStories().get(0);
	// initial request data
	JSONObject storyJson = new JSONObject();
	storyJson.put("id", story.getId()).put("name", "顆顆").put("notes", "崩潰")
			.put("how_to_demo", "做不完").put("importance", 99)
			.put("value", 15).put("estimate", 21).put("status", 0)
			.put("sprint_id", -1).put("tags", "")
			.put("project_name", mProject.getName());

	BasicHttpEntity entity = new BasicHttpEntity();
	entity.setContent(new ByteArrayInputStream(storyJson.toString()
			.getBytes()));
	entity.setContentEncoding("utf-8");
	HttpPut httpPut = new HttpPut(API_URL + "/" + story.getId());
	httpPut.setEntity(entity);
	setHeaders(httpPut, mAccountId, mPlatformType);
	HttpResponse httpResponse = mClient.execute(httpPut);
	String result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
	
	System.out.println(result);
	JSONObject response = new JSONObject(result);

	assertEquals(storyJson.getLong("id"), response.getLong("id"));
	assertEquals(storyJson.getString("name"), response.getString("name"));
	assertEquals(storyJson.getString("notes"), response.getString("notes"));
	assertEquals(storyJson.getString("how_to_demo"),
			response.getString("how_to_demo"));
	assertEquals(storyJson.getInt("importance"),
			response.getInt("importance"));
	assertEquals(storyJson.getInt("value"), response.getInt("value"));
	assertEquals(storyJson.getInt("estimate"), response.getInt("estimate"));
	assertEquals(storyJson.getInt("status"), response.getInt("status"));
	assertEquals(storyJson.getLong("sprint_id"),
			response.getLong("sprint_id"));
	assertEquals(7, response.getJSONArray("histories").length());
	assertEquals(0, response.getJSONArray("tags").length());
}
 
Example #26
Source File: HurlStack.java    From volley_demo with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
 * @param connection
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}
 
Example #27
Source File: BlockingConditionRetrieverTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void run() throws Exception {

    String content = "{\"api\":[\"/pizzashack/1.0.0\"],\"application\":[\"admin:DefaultApplication\"]," +
            "\"ip\":[{\"fixedIp\":\"127.0.0.1\",\"invert\":false,\"type\":\"IP\",\"tenantDomain\":\"carbon" +
            ".super\"}],\"user\":[\"admin\"],\"custom\":[]}";
    PowerMockito.mockStatic(APIUtil.class);
    HttpClient httpClient = Mockito.mock(HttpClient.class);
    HttpResponse httpResponse = Mockito.mock(HttpResponse.class);
    BasicHttpEntity httpEntity = new BasicHttpEntity();
    httpEntity.setContent(new ByteArrayInputStream(content.getBytes()));
    Mockito.when(httpResponse.getEntity()).thenReturn(httpEntity);
    Mockito.when(httpClient.execute(Mockito.any(HttpGet.class))).thenReturn(httpResponse);
    BDDMockito.given(APIUtil.getHttpClient(Mockito.anyInt(), Mockito.anyString())).willReturn(httpClient);
    EventHubConfigurationDto eventHubConfigurationDto = new EventHubConfigurationDto();
    eventHubConfigurationDto.setUsername("admin");
    eventHubConfigurationDto.setPassword("admin".toCharArray());
    eventHubConfigurationDto.setEnabled(true);
    eventHubConfigurationDto.setServiceUrl("http://localhost:18083/internal/data/v1");
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();
    BlockingConditionRetriever blockingConditionRetriever =
            new BlockingConditionRetrieverWrapper(eventHubConfigurationDto, throttleDataHolder);
    blockingConditionRetriever.run();
    Assert.assertTrue(throttleDataHolder.isRequestBlocked("/pizzashack/1.0.0", "admin:DefaultApplication",
            "admin", "127.0.0.1", "carbon.super",
            "/pizzashack/1.0.0:1.0.0:admin-DefaultApplication"));
}
 
Example #28
Source File: KeyTemplateRetrieverTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void run() throws Exception {
    Map map = new HashMap();
    map.put("$userId","$userId");
    map.put("$apiContext","$apiContext");
    map.put("$apiVersion","$apiVersion");
    String content = "[\"$userId\",\"$apiContext\",\"$apiVersion\"]";
    PowerMockito.mockStatic(APIUtil.class);
    HttpClient httpClient = Mockito.mock(HttpClient.class);
    HttpResponse httpResponse = Mockito.mock(HttpResponse.class);
    BasicHttpEntity httpEntity = new BasicHttpEntity();
    httpEntity.setContent(new ByteArrayInputStream(content.getBytes()));
    Mockito.when(httpResponse.getEntity()).thenReturn(httpEntity);
    Mockito.when(httpClient.execute(Mockito.any(HttpGet.class))).thenReturn(httpResponse);
    BDDMockito.given(APIUtil.getHttpClient(Mockito.anyInt(),Mockito.anyString())).willReturn(httpClient);

    EventHubConfigurationDto eventHubConfigurationDto = new EventHubConfigurationDto();
    eventHubConfigurationDto.setUsername("admin");
    eventHubConfigurationDto.setPassword("admin".toCharArray());
    eventHubConfigurationDto.setEnabled(true);
    eventHubConfigurationDto.setServiceUrl("http://localhost:18084/internal/data/v1");
    ThrottleDataHolder throttleDataHolder = new ThrottleDataHolder();
    KeyTemplateRetriever keyTemplateRetriever = new KeyTemplateRetrieverWrapper(eventHubConfigurationDto,
            throttleDataHolder);
    keyTemplateRetriever.run();
    Map<String,String> keyTemplateMap = throttleDataHolder.getKeyTemplateMap();
    Assert.assertNotNull(keyTemplateMap);
    Assert.assertEquals(map,keyTemplateMap);
}
 
Example #29
Source File: HurlStack.java    From jus with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
 * @param connection
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}
 
Example #30
Source File: OkHttpStack.java    From something.apk with MIT License 5 votes vote down vote up
/**
 * Initializes an {@link org.apache.http.HttpEntity} from the given {@link HttpURLConnection}.
 * @param connection
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}