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.thed.zapi.cloud.sample.CreateCycleAndAddTests.java

public String createCycle(String uriStr, ZFJCloudRestClient client, String accessKey, StringEntity cycleJSON)
        throws URISyntaxException, JSONException {

    URI uri = new URI(uriStr);
    int expirationInSec = 360;
    JwtGenerator jwtGenerator = client.getJwtGenerator();
    String jwt = jwtGenerator.generateJWT("POST", uri, expirationInSec);
    System.out.println(uri.toString());
    System.out.println(jwt);/*from  w  w w .  j  a va 2 s  .co m*/

    HttpResponse response = null;
    HttpClient restClient = new DefaultHttpClient();

    HttpPost createCycleReq = new HttpPost(uri);
    createCycleReq.addHeader("Content-Type", "application/json");
    createCycleReq.addHeader("Authorization", jwt);
    createCycleReq.addHeader("zapiAccessKey", accessKey);
    createCycleReq.setEntity(cycleJSON);

    try {
        response = restClient.execute(createCycleReq);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    int statusCode = response.getStatusLine().getStatusCode();
    System.out.println(statusCode);
    String cycleId = "-1";
    if (statusCode >= 200 && statusCode < 300) {
        HttpEntity entity = response.getEntity();
        String string = null;
        try {
            string = EntityUtils.toString(entity);
            JSONObject cycleObj = new JSONObject(string);
            cycleId = cycleObj.getString("id");
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

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

From source file:ss.udapi.sdk.services.HttpServices.java

public ServiceRequest processLogin(ServiceRequest loginReq, String relation, String name) throws Exception {

    if (loginReq == null)
        throw new IllegalArgumentException("loginReq must be a valid request");

    logger.info("Preparing request for: " + name);
    CloseableHttpClient httpClient = HttpClients.custom().setKeepAliveStrategy(loginTimeout).build();
    List<RestItem> serviceRestItems = null;
    ServiceRequest serviceRequest = new ServiceRequest();

    RestItem loginDetails = getRestItems(loginReq, name);
    if (loginDetails == null) {
        logger.error("Link not found for request " + name);
        return null;
    }/*from  w ww .  ja  va2 s .c o m*/

    RestLink link = getLink(loginDetails, relation);
    if (link == null) {
        logger.error("Relation not found for relation: " + relation + " for " + name);
        return null;
    }

    CloseableHttpResponse response = null;
    try {

        HttpUriRequest httpAction = new HttpPost(link.getHref());
        if (compressionEnabled == true) {
            httpAction.setHeader("Accept-Encoding", "gzip");
        }

        httpAction.setHeader("X-Auth-User", SystemProperties.get("ss.username"));
        httpAction.setHeader("X-Auth-Key", SystemProperties.get("ss.password"));
        httpAction.setHeader("Content-Type", "application/json");

        // Send the request of to retrieve the Authentication Token and the
        // list of available services.
        response = httpClient.execute(httpAction);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new ClientProtocolException("Unexpected response status: "
                    + response.getStatusLine().getStatusCode() + " while retrieving services for: " + name);
        }

        if (response.getFirstHeader("X-Auth-Token") == null)
            throw new ClientProtocolException("Unexpected response: no auth token found");

        serviceAuthToken = response.getFirstHeader("X-Auth-Token").getValue();

        serviceRequest.setAuthToken(serviceAuthToken);
        HttpEntity entity = response.getEntity();
        String jsonResponse = new String(EntityUtils.toByteArray(entity));
        serviceRestItems = JsonHelper.toRestItems(jsonResponse);
        serviceRequest.setServiceRestItems(serviceRestItems);

        return serviceRequest;

    } catch (ClientProtocolException protEx) {
        logger.error(
                "Invalid Client Protocol: " + protEx.getMessage() + " while retrieving services for: " + name);
        throw protEx;
    } catch (IOException ioEx) {
        logger.error("Communication error" + ioEx.getCause() + " while retrieving services for: " + name);
        throw ioEx;
    } finally {
        try {
            httpClient.close();
        } catch (IOException ex) {
            // Can safely be ignored, either the server closed the
            // connection or we didn't open it so there's nothing to do
        }
    }
}

From source file:net.shirayu.android.WlanLogin.MyHttpClient.java

public <T> T execute(HttpHost host, HttpRequest request, ResponseHandler<? extends T> handler)
        throws IOException, ClientProtocolException {
    stop_auth = false;/*from w  w w  .j av  a  2  s.co  m*/
    try {
        return client.execute(host, request, handler);
    } catch (RuntimeException ex) {
        throw new ClientProtocolException(ex.getMessage());
    }
}

From source file:com.apigee.sdk.apm.http.impl.client.cache.ResponseProtocolCompliance.java

private void authenticationRequiredDidNotHaveAProxyAuthenticationHeader(HttpRequest request,
        HttpResponse response) throws ClientProtocolException {
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
        return;/* w w  w. j a  va 2  s .co m*/

    if (response.getFirstHeader(HeaderConstants.PROXY_AUTHENTICATE) == null)
        throw new ClientProtocolException("407 Response did not contain a Proxy-Authentication header");
}

From source file:org.aludratest.service.gui.web.selenium.TAFMSSeleniumResourceService.java

@Override
public String acquire() {
    // prepare a JSON query to the given TAFMS server
    JSONObject query = new JSONObject();

    try {//from w ww  . java 2  s  .c  om
        query.put("resourceType", "selenium");
        query.put("niceLevel", configuration.getIntValue("tafms.niceLevel", 0));
        String jobName = configuration.getStringValue("tafms.jobName");
        if (jobName != null && !"".equals(jobName)) {
            query.put("jobName", jobName);
        }
    } catch (JSONException e) {
    }

    // prepare authentication
    BasicCredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
            configuration.getStringValue("tafms.user"), configuration.getStringValue("tafms.password")));

    CloseableHttpClient client = HttpClientBuilder.create()
            .setConnectionReuseStrategy(new NoConnectionReuseStrategy()).disableConnectionState()
            .disableAutomaticRetries().setDefaultCredentialsProvider(provider).build();

    String message = null;
    try {
        boolean wait;

        // use preemptive authentication to avoid double connection count
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        URL url = new URL(getTafmsUrl());
        HttpHost host = new HttpHost(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort(),
                url.getProtocol());
        authCache.put(host, basicAuth);

        // Add AuthCache to the execution context
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

        do {
            // send a POST request to resource URL
            HttpPost request = new HttpPost(getTafmsUrl() + "resource");

            // attach query as JSON string data
            request.setEntity(new StringEntity(query.toString(), ContentType.APPLICATION_JSON));

            CloseableHttpResponse response = null;

            // fire request
            response = client.execute(request, localcontext);

            try {
                if (response.getStatusLine() == null) {
                    throw new ClientProtocolException("No HTTP status line transmitted");
                }

                message = extractMessage(response);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    LOG.error("Exception when querying TAFMS server for resource. HTTP Status: "
                            + response.getStatusLine().getStatusCode() + ", message: " + message);
                    return null;
                }

                JSONObject object = new JSONObject(message);
                if (object.has("errorMessage")) {
                    LOG.error("TAFMS server reported an error: " + object.get("errorMessage"));
                    return null;
                }

                // continue wait?
                if (object.has("waiting") && object.getBoolean("waiting")) {
                    wait = true;
                    query.put("requestId", object.getString("requestId"));
                } else {
                    JSONObject resource = object.optJSONObject("resource");
                    if (resource == null) {
                        LOG.error("TAFMS server response did not provide a resource. Message was: " + message);
                        return null;
                    }

                    String sUrl = resource.getString("url");
                    hostResourceIds.put(sUrl, object.getString("requestId"));

                    return sUrl;
                }
            } finally {
                IOUtils.closeQuietly(response);
            }
        } while (wait);

        // should never come here
        return null;
    } catch (ClientProtocolException e) {
        LOG.error("Exception in HTTP transmission", e);
        return null;
    } catch (IOException e) {
        LOG.error("Exception in communication with TAFMS server", e);
        return null;
    } catch (JSONException e) {
        LOG.error("Invalid JSON received from TAFMS server. JSON message was: " + message, e);
        return null;
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:org.oscarehr.fax.core.FaxImporter.java

private void deleteFax(DefaultHttpClient client, FaxConfig faxConfig, FaxJob fax)
        throws ClientProtocolException, IOException {
    HttpDelete mDelete = new HttpDelete(
            faxConfig.getUrl() + PATH + "/" + faxConfig.getFaxUser() + "/" + fax.getFile_name());
    mDelete.setHeader("accept", "application/json");
    mDelete.setHeader("user", faxConfig.getFaxUser());
    mDelete.setHeader("passwd", faxConfig.getFaxPasswd());

    HttpResponse response = client.execute(mDelete);
    mDelete.releaseConnection();/*from   ww  w . ja v a 2  s .co m*/

    if (!(response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT)) {
        throw new ClientProtocolException("CANNOT DELETE " + fax.getFile_name());
    }

}

From source file:net.shirayu.android.WlanLogin.MyHttpClient.java

public <T> T execute(HttpHost host, HttpRequest request, ResponseHandler<? extends T> handler,
        HttpContext context) throws IOException, ClientProtocolException {
    stop_auth = false;// www . java  2 s.  c  om
    try {
        return client.execute(host, request, handler, context);
    } catch (RuntimeException ex) {
        throw new ClientProtocolException(ex.getMessage());
    }
}

From source file:com.apigee.sdk.apm.http.impl.client.cache.ResponseProtocolCompliance.java

private void notAllowedResponseDidNotHaveAnAllowHeader(HttpRequest request, HttpResponse response)
        throws ClientProtocolException {
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_METHOD_NOT_ALLOWED)
        return;/*from  w ww  . ja v a  2s . co m*/

    if (response.getFirstHeader(HeaderConstants.ALLOW) == null)
        throw new ClientProtocolException("405 Response did not contain an Allow header.");
}

From source file:org.muhia.app.psi.config.http.CustomHttpClientUtilities.java

public String doGetWithResponseHandler(String url, String[] replaceParams, String[] params) {
    String result;// ww  w .  java  2s.  com
    // CloseableHttpResponse response = null;
    CloseableHttpClient client = null;
    try {
        if (replaceParams.length > 0) {
            for (int i = 0; i < replaceParams.length; i++) {
                Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.FINE, replaceParams[i],
                        params[i]);
                url = url.replaceAll(replaceParams[i], params[i]);
            }
        }

        RequestConfig config = RequestConfig.custom().setConnectTimeout(hcp.getConnectionTimeout())
                .setConnectionRequestTimeout(hcp.getConnectionRequestTimeout())
                .setSocketTimeout(hcp.getSockectTimeout()).build();

        client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();

        HttpGet getMethod = new HttpGet(url);

        ResponseHandler<String> responseHandler = (final HttpResponse response) -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= hcp.getLowerStatusLimit() && status <= hcp.getUpperStatusLimit()) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException(hcp.getExceptionMessage() + status);
            }
        };

        result = client.execute(getMethod, responseHandler);
        client.close();

    } catch (SocketTimeoutException ex) {
        result = hcp.getTimeoutMessage();
        Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        result = hcp.getFailMessage();
        Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (client != null) {
                client.close();
            }

        } catch (IOException ex) {
            Logger.getLogger(CustomHttpClientUtilities.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return result;
}

From source file:com.netflix.http4.NFHttpClient.java

private static HttpHost determineTarget(HttpUriRequest request) throws ClientProtocolException {
    // A null target may be acceptable if there is a default target.
    // Otherwise, the null target is detected in the director.
    HttpHost target = null;//www.j  ava2 s .co m
    URI requestURI = request.getURI();
    if (requestURI.isAbsolute()) {
        target = URIUtils.extractHost(requestURI);
        if (target == null) {
            throw new ClientProtocolException("URI does not specify a valid host name: " + requestURI);
        }
    }
    return target;
}