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:io.pravega.segmentstore.storage.impl.extendeds3.S3FileSystemImpl.java

@Override
public S3ObjectMetadata getObjectMetadata(String bucketName, String key) {
    S3ObjectMetadata metadata = new S3ObjectMetadata();
    AclSize data = aclMap.get(key);/*from  w  w w  . j a  v  a 2  s.  c  om*/
    if (data == null) {
        throw new S3Exception("NoSuchKey", HttpStatus.SC_NOT_FOUND, "NoSuchKey", "");
    }
    metadata.setContentLength(data.getSize());
    Path path = Paths.get(this.baseDir, bucketName, key);
    metadata.setLastModified(new Date(path.toFile().lastModified()));
    return metadata;
}

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

public void upload(String artifactName, File file, String description, String repositoryUrl) {
    assertNotNull(artifactName, "artifactName");
    assertNotNull(file, "file");
    assertNotNull(repositoryUrl, "repositoryUrl");
    assertStartsWith(repositoryUrl, GITHUB_REPOSITORY_URL_PREFIX, "repositoryUrl");

    PostMethod githubPost = new PostMethod(toRepositoryDownloadUrl(repositoryUrl));
    githubPost.setRequestBody(new NameValuePair[] { new NameValuePair("login", login),
            new NameValuePair("token", token), new NameValuePair("file_name", artifactName),
            new NameValuePair("file_size", String.valueOf(file.length())),
            new NameValuePair("description", description == null ? "" : description) });

    try {/*from  w  ww  .ja  va2s.c o m*/

        int response = httpClient.executeMethod(githubPost);

        if (response == HttpStatus.SC_OK) {

            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = mapper.readValue(githubPost.getResponseBodyAsString(), JsonNode.class);

            PostMethod s3Post = new PostMethod(GITHUB_S3_URL);

            Part[] parts = { new StringPart("Filename", artifactName),
                    new StringPart("policy", node.path("policy").getTextValue()),
                    new StringPart("success_action_status", "201"),
                    new StringPart("key", node.path("path").getTextValue()),
                    new StringPart("AWSAccessKeyId", node.path("accesskeyid").getTextValue()),
                    new StringPart("Content-Type", node.path("mime_type").getTextValue()),
                    new StringPart("signature", node.path("signature").getTextValue()),
                    new StringPart("acl", node.path("acl").getTextValue()), new FilePart("file", file) };

            MultipartRequestEntity partEntity = new MultipartRequestEntity(parts, s3Post.getParams());
            s3Post.setRequestEntity(partEntity);

            int s3Response = httpClient.executeMethod(s3Post);
            if (s3Response != HttpStatus.SC_CREATED) {
                throw new GithubException(
                        "Cannot upload " + file.getName() + " to repository " + repositoryUrl);
            }

            s3Post.releaseConnection();
        } else if (response == HttpStatus.SC_NOT_FOUND) {
            throw new GithubRepositoryNotFoundException("Cannot found repository " + repositoryUrl);
        } else if (response == HttpStatus.SC_UNPROCESSABLE_ENTITY) {
            throw new GithubArtifactAlreadyExistException(
                    "File " + artifactName + " already exist in " + repositoryUrl + " repository");
        } else {
            throw new GithubException("Error " + HttpStatus.getStatusText(response));
        }
    } catch (IOException e) {
        throw new GithubException(e);
    }

    githubPost.releaseConnection();
}

From source file:com.cubeia.backoffice.operator.client.OperatorServiceClientHTTP.java

@Override
public void updateOperator(OperatorDTO operator) {
    PutMethod method = new PutMethod(baseUrl + UPDATE_OPERATOR);
    prepareMethod(method);//from  w  w w. j a v a  2 s . c om
    try {

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

        // Execute the method.
        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.moss.bdbadmin.openejb.BdbAdminOpenEjbAdapter.java

public void onMessage(final HttpRequest request, final HttpResponse response) throws Exception {

    final IdProof assertion;
    {//from   w  w  w. j av  a2  s  .  c o  m
        IdProof a = null;

        String value = request.getHeader(AuthenticationHeader.HEADER_NAME);
        if (value != null && value.length() > 0) {
            try {
                a = AuthenticationHeader.decode(value);
            } catch (Exception ex) {
                ex.printStackTrace();
                a = null;
            }
        } else {
            System.out.println("No assertion included in request header");
            a = null;
        }

        assertion = a;
    }

    final ServiceResource resource;
    {
        String path;
        if (request.getURI().getPath().length() >= contextPath.length()) {
            path = request.getURI().getPath().substring(contextPath.length()).trim();
        } else {
            path = request.getURI().getPath();
        }

        ServiceResource r = null;
        ;
        try {
            r = service.resolve(path);
        } catch (ResourcePathException ex) {
            ex.printStackTrace();
        }

        resource = r;
    }

    if (assertion == null || resource == null) {
        response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
    } else {
        abstract class Handler {
            abstract void handle() throws Exception;
        }

        Handler handler = resource.acceptVisitor(new ServiceResourceVisitor<Handler>() {
            public Handler visit(BdbMapResource map) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("OPTIONS".equals(request.getMethod().name())) {
                            byte[] data = service.map(assertion);
                            response.setHeader("Content-Length", Integer.toString(data.length));
                            response.getOutputStream().write(data);
                            response.setStatusCode(HttpStatus.SC_OK);
                        } else {
                            response.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }

            public Handler visit(BdbCategory category) {
                return null;
            }

            public Handler visit(BdbEnv env) {
                return null;
            }

            public Handler visit(final BdbDb db) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("GET".equals(request.getMethod().name())) {
                            byte[] data = service.dbInfo(assertion, db);
                            response.setHeader("Content-Length", Integer.toString(data.length));
                            response.getOutputStream().write(data);
                            response.setStatusCode(HttpStatus.SC_OK);
                        } else if ("DELETE".equals(request.getMethod().name())) {
                            service.clearDb(assertion, db);
                            response.setStatusCode(HttpStatus.SC_OK);
                        } else {
                            response.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }

            public Handler visit(final BdbEntityResource entity) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("OPTIONS".equals(request.getMethod().name())) {
                            byte[] data = service.entryInfo(assertion, entity);
                            if (data == null) {
                                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
                            } else {
                                response.setHeader("Content-Length", Integer.toString(data.length));
                                response.getOutputStream().write(data);
                                response.setStatusCode(HttpStatus.SC_OK);
                            }
                        } else if ("GET".equals(request.getMethod().name())) {
                            byte[] data = service.getEntry(assertion, entity);
                            if (data == null) {
                                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
                            } else {
                                response.setHeader("Content-Length", Integer.toString(data.length));
                                response.getOutputStream().write(data);
                                response.setStatusCode(HttpStatus.SC_OK);
                            }
                        } else if ("HEAD".equals(request.getMethod().name())) {
                            byte[] data = service.getEntry(assertion, entity);
                            if (data == null) {
                                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
                            } else {
                                response.setStatusCode(HttpStatus.SC_OK);
                            }
                        } else if ("PUT".equals(request.getMethod().name())) {

                            byte[] input;
                            {
                                InputStream in = request.getInputStream();
                                ByteArrayOutputStream out = new ByteArrayOutputStream();

                                byte[] buffer = new byte[1023 * 10]; //10k buffer
                                for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) {
                                    out.write(buffer, 0, numRead);
                                }

                                in.close();
                                out.close();

                                input = out.toByteArray();
                            }

                            service.putEntry(assertion, entity, input);
                            response.setStatusCode(HttpStatus.SC_OK);
                        } else if ("DELETE".equals(request.getMethod().name())) {
                            if (service.deleteEntry(assertion, entity)) {
                                response.setStatusCode(HttpStatus.SC_OK);
                            } else {
                                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
                            }
                        } else {
                            response.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }
        });

        if (handler == null) {
            System.out.println("Cannot perform any methods on requested path");
            response.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
        } else {
            try {
                handler.handle();
            } catch (IdProovingException ex) {
                ex.printStackTrace();
                response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
            } catch (NotAuthorizedException ex) {
                ex.printStackTrace();
                response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
            } catch (Exception ex) {
                throw new ServletException(ex);
            }
        }
    }

    response.getOutputStream().close();
}

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

@Override
public Account getAccountById(Long accountId) {
    String resource = String.format(baseUrl + ACCOUNT, accountId);
    GetMethod method = createGetMethod(resource);

    try {//from   ww  w.j ava  2s  . 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, Account.class);

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

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

@Override
public InputStream readStreamFromStore(String locator, Mailbox mbox) throws IOException {
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    GetMethod get = new GetMethod(blobApiUrl + locator);
    get.addRequestHeader(TritonHeaders.HASH_TYPE, hashType.toString());
    ZimbraLog.store.info("getting %s", get.getURI());
    int statusCode = HttpClientUtil.executeMethod(client, get);
    if (statusCode == HttpStatus.SC_OK) {
        return new UserServlet.HttpInputStream(get);
    } else {// w  w  w  . jav  a  2s  .c  om
        get.releaseConnection();
        if (statusCode == HttpStatus.SC_NOT_FOUND && emptyLocator.equals(locator)) {
            //empty file edge case. could compare hash before this, but that hurts perf. for normal case
            ZimbraLog.store.info("returning input stream for empty blob");
            return new ByteArrayInputStream(new byte[0]);
        } else {
            throw new IOException("unexpected return code during blob GET: " + get.getStatusText());
        }
    }
}

From source file:com.zimbra.cs.index.elasticsearch.ElasticSearchIndex.java

/**
 * By default, ElasticSearch refreshes every second (configurable?).  Can force it using this.
 * TODO: Perhaps only do this if we've written something in the last second?
 *//*from   w  w w.  j  a va  2s  .  co m*/
private boolean refreshIndexIfNecessary() {
    String url = String.format("%s_refresh", indexUrl);
    GetMethod method = new GetMethod(ElasticSearchConnector.actualUrl(url));
    try {
        ElasticSearchConnector connector = new ElasticSearchConnector();
        int statusCode = connector.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            return true;
        } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
            ZimbraLog.index.debug("Index not present on %s %d", url, statusCode);
            return false;
        }
        ZimbraLog.index.error("Problem refreshing index %s %d", url, statusCode);
    } catch (HttpException e) {
        ZimbraLog.index.error("Problem refreshing index %s", url, e);
    } catch (IOException e) {
        ZimbraLog.index.error("Problem refreshing index %s", url, e);
    }
    return false;
}

From source file:net.sourceforge.jwbf.actions.HttpActionClient.java

/**
 * Process a GET Message./*from   w  w  w.  j a  va 2  s . c  om*/
 * 
 * @param authgets
 *            a
 * @param cp
 *            a
 * @return a returning message, not null
 * @throws IOException on problems
 * @throws CookieException on problems
 * @throws ProcessException on problems
 */
public byte[] get(HttpMethod authgets) throws IOException, CookieException, ProcessException {
    showCookies(client);
    byte[] out = null;
    authgets.getParams().setParameter("http.protocol.content-charset", MediaWikiBot.CHARSET);
    //      System.err.println(authgets.getParams().getParameter("http.protocol.content-charset"));

    client.executeMethod(authgets);
    LOG.debug(authgets.getURI());
    LOG.debug("GET: " + authgets.getStatusLine().toString());

    out = authgets.getResponseBody();

    // release any connection resources used by the method
    authgets.releaseConnection();
    int statuscode = authgets.getStatusCode();

    if (statuscode == HttpStatus.SC_NOT_FOUND) {
        LOG.warn("Not Found: " + authgets.getQueryString());

        throw new FileNotFoundException(authgets.getQueryString());
    }

    return out;
}

From source file:com.hp.alm.ali.idea.cfg.AliConfigurable.java

public static ServerType getServerType(RestClient restClient, boolean loginLogout) throws AuthenticationFailed {
    try {/*w ww  . j  a va  2 s.com*/
        if (loginLogout) {
            restClient.login();
        }
        // check for at least ALM 11
        RestService.getForString(restClient, "defects?query={0}", EntityQuery.encode("{id[0]}"));

        try {
            InputStream is = restClient.getForStream("customization/extensions");
            return checkServerType(ProjectExtensionsList.create(is));
        } catch (HttpClientErrorException e) {
            if (e.getHttpStatus() == HttpStatus.SC_NOT_FOUND) {
                return checkServerTypeOldStyle(restClient);
            }
            throw e;
        }
    } catch (HttpClientErrorException e) {
        if (e.getHttpStatus() == HttpStatus.SC_UNAUTHORIZED) {
            throw new AuthenticationFailed();
        } else {
            throw new RuntimeException("Failed to connect to HP ALM: "
                    + handleGenericException(restClient, restClient.getDomain(), restClient.getProject()));
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to connect to HP ALM: "
                + handleGenericException(restClient, restClient.getDomain(), restClient.getProject()));
    } finally {
        if (loginLogout) {
            RestService.logout(restClient);
        }
    }
}

From source file:io.pravega.segmentstore.storage.impl.extendeds3.S3FileSystemImpl.java

@Override
public InputStream readObjectStream(String bucketName, String key, Range range) {
    byte[] bytes = new byte[Math.toIntExact(range.getLast() + 1 - range.getFirst())];
    Path path = Paths.get(this.baseDir, bucketName, key);
    FileInputStream returnStream;
    try {//from   ww  w . jav  a 2 s .co  m
        returnStream = new FileInputStream(path.toFile());
        if (range.getFirst() != 0) {
            long bytesSkipped = 0;
            do {
                bytesSkipped += returnStream.skip(range.getFirst());
            } while (bytesSkipped < range.getFirst());
        }
        StreamHelpers.readAll(returnStream, bytes, 0, bytes.length);
        return new ByteArrayInputStream(bytes);
    } catch (IOException e) {
        throw new S3Exception("NoSuchKey", HttpStatus.SC_NOT_FOUND, "NoSuchKey", "");
    }
}