Example usage for org.apache.http.client.fluent Request Get

List of usage examples for org.apache.http.client.fluent Request Get

Introduction

In this page you can find the example usage for org.apache.http.client.fluent Request Get.

Prototype

public static Request Get(final String uri) 

Source Link

Usage

From source file:org.wildfly.swarm.microprofile.jwtauth.ParametrizedPathsTest.java

@RunAsClient
@Test//w ww  .j  a v  a  2 s. c  om
public void shouldGetPlainForAllowedUser() throws Exception {
    String response = Request.Get("http://localhost:8080/mpjwt/parameterized-paths/my/hello/view")
            .setHeader("Authorization", "Bearer " + createToken("MappedRole2"))
            .setHeader("Accept", MediaType.TEXT_PLAIN).execute().returnContent().asString();
    Assert.assertEquals("View accessed hello", response);
}

From source file:br.gov.jfrj.siga.base.SigaHTTP.java

/**
 * @param URL/*from www  .  j a  v a  2  s. com*/
 * @param request (se for modulo play, setar pra null)
 * @param cookieValue (necessario apenas nos modulos play)
 */
public String get(String URL, HttpServletRequest request, String cookieValue) {
    String html = "";

    if (URL.startsWith("/"))
        URL = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + URL;

    try {
        // Efetua o request para o Service Provider (mdulo)
        Request req = Request.Get(URL);
        //    req.addHeader(COOKIE, JSESSIONID_PREFIX+getCookie(request, cookieValue));
        // Atribui o html retornado e pega o header do Response
        // Se a aplicao j efetuou a autenticao entre o mdulo da URL o contedo ser trago nesse primeiro GET
        // Caso contrrio passar pelo processo de autenticao (if abaixo)
        html = req.execute().handleResponse(new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse httpResponse)
                    throws ClientProtocolException, IOException {
                // O atributo que importa nesse header  o set-cookie que ser utilizado posteriormente
                headers = httpResponse.getAllHeaders();
                return IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");
            }
        });

        // Verifica se retornou o form de autenticao do picketlink 
        if (html.contains(HTTP_POST_BINDING_REQUEST)) {
            // Atribui o cookie recuperado no response anterior
            String setCookie = null;
            try {
                setCookie = extractCookieFromHeader(getHeader(SET_COOKIE));
            } catch (ElementNotFoundException elnf) {
                log.warning("Nao encontrou o set-cookie");
                setCookie = getCookie(request, cookieValue);
            }

            // Atribui o valor do SAMLRequest contido no html retornado no GET efetuado.
            String SAMLRequestValue = getAttributeValueFromHtml(html, SAMLRequest);
            // Atribui a URL do IDP (sigaidp)
            String idpURL = getAttributeActionFromHtml(html);

            // Faz um novo POST para o IDP com o SAMLRequest como parametro e utilizando o sessionID do IDP
            html = Request.Post(idpURL).addHeader(COOKIE, JSESSIONID_PREFIX + getIdp(request))
                    .bodyForm(Form.form().add(SAMLRequest, SAMLRequestValue).build()).execute().returnContent()
                    .toString();

            // Extrai o valor do SAMLResponse
            // Caso o SAMLResponse no esteja disponvel aqui,  porque o JSESSIONID utilizado no foi o do IDP.
            String SAMLResponseValue = getAttributeValueFromHtml(html, SAMLResponse);

            // Faz um POST para o SP com o atributo SAMLResponse utilizando o sessionid do primeiro GET
            // O retorno  discartado pois o resultado  um 302.
            Request.Post(URL).addHeader(COOKIE, JSESSIONID_PREFIX + setCookie)
                    .bodyForm(Form.form().add(SAMLResponse, SAMLResponseValue).build()).execute()
                    .discardContent();

            // Agora que estamos autenticado efetua o GET para pgina desejada.
            html = Request.Get(URL).addHeader(COOKIE, JSESSIONID_PREFIX + setCookie).execute().returnContent()
                    .toString();
            if (html.contains(HTTP_POST_BINDING_REQUEST)) {
                log.info("Alguma coisa falhou na autenticao!: " + idpURL);
            }
        }
    } catch (Exception io) {
        io.printStackTrace();
    }

    return html;
}

From source file:com.softinstigate.restheart.integrationtest.PutDocumentIT.java

@Test
public void testPutDocument() throws Exception {
    try {/*from  w ww  .  j av a 2  s.c  o  m*/
        Response resp;

        // *** PUT tmpdb
        resp = adminExecutor.execute(Request.Put(dbTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check put db", resp, HttpStatus.SC_CREATED);

        // *** PUT tmpcoll
        resp = adminExecutor.execute(Request.Put(collectionTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check put coll1", resp, HttpStatus.SC_CREATED);

        // *** PUT tmpdoc
        resp = adminExecutor.execute(Request.Put(documentTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check put tmp doc", resp, HttpStatus.SC_CREATED);

        // try to put without etag
        resp = adminExecutor.execute(Request.Put(documentTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check put tmp doc without etag", resp, HttpStatus.SC_CONFLICT);

        // try to put with wrong etag
        resp = adminExecutor.execute(Request.Put(documentTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)
                .addHeader(Headers.IF_MATCH_STRING, "pippoetag"));
        check("check put tmp doc with wrong etag", resp, HttpStatus.SC_PRECONDITION_FAILED);

        resp = adminExecutor.execute(Request.Get(documentTmpUri).addHeader(Headers.CONTENT_TYPE_STRING,
                Representation.HAL_JSON_MEDIA_TYPE));

        JsonObject content = JsonObject.readFrom(resp.returnContent().asString());

        String etag = content.get("_etag").asString();

        // try to put with correct etag
        resp = adminExecutor.execute(Request.Put(documentTmpUri).bodyString("{b:2}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)
                .addHeader(Headers.IF_MATCH_STRING, etag));
        check("check put tmp doc with correct etag", resp, HttpStatus.SC_OK);

        resp = adminExecutor.execute(Request.Get(documentTmpUri).addHeader(Headers.CONTENT_TYPE_STRING,
                Representation.HAL_JSON_MEDIA_TYPE));

        content = JsonObject.readFrom(resp.returnContent().asString());
        assertNull("check put content", content.get("a"));
        assertNotNull("check put content", content.get("b"));
        assertTrue("check put content", content.get("b").asInt() == 2);
    } finally {
        mongoClient.dropDatabase(dbTmpName);
    }
}

From source file:io.bitgrillr.gocddockerexecplugin.utils.GoTestUtils.java

/**
 * Returns the result field of the named pipeline instance.
 *
 * @param pipeline Name of the pipeline.
 * @param counter Counter of the pipeline instance.
 * @return The result field./*from w w  w  .jav a 2s  .c  o  m*/
 * @throws GoError If Go.CD returns a non 2XX response.
 * @throws IOException If a communication error occurs.
 */
public static String getPipelineResult(String pipeline, int counter) throws GoError, IOException {
    final HttpResponse response = executor
            .execute(Request.Get(PIPELINES + pipeline + "/instance/" + Integer.toString(counter)))
            .returnResponse();
    final int status = response.getStatusLine().getStatusCode();
    if (status != HttpStatus.SC_OK) {
        throw new GoError(status);
    }

    final JsonArray stages = Json.createReader(response.getEntity().getContent()).readObject()
            .getJsonArray("stages");
    String result = "Passed";
    for (JsonValue stage : stages) {
        final String stageResult = ((JsonObject) stage).getString("result");
        if (!result.equals(stageResult)) {
            result = stageResult;
            break;
        }
    }
    return result;
}

From source file:nl.mpi.tla.flat.deposit.action.PackageAssembly.java

@Override
public boolean perform(Context context) throws DepositException {
    try {/*from   w ww  .  ja  v a 2s.c  om*/
        File dir = new File(getParameter("dir", "./resources"));
        if (!dir.exists())
            FileUtils.forceMkdir(dir);
        int downloads = 0;
        for (Resource res : context.getSIP().getResources()) {
            if (res.hasFile()) {
                if (res.getFile().canRead()) {
                    logger.info("Previously download[" + res.getFile() + "] of Resource[" + res.getURI()
                            + "] is still available.");
                    continue;
                } else
                    logger.info("Previously download[" + res.getFile() + "] of Resource[" + res.getURI()
                            + "] isn't available anymore!");
            }
            URI uri = res.getURI();
            if (uri.toString().startsWith(dir.toString())) {
                // the file is already in the workdir resources directory
                res.setFile(new File(uri.toString()));
            } else if (uri.toString().startsWith("hdl:" + getParameter("prefix", "foo") + "/") || uri.toString()
                    .startsWith("http://hdl.handle.net/" + getParameter("prefix", "foo") + "/")) {
                // it has already a local handle
                // TODO: what to do? resolve to its local location, and check?
            } else {
                // download the content into a local file 
                String ext = FilenameUtils.getExtension(uri.getPath());
                File file = dir.toPath()
                        .resolve("./" + UUID.randomUUID().toString() + (!ext.equals("") ? "." + ext : ""))
                        .toFile();
                Request.Get(uri).execute().saveContent(file);
                res.setFile(file);
                logger.info("Downloaded Resource[" + (++downloads) + "][" + uri + "] to [" + file + "]");
            }
        }
        if (downloads > 0) {
            context.getSIP().save();
        }
    } catch (Exception ex) {
        throw new DepositException("Couldn't assemble the package!", ex);
    }
    return true;
}

From source file:com.m3958.apps.anonymousupload.integration.java.ModuleIntegrationTest.java

@Test
public void testGetIndex() throws ClientProtocolException, IOException, URISyntaxException {

    File f = new File("README.md");

    Assert.assertTrue(f.exists());//from  w  ww . j  a  va 2s. c  o m

    HttpResponse r = Request.Get(new URIBuilder().setScheme("http").setHost("localhost").setPort(8080).build())
            .execute().returnResponse();

    String c = CharStreams
            .toString(new InputStreamReader(r.getEntity().getContent(), Charset.forName("UTF-8")));
    container.logger().info(c);
    Assert.assertEquals(17, c.length());
    Assert.assertEquals("hello web server.", c);
    Assert.assertEquals("text/html; charset=UTF-8", r.getEntity().getContentType().getValue());
    testComplete();
}

From source file:com.qwazr.scripts.ScriptSingleClient.java

@Override
public ScriptRunStatus getRunStatus(String run_id, Boolean local, String group, Integer msTimeout) {
    UBuilder uriBuilder = new UBuilder(SCRIPT_PREFIX_STATUS, run_id).setParameters(local, group, msTimeout);
    Request request = Request.Get(uriBuilder.build());
    return commonServiceRequest(request, null, null, ScriptRunStatus.class, 200);
}

From source file:io.gravitee.gateway.standalone.QueryParametersTest.java

@Test
public void call_get_query_params_spaces() throws Exception {
    String query = "myparam:test+AND+myotherparam:12";
    URI target = new URIBuilder("http://localhost:8082/test/my_team").addParameter("q", query).build();

    Response response = Request.Get(target).execute();

    HttpResponse returnResponse = response.returnResponse();
    assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode());

    String responseContent = StringUtils.copy(returnResponse.getEntity().getContent());
    assertEquals(query, responseContent);
}

From source file:com.amazonaws.sample.entitlement.authorization.GoogleOAuth2AuthorizationHandler.java

/**
 * Verify acccess_token via the Facebook graph API.
 * @param accessToken// w  w  w . j  a  v  a  2 s  . c o  m
 * @return null because we do not get enough information from the graph API request for an Identity
 * @throws AuthorizationException
 */
@Override
Identity verifyAccessToken(String accessToken) throws AuthorizationException {
    try {

        ResponseContent r = Request.Get("https://www.googleapis.com/userinfo/v2/me")
                .addHeader("Authorization", "Bearer " + URLEncoder.encode(accessToken, "UTF-8")).execute()
                .handleResponse(new AllStatusesContentResponseHandler());

        int statusCode = r.getStatusCode();
        log.info(statusCode);

        Map<String, Object> m = new ObjectMapper().readValue(r.getContent("{}"), new TypeReference<Object>() {
        });

        if (statusCode == HttpStatus.SC_OK) {
            if (!m.containsKey("email")) {
                throw new RuntimeException("Expected response to include email but it does not.");
            }
            return new Identity(m.get("id").toString(), m.get("email").toString());
        }
        if (statusCode == HttpStatus.SC_BAD_REQUEST) {
            throw new OAuthBadRequestException(buildErrorMessageFromResponse(m, statusCode),
                    AUTHORIZATION_TYPE);
        }
        if (statusCode >= 500) {
            throw new RuntimeException(PROVIDER_NAME + " encountered an error. Status code: " + statusCode);
        }

        throw new RuntimeException(
                "Unanticipated response from " + PROVIDER_NAME + ". Status code: " + statusCode);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.restheart.test.integration.PatchCollectionIT.java

@Test
public void testPatchCollection() throws Exception {
    try {//  w ww. j  a  v a2  s .c  om
        Response resp;

        // *** PUT tmpdb
        resp = adminExecutor.execute(Request.Put(dbTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check put db", resp, HttpStatus.SC_CREATED);

        // *** PUT tmpcoll
        resp = adminExecutor.execute(Request.Put(collectionTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check put coll1", resp, HttpStatus.SC_CREATED);

        // try to patch without body
        resp = adminExecutor.execute(Request.Patch(collectionTmpUri).addHeader(Headers.CONTENT_TYPE_STRING,
                Representation.HAL_JSON_MEDIA_TYPE));
        check("check patch tmp doc without etag", resp, HttpStatus.SC_NOT_ACCEPTABLE);

        // try to patch without etag
        resp = adminExecutor.execute(Request.Patch(collectionTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE));
        check("check patch tmp doc without etag", resp, HttpStatus.SC_CONFLICT);

        // try to patch with wrong etag
        resp = adminExecutor.execute(Request.Patch(collectionTmpUri).bodyString("{a:1}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)
                .addHeader(Headers.IF_MATCH_STRING, "pippoetag"));
        check("check patch tmp doc with wrong etag", resp, HttpStatus.SC_PRECONDITION_FAILED);

        resp = adminExecutor.execute(Request.Get(collectionTmpUri).addHeader(Headers.CONTENT_TYPE_STRING,
                Representation.HAL_JSON_MEDIA_TYPE));

        JsonObject content = JsonObject.readFrom(resp.returnContent().asString());

        String etag = content.get("_etag").asObject().get("$oid").asString();

        // try to patch with correct etag
        resp = adminExecutor.execute(Request.Patch(collectionTmpUri).bodyString("{b:2}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)
                .addHeader(Headers.IF_MATCH_STRING, etag));
        check("check patch tmp doc with correct etag", resp, HttpStatus.SC_OK);

        resp = adminExecutor.execute(Request.Get(collectionTmpUri).addHeader(Headers.CONTENT_TYPE_STRING,
                Representation.HAL_JSON_MEDIA_TYPE));

        content = JsonObject.readFrom(resp.returnContent().asString());
        assertNotNull("check patched content", content.get("a"));
        assertNotNull("check patched content", content.get("b"));
        assertTrue("check patched content", content.get("a").asInt() == 1 && content.get("b").asInt() == 2);
        etag = content.get("_etag").asObject().get("$oid").asString();

        // try to patch reserved field name
        resp = adminExecutor.execute(Request.Patch(collectionTmpUri).bodyString("{_embedded:\"a\"}", halCT)
                .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)
                .addHeader(Headers.IF_MATCH_STRING, etag));
        content = JsonObject.readFrom(resp.returnContent().asString());
        assertNotNull("check patched content",
                content.get("_embedded").asObject().get("rh:warnings").asArray());
    } finally {
        mongoClient.dropDatabase(dbTmpName);
    }
}