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

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

Introduction

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

Prototype

public int getStatusCode() 

Source Link

Usage

From source file:com.york.cs.services.SyncAdapter.SyncAdapterCB.java

/**
 * /*w ww  .ja  v  a  2  s .c  o  m*/
 * @return A delegate that can be used to listen for Replication changes
 */
private Replication.ChangeListener getReplicationChangeListener() {
    // A delegate that can be used to listen for Replication changes
    return new Replication.ChangeListener() {

        @Override
        public void changed(Replication.ChangeEvent event) {
            // The type of event raised by a Replication when any of the
            // following properties change: mode, running, error, completed,
            // total.
            Replication replication = event.getSource();
            if (replication.getLastError() != null) {
                Throwable lastError = replication.getLastError();
                if (lastError instanceof HttpResponseException) {
                    HttpResponseException responseException = (HttpResponseException) lastError;
                    if (responseException.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                        onSyncUnauthorizedObservable.notifyChanges();
                    }
                }
            }

            updateSyncProgress(replication.getCompletedChangesCount(), replication.getChangesCount());

        }
    };
}

From source file:seava.j4e.web.controller.ui.extjs.DependencyLoader.java

/**
 * Resolve the dependencies of the given component and returns them in a
 * list./*from w  w  w.  j av a2 s  .  co m*/
 * 
 * @param cmp
 * @return
 * @throws Exception
 */
private List<String> resolveCmpDependencies(String cmp) throws Exception {
    String url = this.urlDpd(cmp);

    HttpGet get = new HttpGet(url);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    List<String> result = null;
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Calling http request: " + url);
        }

        String responseBody = getHttpClient().execute(get, responseHandler);

        result = getJsonMapper().readValue(responseBody, new TypeReference<List<String>>() {
        });

    } catch (HttpResponseException e) {
        if (e.getStatusCode() == 404) {
            logger.warn("Cannot find dependencies for component " + cmp + " at " + url);
        } else {
            e.printStackTrace();
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    get.releaseConnection();
    return result;
}

From source file:me.vertretungsplan.parser.BaseParser.java

private void handleHttpResponseException(HttpResponseException e)
        throws CredentialInvalidException, HttpResponseException {
    if (e.getStatusCode() == 401) {
        throw new CredentialInvalidException();
    } else {// w w  w. jav  a2 s.  co  m
        throw e;
    }
}

From source file:tds.tdsadmin.rest.TDSAdminController.java

@ExceptionHandler(HttpResponseException.class)
@ResponseBody/*from  w  w  w. j ava 2 s  .  c o  m*/
public String handleException(HttpResponseException e) {
    logger.error("Appeals: " + e.getMessage());
    return "HTTP ERROR " + e.getStatusCode() + " : " + e.getMessage();
}

From source file:me.vertretungsplan.parser.IphisParser.java

private JSONArray getJSONArray(String url) throws IOException, CredentialInvalidException {
    try {/*ww  w  .j a v a 2  s.co  m*/
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + authToken);
        headers.put("Content-Type", "application/json");
        headers.put("Accept", "application/json");

        final String httpResponse = httpGet(url, "UTF-8", headers);
        return new JSONArray(httpResponse);
    } catch (HttpResponseException httpResponseException) {
        if (httpResponseException.getStatusCode() == 404) {
            return null;
        }
        throw httpResponseException;
    } catch (JSONException e) {
        return new JSONArray();
    }
}

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

@Override
public void handleException(Exception e) {
    if (isEventCancelled()) {
        return;//  w  w w .j a  v a2  s .co  m
    }

    if (e instanceof ConnectionClosedException) {
        String message = e.getMessage();

        if (message.startsWith("Premature end of Content-Length")) {
            _logger.error(message, e);

            removeEvent();

            SyncFile localSyncFile = getLocalSyncFile();

            if (localSyncFile == null) {
                return;
            }

            FileEventUtil.downloadFile(getSyncAccountId(), localSyncFile, false);

            return;
        }
    } else if (e instanceof HttpResponseException) {
        _logger.error(e.getMessage(), e);

        HttpResponseException hre = (HttpResponseException) e;

        int statusCode = hre.getStatusCode();

        if (statusCode != HttpStatus.SC_NOT_FOUND) {
            super.handleException(e);

            return;
        }

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

        if (syncAccount.getState() != SyncAccount.STATE_CONNECTED) {
            super.handleException(e);

            return;
        }

        removeEvent();

        SyncFile syncFile = getLocalSyncFile();

        if (syncFile == null) {
            return;
        }

        if ((boolean) getParameterValue("patch")) {
            FileEventUtil.downloadFile(getSyncAccountId(), syncFile, false);
        } else {
            handleException(syncFile);
        }

        return;
    }

    super.handleException(e);
}

From source file:org.eclipse.aether.transport.http.HttpTransporter.java

@Override
protected void implGet(GetTask task) throws Exception {
    EntityGetter getter = new EntityGetter(task);
    HttpGet request = commonHeaders(new HttpGet(resolve(task)));
    resume(request, task);//from w  w w.  java  2 s.c  om
    try {
        execute(request, getter);
    } catch (HttpResponseException e) {
        if (e.getStatusCode() == HttpStatus.SC_PRECONDITION_FAILED
                && request.containsHeader(HttpHeaders.RANGE)) {
            request = commonHeaders(new HttpGet(request.getURI()));
            execute(request, getter);
            return;
        }
        throw e;
    }
}

From source file:org.eclipse.aether.transport.http.HttpTransporter.java

@Override
protected void implPut(PutTask task) throws Exception {
    PutTaskEntity entity = new PutTaskEntity(task);
    HttpPut request = commonHeaders(entity(new HttpPut(resolve(task)), entity));
    try {//w w  w  . j  a  v a 2s .c  o m
        execute(request, null);
    } catch (HttpResponseException e) {
        if (e.getStatusCode() == HttpStatus.SC_EXPECTATION_FAILED
                && request.containsHeader(HttpHeaders.EXPECT)) {
            state.setExpectContinue(false);
            request = commonHeaders(entity(new HttpPut(request.getURI()), entity));
            execute(request, null);
            return;
        }
        throw e;
    }
}

From source file:com.comcast.drivethru.client.DefaultRestClient.java

@Override
public RestResponse execute(RestRequest request) throws HttpException {
    /* Build the URL String */
    String url = request.getUrl().setDefaultBaseUrl(defaultBaseUrl).build();

    /* Get our Apache RestRequest object */
    Method method = request.getMethod();
    HttpRequestBase req = method.getRequest(url);
    req.setConfig(request.getConfig());//from   ww w.j a  va2  s  . c o m

    /* Add the Body */
    byte[] payload = request.getBody();
    if (null != payload) {
        if (req instanceof HttpEntityEnclosingRequest) {
            HttpEntity entity = new ByteArrayEntity(payload);
            ((HttpEntityEnclosingRequest) req).setEntity(entity);
        } else {
            throw new HttpException("Cannot attach a body to a " + method.name() + " request");
        }
    }

    /* Add all Headers */
    for (Entry<String, String> pair : defaultHeaders.entrySet()) {
        req.addHeader(pair.getKey(), pair.getValue());
    }
    for (Entry<String, String> pair : request.getHeaders().entrySet()) {
        req.addHeader(pair.getKey(), pair.getValue());
    }

    /* If there is a security provider, sign */
    if (null != securityProvider) {
        securityProvider.sign(req);
    }

    /* Closed in the finally block */
    InputStream in = null;
    ByteArrayOutputStream baos = null;

    try {
        /* Finally, execute the thing */
        org.apache.http.HttpResponse resp = delegate.execute(req);

        /* Create our response */
        RestResponse response = new RestResponse(resp.getStatusLine());

        /* Add all Headers */
        response.addAll(resp.getAllHeaders());

        /* Add the content */
        HttpEntity body = resp.getEntity();
        if (null != body) {
            in = body.getContent();
            baos = new ByteArrayOutputStream();
            IOUtils.copy(in, baos);
            response.setBody(baos.toByteArray());
        }

        return response;
    } catch (RuntimeException ex) {
        // release resources immediately
        req.abort();
        throw ex;
    } catch (HttpResponseException hrex) {
        throw new HttpStatusException(hrex.getStatusCode());
    } catch (ClientProtocolException cpex) {
        throw new HttpException("HTTP Protocol error occurred.", cpex);
    } catch (IOException ioex) {
        throw new HttpException("Error establishing connection.", ioex);
    } finally {
        req.abort();
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(baos);
    }
}

From source file:com.streamsets.stage.destination.waveanalytics.WaveAnalyticsTarget.java

private void runDataflow(String dataflowId) throws IOException {
    try {//from  ww w  .j a  v a  2  s .  c  o m
        HttpResponse res = Request.Put(restEndpoint + String.format(startDataflow, dataflowId))
                .addHeader("Authorization", "OAuth " + connection.getConfig().getSessionId()).execute()
                .returnResponse();

        int statusCode = res.getStatusLine().getStatusCode();
        String content = EntityUtils.toString(res.getEntity());

        LOG.info("PUT dataflow with result {} content {}", statusCode, content);
    } catch (HttpResponseException e) {
        LOG.error("PUT dataflow with result {} {}", e.getStatusCode(), e.getMessage());
        throw e;
    }
}