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:org.apache.falcon.regression.lineage.LineageApiTest.java

@Test
public void testEdgeBlankId() throws Exception {
    final HttpResponse httpResponse = lineageHelper
            .runGetRequest(lineageHelper.getUrl(LineageHelper.URL.EDGES, lineageHelper.getUrlPath("")));
    LOGGER.info(httpResponse.toString());
    LOGGER.info(lineageHelper.getResponseString(httpResponse));
    Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_NOT_FOUND,
            "Expecting not-found error.");
}

From source file:org.apache.falcon.regression.lineage.LineageApiTest.java

@Test
public void testEdgeInvalidId() throws Exception {
    final HttpResponse response = lineageHelper.runGetRequest(
            lineageHelper.getUrl(LineageHelper.URL.EDGES, lineageHelper.getUrlPath("invalid-id")));
    LOGGER.info(response.toString());//from  w w w  . ja  v a2 s .  c  om
    LOGGER.info(lineageHelper.getResponseString(response));
    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_NOT_FOUND,
            "Expecting not-found error.");
}

From source file:org.apache.manifoldcf.examples.ManifoldCFAPIConnect.java

/** Perform an API GET operation.
*@param restPath is the URL path of the REST object, starting with "/".
*@return the json response.//from  www.  j ava 2s  .c  om
*/
public String performAPIRawGetOperation(String restPath) throws IOException {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(formURL(restPath));
    int response = client.executeMethod(method);
    byte[] responseData = method.getResponseBody();
    // We presume that the data is utf-8, since that's what the API
    // uses throughout.
    String responseString = new String(responseData, "utf-8");
    if (response != HttpStatus.SC_OK && response != HttpStatus.SC_NOT_FOUND)
        throw new IOException(
                "API http GET error; expected " + HttpStatus.SC_OK + " or " + HttpStatus.SC_NOT_FOUND + ", "
                        + " saw " + Integer.toString(response) + ": " + responseString);
    return responseString;
}

From source file:org.apache.maven.wagon.providers.http.HttpWagon.java

public List getFileList(String destinationDirectory)
        throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    if (destinationDirectory.length() > 0 && !destinationDirectory.endsWith("/")) {
        destinationDirectory += "/";
    }//from  ww w  .  j  a  v  a 2 s.  c  o  m

    String url = getRepository().getUrl() + "/" + destinationDirectory;

    GetMethod getMethod = new GetMethod(url);

    try {
        int statusCode = execute(getMethod);

        fireTransferDebug(url + " - Status code: " + statusCode);

        // TODO [BP]: according to httpclient docs, really should swallow the output on error. verify if that is required
        switch (statusCode) {
        case HttpStatus.SC_OK:
            break;

        case SC_NULL:
            throw new TransferFailedException("Failed to transfer file: ");

        case HttpStatus.SC_FORBIDDEN:
            throw new AuthorizationException("Access denied to: " + url);

        case HttpStatus.SC_UNAUTHORIZED:
            throw new AuthorizationException("Not authorized.");

        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            throw new AuthorizationException("Not authorized by proxy.");

        case HttpStatus.SC_NOT_FOUND:
            throw new ResourceDoesNotExistException("File: " + url + " does not exist");

            //add more entries here
        default:
            throw new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode);
        }

        InputStream is = null;

        is = getMethod.getResponseBodyAsStream();

        return HtmlFileListParser.parseFileList(url, is);
    } catch (IOException e) {
        throw new TransferFailedException("Could not read response body.", e);
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:org.apache.maven.wagon.providers.webdav.AbstractHttpClientWagon.java

private void put(Resource resource, File source, RequestEntityImplementation requestEntityImplementation,
        String url) throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException {

    // preemptive true for put
    client.getParams().setAuthenticationPreemptive(true);

    //Parent directories need to be created before posting
    try {/* w  w w.j  a  va  2  s .c o m*/
        mkdirs(PathUtils.dirname(resource.getName()));
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);
    }

    PutMethod putMethod = new PutMethod(url);

    firePutStarted(resource, source);

    try {
        putMethod.setRequestEntity(requestEntityImplementation);

        int statusCode;
        try {
            statusCode = execute(putMethod);

        } catch (IOException e) {
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);

            throw new TransferFailedException(e.getMessage(), e);
        }

        fireTransferDebug(url + " - Status code: " + statusCode);

        // Check that we didn't run out of retries.
        switch (statusCode) {
        // Success Codes
        case HttpStatus.SC_OK: // 200
        case HttpStatus.SC_CREATED: // 201
        case HttpStatus.SC_ACCEPTED: // 202
        case HttpStatus.SC_NO_CONTENT: // 204
            break;

        // handle all redirect even if http specs says " the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user"
        case HttpStatus.SC_MOVED_PERMANENTLY: // 301
        case HttpStatus.SC_MOVED_TEMPORARILY: // 302
        case HttpStatus.SC_SEE_OTHER: // 303
            String relocatedUrl = calculateRelocatedUrl(putMethod);
            fireTransferDebug("relocate to " + relocatedUrl);
            put(resource, source, requestEntityImplementation, relocatedUrl);
            return;

        case SC_NULL: {
            TransferFailedException e = new TransferFailedException("Failed to transfer file: " + url);
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);
            throw e;
        }

        case HttpStatus.SC_FORBIDDEN:
            fireSessionConnectionRefused();
            throw new AuthorizationException("Access denied to: " + url);

        case HttpStatus.SC_NOT_FOUND:
            throw new ResourceDoesNotExistException("File: " + url + " does not exist");

            //add more entries here
        default: {
            TransferFailedException e = new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode);
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);
            throw e;
        }
        }

        firePutCompleted(resource, source);
    } finally {
        putMethod.releaseConnection();
    }
}

From source file:org.apache.maven.wagon.providers.webdav.AbstractHttpClientWagon.java

public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException {
    StringBuilder url = new StringBuilder(getRepository().getUrl());
    if (!url.toString().endsWith("/")) {
        url.append('/');
    }/*from  ww  w.ja  v  a  2s. c  o  m*/
    url.append(resourceName);
    HeadMethod headMethod = new HeadMethod(url.toString());

    int statusCode;
    try {
        statusCode = execute(headMethod);
    } catch (IOException e) {
        throw new TransferFailedException(e.getMessage(), e);
    }
    try {
        switch (statusCode) {
        case HttpStatus.SC_OK:
            return true;

        case HttpStatus.SC_NOT_MODIFIED:
            return true;

        case SC_NULL:
            throw new TransferFailedException("Failed to transfer file: " + url);

        case HttpStatus.SC_FORBIDDEN:
            throw new AuthorizationException("Access denied to: " + url);

        case HttpStatus.SC_UNAUTHORIZED:
            throw new AuthorizationException("Not authorized.");

        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            throw new AuthorizationException("Not authorized by proxy.");

        case HttpStatus.SC_NOT_FOUND:
            return false;

        //add more entries here
        default:
            throw new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode);
        }
    } finally {
        headMethod.releaseConnection();
    }
}

From source file:org.apache.maven.wagon.providers.webdav.AbstractHttpClientWagon.java

public void fillInputData(InputData inputData)
        throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    Resource resource = inputData.getResource();

    StringBuilder url = new StringBuilder(getRepository().getUrl());
    if (!url.toString().endsWith("/")) {
        url.append('/');
    }//from  w  w w .j  a v a2s .  c o m
    url.append(resource.getName());

    getMethod = new GetMethod(url.toString());

    long timestamp = resource.getLastModified();
    if (timestamp > 0) {
        SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd-MMM-yy HH:mm:ss zzz", Locale.US);
        fmt.setTimeZone(GMT_TIME_ZONE);
        Header hdr = new Header("If-Modified-Since", fmt.format(new Date(timestamp)));
        fireTransferDebug("sending ==> " + hdr + "(" + timestamp + ")");
        getMethod.addRequestHeader(hdr);
    }

    int statusCode;
    try {
        statusCode = execute(getMethod);
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        throw new TransferFailedException(e.getMessage(), e);
    }

    fireTransferDebug(url + " - Status code: " + statusCode);

    // TODO [BP]: according to httpclient docs, really should swallow the output on error. verify if that is
    // required
    switch (statusCode) {
    case HttpStatus.SC_OK:
        break;

    case HttpStatus.SC_NOT_MODIFIED:
        // return, leaving last modified set to original value so getIfNewer should return unmodified
        return;

    case SC_NULL: {
        TransferFailedException e = new TransferFailedException("Failed to transfer file: " + url);
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);
        throw e;
    }

    case HttpStatus.SC_FORBIDDEN:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Access denied to: " + url);

    case HttpStatus.SC_UNAUTHORIZED:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Not authorized.");

    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Not authorized by proxy.");

    case HttpStatus.SC_NOT_FOUND:
        throw new ResourceDoesNotExistException("File: " + url + " does not exist");

        // add more entries here
    default: {
        cleanupGetTransfer(resource);
        TransferFailedException e = new TransferFailedException(
                "Failed to transfer file: " + url + ". Return code is: " + statusCode);
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);
        throw e;
    }
    }

    InputStream is = null;

    Header contentLengthHeader = getMethod.getResponseHeader("Content-Length");

    if (contentLengthHeader != null) {
        try {
            long contentLength = Integer.valueOf(contentLengthHeader.getValue()).intValue();

            resource.setContentLength(contentLength);
        } catch (NumberFormatException e) {
            fireTransferDebug(
                    "error parsing content length header '" + contentLengthHeader.getValue() + "' " + e);
        }
    }

    Header lastModifiedHeader = getMethod.getResponseHeader("Last-Modified");

    long lastModified = 0;

    if (lastModifiedHeader != null) {
        try {
            lastModified = DateUtil.parseDate(lastModifiedHeader.getValue()).getTime();

            resource.setLastModified(lastModified);
        } catch (DateParseException e) {
            fireTransferDebug("Unable to parse last modified header");
        }

        fireTransferDebug("last-modified = " + lastModifiedHeader.getValue() + " (" + lastModified + ")");
    }

    Header contentEncoding = getMethod.getResponseHeader("Content-Encoding");
    boolean isGZipped = contentEncoding != null && "gzip".equalsIgnoreCase(contentEncoding.getValue());

    try {
        is = getMethod.getResponseBodyAsStream();
        if (isGZipped) {
            is = new GZIPInputStream(is);
        }
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        String msg = "Error occurred while retrieving from remote repository:" + getRepository() + ": "
                + e.getMessage();

        throw new TransferFailedException(msg, e);
    }

    inputData.setInputStream(is);
}

From source file:org.apache.maven.wagon.providers.webdav.WebDavWagon.java

public List<String> getFileList(String destinationDirectory)
        throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    String repositoryUrl = repository.getUrl();
    String url = repositoryUrl + (repositoryUrl.endsWith("/") ? "" : "/") + destinationDirectory;

    PropFindMethod method = null;// w  ww  .j  a v a  2s .  c  o  m
    try {
        if (isDirectory(url)) {
            DavPropertyNameSet nameSet = new DavPropertyNameSet();
            nameSet.add(DavPropertyName.create(DavConstants.PROPERTY_DISPLAYNAME));

            method = new PropFindMethod(url, nameSet, DavConstants.DEPTH_1);
            int status = execute(method);
            if (method.succeeded()) {
                ArrayList<String> dirs = new ArrayList<String>();
                MultiStatus multiStatus = method.getResponseBodyAsMultiStatus();

                for (int i = 0; i < multiStatus.getResponses().length; i++) {

                    MultiStatusResponse response = multiStatus.getResponses()[i];

                    String entryUrl = response.getHref();
                    String fileName = PathUtils.filename(URLDecoder.decode(entryUrl));
                    if (entryUrl.endsWith("/")) {
                        if (i == 0) {
                            //by design jackrabbit webdav sticks parent directory as the first entry
                            // so we need to ignore this entry
                            // http://www.nabble.com/Extra-entry-in-get-file-list-with-jackrabbit-webdav-td21262786.html
                            // http://www.webdav.org/specs/rfc4918.html#rfc.section.9.1
                            continue;
                        }

                        //extract "dir/" part of "path.to.dir/"
                        fileName = PathUtils.filename(PathUtils.dirname(URLDecoder.decode(entryUrl))) + "/";
                    }

                    if (!StringUtils.isEmpty(fileName)) {
                        dirs.add(fileName);
                    }
                }
                return dirs;
            }

            if (status == HttpStatus.SC_NOT_FOUND) {
                throw new ResourceDoesNotExistException("Destination directory does not exist: " + url);
            }
        }
    } catch (DavException e) {
        throw new TransferFailedException(e.getMessage(), e);
    } catch (IOException e) {
        throw new TransferFailedException(e.getMessage(), e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    throw new ResourceDoesNotExistException(
            "Destination path exists but is not a " + "WebDAV collection (directory): " + url);
}

From source file:org.apache.maven.wagon.shared.http.AbstractHttpClientWagon.java

private void put(final InputStream stream, Resource resource, File source)
        throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException {
    String url = getRepository().getUrl();
    String[] parts = StringUtils.split(resource.getName(), "/");
    for (int i = 0; i < parts.length; i++) {
        // TODO: Fix encoding...
        // url += "/" + URLEncoder.encode( parts[i], System.getProperty("file.encoding") );
        url += "/" + URLEncoder.encode(parts[i]);
    }//from w  w  w  . j  a va  2 s  .c  o m

    //Parent directories need to be created before posting
    try {
        mkdirs(PathUtils.dirname(resource.getName()));
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);
    }

    PutMethod putMethod = new PutMethod(url);

    firePutStarted(resource, source);

    try {
        putMethod.setRequestEntity(new RequestEntityImplementation(stream, resource, this, source));

        int statusCode;
        try {
            statusCode = execute(putMethod);
        } catch (IOException e) {
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);

            throw new TransferFailedException(e.getMessage(), e);
        }

        fireTransferDebug(url + " - Status code: " + statusCode);

        // Check that we didn't run out of retries.
        switch (statusCode) {
        // Success Codes
        case HttpStatus.SC_OK: // 200
        case HttpStatus.SC_CREATED: // 201
        case HttpStatus.SC_ACCEPTED: // 202
        case HttpStatus.SC_NO_CONTENT: // 204
            break;

        case SC_NULL: {
            TransferFailedException e = new TransferFailedException("Failed to transfer file: " + url);
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);
            throw e;
        }

        case HttpStatus.SC_FORBIDDEN:
            fireSessionConnectionRefused();
            throw new AuthorizationException("Access denied to: " + url);

        case HttpStatus.SC_NOT_FOUND:
            throw new ResourceDoesNotExistException("File: " + url + " does not exist");

            //add more entries here
        default: {
            TransferFailedException e = new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode);
            fireTransferError(resource, e, TransferEvent.REQUEST_PUT);
            throw e;
        }
        }

        firePutCompleted(resource, source);
    } finally {
        putMethod.releaseConnection();
    }
}

From source file:org.apache.maven.wagon.shared.http.AbstractHttpClientWagon.java

public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException {
    String url = getRepository().getUrl() + "/" + resourceName;
    HeadMethod headMethod = new HeadMethod(url);
    int statusCode;
    try {/* w w w.j  a  va 2s.  c om*/
        statusCode = execute(headMethod);
    } catch (IOException e) {
        throw new TransferFailedException(e.getMessage(), e);
    }
    try {
        switch (statusCode) {
        case HttpStatus.SC_OK:
            return true;

        case HttpStatus.SC_NOT_MODIFIED:
            return true;

        case SC_NULL:
            throw new TransferFailedException("Failed to transfer file: " + url);

        case HttpStatus.SC_FORBIDDEN:
            throw new AuthorizationException("Access denied to: " + url);

        case HttpStatus.SC_UNAUTHORIZED:
            throw new AuthorizationException("Not authorized.");

        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            throw new AuthorizationException("Not authorized by proxy.");

        case HttpStatus.SC_NOT_FOUND:
            return false;

        //add more entries here
        default:
            throw new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode);
        }
    } finally {
        headMethod.releaseConnection();
    }
}