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.maven.wagon.shared.http.AbstractHttpClientWagon.java

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

    String url = getRepository().getUrl() + "/" + resource.getName();
    getMethod = new GetMethod(url);
    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);//from  ww  w  .  j a v  a2  s .co  m
        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 ? false : "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.roller.weblogger.util.Trackback.java

/**
 * Sends trackback from entry to remote URL.
 * See Trackback spec for details: http://www.sixapart.com/pronet/docs/trackback_spec
 *///www.  ja  v  a  2s  .co  m
public RollerMessages send() throws WebloggerException {

    RollerMessages messages = new RollerMessages();

    log.debug("Sending trackback to url - " + trackbackURL);

    // Construct data
    String title = entry.getTitle();
    String excerpt = StringUtils.left(Utilities.removeHTML(entry.getDisplayContent()), 255);
    String url = entry.getPermalink();
    String blog_name = entry.getWebsite().getName();

    // build trackback post parameters as query string
    Map params = new HashMap();
    params.put("title", URLUtilities.encode(title));
    params.put("excerpt", URLUtilities.encode(excerpt));
    params.put("url", URLUtilities.encode(url));
    params.put("blog_name", URLUtilities.encode(blog_name));
    String queryString = URLUtilities.getQueryString(params);

    log.debug("query string - " + queryString);

    // prepare http request
    HttpClient client = new HttpClient();
    client.setConnectionTimeout(45 * 1000);
    HttpMethod method = new PostMethod(trackbackURL);
    method.setQueryString(queryString);

    try {
        // execute trackback
        int statusCode = client.executeMethod(method);

        // read response
        byte[] response = method.getResponseBody();
        String responseString = Utilities.escapeHTML(new String(response, "UTF-8"));

        log.debug("result = " + statusCode + " " + method.getStatusText());
        log.debug("response:\n" + responseString);

        if (statusCode == HttpStatus.SC_OK) {
            // trackback request succeeded, message will give details
            try {
                messages = parseTrackbackResponse(new String(response, "UTF-8"), messages);
            } catch (Exception e) {
                // Cannot parse response, indicates failure
                messages.addError("weblogEdit.trackbackErrorParsing", responseString);
            }
        } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
            // 404, invalid trackback url
            messages.addError("weblogEdit.trackbackError404");
        } else {
            // some other kind of error with url, like 500, 403, etc
            // just provide a generic error message and give the http response text
            messages.addError("weblogEdit.trackbackErrorResponse",
                    new String[] { "" + statusCode, method.getStatusText() });
        }

    } catch (IOException e) {
        // some kind of transport error sending trackback post
        log.debug("Error sending trackback", e);
        messages.addError("weblogEdit.trackbackErrorTransport");
    } finally {
        // release used connection
        method.releaseConnection();
    }

    return messages;
}

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java

private void createIntermediaryPaths(String targetURL)
        throws HttpException, IOException, MojoExecutionException {
    // extract all intermediate URIs (longest one first)
    List<String> intermediateUris = IntermediateUrisExtractor.extractIntermediateUris(targetURL);

    // 1. go up to the node in the repository which exists already (HEAD request towards the root node)
    String existingIntermediateUri = null;
    // go through all intermediate URIs (longest first)
    for (String intermediateUri : intermediateUris) {
        // until one is existing
        int result = performHead(intermediateUri);
        if (result == HttpStatus.SC_OK) {
            existingIntermediateUri = intermediateUri;
            break;
        } else if (result != HttpStatus.SC_NOT_FOUND) {
            throw new MojoExecutionException("Failed getting intermediate path at " + intermediateUri + "."
                    + " Reason: " + HttpStatus.getStatusText(result));
        }//from  www. jav a  2s .co  m
    }

    if (existingIntermediateUri == null) {
        throw new MojoExecutionException(
                "Could not find any intermediate path up until the root of " + targetURL + ".");
    }

    // 2. now create from that level on each intermediate node individually towards the target path
    int startOfInexistingIntermediateUri = intermediateUris.indexOf(existingIntermediateUri);
    if (startOfInexistingIntermediateUri == -1) {
        throw new IllegalStateException(
                "Could not find intermediate uri " + existingIntermediateUri + " in the list");
    }

    for (int index = startOfInexistingIntermediateUri - 1; index >= 0; index--) {
        // use MKCOL to create the intermediate paths
        String intermediateUri = intermediateUris.get(index);
        int result = performMkCol(intermediateUri);
        if (result == HttpStatus.SC_CREATED || result == HttpStatus.SC_OK) {
            getLog().debug("Intermediate path at " + intermediateUri + " successfully created");
            continue;
        } else {
            throw new MojoExecutionException("Failed creating intermediate path at '" + intermediateUri + "'."
                    + " Reason: " + HttpStatus.getStatusText(result));
        }
    }
}

From source file:org.apache.webdav.ant.taskdefs.Put.java

/**
 * Puts a file to a given URL.//from  w ww.jav  a2s .c  o m
 * @param relative for logging purposes only. 
 */
private void uploadFile(HttpURL url, File file, String relative) throws IOException {

    boolean putit = false;
    try {
        if (this.overwrite) {
            putit = true;
        } else {
            // check last modified date (both GMT)
            long remoteLastMod = Utils.getLastModified(getHttpClient(), url);
            long localLastMod = file.lastModified();
            putit = localLastMod > remoteLastMod;
        }
    } catch (HttpException e) {
        switch (e.getReasonCode()) {
        case HttpStatus.SC_NOT_FOUND:
            putit = true;
            break;
        default:
            throw Utils.makeBuildException("Can't get lastmodified!?", e);
        }
    }

    if (putit) {
        log("Uploading: " + relative, ifVerbose());
        try {
            String contentType = Mimetypes.getMimeType(file, DEFAULT_CONTENT_TYPE);
            if (this.filterSets.hasFilters()) {
                // TODO this part doesn't look nice
                InputStreamReader reader = new InputStreamReader(new FileInputStream(file), this.encoding);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                LineTokenizer tok = new LineTokenizer();
                tok.setIncludeDelims(true);

                for (String l = tok.getToken(reader); l != null; l = tok.getToken(reader)) {
                    out.write(this.filterSets.replaceTokens(l).getBytes(this.encoding));
                }
                Utils.putFile(getHttpClient(), url, new ByteArrayInputStream(out.toByteArray()), contentType,
                        this.locktoken);
            } else {
                Utils.putFile(getHttpClient(), url, new FileInputStream(file), contentType, this.locktoken);
            }
            this.countWrittenFiles++;
        } catch (HttpException e) {
            throw Utils.makeBuildException("Can't upload " + url, e);
        }
    } else {
        countOmittedFiles++;
        log("Omitted: " + relative + " (uptodate)", ifVerbose());
    }
}

From source file:org.apache.webdav.ant.taskdefs.Put.java

private void uploadZipEntry(HttpURL url, String name, ZipFile zipFile) throws IOException {
    boolean putit = false;
    ZipEntry entry = zipFile.getEntry(name);

    try {//from   ww w.j  a v  a 2  s.c o  m
        if (this.overwrite) {
            putit = true;
        } else {
            // check last modified date (both GMT)
            long remoteLastMod = Utils.getLastModified(getHttpClient(), url);
            long localLastMod = entry.getTime();
            putit = localLastMod > remoteLastMod;
        }
    } catch (HttpException e) {
        switch (e.getReasonCode()) {
        case HttpStatus.SC_NOT_FOUND:
            putit = true;
            break;
        default:
            throw Utils.makeBuildException("Can't get lastmodified!?", e);
        }
    }

    if (putit) {
        log("Uploading: " + name, ifVerbose());
        String contentType = Mimetypes.getMimeType(name, DEFAULT_CONTENT_TYPE);
        Utils.putFile(getHttpClient(), url, zipFile.getInputStream(entry), contentType, this.locktoken);
        this.countWrittenFiles++;
    } else {
        countOmittedFiles++;
        log("Omitted: " + name + " (uptodate)", ifVerbose());
    }
}

From source file:org.artifactory.repo.index.MavenIndexManager.java

private boolean isNotFoundInRemoteRepo(IOException e) {
    Throwable remoteRequestException = ExceptionUtils.getCauseOfTypes(e, RemoteRequestException.class);
    return remoteRequestException != null
            && HttpStatus.SC_NOT_FOUND == ((RemoteRequestException) e).getRemoteReturnCode();
}

From source file:org.artifactory.repo.webdav.WebdavServiceImpl.java

@Override
public void handleMkcol(ArtifactoryRequest request, ArtifactoryResponse response) throws IOException {
    RepoPath repoPath = request.getRepoPath();
    String repoKey = request.getRepoKey();
    LocalRepo repo = repoService.localOrCachedRepositoryByKey(repoKey);
    if (repo == null) {
        response.sendError(HttpStatus.SC_NOT_FOUND, "Could not find repo '" + repoKey + "'.", log);
        return;/*from  w w w.  j a  v  a2s  . c  om*/
    }

    //Return 405 if called on root or the folder already exists
    String path = repoPath.getPath();
    if (StringUtils.isBlank(path) || repo.itemExists(path)) {
        response.sendError(HttpStatus.SC_METHOD_NOT_ALLOWED,
                "MKCOL can only be executed on non-existent resource: " + repoPath, log);
        return;
    }
    //Check that we are allowed to write
    try {
        // Servlet container doesn't support long values so we take it manually from the header
        String contentLengthHeader = request.getHeader("Content-Length");
        long contentLength = StringUtils.isBlank(contentLengthHeader) ? -1
                : Long.parseLong(contentLengthHeader);
        repoService.assertValidDeployPath(repo, path, contentLength);
    } catch (RepoRejectException rre) {
        response.sendError(rre.getErrorCode(), rre.getMessage(), log);
        return;
    }

    // make sure the parent exists
    VfsFolder parentFolder = repo.getMutableFolder(repoPath.getParent());
    if (parentFolder == null) {
        response.sendError(HttpStatus.SC_CONFLICT,
                "Directory cannot be created: parent doesn't exist: " + repoPath.getParent(), log);
        return;
    }

    repo.createOrGetFolder(repoPath);
    response.setStatus(HttpStatus.SC_CREATED);
}

From source file:org.artifactory.repo.webdav.WebdavServiceImpl.java

@Override
public void handleDelete(ArtifactoryRequest request, ArtifactoryResponse response) throws IOException {
    RepoPath repoPath = request.getRepoPath();
    String repoKey = repoPath.getRepoKey();
    LocalRepo localRepository = repoService.localOrCachedRepositoryByKey(repoKey);
    if (localRepository == null) {
        response.setStatus(HttpStatus.SC_NOT_FOUND);
        return;//  w  ww  .  j  av  a  2 s.c  om
    }

    if (!NamingUtils.isProperties(repoPath.getPath())) {
        deleteItem(response, repoPath);
    } else {
        deleteProperties(response, repoPath);
    }
}

From source file:org.artifactory.repo.webdav.WebdavServiceImpl.java

private void deleteProperties(ArtifactoryResponse response, RepoPath repoPath) throws IOException {
    RepoPathImpl itemRepoPath = new RepoPathImpl(repoPath.getRepoKey(),
            NamingUtils.stripMetadataFromPath(repoPath.getPath()));
    boolean removed = repoService.removeProperties(itemRepoPath);
    if (removed) {
        response.setStatus(HttpStatus.SC_NO_CONTENT);
    } else {/*from ww w  .j a v  a  2s . c  o m*/
        response.sendError(HttpStatus.SC_NOT_FOUND, "Failed to remove properties from " + itemRepoPath, log);
    }
}

From source file:org.artifactory.request.ResponseStatusCodesMapper.java

public int getStatusCode(Throwable e) {
    if (e instanceof BadPomException) {
        return HttpStatus.SC_CONFLICT;
    } else if (e instanceof DoesNotExistException) {
        return HttpStatus.SC_NOT_FOUND;
    } else if (e instanceof ItemNotFoundRuntimeException) {
        return HttpStatus.SC_BAD_REQUEST;
    } else if (e instanceof RepoRejectException) {
        return ((RepoRejectException) e).getErrorCode();
    } else if (e instanceof IllegalArgumentException) {
        return HttpStatus.SC_BAD_REQUEST;
    }//from  www  . j a  v a 2 s  .  com

    return HttpStatus.SC_INTERNAL_SERVER_ERROR;
}