Example usage for org.apache.http.client.methods CloseableHttpResponse getStatusLine

List of usage examples for org.apache.http.client.methods CloseableHttpResponse getStatusLine

Introduction

In this page you can find the example usage for org.apache.http.client.methods CloseableHttpResponse getStatusLine.

Prototype

StatusLine getStatusLine();

Source Link

Usage

From source file:nl.knaw.dans.easy.sword2examples.Common.java

static URI trackDeposit(CloseableHttpClient http, URI statUri) throws Exception {
    CloseableHttpResponse response;
    String bodyText;/*www  .j  a v  a2  s. co m*/
    System.out.println(
            "Start polling Stat-IRI for the current status of the deposit, waiting 10 seconds before every request ...");
    while (true) {
        Thread.sleep(10000);
        System.out.print("Checking deposit status ... ");
        response = http.execute(new HttpGet(statUri));
        if (response.getStatusLine().getStatusCode() != 200) {
            System.out.println("Stat-IRI returned " + response.getStatusLine().getStatusCode());
            System.exit(1);
        }
        bodyText = readEntityAsString(response.getEntity());
        Feed statement = parse(bodyText);
        List<Category> states = statement.getCategories("http://purl.org/net/sword/terms/state");
        if (states.isEmpty()) {
            System.err.println("ERROR: NO STATE FOUND");
            System.exit(1);
        } else if (states.size() > 1) {
            System.err.println("ERROR: FOUND TOO MANY STATES (" + states.size() + "). CAN ONLY HANDLE ONE");
            System.exit(1);
        } else {
            String state = states.get(0).getTerm();
            System.out.println(state);
            if (state.equals("INVALID") || state.equals("REJECTED") || state.equals("FAILED")) {
                System.err.println("FAILURE. Complete statement follows:");
                System.err.println(bodyText);
                System.exit(3);
            } else if (state.equals("ARCHIVED")) {
                List<Entry> entries = statement.getEntries();
                System.out.println("SUCCESS. ");
                if (entries.size() == 1) {
                    System.out.print("Deposit has been archived at: <" + entries.get(0).getId() + ">. ");

                    List<String> dois = getDois(entries.get(0));
                    int numDois = dois.size();
                    switch (numDois) {
                    case 1:
                        System.out.print(" With DOI: [" + dois.get(0) + "]. ");
                        break;
                    case 0:
                        System.out.println("WARNING: No DOI found");
                        break;

                    default:
                        System.out.println("WARNING: More than one DOI found (" + numDois + "): ");
                        boolean first = true;
                        for (String doi : dois) {
                            if (first)
                                first = false;
                            else
                                System.out.print(", ");
                            System.out.print(doi + "");

                        }
                        System.out.println();
                        break;
                    }
                } else {
                    System.out.println(
                            "WARNING: Found (" + entries.size() + ") entry's; should be ONE and only ONE");
                }
                String stateText = states.get(0).getText();
                System.out.println("Dataset landing page will be located at: <" + stateText + ">.");
                System.out.println("Complete statement follows:");
                System.out.println(bodyText);
                return entries.get(0).getId().toURI();
            }
        }
    }
}

From source file:org.wuspba.ctams.ws.ITSoloResultController.java

private static void add() throws Exception {
    ITSoloContestController.add();//  w w  w . j  a va2s.c o m

    CTAMSDocument doc = new CTAMSDocument();
    doc.getPeople().add(TestFixture.INSTANCE.elaine);
    doc.getVenues().add(TestFixture.INSTANCE.venue);
    doc.getJudges().add(TestFixture.INSTANCE.judgeAndy);
    doc.getJudges().add(TestFixture.INSTANCE.judgeJamie);
    doc.getJudges().add(TestFixture.INSTANCE.judgeBob);
    doc.getResults().add(TestFixture.INSTANCE.result5);
    doc.getSoloContests().add(TestFixture.INSTANCE.soloContest);
    doc.getSoloContestResults().add(TestFixture.INSTANCE.soloResult);

    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        TestFixture.INSTANCE.soloResult.setId(doc.getSoloContestResults().get(0).getId());

        for (Result r : doc.getSoloContestResults().get(0).getResults()) {
            if (r.getPoints() == TestFixture.INSTANCE.result1.getPoints()) {
                TestFixture.INSTANCE.result1.setId(r.getId());
            } else if (r.getPoints() == TestFixture.INSTANCE.result2.getPoints()) {
                TestFixture.INSTANCE.result2.setId(r.getId());
            } else if (r.getPoints() == TestFixture.INSTANCE.result3.getPoints()) {
                TestFixture.INSTANCE.result3.setId(r.getId());
            } else if (r.getPoints() == TestFixture.INSTANCE.result4.getPoints()) {
                TestFixture.INSTANCE.result4.setId(r.getId());
            } else if (r.getPoints() == TestFixture.INSTANCE.result5.getPoints()) {
                TestFixture.INSTANCE.result5.setId(r.getId());
            }
        }

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }
}

From source file:com.joyent.manta.http.EncryptedHttpHelperTest.java

/**
 * Builds a fully mocked {@link EncryptionHttpHelper} that is setup to
 * be configured for one cipher/mode and executes requests in another
 * cipher/mode.//from ww  w .jav a2  s .com
 */
private static EncryptionHttpHelper fakeEncryptionHttpHelper(String path) throws Exception {
    MantaConnectionContext connectionContext = mock(MantaConnectionContext.class);

    StandardConfigContext config = new StandardConfigContext();

    SupportedCipherDetails cipherDetails = AesCbcCipherDetails.INSTANCE_192_BIT;

    config.setClientEncryptionEnabled(true)
            .setEncryptionPrivateKeyBytes(SecretKeyUtils.generate(cipherDetails).getEncoded())
            .setEncryptionAlgorithm(cipherDetails.getCipherId());

    EncryptionHttpHelper httpHelper = new EncryptionHttpHelper(connectionContext,
            new MantaHttpRequestFactory(UnitTestConstants.UNIT_TEST_URL), config);

    URI uri = URI.create(DEFAULT_MANTA_URL + "/" + path);

    CloseableHttpResponse fakeResponse = mock(CloseableHttpResponse.class);
    StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");

    SupportedCipherDetails objectCipherDetails = AesGcmCipherDetails.INSTANCE_128_BIT;

    Header[] headers = new Header[] {
            // Notice this is a different cipher than the one set in config
            new BasicHeader(MantaHttpHeaders.ENCRYPTION_CIPHER, objectCipherDetails.getCipherId()) };

    when(fakeResponse.getAllHeaders()).thenReturn(headers);
    when(fakeResponse.getStatusLine()).thenReturn(statusLine);

    BasicHttpEntity fakeEntity = new BasicHttpEntity();
    InputStream source = IOUtils.toInputStream("I'm a stream", StandardCharsets.US_ASCII);
    EofSensorInputStream stream = new EofSensorInputStream(source, null);
    fakeEntity.setContent(stream);
    when(fakeResponse.getEntity()).thenReturn(fakeEntity);

    when(connectionContext.getHttpClient()).thenReturn(new FakeCloseableHttpClient(fakeResponse));

    return httpHelper;
}

From source file:myexamples.MyExamples.java

public static void getExample() throws IOException {
    HttpGet httpGet = new HttpGet("http://localhost:9200/gb/tweet/9");
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    // The underlying HTTP connection is still held by the response object
    // to allow the response content to be streamed directly from the network socket.
    // In order to ensure correct deallocation of system resources
    // the user MUST call CloseableHttpResponse#close() from a finally clause.
    // Please note that if response content is not fully consumed the underlying
    // connection cannot be safely re-used and will be shut down and discarded
    // by the connection manager.
    try {/*from  w  w  w  .java 2s  .  com*/
        System.out.println(response1.getStatusLine());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        if (entity1 != null) {
            long len = entity1.getContentLength();
            if (len != -1 && len < 2048) {
                System.out.println(EntityUtils.toString(entity1));
            } else {
                System.out.println("entity length=" + len);
            }
        }

        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }
}

From source file:myexamples.MyExamples.java

public static String getTweet() throws IOException {
    String result = "";
    HttpGet httpGet = new HttpGet("http://localhost:9200/gb/tweet/9");
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    // The underlying HTTP connection is still held by the response object
    // to allow the response content to be streamed directly from the network socket.
    // In order to ensure correct deallocation of system resources
    // the user MUST call CloseableHttpResponse#close() from a finally clause.
    // Please note that if response content is not fully consumed the underlying
    // connection cannot be safely re-used and will be shut down and discarded
    // by the connection manager.
    try {/*from   w  ww.j ava 2  s.co  m*/
        System.out.println(response1.getStatusLine());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        if (entity1 != null) {
            long len = entity1.getContentLength();
            if (len != -1 && len < 2048) {
                //      System.out.println(EntityUtils.toString(entity1));
                result = EntityUtils.toString(entity1);
            } else {
                System.out.println("entity length=" + len);
            }
        }

        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }
    return result;
}

From source file:org.coding.git.api.CodingNetConnection.java

private static void checkStatusCode(@NotNull CloseableHttpResponse response, @Nullable String body)
        throws IOException {
    int code = response.getStatusLine().getStatusCode();
    switch (code) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NO_CONTENT:
        return;// w  ww.j a  v  a2  s  . c  o  m
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_FORBIDDEN:
        //noinspection ThrowableResultOfMethodCallIgnored
        CodingNetStatusCodeException error = getStatusCodeException(response);

        //        Header headerOTP = response.getFirstHeader("X-GitHub-OTP");
        //        if (headerOTP != null) {
        //          for (HeaderElement element : headerOTP.getElements()) {
        //            if ("required".equals(element.getName())) {
        //              throw new CodingNetTwoFactorAuthenticationException(error.getMessage());
        //            }
        //          }
        //        }
        //
        //        if (error.getError() != null && error.getError().containsReasonMessage("API rate limit exceeded")) {
        //          throw new GithubRateLimitExceededException(error.getMessage());
        //        }

        throw new CodingNetAuthenticationException("Request response: " + error.getMessage());
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNPROCESSABLE_ENTITY:
        LOG.info("body message:" + body);
        throw getStatusCodeException(response);
    default:
        throw getStatusCodeException(response);
    }
}

From source file:org.wuspba.ctams.ws.ITBandResultController.java

private static void add() throws Exception {
    ITBandController.add();//from   w w w .ja v a  2s . c  o  m
    ITBandContestController.add();

    CTAMSDocument doc = new CTAMSDocument();
    doc.getBands().add(TestFixture.INSTANCE.skye);
    doc.getVenues().add(TestFixture.INSTANCE.venue);
    doc.getJudges().add(TestFixture.INSTANCE.judgeAndy);
    doc.getJudges().add(TestFixture.INSTANCE.judgeJamie);
    doc.getJudges().add(TestFixture.INSTANCE.judgeBob);
    doc.getJudges().add(TestFixture.INSTANCE.judgeEoin);
    doc.getResults().add(TestFixture.INSTANCE.result1);
    doc.getResults().add(TestFixture.INSTANCE.result2);
    doc.getResults().add(TestFixture.INSTANCE.result3);
    doc.getResults().add(TestFixture.INSTANCE.result4);
    doc.getBandContests().add(TestFixture.INSTANCE.bandContest);
    doc.getBandContestResults().add(TestFixture.INSTANCE.bandResult);

    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        TestFixture.INSTANCE.bandResult.setId(doc.getBandContestResults().get(0).getId());

        for (Result r : doc.getBandContestResults().get(0).getResults()) {
            if (r.getPoints() == TestFixture.INSTANCE.result1.getPoints()) {
                TestFixture.INSTANCE.result1.setId(r.getId());
            } else if (r.getPoints() == TestFixture.INSTANCE.result2.getPoints()) {
                TestFixture.INSTANCE.result2.setId(r.getId());
            } else if (r.getPoints() == TestFixture.INSTANCE.result3.getPoints()) {
                TestFixture.INSTANCE.result3.setId(r.getId());
            } else if (r.getPoints() == TestFixture.INSTANCE.result4.getPoints()) {
                TestFixture.INSTANCE.result4.setId(r.getId());
            }
        }

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }
}

From source file:io.andyc.papercut.api.PrintApi.java

/**
 * Uploads the file and finalizes the printing
 *
 * @param printJob    {PrintJob} - the print job
 * @param prevElement {Element} - the previous Jsoup element containing the
 *                    upload file Html// w  w w  .  ja  va 2 s  .com
 *
 * @return {boolean} - whether or not the print job completed
 */
static boolean uploadFile(PrintJob printJob, Document prevElement)
        throws PrintingException, UnsupportedMimeTypeException {
    String uploadUrl = printJob.getSession().getDomain().replace("/app", "")
            + PrintApi.getUploadFileUrl(prevElement); // upload directory

    HttpPost post = new HttpPost(uploadUrl);
    CloseableHttpClient client = HttpClientBuilder.create().build();

    // configure multipart post request entity builder
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    // build the file boundary
    String boundary = "-----------------------------" + new Date().getTime();
    entityBuilder.setBoundary(boundary);

    // set the file
    File file = new File(printJob.getFilePath());
    FileBody body = new FileBody(file,
            ContentType.create(ContentTypes.getApplicationType(printJob.getFilePath())), file.getName());
    entityBuilder.addPart("file[]", body);

    // build the post request
    HttpEntity multipart = entityBuilder.build();
    post.setEntity(multipart);

    // set cookie
    post.setHeader("Cookie", printJob.getSession().getSessionKey() + "=" + printJob.getSession().getSession());

    // send
    try {
        CloseableHttpResponse response = client.execute(post);
        return response.getStatusLine().getStatusCode() == 200;
    } catch (IOException e) {
        throw new PrintingException("Error uploading the file");
    }
}

From source file:org.apache.ofbiz.passport.event.GitHubEvents.java

/**
 * Parse GitHub login response and login the user if possible.
 * //  ww  w .jav  a  2 s . c o m
 * @return 
 */
public static String parseGitHubResponse(HttpServletRequest request, HttpServletResponse response) {
    String authorizationCode = request.getParameter(PassportUtil.COMMON_CODE);
    String state = request.getParameter(PassportUtil.COMMON_STATE);
    if (!state.equals(request.getSession().getAttribute(SESSION_GITHUB_STATE))) {
        String errMsg = UtilProperties.getMessage(resource, "GitHubFailedToMatchState",
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    if (UtilValidate.isEmpty(authorizationCode)) {
        String error = request.getParameter(PassportUtil.COMMON_ERROR);
        String errorDescpriton = request.getParameter(PassportUtil.COMMON_ERROR_DESCRIPTION);
        String errMsg = null;
        try {
            errMsg = UtilProperties.getMessage(resource, "FailedToGetGitHubAuthorizationCode",
                    UtilMisc.toMap(PassportUtil.COMMON_ERROR, error, PassportUtil.COMMON_ERROR_DESCRIPTION,
                            URLDecoder.decode(errorDescpriton, "UTF-8")),
                    UtilHttp.getLocale(request));
        } catch (UnsupportedEncodingException e) {
            errMsg = UtilProperties.getMessage(resource, "GetGitHubAuthorizationCodeError",
                    UtilHttp.getLocale(request));
        }
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    Debug.logInfo("GitHub authorization code: " + authorizationCode, module);

    GenericValue oauth2GitHub = getOAuth2GitHubConfig(request);
    if (UtilValidate.isEmpty(oauth2GitHub)) {
        String errMsg = UtilProperties.getMessage(resource, "GetOAuth2GitHubConfigError",
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    String clientId = oauth2GitHub.getString(PassportUtil.COMMON_CLIENT_ID);
    String secret = oauth2GitHub.getString(PassportUtil.COMMON_CLIENT_SECRET);
    String returnURI = oauth2GitHub.getString(PassportUtil.COMMON_RETURN_RUL);

    // Grant token from authorization code and oauth2 token
    // Use the authorization code to obtain an access token
    String accessToken = null;
    String tokenType = null;

    try {
        URI uri = new URIBuilder().setScheme(TokenEndpoint.substring(0, TokenEndpoint.indexOf(":")))
                .setHost(TokenEndpoint.substring(TokenEndpoint.indexOf(":") + 3)).setPath(TokenServiceUri)
                .setParameter("client_id", clientId).setParameter("client_secret", secret)
                .setParameter("code", authorizationCode).setParameter("redirect_uri", returnURI).build();
        HttpPost postMethod = new HttpPost(uri);
        CloseableHttpClient jsonClient = HttpClients.custom().build();
        // Debug.logInfo("GitHub get access token query string: " + postMethod.getURI(), module);
        postMethod.setConfig(PassportUtil.StandardRequestConfig);
        postMethod.setHeader(PassportUtil.ACCEPT_HEADER, "application/json");
        CloseableHttpResponse postResponse = jsonClient.execute(postMethod);
        String responseString = new BasicResponseHandler().handleResponse(postResponse);
        // Debug.logInfo("GitHub get access token response code: " + postResponse.getStatusLine().getStatusCode(), module);
        // Debug.logInfo("GitHub get access token response content: " + responseString, module);
        if (postResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            Debug.logInfo("Json Response from GitHub: " + responseString, module);
            JSON jsonObject = JSON.from(responseString);
            JSONToMap jsonMap = new JSONToMap();
            Map<String, Object> userMap = jsonMap.convert(jsonObject);
            accessToken = (String) userMap.get("access_token");
            tokenType = (String) userMap.get("token_type");
            // Debug.logInfo("Generated Access Token : " + accessToken, module);
            // Debug.logInfo("Token Type: " + tokenType, module);
        } else {
            String errMsg = UtilProperties.getMessage(resource, "GetOAuth2GitHubAccessTokenError",
                    UtilMisc.toMap("error", responseString), UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
    } catch (UnsupportedEncodingException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (IOException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (ConversionException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } catch (URISyntaxException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    }

    // Get User Profile
    HttpGet getMethod = new HttpGet(ApiEndpoint + UserApiUri);
    Map<String, Object> userInfo = null;
    try {
        userInfo = GitHubAuthenticator.getUserInfo(getMethod, accessToken, tokenType,
                UtilHttp.getLocale(request));
    } catch (AuthenticatorException e) {
        request.setAttribute("_ERROR_MESSAGE_", e.toString());
        return "error";
    } finally {
        getMethod.releaseConnection();
    }
    // Debug.logInfo("GitHub User Info:" + userInfo, module);

    // Store the user info and check login the user
    return checkLoginGitHubUser(request, userInfo, accessToken);
}

From source file:org.wuspba.ctams.ws.ITPersonController.java

private static void add(Person person) throws Exception {
    CTAMSDocument doc = new CTAMSDocument();
    doc.getPeople().add(person);/*from   w ww.  j  av a 2s  .co  m*/
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String xml = XMLUtils.marshal(doc);

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

        assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        for (Person p : doc.getPeople()) {
            if (p.getFirstName().equals(TestFixture.INSTANCE.andy.getFirstName())) {
                TestFixture.INSTANCE.andy.setId(p.getId());
            } else if (p.getFirstName().equals(TestFixture.INSTANCE.bob.getFirstName())) {
                TestFixture.INSTANCE.bob.setId(p.getId());
            } else if (p.getFirstName().equals(TestFixture.INSTANCE.elaine.getFirstName())) {
                TestFixture.INSTANCE.elaine.setId(p.getId());
            } else if (p.getFirstName().equals(TestFixture.INSTANCE.eoin.getFirstName())) {
                TestFixture.INSTANCE.eoin.setId(p.getId());
            } else if (p.getFirstName().equals(TestFixture.INSTANCE.jamie.getFirstName())) {
                TestFixture.INSTANCE.jamie.setId(p.getId());
            }
        }

        EntityUtils.consume(responseEntity);
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Unsupported coding", ex);
    } catch (IOException ioex) {
        LOG.error("IOException", ioex);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException ex) {
                LOG.error("Could not close response", ex);
            }
        }
    }
}