org.apache.http.entity.StringEntity Java Examples

The following examples show how to use org.apache.http.entity.StringEntity. 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: AmforeasRestClient.java    From amforeas with GNU General Public License v3.0 6 votes vote down vote up
public Optional<AmforeasResponse> add (String resource, String json) {
    final URI url = this.build(String.format(resource_path, root, alias, resource)).orElseThrow();
    final HttpPost req = new HttpPost(url);
    req.addHeader(this.accept);
    req.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);

    try {
        req.setEntity(new StringEntity(json));
    } catch (UnsupportedEncodingException e) {
        final String msg = "Failed to encode JSON body " + e.getMessage();
        l.error(msg);
        return Optional.of(new ErrorResponse(resource, Response.Status.BAD_REQUEST, msg));
    }

    return this.execute(req);
}
 
Example #2
Source File: TwitterSecurityTest.java    From streams with Apache License 2.0 6 votes vote down vote up
@Test
public void testProcess() throws Exception {
  URI testURI = new URIBuilder()
      .setPath("/1/statuses/update.json")
      .setParameter("include_entities", "true")
      .build();
  HttpPost testRequest = new HttpPost(testURI);
  testRequest.setEntity(new StringEntity("status="+security.encode("Hello Ladies + Gentlemen, a signed OAuth request!")));
  HttpHost host = new HttpHost("api.twitter.com", -1, "https");
  HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(testRequest, host);
  TwitterOAuthConfiguration testOauthConfiguration = new TwitterOAuthConfiguration()
      .withConsumerKey("xvz1evFS4wEEPTGEFPHBog")
      .withConsumerSecret("kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw")
      .withAccessToken("370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb")
      .withAccessTokenSecret("LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE");
  TwitterOAuthRequestInterceptor interceptor = Mockito.spy(new TwitterOAuthRequestInterceptor(testOauthConfiguration));
  Mockito.when(interceptor.generateNonce()).thenReturn("kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg");
  Mockito.when(interceptor.generateTimestamp()).thenReturn("1318622958");
  interceptor.process(wrapper, new HttpCoreContext());
  assertEquals(1, wrapper.getHeaders("Authorization").length);
  String actual = wrapper.getFirstHeader("Authorization").getValue();
  String expected = "OAuth oauth_consumer_key=\"xvz1evFS4wEEPTGEFPHBog\", oauth_nonce=\"kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg\", oauth_signature=\"tnnArxj06cWHq44gCs1OSKk%2FjLY%3D\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1318622958\", oauth_token=\"370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb\", oauth_version=\"1.0\"";
  assertEquals(expected, actual);
}
 
Example #3
Source File: CatalogServiceImpl.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
private static StringEntity generateSoapQuery(final String pathSpecs, final int queryOptions) {
    final StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("<?xml version='1.0' encoding='UTF-8'?>"); //$NON-NLS-1$
    stringBuilder.append("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");//$NON-NLS-1$
    stringBuilder.append("<soap:Body xmlns=\"http://microsoft.com/webservices/\">");//$NON-NLS-1$
    stringBuilder.append("<QueryNodes>");//$NON-NLS-1$
    stringBuilder.append("<pathSpecs>");//$NON-NLS-1$
    stringBuilder.append("<string>" + pathSpecs + "</string>");//$NON-NLS-1$ //$NON-NLS-2$
    stringBuilder.append("</pathSpecs>");//$NON-NLS-1$
    stringBuilder.append("<queryOptions>" + queryOptions + "</queryOptions>");//$NON-NLS-1$
    stringBuilder.append("</QueryNodes>");//$NON-NLS-1$
    stringBuilder.append("</soap:Body>");//$NON-NLS-1$
    stringBuilder.append("</soap:Envelope>");//$NON-NLS-1$

    final StringEntity stringEntity = new StringEntity(stringBuilder.toString(), ContentType.create("application/soap+xml", "utf-8"));//$NON-NLS-1$ //$NON-NLS-2$
    return stringEntity;
}
 
Example #4
Source File: EmbeddedElasticsearchPolicy.java    From calcite with Apache License 2.0 6 votes vote down vote up
void insertBulk(String index, List<ObjectNode> documents) throws IOException {
  Objects.requireNonNull(index, "index");
  Objects.requireNonNull(documents, "documents");

  if (documents.isEmpty()) {
    // nothing to process
    return;
  }

  List<String> bulk = new ArrayList<>(documents.size() * 2);
  for (ObjectNode doc: documents) {
    bulk.add(String.format(Locale.ROOT, "{\"index\": {\"_index\":\"%s\"}}", index));
    bulk.add(mapper().writeValueAsString(doc));
  }

  final StringEntity entity = new StringEntity(String.join("\n", bulk) + "\n",
      ContentType.APPLICATION_JSON);

  final Request r = new Request("POST", "/_bulk?refresh");
  r.setEntity(entity);
  restClient().performRequest(r);
}
 
Example #5
Source File: BindingsRestApiTest.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "bindingData")
public void testCreateBindingWithInvalidExchange(String queueName, String bindingPattern)
        throws IOException, TimeoutException {
    Channel channel = amqpConnection.createChannel();
    channel.queueDeclare(queueName, false, false, false, new HashMap<>());
    channel.close();
    String exchangeName = "InvalidExchange";
    HttpPost httpPost = new HttpPost(apiBasePath + "/queues/" + queueName + "/bindings");
    ClientHelper.setAuthHeader(httpPost, username, password);
    BindingCreateRequest createRequest = new BindingCreateRequest().bindingPattern(bindingPattern)
                                                                 .exchangeName(exchangeName);

    String payloadString = objectMapper.writeValueAsString(createRequest);
    StringEntity stringEntity = new StringEntity(payloadString, ContentType.APPLICATION_JSON);
    httpPost.setEntity(stringEntity);

    CloseableHttpResponse response = client.execute(httpPost);

    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_BAD_REQUEST);

    Error error = HttpClientHelper.getResponseMessage(response, Error.class);

    Assert.assertFalse(error.getMessage().isEmpty());
}
 
Example #6
Source File: MDSApiClient.java    From kafka-topology-builder with MIT License 6 votes vote down vote up
/**
 * Remove the role (cluster or resource scoped) from the principal at the given scope/cluster.
 * No-op if the user doesn’t have the role. Callable by Admins.
 *
 * @param principal Fully-qualified KafkaPrincipal string for a user or group.
 * @param role The name of the role.
 * @param scope The request scope
 */
public void deleteRole(String principal, String role, RequestScope scope) {
  HttpDeleteWithBody request =
      new HttpDeleteWithBody(
          mdsServer + "/security/1.0/principals/" + principal + "/roles/" + role);
  request.addHeader("accept", " application/json");
  request.addHeader("Content-Type", "application/json");
  request.addHeader("Authorization", "Basic " + basicCredentials);
  LOGGER.debug("deleteRole: " + request.getURI());
  try {
    request.setEntity(new StringEntity(scope.asJson()));
    LOGGER.debug("bind.entity: " + scope.asJson());
    delete(request);
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example #7
Source File: ElasticsearchTransport.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Fetches search results given a scrollId.
 */
Function<String, ElasticsearchJson.Result> scroll() {
  return scrollId -> {
    // fetch next scroll
    final HttpPost request = new HttpPost(URI.create("/_search/scroll"));
    final ObjectNode payload = mapper.createObjectNode()
        .put("scroll", "1m")
        .put("scroll_id", scrollId);

    try {
      final String json = mapper.writeValueAsString(payload);
      request.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
      return rawHttp(ElasticsearchJson.Result.class).apply(request);
    } catch (IOException e) {
      String message = String.format(Locale.ROOT, "Couldn't fetch next scroll %s", scrollId);
      throw new UncheckedIOException(message, e);
    }
  };

}
 
Example #8
Source File: Checks.java    From gerrit-code-review-plugin with Apache License 2.0 6 votes vote down vote up
public CheckInfo rerun(String checkerUuid, RerunInput input) throws RestApiException {
  try {
    HttpPost request = new HttpPost(buildRequestUrl(checkerUuid + "/rerun"));
    String inputString =
        JsonBodyParser.createRequestBody(input, new TypeToken<RerunInput>() {}.getType());
    request.setEntity(new StringEntity(inputString));
    request.setHeader("Content-type", "application/json");
    try (CloseableHttpResponse response = client.execute(request)) {
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return JsonBodyParser.parseResponse(
            EntityUtils.toString(response.getEntity()), new TypeToken<CheckInfo>() {}.getType());
      }
      throw new RestApiException(
          String.format(
              "Request failed with status: %d", response.getStatusLine().getStatusCode()));
    }
  } catch (Exception e) {
    throw new RestApiException("Could not rerun check", e);
  }
}
 
Example #9
Source File: AzkabanAjaxAPIClient.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
private static HttpPost preparePostRequest(String requestUrl, String sessionId, Map<String, String> params)
    throws IOException {
  // Create post request
  HttpPost postRequest = new HttpPost(requestUrl);
  StringBuilder stringEntityBuilder = new StringBuilder();
  stringEntityBuilder.append(String.format("session.id=%s", sessionId));
  for (Map.Entry<String, String> entry : params.entrySet()) {
    if (stringEntityBuilder.length() > 0) {
      stringEntityBuilder.append("&");
    }
    stringEntityBuilder.append(String.format("%s=%s", entry.getKey(), entry.getValue()));
  }
  StringEntity input = new StringEntity(stringEntityBuilder.toString());
  input.setContentType("application/x-www-form-urlencoded");
  postRequest.setEntity(input);
  postRequest.setHeader("X-Requested-With", "XMLHttpRequest");

  return postRequest;
}
 
Example #10
Source File: HttpsAdminServerTest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testForceAssignNewToken() throws Exception {
    login(admin.email, admin.pass);
    HttpGet request = new HttpGet(httpsAdminServerUrl + "/users/token/[email protected]&app=Blynk&dashId=79780619&deviceId=0&new=123");

    try (CloseableHttpResponse response = httpclient.execute(request)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
    }

    HttpPut put = new HttpPut(httpServerUrl + "123/update/v10");
    put.setEntity(new StringEntity("[\"100\"]", ContentType.APPLICATION_JSON));

    try (CloseableHttpResponse response = httpclient.execute(put)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
    }

    HttpGet get = new HttpGet(httpServerUrl + "123/get/v10");

    try (CloseableHttpResponse response = httpclient.execute(get)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        List<String> values = TestUtil.consumeJsonPinValues(response);
        assertEquals(1, values.size());
        assertEquals("100", values.get(0));
    }
}
 
Example #11
Source File: RemoteRegistrationRequesterTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldPassAllParametersToPostForRegistrationOfNonElasticAgent() throws IOException {
    String url = "http://cruise.com/go";
    GoAgentServerHttpClient httpClient = mock(GoAgentServerHttpClient.class);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    final ProtocolVersion protocolVersion = new ProtocolVersion("https", 1, 2);
    when(response.getStatusLine()).thenReturn(new BasicStatusLine(protocolVersion, HttpStatus.OK.value(), null));
    when(response.getEntity()).thenReturn(new StringEntity(""));
    when(httpClient.execute(isA(HttpRequestBase.class))).thenReturn(response);
    final DefaultAgentRegistry defaultAgentRegistry = new DefaultAgentRegistry();
    Properties properties = new Properties();
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_KEY, "t0ps3cret");
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_RESOURCES, "linux, java");
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_ENVIRONMENTS, "uat, staging");
    properties.put(AgentAutoRegistrationPropertiesImpl.AGENT_AUTO_REGISTER_HOSTNAME, "agent01.example.com");

    remoteRegistryRequester(url, httpClient, defaultAgentRegistry, 200).requestRegistration("cruise.com", new AgentAutoRegistrationPropertiesImpl(null, properties));
    verify(httpClient).execute(argThat(hasAllParams(defaultAgentRegistry.uuid(), "", "")));
}
 
Example #12
Source File: TokenDemo.java    From ais-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * 二维码识别,使用Base64编码后的文件方式,使用Token认证方式访问服务
 * @param token token认证串
 * @param formFile 文件路径
 * @throws IOException
 */
public static void requestOcrQRCodeBase64(String token, String formFile) {

	// 1.构建二维码识别服务所需要的参数
	String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/qr-code";
	Header[] headers = new Header[] {new BasicHeader("X-Auth-Token", token), new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString()) };
	try {
		byte[] fileData = FileUtils.readFileToByteArray(new File(formFile));
		String fileBase64Str = Base64.encodeBase64String(fileData);
		JSONObject json = new JSONObject();
		json.put("image", fileBase64Str);
		StringEntity stringEntity = new StringEntity(json.toJSONString(), "utf-8");

		// 2.传入二维码识别服务对应的参数, 使用POST方法调用服务并解析输出识别结果
		HttpResponse response = HttpClientUtils.post(url, headers, stringEntity);
		System.out.println(response);
		String content = IOUtils.toString(response.getEntity().getContent());
		System.out.println(content);
	} catch (Exception e) {
		e.printStackTrace();
	}

}
 
Example #13
Source File: GalaxyFDSClient.java    From galaxy-fds-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public void putDomainMapping(String bucketName, String domainName, String indexName)
    throws GalaxyFDSClientException {
  ContentType contentType = ContentType.APPLICATION_JSON;
  URI uri = formatUri(fdsConfig.getBaseUri(), bucketName, (SubResource[]) null);
  HashMap<String, String> params = new HashMap<String, String>();
  params.put("domain", domainName);
  params.put("index", indexName);
  StringEntity requestEntity = getJsonStringEntity("", contentType);
  HttpUriRequest httpRequest = fdsHttpClient.prepareRequestMethod(uri, HttpMethod.PUT,
    contentType, null, params, null, requestEntity);

  HttpResponse response = fdsHttpClient.executeHttpRequest(httpRequest, Action.PutDomainMapping);

  fdsHttpClient.processResponse(response, null,
    "add domain mapping; bucket [" + bucketName + "], domainName [" + domainName + "]");
}
 
Example #14
Source File: RESTServiceConnectorTest.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteCreateObjectWithParameters() throws Exception {
    final TestPojo newObject = new TestPojo();
    newObject.setField("newValue");
    final String newObjectJson = gson.toJson(newObject);
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getEntity()).thenReturn(new StringEntity(newObjectJson));
    when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
    final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
    when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
    final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
    final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build();

    final TestPojo object = connector.executeCreateObject(newObject, "/somepath", DEFAULT_TEST_PARAMETERS);

    assertThat(object, notNullValue());
    assertThat(object, equalTo(newObject));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("POST"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg2=val2"), any(HttpClientContext.class));
    verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg1=val1"), any(HttpClientContext.class));
    verify(response).close();
}
 
Example #15
Source File: QueryBuilderCommon.java    From MultiChainJavaAPI with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 
 * @param command
 * @param parameters
 * 
 * @return
 * 
 *         example : MultichainQueryBuidlder.executeProcess(MultichainCommand .SENDTOADDRESS,
 *         "1EyXuq2JVrj4E3CpM9iNGNSqBpZ2iTPdwGKgvf {\"rdcoin\":0.01}"
 * @throws MultichainException
 */
protected Object execute(CommandElt command, Object... parameters) throws MultichainException {

  if (httpclient != null && httppost != null) {
    try {
      // Generate Mapping of calling arguments
      Map<String, Object> entityValues = prepareMap(this.queryParameters, command, parameters);
      // Generate the entity and initialize request
      StringEntity rpcEntity = prepareRpcEntity(entityValues);
      httppost.setEntity(rpcEntity);
      // Execute the request and get the answer
      return executeRequest();

    } catch (IOException e) {
      e.printStackTrace();
      throw new MultichainException(null, e.toString());
    }
  } else {
    throw new MultichainException("Initialization Problem",
        "MultiChainCommand not initialized, please specify ip, port, user and pwd !");
  }
}
 
Example #16
Source File: GremlinServerHttpIntegrateTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void should200OnPOSTTransactionalGraphInStrictMode() throws Exception {
    assumeNeo4jIsPresent();

    final CloseableHttpClient httpclient = HttpClients.createDefault();
    final HttpPost httppost = new HttpPost(TestClientFactory.createURLString());
    httppost.addHeader("Content-Type", "application/json");
    httppost.setEntity(new StringEntity("{\"gremlin\":\"g1.addV()\",\"aliases\":{\"g1\":\"g\"}}", Consts.UTF_8));

    try (final CloseableHttpResponse response = httpclient.execute(httppost)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("application/json", response.getEntity().getContentType().getValue());
        final String json = EntityUtils.toString(response.getEntity());
        final JsonNode node = mapper.readTree(json);
        assertEquals(1, node.get("result").get("data").get(GraphSONTokens.VALUEPROP).size());
    }
}
 
Example #17
Source File: CaseInstanceResourceTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@CmmnDeployment(resources = { "org/flowable/cmmn/rest/service/api/runtime/testManualEvaluateCriteria.cmmn" })
public void testEvaluateCriteria() throws Exception {
    CaseInstance caseInstance = runtimeService.createCaseInstanceBuilder()
            .caseDefinitionKey("testManualEvaluateCriteria")
            .variable("someBean", new TestBean())
            .start();

    // Triggering the evaluation twice will satisfy the entry criterion for B
    assertThat(runtimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance.getId()).planItemInstanceStateActive().count()).isEqualTo(1);

    String url = buildUrl(CmmnRestUrls.URL_CASE_INSTANCE, caseInstance.getId());
    HttpPut httpPut = new HttpPut(url);

    httpPut.setEntity(new StringEntity("{\"action\": \"evaluateCriteria\"}"));
    executeRequest(httpPut, HttpStatus.SC_OK);

    assertThat(runtimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance.getId()).planItemInstanceStateActive().count()).isEqualTo(1);

    TestBean.RETURN_VALUE = true;
    executeRequest(httpPut, HttpStatus.SC_OK);

    assertThat(runtimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance.getId()).planItemInstanceStateActive().count()).isEqualTo(2);
}
 
Example #18
Source File: LoadData.java    From elastic-rabbitmq with MIT License 6 votes vote down vote up
public ESBulkResponse doBulkRequest(String body) {
    try {
        HttpEntity requestBody = new StringEntity(body);
        Response response = client.performRequest(
                "POST",
                ESConstants.STORE_INDEX + "/" + ESConstants.PRODUCT_TYPE + "/_bulk",
                new HashMap<String, String>(),
                requestBody);

        ESBulkResponse esResponse = gson.fromJson(IOUtils.toString(response.getEntity().getContent()),
                ESBulkResponse.class);
        return esResponse;
    } catch (IOException e) {
        logger.error("Error bulk request " + e);
    }

    return null;
}
 
Example #19
Source File: PacHttpUtils.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param rest
 *            URL for POST method
 * @return String
 * @throws Exception
 */
public static String doHttpPost(final String url, final String requestBody) throws Exception {
	try {

		HttpClient client = HttpClientBuilder.create().build();
		HttpPost httppost = new HttpPost(url);
		httppost.setHeader(CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
		StringEntity jsonEntity = new StringEntity(requestBody);
		httppost.setEntity(jsonEntity);
		HttpResponse httpresponse = client.execute(httppost);
		int statusCode = httpresponse.getStatusLine().getStatusCode();
		if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
			return EntityUtils.toString(httpresponse.getEntity());
		} else {
			LOGGER.error(requestBody);
			throw new Exception(
					"unable to execute post request because " + httpresponse.getStatusLine().getReasonPhrase());
		}
	} catch (ParseException parseException) {
		LOGGER.error("error closing issue" + parseException);
		throw parseException;
	} catch (Exception exception) {
		LOGGER.error("error closing issue" + exception.getMessage());
		throw exception;
	}
}
 
Example #20
Source File: Checks.java    From gerrit-code-review-plugin with Apache License 2.0 6 votes vote down vote up
private CheckInfo performCreateOrUpdate(CheckInput input)
    throws RestApiException, URISyntaxException, ParseException, IOException {
  HttpPost request = new HttpPost(buildRequestUrl());
  String inputString =
      JsonBodyParser.createRequestBody(input, new TypeToken<CheckInput>() {}.getType());
  request.setEntity(new StringEntity(inputString));
  request.setHeader("Content-type", "application/json");

  try (CloseableHttpResponse response = client.execute(request)) {
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
      return JsonBodyParser.parseResponse(
          EntityUtils.toString(response.getEntity()), new TypeToken<CheckInfo>() {}.getType());
    }
    throw new RestApiException(
        String.format("Request returned status %s", response.getStatusLine().getStatusCode()));
  }
}
 
Example #21
Source File: RestClient.java    From kylin with Apache License 2.0 6 votes vote down vote up
private boolean setCache(boolean flag) throws IOException {
    String url = baseUrl + "/admin/config";
    HttpPut put = newPut(url);
    HttpResponse response = null;
    try {
        HashMap<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("key", "kylin.query.cache-enabled");
        paraMap.put("value", flag + "");
        put.setEntity(new StringEntity(new ObjectMapper().writeValueAsString(paraMap), UTF_8));
        response = client.execute(put);
        EntityUtils.consume(response.getEntity());
        if (response.getStatusLine().getStatusCode() != 200) {
            return false;
        } else {
            return true;
        }
    } finally {
        cleanup(put, response);
    }
}
 
Example #22
Source File: DingtalkChatbotClient.java    From beihu-boot with Apache License 2.0 6 votes vote down vote up
public SendResult send(Message message) throws IOException {
    HttpPost httppost = new HttpPost(webhook);
    httppost.addHeader("Content-Type", "application/json; charset=utf-8");
    StringEntity se = new StringEntity(message.toJsonString(), "utf-8");
    httppost.setEntity(se);
    SendResult sendResult = new SendResult();
    HttpResponse response = this.httpclient.execute(httppost);
    if (response.getStatusLine().getStatusCode() == 200) {
        String result = EntityUtils.toString(response.getEntity());
        JSONObject obj = JSONObject.parseObject(result);
        Integer errcode = obj.getInteger("errcode");
        sendResult.setErrorCode(errcode);
        sendResult.setErrorMsg(obj.getString("errmsg"));
        sendResult.setIsSuccess(errcode.equals(0));
    }
    return sendResult;
}
 
Example #23
Source File: ESManagerTest.java    From pacbot with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "static-access" })
@Test 
public void createIndexTest() throws Exception{
    
    HttpEntity jsonEntity = new StringEntity("{}", ContentType.APPLICATION_JSON);
    when(response.getEntity()).thenReturn(jsonEntity);
    when(restClient.performRequest(anyString(), anyString(), anyMap(), any(HttpEntity.class),
    Matchers.<Header>anyVararg())).thenReturn(response);
    ReflectionTestUtils.setField(esManager, "restClient", restClient);
    when(sl.getStatusCode()).thenReturn(100);
    when(response.getStatusLine()).thenReturn(sl);
    
    esManager.createIndex("index", new ArrayList<>());
    
    when(sl.getStatusCode()).thenReturn(200);
    when(response.getStatusLine()).thenReturn(sl);
    
    esManager.createIndex("index", new ArrayList<>());
    
    when(restClient.performRequest(anyString(), anyString(), anyMap(), any(HttpEntity.class),
    Matchers.<Header>anyVararg())).thenThrow(new IOException());
    ReflectionTestUtils.setField(esManager, "restClient", restClient);
    esManager.createIndex("index", new ArrayList<>());
}
 
Example #24
Source File: HttpAPIPinsTest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testMultiPutGetNonExistingPin() throws Exception {
    HttpPut put = new HttpPut(httpsServerUrl + "4ae3851817194e2596cf1b7103603ef8/update/v10");
    put.setEntity(new StringEntity("[\"100\", \"101\", \"102\"]", ContentType.APPLICATION_JSON));

    try (CloseableHttpResponse response = httpclient.execute(put)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
    }

    HttpGet get = new HttpGet(httpsServerUrl + "4ae3851817194e2596cf1b7103603ef8/get/v10");

    try (CloseableHttpResponse response = httpclient.execute(get)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        List<String> values = TestUtil.consumeJsonPinValues(response);
        assertEquals(3, values.size());
        assertEquals("100", values.get(0));
        assertEquals("101", values.get(1));
        assertEquals("102", values.get(2));
    }
}
 
Example #25
Source File: AcquisitionDataClient.java    From render with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Updates the state of the specified tiles on the acquisition server.
 *
 * @param  tileIdList  list of tile ids to update.
 *
 * @throws IOException
 *   if the request fails for any reason.
 */
public void updateTileStates(final AcquisitionTileIdList tileIdList)
        throws IOException {

    final String json = tileIdList.toJson();
    final StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
    final URI uri = getUri(baseUrl + "/tile-state");
    final String requestContext = "PUT " + uri;
    final EmptyResponseHandler responseHandler = new EmptyResponseHandler(requestContext);

    final HttpPut httpPut = new HttpPut(uri);
    httpPut.setEntity(stringEntity);

    LOG.info("updateTileStates: submitting {} with {}", requestContext, tileIdList);

    httpClient.execute(httpPut, responseHandler);
}
 
Example #26
Source File: Log.java    From DiscordBot with Apache License 2.0 6 votes vote down vote up
/**
 * Method by StupPlayer (https://github.com/StupPlayer)
 * @param data
 * @return
 */
public static String hastePost(String data) {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost("https://hastebin.com/documents");

    try {
        post.setEntity(new StringEntity(data));

        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
        return "https://hastebin.com/" + new JsonParser().parse(result).getAsJsonObject().get("key").getAsString();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "Could not post!";
}
 
Example #27
Source File: NamespaceOpenApiServiceTest.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNamespaces() throws Exception {
  StringEntity responseEntity = new StringEntity("[]");
  when(someHttpResponse.getEntity()).thenReturn(responseEntity);

  final ArgumentCaptor<HttpGet> request = ArgumentCaptor.forClass(HttpGet.class);

  namespaceOpenApiService.getNamespaces(someAppId, someEnv, someCluster);

  verify(httpClient, times(1)).execute(request.capture());

  HttpGet get = request.getValue();

  assertEquals(String
          .format("%s/envs/%s/apps/%s/clusters/%s/namespaces", someBaseUrl, someEnv, someAppId, someCluster),
      get.getURI().toString());
}
 
Example #28
Source File: ExecuteSparkInteractive.java    From nifi with Apache License 2.0 6 votes vote down vote up
private JSONObject readJSONObjectFromUrlPOST(String urlString, LivySessionService livySessionService, Map<String, String> headers, String payload)
    throws IOException, JSONException, SessionManagerException {
    HttpClient httpClient = livySessionService.getConnection();

    HttpPost request = new HttpPost(urlString);
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        request.addHeader(entry.getKey(), entry.getValue());
    }
    HttpEntity httpEntity = new StringEntity(payload);
    request.setEntity(httpEntity);
    HttpResponse response = httpClient.execute(request);

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK && response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + " : " + response.getStatusLine().getReasonPhrase());
    }

    InputStream content = response.getEntity().getContent();
    return readAllIntoJSONObject(content);
}
 
Example #29
Source File: RESTServiceConnectorTest.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomDeserializerForCustomLists() throws Exception {
    final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE);
    when(response.getEntity()).thenReturn(new StringEntity("{results: [{field : \"SomeValue\"}], results_count: 1}"));
    final CloseableHttpClient httpClient = mock(CloseableHttpClient.class);
    when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response);
    final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost");
    final Class<? extends CollectionType> clazzListOfTestPojo = new ObjectMapper().getTypeFactory().constructCollectionType(List.class, TestPojo.class).getClass();
    final RESTServiceConnector connector = new RESTServiceConnector.Builder()
            .client(restClient)
            .classToDeserializerEntry(clazzListOfTestPojo, new CustomListDeserializer<TestPojoDeserializer>())
            .build();

    connector.executeRetrieveObject(TestPojo.class, "/somepath");
}
 
Example #30
Source File: RestClient.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
private boolean setCache(boolean flag) throws IOException {
    String url = baseUrl + "/admin/config";
    HttpPut put = newPut(url);
    HttpResponse response = null;
    try {
        HashMap<String, String> paraMap = new HashMap<String, String>();
        paraMap.put("key", "kylin.query.cache-enabled");
        paraMap.put("value", flag + "");
        put.setEntity(new StringEntity(new ObjectMapper().writeValueAsString(paraMap), UTF_8));
        response = client.execute(put);
        EntityUtils.consume(response.getEntity());
        if (response.getStatusLine().getStatusCode() != 200) {
            return false;
        } else {
            return true;
        }
    } finally {
        cleanup(put, response);
    }
}