Example usage for org.apache.commons.httpclient HttpStatus SC_NOT_FOUND

List of usage examples for org.apache.commons.httpclient HttpStatus SC_NOT_FOUND

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_NOT_FOUND.

Prototype

int SC_NOT_FOUND

To view the source code for org.apache.commons.httpclient HttpStatus SC_NOT_FOUND.

Click Source Link

Document

<tt>404 Not Found</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:br.org.acessobrasil.nucleuSilva.util.PegarPaginaWEB.java

/**
 * Mtodo que extra o contedo de uma pgina web.
 * /*from w  ww.j  a va  2 s  . com*/
 * @param url
 *            Pgina que vai ser pesquisada.
 * @return Contedo da pgina HTML.
 * @throws IOException
 *             Erro ao tentar extrair o contedo da pgina html.
 */
public void getContent(final RelatorioDaUrl relatorio) {
    /*
     * Melhorar este cdigo!!! 
     */
    log.addLog("getContent(" + relatorio.getUrl() + ")\n");
    int status = 9999;
    setAtivo(false);
    metodo = null;
    final int mb = 1024;

    String type = new String();
    InputStream ist = null;
    StringBuilder sbd = null;

    setPaginaObtida(true);

    TimeOut tc = new TimeOut(this);

    setAtivo(true);
    Thread thrTc = new Thread(tc);
    thrTc.start();
    try {
        metodo = new GetMethod(relatorio.getUrl());
        metodo.setRequestHeader("user-agent", "Mozilla/5.0");
        metodo.setFollowRedirects(true);
    } catch (Exception e) {
        log.addLog("Erro no GetMetodo: " + e.getMessage() + "\n");
        //Ini - nati code
        colocaNaTabelaErros("timeOut", relatorio);
        setPaginaObtida(false);
        setAtivo(false);
        //Fim - nati code
        metodo = null;
        thrTc = null;
        tc = null;
        return;
    }
    if (!tc.timeOut) {
        // httpClient.setConnectionTimeout(arg0)
        try {
            status = httpClient.executeMethod(metodo);
            type = getContentType(metodo);
            String tam = getContentLength(metodo);
            String location = getLocation(metodo);
            if (location != "") {
                //System.out.print(relatorio.getUrl()+" to "+location+"\n");
            }
            log.addLog("type=" + type + " tam=" + tam + "\n");
            if ((status == HttpStatus.SC_OK) && (type.toUpperCase().indexOf("TEXT/HTML") > -1)) {
                if (!tc.timeOut) {
                    sbd = new StringBuilder();
                    //ist = metodo.getResponseBodyAsStream();
                } else {
                    colocaNaTabelaErros("timeOut", relatorio);
                    setPaginaObtida(false);
                    if (!thrTc.interrupted())
                        if (thrTc.isAlive())
                            thrTc.interrupt();
                    setAtivo(false);
                }

                if (!tc.timeOut) {
                    /*
                    byte[] dados = new byte[mb];
                    int bytesLidos = 0;
                            
                    while ((bytesLidos = ist.read(dados)) > 0) {
                       sbd.append(new String(dados, 0, bytesLidos));
                    }
                            
                    ist.close();
                    */
                    sbd.append(metodo.getResponseBodyAsString());
                } else {
                    colocaNaTabelaErros("timeOut", relatorio);
                    setPaginaObtida(false);
                    if (!thrTc.interrupted())
                        if (thrTc.isAlive())
                            thrTc.interrupt();
                    setAtivo(false);
                }
                //verifica se existe contedo
                if (sbd.toString().equals("") || sbd == null || sbd.toString().trim().length() <= 1) {
                    colocaNaTabelaErros("Sem contedo", relatorio);
                    setPaginaObtida(false);
                    if (!thrTc.interrupted())
                        if (thrTc.isAlive())
                            thrTc.interrupt();
                    setAtivo(false);
                }
            } else {
                //verifica se o tipo est errado
                if (type.toUpperCase().indexOf("TEXT/HTML") == -1) {
                    colocaNaTabelaErros("No HTML", relatorio);
                } else if (status == HttpStatus.SC_NOT_FOUND) {
                    colocaNaTabelaErros("No Encontrado", relatorio);
                } else {
                    colocaNaTabelaErros("Status error " + status, relatorio);
                }
                setPaginaObtida(false);
                if (!thrTc.interrupted())
                    if (thrTc.isAlive())
                        thrTc.interrupt();
                setAtivo(false);
            }

            if (!tc.timeOut) {
                metodo.abort();
                metodo.releaseConnection();
            } else {
                colocaNaTabelaErros("timeOut", relatorio);
                setAtivo(false);
                setPaginaObtida(false);
                if (!thrTc.interrupted())
                    if (thrTc.isAlive())
                        thrTc.interrupt();
            }

            if (!thrTc.interrupted())
                if (thrTc.isAlive())
                    thrTc.interrupt();

        } catch (Exception e) {
            log.addLog("Erro: " + e.getMessage() + "\n");
            colocaNaTabelaErros("Erro: " + e.getMessage(), relatorio);
            setAtivo(false);
            setPaginaObtida(false);
            if (!thrTc.interrupted())
                if (thrTc.isAlive())
                    thrTc.interrupt();
        }
    } else {
        colocaNaTabelaErros("timeOut", relatorio);
        setPaginaObtida(false);
        setAtivo(false);
        if (!thrTc.interrupted())
            if (thrTc.isAlive())
                thrTc.interrupt();
    }
    try {
        metodo.abort();
        metodo.releaseConnection();
    } catch (Exception e) {

    }
    if (sbd != null && (type.toUpperCase().indexOf("TEXT") > -1) && !tc.timeOut && isAtivo()) {
        setAtivo(false);
        //System.out.println("PPW:\n"+sbd.toString());
        relatorio.setConteudo(sbd);
    }
    if (!tc.isTimeOut()) {
        setPaginaObtida(true);
    }

    tc.timeOut = false;
    setAtivo(false);
    if (!thrTc.interrupted())
        if (thrTc.isAlive())
            thrTc.interrupt();

    log.addLog("Ok \n");
}

From source file:com.sittinglittleduck.DirBuster.Worker.java

private boolean verifyIfCodeIsValid(int code) {
    return code != HttpStatus.SC_NOT_FOUND && code != 0 && code != HttpStatus.SC_BAD_GATEWAY;
}

From source file:com.cerema.cloud2.lib.common.OwnCloudClient.java

public RedirectionPath followRedirection(HttpMethod method) throws IOException {
    int redirectionsCount = 0;
    int status = method.getStatusCode();
    RedirectionPath result = new RedirectionPath(status, MAX_REDIRECTIONS_COUNT);
    while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

        Header location = method.getResponseHeader("Location");
        if (location == null) {
            location = method.getResponseHeader("location");
        }/*from ww  w  .j  a va 2  s  .  c o  m*/
        if (location != null) {
            Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue());

            String locationStr = location.getValue();
            result.addLocation(locationStr);

            // Release the connection to avoid reach the max number of connections per host
            // due to it will be set a different url
            exhaustResponse(method.getResponseBodyAsStream());
            method.releaseConnection();

            method.setURI(new URI(locationStr, true));
            Header destination = method.getRequestHeader("Destination");
            if (destination == null) {
                destination = method.getRequestHeader("destination");
            }
            if (destination != null) {
                int suffixIndex = locationStr.lastIndexOf(
                        (mCredentials instanceof OwnCloudBearerCredentials) ? AccountUtils.ODAV_PATH
                                : AccountUtils.WEBDAV_PATH_4_0);
                String redirectionBase = locationStr.substring(0, suffixIndex);

                String destinationStr = destination.getValue();
                String destinationPath = destinationStr.substring(mBaseUri.toString().length());
                String redirectedDestination = redirectionBase + destinationPath;

                destination.setValue(redirectedDestination);
                method.setRequestHeader(destination);
            }
            status = super.executeMethod(method);
            result.addStatus(status);
            redirectionsCount++;

        } else {
            Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
            status = HttpStatus.SC_NOT_FOUND;
        }
    }
    return result;
}

From source file:com.cloud.network.bigswitch.BigSwitchBcfApi.java

private String checkResponse(final HttpMethodBase m, final String errorMessageBase)
        throws BigSwitchBcfApiException, IllegalArgumentException {
    String customErrorMsg = null;
    if (m.getStatusCode() == HttpStatus.SC_OK) {
        String hash = "";
        if (m.getResponseHeader(HASH_MATCH) != null) {
            hash = m.getResponseHeader(HASH_MATCH).getValue();
            set_hash(hash);/*  w  ww . j a  va  2  s. c  om*/
        }
        return hash;
    }
    if (m.getStatusCode() == HttpStatus.SC_CONFLICT) {
        if (m instanceof GetMethod) {
            return HASH_CONFLICT;
        }
        throw new BigSwitchBcfApiException("BCF topology sync required", true);
    }
    if (m.getStatusCode() == HttpStatus.SC_SEE_OTHER) {
        isMaster = false;
        set_hash(HASH_IGNORE);
        return HASH_IGNORE;
    }
    if (m.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
        if (m instanceof DeleteMethod) {
            return "";
        }
    }
    if (m.getStatusCode() == HttpStatus.SC_BAD_REQUEST) {
        customErrorMsg = " Invalid data in BCF request";
        throw new IllegalArgumentException(customErrorMsg);
    }
    String errorMessage = responseToErrorMessage(m);
    m.releaseConnection();
    S_LOGGER.error(errorMessageBase + errorMessage);
    throw new BigSwitchBcfApiException(errorMessageBase + errorMessage + customErrorMsg);
}

From source file:com.serena.rlc.provider.jenkins.client.JenkinsClient.java

private JenkinsClientException createHttpError(HttpResponse response) {
    String message;/*  w  w  w. j  a  v  a  2 s.c om*/
    try {
        StatusLine statusLine = response.getStatusLine();
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line;
        StringBuffer responsePayload = new StringBuffer();
        // Read response until the end
        while ((line = rd.readLine()) != null) {
            responsePayload.append(line);
        }

        message = String.format("request not successful: %d %s. Reason: %s", statusLine.getStatusCode(),
                HttpStatus.getStatusText(statusLine.getStatusCode()), responsePayload);

        logger.info(message);

        if (new Integer(HttpStatus.SC_UNAUTHORIZED).equals(statusLine.getStatusCode())) {
            return new JenkinsClientException("Invalid credentials provided.");
        } else if (new Integer(HttpStatus.SC_NOT_FOUND).equals(statusLine.getStatusCode())) {
            return new JenkinsClientException("Jenkins: Request URL not found.");
        } else if (new Integer(HttpStatus.SC_BAD_REQUEST).equals(statusLine.getStatusCode())) {
            return new JenkinsClientException("Jenkins: Bad request. " + responsePayload);
        }
    } catch (IOException e) {
        return new JenkinsClientException("Jenkins: Can't read response");
    }

    return new JenkinsClientException(message);
}

From source file:au.edu.usq.fascinator.access.couch.CouchAccessControl.java

private JsonConfigHelper get(String recordId) throws Exception {
    GetMethod rq = null;/*from  w  w  w  .j  a  v  a 2  s .  com*/
    try {
        // Send our GET query
        rq = new GetMethod(url + getIdHash(recordId));
        rq.addRequestHeader("Content-Type", "text/plain; charset=UTF-8");
        int statusCode = couch.executeMethod(rq);

        // Something went awry
        if (statusCode != HttpStatus.SC_OK) {
            // It just wasn't there
            if (statusCode == HttpStatus.SC_NOT_FOUND) {
                return null;
            }
            // Something else happened
            throw new Exception("Database GET failed!: '" + statusCode + "': " + rq.getResponseBodyAsString());
        }

        // Return the result
        String response = rq.getResponseBodyAsString();
        JsonConfigHelper result = new JsonConfigHelper(response);
        return result;
    } catch (Exception ex) {
        throw ex;
    } finally {
        if (rq != null) {
            rq.releaseConnection();
        }
    }
}

From source file:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

@Override
public void transfer(Long accountId, TransferRequest request) {
    String resource = String.format(baseUrl + ACCOUNT, accountId);
    PostMethod method = new PostMethod(resource);
    try {//from   w w  w .jav  a2s  .c  om
        String data = serialize(request);
        if (log.isTraceEnabled()) {
            log.trace("Transfer JSON data: " + data);
        }
        method.setRequestEntity(new StringRequestEntity(data, MIME_TYPE_JSON, DEFAULT_CHAR_ENCODING));
        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return;
        }
        assertResponseCodeOK(method, statusCode);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

@Override
public TransactionResult doTransaction(TransactionRequest transaction) {
    PostMethod method = new PostMethod(baseUrl + DO_TRANSACTION);

    log.info("Do Transaction, POST to: " + baseUrl + DO_TRANSACTION);
    try {// w w  w.ja  v  a 2  s . co m
        String data = serialize(transaction);
        method.setRequestEntity(new StringRequestEntity(data, MIME_TYPE_JSON, DEFAULT_CHAR_ENCODING));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        if (statusCode == HttpStatus.SC_OK) {
            InputStream body = method.getResponseBodyAsStream();
            return parseJson(body, TransactionResult.class);

        }
        if (statusCode == HttpStatus.SC_FORBIDDEN) {
            throw new NegativeBalanceException(-1L);

        } else {
            throw new RuntimeException("Failed to do transaction, RESPONSE CODE: " + statusCode);
        }
    } catch (NegativeBalanceException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java

@Override
public UserQueryResult findUsers(Long userId, String name, int offset, int limit, UserOrder sortOrder,
        boolean ascending) {
    PutMethod method = new PutMethod(baseUrl + QUERY);

    UserQuery request = new UserQuery();
    request.setUserId(userId);//from   w  ww.  j  a  v  a  2s  .  c  o  m
    request.setUserName(name);
    request.setQueryOffset(offset);
    request.setQueryLimit(limit);
    request.setAscending(ascending);
    request.setOrder(sortOrder);

    try {
        String data = serialize(request);
        method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8"));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        if (statusCode == HttpStatus.SC_OK) {
            InputStream body = method.getResponseBodyAsStream();
            return parseJson(body, UserQueryResult.class);

        } else {
            throw new RuntimeException("Failed to query users, RESPONSE CODE: " + statusCode);
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

@Override
public Transaction getTransactionById(Long transactionId) {
    String resource = String.format(baseUrl + TRANSACTION, transactionId);
    GetMethod method = createGetMethod(resource);

    try {//  w  w w .  j  a  v a2  s  .c  o  m
        // Execute the method.
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        assertResponseCodeOK(method, statusCode);
        // Read the response body.
        InputStream body = method.getResponseBodyAsStream();
        return parseJson(body, Transaction.class);

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}