org.apache.http.client.fluent.Content Java Examples

The following examples show how to use org.apache.http.client.fluent.Content. 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: DownBook.java    From my_curd with Apache License 2.0 6 votes vote down vote up
/**
 * Get 请求代理
 *
 * @param url
 * @return
 */
public static String getProxy(String url) {
    log.info(" ---- get url: {}", url);

    String resStr = null;
    Content content;
    try {
        content = Request.Get(url).setHeader("User-Agent", userAgents[RandomUtils.number(0, userAgents.length)])
                .connectTimeout(connectTimeout).execute().returnContent();
        resStr = content.asString(Charset.forName(charset));
        log.debug(resStr);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
    return resStr;
}
 
Example #2
Source File: UploadStepdefs.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Given("^\"([^\"]*)\" is starting uploading a content$")
public void userStartUploadContent(String username) {
    AccessToken accessToken = userStepdefs.authenticate(username);

    CountDownLatch startSignal = new CountDownLatch(2);
    CountDownConsumeInputStream bodyStream = new CountDownConsumeInputStream(startSignal);
    Request request = Request.Post(uploadUri)
        .bodyStream(new BufferedInputStream(bodyStream, _1M), org.apache.http.entity.ContentType.DEFAULT_BINARY);
    if (accessToken != null) {
        request.addHeader("Authorization", accessToken.asString());
    }
    async = Async.newInstance().execute(request, new FutureCallback<Content>() {
        
        @Override
        public void failed(Exception ex) {
        }
        
        @Override
        public void completed(Content result) {
        }
        
        @Override
        public void cancelled() {
            bodyStream.getStartSignal().countDown();
            if (bodyStream.getStartSignal().getCount() == 1) {
                isCanceled = true;
            }
        }
    });
}
 
Example #3
Source File: PrincipalLeakTest.java    From thorntail with Apache License 2.0 5 votes vote down vote up
private void checkSubjectShouldNotLeakToNonSecuredRequest(String pathSegment) throws Exception {
    // project-no-roles-props.yml restricts the number of worker threads to 1,
    // that is, all requests are processed by the same single thread
    Content content = Request.Get("http://localhost:8080/mpjwt/subject/unsecured" + pathSegment)
            .execute().returnContent();
    assertThat(content).isNull();
}
 
Example #4
Source File: MpJwtDisabledTest.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@RunAsClient
@Test
public void tokenIsNotProcessed() throws Exception {
    Content content = Request.Get("http://localhost:8080/mpjwt/subject/secured/json-web-token")
            .setHeader("Authorization", "Bearer " + createToken("MappedRole"))
            .execute().returnContent();
    assertThat(content).isNull();
}
 
Example #5
Source File: ApplicationScopedPrincipalLeakTest.java    From thorntail with Apache License 2.0 5 votes vote down vote up
private void checkSubjectShouldNotLeakToNonSecuredRequest(String pathSegment) throws Exception {
    // project-no-roles-props.yml restricts the number of worker threads to 1,
    // that is, all requests are processed by the same single thread
    Content content = Request.Get("http://localhost:8080/mpjwt/subject/unsecured" + pathSegment)
            .execute().returnContent();
    assertThat(content).isNull();
}
 
Example #6
Source File: AppWithNoLoginConfigWithConfiguredJwtRealmTest.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@RunAsClient
@Test
public void subjectShouldNotLeakToNonSecuredRequest() throws Exception {
    // project-no-roles-props.yml restricts the number of worker threads to 1,
    // that is, all requests are processed by the same single thread

    String response = Request.Get("http://localhost:8080/mpjwt/subject/secured/json-web-token")
            .setHeader("Authorization", "Bearer " + createToken("MappedRole"))
            .execute().returnContent().asString();
    assertThat(response).isEqualTo(TokenUtils.SUBJECT);

    Content content = Request.Get("http://localhost:8080/mpjwt/subject/unsecured/json-web-token")
            .execute().returnContent();
    assertThat(content).isNull();
}
 
Example #7
Source File: AppWithNoLoginConfigAndConfiguredJwtRealmTest.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@RunAsClient
@Test
public void tokenIsNotProcessed() throws Exception {
    Content content = Request.Get("http://localhost:8080/mpjwt/subject/secured/json-web-token")
            .setHeader("Authorization", "Bearer " + createToken("MappedRole"))
            .execute().returnContent();
    assertThat(content).isNull();
}
 
Example #8
Source File: MvcTest.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Test
@RunAsClient
public void testGettingView() throws IOException {
    Response response = Request.Get(baseUrl.toString() + "/hello").execute();
    Content content = response.returnContent();
    assertThat(content.asString(), containsString("Hello World!"));
}
 
Example #9
Source File: Test.java    From javabase with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    Content dd = Request.Post("http://s.dianping.com/ajax/json/activity/offline/followNoteAdd")
            .addHeader("Cookie", "isChecked=checked; JSESSIONID=5F9986BAAD08E91A40A18F9B16207DF0; _hc.v=7ff280b3-a676-c8dc-1a84-e5c9067f4dce.1534824829; _lxsdk_cuid=1655ab04f9ac8-00e38d0412b1cf-34677909-1fa400-1655ab04f9bc8; _lxsdk=1655ab04f9ac8-00e38d0412b1cf-34677909-1fa400-1655ab04f9bc8; cityid=1; citypinyin=shanghai; cityname=5LiK5rW3; s_ViewType=10; Hm_lvt_4c4fc10949f0d691f3a2cc4ca5065397=1534137110,1534904349; m_flash2=1; dper=d0a06116fb82790b7f4b503d4d3819545532d655172fbcce35647455fd2970d565f1c804897a94a679d5f9ea51178e6a77bdd3aa929cc272531255fda8f4c9869554ee3733589bd55adf4a5b7281ab234461678ea971200d578e18f7aef57fc2; ll=7fd06e815b796be3df069dec7836c3df; ua=18638217959; Hm_lpvt_4c4fc10949f0d691f3a2cc4ca5065397=1534904979; edper=0a7c1b58f873e7f2d6b8cc9821f469e2b7bb79faed2ed581c1592876d7643944; aburl=1; cye=dplab; ta.uuid=1032881519540281362; isUuidUnion=true; iuuid=1655ab04f9ac8-00e38d0412b1cf-34677909-1fa400-1655ab04f9bc8; dpUserId=21304984; mtUserId=\"\"; pvhistory=\"6L+U5ZuePjo8L3N0YXRpY3Rlc3QvbG9nZXZlbnQ/bmFtZT1XaGVyZUFtSUZhaWwmaW5mbz1odG1sLSU1QiU3QiUyMmNvZGUlMjIlM0EzJTJDJTIybWVzc2FnZSUyMiUzQSUyMlRpbWVvdXQlMjBleHBpcmVkJTIyJTdEJTVEJmNhbGxiYWNrPVdoZXJlQW1JMTE1MzUwOTMxMjk2OTI+OjwxNTM1MDkzMTI5NzU5XV9b\"; ri=1000310100; m_set_info=%7B%22ri%22%3A%221000310100%22%2C%22rv%22%3A%221535093140885%22%2C%22ui%22%3A%226081504%22%7D; rv=1535093140885; cy=1; _lx_utm=utm_source%3Ddp_pc_event; _lxsdk_s=1656aecd48d-b4d-6d4-d8d%7C%7C96")
            .bodyForm(Form.form().add("offlineActivityId", "504460353").add("noteBody", "ddd").build())
            .execute().returnContent();
    log.info(dd.asString());
}
 
Example #10
Source File: ApiCalls.java    From demo with MIT License 5 votes vote down vote up
public static String registerBorrowers(String name) {
    try {
        final Content content = Request.Post("http://localhost:8080/demo/registerborrower")
                .bodyForm(Form.form().add("borrower", name).build())
                .execute().returnContent();
        return content.asString();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example #11
Source File: ApiCalls.java    From demo with MIT License 5 votes vote down vote up
public static String registerBook(String title) {
    try {
        final Content content = Request.Post("http://localhost:8080/demo/registerbook")
                .bodyForm(Form.form().add("book", title).build())
                .execute().returnContent();
        return content.asString();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example #12
Source File: ApiCalls.java    From demo with MIT License 5 votes vote down vote up
/**
 * Use the API to register a user
 * @param username some username
 * @param password a really good password (otherwise it will probably respond with a complaint
 * @return returns the body of the result, if you wish to use it.
 */
public static String registerUser(String username, String password) {
    try {
        final Content content = Request.Post("http://localhost:8080/demo/register")
                .bodyForm(Form.form().add("username", username).add("password", password).build())
                .execute().returnContent();
        return content.asString();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example #13
Source File: HttpClientWrapper.java    From adaptive-alerting with Apache License 2.0 5 votes vote down vote up
/**
 * Makes an HTTP GET call with headers to the given URI and returns the result.
 *
 * @param uri URI
 * @return Call result
 * @throws IOException if there's a problem making the call
 */
public Content get(String uri, Map<String, String> headers) throws IOException {
    if (headers.isEmpty()) {
        return get(uri);
    }
    val getRequest = Request.Get(uri);
    return buildRequestWithHeaders(getRequest, headers)
            .execute()
            .returnContent();
}
 
Example #14
Source File: MetricQueryServiceTest.java    From adaptive-alerting with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
        MockitoAnnotations.initMocks(this);
        metricSourceSinkConfig = ConfigFactory.parseMap(metricSourceSinkConfigMap);
        String functionsInputFile = "config/functions-test.txt";
        metricFunctionsSpec = MetricFunctionsReader
                        .readFromInputFile(ClassLoader.getSystemResource(functionsInputFile).getPath()).get(0);
        String validGraphiteResponse = readFile("tests/validGraphiteResponse.json");
        Content validGraphiteResponseContent = new Content(validGraphiteResponse.getBytes(),
                        ContentType.APPLICATION_JSON);
        when(httpClient.get(
                        "http://graphite/render?format=json&target=sumSeries(a.b.c)&from=1583039039&until=1583039099",
                        graphiteHeaders)).thenReturn(validGraphiteResponseContent);
        when(httpClient.get(
                        "http://graphite/render?format=json&target=sumSeries(a.b.c)&from=1583039039&until=1583039099",
                        metrictankHeaders)).thenReturn(validGraphiteResponseContent);
        when(httpClient.get(
                        "http://graphite/render?format=json&target=sumSeries(d.e.f)&from=1583039039&until=1583039099",
                        graphiteHeaders)).thenReturn(validGraphiteResponseContent);

        String validGraphiteResponseWithNull = readFile("tests/validGraphiteResponseWithNull.json");
        Content validGraphiteResponseWithNullContent = new Content(validGraphiteResponseWithNull.getBytes(),
                        ContentType.APPLICATION_JSON);
        when(httpClient.get(
                        "http://graphite/render?format=json&target=sumSeries(a.b.c)&from=1583125439&until=1583125499",
                        graphiteHeaders)).thenReturn(validGraphiteResponseWithNullContent);

        String invalidGraphiteResponse = readFile("tests/invalidGraphiteResponse.json");
        Content invalidGraphiteResponseContent = new Content(invalidGraphiteResponse.getBytes(),
                        ContentType.APPLICATION_JSON);
        when(httpClient.get(
                        "http://graphite/render?format=json&target=sumSeries(a.b.c)&from=1583211839&until=1583211899",
                        graphiteHeaders)).thenReturn(invalidGraphiteResponseContent);

        Content emptyGraphiteResponseContent = new Content("[]".getBytes(), ContentType.APPLICATION_JSON);
        when(httpClient.get(
                        "http://graphite/render?format=json&target=sumSeries(a.b.c)&from=1583298239&until=1583298299",
                        graphiteHeaders)).thenReturn(emptyGraphiteResponseContent);
}
 
Example #15
Source File: MetricQueryService.java    From adaptive-alerting with Apache License 2.0 4 votes vote down vote up
private MetricData queryGraphite(Config metricSourceSinkConfig, MetricFunctionsSpec metricFunctionsSpec,
        Instant instant) throws MetricQueryServiceException {
    Boolean success = true;
    String graphiteUrl = "";
    String logTimestamp = "";
    String logValue = "";
    String exceptionName = "";
    String errorMessage = "";
    try {

        String graphiteFunction = metricFunctionsSpec.getFunction();
        int intervalInSecs = metricFunctionsSpec.getIntervalInSecs();
        long currentTimestamp = instant.getEpochSecond();
        long snappedCurrentTimestamp = currentTimestamp - (currentTimestamp % intervalInSecs);

        String graphiteUrlTemplate = metricSourceSinkConfig.getString(GRAPHITE_URL_TEMPLATE_KEY);

        // Subtract 1 second from 'from' and 'until' timestamps to get complete data for
        // the interval -
        // otherwise Graphite gives incomplete data.
        long until = snappedCurrentTimestamp - 1;
        long from = until - intervalInSecs;

        graphiteUrl = String.format("%s%s&from=%d&until=%d", graphiteUrlTemplate, graphiteFunction, from, until);
        Map<String, String> headers = Collections.emptyMap();
        if (metricSourceSinkConfig.getString(IS_GRAPHITE_SERVER_METRICTANK_KEY)
                .equals(GRAPHITE_SERVER_METRICTANK)) {
            /* default metrictank orgId */
            headers = Collections.singletonMap("x-org-id", "1");
        }
        Content graphiteResponse = metricFunctionHttpClient.get(graphiteUrl, headers);
        ObjectMapper objectMapper = new ObjectMapper();
        List<GraphiteResult> graphiteResults = Arrays
                .asList(objectMapper.readValue(graphiteResponse.asBytes(), GraphiteResult[].class));
        for (GraphiteResult graphiteResult : graphiteResults) {
            Datapoint datapoint = graphiteResult.getDatapoint();
            logValue = String.valueOf(datapoint.getValue());
            logTimestamp = String.valueOf(datapoint.getTimestamp());

            HashMap<String, String> tagsBuilder = new HashMap<>();
            tagsBuilder.putAll(metricFunctionsSpec.getTags());
            if (metricFunctionsSpec.getMergeTags())
                tagsBuilder.putAll(graphiteResult.getTags());

            TagCollection tags = new TagCollection(tagsBuilder);
            TagCollection metaTags = TagCollection.EMPTY;
            MetricDefinition metricDefinition = new MetricDefinition(graphiteFunction, tags, metaTags);
            String infoMessage = String.format(
                    "step=queryGraphiteSource,success=%s,exception=%s,url=\"%s\",timestamp=%s,value=%s", success,
                    exceptionName, graphiteUrl, logTimestamp, logValue);
            log.info(infoMessage);
            return new MetricData(metricDefinition, datapoint.getValue(), datapoint.getTimestamp());
        }
        throw new MissingDatapointException();
    } catch (Exception e) {
        success = false;
        exceptionName = e.getClass().getSimpleName();
        errorMessage = String.format("step=queryGraphiteSource,success=%s,exception=%s,url=\"%s\"", success,
                exceptionName, graphiteUrl);
        throw new MetricQueryServiceException(errorMessage, e);
    }
}
 
Example #16
Source File: HttpClientWrapper.java    From adaptive-alerting with Apache License 2.0 3 votes vote down vote up
/**
 * Makes an HTTP POST call to the given URI with given body and returns the result.
 *
 * @param uri  the uri
 * @param body the body
 * @return Call result
 * @throws IOException the io exception
 */
@Generated // https://reflectoring.io/100-percent-test-coverage/
public Content post(String uri, String body) throws IOException {
    return Request.Post(uri)
            .bodyString(body, ContentType.APPLICATION_JSON)
            .execute()
            .returnContent();
}
 
Example #17
Source File: HttpClientWrapper.java    From adaptive-alerting with Apache License 2.0 2 votes vote down vote up
/**
 * Makes an HTTP GET call to the given URI and returns the result.
 *
 * @param uri URI
 * @return Call result
 * @throws IOException if there's a problem making the call
 */
public Content get(String uri) throws IOException {
    return Request.Get(uri)
            .execute()
            .returnContent();
}