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:domderrien.wrapper.UrlFetch.UrlFetchHttpConnection.java

@Override
public String readLine(String charset) throws IOException, IllegalStateException {
    if (waitForHttpStatus) {
        // Dom Derrien: called only once to get the HTTP status, other information being read from the response output stream
        int responseCode = getResponse().getResponseCode();
        String line = "HTTP/1.1 " + responseCode;
        switch (responseCode) {
        case HttpStatus.SC_OK:
            line += " OK";
            break;
        case HttpStatus.SC_BAD_REQUEST:
            line += " BAD REQUEST";
            break;
        case HttpStatus.SC_UNAUTHORIZED:
            line += " UNAUTHORIZED";
            break;
        case HttpStatus.SC_FORBIDDEN:
            line += " FORBIDDEN";
            break;
        case HttpStatus.SC_NOT_FOUND:
            line += " NOT FOUND";
            break;
        case HttpStatus.SC_INTERNAL_SERVER_ERROR:
            line += " INTERNAL SERVER ERROR";
            break;
        case HttpStatus.SC_SERVICE_UNAVAILABLE:
            line += " SERVICE UNAVAILABLE";
            break;
        default:/*from w w  w  . j av a  2 s  .c o  m*/
            line = "HTTP/1.1 " + HttpStatus.SC_BAD_REQUEST + " BAD REQUEST";
        }
        waitForHttpStatus = false;
        return line;
    }
    throw new RuntimeException("readLine(String)");
}

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

@Override
public void closeAccount(Long accountId) throws AccountNotFoundException {
    String resource = String.format(baseUrl + ACCOUNT_CLOSE, accountId);
    PutMethod method = new PutMethod(resource);
    try {//from   ww  w  .j av  a2  s.  co m
        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.users.client.UserServiceClientHTTP.java

@SuppressWarnings("unchecked")
@Override/*from w  ww  .j  ava2s  .c  om*/
public Map<String, String> getUserAttributes(Long userId) {
    // Create a method instance.
    String resource = String.format(baseUrl + USER_ATTRIBUTES, userId);
    GetMethod method = createGetMethod(resource);

    try {
        // 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();
        //FileInputStream fis = new FileInputStream("src/test/resources/attributes.json");

        return parseJson(body, HashMap.class);

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

From source file:com.sun.faban.harness.util.CLI.java

private String makeStringRequest(HttpMethodBase method) throws IOException {
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    int status = client.executeMethod(method);
    String enc = method.getResponseCharSet();

    InputStream response = method.getResponseBodyAsStream();
    StringBuilder buffer = new StringBuilder();
    if (status == HttpStatus.SC_NOT_FOUND) {
        System.err.println("Not found!");
        return buffer.toString();
    } else if (status == HttpStatus.SC_NO_CONTENT) {
        System.err.println("Empty!");
        return buffer.toString();
    } else if (response != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(response, enc));
        String line = null;/*  ww  w . j av a2  s  . c  o m*/
        while ((line = reader.readLine()) != null)
            buffer.append(line).append('\n');
    } else if (status != HttpStatus.SC_OK)
        throw new IOException(HttpStatus.getStatusText(status));
    return buffer.toString();
}

From source file:com.serena.rlc.provider.jira.client.JiraClient.java

private JiraClientException createHttpError(HttpResponse response) {
    String message;//from   w w w. j  a  va2  s. co m
    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.debug(message);

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

    return new JiraClientException(message);
}

From source file:JiraWebSession.java

private HostConfiguration login(HttpClient httpClient, IProgressMonitor monitor) throws JiraException {
    RedirectTracker tracker = new RedirectTracker();

    final String restLogin = "/rest/gadget/1.0/login"; //$NON-NLS-1$ // JIRA 4.x has additional endpoint for login that tells if CAPTCHA limit was hit
    final String loginAction = "/secure/Dashboard.jspa"; //$NON-NLS-1$;
    boolean jira4x = true;

    for (int i = 0; i <= MAX_REDIRECTS; i++) {
        AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY);
        if (credentials == null) {
            // TODO prompt user?
            credentials = new AuthenticationCredentials("", ""); //$NON-NLS-1$ //$NON-NLS-2$
        }//from w ww  .  jav  a 2s .c  o  m

        String url = baseUrl + (jira4x ? restLogin : loginAction);

        PostMethod login = new PostMethod(url);
        login.setFollowRedirects(false);
        login.setRequestHeader("Content-Type", getContentType()); //$NON-NLS-1$
        login.addParameter("os_username", credentials.getUserName()); //$NON-NLS-1$
        login.addParameter("os_password", credentials.getPassword()); //$NON-NLS-1$
        login.addParameter("os_destination", "/success"); //$NON-NLS-1$ //$NON-NLS-2$

        tracker.addUrl(url);

        try {
            HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(httpClient, location,
                    monitor);
            int statusCode = WebUtil.execute(httpClient, hostConfiguration, login, monitor);

            if (statusCode == HttpStatus.SC_NOT_FOUND) {
                jira4x = false;
                continue;
            }

            if (needsReauthentication(httpClient, login, monitor)) {
                continue;
            } else if (statusCode != HttpStatus.SC_MOVED_TEMPORARILY
                    && statusCode != HttpStatus.SC_MOVED_PERMANENTLY) {
                throw new JiraServiceUnavailableException("Unexpected status code during login: " + statusCode); //$NON-NLS-1$
            }

            tracker.addRedirect(url, login, statusCode);

            this.characterEncoding = login.getResponseCharSet();

            Header locationHeader = login.getResponseHeader("location"); //$NON-NLS-1$
            if (locationHeader == null) {
                throw new JiraServiceUnavailableException("Invalid redirect, missing location"); //$NON-NLS-1$
            }
            url = locationHeader.getValue();
            tracker.checkForCircle(url);
            if (!insecureRedirect && isSecure() && url.startsWith("http://")) { //$NON-NLS-1$
                tracker.log("Redirect to insecure location during login to repository: " + client.getBaseUrl()); //$NON-NLS-1$
                insecureRedirect = true;
            }
            if (url.endsWith("/success")) { //$NON-NLS-1$
                String newBaseUrl = url.substring(0, url.lastIndexOf("/success")); //$NON-NLS-1$
                if (baseUrl.equals(newBaseUrl) || !client.getLocalConfiguration().getFollowRedirects()) {
                    // success
                    addAuthenticationCookie(httpClient, login);
                    return hostConfiguration;
                } else {
                    // need to login to make sure HttpClient picks up the session cookie
                    baseUrl = newBaseUrl;
                }
            }
        } catch (IOException e) {
            throw new JiraServiceUnavailableException(e);
        } finally {
            login.releaseConnection();
        }
    }

    tracker.log(
            "Exceeded maximum number of allowed redirects during login to repository: " + client.getBaseUrl()); //$NON-NLS-1$

    throw new JiraServiceUnavailableException("Exceeded maximum number of allowed redirects during login"); //$NON-NLS-1$
}

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

@Override
public String getUsername(Long userId) {
    // Create a method instance.
    String resource = String.format(baseUrl + USER_USERNAME, userId);
    GetMethod method = createGetMethod(resource);

    try {//from   w w  w . ja  v a  2s.  c o m
        // Execute the method.
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        assertResponseCodeOK(method, statusCode);
        return new String(method.getResponseBody());

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

From source file:com.zimbra.cs.store.triton.TritonBlobStoreManager.java

/**
 * Run SIS operation against remote server. If a blob already exists for the locator the remote ref count is incremented.
 * @param hash: The content hash of the blob
 * @return true if blob already exists, false if not
 * @throws IOException//  w w  w.  j  av  a  2s . c om
 * @throws ServiceException
 */
private boolean sisCreate(byte[] hash) throws IOException {
    String locator = getLocator(hash);
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    PostMethod post = new PostMethod(blobApiUrl + locator);
    ZimbraLog.store.info("SIS create URL: %s", post.getURI());
    try {
        post.addRequestHeader(TritonHeaders.HASH_TYPE, hashType.toString());
        int statusCode = HttpClientUtil.executeMethod(client, post);
        if (statusCode == HttpStatus.SC_CREATED) {
            return true; //exists, ref count incremented
        } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
            if (emptyLocator.equals(locator)) {
                //empty file
                return true;
            } else {
                return false; //does not exist
            }
        } else if (statusCode == HttpStatus.SC_BAD_REQUEST) {
            //does not exist, probably wrong hash algorithm
            ZimbraLog.store.warn("failed with code %d response: %s", statusCode,
                    post.getResponseBodyAsString());
            return false;
        } else {
            //unexpected condition
            ZimbraLog.store.error("failed with code %d response: %s", statusCode,
                    post.getResponseBodyAsString());
            throw new IOException("unable to SIS create " + statusCode + ":" + post.getStatusText(), null);
        }
    } finally {
        post.releaseConnection();
    }
}

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

@Override
public CreateAccountResult createAccount(CreateAccountRequest request) {
    log.info("Create account request:" + request);
    PostMethod method = null;// ww w. j  a v  a2  s. c  o  m
    try {
        method = new PostMethod(baseUrl + ACCOUNTS);
        String data = serialize(request);
        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, CreateAccountResult.class);

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

    } catch (Exception e) {
        log.error("Failed to create account", e);
        throw new RuntimeException(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:com.github.maven.plugin.client.impl.GithubClientImpl.java

/**
 * Retrieves the download informations associated to the given repository
 * url./* w  ww .  ja  v a 2s  .  c  o m*/
 *
 * @param repositoryUrl The repository url.
 *
 * @return A map containing the downloads informations.
 */
private Map<String, Integer> retrieveDownloadsInfos(String repositoryUrl) {
    final Map<String, Integer> downloads = new HashMap<String, Integer>();

    GetMethod githubGet = new GetMethod(toRepositoryDownloadUrl(repositoryUrl));
    githubGet.setQueryString(
            new NameValuePair[] { new NameValuePair("login", login), new NameValuePair("token", token) });

    int response;

    try {

        response = httpClient.executeMethod(githubGet);
    } catch (IOException e) {
        throw new GithubRepositoryNotFoundException(
                "Cannot retrieve github repository " + repositoryUrl + " informations", e);
    }

    if (response == HttpStatus.SC_OK) {

        String githubResponse;

        try {

            githubResponse = githubGet.getResponseBodyAsString();
        } catch (IOException e) {
            throw new GithubRepositoryNotFoundException(
                    "Cannot retrieve github repository " + repositoryUrl + "  informations", e);
        }

        Pattern pattern = Pattern.compile(
                String.format("<a href=\"(/downloads)?%s/?([^\"]+)\"", removeGithubUrlPart(repositoryUrl)));

        Matcher matcher = pattern.matcher(githubResponse);
        while (matcher.find()) {
            String tmp = matcher.group(2);

            if (tmp.contains("downloads")) {
                String id = matcher.group(2).substring(tmp.lastIndexOf('/') + 1, tmp.length());
                Integer downloadId = Integer.parseInt(id);
                if (matcher.find()) {
                    downloads.put(matcher.group(2), downloadId);
                }
            }
        }

    } else if (response == HttpStatus.SC_NOT_FOUND) {
        throw new GithubRepositoryNotFoundException("Cannot found repository " + repositoryUrl);
    } else {
        throw new GithubRepositoryNotFoundException(
                "Cannot retrieve github repository " + repositoryUrl + " informations");
    }

    githubGet.releaseConnection();

    return downloads;
}