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.jaspersoft.studio.server.protocol.ProxyConnection.java

@Override
public List<ResourceDescriptor> listDatasources(IProgressMonitor monitor, IDatasourceFilter f)
        throws Exception {
    List<ResourceDescriptor> list = null;
    try {//from ww  w. j  av a 2  s .  c  o  m
        list = c.listDatasources(monitor, f);
    } catch (Exception e) {
        if (e instanceof HttpResponseException) {
            HttpResponseException he = (HttpResponseException) e;
            if (he.getStatusCode() == 500) {// &&
                // he.getMessage().contains("Unexpected error"))
                // {
                if (soap == null)
                    throw e;
                list = soap.listDatasources(monitor, f);
                for (ResourceDescriptor r : list)
                    r.setChildrenDirty(false);
                return list;
            } else if (he.getStatusCode() == 401 && !error401) {
                c.connect(monitor, getServerProfile());
                error401 = true;
                return listDatasources(monitor, f);
            }
        }
        error401 = false;
        throw e;
    }
    for (ResourceDescriptor r : list)
        r.setChildrenDirty(false);
    error401 = false;
    return list;
}

From source file:com.jaspersoft.studio.server.protocol.ProxyConnection.java

@Override
public List<ResourceDescriptor> list(IProgressMonitor monitor, ResourceDescriptor rd) throws Exception {
    List<ResourceDescriptor> list = null;
    // String v = c.getServerInfo(monitor).getVersion();
    // if (c != soap && v.compareTo("5.5") > 0 && v.compareTo("6") < 0)
    // list = soap.list(monitor, rd);
    // else/*  www .jav  a  2 s. com*/
    try {
        list = c.list(monitor, rd);
    } catch (Exception e) {
        if (e instanceof HttpResponseException) {
            HttpResponseException he = (HttpResponseException) e;
            if (he.getStatusCode() == 500) {// &&
                // he.getMessage().contains("Unexpected error"))
                // {
                if (soap == null)
                    throw e;
                list = soap.list(monitor, rd);
                for (ResourceDescriptor r : list)
                    r.setChildrenDirty(false);
                return list;
            } else if (he.getStatusCode() == 401 && !error401) {
                c.connect(monitor, getServerProfile());
                error401 = true;
                return list(monitor, rd);
            }
        }
        error401 = false;
        throw e;
    }
    for (ResourceDescriptor r : list)
        r.setChildrenDirty(false);
    error401 = false;
    return list;
}

From source file:com.jaspersoft.studio.server.protocol.ProxyConnection.java

@Override
public ResourceDescriptor get(IProgressMonitor monitor, ResourceDescriptor rd, File f) throws Exception {
    if (useSoap(monitor, rd) && soap != null)
        rd = soap.get(monitor, rd, f);//from   ww  w .j av a  2  s  . c  om
    else
        try {
            rd = c.get(monitor, rd, f);
        } catch (Exception e) {
            if (e instanceof HttpResponseException) {
                HttpResponseException he = (HttpResponseException) e;
                if (he.getStatusCode() == 500 && he.getMessage().contains("Unexpected error")) {
                    if (soap == null)
                        throw e;
                    rd = soap.get(monitor, rd, f);
                    rd.setChildrenDirty(false);
                    return rd;
                } else if (he.getStatusCode() == 403) {
                    try {
                        if (soap == null)
                            throw e;
                        rd = soap.get(monitor, rd, f);
                        rd.setChildrenDirty(false);
                    } catch (Exception e1) {
                        // let's keep original exception , we tried, but it
                        // not works on soap
                        e1.printStackTrace();
                        throw he;
                    }
                    return rd;
                } else if (he.getStatusCode() == 401 && !error401) {
                    c.connect(monitor, getServerProfile());
                    error401 = true;
                    return get(monitor, rd, f);
                }
            }
            error401 = false;
            throw e;
        }
    if (rd != null)
        rd.setChildrenDirty(false);
    error401 = false;
    return rd;
}

From source file:com.francetelecom.clara.cloud.activation.plugin.cf.infrastructure.AbstractCfAdapterIT.java

/**
 * /*  ww w.ja  v  a  2  s  .c o  m*/
 * @param virtualHost
 * @param testRequestPath
 * @param appNameToDumpDiagnosticLogs
 *            the name of the app to display the logs of if the webgui is
 *            unreacheable, or null to no display such logs.
 * @throws IOException
 */
protected void testRemoteAppWebGui(String virtualHost, String testRequestPath,
        String appNameToDumpDiagnosticLogs) throws IOException {

    HttpClientConfig defaultProxyConfig = getHttpProxyConfigToQueryWebGuiRoutes();
    int retry = 0;
    int maxRetries = 10;

    String testResponse = null;
    StringBuffer testFailureDetails = new StringBuffer();
    do {
        logger.info("Querying " + getWebGuiURL(virtualHost, testRequestPath) + " using proxyConfig="
                + defaultProxyConfig + " ...");
        try {
            testResponse = fetchRoutedContentAsString(getWebGuiURL(virtualHost, testRequestPath),
                    defaultProxyConfig);
            break;
        } catch (HttpResponseException e) {
            String msg = "Querying " + getWebGuiURL(virtualHost, testRequestPath) + " ... done. Caught: " + e;
            logger.info(msg);
            testFailureDetails.append(msg);
            testFailureDetails.append("\n");
            if (e.getStatusCode() == 404) {
                logger.info("Sleeping for 10s before next retry (" + retry + "/" + maxRetries + ")");

                if (appNameToDumpDiagnosticLogs != null) {
                    cfAdapter.logAppDiagnostics(appNameToDumpDiagnosticLogs, cfDefaultSpace);
                }
                try {
                    Thread.sleep(10 * 1000);
                } catch (InterruptedException e1) {
                    // Ignore
                }
                retry++;
            } else {
                break; // no retries for unexpected errors
            }
        }
    } while (retry < maxRetries);

    logger.info("Querying " + getWebGuiURL(virtualHost, testRequestPath) + " ... done. Returned: "
            + StringUtils.abbreviate(testResponse, 50));
    assertThat(testResponse).as("webGui response").isNotNull().isNotEmpty();
    assertThat(retry).overridingErrorMessage("Expecting zero retries on webGui polling, got " + retry
            + " retries. Details:" + testFailureDetails).isLessThanOrEqualTo(1); // Expect
    // the app to immediately return a valid response, retries are only here
    // to help diagnostics
}

From source file:com.github.sardine.impl.SardineImpl.java

public <T> T put(String url, HttpEntity entity, Map<String, String> headers, ResponseHandler<T> handler)
        throws IOException {
    HttpPut put = new HttpPut(url);
    put.setEntity(entity);//  www  .j  a va 2  s. c  om
    for (String header : headers.keySet()) {
        put.addHeader(header, headers.get(header));
    }
    if (entity.getContentType() == null && !put.containsHeader(HttpHeaders.CONTENT_TYPE)) {
        put.addHeader(HttpHeaders.CONTENT_TYPE, HTTP.DEF_CONTENT_CHARSET.name());
    }
    try {
        return this.execute(put, handler);
    } catch (HttpResponseException e) {
        if (e.getStatusCode() == HttpStatus.SC_EXPECTATION_FAILED) {
            // Retry with the Expect header removed
            put.removeHeaders(HTTP.EXPECT_DIRECTIVE);
            if (entity.isRepeatable()) {
                return this.execute(put, handler);
            }
        }
        throw e;
    }
}

From source file:com.googlecode.sardine.impl.SardineImpl.java

/**
 * Upload the entity using <code>PUT</code>
 * /*from   ww  w. j a  va 2s  . c o  m*/
 * @param url
 *            Resource
 * @param entity
 *            The entity to read from
 * @param headers
 *            Headers to add to request
 */
public void put(String url, HttpEntity entity, Map<String, String> headers) throws IOException {
    HttpPut put = new HttpPut(url);
    put.setEntity(entity);
    for (String header : headers.keySet()) {
        put.addHeader(header, headers.get(header));
    }
    if (!put.containsHeader("Content-Type")) {
        put.addHeader("Content-Type", HTTP.DEFAULT_CONTENT_TYPE);
    }
    try {
        this.execute(put, new VoidResponseHandler());
    } catch (HttpResponseException e) {
        if (e.getStatusCode() == HttpStatus.SC_EXPECTATION_FAILED) {
            // Retry with the Expect header removed
            put.removeHeaders(HTTP.EXPECT_DIRECTIVE);
            if (entity.isRepeatable()) {
                this.execute(put, new VoidResponseHandler());
                return;
            }
        }
        throw e;
    }
}

From source file:de.aflx.sardine.impl.SardineImpl.java

/**
 * Upload the entity using <code>PUT</code>
 * //from w  ww.  ja  va  2 s .c  om
 * @param url
 *            Resource
 * @param entity
 *            The entity to read from
 * @param headers
 *            Headers to add to request
 */
public void put(String url, HttpEntity entity, Map<String, String> headers) throws IOException {

    HttpPut put = new HttpPut(url);
    _currentRequest = put;
    _isAborted = false;

    put.setEntity(entity);
    for (String header : headers.keySet()) {
        put.addHeader(header, headers.get(header));
    }
    if (!put.containsHeader("Content-Type")) {
        put.addHeader("Content-Type", HTTP.DEFAULT_CONTENT_TYPE);
    }
    try {
        this.execute(put, new VoidResponseHandler());
    } catch (HttpResponseException e) {
        if (e.getStatusCode() == HttpStatus.SC_EXPECTATION_FAILED) {
            // Retry with the Expect header removed
            put.removeHeaders(HTTP.EXPECT_DIRECTIVE);
            if (entity.isRepeatable()) {
                this.execute(put, new VoidResponseHandler());
                return;
            }
        }

        throw e;
    }
}

From source file:com.github.rnewson.couchdb.lucene.DatabaseIndexer.java

public Void handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
    final HttpEntity entity = response.getEntity();
    final BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
    String line;//  w ww  .j  av a  2 s  . c o m
    loop: while ((line = reader.readLine()) != null) {
        maybeCommit();

        // Heartbeat.
        if (line.length() == 0) {
            logger.trace("heartbeat");
            continue loop;
        }

        try {
            final JSONObject json = new JSONObject(line);

            if (json.has("error")) {
                logger.warn("Indexing stopping due to error: " + json);
                break loop;
            }

            if (json.has("last_seq")) {
                logger.info("End of changes detected.");
                break loop;
            }

            final UpdateSequence seq = UpdateSequence.parseUpdateSequence(json.getString("seq"));
            final String id = json.getString("id");
            CouchDocument doc;
            if (!json.isNull("doc")) {
                doc = new CouchDocument(json.getJSONObject("doc"));
            } else {
                // include_docs=true doesn't work prior to 0.11.
                try {
                    doc = database.getDocument(id);
                } catch (final HttpResponseException e) {
                    switch (e.getStatusCode()) {
                    case HttpStatus.SC_NOT_FOUND:
                        doc = CouchDocument.deletedDocument(id);
                        break;
                    default:
                        logger.warn("Failed to fetch " + id);
                        break loop;
                    }
                }
            }

            if (id.startsWith("_design")) {
                if (seq.isLaterThan(ddoc_seq)) {
                    logger.info("Exiting due to design document change.");
                    break loop;
                }
            }

            if (doc.isDeleted()) {
                for (final IndexState state : states.values()) {
                    state.writer.deleteDocuments(new Term("_id", id));
                    state.setPendingSequence(seq);
                    state.readerDirty = true;
                }
            } else {
                for (final Entry<View, IndexState> entry : states.entrySet()) {
                    final View view = entry.getKey();
                    final IndexState state = entry.getValue();

                    if (seq.isLaterThan(state.pending_seq)) {
                        final Collection<Document> docs;
                        try {
                            docs = state.converter.convert(doc, view.getDefaultSettings(), database);
                        } catch (final Exception e) {
                            logger.warn(id + " caused " + e.getMessage());
                            continue loop;
                        }

                        state.writer.updateDocuments(new Term("_id", id), docs, view.getAnalyzer());
                        state.setPendingSequence(seq);
                        state.readerDirty = true;
                    }
                }
            }
        } catch (final JSONException e) {
            logger.error("JSON exception in changes loop", e);
            break loop;
        }
    }
    req.abort();
    return null;
}

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

@Test
public void testPeek_NotFound() throws Exception {
    try {// w  w w  .j av  a  2s . co  m
        transporter.peek(new PeekTask(URI.create("repo/missing.txt")));
        fail("Expected error");
    } catch (HttpResponseException e) {
        assertEquals(404, e.getStatusCode());
        assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(e));
    }
}

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

@Test
public void testGet_NotFound() throws Exception {
    try {/* w  ww .  java 2s  .  c  om*/
        transporter.get(new GetTask(URI.create("repo/missing.txt")));
        fail("Expected error");
    } catch (HttpResponseException e) {
        assertEquals(404, e.getStatusCode());
        assertEquals(Transporter.ERROR_NOT_FOUND, transporter.classify(e));
    }
}