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:org.wikipedia.vlsergey.secretary.jwpf.HttpBot.java

protected void get(final HttpGet getMethod, final ContentProcessable action)
        throws IOException, CookieException, ProcessException {
    getMethod.getParams().setParameter("http.protocol.content-charset", MediaWikiBot.ENCODING);

    getMethod.setHeader("Accept-Encoding", GZIP_CONTENT_ENCODING);

    httpClient.execute(getMethod, new ResponseHandler<Object>() {
        @Override//from   w ww. ja  va 2 s  .c o m
        public Object handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {

            try {
                action.validateReturningCookies(httpClient.getCookieStore().getCookies(), getMethod);

                InputStream inputStream = httpResponse.getEntity().getContent();
                String contentEncoding = httpResponse.getEntity().getContentEncoding() != null
                        ? httpResponse.getEntity().getContentEncoding().getValue()
                        : "";
                if ("gzip".equalsIgnoreCase(contentEncoding))
                    inputStream = new GZIPInputStream(inputStream);

                int statuscode = httpResponse.getStatusLine().getStatusCode();

                if (statuscode == HttpStatus.SC_NOT_FOUND) {
                    log.warn("Not Found: " + getMethod.getRequestLine().getUri());
                    throw new FileNotFoundException(getMethod.getRequestLine().getUri());
                }
                if (statuscode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                    throw new ServerErrorException(httpResponse.getStatusLine());
                }
                if (statuscode != HttpStatus.SC_OK) {
                    throw new ClientProtocolException(httpResponse.getStatusLine().toString());
                }

                String encoding = StringUtils
                        .substringAfter(httpResponse.getEntity().getContentType().getValue(), "charset=");
                String out = IoUtils.readToString(inputStream, encoding);
                action.processReturningText(getMethod, out);
            } catch (CookieException exc) {
                throw new ClientProtocolException(exc);
            } catch (ProcessException exc) {
                throw new ClientProtocolException(exc);
            }
            return null;
        }
    });

}

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

public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws IOException, ClientProtocolException {
    stop_auth = false;//www . java2 s  .co  m
    try {
        return client.execute(target, request, context);
    } catch (RuntimeException ex) {
        throw new ClientProtocolException(ex.getMessage());
    }
}

From source file:org.modelio.vbasic.net.ApacheUriConnection.java

@objid("f8e1a3e4-45b3-4065-8838-90de7fe64eaa")
private void openConnection() throws IOException, IllegalStateException {
    this.context = HttpClientContext.create();

    CredentialsProvider credsProvider = new SystemDefaultCredentialsProvider();
    this.context.setCredentialsProvider(credsProvider);

    if (this.auth != null) {
        switch (this.auth.getSchemeId()) {
        case UserPasswordAuthData.USERPASS_SCHEME_ID:
            UserPasswordAuthData authData = (UserPasswordAuthData) this.auth;

            if (authData.getUser() == null)
                throw new ClientProtocolException(this.uri + ": User name may not be null.");

            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(authData.getUser(),
                    authData.getPassword());
            AuthScope authscope = new AuthScope(this.uri.getHost(), AuthScope.ANY_PORT);
            credsProvider.setCredentials(authscope, credentials);

            break;
        case NoneAuthData.AUTH_NONE_SCHEME_ID:
            break;

        default://from ww  w . j a v a2s . com
            throw new UnknownServiceException(this.auth + " not supported for " + this.uri);
        }
    }

    /** support different proxy */
    configProxy(credsProvider);

    getRequest().setConfig(this.configBuilder.build());

    try {
        this.res = httpclient.execute(getRequest(), this.context);
        int statusCode = this.res.getStatusLine().getStatusCode();

        if (statusCode >= 200 && statusCode < 300) {
            // Try to get content now to get an exception on failure immediately
            this.res.getEntity().getContent();
        } else {
            handleConnectionFailure();
        }

    } catch (ClientProtocolException e) {
        throw new IOException(e.getLocalizedMessage(), e);
    }
}

From source file:com.github.technosf.posterer.modules.commons.transport.CommonsResponseModelTaskImpl.java

/**
 * {@inheritDoc}/*www.  j a v  a  2 s . c o m*/
 * 
 * @see com.github.technosf.posterer.models.impl.base.AbstractResponseModelTask#getReponse()
 */
@SuppressWarnings("null")
@Override
protected HttpResponse getReponse(Auditor auditor) throws ClientProtocolException, IOException {
    this.auditor = auditor;

    if (client != null)
    /*
     * Execute the request
     */
    {
        return client.execute(httpUriRequest);
    }

    LOG.error(CONST_ERR_NULL_CLIENT);
    throw new ClientProtocolException(CONST_ERR_NULL_CLIENT);
}

From source file:com.networknt.client.ClientTest.java

public String callApiSync() throws Exception {

    String url = "http://localhost:8887/api";
    CloseableHttpClient client = Client.getInstance().getSyncClient();
    HttpGet httpGet = new HttpGet(url);
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        @Override/*from   ww  w  .  ja v  a  2  s.c o m*/
        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            Assert.assertEquals(200, status);
            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 responseBody = null;
    try {
        Client.getInstance().addAuthorizationWithScopeToken(httpGet, "Bearer token");
        responseBody = client.execute(httpGet, responseHandler);
        Assert.assertEquals("{\"message\":\"OK!\"}", responseBody);
        logger.debug("message = " + responseBody);
    } catch (Exception e) {
        e.printStackTrace();
        responseBody = "{\"message\":\"Error!\"}";
    }
    return responseBody;
}

From source file:com.google.appinventor.components.runtime.util.ClientLoginHelper.java

/**
 * Uses Google Account Manager to retrieve auth token that can
 * be used to access various Google APIs -- e.g., the Google Voice api.
 *///from w  w  w  .j a v a2 s. c o  m
public String getAuthToken() throws ClientProtocolException {
    Account account = accountChooser.findAccount();
    if (account != null) {
        AccountManagerFuture<Bundle> future;
        future = accountManager.getAuthToken(account, service, null, activity, null, null);
        Log.i(LOG_TAG, "Have account, auth token: " + future);
        Bundle result;
        try {
            result = future.getResult();
            return result.getString(AccountManager.KEY_AUTHTOKEN);
        } catch (AuthenticatorException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (OperationCanceledException e) {
            e.printStackTrace();
        }
    }
    throw new ClientProtocolException("Can't get valid authentication token");
}

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

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

From source file:gov.nasa.arc.geocam.talk.service.TalkServer.java

/**
 * Creates a talk message on the server/*from  w ww. ja  v a  2s  .co  m*/
 *
 * @param message the message
 * @throws ClientProtocolException the client protocol exception
 * @throws AuthenticationFailedException the authentication failed exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws SQLException the sQL exception
 */
public void createTalkMessage(GeoCamTalkMessage message)
        throws ClientProtocolException, AuthenticationFailedException, IOException, SQLException {
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("message", jsonConverter.serialize(message));
    message.setSynchronized(true);
    messageStore.updateMessage(message);
    ServerResponse sr = siteAuth.post(urlCreateMessage, map, message.getAudio());
    if (sr.getResponseCode() == 401) {
        siteAuth.reAuthenticate();
        sr = siteAuth.post(urlCreateMessage, map, message.getAudio());
    }
    if (sr.getResponseCode() == 200) {
        // read content to string
        Map<String, String> result = jsonConverter.createMap(sr.getContent());
        try {
            message.setMessageId(Integer.parseInt(result.get("messageId")));
            message.setAuthorFullname(result.get("authorFullname"));
            if (result.containsKey("audioUrl")) {
                message.setAudioUrl(result.get("audioUrl"));
            }
        } catch (Exception e) {
            Log.e("Talk", "", e);
        }
        message.setSynchronized(true);
        messageStore.updateMessage(message);
        intentHelper.BroadcastNewMessages();
    } else {
        message.setSynchronized(false);
        messageStore.updateMessage(message);
        throw new ClientProtocolException(
                "Message could not be created (HTTP error " + sr.getResponseCode() + ")");
    }
}

From source file:org.dataconservancy.ui.services.EZIDServiceImplTest.java

/**
 * Tests exceptional conditions when calling the create method, including bad return code and unexpect return format
 * @throws ClientProtocolException//from  ww  w  . j a va2  s  .  c om
 * @throws IOException
 */
@Test
public void testCreateExceptions() throws ClientProtocolException, IOException {
    HttpResponse mockResponse = new BasicHttpResponse(new HttpVersion(1, 1), 201, "created");
    StringEntity entity = new StringEntity("success: namespace:id");
    mockResponse.setEntity(entity);

    HttpClient mockHttpClient = mock(HttpClient.class);
    when(mockHttpClient.execute(any(HttpPost.class)))
            .thenThrow(new ClientProtocolException("Expected exception"));

    ezidService.setHttpClient(mockHttpClient);

    boolean caughtException = false;
    try {
        ezidService.createID(metadata);
    } catch (EZIDServiceException e) {
        caughtException = true;
        assertEquals("org.apache.http.client.ClientProtocolException: Expected exception", e.getMessage());
    }

    assertTrue(caughtException);

    mockResponse = new BasicHttpResponse(new HttpVersion(1, 1), 404, "not found");
    mockResponse.setEntity(entity);

    mockHttpClient = mock(HttpClient.class);
    when(mockHttpClient.execute(any(HttpPost.class))).thenReturn(mockResponse);

    ezidService.setHttpClient(mockHttpClient);

    caughtException = false;
    try {
        ezidService.createID(metadata);
    } catch (EZIDServiceException e) {
        caughtException = true;
        assertTrue(e.getMessage().contains("not found"));
    }

    assertTrue(caughtException);

    mockResponse = new BasicHttpResponse(new HttpVersion(1, 1), 201, "created");
    entity = new StringEntity("namespace:id");
    mockResponse.setEntity(entity);

    mockHttpClient = mock(HttpClient.class);
    when(mockHttpClient.execute(any(HttpPost.class))).thenReturn(mockResponse);

    ezidService.setHttpClient(mockHttpClient);

    caughtException = false;
    try {
        ezidService.createID(metadata);
    } catch (EZIDServiceException e) {
        caughtException = true;
        assertEquals("Unexpected response: namespace:id", e.getMessage());
    }

    assertTrue(caughtException);
}

From source file:org.jboss.arquillian.container.was.wlp_remote_8_5.WLPRestClient.java

/**
 * Calls the rest api to determine if the application server is up and
 * running./*w  w  w.  j  a v  a2s. c o m*/
 * 
 * @return boolean - true if the server is running
 */
public boolean isServerUp() throws ClientProtocolException, IOException {
    if (log.isLoggable(Level.FINER)) {
        log.entering(className, "isServerUp");
    }

    String hostName = String.format("https://%s:%d%s", configuration.getHostName(),
            configuration.getHttpsPort(), IBMJMX_CONNECTOR_REST);

    HttpResponse result = executor.execute(Request.Get(hostName)).returnResponse();

    if (!isSuccessful(result)) {
        throw new ClientProtocolException(
                "Could not successfully connect to REST endpoint, server returned response: " + result);
    }

    if (log.isLoggable(Level.FINER)) {
        log.exiting(className, "isServerUp");
    }
    return isSuccessful(result);
}