Example usage for org.apache.http.client ClientProtocolException ClientProtocolException

List of usage examples for org.apache.http.client ClientProtocolException ClientProtocolException

Introduction

In this page you can find the example usage for org.apache.http.client ClientProtocolException ClientProtocolException.

Prototype

public ClientProtocolException(final Throwable cause) 

Source Link

Usage

From source file:com.infinities.keystone4j.PatchClient.java

public JsonNode connect(Object obj) throws ClientProtocolException, IOException {
    String input = JsonUtils.toJsonWithoutPrettyPrint(obj);
    logger.debug("input: {}", input);
    StringEntity requestEntity = new StringEntity(input, ContentType.create("application/json", Consts.UTF_8));

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from  ww  w  .  ja v a  2  s  . co  m
        HttpPatch request = new HttpPatch(url);
        request.addHeader("accept", "application/json");
        request.addHeader("X-Auth-Token", Config.Instance.getOpt(Config.Type.DEFAULT, "admin_token").asText());
        request.setEntity(requestEntity);
        ResponseHandler<JsonNode> rh = new ResponseHandler<JsonNode>() {

            @Override
            public JsonNode handleResponse(final HttpResponse response) throws IOException {
                StatusLine statusLine = response.getStatusLine();
                HttpEntity entity = response.getEntity();
                if (entity == null) {
                    throw new ClientProtocolException("Response contains no content");
                }
                String output = getStringFromInputStream(entity.getContent());
                logger.debug("output: {}", output);
                assertEquals(200, statusLine.getStatusCode());

                JsonNode node = JsonUtils.convertToJsonNode(output);
                return node;
            }

            private String getStringFromInputStream(InputStream is) {

                BufferedReader br = null;
                StringBuilder sb = new StringBuilder();

                String line;
                try {

                    br = new BufferedReader(new InputStreamReader(is));
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                return sb.toString();

            }
        };
        JsonNode node = httpclient.execute(request, rh);

        return node;
    } finally {
        httpclient.close();
    }
}

From source file:eu.bittrade.libs.steemj.communication.HttpClient.java

@Override
public JsonRPCResponse invokeAndReadResponse(JsonRPCRequest requestObject, URI endpointUri,
        boolean sslVerificationDisabled) throws SteemCommunicationException {
    try {//from  w ww .ja  v  a2 s.  co  m
        NetHttpTransport.Builder builder = new NetHttpTransport.Builder();
        // Disable SSL verification if needed
        if (sslVerificationDisabled && endpointUri.getScheme().equals("https")) {
            builder.doNotValidateCertificate();
        }

        String requestPayload = requestObject.toJson();
        HttpRequest httpRequest = builder.build().createRequestFactory(new HttpClientRequestInitializer())
                .buildPostRequest(new GenericUrl(endpointUri),
                        ByteArrayContent.fromString("application/json", requestPayload));

        LOGGER.debug("Sending {}.", requestPayload);

        HttpResponse httpResponse = httpRequest.execute();

        int status = httpResponse.getStatusCode();
        String responsePayload = httpResponse.parseAsString();

        if (status >= 200 && status < 300 && responsePayload != null) {
            return new JsonRPCResponse(CommunicationHandler.getObjectMapper().readTree(responsePayload));
        } else {
            throw new ClientProtocolException("Unexpected response status: " + status);
        }

    } catch (GeneralSecurityException | IOException e) {
        throw new SteemCommunicationException("A problem occured while processing the request.", e);
    }
}

From source file:com.baifendian.swordfish.common.hadoop.YarnRestClient.java

/**
 * ??/*www  . j  a  va2s  . co  m*/
 *
 * @param appId
 * @return ? null, ??
 * @throws JSONException
 * @throws IOException
 */
public FlowStatus getApplicationStatus(String appId) throws JSONException, IOException {
    if (StringUtils.isEmpty(appId)) {
        return null;
    }

    String url = ConfigurationUtil.getApplicationStatusAddress(appId);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(url);

    ResponseHandler<Pair<Integer, String>> rh = response -> {
        StatusLine statusLine = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        if (statusLine.getStatusCode() >= 300) {
            if (statusLine.getStatusCode() == 404 || statusLine.getStatusCode() == 330) {
                return null;
            }

            throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
        }

        if (entity == null) {
            throw new ClientProtocolException("Response contains no content");
        }

        String content = EntityUtils.toString(entity);

        JSONObject o = null;
        try {
            o = new JSONObject(content);
        } catch (JSONException e) {
            throw new HttpResponseException(statusLine.getStatusCode(), content);
        }

        if (!o.has("app") || o.isNull("app")) {
            throw new RuntimeException("Response content not valid " + content);
        }

        try {
            return Pair.of(statusLine.getStatusCode(), o.getJSONObject("app").getString("finalStatus"));
        } catch (JSONException e) {
            throw new HttpResponseException(statusLine.getStatusCode(), content);
        }
    };

    Pair<Integer, String> pair = httpclient.execute(httpget, rh);

    if (pair == null) {
        return null;
    }

    switch (pair.getRight()) {
    case "FAILED":
        return FlowStatus.FAILED;
    case "KILLED":
        return FlowStatus.KILL;
    case "SUCCEEDED":
        return FlowStatus.SUCCESS;
    case "NEW":
    case "NEW_SAVING":
    case "SUBMITTED":
    case "ACCEPTED":
        return FlowStatus.INIT;
    case "RUNNING":
    default:
        return FlowStatus.RUNNING;
    }
}

From source file:com.thed.zephyr.jenkins.utils.rest.Cycle.java

public static Long createCycle(ZephyrConfigModel zephyrData) {

    Long cycleId = 0L;//from   w  w  w. ja  va  2 s  .c o m

    HttpResponse response = null;
    try {
        String createCycleURL = URL_CREATE_CYCLES.replace("{SERVER}", zephyrData.getRestClient().getUrl());

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("E dd, yyyy hh:mm a");
        String dateFormatForCycleCreation = sdf.format(date);

        JSONObject jObject = new JSONObject();
        String cycleName = zephyrData.getCyclePrefix() + dateFormatForCycleCreation;

        SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MMM/yy");
        String startDate = sdf1.format(date);

        GregorianCalendar gCal = new GregorianCalendar();

        if (zephyrData.getCycleDuration().trim().equalsIgnoreCase("30 days")) {
            gCal.add(Calendar.DAY_OF_MONTH, +29);
        } else if (zephyrData.getCycleDuration().trim().equalsIgnoreCase("7 days")) {
            gCal.add(Calendar.DAY_OF_MONTH, +6);
        }

        String endDate = sdf1.format(gCal.getTime());

        jObject.put("name", cycleName);
        jObject.put("projectId", zephyrData.getZephyrProjectId());
        jObject.put("versionId", zephyrData.getVersionId());
        jObject.put("startDate", startDate);
        jObject.put("endDate", endDate);

        StringEntity se = new StringEntity(jObject.toString(), "utf-8");

        HttpPost createCycleRequest = new HttpPost(createCycleURL);

        createCycleRequest.setHeader("Content-Type", "application/json");
        createCycleRequest.setEntity(se);
        response = zephyrData.getRestClient().getHttpclient().execute(createCycleRequest,
                zephyrData.getRestClient().getContext());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode >= 200 && statusCode < 300) {
        HttpEntity entity = response.getEntity();
        String string = null;
        try {
            string = EntityUtils.toString(entity);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            JSONObject cycleObj = new JSONObject(string);
            cycleId = cycleObj.getLong("id");

        } catch (JSONException e) {
            e.printStackTrace();
        }

    } else if (statusCode == 405) {

        try {
            throw new ClientProtocolException("ZAPI plugin license is invalid" + statusCode);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        }

    } else {
        try {
            throw new ClientProtocolException("Unexpected response status: " + statusCode);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        }
    }

    return cycleId;
}

From source file:atc.otn.ckan.client.CKANClient.java

/**
 * //w  w w  .  ja va2  s .  c o  m
 * @return
 */
private ResponseHandler<String> getGenericResponseHandler() {

    // Create a custom response handler
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        @Override
        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();

            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException(
                        "Unexpected response status: " + status + EntityUtils.toString(response.getEntity()));
            }
        }
    };

    return responseHandler;

}

From source file:co.com.soinsoftware.altablero.utils.HttpRequest.java

@Override
public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    int status = response.getStatusLine().getStatusCode();
    if (status >= 200 && status < 300) {
        HttpEntity entity = response.getEntity();
        final ContentType contentType = ContentType.getOrDefault(entity);
        if (contentType.getMimeType().equals(ContentType.APPLICATION_OCTET_STREAM.getMimeType())) {
            InputStream inputStream = null;
            byte[] zipInBytes = EntityUtils.toByteArray(entity);
            if (zipInBytes != null) {
                inputStream = new ByteArrayInputStream(zipInBytes);
            }/*  ww w.j  ava  2  s  .  c  o m*/
            return inputStream;
        }
        return entity != null ? EntityUtils.toString(entity) : null;
    } else {
        throw new ClientProtocolException(EXCEPTION_MESSAGE + status);
    }
}

From source file:com.seleritycorp.context.RequestUtilsTest.java

@Test
public void testPostRequestClientProtocolException() throws Exception {
    JsonObject payload = new JsonObject();
    payload.addProperty("foo", "bar/baz");

    Exception e = new ClientProtocolException("catch me");

    Capture<HttpUriRequest> requestCapture = newCapture();
    Capture<ResponseHandler<JsonObject>> handlerCapture = newCapture();
    expect(httpClient.execute(capture(requestCapture), capture(handlerCapture))).andThrow(e);
    httpClient.close();/*from   w w  w. ja va 2s . co  m*/

    replayAll();

    RequestUtils requestUtils = createRequestUtilsPartialMock();
    try {
        requestUtils.post("pathFoo", payload);
        failBecauseExceptionWasNotThrown(ClientProtocolException.class);
    } catch (ClientProtocolException actual) {
        assertThat(actual.getMessage()).contains("catch me");
    }

    verifyAll();

    verifyPostRequest(requestCapture);
    verifyHandler(handlerCapture);
}

From source file:gov.nasa.arc.geocam.memo.service.DjangoMemoImplementation.java

@Override
public void createMemo(GeoCamMemoMessage message)
        throws ClientProtocolException, AuthenticationFailedException, IOException {
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("message", jsonConverter.serialize(message));
    int responseCode = siteAuthImplementation.post(createMemoMessageJson, map);
    if (responseCode != 200) {
        throw new ClientProtocolException("Message could not be created (HTTP error " + responseCode + ")");
    }/* w  ww.  j  av a  2 s . com*/
}

From source file:br.edu.ifrn.SuapClient.java

public String getData() {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*  w w w.  j  a  va 2  s . c  om*/
        //Obtem as informaes bsicas do usurio logado no SUAP
        String url = "https://suap.ifrn.edu.br/api/v2/minhas-informacoes/meus-dados/";
        HttpGet httpget = new HttpGet(url);

        httpget.addHeader("Accept", "application/json");
        httpget.addHeader("X-CSRFToken", TOKEN);
        httpget.addHeader("Authorization", AUTH);

        System.out.println("Executing request " + httpget.getRequestLine());

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

        };
        String response = httpclient.execute(httpget, responseHandler);
        System.out.println("----------------------------------------");
        return response;
    } catch (IOException io) {
        System.out.println(io.getMessage());
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return "";
}