org.apache.http.message.BasicHeader Java Examples

The following examples show how to use org.apache.http.message.BasicHeader. 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 Project: deprecated-security-advanced-modules   Author: opendistro-for-elasticsearch   File: LdapBackendIntegTest2.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAttributesWithImpersonation() throws Exception {
    String securityConfigAsYamlString = FileHelper.loadFile("ldap/config_ldap2.yml");
    securityConfigAsYamlString = securityConfigAsYamlString.replace("${ldapsPort}", String.valueOf(ldapsPort));
    final Settings settings = Settings.builder()
            .putList(ConfigConstants.OPENDISTRO_SECURITY_AUTHCZ_REST_IMPERSONATION_USERS+".cn=Captain Spock,ou=people,o=TEST", "*")
            .build();
    setup(Settings.EMPTY, new DynamicSecurityConfig().setConfigAsYamlString(securityConfigAsYamlString), settings);
    final RestHelper rh = nonSslRestHelper();
    HttpResponse res;
    Assert.assertEquals(HttpStatus.SC_OK, (res=rh.executeGetRequest("_opendistro/_security/authinfo", new BasicHeader("opendistro_security_impersonate_as", "jacksonm")
            ,encodeBasicHeader("spock", "spocksecret"))).getStatusCode());
    System.out.println(res.getBody());
    Assert.assertTrue(res.getBody().contains("ldap.dn"));
    Assert.assertTrue(res.getBody().contains("attr.ldap.entryDN"));
    Assert.assertTrue(res.getBody().contains("attr.ldap.subschemaSubentry"));

}
 
Example #2
Source Project: deprecated-security-advanced-modules   Author: opendistro-for-elasticsearch   File: LdapBackendIntegTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAttributesWithImpersonation() throws Exception {
    String securityConfigAsYamlString = FileHelper.loadFile("ldap/config.yml");
    securityConfigAsYamlString = securityConfigAsYamlString.replace("${ldapsPort}", String.valueOf(ldapsPort));
    final Settings settings = Settings.builder()
            .putList(ConfigConstants.OPENDISTRO_SECURITY_AUTHCZ_REST_IMPERSONATION_USERS+".cn=Captain Spock,ou=people,o=TEST", "*")
            .build();
    setup(Settings.EMPTY, new DynamicSecurityConfig().setConfigAsYamlString(securityConfigAsYamlString), settings);
    final RestHelper rh = nonSslRestHelper();
    HttpResponse res;
    Assert.assertEquals(HttpStatus.SC_OK, (res=rh.executeGetRequest("_opendistro/_security/authinfo", new BasicHeader("opendistro_security_impersonate_as", "jacksonm")
            ,encodeBasicHeader("spock", "spocksecret"))).getStatusCode());
    System.out.println(res.getBody());
    Assert.assertTrue(res.getBody().contains("ldap.dn"));
    Assert.assertTrue(res.getBody().contains("attr.ldap.entryDN"));
    Assert.assertTrue(res.getBody().contains("attr.ldap.subschemaSubentry"));

}
 
Example #3
Source Project: deprecated-security-advanced-modules   Author: opendistro-for-elasticsearch   File: MultitenancyTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMt() throws Exception {
    final Settings settings = Settings.builder()
            .build();
    setup(settings);
    final RestHelper rh = nonSslRestHelper();

    HttpResponse res;
    String body = "{\"buildNum\": 15460, \"defaultIndex\": \"humanresources\", \"tenant\": \"human_resources\"}";
    Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executePutRequest(".kibana/config/5.6.0?pretty",body, new BasicHeader("securitytenant", "blafasel"), encodeBasicHeader("hr_employee", "hr_employee"))).getStatusCode());

    body = "{\"buildNum\": 15460, \"defaultIndex\": \"humanresources\", \"tenant\": \"human_resources\"}";
    Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executePutRequest(".kibana/config/5.6.0?pretty",body, new BasicHeader("securitytenant", "business_intelligence"), encodeBasicHeader("hr_employee", "hr_employee"))).getStatusCode());

    body = "{\"buildNum\": 15460, \"defaultIndex\": \"humanresources\", \"tenant\": \"human_resources\"}";
    Assert.assertEquals(HttpStatus.SC_CREATED, (res = rh.executePutRequest(".kibana/config/5.6.0?pretty",body, new BasicHeader("securitytenant", "human_resources"), encodeBasicHeader("hr_employee", "hr_employee"))).getStatusCode());
    System.out.println(res.getBody());
    Assert.assertTrue(WildcardMatcher.match("*.kibana_*_humanresources*", res.getBody()));

    Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest(".kibana/config/5.6.0?pretty",new BasicHeader("securitytenant", "human_resources"), encodeBasicHeader("hr_employee", "hr_employee"))).getStatusCode());
    System.out.println(res.getBody());
    Assert.assertTrue(WildcardMatcher.match("*human_resources*", res.getBody()));

}
 
Example #4
Source Project: deprecated-security-advanced-modules   Author: opendistro-for-elasticsearch   File: BasicAuditlogTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAliasBadHeaders() throws Exception {

    Settings additionalSettings = Settings.builder()
            .put("opendistro_security.audit.type", TestAuditlogImpl.class.getName())
            .put(ConfigConstants.OPENDISTRO_SECURITY_AUDIT_ENABLE_TRANSPORT, true)
            .put(ConfigConstants.OPENDISTRO_SECURITY_AUDIT_RESOLVE_BULK_REQUESTS, true)
            .put(ConfigConstants.OPENDISTRO_SECURITY_AUDIT_CONFIG_DISABLED_TRANSPORT_CATEGORIES, "NONE")
            .put(ConfigConstants.OPENDISTRO_SECURITY_AUDIT_CONFIG_DISABLED_REST_CATEGORIES, "NONE")
            .put("opendistro_security.audit.threadpool.size", 0)
            .build();

    setup(additionalSettings);

    TestAuditlogImpl.clear();
    HttpResponse response = rh.executeGetRequest("_search?pretty", new BasicHeader("_opendistro_security_user", "xxx"), encodeBasicHeader("admin", "admin"));
    Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode());
    System.out.println(TestAuditlogImpl.sb.toString());
    Assert.assertFalse(TestAuditlogImpl.sb.toString().contains("YWRtaW46YWRtaW4"));
    Assert.assertTrue(TestAuditlogImpl.sb.toString().contains("BAD_HEADERS"));
    Assert.assertTrue(TestAuditlogImpl.sb.toString().contains("xxx"));
    Assert.assertEquals(1, TestAuditlogImpl.messages.size());
    Assert.assertTrue(validateMsgs(TestAuditlogImpl.messages));
    TestAuditlogImpl.clear();
}
 
Example #5
Source Project: deprecated-security-advanced-modules   Author: opendistro-for-elasticsearch   File: CachingTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRestCachingWithImpersonation() throws Exception {
    final Settings settings = Settings.builder().putList("opendistro_security.authcz.rest_impersonation_user.dummy", "*").build();
    setup(Settings.EMPTY, new DynamicSecurityConfig(), settings);
    final RestHelper rh = nonSslRestHelper();
    HttpResponse res = rh.executeGetRequest("_opendistro/_security/authinfo?pretty", new BasicHeader("opendistro_security_impersonate_as", "impuser"));
    System.out.println(res.getBody());
    Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode());
    res = rh.executeGetRequest("_opendistro/_security/authinfo?pretty", new BasicHeader("opendistro_security_impersonate_as", "impuser"));
    System.out.println(res.getBody());
    Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode());
    res = rh.executeGetRequest("_opendistro/_security/authinfo?pretty", new BasicHeader("opendistro_security_impersonate_as", "impuser"));
    System.out.println(res.getBody());
    Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode());
    res = rh.executeGetRequest("_opendistro/_security/authinfo?pretty", new BasicHeader("opendistro_security_impersonate_as", "impuser2"));
    System.out.println(res.getBody());
    Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode());

    Assert.assertEquals(4, DummyHTTPAuthenticator.getCount());
    Assert.assertEquals(3, DummyAuthorizer.getCount());
    Assert.assertEquals(4, DummyAuthenticationBackend.getAuthCount());
    Assert.assertEquals(2, DummyAuthenticationBackend.getExistsCount());

}
 
Example #6
Source Project: presto   Author: prestosql   File: TestPasswordAuthentication.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test()
        throws IOException
{
    String json = new ObjectMapper().writeValueAsString(ImmutableMap.<String, Object>builder()
            .put("value", 42L)
            .build());

    client.getLowLevelClient()
            .performRequest(
                    "POST",
                    "/test/_doc?refresh",
                    ImmutableMap.of(),
                    new NStringEntity(json, ContentType.APPLICATION_JSON),
                    new BasicHeader("Authorization", format("Basic %s", Base64.encodeAsString(format("%s:%s", USER, PASSWORD).getBytes(StandardCharsets.UTF_8)))));

    assertThat(assertions.query("SELECT * FROM test"))
            .matches("VALUES BIGINT '42'");
}
 
Example #7
Source Project: jlibra   Author: ketola   File: Faucet.java    License: Apache License 2.0 6 votes vote down vote up
public void mint(AuthenticationKey authenticationKey, long amountInMicroLibras, String currencyCode) {
    try {
        URIBuilder builder = new URIBuilder(url)
                .setParameter("amount", Long.toString(amountInMicroLibras))
                .setParameter("auth_key", authenticationKey.toString())
                .setParameter("currency_code", currencyCode);
        HttpPost httpPost = new HttpPost(builder.build().toString());
        httpPost.addHeader(new BasicHeader(USER_AGENT, "JLibra"));
        httpPost.setEntity(new StringEntity(""));

        CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new LibraRuntimeException(String.format("Mint failed. Status code: %d, message: %s",
                    response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
        }
    } catch (IOException | URISyntaxException e) {
        throw new LibraRuntimeException("Mint failed", e);
    }
}
 
Example #8
Source Project: ObjectLogger   Author: yeecode   File: HttpUtil.java    License: Apache License 2.0 6 votes vote down vote up
private synchronized String sendPost(String url, List<NameValuePair> nameValuePairList) throws Exception {
    CloseableHttpResponse response = null;
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost(url);
        StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
        post.setEntity(entity);
        post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
        post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
        response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (200 == statusCode) {
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
    } catch (Exception e) {
        LOGGER.error("send post error", e);
    } finally {
        if (response != null) {
            response.close();
        }
    }
    return null;
}
 
Example #9
Source Project: hop   Author: project-hop   File: HopServer.java    License: Apache License 2.0 6 votes vote down vote up
HttpPost buildSendXmlMethod( byte[] content, String service ) throws Exception {
  // Prepare HTTP put
  //
  String urlString = constructUrl( service );
  if ( log.isDebug() ) {
    log.logDebug( BaseMessages.getString( PKG, "HopServer.DEBUG_ConnectingTo", urlString ) );
  }
  HttpPost postMethod = new HttpPost( urlString );

  // Request content will be retrieved directly from the input stream
  //
  HttpEntity entity = new ByteArrayEntity( content );

  postMethod.setEntity( entity );
  postMethod.addHeader( new BasicHeader( "Content-Type", "text/xml;charset=" + Const.XML_ENCODING ) );

  return postMethod;
}
 
Example #10
Source Project: hop   Author: project-hop   File: HopServer.java    License: Apache License 2.0 6 votes vote down vote up
HttpPost buildSendExportMethod( String type, String load, InputStream is ) throws UnsupportedEncodingException {
  String serviceUrl = RegisterPackageServlet.CONTEXT_PATH;
  if ( type != null && load != null ) {
    serviceUrl +=
      "/?" + RegisterPackageServlet.PARAMETER_TYPE + "=" + type
        + "&" + RegisterPackageServlet.PARAMETER_LOAD + "=" + URLEncoder.encode( load, "UTF-8" );
  }

  String urlString = constructUrl( serviceUrl );
  if ( log.isDebug() ) {
    log.logDebug( BaseMessages.getString( PKG, "HopServer.DEBUG_ConnectingTo", urlString ) );
  }

  HttpPost method = new HttpPost( urlString );
  method.setEntity( new InputStreamEntity( is ) );
  method.addHeader( new BasicHeader( "Content-Type", "binary/zip" ) );

  return method;
}
 
Example #11
Source Project: anomaly-detection   Author: opendistro-for-elasticsearch   File: AnomalyDetectorRestTestCase.java    License: Apache License 2.0 6 votes vote down vote up
protected AnomalyDetector createRandomAnomalyDetector(Boolean refresh, Boolean withMetadata) throws IOException {
    Map<String, Object> uiMetadata = null;
    if (withMetadata) {
        uiMetadata = TestHelpers.randomUiMetadata();
    }
    AnomalyDetector detector = TestHelpers.randomAnomalyDetector(uiMetadata, null);
    String indexName = detector.getIndices().get(0);
    TestHelpers
        .makeRequest(
            client(),
            "POST",
            "/" + indexName + "/_doc/" + randomAlphaOfLength(5) + "?refresh=true",
            ImmutableMap.of(),
            toHttpEntity("{\"name\": \"test\"}"),
            null
        );
    AnomalyDetector createdDetector = createAnomalyDetector(detector, refresh);

    if (withMetadata) {
        return getAnomalyDetector(createdDetector.getDetectorId(), new BasicHeader(HttpHeaders.USER_AGENT, "Kibana"));
    }
    return getAnomalyDetector(createdDetector.getDetectorId(), new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
}
 
Example #12
Source Project: spring-cloud-openfeign   Author: spring-cloud   File: ApacheHttpClientConfigurationTests.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HttpClientBuilder createBuilder() {
	CloseableHttpClient client = mock(CloseableHttpClient.class);
	CloseableHttpResponse response = mock(CloseableHttpResponse.class);
	StatusLine statusLine = mock(StatusLine.class);
	doReturn(200).when(statusLine).getStatusCode();
	Mockito.doReturn(statusLine).when(response).getStatusLine();
	Header[] headers = new BasicHeader[0];
	doReturn(headers).when(response).getAllHeaders();
	try {
		Mockito.doReturn(response).when(client)
				.execute(any(HttpUriRequest.class));
	}
	catch (IOException e) {
		e.printStackTrace();
	}
	HttpClientBuilder builder = mock(HttpClientBuilder.class);
	Mockito.doReturn(client).when(builder).build();
	return builder;
}
 
Example #13
Source Project: TrackRay   Author: iSafeBlue   File: Awvs.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void initCheck(){
    headers = new Header[]{
            new BasicHeader("X-Auth",apikey),
            new BasicHeader("content-type","application/json"),
    };

    CrawlerPage page = new CrawlerPage();
    page.getRequest().setUrl(host+"/api/v1/scans");
    page.getRequest().setHttpHeaders(headers);
    page.getRequest().setHttpMethod(HttpMethod.GET);
    f.run(page);
    int statusCode = page.getResponse().getStatus().getStatusCode();
    if (statusCode>=200 && statusCode<300){
        ok = true;
        SysLog.info("[AWVS] AWVS配置正常");
    }else {
        ok = false;
        SysLog.error("[AWVS] AWVS配置异常请检查");
    }

}
 
Example #14
Source Project: TrackRay   Author: iSafeBlue   File: Wordpress001.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public String start() {

    String url = param.get("target")+"/wp-login.php?action=lostpassword";

    crawlerPage.getRequest().setUrl(url);
    crawlerPage.getRequest().setHttpMethod(HttpMethod.POST);
    HashMap<String, String> map = new HashMap<>();
    map.put("user_login",param.get("username").toString());
    map.put("redirect_to","");
    map.put("wp-submit","Get+New+Password");
    crawlerPage.getRequest().addHttpHeader(new BasicHeader("Host",param.get("host").toString()));
    crawlerPage.getRequest().setParamMap(map);
    fetcher.run(crawlerPage);
    return crawlerPage.getResponse().getStatus().getContent();
}
 
Example #15
Source Project: roncoo-education   Author: roncoo   File: HttpUtil.java    License: MIT License 6 votes vote down vote up
/**
 * 
 * @param url
 * @param param
 * @return
 */
public static String post(String url, Map<String, Object> param) {
	logger.info("POST 请求, url={},map={}", url, param.toString());
	try {
		HttpPost httpPost = new HttpPost(url.trim());
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT).setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();
		httpPost.setConfig(requestConfig);
		httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
		StringEntity se = new StringEntity(param.toString(), CHARSET_UTF_8);
		se.setContentType(CONTENT_TYPE_TEXT_JSON);
		se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
		httpPost.setEntity(se);
		HttpResponse httpResponse = HttpClientBuilder.create().build().execute(httpPost);
		return EntityUtils.toString(httpResponse.getEntity(), CHARSET_UTF_8);
	} catch (Exception e) {
		logger.info("HTTP请求出错", e);
		e.printStackTrace();
	}
	return "";
}
 
Example #16
Source Project: docker-java-api   Author: amihaiemil   File: RtContainer.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Exec exec(final JsonObject config) throws IOException {
    final URI uri = new UncheckedUriBuilder(
        this.baseUri.toString() + "/exec")
        .build();
    final HttpPost post = new HttpPost(uri);
    try {
        post.setEntity(new StringEntity(config.toString()));
        post.setHeader(new BasicHeader("Content-Type", "application/json"));
        final JsonObject json = this.client.execute(
            post,
            new ReadJsonObject(
                new MatchStatus(post.getURI(), HttpStatus.SC_CREATED)
            )
        );
        return this.docker.execs().get(json.getString("Id"));
    } finally {
        post.releaseConnection();
    }
}
 
Example #17
Source Project: docker-java-api   Author: amihaiemil   File: AuthHttpClientTestCase.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Leaves the request's header intact if it exists.
 * @throws Exception If something goes wrong.
 */
@Test
public void leavesExistingHeaderAlone() throws Exception {
    final Header auth = new BasicHeader("X-Registry-Auth", "12356");
    final HttpUriRequest request = new HttpGet();
    request.setHeader(auth);
    new AuthHttpClient(
        noOpClient,
        this.fakeAuth("X-New-Header", "abc")
    ).execute(request);
    MatcherAssert.assertThat(
        request.getFirstHeader("X-Registry-Auth").getValue(),
        new IsEqual<>("12356")
    );
    MatcherAssert.assertThat(
        request.getFirstHeader("X-New-Header").getValue(),
        new IsEqual<>("abc")
    );
}
 
Example #18
Source Project: imagehosting   Author: jingxiang   File: AbstractInnerImageUploadService.java    License: MIT License 5 votes vote down vote up
public String upload(File imageFile,ImageHostingReqConfig reqConfig) throws IOException {
		String result = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String url = getUploadUrl();
		HttpPost httpPost = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(reqConfig.getConnetionTimeOut())
				.setSocketTimeout(reqConfig.getSocketTimeout()).build();
		httpPost.setConfig(requestConfig);
		httpPost.setEntity(getHttpEntity(imageFile));
		Map<String, String> headerMap = getHeaderMap();
		if(headerMap != null && !headerMap.isEmpty()) {
			for(Map.Entry<String, String> entry : headerMap.entrySet()) {
				httpPost.addHeader(new BasicHeader(entry.getKey(), entry.getValue()));
			}
		}
		CloseableHttpResponse response = httpclient.execute(httpPost);
		try {
			HttpEntity resEntity = response.getEntity();
			if (resEntity != null) {
				String responseEntity = EntityUtils.toString(response.getEntity());
				result = anaysisResult(responseEntity);
				if(result == null || result.isEmpty()) {
					printError(url, responseEntity);
				}
			}
			
//			EntityUtils.consume(resEntity);
			return result;
		} finally {
			try {
				response.close();
			} catch (Exception e) {
			}
		}
	}
 
Example #19
Source Project: deprecated-security-advanced-modules   Author: opendistro-for-elasticsearch   File: MultitenancyTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testKibanaAlias65() throws Exception {
    final Settings settings = Settings.builder()
            .build();
    setup(settings);

    try (TransportClient tc = getInternalTransportClient()) {
        String body = "{\"buildNum\": 15460, \"defaultIndex\": \"humanresources\", \"tenant\": \"human_resources\"}";
        Map indexSettings = new HashMap();
        indexSettings.put("number_of_shards", 1);
        indexSettings.put("number_of_replicas", 0);
        tc.admin().indices().create(new CreateIndexRequest(".kibana_1")
            .alias(new Alias(".kibana"))
            .settings(indexSettings))
            .actionGet();

        tc.index(new IndexRequest(".kibana_1").type("doc").id("6.2.2").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source(body, XContentType.JSON)).actionGet();
        tc.index(new IndexRequest(".kibana_-900636979_kibanaro").type("doc").id("6.2.2").setRefreshPolicy(RefreshPolicy.IMMEDIATE).source(body, XContentType.JSON)).actionGet();

    }

    final RestHelper rh = nonSslRestHelper();

    HttpResponse res;
    Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest(".kibana/doc/6.2.2?pretty", new BasicHeader("securitytenant", "__user__"), encodeBasicHeader("kibanaro", "kibanaro"))).getStatusCode());
    System.out.println(res.getBody());
    Assert.assertTrue(res.getBody().contains(".kibana_-900636979_kibanaro"));
}
 
Example #20
Source Project: deprecated-security-advanced-modules   Author: opendistro-for-elasticsearch   File: BasicAuditlogTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testBadHeader() throws Exception {

        HttpResponse response = rh.executeGetRequest("", new BasicHeader("_opendistro_security_bad", "bad"), encodeBasicHeader("admin", "admin"));
        Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode());
        Assert.assertFalse(TestAuditlogImpl.sb.toString(), TestAuditlogImpl.sb.toString().contains("AUTHENTICATED"));
        Assert.assertTrue(TestAuditlogImpl.sb.toString(), TestAuditlogImpl.sb.toString().contains("BAD_HEADERS"));
        Assert.assertTrue(TestAuditlogImpl.sb.toString(), TestAuditlogImpl.sb.toString().contains("_opendistro_security_bad"));
        Assert.assertEquals(TestAuditlogImpl.sb.toString(), 1, TestAuditlogImpl.messages.size());
        Assert.assertTrue(validateMsgs(TestAuditlogImpl.messages));
    }
 
Example #21
/**
 * @param mapHeaders Map of header entries
 * @return modeled Header objects
 */
private static Header[] mapToHeaderArray(final Map<String, String> mapHeaders)
{
    Header[] headers = new Header[mapHeaders.size()];
    int i = 0;
    for (Map.Entry<String, String> headerEntry : mapHeaders.entrySet()) {
        headers[i++] = new BasicHeader(headerEntry.getKey(), headerEntry.getValue());
    }
    return headers;
}
 
Example #22
Source Project: vividus   Author: vividus-framework   File: HttpRequestSteps.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Set up request headers that will be used while sending request
 * @param headers ExamplesTable representing list of headers with columns "name" and "value" specifying HTTP header
 * names and values respectively
 */
@When("I set request headers:$headers")
public void setUpRequestHeaders(ExamplesTable headers)
{
    List<Header> requestHeaders = headers.getRowsAsParameters(true).stream()
            .map(row -> new BasicHeader(row.valueAs(NAME, String.class), row.valueAs(VALUE, String.class)))
            .collect(toList());
    httpTestContext.putRequestHeaders(requestHeaders);
}
 
Example #23
Source Project: ProjectStudy   Author: dolyw   File: RestClientConfig.java    License: MIT License 5 votes vote down vote up
/**
 * LowLevelRestConfig
 *
 * @param
 * @return org.elasticsearch.client.RestClient
 * @author wliduo[[email protected]]
 * @date 2019/8/12 18:56
 */
@Bean
public RestClient restClient() {
    // 如果有多个从节点可以持续在内部new多个HttpHost,参数1是IP,参数2是端口,参数3是通信协议
    RestClientBuilder clientBuilder = RestClient.builder(new HttpHost(hostname, port, "http"));
    // 设置Header编码
    Header[] defaultHeaders = {new BasicHeader("content-type", "application/json")};
    clientBuilder.setDefaultHeaders(defaultHeaders);
    // 添加其他配置,这些配置都是可选的,详情配置可看https://blog.csdn.net/jacksonary/article/details/82729556
    return clientBuilder.build();
}
 
Example #24
Source Project: ProjectStudy   Author: dolyw   File: RestClientConfig.java    License: MIT License 5 votes vote down vote up
/**
 * LowLevelRestConfig
 *
 * @param
 * @return org.elasticsearch.client.RestClient
 * @author wliduo[[email protected]]
 * @date 2019/8/12 18:56
 */
@Bean
public RestClient restClient() {
    // 如果有多个从节点可以持续在内部new多个HttpHost,参数1是IP,参数2是端口,参数3是通信协议
    RestClientBuilder clientBuilder = RestClient.builder(new HttpHost(hostname, port, "http"));
    // 设置Header编码
    Header[] defaultHeaders = {new BasicHeader("content-type", "application/json")};
    clientBuilder.setDefaultHeaders(defaultHeaders);
    // 添加其他配置,这些配置都是可选的,详情配置可看https://blog.csdn.net/jacksonary/article/details/82729556
    return clientBuilder.build();
}
 
Example #25
Source Project: spring-analysis-note   Author: Vip-Augus   File: HttpComponentsStreamingClientHttpRequest.java    License: MIT License 5 votes vote down vote up
@Override
@Nullable
public Header getContentEncoding() {
	String contentEncoding = this.headers.getFirst("Content-Encoding");
	return (contentEncoding != null ? new BasicHeader("Content-Encoding", contentEncoding) : null);

}
 
Example #26
Source Project: torrssen2   Author: tarpha   File: TelegramService.java    License: MIT License 5 votes vote down vote up
private void initialize() {
    token = settingService.getSettingValue("TELEGRAM_TOKEN");
    chatIds = StringUtils.split(settingService.getSettingValue("TELEGRAM_CHAT_ID"), ",");
    baseUrl = "https://api.telegram.org/bot" + token + "/sendMessage";
    
    List<Header> headers = new ArrayList<Header>();
    headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
    httpClient = HttpClientBuilder.create().setDefaultHeaders(headers).build();
}
 
Example #27
Source Project: torrssen2   Author: tarpha   File: TelegramService.java    License: MIT License 5 votes vote down vote up
public boolean sendMessage(String inToken, String chatId, String message) {
    boolean ret = false;

    baseUrl = "https://api.telegram.org/bot" + inToken + "/sendMessage";
    
    List<Header> headers = new ArrayList<Header>();
    headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
    httpClient = HttpClientBuilder.create().setDefaultHeaders(headers).build();

    HttpPost httpPost = new HttpPost(baseUrl);
    CloseableHttpResponse response = null;

    log.debug("token:" + inToken);
    log.debug("chatId: " + chatId);

    try {
        JSONObject params = new JSONObject();
        params.put("chat_id", chatId);
        params.put("text", message);
        params.put("parse_mode", "HTML");
        httpPost.setEntity(new StringEntity(params.toString(), StandardCharsets.UTF_8));

        response = httpClient.execute(httpPost);

        log.debug("telegram-send-message-response-code: " + response.getStatusLine().getStatusCode());
        if (response.getStatusLine().getStatusCode() == 200) {
            ret = true;
        } 
    } catch (IOException e) {
        log.error(e.getMessage());
    } finally {
        HttpClientUtils.closeQuietly(response);
    }

    return ret;
}
 
Example #28
Source Project: api-layer   Author: zowe   File: RequestUtilsTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void givenRequestWithHeaders_whenSetExistingHeader_thenHeaderOverwritten() {
    doReturn(new Header[] { contentLenght, pragma}).when(request).getAllHeaders();
    ArgumentCaptor<Header[]> argument = ArgumentCaptor.forClass(Header[].class);

    BasicHeader modifiedHeader = new BasicHeader("pragma", "always");
    wrapper.setHeader(modifiedHeader);
    verify(request).setHeaders(argument.capture());
    assertThat(argument.getValue(), hasItemInArray(contentLenght));
    assertThat(argument.getValue(), hasItemInArray(modifiedHeader));
}
 
Example #29
Source Project: aem-core-cif-components   Author: adobe   File: MagentoGraphqlClientTest.java    License: Apache License 2.0 5 votes vote down vote up
private void executeAndCheck(boolean withStoreHeader, MagentoGraphqlClient client) {
    // Verify parameters with default execute() method and store property
    client.execute("{dummy}");
    List<Header> headers = withStoreHeader ? Collections.singletonList(new BasicHeader("Store", "my-store")) : Collections.emptyList();
    RequestOptionsMatcher matcher = new RequestOptionsMatcher(headers, null);
    Mockito.verify(graphqlClient)
        .execute(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.argThat(matcher));

    // Verify setting a custom HTTP method
    client.execute("{dummy}", HttpMethod.GET);
    matcher = new RequestOptionsMatcher(headers, HttpMethod.GET);
    Mockito.verify(graphqlClient)
        .execute(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.argThat(matcher));
}
 
Example #30
Source Project: hop   Author: project-hop   File: WebServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getLocationFrom() {
  HttpPost postMethod = mock( HttpPost.class );
  Header locationHeader = new BasicHeader( LOCATION_HEADER, TEST_URL );
  doReturn( locationHeader ).when( postMethod ).getFirstHeader( LOCATION_HEADER );

  assertEquals( TEST_URL, WebService.getLocationFrom( postMethod ) );
}