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

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

Introduction

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

Prototype

public HttpResponseException(final int statusCode, final String s) 

Source Link

Usage

From source file:de.catma.document.source.contenthandler.HttpResponseHandler.java

public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    Header[] headers = response.getHeaders("Content-Type");
    if (headers.length > 0) {
        contentType = headers[0].getValue();
    }/* ww  w  .j av  a 2s .c  o m*/
    // TODO: Content-Encoding, hanle compressed content

    StatusLine statusLine = response.getStatusLine();
    HttpEntity entity = response.getEntity();
    if (statusLine.getStatusCode() >= 300) {
        try {
            EntityUtils.toByteArray(entity);
        } catch (IOException notOfInterest) {
        }
        throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
    }
    return entity == null ? null : EntityUtils.toByteArray(entity);
}

From source file:org.stem.api.JsonResponseHandler.java

@Override
public StemResponse handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
    StatusLine status = response.getStatusLine();
    HttpEntity entity = response.getEntity();
    InputStream content = entity.getContent();

    if (status.getStatusCode() >= 300) {
        try {//from w  w w.jav  a  2s. c o  m
            ErrorResponse errorResponse = JsonUtils.decode(content, ErrorResponse.class);

            String message = String.format("%s [%s]: Code: %s, Message: %s", status.getReasonPhrase(),
                    status.getStatusCode(), errorResponse.getErrorCode(), errorResponse.getError());

            throw new HttpResponseException(status.getStatusCode(), message);
        } catch (RuntimeException e) {
            throw new HttpResponseException(status.getStatusCode(), status.getReasonPhrase());
        }
    }

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

    //SimpleType simpleType = SimpleType.construct(clazz);
    return JsonUtils.decode(content, clazz);
}

From source file:com.puppetlabs.geppetto.forge.v2.service.ForgeService.java

/**
 * Resolves a HAL link into a proper instance.
 * /*from  www  .  j av a 2s .  co  m*/
 * @param link
 *            The link to resolve
 * @param type
 *            The type of the instance
 * @return The resolved instance.
 * @throws IOException
 *             If the link could not be resolved.
 */
public <T> T resolveLink(HalLink link, Class<T> type) throws IOException {
    if (link == null)
        return null;

    String href = link.getHref();
    if (href == null)
        return null;

    if (!href.startsWith("/v2/"))
        throw new HttpResponseException(404, "Not found: " + href);

    return getClient(false).get(href.substring(4), null, type);
}

From source file:de.incoherent.suseconferenceclient.app.HTTPWrapper.java

public static Bitmap getImage(String url) throws ClientProtocolException, IOException {
    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);
    Log.d("SUSEConferences", "Get: " + url);
    HttpResponse response = client.execute(get);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode >= 200 && statusCode <= 299) {
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent();
                final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }//from  www  .j  ava2s .co  m
                entity.consumeContent();
            }
        } else {
            throw new HttpResponseException(statusCode, statusLine.getReasonPhrase());
        }
    } else {
        throw new HttpResponseException(statusCode, statusLine.getReasonPhrase());
    }
}

From source file:io.encoded.jersik.runtime.client.AbstractServiceClient.java

protected <S, T> T execute(String operationName, S request, ObjectCodec<S> requestCodec,
        ObjectCodec<T> responseCodec) throws IOException {
    URI operationUri = serviceUri.resolve(operationName);
    HttpPost post = new HttpPost(operationUri);
    post.setEntity(new RequestEntity<S>(request, requestCodec, JsonCodec.INSTANCE));
    HttpResponse httpResponse = httpClient.execute(post);
    StatusLine statusLine = httpResponse.getStatusLine();
    if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
        consume(httpResponse.getEntity());
        throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
    }/*ww w. j av a 2s  . c o  m*/
    return JsonCodec.INSTANCE.decode(httpResponse.getEntity().getContent(), responseCodec);
}

From source file:org.dasein.cloud.utils.requester.DaseinResponseHandler.java

@Override
public T handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
    if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK
            && httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT
            && httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED
            && httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_ACCEPTED) {
        throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                EntityUtils.toString(httpResponse.getEntity()));
    } else {/*from w  w w  . java 2 s . c  om*/
        if (httpResponse.getEntity() == null)
            return null;

        return processor.read(httpResponse.getEntity().getContent(), classType);
    }
}

From source file:com.liferay.sync.engine.document.library.handler.GetSyncContextHandler.java

protected SyncContext doProcessResponse(String response) throws Exception {
    SyncContext syncContext = JSONUtil.readValue(response, SyncContext.class);

    SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(getSyncAccountId());

    SyncUser remoteSyncUser = syncContext.getSyncUser();

    if (remoteSyncUser == null) {
        throw new HttpResponseException(HttpStatus.SC_UNAUTHORIZED, "Authenticated access required");
    }//from ww w. j a v  a 2 s.co  m

    SyncUser localSyncUser = SyncUserService.fetchSyncUser(syncAccount.getSyncAccountId());

    if (localSyncUser == null) {
        remoteSyncUser.setSyncAccountId(getSyncAccountId());

        localSyncUser = SyncUserService.update(remoteSyncUser);
    }

    if ((localSyncUser.getUserId() > 0) && (localSyncUser.getUserId() != remoteSyncUser.getUserId())) {

        syncAccount.setState(SyncAccount.STATE_DISCONNECTED);
        syncAccount.setUiEvent(SyncAccount.UI_EVENT_AUTHENTICATION_EXCEPTION);

        SyncAccountService.update(syncAccount);

        return syncContext;
    }

    if (!syncAccount.isOAuthEnabled()) {
        String login = syncAccount.getLogin();

        if (login == null) {
            login = "";
        }

        String authType = syncContext.getAuthType();

        if (authType.equals(SyncContext.AUTH_TYPE_EMAIL_ADDRESS)) {
            if (!login.equals(remoteSyncUser.getEmailAddress())) {
                syncAccount.setLogin(remoteSyncUser.getEmailAddress());
            }
        } else if (authType.equals(SyncContext.AUTH_TYPE_SCREEN_NAME)) {
            if (!login.equals(remoteSyncUser.getScreenName())) {
                syncAccount.setLogin(remoteSyncUser.getScreenName());
            }
        } else if (authType.equals(SyncContext.AUTH_TYPE_USER_ID)) {
            if (!login.equals(String.valueOf(remoteSyncUser.getUserId()))) {
                syncAccount.setLogin(String.valueOf(remoteSyncUser.getUserId()));
            }
        }
    }

    remoteSyncUser.setSyncAccountId(localSyncUser.getSyncAccountId());
    remoteSyncUser.setSyncUserId(localSyncUser.getSyncUserId());

    SyncUserService.update(remoteSyncUser);

    Map<String, String> portletPreferencesMap = syncContext.getPortletPreferencesMap();

    int authenticationRetryInterval = GetterUtil.getInteger(
            portletPreferencesMap.get(SyncContext.PREFERENCE_KEY_AUTHENTICATION_RETRY_INTERVAL), 60);

    syncAccount.setAuthenticationRetryInterval(authenticationRetryInterval);

    int batchFileMaxSize = GetterUtil
            .getInteger(portletPreferencesMap.get(SyncContext.PREFERENCE_KEY_BATCH_FILE_MAX_SIZE));

    syncAccount.setBatchFileMaxSize(batchFileMaxSize);

    syncAccount.setLanCertificate(syncContext.getLanCertificate());
    syncAccount.setLanEnabled(syncContext.getLanEnabled());
    syncAccount.setLanKey(syncContext.getLanKey());
    syncAccount.setLanServerUuid(syncContext.getLanServerUuid());

    int maxConnections = GetterUtil
            .getInteger(portletPreferencesMap.get(SyncContext.PREFERENCE_KEY_MAX_CONNECTIONS), 1);

    syncAccount.setMaxConnections(maxConnections);

    int maxDownloadRate = GetterUtil
            .getInteger(portletPreferencesMap.get(SyncContext.PREFERENCE_KEY_MAX_DOWNLOAD_RATE));

    syncAccount.setMaxDownloadRate(maxDownloadRate);

    int maxUploadRate = GetterUtil
            .getInteger(portletPreferencesMap.get(SyncContext.PREFERENCE_KEY_MAX_UPLOAD_RATE));

    syncAccount.setMaxUploadRate(maxUploadRate);

    syncAccount.setPluginVersion(syncContext.getPluginVersion());

    int pollInterval = GetterUtil
            .getInteger(portletPreferencesMap.get(SyncContext.PREFERENCE_KEY_POLL_INTERVAL), 5);

    syncAccount.setPollInterval(pollInterval);

    syncAccount.setSocialOfficeInstalled(syncContext.isSocialOfficeInstalled());

    SyncAccountService.update(syncAccount);

    return syncContext;
}

From source file:org.workin.http.httpclient.v4.handler.response.AbstractResponseHandler.java

/**
 * @description ??/* ww w.j  a v a2  s.c  om*/
 * @author <a href="mailto:code727@gmail.com">?</a> 
 * @param response
 * @return
 * @throws IOException
 */
protected String doResponse(HttpResponse response) throws IOException {
    final StatusLine statusLine = response.getStatusLine();
    final HttpEntity entity = response.getEntity();
    if (statusLine.getStatusCode() >= 300) {
        EntityUtils.consume(entity);
        throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
    }
    return entity != null ? EntityUtils.toString(entity, getEncoding()) : null;
}

From source file:com.canoo.dolphin.client.impl.IdBasedResponseHandler.java

@Override
public String handleResponse(HttpResponse response) throws IOException {
    final StatusLine statusLine = response.getStatusLine();
    final HttpEntity entity = response.getEntity();

    if (statusLine.getStatusCode() == 408) {
        EntityUtils.consume(entity);/*  w w  w.  j  a v  a 2  s . c  o  m*/
        throw new DolphinSessionException("Server can not handle Dolphin Client ID");
    }

    if (statusLine.getStatusCode() >= 300) {
        EntityUtils.consume(entity);
        throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
    }

    try {
        final Header dolphinHeader = response.getFirstHeader(PlatformConstants.CLIENT_ID_HTTP_HEADER_NAME);
        clientConnector.setClientId(dolphinHeader.getValue());
    } catch (Exception e) {
        throw new DolphinSessionException("Error in handling Dolphin Client ID", e);
    }

    String sessionID = null;
    Header cookieHeader = response.getFirstHeader("Set-Cookie");
    if (cookieHeader != null) {
        sessionID = cookieHeader.getValue();
        if (lastSessionId != null) {
            throw new DolphinSessionException(
                    "Http session must not change but did. Old: " + lastSessionId + ", new: " + sessionID);
        }
        lastSessionId = sessionID;
    }
    return entity == null ? null : EntityUtils.toString(entity);
}

From source file:at.ac.tuwien.big.testsuite.impl.util.DomResponseHandler.java

@Override
public Document handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
    StatusLine statusLine = response.getStatusLine();
    HttpEntity entity = response.getEntity();
    Document doc = null;//from www.  j  a  v  a 2s.c  o  m

    if (statusLine.getStatusCode() >= 300) {

        if (statusLine.getStatusCode() == 502 && retries < MAX_RETRIES) {
            // Proxy Error
            retries++;
            doc = httpClient.execute(request, this);
            retries = 0;
        } else {
            EntityUtils.consume(entity);
            throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
        }
    }

    if (doc == null) {
        doc = entity == null ? null : DomUtils.createDocument(entity.getContent());
    }

    request.releaseConnection();
    return doc;
}